diff --git a/zlt-business/order-center/README.md b/zlt-business/order-center/README.md index 6ef05704..b9ae66d3 100644 --- a/zlt-business/order-center/README.md +++ b/zlt-business/order-center/README.md @@ -3,3 +3,20 @@ 1. 景区管理 2. 套餐管理 3. 素材管理 + + + +-- 订单创建时间 + 状态的联合索引(用于时间范围和状态统计) +CREATE INDEX idx_orders_create_status ON orders(create_time, order_status); + +-- 二维码ID + 创建时间的联合索引(用于按二维码统计) +CREATE INDEX idx_orders_qrcode_time ON orders(code_id, create_time); + +-- 景区ID + 创建时间的联合索引(用于按景区统计) +CREATE INDEX idx_orders_tourism_time ON orders(tourism_id, create_time); + +-- 设备编号 + 创建时间的联合索引(用于按设备统计) +CREATE INDEX idx_orders_device_time ON orders(device_sn, create_time); + +-- 软删除标记 + 创建时间的联合索引(用于过滤已删除订单) +CREATE INDEX idx_orders_del_time ON orders(is_del, create_time); diff --git a/zlt-business/order-center/src/main/java/com/central/order/constants/OrderStatusConstants.java b/zlt-business/order-center/src/main/java/com/central/order/constants/OrderStatusConstants.java new file mode 100644 index 00000000..f30536ee --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/constants/OrderStatusConstants.java @@ -0,0 +1,21 @@ +package com.central.order.constants; + +import com.central.order.enums.OrderStatus; + +public class OrderStatusConstants { + + // 已支付状态集合(已支付排队中、正在服务中、设备执行完成、素材上传中、素材上传完成) + public static final String PAID_STATUS = String.format("(%d,%d,%d,%d,%d)", + OrderStatus.PAID.getId(), // 1-已支付排队中 + OrderStatus.DOING.getId(), // 4-正在服务中 + OrderStatus.COMPLETE.getId(), // 3-设备执行完成 + OrderStatus.UPLOADING.getId(), // 5-素材上传中 + OrderStatus.UPLOADED.getId() // 6-素材上传完成 + ); + + // 退款状态集合(退款中、已退款) + public static final String REFUND_STATUS = String.format("(%d,%d)", + OrderStatus.REFUNDING.getId(), // 7-退款中 + OrderStatus.REFUNDED.getId() // 8-已退款 + ); +} \ No newline at end of file diff --git a/zlt-business/order-center/src/main/java/com/central/order/mapper/OrderStatisticsMapper.java b/zlt-business/order-center/src/main/java/com/central/order/mapper/OrderStatisticsMapper.java index be362d78..b83157b9 100644 --- a/zlt-business/order-center/src/main/java/com/central/order/mapper/OrderStatisticsMapper.java +++ b/zlt-business/order-center/src/main/java/com/central/order/mapper/OrderStatisticsMapper.java @@ -2,8 +2,8 @@ package com.central.order.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.central.order.model.OrderStatistics; +import com.central.order.model.OrderStatisticsQuery; import org.apache.ibatis.annotations.Mapper; -import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import java.util.List; @@ -11,85 +11,56 @@ import java.util.Map; @Mapper public interface OrderStatisticsMapper extends BaseMapper { - + @Select({ + "" }) - List> statisticsByQrcode( - @Param("startTime") String startTime, - @Param("endTime") String endTime - ); - - @Select({ - "SELECT DATE_FORMAT(o.create_time, #{dateFormat}) as timeGroup,", - " COUNT(o.id) as totalOrders,", - " SUM(CAST(o.order_amount AS SIGNED)) as totalAmount", - "FROM orders o", - "WHERE o.code_id = #{qrcodeId}", - " AND o.create_time BETWEEN #{startTime} AND #{endTime}", - " AND o.is_del = 0", - "GROUP BY timeGroup", - "ORDER BY timeGroup" - }) - List> statisticsByTime( - @Param("qrcodeId") String qrcodeId, - @Param("startTime") String startTime, - @Param("endTime") String endTime, - @Param("dateFormat") String dateFormat - ); + List> getOrderStatistics(OrderStatisticsQuery query); @Select({ + "" }) - List> statisticsByDevice( - @Param("startTime") String startTime, - @Param("endTime") String endTime - ); -} \ No newline at end of file + List> getOrderStatisticsByGroup(OrderStatisticsQuery query); +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/OrderStatisticsQuery.java b/zlt-business/order-center/src/main/java/com/central/order/model/OrderStatisticsQuery.java new file mode 100644 index 00000000..d2efde49 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/OrderStatisticsQuery.java @@ -0,0 +1,28 @@ +package com.central.order.model; + +import com.central.order.constants.OrderStatusConstants; +import com.central.order.enums.OrderStatus; +import lombok.Builder; +import lombok.Data; + +@Data +@Builder +public class OrderStatisticsQuery { + private String startTime; + private String endTime; + private String qrcodeId; + private Long tourismId; + private String deviceSn; + private String groupField; // 分组字段 + + @Builder.Default + private Integer completeStatus = OrderStatus.COMPLETE.getId(); + @Builder.Default + private Integer cancelStatus = OrderStatus.CANCELED.getId(); + + // 添加状态集合字符串 + @Builder.Default + private String paidStatus = OrderStatusConstants.PAID_STATUS; + @Builder.Default + private String refundStatus = OrderStatusConstants.REFUND_STATUS; +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/QrCode.java b/zlt-business/order-center/src/main/java/com/central/order/model/QrCode.java index 3f0e95ec..f9e0b31a 100644 --- a/zlt-business/order-center/src/main/java/com/central/order/model/QrCode.java +++ b/zlt-business/order-center/src/main/java/com/central/order/model/QrCode.java @@ -26,6 +26,9 @@ public class QrCode extends SuperEntity { private String codeId; private Long tourismId; + + // 新增二维码名称字段 + private String name; private String templateId; private String filePath; diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/impl/OrderStatisticsServiceImpl.java b/zlt-business/order-center/src/main/java/com/central/order/service/impl/OrderStatisticsServiceImpl.java index dee14595..74193352 100644 --- a/zlt-business/order-center/src/main/java/com/central/order/service/impl/OrderStatisticsServiceImpl.java +++ b/zlt-business/order-center/src/main/java/com/central/order/service/impl/OrderStatisticsServiceImpl.java @@ -4,11 +4,12 @@ import com.central.common.model.PageResult; import com.central.common.service.impl.SuperServiceImpl; import com.central.order.mapper.OrderStatisticsMapper; import com.central.order.model.OrderStatistics; -import com.central.order.model.QrCode; +import com.central.order.model.OrderStatisticsQuery; import com.central.order.service.IOrderStatisticsService; import com.central.order.service.IQrCodeService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -18,7 +19,6 @@ import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; -import java.util.HashMap; import java.util.List; import java.util.Map; @@ -41,72 +41,78 @@ public class OrderStatisticsServiceImpl extends SuperServiceImpl> statisticsList = orderStatisticsMapper.statisticsByQrcode(startTime, endTime); - + // 使用新的查询方法 + OrderStatisticsQuery query = OrderStatisticsQuery.builder() + .startTime(startTime) + .endTime(endTime) + .build(); + + List> statisticsList = orderStatisticsMapper.getOrderStatistics(query); + for (Map statistics : statisticsList) { OrderStatistics orderStatistics = new OrderStatistics(); - + // 设置基础信息 orderStatistics.setQrcodeId(String.valueOf(statistics.get("qrcodeId"))); orderStatistics.setTourismId(getLongValue(statistics.get("tourismId"))); orderStatistics.setTourismName(String.valueOf(statistics.get("tourismName"))); orderStatistics.setDeviceSn(String.valueOf(statistics.get("deviceSn"))); - + // 设置订单统计 orderStatistics.setTotalOrders(getIntegerValue(statistics.get("totalOrders"))); orderStatistics.setPaidOrders(getIntegerValue(statistics.get("paidOrders"))); orderStatistics.setCompletedOrders(getIntegerValue(statistics.get("completedOrders"))); orderStatistics.setCanceledOrders(getIntegerValue(statistics.get("canceledOrders"))); - + // 设置金额统计 orderStatistics.setTotalAmount(getLongValue(statistics.get("totalAmount"))); orderStatistics.setPaidAmount(getLongValue(statistics.get("paidAmount"))); orderStatistics.setRefundAmount(getLongValue(statistics.get("refundAmount"))); - + // 设置默认分账比例和金额 BigDecimal platformRate = new BigDecimal("0.30"); BigDecimal tourismRate = new BigDecimal("0.70"); - + orderStatistics.setPlatformRate(platformRate); orderStatistics.setTourismRate(tourismRate); - + // 计算分账金额 Long paidAmount = orderStatistics.getPaidAmount(); if (paidAmount == null) { paidAmount = 0L; } - + // 计算平台分成金额 Long platformAmount = platformRate .multiply(new BigDecimal(paidAmount)) .divide(new BigDecimal("100"), 0, RoundingMode.HALF_UP) .longValue(); orderStatistics.setPlatformAmount(platformAmount); - + // 计算景区分成金额 Long tourismAmount = tourismRate .multiply(new BigDecimal(paidAmount)) .divide(new BigDecimal("100"), 0, RoundingMode.HALF_UP) .longValue(); orderStatistics.setTourismAmount(tourismAmount); - + // 设置时间 orderStatistics.setStartTime(parseDateTime(startTime)); orderStatistics.setEndTime(parseDateTime(endTime)); orderStatistics.setCreateTime(new Date()); - + // 设置统计日期 SimpleDateFormat dateSdf = new SimpleDateFormat("yyyy-MM-dd"); orderStatistics.setStatisticsDate(dateSdf.format(new Date())); - + // 设置统计小时 Calendar cal = Calendar.getInstance(); orderStatistics.setStatisticsHour(cal.get(Calendar.HOUR_OF_DAY)); - + // 保存统计数据 orderStatisticsMapper.insert(orderStatistics); } - + return true; } catch (Exception e) { log.error("生成统计数据失败", e); @@ -162,38 +168,34 @@ public class OrderStatisticsServiceImpl extends SuperServiceImpl> statisticsByTime(String qrcodeId, String startTime, String endTime, String timeType) { try { - String dateFormat; + String groupField; switch (timeType) { case "hour": - dateFormat = "%Y-%m-%d %H:00:00"; + groupField = "DATE_FORMAT(o.create_time, '%Y-%m-%d %H:00:00')"; break; case "day": - dateFormat = "%Y-%m-%d"; + groupField = "DATE_FORMAT(o.create_time, '%Y-%m-%d')"; break; case "month": - dateFormat = "%Y-%m"; + groupField = "DATE_FORMAT(o.create_time, '%Y-%m')"; break; default: - dateFormat = "%Y-%m-%d"; + groupField = "DATE_FORMAT(o.create_time, '%Y-%m-%d')"; } - List> statistics = orderStatisticsMapper.statisticsByTime( - qrcodeId, startTime, endTime, dateFormat); + OrderStatisticsQuery query = OrderStatisticsQuery.builder() + .startTime(startTime) + .endTime(endTime) + .qrcodeId(qrcodeId) + .groupField(groupField) + .build(); - // 处理统计数据 - for (Map stat : statistics) { - // 添加金额格式化(转换为元) - Long totalAmount = getLongValue(stat.get("totalAmount")); - stat.put("totalAmountYuan", formatAmount(totalAmount)); - - // 添加时间格式化 - String timeGroup = (String) stat.get("timeGroup"); - stat.put("formatTime", formatTimeGroup(timeGroup, timeType)); - } - - return statistics; + List> statistics = baseMapper.getOrderStatisticsByGroup(query); + return processStatisticsResult(statistics); } catch (Exception e) { log.error("按时间维度统计失败", e); return List.of(); @@ -203,31 +205,14 @@ public class OrderStatisticsServiceImpl extends SuperServiceImpl> statisticsByTourism(String startTime, String endTime) { try { - List> statistics = orderStatisticsMapper.statisticsByTourism(startTime, endTime); - - // 处理统计数据 - for (Map stat : statistics) { - // 添加金额格式化 - Long totalAmount = getLongValue(stat.get("totalAmount")); - Long paidAmount = getLongValue(stat.get("paidAmount")); - Long refundAmount = getLongValue(stat.get("refundAmount")); - - stat.put("totalAmountYuan", formatAmount(totalAmount)); - stat.put("paidAmountYuan", formatAmount(paidAmount)); - stat.put("refundAmountYuan", formatAmount(refundAmount)); - - // 计算完成率 - Integer totalOrders = getIntegerValue(stat.get("totalOrders")); - Integer completedOrders = getIntegerValue(stat.get("completedOrders")); - if (totalOrders > 0) { - double completionRate = (completedOrders * 100.0) / totalOrders; - stat.put("completionRate", String.format("%.2f%%", completionRate)); - } else { - stat.put("completionRate", "0.00%"); - } - } - - return statistics; + OrderStatisticsQuery query = OrderStatisticsQuery.builder() + .startTime(startTime) + .endTime(endTime) + .groupField("o.tourism_id") + .build(); + + List> statistics = baseMapper.getOrderStatisticsByGroup(query); + return processStatisticsResult(statistics); } catch (Exception e) { log.error("按景区维度统计失败", e); return List.of(); @@ -237,33 +222,48 @@ public class OrderStatisticsServiceImpl extends SuperServiceImpl> statisticsByDevice(String startTime, String endTime) { try { - List> statistics = orderStatisticsMapper.statisticsByDevice(startTime, endTime); - - // 处理统计数据 - for (Map stat : statistics) { - // 添加金额格式化 - Long totalAmount = getLongValue(stat.get("totalAmount")); - stat.put("totalAmountYuan", formatAmount(totalAmount)); - - // 计算设备使用率 - Integer totalHours = getIntegerValue(stat.get("totalHours")); - Integer usedHours = getIntegerValue(stat.get("usedHours")); - if (totalHours > 0) { - double usageRate = (usedHours * 100.0) / totalHours; - stat.put("usageRate", String.format("%.2f%%", usageRate)); - } else { - stat.put("usageRate", "0.00%"); - } - } - - return statistics; + OrderStatisticsQuery query = OrderStatisticsQuery.builder() + .startTime(startTime) + .endTime(endTime) + .groupField("o.device_sn") + .build(); + + List> statistics = baseMapper.getOrderStatisticsByGroup(query); + return processStatisticsResult(statistics); } catch (Exception e) { log.error("按设备维度统计失败", e); return List.of(); } } - // 格式化金额(分转元) + /** + * 处理统计结果 + */ + private List> processStatisticsResult(List> statistics) { + for (Map stat : statistics) { + // 添加金额格式化(转换为元) + Long totalAmount = getLongValue(stat.get("totalAmount")); + Long paidAmount = getLongValue(stat.get("paidAmount")); + Long refundAmount = getLongValue(stat.get("refundAmount")); + + stat.put("totalAmountYuan", formatAmount(totalAmount)); + stat.put("paidAmountYuan", formatAmount(paidAmount)); + stat.put("refundAmountYuan", formatAmount(refundAmount)); + + // 计算完成率 + Integer totalOrders = getIntegerValue(stat.get("totalOrders")); + Integer completedOrders = getIntegerValue(stat.get("completedOrders")); + if (totalOrders > 0) { + double completionRate = (completedOrders * 100.0) / totalOrders; + stat.put("completionRate", String.format("%.2f%%", completionRate)); + } else { + stat.put("completionRate", "0.00%"); + } + } + return statistics; + } + + // 格式化金额 private String formatAmount(Long amount) { if (amount == null) { return "0.00"; diff --git a/zlt-web/react-web/src/main/frontend/package.json b/zlt-web/react-web/src/main/frontend/package.json index 38d22bdd..62c6ba7d 100644 --- a/zlt-web/react-web/src/main/frontend/package.json +++ b/zlt-web/react-web/src/main/frontend/package.json @@ -49,9 +49,11 @@ "@ant-design/icons": "^4.7.0", "@ant-design/pro-components": "1.1.1", "@babel/runtime": "^7.27.0", + "@types/file-saver": "^2.0.7", "@umijs/route-utils": "^2.0.0", "antd": "^4.20.0", "classnames": "^2.3.0", + "file-saver": "^2.0.5", "lodash": "^4.17.21", "moment": "^2.29.0", "omit.js": "^2.0.2", @@ -67,7 +69,8 @@ "spark-md5": "^3.0.2", "treeify-js": "^1.0.8", "umi": "^3.5.0", - "uuid": "^9.0.0" + "uuid": "^9.0.0", + "xlsx": "^0.18.5" }, "devDependencies": { "@ant-design/pro-cli": "^2.1.0", diff --git a/zlt-web/react-web/src/main/frontend/src/pages/device/Wayline/index.tsx b/zlt-web/react-web/src/main/frontend/src/pages/device/Wayline/index.tsx index 9df6ab44..fb69ae1a 100644 --- a/zlt-web/react-web/src/main/frontend/src/pages/device/Wayline/index.tsx +++ b/zlt-web/react-web/src/main/frontend/src/pages/device/Wayline/index.tsx @@ -28,7 +28,7 @@ const statusColorMap = { }; // 提取常量 -const WORKSPACE_OPTIONS: DefaultOptionType[] = [ +export const WORKSPACE_OPTIONS: DefaultOptionType[] = [ { label: '工作区1', value: '1' }, { label: '工作区2', value: '2' }, // ... 根据实际需求添加更多选项 diff --git a/zlt-web/react-web/src/main/frontend/src/pages/orders/statistics/index.less b/zlt-web/react-web/src/main/frontend/src/pages/orders/statistics/index.less new file mode 100644 index 00000000..48f1c8f4 --- /dev/null +++ b/zlt-web/react-web/src/main/frontend/src/pages/orders/statistics/index.less @@ -0,0 +1,61 @@ +.statistics-filter-card { + .ant-form { + .ant-row { + align-items: flex-end; + } + } + + .ant-radio-group { + margin-bottom: 24px; + + .ant-radio-button-wrapper { + min-width: 100px; + text-align: center; + } + } +} + +.ant-tabs-card { + .ant-tabs-content { + margin-top: -16px; + } + + .ant-tabs-tab { + border-radius: 4px 4px 0 0; + background: #fafafa; + border-color: #f0f0f0; + + &.ant-tabs-tab-active { + background: #fff; + } + } + + .ant-card { + border-radius: 0 4px 4px 4px; + } +} + +.ant-card { + .ant-statistic { + .ant-statistic-title { + font-size: 14px; + color: rgba(0, 0, 0, 0.45); + } + + .ant-statistic-content { + font-size: 24px; + font-weight: 500; + } + } +} + +.ant-pro-table { + .ant-table { + .ant-table-thead { + > tr > th { + background: #fafafa; + font-weight: 500; + } + } + } +} \ No newline at end of file diff --git a/zlt-web/react-web/src/main/frontend/src/pages/orders/statistics/index.tsx b/zlt-web/react-web/src/main/frontend/src/pages/orders/statistics/index.tsx new file mode 100644 index 00000000..fb54e250 --- /dev/null +++ b/zlt-web/react-web/src/main/frontend/src/pages/orders/statistics/index.tsx @@ -0,0 +1,387 @@ +import React, { useState, useEffect, useRef } from 'react'; +import { PageContainer, ProForm, ProFormDateRangePicker, ProFormSelect, ProTable } from '@ant-design/pro-components'; +import { Card, Radio, Space, message, Tabs, Row, Col, Statistic, Button } from 'antd'; +import { Line } from '@ant-design/plots'; +import { ReloadOutlined, DownloadOutlined } from '@ant-design/icons'; +import moment from 'moment'; +import { getTimeStatistics, getQrcodeList } from '@/services/statistics/api'; +import { exportExcel } from '@/utils/export'; + +// 定义数据结构接口 +interface StatisticsItem { + groupKey: string; + totalOrders: number; + paidOrders: number; + completedOrders: number; + canceledOrders: number; + totalAmount: number; + totalAmountYuan: string; + paidAmount: number; + paidAmountYuan: string; + refundAmount: number; + refundAmountYuan: string; + completionRate: string; +} + +const Statistics: React.FC = () => { + const [loading, setLoading] = useState(false); + const [qrcodeOptions, setQrcodeOptions] = useState<{ label: string; value: string; }[]>([]); + const [qrcodeId, setQrcodeId] = useState(); + const [timeType, setTimeType] = useState<'hour' | 'day' | 'month'>('day'); + const [timeRange, setTimeRange] = useState<[moment.Moment, moment.Moment]>([ + moment().startOf('month'), + moment().endOf('month') + ]); + const [statisticsData, setStatisticsData] = useState([]); + const [refreshKey, setRefreshKey] = useState(0); // 用于触发数据刷新 + + // 自动刷新定时器 + const refreshTimer = useRef(); + + // 获取二维码列表 + const fetchQrcodeList = async () => { + try { + const res = await getQrcodeList({ page: 1, limit: 100 }); + 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)}元`, + value: item.codeId, + })); + setQrcodeOptions(options); + if (options.length > 0) { + setQrcodeId(options[0].value); + } + } + } catch (error) { + message.error('获取二维码列表失败'); + } + }; + + // 获取统计数据 + const fetchStatisticsData = async () => { + if (!qrcodeId) return; + + setLoading(true); + try { + const params = { + qrcodeId, + startTime: timeRange[0].format('YYYY-MM-DD HH:mm:ss'), + endTime: timeRange[1].format('YYYY-MM-DD HH:mm:ss'), + timeType, + }; + + const res = await getTimeStatistics(params); + if (res.resp_code === 0) { + setStatisticsData(res.data || []); + } + } catch (error) { + message.error('获取统计数据失败'); + } finally { + setLoading(false); + } + }; + + // 处理数据导出 + const handleExport = () => { + const header = [ + { title: '统计时间', dataIndex: 'groupKey' }, + { title: '订单总数', dataIndex: 'totalOrders' }, + { title: '已支付订单数', dataIndex: 'paidOrders' }, + { title: '已完成订单数', dataIndex: 'completedOrders' }, + { title: '已取消订单数', dataIndex: 'canceledOrders' }, + { title: '订单总金额(元)', dataIndex: 'totalAmountYuan' }, + { title: '已支付金额(元)', dataIndex: 'paidAmountYuan' }, + { title: '退款金额(元)', dataIndex: 'refundAmountYuan' }, + { title: '完成率', dataIndex: 'completionRate' }, + ]; + + exportExcel({ + data: statisticsData, + header, + fileName: `订单统计数据_${moment().format('YYYY-MM-DD')}`, + }); + }; + + // 图表配置 + const chartConfig = { + data: statisticsData, + loading, + xField: 'groupKey', + yField: 'value', + seriesField: 'type', + smooth: true, + meta: { + value: { + alias: '数量/金额', + }, + }, + tooltip: { + formatter: (datum: any) => ({ + name: datum.type, + value: datum.type.includes('金额') ? `¥${datum.value}` : datum.value, + }), + }, + }; + + // 处理图表数据 + const getChartData = () => { + const result: any[] = []; + statisticsData.forEach(item => { + result.push( + { + groupKey: item.groupKey, + type: '订单总数', + value: item.totalOrders, + }, + { + groupKey: item.groupKey, + type: '总金额(元)', + value: Number(item.totalAmountYuan), + }, + ); + }); + return result; + }; + + // 表格列定义 + const columns = [ + { + title: '统计时间', + dataIndex: 'groupKey', + width: 180, + fixed: 'left', + }, + { + title: '订单数量', + children: [ + { + title: '总订单', + dataIndex: 'totalOrders', + width: 100, + sorter: (a, b) => a.totalOrders - b.totalOrders, + }, + { + title: '已支付', + dataIndex: 'paidOrders', + width: 100, + sorter: (a, b) => a.paidOrders - b.paidOrders, + }, + { + title: '已完成', + dataIndex: 'completedOrders', + width: 100, + sorter: (a, b) => a.completedOrders - b.completedOrders, + }, + { + title: '已取消', + dataIndex: 'canceledOrders', + width: 100, + sorter: (a, b) => a.canceledOrders - b.canceledOrders, + }, + { + title: '完成率', + dataIndex: 'completionRate', + width: 100, + sorter: (a, b) => parseFloat(a.completionRate) - parseFloat(b.completionRate), + } + ], + }, + { + title: '订单金额(元)', + children: [ + { + title: '总金额', + dataIndex: 'totalAmountYuan', + width: 120, + sorter: (a, b) => parseFloat(a.totalAmountYuan) - parseFloat(b.totalAmountYuan), + }, + { + title: '已支付', + dataIndex: 'paidAmountYuan', + width: 120, + sorter: (a, b) => parseFloat(a.paidAmountYuan) - parseFloat(b.paidAmountYuan), + }, + { + title: '退款', + dataIndex: 'refundAmountYuan', + width: 120, + sorter: (a, b) => parseFloat(a.refundAmountYuan) - parseFloat(b.refundAmountYuan), + }, + ], + }, + ]; + + // 计算总览数据 + const getOverviewData = () => { + if (statisticsData.length === 0) return null; + + return statisticsData.reduce((acc, cur) => ({ + totalOrders: acc.totalOrders + cur.totalOrders, + paidOrders: acc.paidOrders + cur.paidOrders, + totalAmount: acc.totalAmount + parseFloat(cur.totalAmountYuan), + avgCompletionRate: (acc.avgCompletionRate + parseFloat(cur.completionRate)) / 2, + }), { + totalOrders: 0, + paidOrders: 0, + totalAmount: 0, + avgCompletionRate: 0, + }); + }; + + // 自动刷新 + useEffect(() => { + refreshTimer.current = setInterval(() => { + setRefreshKey(prev => prev + 1); + }, 300000); // 每5分钟刷新一次 + + return () => { + if (refreshTimer.current) { + clearInterval(refreshTimer.current); + } + }; + }, []); + + // 添加初始化加载二维码列表 + useEffect(() => { + fetchQrcodeList(); + }, []); + + // 数据刷新 + useEffect(() => { + fetchStatisticsData(); + }, [qrcodeId, timeType, timeRange, refreshKey]); + + return ( + } + onClick={() => setRefreshKey(prev => prev + 1)} + > + 刷新 + , + , + ]} + > + {/* 筛选条件 */} + + + + + + (option?.label ?? '').toLowerCase().includes(input.toLowerCase()), + optionLabelProp: "label", + }} + /> + + + + + + setTimeType(e.target.value)} + optionType="button" + buttonStyle="solid" + > + 按小时 + 按天 + 按月 + + + + + + + {/* 数据概览 */} + + + + + + + + + + + + + + + + + + {/* 趋势图表 */} + +
+ +
+
+ + {/* 详细数据表格 */} + + + +
+ ); +}; + +export default Statistics; \ No newline at end of file diff --git a/zlt-web/react-web/src/main/frontend/src/pages/statistics/components/StatisticsTable.tsx b/zlt-web/react-web/src/main/frontend/src/pages/statistics/components/StatisticsTable.tsx deleted file mode 100644 index 82b5f775..00000000 --- a/zlt-web/react-web/src/main/frontend/src/pages/statistics/components/StatisticsTable.tsx +++ /dev/null @@ -1,80 +0,0 @@ -import React from 'react'; -import { ProTable } from '@ant-design/pro-components'; -import type { ProColumns } from '@ant-design/pro-components'; - -interface StatisticsTableProps { - data: STATISTICS.OrderStatistics[]; - loading?: boolean; -} - -const StatisticsTable: React.FC = ({ data, loading }) => { - const columns: ProColumns[] = [ - { - title: '统计日期', - dataIndex: 'statisticsDate', - valueType: 'date', - }, - { - title: '景区名称', - dataIndex: 'tourismName', - }, - { - title: '设备编号', - dataIndex: 'deviceSn', - }, - { - title: '总订单数', - dataIndex: 'totalOrders', - }, - { - title: '已支付订单数', - dataIndex: 'paidOrders', - }, - { - title: '已完成订单数', - dataIndex: 'completedOrders', - }, - { - title: '已取消订单数', - dataIndex: 'canceledOrders', - }, - { - title: '总金额(元)', - dataIndex: 'totalAmount', - render: (val) => (val as number / 100).toFixed(2), - }, - { - title: '已支付金额(元)', - dataIndex: 'paidAmount', - render: (val) => (val as number / 100).toFixed(2), - }, - { - title: '退款金额(元)', - dataIndex: 'refundAmount', - render: (val) => (val as number / 100).toFixed(2), - }, - { - title: '平台分成(元)', - dataIndex: 'platformAmount', - render: (val) => (val as number / 100).toFixed(2), - }, - { - title: '景区分成(元)', - dataIndex: 'tourismAmount', - render: (val) => (val as number / 100).toFixed(2), - }, - ]; - - return ( - - columns={columns} - dataSource={data} - loading={loading} - search={false} - options={false} - pagination={false} - /> - ); -}; - -export default StatisticsTable; \ No newline at end of file diff --git a/zlt-web/react-web/src/main/frontend/src/pages/statistics/index.tsx b/zlt-web/react-web/src/main/frontend/src/pages/statistics/index.tsx deleted file mode 100644 index 964e277c..00000000 --- a/zlt-web/react-web/src/main/frontend/src/pages/statistics/index.tsx +++ /dev/null @@ -1,144 +0,0 @@ -import React, { useState, useEffect } from 'react'; -import { - PageContainer, - ProCard, - ProForm, - ProFormDateTimeRangePicker, - ProFormSelect, -} from '@ant-design/pro-components'; -import { Card, Tabs, message } from 'antd'; -import { Line, Column, Pie } from '@ant-design/plots'; -import { - generateStatistics, - getTimeStatistics, - getTourismStatistics, - getDeviceStatistics, -} from '@/services/statistics/api'; - -const Statistics: React.FC = () => { - const [timeData, setTimeData] = useState([]); - const [tourismData, setTourismData] = useState([]); - const [deviceData, setDeviceData] = useState([]); - const [loading, setLoading] = useState(false); - - // 获取统计数据 - const fetchStatistics = async (params: STATISTICS.StatisticsParams) => { - setLoading(true); - try { - // 生成统计数据 - await generateStatistics(params); - - // 获取各维度统计数据 - const [timeRes, tourismRes, deviceRes] = await Promise.all([ - getTimeStatistics(params), - getTourismStatistics(params), - getDeviceStatistics(params), - ]); - - if (timeRes.resp_code === 0) setTimeData(timeRes.data); - if (tourismRes.resp_code === 0) setTourismData(tourismRes.data); - if (deviceRes.resp_code === 0) setDeviceData(deviceRes.data); - } catch (error) { - message.error('获取统计数据失败'); - } finally { - setLoading(false); - } - }; - - // 时间维度图表配置 - const timeChartConfig = { - data: timeData, - xField: 'statisticsDate', - yField: 'totalAmount', - seriesField: 'type', - legend: { position: 'top' }, - }; - - // 景区维度图表配置 - const tourismChartConfig = { - data: tourismData.map(item => ({ - type: '订单总额', - value: item.totalAmount / 100, - tourism: item.tourismName, - })), - angleField: 'value', - colorField: 'tourism', - }; - - return ( - - - { - const [startTime, endTime] = values.timeRange || []; - await fetchStatistics({ - startTime, - endTime, - timeType: values.timeType, - }); - }} - > - - - - - - - - - ), - }, - { - key: 'tourism', - label: '景区维度统计', - children: ( - - - - ), - }, - { - key: 'device', - label: '设备维度统计', - children: ( - - - - ), - }, - ]} - /> - - ); -}; - -export default Statistics; \ No newline at end of file diff --git a/zlt-web/react-web/src/main/frontend/src/services/statistics/api.ts b/zlt-web/react-web/src/main/frontend/src/services/statistics/api.ts index f5d989da..2155bc08 100644 --- a/zlt-web/react-web/src/main/frontend/src/services/statistics/api.ts +++ b/zlt-web/react-web/src/main/frontend/src/services/statistics/api.ts @@ -1,97 +1,43 @@ -import { request } from '@/utils/request'; -import moment from 'moment'; +import { request } from 'umi'; -/** 生成统计数据 */ -export async function generateStatistics(params: { - startTime: string; - endTime: string; -}) { - return request('/api-order/statistics/generate', { - method: 'POST', - data: params, - }); +/** 获取二维码列表参数 */ +interface QrcodeListParams { + page: number; + limit: number; } -/** 获取二维码维度统计数据 */ -export async function getQrcodeStatistics(params: { - startTime?: string; - endTime?: string; -}) { - const response = await request('/api-order/statistics/qrcode', { - method: 'GET', - params, - }); - return { - ...response, - data: processChartData(response.data || []), - }; -} - -/** 获取景区维度统计数据 */ -export async function getTourismStatistics(params: { - startTime?: string; - endTime?: string; -}) { - const response = await request('/api-order/statistics/tourism', { - method: 'GET', - params, - }); - return { - ...response, - data: processChartData(response.data || []), - }; -} - -/** 获取设备维度统计数据 */ -export async function getDeviceStatistics(params: { - startTime: string; - endTime: string; -}) { - return request('/api-order/statistics/device', { +/** 获取二维码列表 */ +export async function getQrcodeList(params: QrcodeListParams = { page: 1, limit: 100 }) { + return request('/api-order/qrcode', { method: 'GET', params, }); } -// 获取二维码时间维度统计数据 -export async function getQrcodeTimeStatistics(params: { +/** 时间维度类型 */ +type TimeType = 'hour' | 'day' | 'month'; + +/** 获取时间统计数据参数 */ +export interface TimeStatisticsParams { + /** 二维码ID */ qrcodeId: string; + /** 开始时间 (格式:yyyy-MM-dd HH:mm:ss) */ startTime: string; + /** 结束时间 (格式:yyyy-MM-dd HH:mm:ss) */ endTime: string; - timeType?: 'hour' | 'day' | 'month'; -}) { + /** 时间维度类型(hour/day/month) */ + timeType?: TimeType; +} + +/** 获取时间统计数据 */ +export async function getTimeStatistics(params: TimeStatisticsParams) { return request('/api-order/statistics/time', { method: 'GET', - params, + params: { + qrcodeId: params.qrcodeId, + startTime: params.startTime, + endTime: params.endTime, + timeType: params.timeType || 'day', + }, }); -} - -// 获取时间维度统计数据 -export async function getTimeStatistics(params: { - qrcodeId: string; - startTime: string; - endTime: string; - timeType: 'hour' | 'day' | 'month'; -}) { - return request('/api-order/statistics/time', { - method: 'GET', - params, - }); -} - -// 获取二维码列表 -export async function getQrcodeList() { - return request('/api-order/qrcode/list', { - method: 'GET', - }); -} - -// 处理图表数据的辅助函数 -const processChartData = (data: any[]) => { - return data.map(item => ({ - ...item, - date: item.statisticsTime || moment().format('YYYY-MM-DD'), - value: item.amount || 0, - count: item.count || 0, - })); -}; \ No newline at end of file +} \ No newline at end of file diff --git a/zlt-web/react-web/src/main/frontend/src/services/statistics/typings.d.ts b/zlt-web/react-web/src/main/frontend/src/services/statistics/typings.d.ts deleted file mode 100644 index 378a6825..00000000 --- a/zlt-web/react-web/src/main/frontend/src/services/statistics/typings.d.ts +++ /dev/null @@ -1,37 +0,0 @@ -declare namespace STATISTICS { - interface OrderStatistics { - id: number; - qrcodeId: string; - tourismId: number; - tourismName: string; - deviceSn: string; - tenantId: string; - - totalOrders: number; - paidOrders: number; - completedOrders: number; - canceledOrders: number; - - totalAmount: number; - paidAmount: number; - refundAmount: number; - - platformRate: number; - tourismRate: number; - platformAmount: number; - tourismAmount: number; - - startTime: string; - endTime: string; - statisticsDate: string; - statisticsHour: number; - createTime: string; - } - - interface StatisticsParams { - qrcodeId: string; - startTime: string; - endTime: string; - timeType: 'hour' | 'day' | 'month'; - } -} \ No newline at end of file diff --git a/zlt-web/react-web/src/main/frontend/src/utils/export.ts b/zlt-web/react-web/src/main/frontend/src/utils/export.ts new file mode 100644 index 00000000..aff22989 --- /dev/null +++ b/zlt-web/react-web/src/main/frontend/src/utils/export.ts @@ -0,0 +1,43 @@ +import { saveAs } from 'file-saver'; +import * as XLSX from 'xlsx'; + +interface ExportExcelParams { + data: any[]; + header: { + title: string; + dataIndex: string; + }[]; + fileName: string; +} + +export const exportExcel = ({ data, header, fileName }: ExportExcelParams) => { + try { + // 转换数据格式 + const excelData = data.map(item => { + const row: any = {}; + header.forEach(h => { + row[h.title] = item[h.dataIndex]; + }); + return row; + }); + + // 创建工作簿 + const wb = XLSX.utils.book_new(); + // 创建工作表 + const ws = XLSX.utils.json_to_sheet(excelData, { + header: header.map(h => h.title), + }); + + // 将工作表添加到工作簿 + XLSX.utils.book_append_sheet(wb, ws, 'Sheet1'); + + // 生成excel文件 + const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' }); + const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }); + + // 下载文件 + saveAs(blob, `${fileName}.xlsx`); + } catch (error) { + console.error('导出Excel失败:', error); + } +}; \ No newline at end of file