fix(后台管理):首页商户统计功能实现

This commit is contained in:
2025-07-19 00:08:43 +08:00
parent 8386f51b0e
commit 81c825d54a
20 changed files with 768 additions and 293 deletions
@@ -4,13 +4,17 @@ import com.central.common.model.Result;
import com.central.order.model.vo.DashboardStatisticsVO;
import com.central.order.service.IDashboardService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/dashboard")
@@ -22,9 +26,22 @@ public class DashboardController {
@Operation(summary = "获取首页统计数据")
@GetMapping("/statistics")
public Result<DashboardStatisticsVO> getStatistics() {
public Result<DashboardStatisticsVO> getStatistics(
@Parameter(description = "景区ID") @RequestParam(required = false) Long tourismId,
@Parameter(description = "二维码ID") @RequestParam(required = false) String qrcodeId,
@Parameter(description = "设备编号") @RequestParam(required = false) String deviceSn,
@Parameter(description = "开始时间") @RequestParam(required = false) String startTime,
@Parameter(description = "结束时间") @RequestParam(required = false) String endTime) {
try {
DashboardStatisticsVO statistics = dashboardService.getDashboardStatistics();
Map<String, Object> params = Map.of(
"tourismId", tourismId,
"qrcodeId", qrcodeId,
"deviceSn", deviceSn,
"startTime", startTime,
"endTime", endTime
);
DashboardStatisticsVO statistics = dashboardService.getDashboardStatistics(params);
return Result.succeed(statistics, "获取首页统计数据成功");
} catch (Exception e) {
log.error("获取首页统计数据失败", e);
@@ -67,14 +67,16 @@ public class OrderStatisticsController {
@Operation(summary = "按景区维度统计", description = "统计时间范围内各景区的订单数据")
@Parameters({
@Parameter(name = "startTime", description = "开始时间 (格式:yyyy-MM-dd HH:mm:ss)", required = true),
@Parameter(name = "endTime", description = "结束时间 (格式:yyyy-MM-dd HH:mm:ss)", required = true)
@Parameter(name = "endTime", description = "结束时间 (格式:yyyy-MM-dd HH:mm:ss)", required = true),
@Parameter(name = "tourismId", description = "景区ID筛选", required = false)
})
@GetMapping("/tourism")
public Result<List<Map<String, Object>>> statisticsByTourism(
@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String startTime,
@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String endTime) {
@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String endTime,
@RequestParam(required = false) String tourismId) {
try {
List<Map<String, Object>> result = orderStatisticsService.statisticsByTourism(startTime, endTime);
List<Map<String, Object>> result = orderStatisticsService.statisticsByTourism(startTime, endTime, tourismId);
return Result.succeed(result, "获取景区维度统计数据成功");
} catch (Exception e) {
log.error("获取景区维度统计数据失败", e);
@@ -85,14 +87,16 @@ public class OrderStatisticsController {
@Operation(summary = "按设备维度统计", description = "统计时间范围内各设备的订单数据")
@Parameters({
@Parameter(name = "startTime", description = "开始时间 (格式:yyyy-MM-dd HH:mm:ss)", required = true),
@Parameter(name = "endTime", description = "结束时间 (格式:yyyy-MM-dd HH:mm:ss)", required = true)
@Parameter(name = "endTime", description = "结束时间 (格式:yyyy-MM-dd HH:mm:ss)", required = true),
@Parameter(name = "deviceSn", description = "设备编号筛选", required = false)
})
@GetMapping("/device")
public Result<List<Map<String, Object>>> statisticsByDevice(
@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String startTime,
@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String endTime) {
@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String endTime,
@RequestParam(required = false) String deviceSn) {
try {
List<Map<String, Object>> result = orderStatisticsService.statisticsByDevice(startTime, endTime);
List<Map<String, Object>> result = orderStatisticsService.statisticsByDevice(startTime, endTime, deviceSn);
return Result.succeed(result, "获取设备维度统计数据成功");
} catch (Exception e) {
log.error("获取设备维度统计数据失败", e);
@@ -1,52 +1,194 @@
package com.central.order.mapper;
import com.central.order.model.vo.IncomeDataVO;
import com.central.order.model.vo.TourismRankingVO;
import com.central.order.model.vo.TrendDataVO;
import com.central.order.model.vo.*;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
import java.util.Map;
@Mapper
public interface DashboardMapper {
@Select("SELECT COUNT(*) FROM orders WHERE is_del = 0")
Long getTotalOrders();
// 基础订单统计(支持筛选)
@Select({
"<script>",
"SELECT COUNT(*) FROM orders WHERE is_del = 0",
"<if test='p.tourismId != null'>",
" AND tourism_id = #{p.tourismId}",
"</if>",
"<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
" AND code_id = #{p.qrcodeId}",
"</if>",
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND device_sn = #{p.deviceSn}",
"</if>",
"<if test='p.startTime != null and p.startTime != \"\"'>",
" AND create_time >= #{p.startTime}",
"</if>",
"<if test='p.endTime != null and p.endTime != \"\"'>",
" AND create_time &lt;= #{p.endTime}",
"</if>",
"</script>"
})
Long getTotalOrders(@Param("p") Map<String, Object> params);
@Select("SELECT COUNT(*) FROM orders WHERE is_del = 0 AND DATE(create_time) = CURDATE()")
Long getTodayOrders();
@Select({
"<script>",
"SELECT COUNT(*) FROM orders WHERE is_del = 0 AND DATE(create_time) = CURDATE()",
"<if test='p.tourismId != null'>",
" AND tourism_id = #{p.tourismId}",
"</if>",
"<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
" AND code_id = #{p.qrcodeId}",
"</if>",
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND device_sn = #{p.deviceSn}",
"</if>",
"</script>"
})
Long getTodayOrders(@Param("p") Map<String, Object> params);
@Select("SELECT COUNT(*) FROM orders WHERE is_del = 0 AND DATE(create_time) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)")
Long getYesterdayOrders();
@Select({
"<script>",
"SELECT COUNT(*) FROM orders WHERE is_del = 0 AND DATE(create_time) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)",
"<if test='p.tourismId != null'>",
" AND tourism_id = #{p.tourismId}",
"</if>",
"<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
" AND code_id = #{p.qrcodeId}",
"</if>",
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND device_sn = #{p.deviceSn}",
"</if>",
"</script>"
})
Long getYesterdayOrders(@Param("p") Map<String, Object> params);
@Select("SELECT COUNT(*) FROM orders WHERE is_del = 0 AND order_status = #{completeStatus}")
Long getCompletedOrders();
@Select({
"<script>",
"SELECT COUNT(*) FROM orders WHERE is_del = 0 AND order_status = 3",
"<if test='p.tourismId != null'>",
" AND tourism_id = #{p.tourismId}",
"</if>",
"<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
" AND code_id = #{p.qrcodeId}",
"</if>",
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND device_sn = #{p.deviceSn}",
"</if>",
"<if test='p.startTime != null and p.startTime != \"\"'>",
" AND create_time >= #{p.startTime}",
"</if>",
"<if test='p.endTime != null and p.endTime != \"\"'>",
" AND create_time &lt;= #{p.endTime}",
"</if>",
"</script>"
})
Long getCompletedOrders(@Param("p") Map<String, Object> params);
// 对账相关统计
@Select({
"<script>",
"SELECT COALESCE(SUM(order_amount), 0)",
"FROM orders",
"WHERE is_del = 0",
"AND order_status IN ${@com.central.order.constants.OrderStatusConstants@PAID_STATUS}",
"AND order_status IN (2, 3)", // 已支付、已完成
"<if test='p.tourismId != null'>",
" AND tourism_id = #{p.tourismId}",
"</if>",
"<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
" AND code_id = #{p.qrcodeId}",
"</if>",
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND device_sn = #{p.deviceSn}",
"</if>",
"<if test='p.startTime != null and p.startTime != \"\"'>",
" AND create_time >= #{p.startTime}",
"</if>",
"<if test='p.endTime != null and p.endTime != \"\"'>",
" AND create_time &lt;= #{p.endTime}",
"</if>",
"</script>"
})
Long getTotalIncome();
Long getTotalAmount(@Param("p") Map<String, Object> params);
@Select({
"<script>",
"SELECT COALESCE(SUM(order_amount), 0)",
"FROM orders",
"WHERE is_del = 0",
"AND order_status IN ${@com.central.order.constants.OrderStatusConstants@PAID_STATUS}",
"AND DATE(create_time) = CURDATE()",
"SELECT COALESCE(SUM(platform_amount), 0)",
"FROM order_statistics",
"WHERE 1=1",
"<if test='p.tourismId != null'>",
" AND tourism_id = #{p.tourismId}",
"</if>",
"<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
" AND qrcode_id = #{p.qrcodeId}",
"</if>",
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND device_sn = #{p.deviceSn}",
"</if>",
"<if test='p.startTime != null and p.startTime != \"\"'>",
" AND create_time >= #{p.startTime}",
"</if>",
"<if test='p.endTime != null and p.endTime != \"\"'>",
" AND create_time &lt;= #{p.endTime}",
"</if>",
"</script>"
})
Long getTodayIncome();
Long getPlatformAmount(@Param("p") Map<String, Object> params);
@Select({
"<script>",
"SELECT COALESCE(SUM(tourism_amount), 0)",
"FROM order_statistics",
"WHERE 1=1",
"<if test='p.tourismId != null'>",
" AND tourism_id = #{p.tourismId}",
"</if>",
"<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
" AND qrcode_id = #{p.qrcodeId}",
"</if>",
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND device_sn = #{p.deviceSn}",
"</if>",
"<if test='p.startTime != null and p.startTime != \"\"'>",
" AND create_time >= #{p.startTime}",
"</if>",
"<if test='p.endTime != null and p.endTime != \"\"'>",
" AND create_time &lt;= #{p.endTime}",
"</if>",
"</script>"
})
Long getTourismAmount(@Param("p") Map<String, Object> params);
@Select({
"<script>",
"SELECT COALESCE(SUM(refund_amount), 0)",
"FROM order_statistics",
"WHERE 1=1",
"<if test='p.tourismId != null'>",
" AND tourism_id = #{p.tourismId}",
"</if>",
"<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
" AND qrcode_id = #{p.qrcodeId}",
"</if>",
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND device_sn = #{p.deviceSn}",
"</if>",
"<if test='p.startTime != null and p.startTime != \"\"'>",
" AND create_time >= #{p.startTime}",
"</if>",
"<if test='p.endTime != null and p.endTime != \"\"'>",
" AND create_time &lt;= #{p.endTime}",
"</if>",
"</script>"
})
Long getRefundAmount(@Param("p") Map<String, Object> params);
// 图表数据
@Select({
"<script>",
"SELECT",
" DATE_FORMAT(create_time, '%Y-%m-%d') as date,",
" 'orders' as type,",
@@ -54,38 +196,130 @@ public interface DashboardMapper {
"FROM orders",
"WHERE is_del = 0",
" AND create_time >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)",
"GROUP BY DATE_FORMAT(create_time, '%Y-%m-%d')"
"<if test='p.tourismId != null'>",
" AND tourism_id = #{p.tourismId}",
"</if>",
"<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
" AND code_id = #{p.qrcodeId}",
"</if>",
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND device_sn = #{p.deviceSn}",
"</if>",
"GROUP BY DATE_FORMAT(create_time, '%Y-%m-%d')",
"ORDER BY date",
"</script>"
})
List<TrendDataVO> getOrderTrend();
List<TrendDataVO> getOrderTrend(@Param("p") Map<String, Object> params);
@Select({
"<script>",
"SELECT",
" 'platform' as type,",
" SUM(platform_amount) as value",
" CASE order_status",
" WHEN 1 THEN '待支付'",
" WHEN 2 THEN '已支付'",
" WHEN 3 THEN '已完成'",
" WHEN 4 THEN '已取消'",
" WHEN 5 THEN '已退款'",
" ELSE '其他'",
" END as type,",
" COUNT(*) as value",
"FROM orders",
"WHERE is_del = 0",
"<if test='p.tourismId != null'>",
" AND tourism_id = #{p.tourismId}",
"</if>",
"<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
" AND code_id = #{p.qrcodeId}",
"</if>",
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND device_sn = #{p.deviceSn}",
"</if>",
"<if test='p.startTime != null and p.startTime != \"\"'>",
" AND create_time >= #{p.startTime}",
"</if>",
"<if test='p.endTime != null and p.endTime != \"\"'>",
" AND create_time &lt;= #{p.endTime}",
"</if>",
"GROUP BY order_status",
"</script>"
})
List<DistributionDataVO> getOrderDistribution(@Param("p") Map<String, Object> params);
@Select({
"<script>",
"SELECT",
" '平台分账' as type,",
" COALESCE(SUM(platform_amount), 0) as value",
"FROM order_statistics",
"WHERE DATE(create_time) = CURDATE()",
"WHERE 1=1",
"<if test='p.tourismId != null'>",
" AND tourism_id = #{p.tourismId}",
"</if>",
"<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
" AND qrcode_id = #{p.qrcodeId}",
"</if>",
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND device_sn = #{p.deviceSn}",
"</if>",
"<if test='p.startTime != null and p.startTime != \"\"'>",
" AND create_time >= #{p.startTime}",
"</if>",
"<if test='p.endTime != null and p.endTime != \"\"'>",
" AND create_time &lt;= #{p.endTime}",
"</if>",
"UNION ALL",
"SELECT",
" 'tourism' as type,",
" SUM(tourism_amount) as value",
" '景区分账' as type,",
" COALESCE(SUM(tourism_amount), 0) as value",
"FROM order_statistics",
"WHERE DATE(create_time) = CURDATE()"
})
List<IncomeDataVO> getIncomeData();
@Select({
"WHERE 1=1",
"<if test='p.tourismId != null'>",
" AND tourism_id = #{p.tourismId}",
"</if>",
"<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
" AND qrcode_id = #{p.qrcodeId}",
"</if>",
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND device_sn = #{p.deviceSn}",
"</if>",
"<if test='p.startTime != null and p.startTime != \"\"'>",
" AND create_time >= #{p.startTime}",
"</if>",
"<if test='p.endTime != null and p.endTime != \"\"'>",
" AND create_time &lt;= #{p.endTime}",
"</if>",
"UNION ALL",
"SELECT",
" t.id,",
" t.tourism_name as name,",
" COUNT(o.id) as value",
"FROM tourisms t",
"LEFT JOIN orders o ON t.id = o.tourism_id",
"WHERE t.is_del = 0",
" AND o.is_del = 0",
" AND o.create_time >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)",
"GROUP BY t.id, t.tourism_name",
"ORDER BY value DESC",
"LIMIT 10"
" '退款金额' as type,",
" COALESCE(SUM(refund_amount), 0) as value",
"FROM order_statistics",
"WHERE 1=1",
"<if test='p.tourismId != null'>",
" AND tourism_id = #{p.tourismId}",
"</if>",
"<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
" AND qrcode_id = #{p.qrcodeId}",
"</if>",
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND device_sn = #{p.deviceSn}",
"</if>",
"<if test='p.startTime != null and p.startTime != \"\"'>",
" AND create_time >= #{p.startTime}",
"</if>",
"<if test='p.endTime != null and p.endTime != \"\"'>",
" AND create_time &lt;= #{p.endTime}",
"</if>",
"</script>"
})
List<TourismRankingVO> getTourismRanking();
List<IncomeDataVO> getIncomeBreakdown(@Param("p") Map<String, Object> params);
// 筛选选项
@Select("SELECT id as value, tourism_name as label FROM tourisms WHERE is_del = 0 ORDER BY tourism_name")
List<FilterOptions.OptionItem> getTourismOptions();
@Select("SELECT code_id as value, CONCAT(name, ' | ', device_sn) as label FROM qrcodes WHERE is_del = 0 ORDER BY name")
List<FilterOptions.OptionItem> getQrcodeOptions();
@Select("SELECT DISTINCT device_sn as value, device_sn as label FROM orders WHERE device_sn IS NOT NULL AND device_sn != '' ORDER BY device_sn")
List<FilterOptions.OptionItem> getDeviceOptions();
}
@@ -6,14 +6,14 @@ import lombok.Data;
import java.util.List;
@Data
@Schema(description = "图表统计数据")
@Schema(description = "图表统计")
public class ChartStatistics {
@Schema(description = "订单趋势")
private List<TrendDataVO> orderTrend;
@Schema(description = "设备分布")
private List<DistributionDataVO> deviceDistribution;
@Schema(description = "订单状态分布")
private List<DistributionDataVO> orderDistribution;
@Schema(description = "收入构成")
private List<IncomeDataVO> incomeData;
private List<IncomeDataVO> incomeBreakdown;
}
@@ -11,18 +11,9 @@ public class DashboardStatisticsVO {
@Schema(description = "订单统计")
private OrderStatistics orderStats;
@Schema(description = "收入统计")
private IncomeStatistics incomeStats;
@Schema(description = "航线统计")
private WaylineStatistics waylineStats;
@Schema(description = "设备统计")
private DeviceStatistics deviceStats;
@Schema(description = "图表统计")
private ChartStatistics chartStats;
@Schema(description = "景区排行")
private List<TourismRankingVO> tourismRanking;
@Schema(description = "筛选选项")
private FilterOptions filterOptions;
}
@@ -6,9 +6,9 @@ import lombok.Data;
import java.math.BigDecimal;
@Data
@Schema(description = "订单统计数据")
@Schema(description = "订单统计")
public class OrderStatistics {
@Schema(description = "订单总数")
@Schema(description = "总订单数")
private Long totalOrders;
@Schema(description = "今日订单数")
@@ -17,6 +17,21 @@ public class OrderStatistics {
@Schema(description = "订单增长率")
private BigDecimal orderGrowth;
@Schema(description = "订单完成率")
@Schema(description = "完成率")
private BigDecimal completionRate;
@Schema(description = "订单总金额(分)")
private Long totalAmount;
@Schema(description = "平台分账金额(分)")
private Long platformAmount;
@Schema(description = "景区分账金额(分)")
private Long tourismAmount;
@Schema(description = "退款金额(分)")
private Long refundAmount;
@Schema(description = "净收入(分)")
private Long netIncome;
}
@@ -2,9 +2,12 @@ package com.central.order.service;
import com.central.order.model.vo.DashboardStatisticsVO;
import java.util.Map;
public interface IDashboardService {
/**
* 获取首页统计数据
* @param params 筛选参数
*/
DashboardStatisticsVO getDashboardStatistics();
DashboardStatisticsVO getDashboardStatistics(Map<String, Object> params);
}
@@ -38,6 +38,7 @@ public interface IOrderStatisticsService extends ISuperService<OrderStatistics>
* 按景区维度统计
* @param startTime 开始时间
* @param endTime 结束时间
* @param tourismId 景区ID筛选(可选)
* @return 统计数据列表,包含:
* - tourismId: 景区ID
* - tourismName: 景区名称
@@ -48,17 +49,18 @@ public interface IOrderStatisticsService extends ISuperService<OrderStatistics>
* - paidAmountYuan: 已支付金额(元)
* - refundAmountYuan: 退款金额(元)
*/
List<Map<String, Object>> statisticsByTourism(String startTime, String endTime);
List<Map<String, Object>> statisticsByTourism(String startTime, String endTime, String tourismId);
/**
* 按设备维度统计
* @param startTime 开始时间
* @param endTime 结束时间
* @param deviceSn 设备编号筛选(可选)
* @return 统计数据列表,包含:
* - deviceSn: 设备编号
* - totalOrders: 订单总数
* - totalAmountYuan: 总金额(元)
* - usageRate: 设备使用率
*/
List<Map<String, Object>> statisticsByDevice(String startTime, String endTime);
List<Map<String, Object>> statisticsByDevice(String startTime, String endTime, String deviceSn);
}
@@ -10,6 +10,7 @@ import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Map;
@Slf4j
@Service
@@ -19,21 +20,18 @@ public class DashboardServiceImpl implements IDashboardService {
private final DashboardMapper dashboardMapper;
@Override
public DashboardStatisticsVO getDashboardStatistics() {
public DashboardStatisticsVO getDashboardStatistics(Map<String, Object> params) {
DashboardStatisticsVO statistics = new DashboardStatisticsVO();
try {
// 1. 获取订单统计
statistics.setOrderStats(getOrderStatistics());
// 1. 获取订单统计(包含对账数据)
statistics.setOrderStats(getOrderStatistics(params));
// 2. 获取收入统计
statistics.setIncomeStats(getIncomeStatistics());
// 2. 获取图表统计
statistics.setChartStats(getChartStatistics(params));
// 5. 获取图表统计
statistics.setChartStats(getChartStatistics());
// 6. 获取景区排行
statistics.setTourismRanking(getTourismRanking());
// 3. 获取筛选选项
statistics.setFilterOptions(getFilterOptions());
} catch (Exception e) {
log.error("获取仪表盘统计数据失败", e);
@@ -43,19 +41,19 @@ public class DashboardServiceImpl implements IDashboardService {
}
/**
* 获取订单统计
* 获取订单统计(包含对账数据)
*/
private OrderStatistics getOrderStatistics() {
private OrderStatistics getOrderStatistics(Map<String, Object> params) {
OrderStatistics stats = new OrderStatistics();
// 获取订单总数
stats.setTotalOrders(dashboardMapper.getTotalOrders());
stats.setTotalOrders(dashboardMapper.getTotalOrders(params));
// 获取今日订单数
stats.setTodayOrders(dashboardMapper.getTodayOrders());
stats.setTodayOrders(dashboardMapper.getTodayOrders(params));
// 计算订单增长率
Long yesterdayOrders = dashboardMapper.getYesterdayOrders();
Long yesterdayOrders = dashboardMapper.getYesterdayOrders(params);
if (yesterdayOrders > 0) {
BigDecimal growth = new BigDecimal(stats.getTodayOrders() - yesterdayOrders)
.divide(new BigDecimal(yesterdayOrders), 4, RoundingMode.HALF_UP)
@@ -64,7 +62,7 @@ public class DashboardServiceImpl implements IDashboardService {
}
// 计算完成率
Long completedOrders = dashboardMapper.getCompletedOrders();
Long completedOrders = dashboardMapper.getCompletedOrders(params);
if (stats.getTotalOrders() > 0) {
BigDecimal completionRate = new BigDecimal(completedOrders)
.divide(new BigDecimal(stats.getTotalOrders()), 4, RoundingMode.HALF_UP)
@@ -72,29 +70,16 @@ public class DashboardServiceImpl implements IDashboardService {
stats.setCompletionRate(completionRate);
}
return stats;
}
/**
* 获取收入统计
*/
private IncomeStatistics getIncomeStatistics() {
IncomeStatistics stats = new IncomeStatistics();
// 获取总收入
stats.setTotalAmount(dashboardMapper.getTotalIncome());
// 获取今日收入
stats.setTodayAmount(dashboardMapper.getTodayIncome());
// 计算目标完成率(假设每日目标10000元)
BigDecimal targetAmount = new BigDecimal(1000000); // 100元 * 100(分)
if (stats.getTodayAmount() > 0) {
BigDecimal completion = new BigDecimal(stats.getTodayAmount())
.divide(targetAmount, 4, RoundingMode.HALF_UP)
.multiply(new BigDecimal(100));
stats.setTargetCompletion(completion);
}
// 获取对账相关数据
stats.setTotalAmount(dashboardMapper.getTotalAmount(params));
stats.setPlatformAmount(dashboardMapper.getPlatformAmount(params));
stats.setTourismAmount(dashboardMapper.getTourismAmount(params));
stats.setRefundAmount(dashboardMapper.getRefundAmount(params));
// 计算净收入 = 景区分账金额 - 退款金额
Long netIncome = (stats.getTourismAmount() != null ? stats.getTourismAmount() : 0) -
(stats.getRefundAmount() != null ? stats.getRefundAmount() : 0);
stats.setNetIncome(netIncome);
return stats;
}
@@ -102,22 +87,36 @@ public class DashboardServiceImpl implements IDashboardService {
/**
* 获取图表统计
*/
private ChartStatistics getChartStatistics() {
private ChartStatistics getChartStatistics(Map<String, Object> params) {
ChartStatistics stats = new ChartStatistics();
// 获取订单趋势(最近7天)
stats.setOrderTrend(dashboardMapper.getOrderTrend());
stats.setOrderTrend(dashboardMapper.getOrderTrend(params));
// 获取订单状态分布
stats.setOrderDistribution(dashboardMapper.getOrderDistribution(params));
// 获取收入构成
stats.setIncomeData(dashboardMapper.getIncomeData());
stats.setIncomeBreakdown(dashboardMapper.getIncomeBreakdown(params));
return stats;
}
/**
* 获取景区排行
* 获取筛选选项
*/
private List<TourismRankingVO> getTourismRanking() {
return dashboardMapper.getTourismRanking();
private FilterOptions getFilterOptions() {
FilterOptions options = new FilterOptions();
// 获取景区列表
options.setTourismList(dashboardMapper.getTourismOptions());
// 获取二维码列表
options.setQrcodeList(dashboardMapper.getQrcodeOptions());
// 获取设备列表
options.setDeviceList(dashboardMapper.getDeviceOptions());
return options;
}
}
@@ -202,15 +202,23 @@ public class OrderStatisticsServiceImpl extends SuperServiceImpl<OrderStatistics
}
@Override
public List<Map<String, Object>> statisticsByTourism(String startTime, String endTime) {
public List<Map<String, Object>> statisticsByTourism(String startTime, String endTime, String tourismId) {
try {
OrderStatisticsQuery query = OrderStatisticsQuery.builder()
OrderStatisticsQuery.OrderStatisticsQueryBuilder queryBuilder = OrderStatisticsQuery.builder()
.startTime(startTime)
.endTime(endTime)
.groupField("o.tourism_id")
.build();
.groupField("o.tourism_id");
// 如果指定了景区ID,则添加筛选条件
if (tourismId != null && !tourismId.trim().isEmpty()) {
try {
queryBuilder.tourismId(Long.parseLong(tourismId));
} catch (NumberFormatException e) {
log.warn("景区ID格式错误: {}", tourismId);
}
}
List<Map<String, Object>> statistics = baseMapper.getOrderStatisticsByGroup(query);
List<Map<String, Object>> statistics = baseMapper.getOrderStatisticsByGroup(queryBuilder.build());
return processStatisticsResult(statistics);
} catch (Exception e) {
log.error("按景区维度统计失败", e);
@@ -219,15 +227,19 @@ public class OrderStatisticsServiceImpl extends SuperServiceImpl<OrderStatistics
}
@Override
public List<Map<String, Object>> statisticsByDevice(String startTime, String endTime) {
public List<Map<String, Object>> statisticsByDevice(String startTime, String endTime, String deviceSn) {
try {
OrderStatisticsQuery query = OrderStatisticsQuery.builder()
OrderStatisticsQuery.OrderStatisticsQueryBuilder queryBuilder = OrderStatisticsQuery.builder()
.startTime(startTime)
.endTime(endTime)
.groupField("o.device_sn")
.build();
.groupField("o.device_sn");
// 如果指定了设备编号,则添加筛选条件
if (deviceSn != null && !deviceSn.trim().isEmpty()) {
queryBuilder.deviceSn(deviceSn);
}
List<Map<String, Object>> statistics = baseMapper.getOrderStatisticsByGroup(query);
List<Map<String, Object>> statistics = baseMapper.getOrderStatisticsByGroup(queryBuilder.build());
return processStatisticsResult(statistics);
} catch (Exception e) {
log.error("按设备维度统计失败", e);
@@ -9,43 +9,43 @@
export default {
dev: {
'/api-uaa/': {
// target: 'http://119.45.169.13:9900',
target: 'http://127.0.0.1:9900',
target: 'http://119.45.169.13:9900',
// target: 'http://127.0.0.1:9900',
changeOrigin: true,
},
'/api-user/': {
// target: 'http://119.45.169.13:9900',
target: 'http://127.0.0.1:9900',
target: 'http://119.45.169.13:9900',
// target: 'http://127.0.0.1:9900',
changeOrigin: true,
},
'/api-log/': {
// target: 'http://119.45.169.13:9900',
target: 'http://127.0.0.1:9900',
target: 'http://119.45.169.13:9900',
// target: 'http://127.0.0.1:9900',
changeOrigin: true,
},
'/api-search/': {
// target: 'http://119.45.169.13:9900',
target: 'http://127.0.0.1:9900',
target: 'http://119.45.169.13:9900',
// target: 'http://127.0.0.1:9900',
changeOrigin: true,
},
'/api-generator/': {
// target: 'http://119.45.169.13:9900',
target: 'http://127.0.0.1:9900',
target: 'http://119.45.169.13:9900',
// target: 'http://127.0.0.1:9900',
changeOrigin: true,
},
'/api-file/': {
// target: 'http://119.45.169.13:9900',
target: 'http://127.0.0.1:9900',
target: 'http://119.45.169.13:9900',
// target: 'http://127.0.0.1:9900',
changeOrigin: true,
},
'/api-order/': {
// target: 'http://119.45.169.13:9900',
target: 'http://127.0.0.1:9900',
target: 'http://119.45.169.13:9900',
// target: 'http://127.0.0.1:9900',
changeOrigin: true,
},
'/api-device/': {
// target: 'http://119.45.169.13:9900',
target: 'http://127.0.0.1:9900',
target: 'http://119.45.169.13:9900',
// target: 'http://127.0.0.1:9900',
changeOrigin: true,
},
},
@@ -1,62 +1,78 @@
import { PageContainer } from '@ant-design/pro-components';
import { Card, Row, Col, Statistic, Progress, Typography } from 'antd';
import { Card, Row, Col, Statistic, Progress, Typography, Select, DatePicker, Space, Button } from 'antd';
import React, { useState, useEffect } from 'react';
import { dashboard } from '@/services/orders/api';
import { Area, Column, Pie } from '@ant-design/plots';
import {
ShoppingCartOutlined,
RocketOutlined,
MobileOutlined,
UserOutlined,
RiseOutlined,
PayCircleOutlined,
RiseOutlined,
FilterOutlined,
ReloadOutlined,
} from '@ant-design/icons';
import styles from './Welcome.less';
const { Title } = Typography;
const { RangePicker } = DatePicker;
interface Statistics {
totalOrders: number;
todayOrders: number;
orderGrowth: number;
completionRate: number;
totalAmount: number;
todayAmount: number;
targetCompletion: number;
totalWaylines: number;
activeWaylines: number;
waylineUsage: number;
totalDevices: number;
onlineDevices: number;
deviceOnlineRate: number;
orderTrend: {
date: string;
type: string;
value: number;
}[];
deviceDistribution: {
type: string;
value: number;
}[];
incomeData: {
type: string;
value: number;
}[];
tourismRanking: {
id: string;
name: string;
value: number;
}[];
orderStats: {
totalOrders: number;
todayOrders: number;
orderGrowth: number;
completionRate: number;
// 新增对账维度
totalAmount: number; // 订单总金额(分)
platformAmount: number; // 平台分账金额(分)
tourismAmount: number; // 景区分账金额(分)
refundAmount: number; // 退款金额(分)
netIncome: number; // 净收入(分)
};
// 移除设备和航线统计
chartStats: {
orderTrend: {
date: string;
type: string;
value: number;
}[];
orderDistribution: {
type: string;
value: number;
}[];
incomeBreakdown: {
type: string;
value: number;
}[];
};
// 新增筛选维度数据
filterOptions: {
tourismList: { label: string; value: number; }[];
qrcodeList: { label: string; value: string; }[];
deviceList: { label: string; value: string; }[];
};
}
const Welcome: React.FC = () => {
const [loading, setLoading] = useState<boolean>(true);
const [statistics, setStatistics] = useState<any>({});
// 筛选条件
const [selectedTourism, setSelectedTourism] = useState<number | undefined>();
const [selectedQrcode, setSelectedQrcode] = useState<string | undefined>();
const [selectedDevice, setSelectedDevice] = useState<string | undefined>();
const [timeRange, setTimeRange] = useState<[string, string]>(['', '']);
const fetchData = async () => {
try {
setLoading(true);
const result = await dashboard();
const params = {
tourismId: selectedTourism,
qrcodeId: selectedQrcode,
deviceSn: selectedDevice,
startTime: timeRange[0],
endTime: timeRange[1],
};
const result = await dashboard(params);
if (result.resp_code === 0) {
setStatistics(result.data);
}
@@ -69,16 +85,12 @@ const Welcome: React.FC = () => {
useEffect(() => {
fetchData();
const timer = setInterval(fetchData, 5 * 60 * 1000);
return () => clearInterval(timer);
}, []);
}, [selectedTourism, selectedQrcode, selectedDevice, timeRange]);
// 更新数据访问方式
const orderStats = statistics.orderStats || {};
const incomeStats = statistics.incomeStats || {};
const waylineStats = statistics.waylineStats || {};
const deviceStats = statistics.deviceStats || {};
const chartStats = statistics.chartStats || {};
const filterOptions = statistics.filterOptions || {};
// 订单趋势配置
const orderTrendConfig = {
@@ -96,9 +108,9 @@ const Welcome: React.FC = () => {
},
};
// 设备分布配置
const deviceDistConfig = {
data: chartStats.deviceDistribution || [],
// 订单分布配置
const orderDistConfig = {
data: chartStats.orderDistribution || [],
angleField: 'value',
colorField: 'type',
radius: 0.8,
@@ -108,9 +120,9 @@ const Welcome: React.FC = () => {
},
};
// 收入统计配置
// 收入构成配置
const incomeConfig = {
data: chartStats.incomeData || [],
data: chartStats.incomeBreakdown || [],
xField: 'type',
yField: 'value',
label: {
@@ -124,9 +136,58 @@ const Welcome: React.FC = () => {
return (
<PageContainer className={styles.container}>
{/* 筛选条件 */}
<Card style={{ marginBottom: 16 }}>
<Space size="large">
<span>筛选条件:</span>
<Select
placeholder="选择景区"
style={{ width: 200 }}
allowClear
options={filterOptions.tourismList || []}
value={selectedTourism}
onChange={setSelectedTourism}
/>
<Select
placeholder="选择二维码/点位"
style={{ width: 200 }}
allowClear
options={filterOptions.qrcodeList || []}
value={selectedQrcode}
onChange={setSelectedQrcode}
/>
<Select
placeholder="选择设备"
style={{ width: 200 }}
allowClear
options={filterOptions.deviceList || []}
value={selectedDevice}
onChange={setSelectedDevice}
/>
<RangePicker
placeholder={['开始时间', '结束时间']}
onChange={(dates) => {
if (dates) {
setTimeRange([
dates[0]?.format('YYYY-MM-DD HH:mm:ss') || '',
dates[1]?.format('YYYY-MM-DD HH:mm:ss') || ''
]);
}
}}
/>
<Button
icon={<ReloadOutlined />}
onClick={fetchData}
type="primary"
>
刷新
</Button>
</Space>
</Card>
{/* 核心指标 */}
<Row gutter={[16, 16]}>
<Col xs={24} sm={12} md={6}>
<Col xs={24} sm={12} md={8}>
<Card className={styles.statCard} loading={loading}>
<div className={styles.statHeader}>
<ShoppingCartOutlined className={styles.iconOrders} />
@@ -152,65 +213,60 @@ const Welcome: React.FC = () => {
</Card>
</Col>
<Col xs={24} sm={12} md={6}>
<Col xs={24} sm={12} md={8}>
<Card className={styles.statCard} loading={loading}>
<div className={styles.statHeader}>
<PayCircleOutlined className={styles.iconIncome} />
<span>收入统计</span>
</div>
<Statistic
title="总收入"
value={(incomeStats.totalAmount || 0) / 100}
title="订单总金额"
value={(orderStats.totalAmount || 0) / 100}
precision={2}
prefix="¥"
/>
<div className={styles.subStats}>
<Statistic
title="今日收入"
value={(incomeStats.todayAmount || 0) / 100}
title="景区净收入"
value={(orderStats.netIncome || 0) / 100}
precision={2}
prefix="¥"
/>
<Statistic
title="退款金额"
value={(orderStats.refundAmount || 0) / 100}
precision={2}
prefix="¥"
/>
</div>
</Card>
</Col>
<Col xs={24} sm={12} md={8}>
<Card className={styles.statCard} loading={loading}>
<div className={styles.statHeader}>
<PayCircleOutlined className={styles.iconIncome} />
<span>分账明细</span>
</div>
<Statistic
title="平台分账"
value={(orderStats.platformAmount || 0) / 100}
precision={2}
prefix="¥"
/>
<div className={styles.subStats}>
<Statistic
title="景区分账"
value={(orderStats.tourismAmount || 0) / 100}
precision={2}
prefix="¥"
/>
<Progress
percent={incomeStats.targetCompletion || 0}
size="small"
status="active"
/>
</div>
</Card>
</Col>
<Col xs={24} sm={12} md={6}>
<Card className={styles.statCard} loading={loading}>
<div className={styles.statHeader}>
<RocketOutlined className={styles.iconWayline} />
<span>航线概况</span>
</div>
<Statistic title="航线总数" value={waylineStats.totalWaylines || 0} />
<div className={styles.subStats}>
<Statistic title="活跃航线" value={waylineStats.activeWaylines || 0} />
<Progress
percent={waylineStats.waylineUsage || 0}
size="small"
status="active"
/>
</div>
</Card>
</Col>
<Col xs={24} sm={12} md={6}>
<Card className={styles.statCard} loading={loading}>
<div className={styles.statHeader}>
<MobileOutlined className={styles.iconDevice} />
<span>设备状态</span>
</div>
<Statistic title="设备总数" value={deviceStats.totalDevices || 0} />
<div className={styles.subStats}>
<Statistic title="在线设备" value={deviceStats.onlineDevices || 0} />
<Progress
percent={deviceStats.deviceOnlineRate || 0}
percent={orderStats.totalAmount > 0 ?
((orderStats.tourismAmount || 0) / orderStats.totalAmount * 100) : 0}
size="small"
status="active"
format={(percent) => `分账率 ${percent?.toFixed(1)}%`}
/>
</div>
</Card>
@@ -225,34 +281,19 @@ const Welcome: React.FC = () => {
</Card>
</Col>
<Col xs={24} lg={8}>
<Card title="设备分布" loading={loading}>
<Pie {...deviceDistConfig} height={300} />
<Card title="订单状态分布" loading={loading}>
<Pie {...orderDistConfig} height={300} />
</Card>
</Col>
</Row>
{/* 业务数据 */}
<Row gutter={[16, 16]} className={styles.businessRow}>
<Col xs={24} lg={12}>
<Card title="收入统计" loading={loading}>
{/* 收入构成 */}
<Row gutter={[16, 16]}>
<Col xs={24}>
<Card title="收入构成分析" loading={loading}>
<Column {...incomeConfig} height={300} />
</Card>
</Col>
<Col xs={24} lg={12}>
<Card title="景区排名" loading={loading}>
<div className={styles.rankList}>
{statistics.tourismRanking?.map((item: { id: string; name: string; value: number }, index: number) => (
<div key={item.id} className={styles.rankItem}>
<span className={`${styles.rankNum} ${index < 3 ? 'topThree' : ''}`}>
{index + 1}
</span>
<span className={styles.rankName}>{item.name}</span>
<span className={styles.rankValue}>{item.value}</span>
</div>
))}
</div>
</Card>
</Col>
</Row>
</PageContainer>
);
@@ -79,6 +79,15 @@ const UpdateForm: React.FC<UpdateFormProps> = ({
/>
</ProForm.Group>
<ProForm.Group>
<ProFormText
name="tenantId"
label="租户ID"
width="md"
placeholder="请输入租户ID"
/>
</ProForm.Group>
<ProForm.Group>
<ProFormTextArea
name="tourismDesc"
@@ -142,6 +142,12 @@ const TableList: React.FC = () => {
dataIndex: 'tourismPhone',
copyable: true,
},
{
title: '租户ID',
dataIndex: 'tenantId',
copyable: true,
hideInSearch: true,
},
{
title: '状态',
dataIndex: 'status',
@@ -259,6 +265,15 @@ const TableList: React.FC = () => {
/>
</ProForm.Group>
<ProForm.Group>
<ProFormText
name="tenantId"
label="租户ID"
width="md"
placeholder="请输入租户ID(可选,不填将自动获取当前租户)"
/>
</ProForm.Group>
<ProForm.Group>
<ProFormTextArea
name="tourismDesc"
@@ -1,6 +1,6 @@
// 设备维度统计组件
import React, { forwardRef, useImperativeHandle, useState, useEffect } from 'react';
import { ProForm, ProFormDateRangePicker, ProTable } from '@ant-design/pro-components';
import { ProForm, ProFormDateRangePicker, ProFormSelect, ProTable } from '@ant-design/pro-components';
import { Card, Row, Col, Statistic, message } from 'antd';
import { Column } from '@ant-design/plots';
import moment from 'moment';
@@ -24,9 +24,12 @@ interface DeviceStatisticsItem {
interface DeviceStatisticsProps {
refreshKey: number;
deviceOptions: { label: string; value: string; }[];
deviceSn?: string;
onDeviceChange: (deviceSn: string) => void;
}
const DeviceStatistics = forwardRef(({ refreshKey }: DeviceStatisticsProps, ref) => {
const DeviceStatistics = forwardRef(({ refreshKey, deviceOptions, deviceSn, onDeviceChange }: DeviceStatisticsProps, ref) => {
const [loading, setLoading] = useState(false);
const [timeRange, setTimeRange] = useState<[moment.Moment, moment.Moment]>([
moment().startOf('month'),
@@ -41,6 +44,7 @@ const DeviceStatistics = forwardRef(({ refreshKey }: DeviceStatisticsProps, ref)
const params = {
startTime: timeRange[0].format('YYYY-MM-DD HH:mm:ss'),
endTime: timeRange[1].format('YYYY-MM-DD HH:mm:ss'),
deviceSn: deviceSn,
};
const res = await getDeviceStatistics(params);
@@ -191,8 +195,8 @@ const DeviceStatistics = forwardRef(({ refreshKey }: DeviceStatisticsProps, ref)
submitter={false}
initialValues={{ timeRange }}
>
<Row>
<Col span={24}>
<Row gutter={16}>
<Col span={12}>
<ProFormDateRangePicker
name="timeRange"
label="统计时间"
@@ -208,6 +212,19 @@ const DeviceStatistics = forwardRef(({ refreshKey }: DeviceStatisticsProps, ref)
}}
/>
</Col>
<Col span={12}>
<ProFormSelect
name="deviceSn"
label="选择设备"
fieldProps={{
value: deviceSn,
onChange: onDeviceChange,
options: deviceOptions,
placeholder: '请选择设备',
allowClear: true,
}}
/>
</Col>
</Row>
</ProForm>
</Card>
@@ -1,5 +1,5 @@
import React, { forwardRef, useImperativeHandle, useState, useEffect } from 'react';
import { ProForm, ProFormDateRangePicker, ProTable } from '@ant-design/pro-components';
import { ProForm, ProFormDateRangePicker, ProFormSelect, ProTable } from '@ant-design/pro-components';
import { Card, Row, Col, Statistic, message } from 'antd';
import { Column } from '@ant-design/plots';
import moment from 'moment';
@@ -23,9 +23,12 @@ interface TourismStatisticsItem {
interface TourismStatisticsProps {
refreshKey: number;
tourismOptions: { label: string; value: string; }[];
tourismId?: string;
onTourismChange: (tourismId: string) => void;
}
const TourismStatistics = forwardRef(({ refreshKey }: TourismStatisticsProps, ref) => {
const TourismStatistics = forwardRef(({ refreshKey, tourismOptions, tourismId, onTourismChange }: TourismStatisticsProps, ref) => {
const [loading, setLoading] = useState(false);
const [timeRange, setTimeRange] = useState<[moment.Moment, moment.Moment]>([
moment().startOf('month'),
@@ -40,6 +43,7 @@ const TourismStatistics = forwardRef(({ refreshKey }: TourismStatisticsProps, re
const params = {
startTime: timeRange[0].format('YYYY-MM-DD HH:mm:ss'),
endTime: timeRange[1].format('YYYY-MM-DD HH:mm:ss'),
tourismId: tourismId,
};
const res = await getTourismStatistics(params);
@@ -191,8 +195,8 @@ const TourismStatistics = forwardRef(({ refreshKey }: TourismStatisticsProps, re
submitter={false}
initialValues={{ timeRange }}
>
<Row>
<Col span={24}>
<Row gutter={16}>
<Col span={12}>
<ProFormDateRangePicker
name="timeRange"
label="统计时间"
@@ -208,6 +212,19 @@ const TourismStatistics = forwardRef(({ refreshKey }: TourismStatisticsProps, re
}}
/>
</Col>
<Col span={12}>
<ProFormSelect
name="tourismId"
label="选择景区"
fieldProps={{
value: tourismId,
onChange: onTourismChange,
options: tourismOptions,
placeholder: '请选择景区',
allowClear: true,
}}
/>
</Col>
</Row>
</ProForm>
</Card>
@@ -3,7 +3,7 @@ import { PageContainer } from '@ant-design/pro-components';
import { Card, Tabs, Button, message, Modal, DatePicker } from 'antd';
import { ReloadOutlined, DownloadOutlined, LineChartOutlined } from '@ant-design/icons';
import type { TabsProps } from 'antd';
import { getQrcodeList, generateStatistics } from '@/services/statistics/api';
import { getQrcodeList, getDeviceList, getTourismList, generateStatistics } from '@/services/statistics/api';
import QrcodeStatistics from './components/QrcodeStatistics';
import DeviceStatistics from './components/DeviceStatistics';
import TourismStatistics from './components/TourismStatistics';
@@ -13,7 +13,11 @@ const { RangePicker } = DatePicker;
const Statistics: React.FC = () => {
const [qrcodeOptions, setQrcodeOptions] = useState<{ label: string; value: string; }[]>([]);
const [deviceOptions, setDeviceOptions] = useState<{ label: string; value: string; }[]>([]);
const [tourismOptions, setTourismOptions] = useState<{ label: string; value: string; }[]>([]);
const [qrcodeId, setQrcodeId] = useState<string>();
const [deviceSn, setDeviceSn] = useState<string>();
const [tourismId, setTourismId] = useState<string>();
const [refreshKey, setRefreshKey] = useState(0);
const [generateModalVisible, setGenerateModalVisible] = useState(false);
const [generateTimeRange, setGenerateTimeRange] = useState<[moment.Moment, moment.Moment]>([
@@ -27,24 +31,73 @@ const Statistics: React.FC = () => {
const fetchQrcodeList = async () => {
try {
const res = await getQrcodeList({ page: 1, limit: 100 });
console.log('二维码列表响应:', res); // 添加调试日志
if (res.resp_code === 0 && res.data) {
const options = res.data.map((item: any) => ({
label: `${item.name || item.qrcode} | ${item.deviceSn || '无设备'} | ${((item.price || 0) / 100).toFixed(2)}元`,
label: `${item.name || item.codeId} | ${item.deviceSn || '无设备'} | ${((item.price || 0) / 100).toFixed(2)}元`,
value: item.codeId,
}));
console.log('二维码选项:', options); // 添加调试日志
setQrcodeOptions(options);
if (options.length > 0) {
setQrcodeId(options[0].value);
}
}
} catch (error) {
console.error('获取二维码列表失败:', error); // 添加错误日志
message.error('获取二维码列表失败');
}
};
// 获取设备列表
const fetchDeviceList = async () => {
try {
const res = await getDeviceList({ page: 1, limit: 100 });
console.log('设备列表响应:', res);
if (res.resp_code === 0 && res.data) {
const options = res.data.map((item: any) => ({
label: `${item.deviceSn || '未知设备'} | ${item.deviceName || '无名称'}`,
value: item.deviceSn,
}));
console.log('设备选项:', options);
setDeviceOptions(options);
if (options.length > 0) {
setDeviceSn(options[0].value);
}
}
} catch (error) {
console.error('获取设备列表失败:', error);
message.error('获取设备列表失败');
}
};
// 获取景区列表
const fetchTourismList = async () => {
try {
const res = await getTourismList({ page: 1, limit: 100 });
console.log('景区列表响应:', res);
if (res.resp_code === 0 && res.data) {
const options = res.data.map((item: any) => ({
label: `${item.name || '未知景区'} | ${item.address || '无地址'}`,
value: item.id?.toString(),
}));
console.log('景区选项:', options);
setTourismOptions(options);
if (options.length > 0) {
setTourismId(options[0].value);
}
}
} catch (error) {
console.error('获取景区列表失败:', error);
message.error('获取景区列表失败');
}
};
// 初始化加载
useEffect(() => {
fetchQrcodeList();
fetchDeviceList();
fetchTourismList();
}, []);
// 生成统计数据
@@ -158,6 +211,9 @@ const Statistics: React.FC = () => {
children: (
<DeviceStatistics
ref={deviceRef}
deviceOptions={deviceOptions}
deviceSn={deviceSn}
onDeviceChange={setDeviceSn}
refreshKey={refreshKey}
/>
),
@@ -168,6 +224,9 @@ const Statistics: React.FC = () => {
children: (
<TourismStatistics
ref={tourismRef}
tourismOptions={tourismOptions}
tourismId={tourismId}
onTourismChange={setTourismId}
refreshKey={refreshKey}
/>
),
@@ -184,9 +184,16 @@ export async function getOrderDetail(orderNo: string) {
}
/** 获取首页统计数据 GET /api-order/dashboard/statistics */
export async function dashboard() {
export async function dashboard(params?: {
tourismId?: number;
qrcodeId?: string;
deviceSn?: string;
startTime?: string;
endTime?: string;
}) {
return request('/api-order/dashboard/statistics', {
method: 'GET',
params,
});
}
@@ -108,21 +108,12 @@ declare namespace ORDERS {
todayOrders: number;
orderGrowth: number;
completionRate: number;
};
incomeStats: {
totalAmount: number;
todayAmount: number;
targetCompletion: number;
};
waylineStats: {
totalWaylines: number;
activeWaylines: number;
waylineUsage: number;
};
deviceStats: {
totalDevices: number;
onlineDevices: number;
deviceOnlineRate: number;
// 对账相关字段
totalAmount: number; // 订单总金额(分)
platformAmount: number; // 平台分账金额(分)
tourismAmount: number; // 景区分账金额(分)
refundAmount: number; // 退款金额(分)
netIncome: number; // 净收入(分)
};
chartStats: {
orderTrend: Array<{
@@ -130,20 +121,29 @@ declare namespace ORDERS {
type: string;
value: number;
}>;
deviceDistribution: Array<{
orderDistribution: Array<{
type: string;
value: number;
}>;
incomeData: Array<{
incomeBreakdown: Array<{
type: string;
value: number;
}>;
};
tourismRanking: Array<{
id: string;
name: string;
value: number;
}>;
filterOptions: {
tourismList: Array<{
label: string;
value: number;
}>;
qrcodeList: Array<{
label: string;
value: string;
}>;
deviceList: Array<{
label: string;
value: string;
}>;
};
}
interface ProfitSharing {
@@ -14,6 +14,34 @@ export async function getQrcodeList(params: QrcodeListParams = { page: 1, limit:
});
}
/** 获取设备列表参数 */
interface DeviceListParams {
page: number;
limit: number;
}
/** 获取设备列表 */
export async function getDeviceList(params: DeviceListParams = { page: 1, limit: 100 }) {
return request('/api-device/device', {
method: 'GET',
params,
});
}
/** 获取景区列表参数 */
interface TourismListParams {
page: number;
limit: number;
}
/** 获取景区列表 */
export async function getTourismList(params: TourismListParams = { page: 1, limit: 100 }) {
return request('/api-order/tourism', {
method: 'GET',
params,
});
}
/** 时间维度类型 */
type TimeType = 'hour' | 'day' | 'month';
@@ -46,6 +74,7 @@ export async function getTimeStatistics(params: TimeStatisticsParams) {
interface DeviceStatisticsParams {
startTime: string;
endTime: string;
deviceSn?: string;
}
/** 获取设备维度统计数据 */
@@ -56,11 +85,15 @@ export async function getDeviceStatistics(params: DeviceStatisticsParams) {
});
}
/** 获取景区维度统计数据 */
export async function getTourismStatistics(params: {
/** 获取景区维度统计数据参数 */
interface TourismStatisticsParams {
startTime: string;
endTime: string;
}) {
tourismId?: string;
}
/** 获取景区维度统计数据 */
export async function getTourismStatistics(params: TourismStatisticsParams) {
return request('/api-order/statistics/tourism', {
method: 'GET',
params,