From b19f6d60f9aecf2e2986f13f8eefaad994492318 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E8=9F=91=E8=9E=82?= Date: Mon, 1 Jun 2026 15:45:31 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E8=AE=A2=E5=8D=95=E7=BB=9F=E8=AE=A1):=20?= =?UTF-8?q?=E8=90=BD=E5=9C=B0=E8=AF=BB=E6=A8=A1=E5=9E=8B=E6=B1=87=E6=80=BB?= =?UTF-8?q?=E8=A1=A8=E4=B8=8E=20refresh=20=E5=86=99=E5=85=A5=E9=93=BE?= =?UTF-8?q?=E8=B7=AF=EF=BC=8C=E5=B7=A5=E4=BD=9C=E5=8F=B0/=E6=A6=82?= =?UTF-8?q?=E8=A7=88/=E5=AF=BC=E5=87=BA=E5=88=87=E8=AF=BB=20daily=20?= =?UTF-8?q?=E6=B1=87=E6=80=BB=E5=B9=B6=E8=A1=A5=E5=85=85=20Admin=20rebuild?= =?UTF-8?q?=20=E4=B8=8E=E5=AF=B9=E8=B4=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../docs/订单统计读模型实施计划.md | 166 ++++++ ecom-dmb-backend/sql/ec_order_stat_design.sql | 522 ++++++++++++++++++ .../V20260606__ec_order_stat_agg_tables.sql | 367 ++++++++++++ .../EComDMBBackendApplication.java | 2 + .../service/impl/BrushOrderServiceImpl.java | 11 +- .../service/impl/ImportRuntimeContext.java | 35 ++ .../impl/ImportTaskProcessorServiceImpl.java | 67 ++- .../service/impl/OrderImportProcessor.java | 12 + .../ecom/order/mapper/OrderMapper.java | 41 ++ .../order/service/impl/OrderServiceImpl.java | 42 +- .../stat/config/OrderStatProperties.java | 46 ++ .../controller/OrderStatAdminController.java | 61 ++ .../stat/job/OrderStatNightlyRebuildJob.java | 64 +++ .../order/stat/mapper/FeeStatDailyMapper.java | 64 +++ .../stat/mapper/OrderStatDailyMapper.java | 55 ++ .../stat/mapper/OrderStatQueryMapper.java | 98 ++++ .../mapper/OrderStatRebuildTaskMapper.java | 9 + .../stat/mapper/OrderStatRefreshMapper.java | 60 ++ .../stat/model/OrderShopStatDateRow.java | 12 + .../stat/model/dto/OrderStatMetricsDTO.java | 39 ++ .../model/dto/OrderStatRebuildRequestDTO.java | 27 + .../dto/OrderStatReconcileRequestDTO.java | 24 + .../model/po/OrderStatDailyProductPO.java | 62 +++ .../stat/model/po/OrderStatDailyShopPO.java | 65 +++ .../stat/model/po/OrderStatDailySpecPO.java | 65 +++ .../stat/model/po/OrderStatRebuildTaskPO.java | 49 ++ .../model/po/OrderStatRefreshQueuePO.java | 43 ++ .../model/po/PromotionFeeStatDailyPO.java | 44 ++ .../stat/service/FeeStatCrudCoordinator.java | 102 ++++ .../stat/service/FeeStatRefreshService.java | 69 +++ .../stat/service/OrderStatCacheService.java | 91 +++ .../service/OrderStatCrudCoordinator.java | 128 +++++ .../service/OrderStatOverviewAssembler.java | 195 +++++++ .../stat/service/OrderStatQueryService.java | 192 +++++++ .../stat/service/OrderStatReadFacade.java | 322 +++++++++++ .../stat/service/OrderStatRebuildService.java | 114 ++++ .../service/OrderStatReconcileService.java | 177 ++++++ .../service/OrderStatRefreshCoordinator.java | 97 ++++ .../stat/service/OrderStatRefreshService.java | 233 ++++++++ .../stat/service/OrderStatRefreshWorker.java | 91 +++ .../stat/service/OrderStatRollupService.java | 30 + .../stat/support/OrderStatParamHelper.java | 48 ++ .../order/stat/support/RefreshSource.java | 13 + .../ecom/order/stat/support/StatDirtyKey.java | 16 + .../service/impl/OrderStatusServiceImpl.java | 63 ++- .../support/OrderStatusStatResolver.java | 3 +- .../impl/CompanyOverviewServiceImpl.java | 21 +- .../ShopOverviewStatisticsServiceImpl.java | 177 +++++- .../impl/ProductOverviewServiceImpl.java | 228 +++++++- .../service/impl/ProductSpecServiceImpl.java | 24 +- .../service/impl/PromotionFeeServiceImpl.java | 22 +- .../impl/WorkbenchExportServiceImpl.java | 93 +--- .../service/impl/WorkbenchServiceImpl.java | 61 +- .../src/main/resources/application.yml | 15 + .../mapper/order/stat/FeeStatDailyMapper.xml | 94 ++++ .../order/stat/OrderStatDailyMapper.xml | 230 ++++++++ .../order/stat/OrderStatQueryMapper.xml | 284 ++++++++++ .../order/stat/OrderStatRefreshMapper.xml | 78 +++ 58 files changed, 5332 insertions(+), 131 deletions(-) create mode 100644 ecom-dmb-backend/docs/订单统计读模型实施计划.md create mode 100644 ecom-dmb-backend/sql/ec_order_stat_design.sql create mode 100644 ecom-dmb-backend/sql/migration/V20260606__ec_order_stat_agg_tables.sql create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/config/OrderStatProperties.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/controller/OrderStatAdminController.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/job/OrderStatNightlyRebuildJob.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/mapper/FeeStatDailyMapper.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/mapper/OrderStatDailyMapper.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/mapper/OrderStatQueryMapper.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/mapper/OrderStatRebuildTaskMapper.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/mapper/OrderStatRefreshMapper.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/OrderShopStatDateRow.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/dto/OrderStatMetricsDTO.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/dto/OrderStatRebuildRequestDTO.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/dto/OrderStatReconcileRequestDTO.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/OrderStatDailyProductPO.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/OrderStatDailyShopPO.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/OrderStatDailySpecPO.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/OrderStatRebuildTaskPO.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/OrderStatRefreshQueuePO.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/PromotionFeeStatDailyPO.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/FeeStatCrudCoordinator.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/FeeStatRefreshService.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatCacheService.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatCrudCoordinator.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatOverviewAssembler.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatQueryService.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatReadFacade.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatRebuildService.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatReconcileService.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatRefreshCoordinator.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatRefreshService.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatRefreshWorker.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatRollupService.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/support/OrderStatParamHelper.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/support/RefreshSource.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/support/StatDirtyKey.java create mode 100644 ecom-dmb-backend/src/main/resources/mapper/order/stat/FeeStatDailyMapper.xml create mode 100644 ecom-dmb-backend/src/main/resources/mapper/order/stat/OrderStatDailyMapper.xml create mode 100644 ecom-dmb-backend/src/main/resources/mapper/order/stat/OrderStatQueryMapper.xml create mode 100644 ecom-dmb-backend/src/main/resources/mapper/order/stat/OrderStatRefreshMapper.xml diff --git a/ecom-dmb-backend/docs/订单统计读模型实施计划.md b/ecom-dmb-backend/docs/订单统计读模型实施计划.md new file mode 100644 index 00000000..8727abc9 --- /dev/null +++ b/ecom-dmb-backend/docs/订单统计读模型实施计划.md @@ -0,0 +1,166 @@ +# 订单统计读模型 — 完整实施计划 + +> **目的**:跨会话可续作;每完成一项将 `[ ]` 改为 `[x]`。 +> **DDL**:已执行 `sql/migration/V20260606__ec_order_stat_agg_tables.sql`(20 聚合表 + 2 任务表)。 +> **设计参考**:`docs/订单统计读模型方案.md`、`sql/ec_order_stat_design.sql` + +--- + +## 进度总览 + +| Phase | 名称 | 状态 | +|-------|------|------| +| A | 写入基础设施 | **已完成(首版)** | +| B | 导入链路改造 | **已完成(首版)** | +| C | 订单 CRUD 钩子 | **已完成** | +| D | 推广/刷单费聚合 | **已完成** | +| E | 历史 Backfill + Admin | **已完成** | +| F | 读路径 QueryService | **已完成** | +| G | 工作台/概览切读 | **已完成** | +| H | 状态配置 Rebuild | **已完成** | +| I | 缓存 + 对账 + 监控 | **已完成(首版)** | + +--- + +## Phase A — 写入基础设施 + +- [x] A1 `OrderStatProperties` + `application.yml` 配置项 +- [x] A2 PO:`OrderStatDailyShop/Product/SpecPO`、`OrderStatRefreshQueuePO` +- [x] A3 Mapper:`OrderStatDailyMapper`(upsert/delete/batch/rollup 月年) +- [x] A4 `OrderStatRefreshMapper` — 规格日聚合 SQL + `countGmvOrdersByShopDay` +- [x] A5 `OrderStatRefreshService#refreshShopDay`(日表 shop/product/spec) +- [x] A6 `OrderStatRollupService`(日→月→年) +- [x] A7 `OrderStatRefreshCoordinator`(入队、去重) +- [x] A8 `OrderStatRefreshWorker`(独立线程池轮询 queue 表) +- [ ] A9 单测:refresh 口径 vs `OrderStatAggMapper` 抽样 + +--- + +## Phase B — 导入链路改造 + +- [x] B1 `ImportRuntimeContext` — `dirtyStatDates` + `markOrderStatDirty` +- [x] B2 `OrderImportProcessor` — 解析/更新时 mark dirty +- [x] B3 `OrderMapper#selectDistinctOrderDatesByImportTaskId` +- [x] B4 `ImportTaskProcessorServiceImpl` — 导入成功后 `enqueueRefresh` +- [ ] B5 可选:`ec_import_tasks.stat_refresh_status` 字段 + migration +- [ ] B6 集成测试:导入小 CSV → queue → daily 表有数据 + +--- + +## Phase C — 订单 CRUD 钩子 + +- [x] C1 `OrderServiceImpl#createOrder` — 同步 refresh 当日 +- [x] C2 `OrderServiceImpl#updateOrder` — 新旧 shop/date refresh +- [x] C3 `OrderServiceImpl#deleteOrder(s)` — 删除前记录维度后 refresh +- [x] C4 `ProductSpecServiceImpl#relinkOrphanOrdersBySpecCode` 调用方 enqueue + +--- + +## Phase D — 推广/刷单费聚合 + +- [x] D1 `FeeStatRefreshService` — daily/monthly/yearly +- [x] D2 推广费导入完成钩子(`ImportTaskProcessorServiceImpl`) +- [x] D3 推广费/刷单 CRUD 钩子(`FeeStatCrudCoordinator`) +- [x] D4 读缓存失效(`OrderStatCacheService.invalidateCompanyShopRange`) + +--- + +## Phase E — 历史 Backfill + Admin + +- [x] E1 `OrderStatRebuildService#scheduleRebuild` +- [x] E2 `OrderStatAdminController` — POST rebuild / GET 进度 +- [x] E3 夜间全公司灌数(`OrderStatNightlyRebuildJob`,默认关闭) +- [x] E4 断点续跑 `ec_order_stat_rebuild_task.progress_date` + +--- + +## Phase F — 读路径 QueryService + +- [x] F1 `OrderStatQueryService` — 粒度路由(≤90 日 / ≤1095 日 / 更长) +- [x] F2 `sumShopMetrics` / `sumByDay` / `sumByShop` / `sumByCategory` / `sumByProduct` / `sumBySpec` +- [x] F3 `ensureStatReady` + `auto-refresh-on-miss` +- [x] F4 Feature flag `order-stat.stat-source: daily | order`(`OrderStatReadFacade` 统一路由) + +--- + +## Phase G — 工作台/概览切读 + +- [x] G1 `WorkbenchServiceImpl` → `OrderStatReadFacade` +- [x] G2 `CompanyOverviewServiceImpl` → `OrderStatOverviewAssembler` +- [x] G3 `ShopOverviewStatisticsServiceImpl` 汇总表读路径 +- [x] G4 `ProductOverviewServiceImpl` 汇总表读路径(含 spec) +- [x] G5 `WorkbenchExportServiceImpl` 删 `loadOrders`,走 `buildWorkbenchSummaryTablesFromAgg` +- [x] G6 店铺/公司 export 随概览受益 + +--- + +## Phase H — 状态配置 Rebuild + +- [ ] H1 `OrderStatusStatResolver#evictCache`(Resolver 无缓存,暂不需要) +- [x] H2 `OrderStatusServiceImpl` — 五维开关变更检测 → `scheduleRebuild` +- [x] H3 RebuildWorker 按 shop×date 串行 refresh(`OrderStatRebuildService`) +- [x] H4 管理端 rebuild 进度展示(`GET /ec/admin/order-stat/rebuild/{taskId}`) + +--- + +## Phase I — 缓存 + 对账 + 监控 + +- [x] I1 `OrderStatCacheService` — Redis TTL + invalidate +- [x] I2 对账 API `POST /ec/admin/order-stat/reconcile`(抽样 100 shop×date) +- [ ] I3 指标:refresh 队列深度、查询 P95、reconcile.diff(待接入监控系统) +- [ ] I4 稳定 2 周后移除 `stat-source=order` 回退 + +--- + +## 包结构(目标) + +``` +modules/ecom/order/stat/ +├── config/OrderStatProperties.java +├── model/po/ | model/dto/ +├── mapper/ +├── service/ +│ ├── OrderStatRefreshService.java +│ ├── OrderStatRollupService.java +│ ├── OrderStatRefreshCoordinator.java +│ ├── OrderStatRefreshWorker.java +│ ├── OrderStatRebuildService.java +│ ├── OrderStatQueryService.java +│ ├── OrderStatReadFacade.java # 读路径统一门面 +│ ├── OrderStatOverviewAssembler.java # 概览 VO 组装 +│ ├── FeeStatRefreshService.java +│ ├── FeeStatCrudCoordinator.java +│ └── OrderStatCacheService.java +├── job/OrderStatNightlyRebuildJob.java +└── controller/OrderStatAdminController.java +``` + +--- + +## 关键设计约束(不可违背) + +1. **导入主路径不在每批 flush 写汇总** — 仅任务成功后 enqueue。 +2. **RefreshWorker 与 ImportConsumer 线程池隔离** — 各 2~4 / 3 线程。 +3. **同一 (company, shop, date) 串行** — queue 去重。 +4. **日表是唯一从 ec_order 重算的层** — 月/年仅 rollup。 +5. **状态五维配置变更 → 全公司 rebuild** — 不可增量 patch 历史。 +6. **读路径切换前必须 backfill + 对账通过**。 + +--- + +## 上线检查清单 + +1. `POST /ec/admin/order-stat/rebuild` 对目标公司全量灌数 +2. `POST /ec/admin/order-stat/reconcile` 抽样对账通过 +3. 确认 `order-stat.stat-source: daily`(已默认) +4. 按需开启 `order-stat.nightly-rebuild-enabled: true` + +--- + +## 当前会话记录 + +| 日期 | 完成项 | 备注 | +|------|--------|------| +| 2026-05-28 | DDL 20 表已建 | ecom_dmb_dev | +| 2026-05-28 | Phase A~I 首版代码 | ReadFacade + 全读路径切汇总表 | +| 2026-05-28 | Admin reconcile + nightly job | nightly 默认关闭 | diff --git a/ecom-dmb-backend/sql/ec_order_stat_design.sql b/ecom-dmb-backend/sql/ec_order_stat_design.sql new file mode 100644 index 00000000..2f171216 --- /dev/null +++ b/ecom-dmb-backend/sql/ec_order_stat_design.sql @@ -0,0 +1,522 @@ +-- ============================================================================= +-- 订单统计读模型:日 / 月 / 年 聚合表设计 +-- ============================================================================= +-- 目标:支撑 1 天~5 年(1825 天)区间查询与导出,避免在线扫 ec_order 明细。 +-- 口径:与 OrderStatusStatSets + OrderStatAggMapper 一致(五维度 + GMV + 件数)。 +-- 写入:ec_order 变更 / 导入完成后,按 (company, shop, stat_date) 重算日表,再 rollup 月/年。 +-- 详细方案见:docs/订单统计读模型方案.md +-- +-- 【读路径路由建议】 +-- ≤ 90 天 → 日表(趋势、KPI、四维汇总) +-- 91~1095 天 → 店铺/平台 KPI、趋势按月:月表;商品/品类明细:月表 +-- > 3 年 或整年对比 → 年表(KPI/平台);商品 TopN 仍走月表 +-- 推广费/刷单 → ec_promotion_fee_stat_* / ec_brush_fee_stat_*(小表,与日表同策略) +-- +-- 【容量估算 · 单公司 · 50 店 · 5000 SKU · 日 10 万单】 +-- daily_shop 50 × 1825 ≈ 9.1 万行/5年 +-- daily_product 活跃维度 × 1825(全量 SKU 约数百万,按店×品×日) +-- monthly_shop 50 × 60 ≈ 3 千行/5年 +-- yearly_shop 50 × 5 ≈ 250 行/5年 +-- 5 年全店 KPI 读 yearly_shop:1 条 SUM,毫秒级 +-- ============================================================================= + + +-- ----------------------------------------------------------------------------- +-- 一、公共指标列说明(日 / 月 / 年 三张同维度表字段一致,仅时间键不同) +-- ----------------------------------------------------------------------------- +-- sales_amount 计入销售额的 received_amount 合计(salesStatusIds) +-- refund_amount 计入退款的 received_amount 合计(refundStatusIds) +-- sales_order_count 计入销售额的订单笔数 +-- product_cost 商品成本 × qty(productCostStatusIds) +-- freight_cost 运费成本 × qty(freightCostStatusIds) +-- other_cost 其他成本 × qty(otherCostStatusIds) +-- gmv_amount 全状态 received_amount 合计(仅 shop / spec 层需要 GMV 时保留) +-- gmv_order_count 全状态订单笔数(仅 shop 层) +-- quantity_sum 销量件数合计(spec 层;qty = IFNULL(NULLIF(quantity,0),1)) +-- stat_version 重算批次号,状态配置 rebuild 时递增,便于排查 +-- ----------------------------------------------------------------------------- + + +-- ============================================================================= +-- 二、店铺维度(KPI / 趋势 / 店铺表 / 平台 rollup 主读表) +-- ============================================================================= + +DROP TABLE IF EXISTS `ec_order_stat_daily_shop`; +CREATE TABLE `ec_order_stat_daily_shop` ( + `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键', + `company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID', + `shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID', + `platform_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '平台ID(写入时快照 ec_shop.platform_id)', + `stat_date` date NOT NULL COMMENT '自然日(Asia/Shanghai,与 order_time 的 DATE 一致)', + + `sales_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '销售额', + `refund_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额', + `sales_order_count` int NOT NULL DEFAULT 0 COMMENT '销售单量', + `product_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '商品成本', + `freight_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '运费成本', + `other_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '其他成本', + `gmv_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT 'GMV(全状态商家实收)', + `gmv_order_count` int NOT NULL DEFAULT 0 COMMENT 'GMV 订单笔数', + + `stat_version` int NOT NULL DEFAULT 0 COMMENT '重算版本号', + `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `uk_company_shop_date` (`company_id`, `shop_id`, `stat_date`) USING BTREE, + INDEX `idx_company_date` (`company_id`, `stat_date`) USING BTREE, + INDEX `idx_company_platform_date` (`company_id`, `platform_id`, `stat_date`) USING BTREE, + INDEX `idx_shop_date` (`shop_id`, `stat_date`) USING BTREE, + CONSTRAINT `fk_oss_daily_shop_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_oss_daily_shop_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '订单统计-店铺-日汇总'; + + +DROP TABLE IF EXISTS `ec_order_stat_monthly_shop`; +CREATE TABLE `ec_order_stat_monthly_shop` ( + `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键', + `company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID', + `shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID', + `platform_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '平台ID(月 rollup 时取当月最后写入快照)', + `stat_month` date NOT NULL COMMENT '自然月首日,如 2024-03-01', + + `sales_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '销售额', + `refund_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额', + `sales_order_count` int NOT NULL DEFAULT 0 COMMENT '销售单量', + `product_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '商品成本', + `freight_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '运费成本', + `other_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '其他成本', + `gmv_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT 'GMV', + `gmv_order_count` int NOT NULL DEFAULT 0 COMMENT 'GMV 订单笔数', + + `stat_version` int NOT NULL DEFAULT 0 COMMENT '重算版本号', + `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `uk_company_shop_month` (`company_id`, `shop_id`, `stat_month`) USING BTREE, + INDEX `idx_company_month` (`company_id`, `stat_month`) USING BTREE, + INDEX `idx_company_platform_month` (`company_id`, `platform_id`, `stat_month`) USING BTREE, + CONSTRAINT `fk_oss_monthly_shop_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_oss_monthly_shop_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '订单统计-店铺-月汇总(由日表 SUM 或订单直算)'; + + +DROP TABLE IF EXISTS `ec_order_stat_yearly_shop`; +CREATE TABLE `ec_order_stat_yearly_shop` ( + `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键', + `company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID', + `shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID', + `platform_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '平台ID', + `stat_year` smallint NOT NULL COMMENT '自然年,如 2024', + + `sales_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '销售额', + `refund_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额', + `sales_order_count` int NOT NULL DEFAULT 0 COMMENT '销售单量', + `product_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '商品成本', + `freight_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '运费成本', + `other_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '其他成本', + `gmv_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT 'GMV', + `gmv_order_count` int NOT NULL DEFAULT 0 COMMENT 'GMV 订单笔数', + + `stat_version` int NOT NULL DEFAULT 0 COMMENT '重算版本号', + `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `uk_company_shop_year` (`company_id`, `shop_id`, `stat_year`) USING BTREE, + INDEX `idx_company_year` (`company_id`, `stat_year`) USING BTREE, + INDEX `idx_company_platform_year` (`company_id`, `platform_id`, `stat_year`) USING BTREE, + CONSTRAINT `fk_oss_yearly_shop_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_oss_yearly_shop_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '订单统计-店铺-年汇总(3~5 年 KPI / 平台占比主读表)'; + + +-- ============================================================================= +-- 三、商品维度(品类 / 商品 / 排行 / 工作台底表) +-- product_id = 0 表示未匹配商品;category_id 为订单写入时快照,商品改类目不回算历史 +-- ============================================================================= + +DROP TABLE IF EXISTS `ec_order_stat_daily_product`; +CREATE TABLE `ec_order_stat_daily_product` ( + `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键', + `company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID', + `shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID', + `product_id` bigint NOT NULL DEFAULT 0 COMMENT '商品ID,0=未匹配', + `category_id` bigint NOT NULL DEFAULT 0 COMMENT '品类ID,0=未分类', + `stat_date` date NOT NULL COMMENT '自然日', + + `sales_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '销售额', + `refund_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额', + `sales_order_count` int NOT NULL DEFAULT 0 COMMENT '销售单量', + `product_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '商品成本', + `freight_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '运费成本', + `other_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '其他成本', + + `stat_version` int NOT NULL DEFAULT 0 COMMENT '重算版本号', + `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `uk_company_shop_prod_cat_date` (`company_id`, `shop_id`, `product_id`, `category_id`, `stat_date`) USING BTREE, + INDEX `idx_company_date` (`company_id`, `stat_date`) USING BTREE, + INDEX `idx_company_cat_date` (`company_id`, `category_id`, `stat_date`) USING BTREE, + INDEX `idx_company_prod_date` (`company_id`, `product_id`, `stat_date`) USING BTREE, + INDEX `idx_shop_prod_date` (`shop_id`, `product_id`, `stat_date`) USING BTREE, + CONSTRAINT `fk_oss_daily_product_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_oss_daily_product_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '订单统计-商品-日汇总'; + + +DROP TABLE IF EXISTS `ec_order_stat_monthly_product`; +CREATE TABLE `ec_order_stat_monthly_product` ( + `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键', + `company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID', + `shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID', + `product_id` bigint NOT NULL DEFAULT 0 COMMENT '商品ID', + `category_id` bigint NOT NULL DEFAULT 0 COMMENT '品类ID', + `stat_month` date NOT NULL COMMENT '自然月首日', + + `sales_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '销售额', + `refund_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额', + `sales_order_count` int NOT NULL DEFAULT 0 COMMENT '销售单量', + `product_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '商品成本', + `freight_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '运费成本', + `other_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '其他成本', + + `stat_version` int NOT NULL DEFAULT 0 COMMENT '重算版本号', + `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `uk_company_shop_prod_cat_month` (`company_id`, `shop_id`, `product_id`, `category_id`, `stat_month`) USING BTREE, + INDEX `idx_company_month` (`company_id`, `stat_month`) USING BTREE, + INDEX `idx_company_cat_month` (`company_id`, `category_id`, `stat_month`) USING BTREE, + INDEX `idx_company_prod_month` (`company_id`, `product_id`, `stat_month`) USING BTREE, + CONSTRAINT `fk_oss_monthly_product_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_oss_monthly_product_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '订单统计-商品-月汇总(跨月~3年品类/商品明细主读表)'; + + +DROP TABLE IF EXISTS `ec_order_stat_yearly_product`; +CREATE TABLE `ec_order_stat_yearly_product` ( + `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键', + `company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID', + `shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID', + `product_id` bigint NOT NULL DEFAULT 0 COMMENT '商品ID', + `category_id` bigint NOT NULL DEFAULT 0 COMMENT '品类ID', + `stat_year` smallint NOT NULL COMMENT '自然年', + + `sales_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '销售额', + `refund_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额', + `sales_order_count` int NOT NULL DEFAULT 0 COMMENT '销售单量', + `product_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '商品成本', + `freight_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '运费成本', + `other_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '其他成本', + + `stat_version` int NOT NULL DEFAULT 0 COMMENT '重算版本号', + `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `uk_company_shop_prod_cat_year` (`company_id`, `shop_id`, `product_id`, `category_id`, `stat_year`) USING BTREE, + INDEX `idx_company_year` (`company_id`, `stat_year`) USING BTREE, + INDEX `idx_company_cat_year` (`company_id`, `category_id`, `stat_year`) USING BTREE, + INDEX `idx_company_prod_year` (`company_id`, `product_id`, `stat_year`) USING BTREE, + CONSTRAINT `fk_oss_yearly_product_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_oss_yearly_product_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '订单统计-商品-年汇总(3~5 年商品/品类排行)'; + + +-- ============================================================================= +-- 四、规格维度(商品概览 spec 块专用) +-- ============================================================================= + +DROP TABLE IF EXISTS `ec_order_stat_daily_spec`; +CREATE TABLE `ec_order_stat_daily_spec` ( + `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键', + `company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID', + `shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID', + `product_id` bigint UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品ID', + `product_spec_id` bigint UNSIGNED NOT NULL DEFAULT 0 COMMENT '规格ID,0=未绑定', + `stat_date` date NOT NULL COMMENT '自然日', + + `sales_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '销售额', + `refund_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额', + `sales_order_count` int NOT NULL DEFAULT 0 COMMENT '销售单量', + `quantity_sum` int NOT NULL DEFAULT 0 COMMENT '销量件数合计', + `product_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '商品成本', + `freight_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '运费成本', + `other_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '其他成本', + + `stat_version` int NOT NULL DEFAULT 0 COMMENT '重算版本号', + `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `uk_company_shop_spec_date` (`company_id`, `shop_id`, `product_spec_id`, `stat_date`) USING BTREE, + INDEX `idx_company_prod_date` (`company_id`, `product_id`, `stat_date`) USING BTREE, + INDEX `idx_company_date` (`company_id`, `stat_date`) USING BTREE, + CONSTRAINT `fk_oss_daily_spec_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_oss_daily_spec_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '订单统计-规格-日汇总'; + + +DROP TABLE IF EXISTS `ec_order_stat_monthly_spec`; +CREATE TABLE `ec_order_stat_monthly_spec` ( + `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键', + `company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID', + `shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID', + `product_id` bigint UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品ID', + `product_spec_id` bigint UNSIGNED NOT NULL DEFAULT 0 COMMENT '规格ID', + `stat_month` date NOT NULL COMMENT '自然月首日', + + `sales_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '销售额', + `refund_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额', + `sales_order_count` int NOT NULL DEFAULT 0 COMMENT '销售单量', + `quantity_sum` int NOT NULL DEFAULT 0 COMMENT '销量件数合计', + `product_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '商品成本', + `freight_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '运费成本', + `other_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '其他成本', + + `stat_version` int NOT NULL DEFAULT 0 COMMENT '重算版本号', + `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `uk_company_shop_spec_month` (`company_id`, `shop_id`, `product_spec_id`, `stat_month`) USING BTREE, + INDEX `idx_company_prod_month` (`company_id`, `product_id`, `stat_month`) USING BTREE, + CONSTRAINT `fk_oss_monthly_spec_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_oss_monthly_spec_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '订单统计-规格-月汇总'; + + +DROP TABLE IF EXISTS `ec_order_stat_yearly_spec`; +CREATE TABLE `ec_order_stat_yearly_spec` ( + `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键', + `company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID', + `shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID', + `product_id` bigint UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品ID', + `product_spec_id` bigint UNSIGNED NOT NULL DEFAULT 0 COMMENT '规格ID', + `stat_year` smallint NOT NULL COMMENT '自然年', + + `sales_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '销售额', + `refund_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额', + `sales_order_count` int NOT NULL DEFAULT 0 COMMENT '销售单量', + `quantity_sum` int NOT NULL DEFAULT 0 COMMENT '销量件数合计', + `product_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '商品成本', + `freight_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '运费成本', + `other_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '其他成本', + + `stat_version` int NOT NULL DEFAULT 0 COMMENT '重算版本号', + `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `uk_company_shop_spec_year` (`company_id`, `shop_id`, `product_spec_id`, `stat_year`) USING BTREE, + INDEX `idx_company_prod_year` (`company_id`, `product_id`, `stat_year`) USING BTREE, + CONSTRAINT `fk_oss_yearly_spec_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_oss_yearly_spec_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '订单统计-规格-年汇总'; + + +-- ============================================================================= +-- 五、推广费 / 刷单费 聚合(跨年区间 SUM 推广/刷单小表仍可能扫大量行,预聚合更稳) +-- 粒度与 ec_promotion_fee 一致:shop + 可选 product_id / category_id +-- ============================================================================= + +DROP TABLE IF EXISTS `ec_promotion_fee_stat_daily`; +CREATE TABLE `ec_promotion_fee_stat_daily` ( + `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键', + `company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID', + `shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID', + `product_id` bigint UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品ID,0=非商品级', + `category_id` bigint UNSIGNED NOT NULL DEFAULT 0 COMMENT '品类ID,0=非品类级', + `stat_date` date NOT NULL COMMENT '自然日(fee_date)', + + `fee_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '推广费合计', + + `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `uk_company_shop_dims_date` (`company_id`, `shop_id`, `product_id`, `category_id`, `stat_date`) USING BTREE, + INDEX `idx_company_date` (`company_id`, `stat_date`) USING BTREE, + CONSTRAINT `fk_pfs_daily_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_pfs_daily_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '推广费-日汇总'; + + +DROP TABLE IF EXISTS `ec_promotion_fee_stat_monthly`; +CREATE TABLE `ec_promotion_fee_stat_monthly` ( + `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键', + `company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID', + `shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID', + `product_id` bigint UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品ID,0=非商品级', + `category_id` bigint UNSIGNED NOT NULL DEFAULT 0 COMMENT '品类ID,0=非品类级', + `stat_month` date NOT NULL COMMENT '自然月首日', + + `fee_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '推广费合计', + + `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `uk_company_shop_dims_month` (`company_id`, `shop_id`, `product_id`, `category_id`, `stat_month`) USING BTREE, + INDEX `idx_company_month` (`company_id`, `stat_month`) USING BTREE, + CONSTRAINT `fk_pfs_monthly_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_pfs_monthly_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '推广费-月汇总'; + + +DROP TABLE IF EXISTS `ec_promotion_fee_stat_yearly`; +CREATE TABLE `ec_promotion_fee_stat_yearly` ( + `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键', + `company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID', + `shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID', + `product_id` bigint UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品ID,0=非商品级', + `category_id` bigint UNSIGNED NOT NULL DEFAULT 0 COMMENT '品类ID,0=非品类级', + `stat_year` smallint NOT NULL COMMENT '自然年', + + `fee_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '推广费合计', + + `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `uk_company_shop_dims_year` (`company_id`, `shop_id`, `product_id`, `category_id`, `stat_year`) USING BTREE, + INDEX `idx_company_year` (`company_id`, `stat_year`) USING BTREE, + CONSTRAINT `fk_pfs_yearly_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_pfs_yearly_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '推广费-年汇总'; + + +DROP TABLE IF EXISTS `ec_brush_fee_stat_daily`; +CREATE TABLE `ec_brush_fee_stat_daily` ( + `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键', + `company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID', + `shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID', + `stat_date` date NOT NULL COMMENT '自然日', + + `brush_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '刷单费合计', + + `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `uk_company_shop_date` (`company_id`, `shop_id`, `stat_date`) USING BTREE, + INDEX `idx_company_date` (`company_id`, `stat_date`) USING BTREE, + CONSTRAINT `fk_bfs_daily_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_bfs_daily_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '刷单费-日汇总'; + + +DROP TABLE IF EXISTS `ec_brush_fee_stat_monthly`; +CREATE TABLE `ec_brush_fee_stat_monthly` ( + `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键', + `company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID', + `shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID', + `stat_month` date NOT NULL COMMENT '自然月首日', + + `brush_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '刷单费合计', + + `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `uk_company_shop_month` (`company_id`, `shop_id`, `stat_month`) USING BTREE, + INDEX `idx_company_month` (`company_id`, `stat_month`) USING BTREE, + CONSTRAINT `fk_bfs_monthly_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_bfs_monthly_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '刷单费-月汇总'; + + +DROP TABLE IF EXISTS `ec_brush_fee_stat_yearly`; +CREATE TABLE `ec_brush_fee_stat_yearly` ( + `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键', + `company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID', + `shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID', + `stat_year` smallint NOT NULL COMMENT '自然年', + + `brush_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '刷单费合计', + + `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `uk_company_shop_year` (`company_id`, `shop_id`, `stat_year`) USING BTREE, + INDEX `idx_company_year` (`company_id`, `stat_year`) USING BTREE, + CONSTRAINT `fk_bfs_yearly_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_bfs_yearly_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '刷单费-年汇总'; + + +-- ============================================================================= +-- 六、刷新 / 重建任务(Backfill、导入后异步、状态配置变更全量 rebuild) +-- ============================================================================= + +DROP TABLE IF EXISTS `ec_order_stat_rebuild_task`; +CREATE TABLE `ec_order_stat_rebuild_task` ( + `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键', + `company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID', + `shop_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '店铺ID,NULL=全店', + `start_date` date NOT NULL COMMENT '重建起始日', + `end_date` date NOT NULL COMMENT '重建结束日', + `granularity` varchar(16) NOT NULL DEFAULT 'all' COMMENT 'daily/monthly/yearly/all', + `status` varchar(20) NOT NULL DEFAULT 'pending' COMMENT 'pending/running/done/failed', + `progress_date` date NULL DEFAULT NULL COMMENT '已处理到的日期(断点续跑)', + `error_message` text NULL COMMENT '失败原因', + `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + + PRIMARY KEY (`id`) USING BTREE, + INDEX `idx_company_status` (`company_id`, `status`) USING BTREE, + CONSTRAINT `fk_osrt_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '订单统计重建任务'; + + +DROP TABLE IF EXISTS `ec_order_stat_refresh_queue`; +CREATE TABLE `ec_order_stat_refresh_queue` ( + `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键', + `company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID', + `shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID', + `stat_date` date NOT NULL COMMENT '待刷新自然日', + `source` varchar(32) NOT NULL COMMENT 'import/crud/status_change/manual', + `status` varchar(20) NOT NULL DEFAULT 'pending' COMMENT 'pending/running/done/failed', + `retry_count` int NOT NULL DEFAULT 0 COMMENT '重试次数', + `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `uk_company_shop_date_pending` (`company_id`, `shop_id`, `stat_date`, `status`) USING BTREE, + INDEX `idx_status_ctime` (`status`, `create_time`) USING BTREE, + CONSTRAINT `fk_osrq_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_osrq_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '订单统计日汇总待刷新队列'; + + +-- ============================================================================= +-- 七、Rollup 示例(写入侧 Job 参考,不在应用启动时执行) +-- ============================================================================= +-- +-- 月表 ← 日表(店铺): +-- INSERT INTO ec_order_stat_monthly_shop (...) +-- SELECT company_id, shop_id, MAX(platform_id), +-- DATE_FORMAT(stat_date, '%Y-%m-01'), +-- SUM(sales_amount), SUM(refund_amount), SUM(sales_order_count), ... +-- FROM ec_order_stat_daily_shop +-- WHERE company_id=? AND shop_id=? AND stat_date BETWEEN ? AND ? +-- GROUP BY company_id, shop_id, DATE_FORMAT(stat_date, '%Y-%m-01') +-- ON DUPLICATE KEY UPDATE sales_amount=VALUES(sales_amount), ...; +-- +-- 年表 ← 月表(店铺): +-- INSERT INTO ec_order_stat_yearly_shop (...) +-- SELECT company_id, shop_id, MAX(platform_id), YEAR(stat_month), +-- SUM(sales_amount), ... +-- FROM ec_order_stat_monthly_shop +-- WHERE company_id=? AND stat_year BETWEEN ? AND ? +-- GROUP BY company_id, shop_id, YEAR(stat_month) +-- ON DUPLICATE KEY UPDATE ...; +-- +-- 单日 refresh 顺序:ec_order → daily_* → 触达 stat_month/stat_year 边界时 rollup 对应月/年行 +-- ============================================================================= diff --git a/ecom-dmb-backend/sql/migration/V20260606__ec_order_stat_agg_tables.sql b/ecom-dmb-backend/sql/migration/V20260606__ec_order_stat_agg_tables.sql new file mode 100644 index 00000000..5dc0be87 --- /dev/null +++ b/ecom-dmb-backend/sql/migration/V20260606__ec_order_stat_agg_tables.sql @@ -0,0 +1,367 @@ +-- ================================================ +-- 订单统计读模型:日 / 月 / 年 聚合表(含推广费/刷单费 + 刷新队列) +-- 设计说明见 sql/ec_order_stat_design.sql +-- ================================================ + +-- ---------- 店铺维度 ---------- + +CREATE TABLE IF NOT EXISTS `ec_order_stat_daily_shop` ( + `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键', + `company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID', + `shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID', + `platform_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '平台ID(写入时快照)', + `stat_date` date NOT NULL COMMENT '自然日', + `sales_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '销售额', + `refund_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额', + `sales_order_count` int NOT NULL DEFAULT 0 COMMENT '销售单量', + `product_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '商品成本', + `freight_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '运费成本', + `other_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '其他成本', + `gmv_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT 'GMV', + `gmv_order_count` int NOT NULL DEFAULT 0 COMMENT 'GMV 订单笔数', + `stat_version` int NOT NULL DEFAULT 0 COMMENT '重算版本号', + `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `uk_company_shop_date` (`company_id`, `shop_id`, `stat_date`) USING BTREE, + INDEX `idx_company_date` (`company_id`, `stat_date`) USING BTREE, + INDEX `idx_company_platform_date` (`company_id`, `platform_id`, `stat_date`) USING BTREE, + CONSTRAINT `fk_oss_daily_shop_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_oss_daily_shop_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '订单统计-店铺-日汇总'; + +CREATE TABLE IF NOT EXISTS `ec_order_stat_monthly_shop` ( + `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键', + `company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID', + `shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID', + `platform_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '平台ID', + `stat_month` date NOT NULL COMMENT '自然月首日', + `sales_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '销售额', + `refund_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额', + `sales_order_count` int NOT NULL DEFAULT 0 COMMENT '销售单量', + `product_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '商品成本', + `freight_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '运费成本', + `other_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '其他成本', + `gmv_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT 'GMV', + `gmv_order_count` int NOT NULL DEFAULT 0 COMMENT 'GMV 订单笔数', + `stat_version` int NOT NULL DEFAULT 0 COMMENT '重算版本号', + `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `uk_company_shop_month` (`company_id`, `shop_id`, `stat_month`) USING BTREE, + INDEX `idx_company_month` (`company_id`, `stat_month`) USING BTREE, + INDEX `idx_company_platform_month` (`company_id`, `platform_id`, `stat_month`) USING BTREE, + CONSTRAINT `fk_oss_monthly_shop_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_oss_monthly_shop_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '订单统计-店铺-月汇总'; + +CREATE TABLE IF NOT EXISTS `ec_order_stat_yearly_shop` ( + `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键', + `company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID', + `shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID', + `platform_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '平台ID', + `stat_year` smallint NOT NULL COMMENT '自然年', + `sales_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '销售额', + `refund_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额', + `sales_order_count` int NOT NULL DEFAULT 0 COMMENT '销售单量', + `product_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '商品成本', + `freight_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '运费成本', + `other_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '其他成本', + `gmv_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT 'GMV', + `gmv_order_count` int NOT NULL DEFAULT 0 COMMENT 'GMV 订单笔数', + `stat_version` int NOT NULL DEFAULT 0 COMMENT '重算版本号', + `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `uk_company_shop_year` (`company_id`, `shop_id`, `stat_year`) USING BTREE, + INDEX `idx_company_year` (`company_id`, `stat_year`) USING BTREE, + INDEX `idx_company_platform_year` (`company_id`, `platform_id`, `stat_year`) USING BTREE, + CONSTRAINT `fk_oss_yearly_shop_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_oss_yearly_shop_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '订单统计-店铺-年汇总'; + +-- ---------- 商品维度 ---------- + +CREATE TABLE IF NOT EXISTS `ec_order_stat_daily_product` ( + `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键', + `company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID', + `shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID', + `product_id` bigint NOT NULL DEFAULT 0 COMMENT '商品ID', + `category_id` bigint NOT NULL DEFAULT 0 COMMENT '品类ID', + `stat_date` date NOT NULL COMMENT '自然日', + `sales_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '销售额', + `refund_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额', + `sales_order_count` int NOT NULL DEFAULT 0 COMMENT '销售单量', + `product_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '商品成本', + `freight_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '运费成本', + `other_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '其他成本', + `stat_version` int NOT NULL DEFAULT 0 COMMENT '重算版本号', + `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `uk_company_shop_prod_cat_date` (`company_id`, `shop_id`, `product_id`, `category_id`, `stat_date`) USING BTREE, + INDEX `idx_company_date` (`company_id`, `stat_date`) USING BTREE, + INDEX `idx_company_cat_date` (`company_id`, `category_id`, `stat_date`) USING BTREE, + INDEX `idx_company_prod_date` (`company_id`, `product_id`, `stat_date`) USING BTREE, + CONSTRAINT `fk_oss_daily_product_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_oss_daily_product_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '订单统计-商品-日汇总'; + +CREATE TABLE IF NOT EXISTS `ec_order_stat_monthly_product` ( + `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键', + `company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID', + `shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID', + `product_id` bigint NOT NULL DEFAULT 0 COMMENT '商品ID', + `category_id` bigint NOT NULL DEFAULT 0 COMMENT '品类ID', + `stat_month` date NOT NULL COMMENT '自然月首日', + `sales_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '销售额', + `refund_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额', + `sales_order_count` int NOT NULL DEFAULT 0 COMMENT '销售单量', + `product_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '商品成本', + `freight_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '运费成本', + `other_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '其他成本', + `stat_version` int NOT NULL DEFAULT 0 COMMENT '重算版本号', + `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `uk_company_shop_prod_cat_month` (`company_id`, `shop_id`, `product_id`, `category_id`, `stat_month`) USING BTREE, + INDEX `idx_company_month` (`company_id`, `stat_month`) USING BTREE, + INDEX `idx_company_cat_month` (`company_id`, `category_id`, `stat_month`) USING BTREE, + INDEX `idx_company_prod_month` (`company_id`, `product_id`, `stat_month`) USING BTREE, + CONSTRAINT `fk_oss_monthly_product_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_oss_monthly_product_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '订单统计-商品-月汇总'; + +CREATE TABLE IF NOT EXISTS `ec_order_stat_yearly_product` ( + `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键', + `company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID', + `shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID', + `product_id` bigint NOT NULL DEFAULT 0 COMMENT '商品ID', + `category_id` bigint NOT NULL DEFAULT 0 COMMENT '品类ID', + `stat_year` smallint NOT NULL COMMENT '自然年', + `sales_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '销售额', + `refund_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额', + `sales_order_count` int NOT NULL DEFAULT 0 COMMENT '销售单量', + `product_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '商品成本', + `freight_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '运费成本', + `other_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '其他成本', + `stat_version` int NOT NULL DEFAULT 0 COMMENT '重算版本号', + `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `uk_company_shop_prod_cat_year` (`company_id`, `shop_id`, `product_id`, `category_id`, `stat_year`) USING BTREE, + INDEX `idx_company_year` (`company_id`, `stat_year`) USING BTREE, + INDEX `idx_company_cat_year` (`company_id`, `category_id`, `stat_year`) USING BTREE, + INDEX `idx_company_prod_year` (`company_id`, `product_id`, `stat_year`) USING BTREE, + CONSTRAINT `fk_oss_yearly_product_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_oss_yearly_product_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '订单统计-商品-年汇总'; + +-- ---------- 规格维度 ---------- + +CREATE TABLE IF NOT EXISTS `ec_order_stat_daily_spec` ( + `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键', + `company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID', + `shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID', + `product_id` bigint UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品ID', + `product_spec_id` bigint UNSIGNED NOT NULL DEFAULT 0 COMMENT '规格ID', + `stat_date` date NOT NULL COMMENT '自然日', + `sales_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '销售额', + `refund_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额', + `sales_order_count` int NOT NULL DEFAULT 0 COMMENT '销售单量', + `quantity_sum` int NOT NULL DEFAULT 0 COMMENT '销量件数', + `product_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '商品成本', + `freight_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '运费成本', + `other_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '其他成本', + `stat_version` int NOT NULL DEFAULT 0 COMMENT '重算版本号', + `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `uk_company_shop_spec_date` (`company_id`, `shop_id`, `product_spec_id`, `stat_date`) USING BTREE, + INDEX `idx_company_prod_date` (`company_id`, `product_id`, `stat_date`) USING BTREE, + INDEX `idx_company_date` (`company_id`, `stat_date`) USING BTREE, + CONSTRAINT `fk_oss_daily_spec_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_oss_daily_spec_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '订单统计-规格-日汇总'; + +CREATE TABLE IF NOT EXISTS `ec_order_stat_monthly_spec` ( + `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键', + `company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID', + `shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID', + `product_id` bigint UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品ID', + `product_spec_id` bigint UNSIGNED NOT NULL DEFAULT 0 COMMENT '规格ID', + `stat_month` date NOT NULL COMMENT '自然月首日', + `sales_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '销售额', + `refund_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额', + `sales_order_count` int NOT NULL DEFAULT 0 COMMENT '销售单量', + `quantity_sum` int NOT NULL DEFAULT 0 COMMENT '销量件数', + `product_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '商品成本', + `freight_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '运费成本', + `other_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '其他成本', + `stat_version` int NOT NULL DEFAULT 0 COMMENT '重算版本号', + `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `uk_company_shop_spec_month` (`company_id`, `shop_id`, `product_spec_id`, `stat_month`) USING BTREE, + INDEX `idx_company_prod_month` (`company_id`, `product_id`, `stat_month`) USING BTREE, + CONSTRAINT `fk_oss_monthly_spec_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_oss_monthly_spec_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '订单统计-规格-月汇总'; + +CREATE TABLE IF NOT EXISTS `ec_order_stat_yearly_spec` ( + `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键', + `company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID', + `shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID', + `product_id` bigint UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品ID', + `product_spec_id` bigint UNSIGNED NOT NULL DEFAULT 0 COMMENT '规格ID', + `stat_year` smallint NOT NULL COMMENT '自然年', + `sales_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '销售额', + `refund_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额', + `sales_order_count` int NOT NULL DEFAULT 0 COMMENT '销售单量', + `quantity_sum` int NOT NULL DEFAULT 0 COMMENT '销量件数', + `product_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '商品成本', + `freight_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '运费成本', + `other_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '其他成本', + `stat_version` int NOT NULL DEFAULT 0 COMMENT '重算版本号', + `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `uk_company_shop_spec_year` (`company_id`, `shop_id`, `product_spec_id`, `stat_year`) USING BTREE, + INDEX `idx_company_prod_year` (`company_id`, `product_id`, `stat_year`) USING BTREE, + CONSTRAINT `fk_oss_yearly_spec_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_oss_yearly_spec_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '订单统计-规格-年汇总'; + +-- ---------- 推广费 / 刷单费 ---------- + +CREATE TABLE IF NOT EXISTS `ec_promotion_fee_stat_daily` ( + `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键', + `company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID', + `shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID', + `product_id` bigint UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品ID,0=非商品级', + `category_id` bigint UNSIGNED NOT NULL DEFAULT 0 COMMENT '品类ID,0=非品类级', + `stat_date` date NOT NULL COMMENT '自然日', + `fee_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '推广费合计', + `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `uk_company_shop_dims_date` (`company_id`, `shop_id`, `product_id`, `category_id`, `stat_date`) USING BTREE, + INDEX `idx_company_date` (`company_id`, `stat_date`) USING BTREE, + CONSTRAINT `fk_pfs_daily_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_pfs_daily_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '推广费-日汇总'; + +CREATE TABLE IF NOT EXISTS `ec_promotion_fee_stat_monthly` ( + `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键', + `company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID', + `shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID', + `product_id` bigint UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品ID', + `category_id` bigint UNSIGNED NOT NULL DEFAULT 0 COMMENT '品类ID', + `stat_month` date NOT NULL COMMENT '自然月首日', + `fee_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '推广费合计', + `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `uk_company_shop_dims_month` (`company_id`, `shop_id`, `product_id`, `category_id`, `stat_month`) USING BTREE, + INDEX `idx_company_month` (`company_id`, `stat_month`) USING BTREE, + CONSTRAINT `fk_pfs_monthly_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_pfs_monthly_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '推广费-月汇总'; + +CREATE TABLE IF NOT EXISTS `ec_promotion_fee_stat_yearly` ( + `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键', + `company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID', + `shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID', + `product_id` bigint UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品ID', + `category_id` bigint UNSIGNED NOT NULL DEFAULT 0 COMMENT '品类ID', + `stat_year` smallint NOT NULL COMMENT '自然年', + `fee_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '推广费合计', + `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `uk_company_shop_dims_year` (`company_id`, `shop_id`, `product_id`, `category_id`, `stat_year`) USING BTREE, + INDEX `idx_company_year` (`company_id`, `stat_year`) USING BTREE, + CONSTRAINT `fk_pfs_yearly_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_pfs_yearly_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '推广费-年汇总'; + +CREATE TABLE IF NOT EXISTS `ec_brush_fee_stat_daily` ( + `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键', + `company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID', + `shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID', + `stat_date` date NOT NULL COMMENT '自然日', + `brush_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '刷单费合计', + `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `uk_company_shop_date` (`company_id`, `shop_id`, `stat_date`) USING BTREE, + INDEX `idx_company_date` (`company_id`, `stat_date`) USING BTREE, + CONSTRAINT `fk_bfs_daily_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_bfs_daily_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '刷单费-日汇总'; + +CREATE TABLE IF NOT EXISTS `ec_brush_fee_stat_monthly` ( + `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键', + `company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID', + `shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID', + `stat_month` date NOT NULL COMMENT '自然月首日', + `brush_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '刷单费合计', + `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `uk_company_shop_month` (`company_id`, `shop_id`, `stat_month`) USING BTREE, + INDEX `idx_company_month` (`company_id`, `stat_month`) USING BTREE, + CONSTRAINT `fk_bfs_monthly_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_bfs_monthly_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '刷单费-月汇总'; + +CREATE TABLE IF NOT EXISTS `ec_brush_fee_stat_yearly` ( + `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键', + `company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID', + `shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID', + `stat_year` smallint NOT NULL COMMENT '自然年', + `brush_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '刷单费合计', + `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `uk_company_shop_year` (`company_id`, `shop_id`, `stat_year`) USING BTREE, + INDEX `idx_company_year` (`company_id`, `stat_year`) USING BTREE, + CONSTRAINT `fk_bfs_yearly_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_bfs_yearly_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '刷单费-年汇总'; + +-- ---------- 任务队列 ---------- + +CREATE TABLE IF NOT EXISTS `ec_order_stat_rebuild_task` ( + `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键', + `company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID', + `shop_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '店铺ID,NULL=全店', + `start_date` date NOT NULL COMMENT '重建起始日', + `end_date` date NOT NULL COMMENT '重建结束日', + `granularity` varchar(16) NOT NULL DEFAULT 'all' COMMENT 'daily/monthly/yearly/all', + `status` varchar(20) NOT NULL DEFAULT 'pending' COMMENT 'pending/running/done/failed', + `progress_date` date NULL DEFAULT NULL COMMENT '断点日期', + `error_message` text NULL COMMENT '失败原因', + `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (`id`) USING BTREE, + INDEX `idx_company_status` (`company_id`, `status`) USING BTREE, + CONSTRAINT `fk_osrt_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '订单统计重建任务'; + +CREATE TABLE IF NOT EXISTS `ec_order_stat_refresh_queue` ( + `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键', + `company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID', + `shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID', + `stat_date` date NOT NULL COMMENT '待刷新自然日', + `source` varchar(32) NOT NULL COMMENT 'import/crud/status_change/manual', + `status` varchar(20) NOT NULL DEFAULT 'pending' COMMENT 'pending/running/done/failed', + `retry_count` int NOT NULL DEFAULT 0 COMMENT '重试次数', + `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `uk_company_shop_date_pending` (`company_id`, `shop_id`, `stat_date`, `status`) USING BTREE, + INDEX `idx_status_ctime` (`status`, `create_time`) USING BTREE, + CONSTRAINT `fk_osrq_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_osrq_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '订单统计日汇总待刷新队列'; diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/EComDMBBackendApplication.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/EComDMBBackendApplication.java index 7da2dfdc..fcca83af 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/EComDMBBackendApplication.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/EComDMBBackendApplication.java @@ -5,9 +5,11 @@ import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @EnableAsync +@EnableScheduling @MapperScan( basePackages = "top.xyquan.ecomdmbbackend.modules", annotationClass = Mapper.class diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/brushorder/service/impl/BrushOrderServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/brushorder/service/impl/BrushOrderServiceImpl.java index aabdadba..1314736e 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/brushorder/service/impl/BrushOrderServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/brushorder/service/impl/BrushOrderServiceImpl.java @@ -20,6 +20,7 @@ import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductSpecPO; import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO; import top.xyquan.ecomdmbbackend.modules.ecom.brushorder.model.vo.BrushOrderVO; import top.xyquan.ecomdmbbackend.modules.ecom.brushorder.service.BrushOrderService; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.FeeStatCrudCoordinator; import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductService; import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductSpecService; import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopService; @@ -38,13 +39,16 @@ public class BrushOrderServiceImpl extends ServiceImpl progressCallback; + /** 本任务涉及、需 refresh 汇总表的自然日(order_time → Asia/Shanghai DATE) */ + private final Set dirtyStatDates = ConcurrentHashMap.newKeySet(); + + private static final ZoneId STAT_ZONE = ZoneId.of("Asia/Shanghai"); + /** 本次订单导入的字段映射(仅主线程在 process 入口设置,用于「有变更才更新」时按映射比较) */ private transient Map orderImportFieldMapping; @@ -243,6 +251,33 @@ public class ImportRuntimeContext { public Set getPendingRelationKeys() { return pendingRelationKeys; } public Set getPendingPlatformOrderNos() { return pendingPlatformOrderNos; } + public Set getDirtyStatDates() { + return Collections.unmodifiableSet(dirtyStatDates); + } + + /** + * 标记订单所属自然日需重算汇总(导入/更新路径调用)。 + */ + public void markOrderStatDirty(LocalDateTime orderTime) { + markOrderStatDirty(shopId, orderTime); + } + + public void markOrderStatDirty(Long targetShopId, LocalDateTime orderTime) { + if (orderTime == null || targetShopId == null) { + return; + } + dirtyStatDates.add(orderTime.atZone(STAT_ZONE).toLocalDate()); + } + + /** 更新订单时:旧快照的 shop/date 也需 refresh */ + public void markOrderStatDirtyFromSnapshot(OrderPO before) { + if (before == null || before.getOrderTime() == null) { + return; + } + Long sid = before.getShopId() != null ? before.getShopId() : shopId; + markOrderStatDirty(sid, before.getOrderTime()); + } + // ==================== 工具方法 ==================== public void addNormalizedValue(Set target, String rawValue) { diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/ImportTaskProcessorServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/ImportTaskProcessorServiceImpl.java index c8d5fa6c..0ac8cf75 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/ImportTaskProcessorServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/ImportTaskProcessorServiceImpl.java @@ -3,6 +3,8 @@ package top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.impl; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.ibatis.session.SqlSessionFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import top.xyquan.ecomdmbbackend.common.exception.BusinessException; import top.xyquan.ecomdmbbackend.modules.ecom.importtask.model.po.ImportTaskPO; @@ -11,6 +13,9 @@ import top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.ImportTaskProce import top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.ImportTaskService; import top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.SseNotificationService; import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.FeeStatRefreshService; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatRefreshCoordinator; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support.RefreshSource; import top.xyquan.ecomdmbbackend.modules.ecom.order.service.OrderService; import top.xyquan.ecomdmbbackend.modules.ecom.order.status.service.OrderStatusService; import top.xyquan.ecomdmbbackend.modules.ecom.product.mapper.ProductMapper; @@ -33,8 +38,13 @@ import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CodingErrorAction; import java.nio.charset.StandardCharsets; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.stream.Collectors; /** @@ -43,6 +53,8 @@ import java.util.stream.Collectors; @Service public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorService { + private static final Logger log = LoggerFactory.getLogger(ImportTaskProcessorServiceImpl.class); + private final ImportTaskService importTaskService; private final ProductSpecService productSpecService; private final OrderMapper orderMapper; @@ -60,6 +72,8 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic private final OrderImportProcessor orderImportProcessor; private final ProductSpecImportHelper productSpecImportHelper; private final PromotionFeeImportProcessor promotionFeeImportProcessor; + private final OrderStatRefreshCoordinator orderStatRefreshCoordinator; + private final FeeStatRefreshService feeStatRefreshService; public ImportTaskProcessorServiceImpl(ImportTaskService importTaskService, OrderService orderService, @@ -75,7 +89,9 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic SqlSessionFactory sqlSessionFactory, OssService ossService, SysFileService sysFileService, - PromotionFeeImportProcessor promotionFeeImportProcessor) { + PromotionFeeImportProcessor promotionFeeImportProcessor, + OrderStatRefreshCoordinator orderStatRefreshCoordinator, + FeeStatRefreshService feeStatRefreshService) { this.importTaskService = importTaskService; this.productSpecService = productSpecService; this.orderMapper = orderMapper; @@ -89,6 +105,8 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic this.ossService = ossService; this.sysFileService = sysFileService; this.promotionFeeImportProcessor = promotionFeeImportProcessor; + this.orderStatRefreshCoordinator = orderStatRefreshCoordinator; + this.feeStatRefreshService = feeStatRefreshService; // 初始化 helper 和 processor this.productSpecImportHelper = new ProductSpecImportHelper( @@ -216,11 +234,42 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic String message = result.failCount > 0 ? summary + "\n" + result.errorMessages.toString() : summary; updateTaskStatus(task.getId(), finalStatus, message, result.totalCount, result.successCount, result.failCount); + // 明细写入成功后:异步排队 refresh 汇总表(不阻塞导入线程) + enqueueOrderStatRefreshAfterImport(task, context); + } finally { if (tempOssFile != null && tempOssFile.exists()) tempOssFile.delete(); } } + /** 合并内存脏日期 + DB 兜底,写入 refresh 队列 */ + private void enqueueOrderStatRefreshAfterImport(ImportTaskPO task, ImportRuntimeContext context) { + if (task.getCompanyId() == null || task.getShopId() == null) { + return; + } + Set dates = new HashSet<>(context.getDirtyStatDates()); + try { + List fromDb = orderMapper.selectDistinctOrderDatesByImportTaskId(task.getId()); + if (fromDb != null) { + dates.addAll(fromDb); + } + } catch (Exception e) { + // 兜底查询失败不影响导入成功态 + } + if (dates.isEmpty()) { + return; + } + int queued = orderStatRefreshCoordinator.enqueueRefresh( + task.getCompanyId(), task.getShopId(), dates, RefreshSource.IMPORT); + if (queued > 0) { + ImportTaskPO t = importTaskService.getById(task.getId()); + if (t != null && t.getMessage() != null) { + t.setMessage(t.getMessage() + String.format(";汇总刷新已排队 %d 个自然日", dates.size())); + importTaskService.updateById(t); + } + } + } + private void processPromotionFeeImport(ImportTaskPO task) throws Exception { com.fasterxml.jackson.databind.JsonNode rootNode; try { @@ -285,12 +334,28 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic message += "\n" + result.detailMessage; } updateTaskStatus(task.getId(), finalStatus, message, result.totalCount, result.successCount, result.failCount); + refreshFeeStatAfterPromotionImport(task, feeDateStr, result.successCount); } finally { if (tempOssFile != null && tempOssFile.exists()) tempOssFile.delete(); } } + /** 推广费导入成功后重算对应自然日的费汇总表 */ + private void refreshFeeStatAfterPromotionImport(ImportTaskPO task, String feeDateStr, int successCount) { + if (successCount <= 0 || task.getShopId() == null || feeDateStr == null || feeDateStr.isBlank()) { + return; + } + try { + LocalDate feeDate = LocalDate.parse(feeDateStr.trim(), DateTimeFormatter.ISO_LOCAL_DATE); + feeStatRefreshService.refreshShopDay(task.getCompanyId(), task.getShopId(), feeDate); + } catch (DateTimeParseException e) { + log.warn("推广费导入后 refresh 跳过:feeDate 格式无效 taskId={} feeDate={}", task.getId(), feeDateStr); + } catch (Exception e) { + log.warn("推广费导入后 refresh 失败 taskId={} shopId={} feeDate={}", task.getId(), task.getShopId(), feeDateStr, e); + } + } + private ImportRuntimeContext.MappingConfig parseMappingConfig(String mappingJson) { try { if (mappingJson == null || mappingJson.trim().isEmpty()) { diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/OrderImportProcessor.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/OrderImportProcessor.java index d0d9511b..a2546788 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/OrderImportProcessor.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/OrderImportProcessor.java @@ -1080,6 +1080,13 @@ public class OrderImportProcessor { r.rowNumber, r.platformOrderNo, r.order, r.order.getId(), updateMsg, r.dto != null && Boolean.TRUE.equals(r.dto.getOrderTimeEmptyInInput())); + if (r.order != null && r.order.getOrderTime() != null) { + context.markOrderStatDirty(r.order.getShopId(), r.order.getOrderTime()); + } + if (r.platformOrderNo != null && !r.platformOrderNo.trim().isEmpty()) { + OrderPO snap = context.existingOrderSnapshotByPlatformNo.get(r.platformOrderNo.trim()); + context.markOrderStatDirtyFromSnapshot(snap); + } context.pendingOrders.add(pending); if (r.platformOrderNo != null && !r.platformOrderNo.trim().isEmpty()) { synchronized (context.pendingOrderByPlatformNo) { @@ -1612,6 +1619,11 @@ public class OrderImportProcessor { if (existing != null) { existing.updateData(newOrderPO, existingId, newUpdateMsg, newRowNumber, newOrderTimeEmptyInInput); + if (newOrderPO != null && newOrderPO.getOrderTime() != null) { + context.markOrderStatDirty(newOrderPO.getShopId(), newOrderPO.getOrderTime()); + } + OrderPO snap = context.existingOrderSnapshotByPlatformNo.get(normalized); + context.markOrderStatDirtyFromSnapshot(snap); } } return true; diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/mapper/OrderMapper.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/mapper/OrderMapper.java index 4d0e87c5..bc1c95b5 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/mapper/OrderMapper.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/mapper/OrderMapper.java @@ -4,10 +4,15 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Update; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; import top.xyquan.ecomdmbbackend.modules.ecom.order.model.po.OrderPO; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.OrderShopStatDateRow; import java.math.BigDecimal; +import java.time.LocalDate; import java.time.LocalDateTime; +import java.util.List; /** * 订单Mapper接口 @@ -43,4 +48,40 @@ public interface OrderMapper extends BaseMapper { int linkOrdersBySpecCodeWhenSpecIdNull(@Param("companyId") Long companyId, @Param("specCode") String specCode, @Param("productSpecId") Long productSpecId); + + /** 导入任务完成后兜底:该任务写入订单涉及的自然日 */ + @Select("SELECT DISTINCT DATE(order_time) FROM ec_order WHERE import_task_id = #{importTaskId}") + List selectDistinctOrderDatesByImportTaskId(@Param("importTaskId") Long importTaskId); + + @Select(""" + SELECT DISTINCT DATE(order_time) AS statDate FROM ec_order + WHERE company_id = #{companyId} AND shop_id = #{shopId} + AND order_time >= #{startDate} AND order_time < DATE_ADD(#{endDate}, INTERVAL 1 DAY) + ORDER BY statDate + """) + List selectDistinctOrderDatesByCompanyShopRange( + @Param("companyId") Long companyId, + @Param("shopId") Long shopId, + @Param("startDate") LocalDate startDate, + @Param("endDate") LocalDate endDate); + + /** 公司订单日期范围(rebuild 用) */ + @Select(""" + SELECT MIN(DATE(order_time)) FROM ec_order WHERE company_id = #{companyId} + """) + LocalDate selectMinOrderDateByCompany(@Param("companyId") Long companyId); + + @Select(""" + SELECT MAX(DATE(order_time)) FROM ec_order WHERE company_id = #{companyId} + """) + LocalDate selectMaxOrderDateByCompany(@Param("companyId") Long companyId); + + @Select(""" + SELECT shop_id AS shopId, DATE(order_time) AS statDate FROM ec_order + WHERE company_id = #{companyId} AND spec_code = #{specCode} AND product_spec_id IS NULL + GROUP BY shop_id, DATE(order_time) + """) + List selectOrphanOrderStatDatesBySpecCode( + @Param("companyId") Long companyId, + @Param("specCode") String specCode); } diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/service/impl/OrderServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/service/impl/OrderServiceImpl.java index 87594a8e..c17fd093 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/service/impl/OrderServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/service/impl/OrderServiceImpl.java @@ -32,12 +32,17 @@ import top.xyquan.ecomdmbbackend.modules.ecom.order.status.service.OrderStatusSe import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.vo.ShopVO; import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductService; import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductSpecService; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatCrudCoordinator; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support.StatDirtyKey; import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopService; import top.xyquan.ecomdmbbackend.utils.CurrentUserContext; +import java.time.ZoneId; import java.util.ArrayList; +import java.util.HashSet; import java.util.List; import java.util.Objects; +import java.util.Set; import java.util.stream.Collectors; /** @@ -51,15 +56,18 @@ public class OrderServiceImpl extends ServiceImpl implemen private final ProductService productService; private final ProductSpecService productSpecService; private final OrderStatusService orderStatusService; + private final OrderStatCrudCoordinator orderStatCrudCoordinator; public OrderServiceImpl(CurrentUserContext currentUserContext, ShopService shopService, ProductService productService, ProductSpecService productSpecService, - OrderStatusService orderStatusService) { + OrderStatusService orderStatusService, + OrderStatCrudCoordinator orderStatCrudCoordinator) { this.currentUserContext = currentUserContext; this.shopService = shopService; this.productService = productService; this.productSpecService = productSpecService; this.orderStatusService = orderStatusService; + this.orderStatCrudCoordinator = orderStatCrudCoordinator; } /** @@ -131,6 +139,7 @@ public class OrderServiceImpl extends ServiceImpl implemen // 保存订单 this.save(order); + orderStatCrudCoordinator.afterOrderSaved(null, order); // 转换为VO并返回 return convertToVO(order); @@ -236,8 +245,11 @@ public class OrderServiceImpl extends ServiceImpl implemen // 更新订单 this.updateById(order); + OrderPO after = this.getById(id); + orderStatCrudCoordinator.afterOrderSaved(existingOrder, after); + // 转换为VO并返回 - return convertToVO(order); + return convertToVO(after != null ? after : order); } /** @@ -257,6 +269,7 @@ public class OrderServiceImpl extends ServiceImpl implemen } // 硬删除订单(外键约束会自动处理相关数据) + orderStatCrudCoordinator.afterOrderDeleted(existingOrder); this.removeById(id); } @@ -283,10 +296,12 @@ public class OrderServiceImpl extends ServiceImpl implemen LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); wrapper.eq(OrderPO::getCompanyId, companyId) .in(OrderPO::getId, uniqueIds); - long matched = this.count(wrapper); + List toRemove = this.list(wrapper); + long matched = toRemove.size(); if (matched != uniqueIds.size()) { throw new BusinessException("存在无效订单或无权删除的订单"); } + orderStatCrudCoordinator.afterOrdersDeletedBatch(toRemove); this.remove(wrapper); } @@ -485,7 +500,26 @@ public class OrderServiceImpl extends ServiceImpl implemen public int syncCostsToOrders(Long specId, java.math.BigDecimal productCost, java.math.BigDecimal shippingCost, java.math.BigDecimal otherCost, java.time.LocalDateTime startTime, java.time.LocalDateTime endTime) { - return baseMapper.updateCostFields(productCost, shippingCost, otherCost, specId, startTime, endTime); + ProductSpecPO spec = productSpecService.getById(specId); + int n = baseMapper.updateCostFields(productCost, shippingCost, otherCost, specId, startTime, endTime); + if (n > 0 && spec != null && spec.getCompanyId() != null) { + List affected = list(new LambdaQueryWrapper() + .eq(OrderPO::getCompanyId, spec.getCompanyId()) + .eq(OrderPO::getProductSpecId, specId) + .ge(OrderPO::getOrderTime, startTime) + .le(OrderPO::getOrderTime, endTime) + .select(OrderPO::getCompanyId, OrderPO::getShopId, OrderPO::getOrderTime)); + Set keys = new HashSet<>(); + ZoneId zone = ZoneId.of("Asia/Shanghai"); + for (OrderPO o : affected) { + if (o.getShopId() != null && o.getOrderTime() != null) { + keys.add(new StatDirtyKey(o.getCompanyId(), o.getShopId(), + o.getOrderTime().atZone(zone).toLocalDate())); + } + } + orderStatCrudCoordinator.enqueueDirtyKeys(keys); + } + return n; } @Override diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/config/OrderStatProperties.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/config/OrderStatProperties.java new file mode 100644 index 00000000..ca4978ef --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/config/OrderStatProperties.java @@ -0,0 +1,46 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +/** + * 订单统计读模型配置(写入 Worker、读路径开关、缓存 TTL)。 + */ +@Data +@Component +@ConfigurationProperties(prefix = "order-stat") +public class OrderStatProperties { + + /** daily=读汇总表;order=应急回退扫 ec_order */ + private String statSource = "daily"; + + /** 汇总行缺失时同步补算 */ + private boolean autoRefreshOnMiss = true; + + /** 是否启用夜间全公司 rebuild 定时任务 */ + private boolean nightlyRebuildEnabled = false; + + /** cron 表达式,见 {@code order-stat.nightly-rebuild-cron} */ + private String nightlyRebuildCron = "0 30 2 * * ?"; + + private RefreshWorker refreshWorker = new RefreshWorker(); + + private Cache cache = new Cache(); + + @Data + public static class RefreshWorker { + /** 是否启动异步 refresh 消费者 */ + private boolean enabled = true; + private int poolSize = 4; + /** 轮询 ec_order_stat_refresh_queue 间隔毫秒 */ + private long pollIntervalMs = 2000; + } + + @Data + public static class Cache { + private boolean enabled = true; + private long ttlHistorySeconds = 86400; + private long ttlTodaySeconds = 900; + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/controller/OrderStatAdminController.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/controller/OrderStatAdminController.java new file mode 100644 index 00000000..25d88bd1 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/controller/OrderStatAdminController.java @@ -0,0 +1,61 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.controller; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission; +import top.xyquan.ecomdmbbackend.common.response.ApiResponse; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatRebuildRequestDTO; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatReconcileRequestDTO; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.OrderStatRebuildTaskPO; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatRebuildService; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatReconcileService; + +@Tag(name = "电商-订单统计管理", description = "汇总表 backfill / rebuild") +@RestController +@RequestMapping("/ec/admin/order-stat") +public class OrderStatAdminController { + + private final OrderStatRebuildService orderStatRebuildService; + private final OrderStatReconcileService orderStatReconcileService; + + public OrderStatAdminController(OrderStatRebuildService orderStatRebuildService, + OrderStatReconcileService orderStatReconcileService) { + this.orderStatRebuildService = orderStatRebuildService; + this.orderStatReconcileService = orderStatReconcileService; + } + + @Operation(summary = "创建 rebuild 任务", description = "异步按 shop×date 重算日/月/年汇总表") + @PostMapping("/rebuild") + @RequirePermission(value = "ecom:shop:read", description = "订单统计 rebuild", allowSuper = true) + public ApiResponse rebuild(@Valid @RequestBody OrderStatRebuildRequestDTO dto) { + Long taskId = orderStatRebuildService.scheduleRebuild( + dto.getCompanyId(), dto.getShopId(), dto.getStartDate(), dto.getEndDate()); + return ApiResponse.success("rebuild 任务已创建", taskId); + } + + @Operation(summary = "查询 rebuild 进度") + @GetMapping("/rebuild/{taskId}") + @RequirePermission(value = "ecom:shop:read", description = "查询 rebuild 进度", allowSuper = true) + public ApiResponse rebuildStatus(@PathVariable Long taskId) { + OrderStatRebuildTaskPO task = orderStatRebuildService.getTask(taskId); + return ApiResponse.success("查询成功", task); + } + + @Operation(summary = "抽样对账", description = "汇总表 vs 明细聚合,默认 100 个 shop×date") + @PostMapping("/reconcile") + @RequirePermission(value = "ecom:shop:read", description = "订单统计对账", allowSuper = true) + public ApiResponse reconcile( + @Valid @RequestBody OrderStatReconcileRequestDTO dto) { + int sample = dto.getSampleSize() != null ? dto.getSampleSize() : 100; + OrderStatReconcileService.ReconcileReport report = orderStatReconcileService.reconcileCompany( + dto.getCompanyId(), dto.getStartDate(), dto.getEndDate(), sample); + return ApiResponse.success(report.isPassed() ? "对账通过" : "存在差异", report); + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/job/OrderStatNightlyRebuildJob.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/job/OrderStatNightlyRebuildJob.java new file mode 100644 index 00000000..430c99bf --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/job/OrderStatNightlyRebuildJob.java @@ -0,0 +1,64 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.job; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; +import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.config.OrderStatProperties; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatRebuildService; +import top.xyquan.ecomdmbbackend.modules.org.company.model.po.CompanyPO; +import top.xyquan.ecomdmbbackend.modules.org.company.service.CompanyService; + +import java.time.LocalDate; +import java.util.List; + +/** + * 夜间全公司汇总灌数:按公司订单日期范围创建 rebuild 任务。 + */ +@Component +public class OrderStatNightlyRebuildJob { + + private static final Logger log = LoggerFactory.getLogger(OrderStatNightlyRebuildJob.class); + + private final OrderStatProperties properties; + private final CompanyService companyService; + private final OrderMapper orderMapper; + private final OrderStatRebuildService orderStatRebuildService; + + public OrderStatNightlyRebuildJob(OrderStatProperties properties, + CompanyService companyService, + OrderMapper orderMapper, + OrderStatRebuildService orderStatRebuildService) { + this.properties = properties; + this.companyService = companyService; + this.orderMapper = orderMapper; + this.orderStatRebuildService = orderStatRebuildService; + } + + /** 默认每天 02:30 触发(可在 yml 覆盖 cron) */ + @Scheduled(cron = "${order-stat.nightly-rebuild-cron:0 30 2 * * ?}") + public void runNightlyRebuild() { + if (!properties.isNightlyRebuildEnabled()) { + return; + } + List companies = companyService.list(); + for (CompanyPO company : companies) { + try { + scheduleCompany(company.getId()); + } catch (Exception e) { + log.warn("nightly rebuild schedule failed company={}", company.getId(), e); + } + } + } + + private void scheduleCompany(Long companyId) { + LocalDate start = orderMapper.selectMinOrderDateByCompany(companyId); + LocalDate end = orderMapper.selectMaxOrderDateByCompany(companyId); + if (start == null || end == null) { + return; + } + Long taskId = orderStatRebuildService.scheduleRebuild(companyId, null, start, end); + log.info("nightly rebuild scheduled company={} taskId={} range {}~{}", companyId, taskId, start, end); + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/mapper/FeeStatDailyMapper.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/mapper/FeeStatDailyMapper.java new file mode 100644 index 00000000..8b5ad71a --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/mapper/FeeStatDailyMapper.java @@ -0,0 +1,64 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import lombok.Data; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.PromotionFeeStatDailyPO; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.util.List; + +@Mapper +public interface FeeStatDailyMapper extends BaseMapper { + + void deletePromotionDaily(@Param("companyId") Long companyId, + @Param("shopId") Long shopId, + @Param("statDate") LocalDate statDate); + + void batchInsertPromotionDaily(@Param("list") List list); + + void rollupPromotionMonthly(@Param("companyId") Long companyId, + @Param("shopId") Long shopId, + @Param("statMonth") LocalDate statMonth); + + void rollupPromotionYearly(@Param("companyId") Long companyId, + @Param("shopId") Long shopId, + @Param("statYear") int statYear); + + void deleteBrushDaily(@Param("companyId") Long companyId, + @Param("shopId") Long shopId, + @Param("statDate") LocalDate statDate); + + void upsertBrushDaily(@Param("companyId") Long companyId, + @Param("shopId") Long shopId, + @Param("statDate") LocalDate statDate, + @Param("brushAmount") BigDecimal brushAmount); + + void rollupBrushMonthly(@Param("companyId") Long companyId, + @Param("shopId") Long shopId, + @Param("statMonth") LocalDate statMonth); + + void rollupBrushYearly(@Param("companyId") Long companyId, + @Param("shopId") Long shopId, + @Param("statYear") int statYear); + + /** 从 ec_promotion_fee 聚合单日单店 */ + List aggregatePromotionByShopDay( + @Param("companyId") Long companyId, + @Param("shopId") Long shopId, + @Param("statDate") LocalDate statDate); + + /** 从 ec_brush_order 聚合单日单店 */ + BigDecimal aggregateBrushByShopDay(@Param("companyId") Long companyId, + @Param("shopId") Long shopId, + @Param("statDate") LocalDate statDate); + + @Data + class PromotionFeeAggRow { + private Long productId; + private Long categoryId; + private BigDecimal feeAmount; + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/mapper/OrderStatDailyMapper.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/mapper/OrderStatDailyMapper.java new file mode 100644 index 00000000..1ab785a2 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/mapper/OrderStatDailyMapper.java @@ -0,0 +1,55 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.OrderStatDailyProductPO; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.OrderStatDailyShopPO; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.OrderStatDailySpecPO; + +import java.time.LocalDate; +import java.util.List; + +@Mapper +public interface OrderStatDailyMapper extends BaseMapper { + + void upsertDailyShop(OrderStatDailyShopPO row); + + void deleteDailyProduct(@Param("companyId") Long companyId, + @Param("shopId") Long shopId, + @Param("statDate") LocalDate statDate); + + void batchInsertDailyProduct(@Param("list") List list); + + void deleteDailySpec(@Param("companyId") Long companyId, + @Param("shopId") Long shopId, + @Param("statDate") LocalDate statDate); + + void batchInsertDailySpec(@Param("list") List list); + + /** 日表 → 月表(店铺) */ + void rollupMonthlyShop(@Param("companyId") Long companyId, + @Param("shopId") Long shopId, + @Param("statMonth") LocalDate statMonth); + + /** 日表 → 年表(店铺) */ + void rollupYearlyShop(@Param("companyId") Long companyId, + @Param("shopId") Long shopId, + @Param("statYear") int statYear); + + void rollupMonthlyProduct(@Param("companyId") Long companyId, + @Param("shopId") Long shopId, + @Param("statMonth") LocalDate statMonth); + + void rollupYearlyProduct(@Param("companyId") Long companyId, + @Param("shopId") Long shopId, + @Param("statYear") int statYear); + + void rollupMonthlySpec(@Param("companyId") Long companyId, + @Param("shopId") Long shopId, + @Param("statMonth") LocalDate statMonth); + + void rollupYearlySpec(@Param("companyId") Long companyId, + @Param("shopId") Long shopId, + @Param("statYear") int statYear); +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/mapper/OrderStatQueryMapper.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/mapper/OrderStatQueryMapper.java new file mode 100644 index 00000000..6d34ca91 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/mapper/OrderStatQueryMapper.java @@ -0,0 +1,98 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper; + +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO; + +import java.time.LocalDate; +import java.util.List; + +/** 汇总表读路径 SQL(日/月/年表 SUM)。 */ +@Mapper +public interface OrderStatQueryMapper { + + OrderStatMetricsDTO sumDailyShop(@Param("companyId") Long companyId, + @Param("shopIds") List shopIds, + @Param("startDate") LocalDate startDate, + @Param("endDate") LocalDate endDate); + + List sumDailyShopByDay(@Param("companyId") Long companyId, + @Param("shopIds") List shopIds, + @Param("startDate") LocalDate startDate, + @Param("endDate") LocalDate endDate); + + List sumDailyShopByShop(@Param("companyId") Long companyId, + @Param("shopIds") List shopIds, + @Param("startDate") LocalDate startDate, + @Param("endDate") LocalDate endDate); + + List sumDailyProductByCategory(@Param("companyId") Long companyId, + @Param("shopIds") List shopIds, + @Param("startDate") LocalDate startDate, + @Param("endDate") LocalDate endDate); + + List sumDailyProductByProduct(@Param("companyId") Long companyId, + @Param("shopIds") List shopIds, + @Param("startDate") LocalDate startDate, + @Param("endDate") LocalDate endDate); + + List sumDailyProductByShopProduct(@Param("companyId") Long companyId, + @Param("shopIds") List shopIds, + @Param("startDate") LocalDate startDate, + @Param("endDate") LocalDate endDate); + + OrderStatMetricsDTO sumDailyProductForOneProduct(@Param("companyId") Long companyId, + @Param("shopIds") List shopIds, + @Param("productId") Long productId, + @Param("startDate") LocalDate startDate, + @Param("endDate") LocalDate endDate); + + List sumDailyProductByDayForOneProduct(@Param("companyId") Long companyId, + @Param("shopIds") List shopIds, + @Param("productId") Long productId, + @Param("startDate") LocalDate startDate, + @Param("endDate") LocalDate endDate); + + List sumMonthlyProductByCategory(@Param("companyId") Long companyId, + @Param("shopIds") List shopIds, + @Param("startMonth") LocalDate startMonth, + @Param("endMonth") LocalDate endMonth); + + List sumMonthlyProductByProduct(@Param("companyId") Long companyId, + @Param("shopIds") List shopIds, + @Param("startMonth") LocalDate startMonth, + @Param("endMonth") LocalDate endMonth); + + List sumYearlyProductByCategory(@Param("companyId") Long companyId, + @Param("shopIds") List shopIds, + @Param("startYear") int startYear, + @Param("endYear") int endYear); + + List sumYearlyProductByProduct(@Param("companyId") Long companyId, + @Param("shopIds") List shopIds, + @Param("startYear") int startYear, + @Param("endYear") int endYear); + + List sumDailySpecBySpec(@Param("companyId") Long companyId, + @Param("shopIds") List shopIds, + @Param("productId") Long productId, + @Param("startDate") LocalDate startDate, + @Param("endDate") LocalDate endDate); + + List sumMonthlySpecBySpec(@Param("companyId") Long companyId, + @Param("shopIds") List shopIds, + @Param("productId") Long productId, + @Param("startMonth") LocalDate startMonth, + @Param("endMonth") LocalDate endMonth); + + List sumYearlySpecBySpec(@Param("companyId") Long companyId, + @Param("shopIds") List shopIds, + @Param("productId") Long productId, + @Param("startYear") int startYear, + @Param("endYear") int endYear); + + int countDailyShopRows(@Param("companyId") Long companyId, + @Param("shopIds") List shopIds, + @Param("startDate") LocalDate startDate, + @Param("endDate") LocalDate endDate); +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/mapper/OrderStatRebuildTaskMapper.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/mapper/OrderStatRebuildTaskMapper.java new file mode 100644 index 00000000..08cc35dc --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/mapper/OrderStatRebuildTaskMapper.java @@ -0,0 +1,9 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Mapper; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.OrderStatRebuildTaskPO; + +@Mapper +public interface OrderStatRebuildTaskMapper extends BaseMapper { +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/mapper/OrderStatRefreshMapper.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/mapper/OrderStatRefreshMapper.java new file mode 100644 index 00000000..a661793a --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/mapper/OrderStatRefreshMapper.java @@ -0,0 +1,60 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import lombok.Data; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.OrderStatRefreshQueuePO; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.List; + +@Mapper +public interface OrderStatRefreshMapper extends BaseMapper { + + void markDone(@Param("id") Long id); + + void markFailed(@Param("id") Long id, @Param("retryCount") int retryCount); + + /** 入队:若已有 pending 同维度则忽略 */ + int insertPendingIgnore(@Param("companyId") Long companyId, + @Param("shopId") Long shopId, + @Param("statDate") LocalDate statDate, + @Param("source") String source); + + /** + * 单日单店规格维度聚合(口径与 OrderStatAggMapper 一致)。 + */ + /** 全状态 GMV 订单笔数(单日单店) */ + Integer countGmvOrdersByShopDay(@Param("companyId") Long companyId, + @Param("shopId") Long shopId, + @Param("start") java.time.LocalDateTime start, + @Param("end") java.time.LocalDateTime end); + + List aggregateSpecByShopDay( + @Param("companyId") Long companyId, + @Param("shopId") Long shopId, + @Param("start") LocalDateTime start, + @Param("end") LocalDateTime end, + @Param("unionStatusIds") List unionStatusIds, + @Param("salesStatusIds") List salesStatusIds, + @Param("refundStatusIds") List refundStatusIds, + @Param("productCostStatusIds") List productCostStatusIds, + @Param("freightCostStatusIds") List freightCostStatusIds, + @Param("otherCostStatusIds") List otherCostStatusIds); + + @Data + class SpecDayRow { + private Long productId; + private Long productSpecId; + private BigDecimal salesAmount; + private Long orderCount; + private BigDecimal refundAmount; + private Integer quantitySum; + private BigDecimal productCost; + private BigDecimal freightCost; + private BigDecimal otherCost; + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/OrderShopStatDateRow.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/OrderShopStatDateRow.java new file mode 100644 index 00000000..b87c54ec --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/OrderShopStatDateRow.java @@ -0,0 +1,12 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model; + +import lombok.Data; + +import java.time.LocalDate; + +/** 订单汇总 refresh 维度:店铺 + 自然日 */ +@Data +public class OrderShopStatDateRow { + private Long shopId; + private LocalDate statDate; +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/dto/OrderStatMetricsDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/dto/OrderStatMetricsDTO.java new file mode 100644 index 00000000..e97cd79c --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/dto/OrderStatMetricsDTO.java @@ -0,0 +1,39 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDate; + +/** + * 汇总表读侧统一指标 DTO(店铺/商品/规格维度共用字段集)。 + */ +@Data +public class OrderStatMetricsDTO { + + private LocalDate statDate; + private Long shopId; + private Long platformId; + private Long productId; + private Long categoryId; + private Long productSpecId; + + private BigDecimal salesAmount = BigDecimal.ZERO; + private BigDecimal refundAmount = BigDecimal.ZERO; + private Integer salesOrderCount = 0; + private BigDecimal productCost = BigDecimal.ZERO; + private BigDecimal freightCost = BigDecimal.ZERO; + private BigDecimal otherCost = BigDecimal.ZERO; + private BigDecimal gmvAmount = BigDecimal.ZERO; + private Integer gmvOrderCount = 0; + private Integer quantitySum = 0; + + /** 订单成本合计 */ + public BigDecimal getOrderCost() { + return nz(productCost).add(nz(freightCost)).add(nz(otherCost)); + } + + private static BigDecimal nz(BigDecimal v) { + return v != null ? v : BigDecimal.ZERO; + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/dto/OrderStatRebuildRequestDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/dto/OrderStatRebuildRequestDTO.java new file mode 100644 index 00000000..b2e37767 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/dto/OrderStatRebuildRequestDTO.java @@ -0,0 +1,27 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto; + +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotNull; +import lombok.Data; + +import java.time.LocalDate; + +@Data +@Schema(description = "订单统计 rebuild 请求") +public class OrderStatRebuildRequestDTO { + + @NotNull + @Schema(description = "公司ID") + private Long companyId; + + @Schema(description = "店铺ID,空=全店") + private Long shopId; + + @NotNull + @Schema(description = "起始自然日") + private LocalDate startDate; + + @NotNull + @Schema(description = "结束自然日") + private LocalDate endDate; +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/dto/OrderStatReconcileRequestDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/dto/OrderStatReconcileRequestDTO.java new file mode 100644 index 00000000..54abf51e --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/dto/OrderStatReconcileRequestDTO.java @@ -0,0 +1,24 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto; + +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotNull; +import lombok.Data; + +import java.time.LocalDate; + +@Data +@Schema(description = "汇总表对账请求") +public class OrderStatReconcileRequestDTO { + + @NotNull + private Long companyId; + + @NotNull + private LocalDate startDate; + + @NotNull + private LocalDate endDate; + + @Schema(description = "抽样条数,默认 100") + private Integer sampleSize = 100; +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/OrderStatDailyProductPO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/OrderStatDailyProductPO.java new file mode 100644 index 00000000..dd9ac587 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/OrderStatDailyProductPO.java @@ -0,0 +1,62 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.LocalDateTime; + +@Data +@TableName("ec_order_stat_daily_product") +public class OrderStatDailyProductPO { + + @TableId(value = "id", type = IdType.AUTO) + private Long id; + + @TableField("company_id") + private Long companyId; + + @TableField("shop_id") + private Long shopId; + + @TableField("product_id") + private Long productId; + + @TableField("category_id") + private Long categoryId; + + @TableField("stat_date") + private LocalDate statDate; + + @TableField("sales_amount") + private BigDecimal salesAmount; + + @TableField("refund_amount") + private BigDecimal refundAmount; + + @TableField("sales_order_count") + private Integer salesOrderCount; + + @TableField("product_cost") + private BigDecimal productCost; + + @TableField("freight_cost") + private BigDecimal freightCost; + + @TableField("other_cost") + private BigDecimal otherCost; + + @TableField("stat_version") + private Integer statVersion; + + @TableField(value = "create_time", fill = FieldFill.INSERT) + private LocalDateTime createTime; + + @TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE) + private LocalDateTime updateTime; +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/OrderStatDailyShopPO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/OrderStatDailyShopPO.java new file mode 100644 index 00000000..98690984 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/OrderStatDailyShopPO.java @@ -0,0 +1,65 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.LocalDateTime; + +@Data +@TableName("ec_order_stat_daily_shop") +public class OrderStatDailyShopPO { + + @TableId(value = "id", type = IdType.AUTO) + private Long id; + + @TableField("company_id") + private Long companyId; + + @TableField("shop_id") + private Long shopId; + + @TableField("platform_id") + private Long platformId; + + @TableField("stat_date") + private LocalDate statDate; + + @TableField("sales_amount") + private BigDecimal salesAmount; + + @TableField("refund_amount") + private BigDecimal refundAmount; + + @TableField("sales_order_count") + private Integer salesOrderCount; + + @TableField("product_cost") + private BigDecimal productCost; + + @TableField("freight_cost") + private BigDecimal freightCost; + + @TableField("other_cost") + private BigDecimal otherCost; + + @TableField("gmv_amount") + private BigDecimal gmvAmount; + + @TableField("gmv_order_count") + private Integer gmvOrderCount; + + @TableField("stat_version") + private Integer statVersion; + + @TableField(value = "create_time", fill = FieldFill.INSERT) + private LocalDateTime createTime; + + @TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE) + private LocalDateTime updateTime; +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/OrderStatDailySpecPO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/OrderStatDailySpecPO.java new file mode 100644 index 00000000..a638f05a --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/OrderStatDailySpecPO.java @@ -0,0 +1,65 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.LocalDateTime; + +@Data +@TableName("ec_order_stat_daily_spec") +public class OrderStatDailySpecPO { + + @TableId(value = "id", type = IdType.AUTO) + private Long id; + + @TableField("company_id") + private Long companyId; + + @TableField("shop_id") + private Long shopId; + + @TableField("product_id") + private Long productId; + + @TableField("product_spec_id") + private Long productSpecId; + + @TableField("stat_date") + private LocalDate statDate; + + @TableField("sales_amount") + private BigDecimal salesAmount; + + @TableField("refund_amount") + private BigDecimal refundAmount; + + @TableField("sales_order_count") + private Integer salesOrderCount; + + @TableField("quantity_sum") + private Integer quantitySum; + + @TableField("product_cost") + private BigDecimal productCost; + + @TableField("freight_cost") + private BigDecimal freightCost; + + @TableField("other_cost") + private BigDecimal otherCost; + + @TableField("stat_version") + private Integer statVersion; + + @TableField(value = "create_time", fill = FieldFill.INSERT) + private LocalDateTime createTime; + + @TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE) + private LocalDateTime updateTime; +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/OrderStatRebuildTaskPO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/OrderStatRebuildTaskPO.java new file mode 100644 index 00000000..00f1a6eb --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/OrderStatRebuildTaskPO.java @@ -0,0 +1,49 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.time.LocalDate; +import java.time.LocalDateTime; + +@Data +@TableName("ec_order_stat_rebuild_task") +public class OrderStatRebuildTaskPO { + + @TableId(value = "id", type = IdType.AUTO) + private Long id; + + @TableField("company_id") + private Long companyId; + + @TableField("shop_id") + private Long shopId; + + @TableField("start_date") + private LocalDate startDate; + + @TableField("end_date") + private LocalDate endDate; + + @TableField("granularity") + private String granularity; + + @TableField("status") + private String status; + + @TableField("progress_date") + private LocalDate progressDate; + + @TableField("error_message") + private String errorMessage; + + @TableField(value = "create_time", fill = FieldFill.INSERT) + private LocalDateTime createTime; + + @TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE) + private LocalDateTime updateTime; +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/OrderStatRefreshQueuePO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/OrderStatRefreshQueuePO.java new file mode 100644 index 00000000..4ed7dc38 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/OrderStatRefreshQueuePO.java @@ -0,0 +1,43 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.time.LocalDate; +import java.time.LocalDateTime; + +@Data +@TableName("ec_order_stat_refresh_queue") +public class OrderStatRefreshQueuePO { + + @TableId(value = "id", type = IdType.AUTO) + private Long id; + + @TableField("company_id") + private Long companyId; + + @TableField("shop_id") + private Long shopId; + + @TableField("stat_date") + private LocalDate statDate; + + @TableField("source") + private String source; + + @TableField("status") + private String status; + + @TableField("retry_count") + private Integer retryCount; + + @TableField(value = "create_time", fill = FieldFill.INSERT) + private LocalDateTime createTime; + + @TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE) + private LocalDateTime updateTime; +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/PromotionFeeStatDailyPO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/PromotionFeeStatDailyPO.java new file mode 100644 index 00000000..71bcad06 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/PromotionFeeStatDailyPO.java @@ -0,0 +1,44 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.LocalDateTime; + +@Data +@TableName("ec_promotion_fee_stat_daily") +public class PromotionFeeStatDailyPO { + + @TableId(value = "id", type = IdType.AUTO) + private Long id; + + @TableField("company_id") + private Long companyId; + + @TableField("shop_id") + private Long shopId; + + @TableField("product_id") + private Long productId; + + @TableField("category_id") + private Long categoryId; + + @TableField("stat_date") + private LocalDate statDate; + + @TableField("fee_amount") + private BigDecimal feeAmount; + + @TableField(value = "create_time", fill = FieldFill.INSERT) + private LocalDateTime createTime; + + @TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE) + private LocalDateTime updateTime; +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/FeeStatCrudCoordinator.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/FeeStatCrudCoordinator.java new file mode 100644 index 00000000..12e38126 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/FeeStatCrudCoordinator.java @@ -0,0 +1,102 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import top.xyquan.ecomdmbbackend.modules.ecom.brushorder.model.po.BrushOrderPO; +import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.po.PromotionFeePO; + +import java.time.LocalDate; +import java.time.ZoneId; +import java.util.HashSet; +import java.util.Set; + +/** + * 推广费/刷单 CRUD 后刷新费汇总日表(事务提交后执行)。 + */ +@Service +public class FeeStatCrudCoordinator { + + private static final Logger log = LoggerFactory.getLogger(FeeStatCrudCoordinator.class); + private static final ZoneId STAT_ZONE = ZoneId.of("Asia/Shanghai"); + + private final FeeStatRefreshService feeStatRefreshService; + private final OrderStatCacheService orderStatCacheService; + + public FeeStatCrudCoordinator(FeeStatRefreshService feeStatRefreshService, + OrderStatCacheService orderStatCacheService) { + this.feeStatRefreshService = feeStatRefreshService; + this.orderStatCacheService = orderStatCacheService; + } + + public void afterPromotionFeeSaved(PromotionFeePO before, PromotionFeePO after) { + Set keys = new HashSet<>(); + addPromotionKey(keys, before); + addPromotionKey(keys, after); + runAfterCommit(keys); + } + + public void afterPromotionFeeDeleted(PromotionFeePO before) { + Set keys = new HashSet<>(); + addPromotionKey(keys, before); + runAfterCommit(keys); + } + + public void afterBrushOrderSaved(BrushOrderPO before, BrushOrderPO after) { + Set keys = new HashSet<>(); + addBrushKey(keys, before); + addBrushKey(keys, after); + runAfterCommit(keys); + } + + public void afterBrushOrderDeleted(BrushOrderPO before) { + Set keys = new HashSet<>(); + addBrushKey(keys, before); + runAfterCommit(keys); + } + + private void runAfterCommit(Set keys) { + if (keys.isEmpty()) { + return; + } + Runnable task = () -> { + for (ShopDay k : keys) { + try { + feeStatRefreshService.refreshShopDay(k.companyId(), k.shopId(), k.statDate()); + orderStatCacheService.invalidateCompanyShopRange(k.companyId(), k.shopId(), k.statDate(), k.statDate()); + } catch (Exception e) { + log.warn("fee stat refresh failed: {}", k, e); + } + } + }; + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { + @Override + public void afterCommit() { + task.run(); + } + }); + } else { + task.run(); + } + } + + private static void addPromotionKey(Set keys, PromotionFeePO po) { + if (po == null || po.getCompanyId() == null || po.getShopId() == null || po.getFeeDate() == null) { + return; + } + keys.add(new ShopDay(po.getCompanyId(), po.getShopId(), po.getFeeDate())); + } + + private static void addBrushKey(Set keys, BrushOrderPO po) { + if (po == null || po.getCompanyId() == null || po.getShopId() == null || po.getBrushTime() == null) { + return; + } + LocalDate d = po.getBrushTime().atZone(STAT_ZONE).toLocalDate(); + keys.add(new ShopDay(po.getCompanyId(), po.getShopId(), d)); + } + + private record ShopDay(Long companyId, Long shopId, LocalDate statDate) {} +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/FeeStatRefreshService.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/FeeStatRefreshService.java new file mode 100644 index 00000000..dca79710 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/FeeStatRefreshService.java @@ -0,0 +1,69 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service; + +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper.FeeStatDailyMapper; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.PromotionFeeStatDailyPO; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; + +/** 推广费/刷单费日表 refresh + 月年 rollup。 */ +@Service +public class FeeStatRefreshService { + + private final FeeStatDailyMapper feeStatDailyMapper; + + public FeeStatRefreshService(FeeStatDailyMapper feeStatDailyMapper) { + this.feeStatDailyMapper = feeStatDailyMapper; + } + + @Transactional(rollbackFor = Exception.class) + public void refreshShopDay(Long companyId, Long shopId, LocalDate statDate) { + refreshPromotionDay(companyId, shopId, statDate); + refreshBrushDay(companyId, shopId, statDate); + LocalDate statMonth = statDate.withDayOfMonth(1); + int statYear = statDate.getYear(); + feeStatDailyMapper.rollupPromotionMonthly(companyId, shopId, statMonth); + feeStatDailyMapper.rollupPromotionYearly(companyId, shopId, statYear); + feeStatDailyMapper.rollupBrushMonthly(companyId, shopId, statMonth); + feeStatDailyMapper.rollupBrushYearly(companyId, shopId, statYear); + } + + private void refreshPromotionDay(Long companyId, Long shopId, LocalDate statDate) { + feeStatDailyMapper.deletePromotionDaily(companyId, shopId, statDate); + List rows = + feeStatDailyMapper.aggregatePromotionByShopDay(companyId, shopId, statDate); + if (rows == null || rows.isEmpty()) { + return; + } + List list = new ArrayList<>(); + for (FeeStatDailyMapper.PromotionFeeAggRow r : rows) { + if (r.getFeeAmount() == null || r.getFeeAmount().signum() == 0) { + continue; + } + PromotionFeeStatDailyPO po = new PromotionFeeStatDailyPO(); + po.setCompanyId(companyId); + po.setShopId(shopId); + po.setProductId(r.getProductId() != null ? r.getProductId() : 0L); + po.setCategoryId(r.getCategoryId() != null ? r.getCategoryId() : 0L); + po.setStatDate(statDate); + po.setFeeAmount(r.getFeeAmount()); + list.add(po); + } + if (!list.isEmpty()) { + feeStatDailyMapper.batchInsertPromotionDaily(list); + } + } + + private void refreshBrushDay(Long companyId, Long shopId, LocalDate statDate) { + BigDecimal amt = feeStatDailyMapper.aggregateBrushByShopDay(companyId, shopId, statDate); + if (amt == null || amt.signum() == 0) { + feeStatDailyMapper.deleteBrushDaily(companyId, shopId, statDate); + return; + } + feeStatDailyMapper.upsertBrushDaily(companyId, shopId, statDate, amt); + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatCacheService.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatCacheService.java new file mode 100644 index 00000000..58d6b861 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatCacheService.java @@ -0,0 +1,91 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Service; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.config.OrderStatProperties; + +import java.time.LocalDate; +import java.util.concurrent.TimeUnit; + +/** + * 汇总读路径 Redis 缓存失效(按公司+店铺+日期区间)。 + */ +@Service +public class OrderStatCacheService { + + private static final Logger log = LoggerFactory.getLogger(OrderStatCacheService.class); + private static final String KEY_PREFIX = "order-stat:read:"; + + private final OrderStatProperties properties; + private final RedisTemplate redisTemplate; + + public OrderStatCacheService(OrderStatProperties properties, + RedisTemplate redisTemplate) { + this.properties = properties; + this.redisTemplate = redisTemplate; + } + + public boolean isEnabled() { + return properties.getCache().isEnabled(); + } + + /** 写入缓存(Query 层按需调用) */ + public void put(String cacheKey, Object value, long ttlSeconds) { + if (!isEnabled() || cacheKey == null) { + return; + } + try { + redisTemplate.opsForValue().set(KEY_PREFIX + cacheKey, value, ttlSeconds, TimeUnit.SECONDS); + } catch (Exception e) { + log.debug("order-stat cache put skip: {}", cacheKey, e); + } + } + + @SuppressWarnings("unchecked") + public T get(String cacheKey, Class type) { + if (!isEnabled() || cacheKey == null) { + return null; + } + try { + Object v = redisTemplate.opsForValue().get(KEY_PREFIX + cacheKey); + if (v != null && type.isInstance(v)) { + return (T) v; + } + } catch (Exception e) { + log.debug("order-stat cache get skip: {}", cacheKey, e); + } + return null; + } + + /** 费用/订单变更后失效读缓存 */ + public void invalidateCompanyShopRange(Long companyId, Long shopId, LocalDate start, LocalDate end) { + if (!isEnabled() || companyId == null || shopId == null || start == null || end == null) { + return; + } + try { + for (LocalDate d = start; !d.isAfter(end); d = d.plusDays(1)) { + String pattern = KEY_PREFIX + companyId + ":" + shopId + ":" + d + ":*"; + var keys = redisTemplate.keys(pattern); + if (keys != null && !keys.isEmpty()) { + redisTemplate.delete(keys); + } + } + } catch (Exception e) { + log.warn("order-stat cache invalidate failed company={} shop={}", companyId, shopId, e); + } + } + + public long resolveTtlSeconds(LocalDate endDate) { + LocalDate today = LocalDate.now(); + if (endDate != null && !endDate.isBefore(today)) { + return properties.getCache().getTtlTodaySeconds(); + } + return properties.getCache().getTtlHistorySeconds(); + } + + public static String buildKey(Long companyId, Long shopId, LocalDate start, LocalDate end, String suffix) { + return companyId + ":" + shopId + ":" + start + ":" + end + ":" + suffix; + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatCrudCoordinator.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatCrudCoordinator.java new file mode 100644 index 00000000..ec4ecbae --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatCrudCoordinator.java @@ -0,0 +1,128 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import top.xyquan.ecomdmbbackend.modules.ecom.order.model.po.OrderPO; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support.RefreshSource; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support.StatDirtyKey; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * 订单 CRUD 后触发汇总 refresh(事务提交后执行,避免读到未提交明细)。 + */ +@Service +public class OrderStatCrudCoordinator { + + private static final Logger log = LoggerFactory.getLogger(OrderStatCrudCoordinator.class); + private static final ZoneId STAT_ZONE = ZoneId.of("Asia/Shanghai"); + + private final OrderStatRefreshService orderStatRefreshService; + private final OrderStatRefreshCoordinator orderStatRefreshCoordinator; + + public OrderStatCrudCoordinator(OrderStatRefreshService orderStatRefreshService, + OrderStatRefreshCoordinator orderStatRefreshCoordinator) { + this.orderStatRefreshService = orderStatRefreshService; + this.orderStatRefreshCoordinator = orderStatRefreshCoordinator; + } + + /** 单条创建/更新后:同步 refresh 涉及的自然日 */ + public void afterOrderSaved(OrderPO before, OrderPO after) { + Set keys = new HashSet<>(); + addKey(keys, before); + addKey(keys, after); + runAfterCommit(keys, true); + } + + /** 单条删除后 */ + public void afterOrderDeleted(OrderPO before) { + Set keys = new HashSet<>(); + addKey(keys, before); + runAfterCommit(keys, true); + } + + /** 批量删除:异步入队(避免一次 refresh 过多) */ + public void afterOrdersDeletedBatch(List removed) { + if (removed == null || removed.isEmpty()) { + return; + } + Set keys = new HashSet<>(); + for (OrderPO o : removed) { + addKey(keys, o); + } + runAfterCommit(keys, false); + } + + /** 规格补链等批量影响:异步入队 */ + public void enqueueDirtyKeys(Collection keys) { + if (keys == null || keys.isEmpty()) { + return; + } + runAfterCommit(new HashSet<>(keys), false); + } + + /** 成本同步等按时间范围影响:按 shop+日 enqueue */ + public void afterOrdersAffectedInRange(Long companyId, Long shopId, + LocalDateTime start, LocalDateTime end) { + if (companyId == null || shopId == null || start == null || end == null) { + return; + } + LocalDate d0 = start.atZone(STAT_ZONE).toLocalDate(); + LocalDate d1 = end.atZone(STAT_ZONE).toLocalDate(); + Set keys = new HashSet<>(); + for (LocalDate d = d0; !d.isAfter(d1); d = d.plusDays(1)) { + keys.add(new StatDirtyKey(companyId, shopId, d)); + } + runAfterCommit(keys, keys.size() <= 3); + } + + private void runAfterCommit(Set keys, boolean sync) { + if (keys.isEmpty()) { + return; + } + Runnable task = () -> executeRefresh(keys, sync); + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { + @Override + public void afterCommit() { + task.run(); + } + }); + } else { + task.run(); + } + } + + private void executeRefresh(Set keys, boolean sync) { + if (sync) { + for (StatDirtyKey k : keys) { + try { + orderStatRefreshService.refreshShopDay(k.companyId(), k.shopId(), k.statDate()); + } catch (Exception e) { + log.warn("sync refresh failed, fallback enqueue: {}", k, e); + orderStatRefreshCoordinator.enqueueDirtyKeys(Set.of(k), RefreshSource.CRUD); + } + } + } else { + orderStatRefreshCoordinator.enqueueDirtyKeys(keys, RefreshSource.CRUD); + } + } + + private static void addKey(Set keys, OrderPO order) { + if (order == null || order.getCompanyId() == null || order.getShopId() == null + || order.getOrderTime() == null) { + return; + } + LocalDate d = order.getOrderTime().atZone(STAT_ZONE).toLocalDate(); + keys.add(new StatDirtyKey(order.getCompanyId(), order.getShopId(), d)); + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatOverviewAssembler.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatOverviewAssembler.java new file mode 100644 index 00000000..ed4ba23d --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatOverviewAssembler.java @@ -0,0 +1,195 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service; + +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Service; +import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO; +import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets; +import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.vo.CompanyOverviewVO; +import top.xyquan.ecomdmbbackend.modules.ecom.overview.service.CompanyOverviewService; +import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** + * 基于汇总表的概览 VO 组装(公司/店铺/商品概览读路径切换共用)。 + */ +@Service +public class OrderStatOverviewAssembler { + + private final OrderStatReadFacade orderStatReadFacade; + private final CompanyOverviewService companyOverviewService; + + public OrderStatOverviewAssembler(OrderStatReadFacade orderStatReadFacade, + @Lazy CompanyOverviewService companyOverviewService) { + this.orderStatReadFacade = orderStatReadFacade; + this.companyOverviewService = companyOverviewService; + } + + /** 公司全店概览(汇总表读路径) */ + public CompanyOverviewVO buildCompanyOverview(Long companyId, List shops, + LocalDate startDate, LocalDate endDate, + BigDecimal taxRate, OrderStatusStatSets stat) { + List shopIds = shops.stream().map(ShopPO::getId).filter(Objects::nonNull).toList(); + OrderStatMetricsDTO cur = orderStatReadFacade.sumShopMetrics(companyId, shopIds, startDate, endDate); + LocalDate lastStart = startDate.minusMonths(1); + LocalDate lastEnd = endDate.minusMonths(1); + OrderStatMetricsDTO lastMonth = orderStatReadFacade.sumShopMetrics(companyId, shopIds, lastStart, lastEnd); + + BigDecimal totalSales = nz(cur.getSalesAmount()); + BigDecimal totalRefund = nz(cur.getRefundAmount()); + int totalOrderCount = cur.getSalesOrderCount() != null ? cur.getSalesOrderCount() : 0; + BigDecimal lastMonthSales = nz(lastMonth.getSalesAmount()); + + List promoRows = orderStatReadFacade.loadPromotionRows( + companyId, shopIds, startDate, endDate); + List brushRows = orderStatReadFacade.loadBrushRows( + companyId, shopIds, startDate.atStartOfDay(), endDate.atTime(23, 59, 59)); + BigDecimal totalPromo = promoRows.stream().map(r -> nz(r.getFeeAmount())).reduce(BigDecimal.ZERO, BigDecimal::add); + BigDecimal totalBrush = brushRows.stream().map(r -> nz(r.getBrushAmount())).reduce(BigDecimal.ZERO, BigDecimal::add); + + BigDecimal orderCost = nz(cur.getProductCost()).add(nz(cur.getFreightCost())).add(nz(cur.getOtherCost())); + BigDecimal profitBeforeTax = totalSales.subtract(orderCost).subtract(totalRefund).subtract(totalPromo).subtract(totalBrush); + BigDecimal tax = salesTaxOnNetSales(totalSales, totalRefund, taxRate); + BigDecimal profitAfterTax = profitBeforeTax.subtract(tax).setScale(2, RoundingMode.HALF_UP); + + CompanyOverviewVO vo = new CompanyOverviewVO(); + vo.setTotalSalesAmount(totalSales); + vo.setTotalOrderCount(totalOrderCount); + vo.setTotalPromotionFee(totalPromo); + vo.setTotalNetProfitAfterTax(profitAfterTax); + vo.setTotalTaxAmount(tax); + vo.setTotalProfitAfterTax(profitAfterTax); + vo.setMonthOverMonthGrowth(growthPct(totalSales, lastMonthSales)); + vo.setAverageFeeRatio(totalSales.signum() > 0 + ? totalPromo.divide(totalSales, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO); + vo.setTotalROI(totalPromo.signum() > 0 + ? totalSales.subtract(totalRefund).divide(totalPromo, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO); + + vo.setShopSalesRatios(buildShopSalesRatios(companyId, shopIds, shops, startDate, endDate, totalSales)); + vo.setSalesAmountTrend(buildSalesTrend(companyId, shopIds, startDate, endDate)); + vo.setOrderCountTrend(buildOrderTrend(companyId, shopIds, startDate, endDate)); + + List orderRows = orderStatReadFacade.loadShopProductRows( + companyId, shopIds, startDate, endDate, stat); + CompanyOverviewVO.WorkbenchTableBundle bundle = companyOverviewService.buildWorkbenchSummaryTablesFromAgg( + taxRate, companyId, shops, orderRows, promoRows, brushRows, startDate, endDate); + vo.setShopSummary(bundle.getShopTable()); + vo.setCategorySummary(bundle.getCategoryTable()); + vo.setPlatformSummary(bundle.getPlatformTable()); + vo.setShopEfficiencyQuadrants(buildShopEfficiency(bundle.getShopTable())); + return vo; + } + + private List buildShopSalesRatios(Long companyId, List shopIds, + List shops, + LocalDate start, LocalDate end, + BigDecimal totalSales) { + List byShop = orderStatReadFacade.sumShopMetricsByShop(companyId, shopIds, start, end); + Map salesMap = new HashMap<>(); + for (OrderStatMetricsDTO m : byShop) { + if (m.getShopId() != null) { + salesMap.put(m.getShopId(), nz(m.getSalesAmount())); + } + } + List list = new ArrayList<>(); + for (ShopPO shop : shops) { + BigDecimal sales = salesMap.getOrDefault(shop.getId(), BigDecimal.ZERO); + CompanyOverviewVO.ShopSalesRatio r = new CompanyOverviewVO.ShopSalesRatio(); + r.setShopId(shop.getId()); + r.setShopName(shop.getName()); + r.setSalesAmount(sales); + r.setRatio(totalSales.signum() > 0 + ? sales.divide(totalSales, 4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100)) + : BigDecimal.ZERO); + list.add(r); + } + list.sort((a, b) -> nz(b.getSalesAmount()).compareTo(nz(a.getSalesAmount()))); + return list; + } + + private CompanyOverviewVO.TrendData buildSalesTrend(Long companyId, List shopIds, + LocalDate start, LocalDate end) { + List daily = orderStatReadFacade.sumShopMetricsByDay(companyId, shopIds, start, end); + Map map = new HashMap<>(); + for (OrderStatMetricsDTO d : daily) { + if (d.getStatDate() != null) { + map.put(d.getStatDate(), nz(d.getSalesAmount())); + } + } + return fillTrend(start, end, map); + } + + private CompanyOverviewVO.TrendData buildOrderTrend(Long companyId, List shopIds, + LocalDate start, LocalDate end) { + List daily = orderStatReadFacade.sumShopMetricsByDay(companyId, shopIds, start, end); + Map map = new HashMap<>(); + for (OrderStatMetricsDTO d : daily) { + if (d.getStatDate() != null) { + map.put(d.getStatDate(), BigDecimal.valueOf(d.getSalesOrderCount() != null ? d.getSalesOrderCount() : 0)); + } + } + return fillTrend(start, end, map); + } + + private static CompanyOverviewVO.TrendData fillTrend(LocalDate start, LocalDate end, Map map) { + List items = new ArrayList<>(); + BigDecimal total = BigDecimal.ZERO; + for (LocalDate d = start; !d.isAfter(end); d = d.plusDays(1)) { + BigDecimal v = map.getOrDefault(d, BigDecimal.ZERO); + CompanyOverviewVO.TrendDataItem item = new CompanyOverviewVO.TrendDataItem(); + item.setDate(d); + item.setValue(v); + items.add(item); + total = total.add(v); + } + CompanyOverviewVO.TrendData trend = new CompanyOverviewVO.TrendData(); + trend.setDailyDataList(items); + trend.setTotal(total); + return trend; + } + + private static List buildShopEfficiency( + CompanyOverviewVO.ShopOverview shopOverview) { + if (shopOverview == null || shopOverview.getShops() == null) { + return List.of(); + } + List list = new ArrayList<>(); + for (CompanyOverviewVO.ShopSummary s : shopOverview.getShops()) { + CompanyOverviewVO.ShopEfficiencyQuadrant q = new CompanyOverviewVO.ShopEfficiencyQuadrant(); + q.setShopId(s.getShopId()); + q.setShopName(s.getShopName()); + q.setRoi(s.getRoi()); + q.setNetProfit(s.getProfitAfterTax()); + list.add(q); + } + return list; + } + + private static BigDecimal growthPct(BigDecimal cur, BigDecimal prev) { + if (prev.signum() > 0) { + return cur.subtract(prev).divide(prev, 4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100)); + } + return cur.signum() > 0 ? BigDecimal.valueOf(100) : BigDecimal.ZERO; + } + + private static BigDecimal salesTaxOnNetSales(BigDecimal sales, BigDecimal refund, BigDecimal taxRate) { + BigDecimal base = sales.subtract(refund); + if (base.signum() < 0) { + base = BigDecimal.ZERO; + } + BigDecimal rate = taxRate != null ? taxRate : new BigDecimal("0.04"); + return base.multiply(rate).setScale(2, RoundingMode.HALF_UP); + } + + private static BigDecimal nz(BigDecimal v) { + return v != null ? v : BigDecimal.ZERO; + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatQueryService.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatQueryService.java new file mode 100644 index 00000000..d31d67b4 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatQueryService.java @@ -0,0 +1,192 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.config.OrderStatProperties; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper.OrderStatQueryMapper; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support.RefreshSource; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.temporal.ChronoUnit; +import java.util.Collections; +import java.util.List; + +/** + * 统一读服务:按区间粒度路由日/月/年汇总表;{@code stat-source=order} 时由上层继续走明细聚合(Phase G 切换)。 + */ +@Service +public class OrderStatQueryService { + + private static final Logger log = LoggerFactory.getLogger(OrderStatQueryService.class); + + /** ≤90 天走日表 */ + private static final int DAILY_THRESHOLD_DAYS = 90; + /** ≤1095 天(约 3 年)走月表 */ + private static final int MONTHLY_THRESHOLD_DAYS = 1095; + + private final OrderStatProperties properties; + private final OrderStatQueryMapper orderStatQueryMapper; + private final OrderStatRefreshCoordinator orderStatRefreshCoordinator; + private final OrderMapper orderMapper; + + public OrderStatQueryService(OrderStatProperties properties, + OrderStatQueryMapper orderStatQueryMapper, + OrderStatRefreshCoordinator orderStatRefreshCoordinator, + OrderMapper orderMapper) { + this.properties = properties; + this.orderStatQueryMapper = orderStatQueryMapper; + this.orderStatRefreshCoordinator = orderStatRefreshCoordinator; + this.orderMapper = orderMapper; + } + + public boolean usesDailyStatSource() { + return "daily".equalsIgnoreCase(properties.getStatSource()); + } + + /** 店铺 KPI 合计(始终读日表) */ + public OrderStatMetricsDTO sumShopMetrics(Long companyId, List shopIds, + LocalDate startDate, LocalDate endDate) { + requireDailySource(); + ensureStatReady(companyId, shopIds, startDate, endDate); + OrderStatMetricsDTO row = orderStatQueryMapper.sumDailyShop(companyId, shopIds, startDate, endDate); + return row != null ? row : emptyMetrics(); + } + + public List sumShopMetricsByDay(Long companyId, List shopIds, + LocalDate startDate, LocalDate endDate) { + requireDailySource(); + ensureStatReady(companyId, shopIds, startDate, endDate); + List rows = orderStatQueryMapper.sumDailyShopByDay(companyId, shopIds, startDate, endDate); + return rows != null ? rows : Collections.emptyList(); + } + + public List sumShopMetricsByShop(Long companyId, List shopIds, + LocalDate startDate, LocalDate endDate) { + requireDailySource(); + ensureStatReady(companyId, shopIds, startDate, endDate); + List rows = orderStatQueryMapper.sumDailyShopByShop(companyId, shopIds, startDate, endDate); + return rows != null ? rows : Collections.emptyList(); + } + + public List sumProductMetricsByCategory(Long companyId, List shopIds, + LocalDate startDate, LocalDate endDate) { + requireDailySource(); + ensureStatReady(companyId, shopIds, startDate, endDate); + ProductGranularity g = resolveProductGranularity(startDate, endDate); + return switch (g) { + case DAILY -> nullSafe(orderStatQueryMapper.sumDailyProductByCategory( + companyId, shopIds, startDate, endDate)); + case MONTHLY -> nullSafe(orderStatQueryMapper.sumMonthlyProductByCategory( + companyId, shopIds, monthStart(startDate), monthStart(endDate))); + case YEARLY -> nullSafe(orderStatQueryMapper.sumYearlyProductByCategory( + companyId, shopIds, startDate.getYear(), endDate.getYear())); + }; + } + + public List sumProductMetricsByProduct(Long companyId, List shopIds, + LocalDate startDate, LocalDate endDate) { + requireDailySource(); + ensureStatReady(companyId, shopIds, startDate, endDate); + ProductGranularity g = resolveProductGranularity(startDate, endDate); + return switch (g) { + case DAILY -> nullSafe(orderStatQueryMapper.sumDailyProductByProduct( + companyId, shopIds, startDate, endDate)); + case MONTHLY -> nullSafe(orderStatQueryMapper.sumMonthlyProductByProduct( + companyId, shopIds, monthStart(startDate), monthStart(endDate))); + case YEARLY -> nullSafe(orderStatQueryMapper.sumYearlyProductByProduct( + companyId, shopIds, startDate.getYear(), endDate.getYear())); + }; + } + + public List sumSpecMetricsBySpec(Long companyId, List shopIds, Long productId, + LocalDate startDate, LocalDate endDate) { + requireDailySource(); + if (productId == null) { + return Collections.emptyList(); + } + ensureStatReady(companyId, shopIds, startDate, endDate); + ProductGranularity g = resolveProductGranularity(startDate, endDate); + return switch (g) { + case DAILY -> nullSafe(orderStatQueryMapper.sumDailySpecBySpec( + companyId, shopIds, productId, startDate, endDate)); + case MONTHLY -> nullSafe(orderStatQueryMapper.sumMonthlySpecBySpec( + companyId, shopIds, productId, monthStart(startDate), monthStart(endDate))); + case YEARLY -> nullSafe(orderStatQueryMapper.sumYearlySpecBySpec( + companyId, shopIds, productId, startDate.getYear(), endDate.getYear())); + }; + } + + /** + * 汇总行缺失且区间内有订单时,异步 enqueue refresh(不阻塞读路径)。 + *

+ * 若区间内无 ec_order 明细(如同比去年、未来日期),空汇总结果是正确口径,不应打日志或入队。 + */ + public void ensureStatReady(Long companyId, List shopIds, LocalDate startDate, LocalDate endDate) { + if (!properties.isAutoRefreshOnMiss() || shopIds == null || shopIds.isEmpty()) { + return; + } + if (orderStatQueryMapper.countDailyShopRows(companyId, shopIds, startDate, endDate) > 0) { + return; + } + int enqueuedShops = 0; + for (Long shopId : shopIds) { + List dates = orderMapper.selectDistinctOrderDatesByCompanyShopRange( + companyId, shopId, startDate, endDate); + if (dates == null || dates.isEmpty()) { + continue; + } + orderStatRefreshCoordinator.enqueueRefresh(companyId, shopId, dates, RefreshSource.AUTO_MISS); + enqueuedShops++; + } + if (enqueuedShops > 0) { + log.info("汇总表缺失且区间内有订单,已异步 enqueue refresh company={} shops={} {}~{}", + companyId, shopIds, startDate, endDate); + } + } + + private void requireDailySource() { + if (!usesDailyStatSource()) { + throw new IllegalStateException("order-stat.stat-source=order 时读路径尚未切换,请由上层走 OrderStatAggMapper"); + } + } + + private static ProductGranularity resolveProductGranularity(LocalDate startDate, LocalDate endDate) { + long days = ChronoUnit.DAYS.between(startDate, endDate) + 1; + if (days <= DAILY_THRESHOLD_DAYS) { + return ProductGranularity.DAILY; + } + if (days <= MONTHLY_THRESHOLD_DAYS) { + return ProductGranularity.MONTHLY; + } + return ProductGranularity.YEARLY; + } + + private static LocalDate monthStart(LocalDate date) { + return date.withDayOfMonth(1); + } + + private static List nullSafe(List rows) { + return rows != null ? rows : Collections.emptyList(); + } + + private static OrderStatMetricsDTO emptyMetrics() { + OrderStatMetricsDTO dto = new OrderStatMetricsDTO(); + dto.setSalesAmount(BigDecimal.ZERO); + dto.setRefundAmount(BigDecimal.ZERO); + dto.setSalesOrderCount(0); + dto.setProductCost(BigDecimal.ZERO); + dto.setFreightCost(BigDecimal.ZERO); + dto.setOtherCost(BigDecimal.ZERO); + dto.setGmvAmount(BigDecimal.ZERO); + dto.setGmvOrderCount(0); + return dto; + } + + private enum ProductGranularity { + DAILY, MONTHLY, YEARLY + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatReadFacade.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatReadFacade.java new file mode 100644 index 00000000..9c95b6f0 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatReadFacade.java @@ -0,0 +1,322 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service; + +import org.springframework.stereotype.Service; +import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.config.OrderStatProperties; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper.OrderStatQueryMapper; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support.OrderStatParamHelper; +import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets; +import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO; +import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopService; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * 读路径统一门面:{@code stat-source=daily} 走汇总表,否则回退 {@link OrderStatAggMapper} 扫明细。 + */ +@Service +public class OrderStatReadFacade { + + private final OrderStatProperties properties; + private final OrderStatQueryService orderStatQueryService; + private final OrderStatQueryMapper orderStatQueryMapper; + private final OrderStatAggMapper orderStatAggMapper; + private final ShopService shopService; + + public OrderStatReadFacade(OrderStatProperties properties, + OrderStatQueryService orderStatQueryService, + OrderStatQueryMapper orderStatQueryMapper, + OrderStatAggMapper orderStatAggMapper, + ShopService shopService) { + this.properties = properties; + this.orderStatQueryService = orderStatQueryService; + this.orderStatQueryMapper = orderStatQueryMapper; + this.orderStatAggMapper = orderStatAggMapper; + this.shopService = shopService; + } + + public boolean usesDailyStatSource() { + return "daily".equalsIgnoreCase(properties.getStatSource()); + } + + /** 工作台/概览共用:shop×product 聚合行 */ + public List loadShopProductRows(Long companyId, List shopIds, + LocalDate startDate, LocalDate endDate, + OrderStatusStatSets stat) { + if (!usesDailyStatSource()) { + return orderStatAggMapper.aggregateByShopProduct( + companyId, shopIds, startDate.atStartOfDay(), endDate.atTime(23, 59, 59), + OrderStatParamHelper.unionList(stat), OrderStatParamHelper.salesList(stat), + OrderStatParamHelper.refundList(stat), OrderStatParamHelper.productCostList(stat), + OrderStatParamHelper.freightCostList(stat), OrderStatParamHelper.otherCostList(stat)); + } + orderStatQueryService.ensureStatReady(companyId, shopIds, startDate, endDate); + Map platformByShop = platformByShop(shopIds); + List rows = orderStatQueryMapper.sumDailyProductByShopProduct( + companyId, shopIds, startDate, endDate); + if (rows == null || rows.isEmpty()) { + return Collections.emptyList(); + } + List out = new ArrayList<>(rows.size()); + for (OrderStatMetricsDTO m : rows) { + OrderStatAggMapper.ShopProductRow r = new OrderStatAggMapper.ShopProductRow(); + r.setShopId(m.getShopId()); + r.setPlatformId(platformByShop.get(m.getShopId())); + r.setProductId(m.getProductId()); + r.setCategoryId(m.getCategoryId()); + r.setSalesAmount(m.getSalesAmount()); + r.setRefundAmount(m.getRefundAmount()); + r.setOrderCount(m.getSalesOrderCount() != null ? m.getSalesOrderCount().longValue() : 0L); + r.setProductCost(m.getProductCost()); + r.setFreightCost(m.getFreightCost()); + r.setOtherCost(m.getOtherCost()); + r.setGmvAllStatus(BigDecimal.ZERO); + out.add(r); + } + return out; + } + + public List loadDailyRows(Long companyId, List shopIds, + LocalDate startDate, LocalDate endDate, + OrderStatusStatSets stat) { + if (!usesDailyStatSource()) { + return orderStatAggMapper.aggregateDaily( + companyId, shopIds, startDate.atStartOfDay(), endDate.atTime(23, 59, 59), + OrderStatParamHelper.unionList(stat), OrderStatParamHelper.salesList(stat), + OrderStatParamHelper.refundList(stat), OrderStatParamHelper.productCostList(stat), + OrderStatParamHelper.freightCostList(stat), OrderStatParamHelper.otherCostList(stat)); + } + orderStatQueryService.ensureStatReady(companyId, shopIds, startDate, endDate); + List rows = orderStatQueryService.sumShopMetricsByDay( + companyId, shopIds, startDate, endDate); + List out = new ArrayList<>(); + for (OrderStatMetricsDTO m : rows) { + OrderStatAggMapper.DailyRow r = new OrderStatAggMapper.DailyRow(); + r.setStatDate(m.getStatDate()); + r.setSalesAmount(m.getSalesAmount()); + r.setRefundAmount(m.getRefundAmount()); + r.setProductCost(m.getProductCost()); + r.setFreightCost(m.getFreightCost()); + r.setOtherCost(m.getOtherCost()); + out.add(r); + } + return out; + } + + /** 三段时间 KPI(当前/环比/同比) */ + public OrderStatAggMapper.PeriodKpiRow loadPeriodKpi(Long companyId, List shopIds, + LocalDate curStart, LocalDate curEnd, + LocalDate prevStart, LocalDate prevEnd, + LocalDate yoyStart, LocalDate yoyEnd, + OrderStatusStatSets stat) { + if (!usesDailyStatSource()) { + LocalDateTime scanStart = minTime(prevStart, yoyStart, curStart); + LocalDateTime scanEnd = maxTime(prevEnd, yoyEnd, curEnd); + OrderStatAggMapper.PeriodKpiRow row = orderStatAggMapper.aggregatePeriodKpi( + companyId, shopIds, scanStart, scanEnd, + curStart.atStartOfDay(), curEnd.atTime(23, 59, 59), + prevStart.atStartOfDay(), prevEnd.atTime(23, 59, 59), + yoyStart.atStartOfDay(), yoyEnd.atTime(23, 59, 59), + OrderStatParamHelper.unionList(stat), OrderStatParamHelper.salesList(stat), + OrderStatParamHelper.refundList(stat), OrderStatParamHelper.productCostList(stat), + OrderStatParamHelper.freightCostList(stat), OrderStatParamHelper.otherCostList(stat)); + return row != null ? row : new OrderStatAggMapper.PeriodKpiRow(); + } + OrderStatMetricsDTO cur = orderStatQueryService.sumShopMetrics(companyId, shopIds, curStart, curEnd); + OrderStatMetricsDTO prev = orderStatQueryService.sumShopMetrics(companyId, shopIds, prevStart, prevEnd); + OrderStatMetricsDTO yoy = orderStatQueryService.sumShopMetrics(companyId, shopIds, yoyStart, yoyEnd); + OrderStatAggMapper.PeriodKpiRow row = new OrderStatAggMapper.PeriodKpiRow(); + fillPeriodSlice(row, cur, Period.CUR); + fillPeriodSlice(row, prev, Period.PREV); + fillPeriodSlice(row, yoy, Period.YOY); + return row; + } + + public OrderStatMetricsDTO sumShopMetrics(Long companyId, List shopIds, + LocalDate startDate, LocalDate endDate) { + if (!usesDailyStatSource()) { + OrderStatusStatSets stat = OrderStatusStatSets.from(List.of()); + List rows = loadShopProductRows(companyId, shopIds, startDate, endDate, stat); + OrderStatMetricsDTO dto = new OrderStatMetricsDTO(); + BigDecimal sales = BigDecimal.ZERO, refund = BigDecimal.ZERO; + BigDecimal pc = BigDecimal.ZERO, fc = BigDecimal.ZERO, oc = BigDecimal.ZERO; + int cnt = 0; + for (OrderStatAggMapper.ShopProductRow r : rows) { + sales = sales.add(nz(r.getSalesAmount())); + refund = refund.add(nz(r.getRefundAmount())); + pc = pc.add(nz(r.getProductCost())); + fc = fc.add(nz(r.getFreightCost())); + oc = oc.add(nz(r.getOtherCost())); + cnt += r.getOrderCount() != null ? r.getOrderCount().intValue() : 0; + } + dto.setSalesAmount(sales); + dto.setRefundAmount(refund); + dto.setSalesOrderCount(cnt); + dto.setProductCost(pc); + dto.setFreightCost(fc); + dto.setOtherCost(oc); + return dto; + } + return orderStatQueryService.sumShopMetrics(companyId, shopIds, startDate, endDate); + } + + public List sumShopMetricsByDay(Long companyId, List shopIds, + LocalDate startDate, LocalDate endDate) { + if (!usesDailyStatSource()) { + return Collections.emptyList(); + } + return orderStatQueryService.sumShopMetricsByDay(companyId, shopIds, startDate, endDate); + } + + public List sumShopMetricsByShop(Long companyId, List shopIds, + LocalDate startDate, LocalDate endDate) { + if (!usesDailyStatSource()) { + return Collections.emptyList(); + } + orderStatQueryService.ensureStatReady(companyId, shopIds, startDate, endDate); + List rows = orderStatQueryMapper.sumDailyShopByShop( + companyId, shopIds, startDate, endDate); + return rows != null ? rows : Collections.emptyList(); + } + + public OrderStatMetricsDTO sumProductForOne(Long companyId, List shopIds, Long productId, + LocalDate startDate, LocalDate endDate) { + if (!usesDailyStatSource()) { + return new OrderStatMetricsDTO(); + } + orderStatQueryService.ensureStatReady(companyId, shopIds, startDate, endDate); + OrderStatMetricsDTO row = orderStatQueryMapper.sumDailyProductForOneProduct( + companyId, shopIds, productId, startDate, endDate); + return row != null ? row : new OrderStatMetricsDTO(); + } + + public List sumProductByDayForOne(Long companyId, List shopIds, Long productId, + LocalDate startDate, LocalDate endDate) { + if (!usesDailyStatSource()) { + return Collections.emptyList(); + } + orderStatQueryService.ensureStatReady(companyId, shopIds, startDate, endDate); + List rows = orderStatQueryMapper.sumDailyProductByDayForOneProduct( + companyId, shopIds, productId, startDate, endDate); + return rows != null ? rows : Collections.emptyList(); + } + + public List sumSpecMetrics(Long companyId, List shopIds, Long productId, + LocalDate startDate, LocalDate endDate) { + if (!usesDailyStatSource()) { + return Collections.emptyList(); + } + return orderStatQueryService.sumSpecMetricsBySpec(companyId, shopIds, productId, startDate, endDate); + } + + /** 推广/刷单仍走明细表 SQL(数据量小) */ + public List loadPromotionRows(Long companyId, List shopIds, + LocalDate startDate, LocalDate endDate) { + List rows = orderStatAggMapper.aggregatePromotionFees( + companyId, shopIds, startDate, endDate); + return rows != null ? rows : Collections.emptyList(); + } + + public List loadBrushRows(Long companyId, List shopIds, + LocalDateTime start, LocalDateTime end) { + List rows = orderStatAggMapper.aggregateBrushFees( + companyId, shopIds, start, end); + return rows != null ? rows : Collections.emptyList(); + } + + public OrderStatAggMapper.FeeKpiRow loadPromotionPeriodKpi(Long companyId, List shopIds, + LocalDate scanStart, LocalDate scanEnd, + LocalDate curStart, LocalDate curEnd, + LocalDate prevStart, LocalDate prevEnd, + LocalDate yoyStart, LocalDate yoyEnd) { + OrderStatAggMapper.FeeKpiRow row = orderStatAggMapper.aggregatePromotionPeriodKpi( + companyId, shopIds, scanStart, scanEnd, curStart, curEnd, prevStart, prevEnd, yoyStart, yoyEnd); + return row != null ? row : new OrderStatAggMapper.FeeKpiRow(); + } + + public OrderStatAggMapper.FeeKpiRow loadBrushPeriodKpi(Long companyId, List shopIds, + LocalDateTime scanStart, LocalDateTime scanEnd, + LocalDateTime curStart, LocalDateTime curEnd, + LocalDateTime prevStart, LocalDateTime prevEnd, + LocalDateTime yoyStart, LocalDateTime yoyEnd) { + OrderStatAggMapper.FeeKpiRow row = orderStatAggMapper.aggregateBrushPeriodKpi( + companyId, shopIds, scanStart, scanEnd, curStart, curEnd, prevStart, prevEnd, yoyStart, yoyEnd); + return row != null ? row : new OrderStatAggMapper.FeeKpiRow(); + } + + private Map platformByShop(List shopIds) { + if (shopIds == null || shopIds.isEmpty()) { + return Map.of(); + } + return shopService.listByIds(shopIds).stream() + .collect(Collectors.toMap(ShopPO::getId, s -> s.getPlatformId() != null ? s.getPlatformId() : 0L, (a, b) -> a)); + } + + private enum Period { CUR, PREV, YOY } + + private static void fillPeriodSlice(OrderStatAggMapper.PeriodKpiRow row, OrderStatMetricsDTO m, Period p) { + switch (p) { + case CUR -> { + row.setCurSalesAmount(nz(m.getSalesAmount())); + row.setCurOrderCount(m.getSalesOrderCount() != null ? m.getSalesOrderCount().longValue() : 0L); + row.setCurRefundAmount(nz(m.getRefundAmount())); + row.setCurProductCost(nz(m.getProductCost())); + row.setCurFreightCost(nz(m.getFreightCost())); + row.setCurOtherCost(nz(m.getOtherCost())); + row.setCurGmvAllStatus(nz(m.getGmvAmount())); + } + case PREV -> { + row.setPrevSalesAmount(nz(m.getSalesAmount())); + row.setPrevOrderCount(m.getSalesOrderCount() != null ? m.getSalesOrderCount().longValue() : 0L); + row.setPrevRefundAmount(nz(m.getRefundAmount())); + row.setPrevProductCost(nz(m.getProductCost())); + row.setPrevFreightCost(nz(m.getFreightCost())); + row.setPrevOtherCost(nz(m.getOtherCost())); + row.setPrevGmvAllStatus(nz(m.getGmvAmount())); + } + case YOY -> { + row.setYoySalesAmount(nz(m.getSalesAmount())); + row.setYoyOrderCount(m.getSalesOrderCount() != null ? m.getSalesOrderCount().longValue() : 0L); + row.setYoyRefundAmount(nz(m.getRefundAmount())); + row.setYoyProductCost(nz(m.getProductCost())); + row.setYoyFreightCost(nz(m.getFreightCost())); + row.setYoyOtherCost(nz(m.getOtherCost())); + row.setYoyGmvAllStatus(nz(m.getGmvAmount())); + } + } + } + + private static LocalDateTime minTime(LocalDate... dates) { + LocalDateTime min = dates[0].atStartOfDay(); + for (int i = 1; i < dates.length; i++) { + LocalDateTime t = dates[i].atStartOfDay(); + if (t.isBefore(min)) { + min = t; + } + } + return min; + } + + private static LocalDateTime maxTime(LocalDate... dates) { + LocalDateTime max = dates[0].atTime(23, 59, 59); + for (int i = 1; i < dates.length; i++) { + LocalDateTime t = dates[i].atTime(23, 59, 59); + if (t.isAfter(max)) { + max = t; + } + } + return max; + } + + private static BigDecimal nz(BigDecimal v) { + return v != null ? v : BigDecimal.ZERO; + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatRebuildService.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatRebuildService.java new file mode 100644 index 00000000..1424a984 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatRebuildService.java @@ -0,0 +1,114 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper.OrderStatRebuildTaskMapper; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.OrderStatRebuildTaskPO; +import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO; +import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopService; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** + * 历史订单 backfill:按 shop × date 调用 {@link OrderStatRefreshService#refreshShopDay}。 + */ +@Service +public class OrderStatRebuildService extends ServiceImpl { + + private static final Logger log = LoggerFactory.getLogger(OrderStatRebuildService.class); + + private final ShopService shopService; + private final OrderMapper orderMapper; + private final OrderStatRefreshService orderStatRefreshService; + private final FeeStatRefreshService feeStatRefreshService; + private final ExecutorService executor = Executors.newSingleThreadExecutor(r -> { + Thread t = new Thread(r, "order-stat-rebuild"); + t.setDaemon(true); + return t; + }); + + public OrderStatRebuildService(ShopService shopService, + OrderMapper orderMapper, + OrderStatRefreshService orderStatRefreshService, + FeeStatRefreshService feeStatRefreshService) { + this.shopService = shopService; + this.orderMapper = orderMapper; + this.orderStatRefreshService = orderStatRefreshService; + this.feeStatRefreshService = feeStatRefreshService; + } + + /** 创建 rebuild 任务并异步执行 */ + public Long scheduleRebuild(Long companyId, Long shopId, LocalDate startDate, LocalDate endDate) { + OrderStatRebuildTaskPO task = new OrderStatRebuildTaskPO(); + task.setCompanyId(companyId); + task.setShopId(shopId); + task.setStartDate(startDate); + task.setEndDate(endDate); + task.setGranularity("all"); + task.setStatus("pending"); + save(task); + Long taskId = task.getId(); + executor.submit(() -> runRebuild(taskId)); + return taskId; + } + + public OrderStatRebuildTaskPO getTask(Long taskId) { + return getById(taskId); + } + + private void runRebuild(Long taskId) { + OrderStatRebuildTaskPO task = getById(taskId); + if (task == null) { + return; + } + task.setStatus("running"); + updateById(task); + try { + List shopIds = resolveShopIds(task.getCompanyId(), task.getShopId()); + LocalDate cursor = task.getProgressDate() != null ? task.getProgressDate() : task.getStartDate(); + if (cursor.isBefore(task.getStartDate())) { + cursor = task.getStartDate(); + } + for (Long shopId : shopIds) { + List dates = orderMapper.selectDistinctOrderDatesByCompanyShopRange( + task.getCompanyId(), shopId, task.getStartDate(), task.getEndDate()); + if (dates == null) { + dates = new ArrayList<>(); + } + for (LocalDate d : dates) { + if (d.isBefore(cursor)) { + continue; + } + orderStatRefreshService.refreshShopDay(task.getCompanyId(), shopId, d); + feeStatRefreshService.refreshShopDay(task.getCompanyId(), shopId, d); + task.setProgressDate(d); + updateById(task); + } + } + task.setStatus("done"); + task.setProgressDate(task.getEndDate()); + updateById(task); + } catch (Exception e) { + log.error("rebuild task {} failed", taskId, e); + task.setStatus("failed"); + task.setErrorMessage(e.getMessage()); + updateById(task); + } + } + + private List resolveShopIds(Long companyId, Long shopId) { + if (shopId != null) { + return List.of(shopId); + } + return shopService.list(new LambdaQueryWrapper().eq(ShopPO::getCompanyId, companyId)) + .stream().map(ShopPO::getId).toList(); + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatReconcileService.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatReconcileService.java new file mode 100644 index 00000000..93df49e5 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatReconcileService.java @@ -0,0 +1,177 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper; +import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO; +import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatResolver; +import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets; +import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO; +import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopService; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Random; + +/** + * 汇总表 vs 明细聚合对账(抽样 shop×date)。 + */ +@Service +public class OrderStatReconcileService { + + private static final Logger log = LoggerFactory.getLogger(OrderStatReconcileService.class); + private static final BigDecimal TOLERANCE = new BigDecimal("0.01"); + + private final OrderStatReadFacade orderStatReadFacade; + private final OrderStatAggMapper orderStatAggMapper; + private final OrderStatusStatResolver orderStatusStatResolver; + private final OrderMapper orderMapper; + private final ShopService shopService; + + public OrderStatReconcileService(OrderStatReadFacade orderStatReadFacade, + OrderStatAggMapper orderStatAggMapper, + OrderStatusStatResolver orderStatusStatResolver, + OrderMapper orderMapper, + ShopService shopService) { + this.orderStatReadFacade = orderStatReadFacade; + this.orderStatAggMapper = orderStatAggMapper; + this.orderStatusStatResolver = orderStatusStatResolver; + this.orderMapper = orderMapper; + this.shopService = shopService; + } + + public ReconcileReport reconcileCompany(Long companyId, LocalDate startDate, LocalDate endDate, int sampleSize) { + ReconcileReport report = new ReconcileReport(); + report.setCompanyId(companyId); + report.setStartDate(startDate); + report.setEndDate(endDate); + if (!orderStatReadFacade.usesDailyStatSource()) { + report.setMessage("stat-source=order,跳过对账"); + return report; + } + List shops = shopService.lambdaQuery().eq(ShopPO::getCompanyId, companyId).list(); + if (shops.isEmpty()) { + report.setMessage("无店铺"); + return report; + } + OrderStatusStatSets stat = orderStatusStatResolver.resolve(companyId); + List samples = pickSamples(companyId, shops, startDate, endDate, sampleSize); + for (SampleKey s : samples) { + ReconcileItem item = reconcileOne(companyId, s.shopId(), s.statDate(), stat); + report.getItems().add(item); + if (!item.isMatch()) { + report.setMismatchCount(report.getMismatchCount() + 1); + } + } + report.setSampleCount(samples.size()); + report.setPassed(report.getMismatchCount() == 0); + log.info("reconcile company={} samples={} mismatch={}", companyId, samples.size(), report.getMismatchCount()); + return report; + } + + private ReconcileItem reconcileOne(Long companyId, Long shopId, LocalDate d, OrderStatusStatSets stat) { + OrderStatMetricsDTO daily = orderStatReadFacade.sumShopMetrics(companyId, List.of(shopId), d, d); + List rows = orderStatAggMapper.aggregateByShopProduct( + companyId, List.of(shopId), d.atStartOfDay(), d.atTime(23, 59, 59), + stat.getUnionStatusIds(), list(stat.getSalesIds()), list(stat.getRefundIds()), + list(stat.getProductCostIds()), list(stat.getFreightCostIds()), list(stat.getOtherCostIds())); + BigDecimal aggSales = BigDecimal.ZERO; + for (OrderStatAggMapper.ShopProductRow r : rows) { + aggSales = aggSales.add(nz(r.getSalesAmount())); + } + ReconcileItem item = new ReconcileItem(); + item.setShopId(shopId); + item.setStatDate(d); + item.setStatSales(nz(daily.getSalesAmount())); + item.setAggSales(aggSales); + item.setDiff(item.getStatSales().subtract(item.getAggSales()).abs()); + item.setMatch(item.getDiff().compareTo(TOLERANCE) <= 0); + return item; + } + + private List pickSamples(Long companyId, List shops, + LocalDate start, LocalDate end, int sampleSize) { + List pool = new ArrayList<>(); + for (ShopPO shop : shops) { + List dates = orderMapper.selectDistinctOrderDatesByCompanyShopRange( + companyId, shop.getId(), start, end); + if (dates == null) { + continue; + } + for (LocalDate d : dates) { + pool.add(new SampleKey(shop.getId(), d)); + } + } + if (pool.isEmpty()) { + return Collections.emptyList(); + } + Collections.shuffle(pool, new Random(42)); + return pool.subList(0, Math.min(sampleSize, pool.size())); + } + + private static List list(java.util.Set ids) { + return ids == null ? List.of() : new ArrayList<>(ids); + } + + private static BigDecimal nz(BigDecimal v) { + return v != null ? v : BigDecimal.ZERO; + } + + private record SampleKey(Long shopId, LocalDate statDate) {} + + public static class ReconcileReport { + private Long companyId; + private LocalDate startDate; + private LocalDate endDate; + private int sampleCount; + private int mismatchCount; + private boolean passed; + private String message; + private List items = new ArrayList<>(); + + public Long getCompanyId() { return companyId; } + public void setCompanyId(Long companyId) { this.companyId = companyId; } + public LocalDate getStartDate() { return startDate; } + public void setStartDate(LocalDate startDate) { this.startDate = startDate; } + public LocalDate getEndDate() { return endDate; } + public void setEndDate(LocalDate endDate) { this.endDate = endDate; } + public int getSampleCount() { return sampleCount; } + public void setSampleCount(int sampleCount) { this.sampleCount = sampleCount; } + public int getMismatchCount() { return mismatchCount; } + public void setMismatchCount(int mismatchCount) { this.mismatchCount = mismatchCount; } + public boolean isPassed() { return passed; } + public void setPassed(boolean passed) { this.passed = passed; } + public String getMessage() { return message; } + public void setMessage(String message) { this.message = message; } + public List getItems() { return items; } + public void setItems(List items) { this.items = items; } + } + + public static class ReconcileItem { + private Long shopId; + private LocalDate statDate; + private BigDecimal statSales; + private BigDecimal aggSales; + private BigDecimal diff; + private boolean match; + + public Long getShopId() { return shopId; } + public void setShopId(Long shopId) { this.shopId = shopId; } + public LocalDate getStatDate() { return statDate; } + public void setStatDate(LocalDate statDate) { this.statDate = statDate; } + public BigDecimal getStatSales() { return statSales; } + public void setStatSales(BigDecimal statSales) { this.statSales = statSales; } + public BigDecimal getAggSales() { return aggSales; } + public void setAggSales(BigDecimal aggSales) { this.aggSales = aggSales; } + public BigDecimal getDiff() { return diff; } + public void setDiff(BigDecimal diff) { this.diff = diff.setScale(2, RoundingMode.HALF_UP); } + public boolean isMatch() { return match; } + public void setMatch(boolean match) { this.match = match; } + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatRefreshCoordinator.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatRefreshCoordinator.java new file mode 100644 index 00000000..4dc15806 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatRefreshCoordinator.java @@ -0,0 +1,97 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper.OrderStatRefreshMapper; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.OrderStatRefreshQueuePO; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support.RefreshSource; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support.StatDirtyKey; + +import java.time.LocalDate; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; + +/** + * 汇总 refresh 入队与任务锁定(DB 队列,与导入消费者解耦)。 + */ +@Service +public class OrderStatRefreshCoordinator extends ServiceImpl { + + private static final Logger log = LoggerFactory.getLogger(OrderStatRefreshCoordinator.class); + private static final int MAX_RETRY = 3; + + private final OrderStatRefreshMapper orderStatRefreshMapper; + private final OrderStatRefreshService orderStatRefreshService; + + public OrderStatRefreshCoordinator(OrderStatRefreshMapper orderStatRefreshMapper, + OrderStatRefreshService orderStatRefreshService) { + this.orderStatRefreshMapper = orderStatRefreshMapper; + this.orderStatRefreshService = orderStatRefreshService; + } + + /** 批量入队(去重:同维度 pending 仅一条) */ + public int enqueueRefresh(Long companyId, Long shopId, Collection statDates, RefreshSource source) { + if (companyId == null || shopId == null || statDates == null || statDates.isEmpty()) { + return 0; + } + Set unique = new HashSet<>(statDates); + int n = 0; + for (LocalDate d : unique) { + n += orderStatRefreshMapper.insertPendingIgnore(companyId, shopId, d, source.name()); + } + log.info("order-stat enqueue company={} shop={} dates={} inserted={}", companyId, shopId, unique.size(), n); + return n; + } + + public int enqueueDirtyKeys(Collection keys, RefreshSource source) { + if (keys == null || keys.isEmpty()) { + return 0; + } + int n = 0; + for (StatDirtyKey k : keys) { + n += orderStatRefreshMapper.insertPendingIgnore(k.companyId(), k.shopId(), k.statDate(), source.name()); + } + return n; + } + + /** 取一条 pending 并置为 running */ + @Transactional(rollbackFor = Exception.class) + public OrderStatRefreshQueuePO fetchAndLockPending() { + LambdaQueryWrapper q = new LambdaQueryWrapper<>(); + q.eq(OrderStatRefreshQueuePO::getStatus, "pending") + .orderByAsc(OrderStatRefreshQueuePO::getId) + .last("LIMIT 1 FOR UPDATE SKIP LOCKED"); + OrderStatRefreshQueuePO row = getOne(q); + if (row == null) { + return null; + } + row.setStatus("running"); + updateById(row); + return row; + } + + /** 执行单条队列任务 */ + public void processQueueItem(OrderStatRefreshQueuePO item) { + try { + orderStatRefreshService.refreshShopDay(item.getCompanyId(), item.getShopId(), item.getStatDate()); + orderStatRefreshMapper.markDone(item.getId()); + } catch (Exception e) { + int retry = (item.getRetryCount() != null ? item.getRetryCount() : 0) + 1; + log.error("order-stat refresh failed id={} company={} shop={} date={} retry={}", + item.getId(), item.getCompanyId(), item.getShopId(), item.getStatDate(), retry, e); + if (retry < MAX_RETRY) { + // 重新入队 pending + item.setStatus("pending"); + item.setRetryCount(retry); + updateById(item); + } else { + orderStatRefreshMapper.markFailed(item.getId(), retry); + } + } + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatRefreshService.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatRefreshService.java new file mode 100644 index 00000000..f506f472 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatRefreshService.java @@ -0,0 +1,233 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service; + +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper.OrderStatDailyMapper; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper.OrderStatRefreshMapper; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.OrderStatDailyProductPO; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.OrderStatDailyShopPO; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.OrderStatDailySpecPO; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support.OrderStatParamHelper; +import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatResolver; +import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets; +import top.xyquan.ecomdmbbackend.modules.ecom.shop.mapper.ShopMapper; +import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + +/** + * 单日单店重算:ec_order → 日汇总表,再触发月/年 rollup。 + */ +@Service +public class OrderStatRefreshService { + + private final OrderStatusStatResolver orderStatusStatResolver; + private final OrderStatAggMapper orderStatAggMapper; + private final OrderStatRefreshMapper orderStatRefreshMapper; + private final OrderStatDailyMapper orderStatDailyMapper; + private final OrderStatRollupService orderStatRollupService; + private final ShopMapper shopMapper; + + public OrderStatRefreshService(OrderStatusStatResolver orderStatusStatResolver, + OrderStatAggMapper orderStatAggMapper, + OrderStatRefreshMapper orderStatRefreshMapper, + OrderStatDailyMapper orderStatDailyMapper, + OrderStatRollupService orderStatRollupService, + ShopMapper shopMapper) { + this.orderStatusStatResolver = orderStatusStatResolver; + this.orderStatAggMapper = orderStatAggMapper; + this.orderStatRefreshMapper = orderStatRefreshMapper; + this.orderStatDailyMapper = orderStatDailyMapper; + this.orderStatRollupService = orderStatRollupService; + this.shopMapper = shopMapper; + } + + /** + * 重算指定自然日的店铺/商品/规格日表,并 rollup 对应月、年。 + */ + @Transactional(rollbackFor = Exception.class) + public void refreshShopDay(Long companyId, Long shopId, LocalDate statDate) { + OrderStatusStatSets stat = orderStatusStatResolver.resolve(companyId); + if (stat.isUnionEmpty()) { + writeEmptyShopDay(companyId, shopId, statDate); + orderStatDailyMapper.deleteDailyProduct(companyId, shopId, statDate); + orderStatDailyMapper.deleteDailySpec(companyId, shopId, statDate); + orderStatRollupService.rollupAfterDailyChange(companyId, shopId, statDate); + return; + } + + LocalDateTime start = statDate.atStartOfDay(); + LocalDateTime end = statDate.atTime(23, 59, 59); + List shopIds = List.of(shopId); + + List productRows = orderStatAggMapper.aggregateByShopProduct( + companyId, shopIds, start, end, + OrderStatParamHelper.unionList(stat), + OrderStatParamHelper.salesList(stat), + OrderStatParamHelper.refundList(stat), + OrderStatParamHelper.productCostList(stat), + OrderStatParamHelper.freightCostList(stat), + OrderStatParamHelper.otherCostList(stat)); + + Long platformId = resolvePlatformId(shopId); + Integer gmvOrderCount = orderStatRefreshMapper.countGmvOrdersByShopDay( + companyId, shopId, start, end); + OrderStatDailyShopPO shopRow = buildShopRow(companyId, shopId, platformId, statDate, productRows, + gmvOrderCount != null ? gmvOrderCount : 0); + orderStatDailyMapper.upsertDailyShop(shopRow); + + orderStatDailyMapper.deleteDailyProduct(companyId, shopId, statDate); + List dailyProducts = buildProductRows(companyId, shopId, statDate, productRows); + if (!dailyProducts.isEmpty()) { + orderStatDailyMapper.batchInsertDailyProduct(dailyProducts); + } + + orderStatDailyMapper.deleteDailySpec(companyId, shopId, statDate); + List specRows = orderStatRefreshMapper.aggregateSpecByShopDay( + companyId, shopId, start, end, + OrderStatParamHelper.unionList(stat), + OrderStatParamHelper.salesList(stat), + OrderStatParamHelper.refundList(stat), + OrderStatParamHelper.productCostList(stat), + OrderStatParamHelper.freightCostList(stat), + OrderStatParamHelper.otherCostList(stat)); + List dailySpecs = buildSpecRows(companyId, shopId, statDate, specRows); + if (!dailySpecs.isEmpty()) { + orderStatDailyMapper.batchInsertDailySpec(dailySpecs); + } + + orderStatRollupService.rollupAfterDailyChange(companyId, shopId, statDate); + } + + private Long resolvePlatformId(Long shopId) { + ShopPO shop = shopMapper.selectById(shopId); + return shop != null ? shop.getPlatformId() : null; + } + + private void writeEmptyShopDay(Long companyId, Long shopId, LocalDate statDate) { + OrderStatDailyShopPO row = new OrderStatDailyShopPO(); + row.setCompanyId(companyId); + row.setShopId(shopId); + row.setPlatformId(resolvePlatformId(shopId)); + row.setStatDate(statDate); + row.setSalesAmount(BigDecimal.ZERO); + row.setRefundAmount(BigDecimal.ZERO); + row.setSalesOrderCount(0); + row.setProductCost(BigDecimal.ZERO); + row.setFreightCost(BigDecimal.ZERO); + row.setOtherCost(BigDecimal.ZERO); + row.setGmvAmount(BigDecimal.ZERO); + row.setGmvOrderCount(0); + row.setStatVersion(0); + orderStatDailyMapper.upsertDailyShop(row); + } + + private static OrderStatDailyShopPO buildShopRow(Long companyId, Long shopId, Long platformId, + LocalDate statDate, + List rows, + int gmvOrderCount) { + BigDecimal sales = BigDecimal.ZERO; + BigDecimal refund = BigDecimal.ZERO; + BigDecimal pc = BigDecimal.ZERO; + BigDecimal fc = BigDecimal.ZERO; + BigDecimal oc = BigDecimal.ZERO; + BigDecimal gmv = BigDecimal.ZERO; + int orderCount = 0; + for (OrderStatAggMapper.ShopProductRow r : rows) { + sales = sales.add(nz(r.getSalesAmount())); + refund = refund.add(nz(r.getRefundAmount())); + pc = pc.add(nz(r.getProductCost())); + fc = fc.add(nz(r.getFreightCost())); + oc = oc.add(nz(r.getOtherCost())); + gmv = gmv.add(nz(r.getGmvAllStatus())); + orderCount += r.getOrderCount() != null ? r.getOrderCount().intValue() : 0; + } + OrderStatDailyShopPO row = new OrderStatDailyShopPO(); + row.setCompanyId(companyId); + row.setShopId(shopId); + row.setPlatformId(platformId); + row.setStatDate(statDate); + row.setSalesAmount(sales); + row.setRefundAmount(refund); + row.setSalesOrderCount(orderCount); + row.setProductCost(pc); + row.setFreightCost(fc); + row.setOtherCost(oc); + row.setGmvAmount(gmv); + row.setGmvOrderCount(gmvOrderCount); + row.setStatVersion(0); + return row; + } + + private static List buildProductRows(Long companyId, Long shopId, LocalDate statDate, + List rows) { + List list = new ArrayList<>(); + for (OrderStatAggMapper.ShopProductRow r : rows) { + if (isAllZeroProductRow(r)) { + continue; + } + OrderStatDailyProductPO p = new OrderStatDailyProductPO(); + p.setCompanyId(companyId); + p.setShopId(shopId); + p.setProductId(r.getProductId() != null ? r.getProductId() : 0L); + p.setCategoryId(r.getCategoryId() != null ? r.getCategoryId() : 0L); + p.setStatDate(statDate); + p.setSalesAmount(nz(r.getSalesAmount())); + p.setRefundAmount(nz(r.getRefundAmount())); + p.setSalesOrderCount(r.getOrderCount() != null ? r.getOrderCount().intValue() : 0); + p.setProductCost(nz(r.getProductCost())); + p.setFreightCost(nz(r.getFreightCost())); + p.setOtherCost(nz(r.getOtherCost())); + p.setStatVersion(0); + list.add(p); + } + return list; + } + + private static List buildSpecRows(Long companyId, Long shopId, LocalDate statDate, + List rows) { + List list = new ArrayList<>(); + for (OrderStatRefreshMapper.SpecDayRow r : rows) { + if (isAllZeroSpecRow(r)) { + continue; + } + OrderStatDailySpecPO s = new OrderStatDailySpecPO(); + s.setCompanyId(companyId); + s.setShopId(shopId); + s.setProductId(r.getProductId() != null ? r.getProductId() : 0L); + s.setProductSpecId(r.getProductSpecId() != null ? r.getProductSpecId() : 0L); + s.setStatDate(statDate); + s.setSalesAmount(nz(r.getSalesAmount())); + s.setRefundAmount(nz(r.getRefundAmount())); + s.setSalesOrderCount(r.getOrderCount() != null ? r.getOrderCount().intValue() : 0); + s.setQuantitySum(r.getQuantitySum() != null ? r.getQuantitySum() : 0); + s.setProductCost(nz(r.getProductCost())); + s.setFreightCost(nz(r.getFreightCost())); + s.setOtherCost(nz(r.getOtherCost())); + s.setStatVersion(0); + list.add(s); + } + return list; + } + + private static boolean isAllZeroProductRow(OrderStatAggMapper.ShopProductRow r) { + return nz(r.getSalesAmount()).signum() == 0 + && nz(r.getRefundAmount()).signum() == 0 + && (r.getOrderCount() == null || r.getOrderCount() == 0); + } + + private static boolean isAllZeroSpecRow(OrderStatRefreshMapper.SpecDayRow r) { + return nz(r.getSalesAmount()).signum() == 0 + && nz(r.getRefundAmount()).signum() == 0 + && (r.getOrderCount() == null || r.getOrderCount() == 0); + } + + private static BigDecimal nz(BigDecimal v) { + return v != null ? v : BigDecimal.ZERO; + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatRefreshWorker.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatRefreshWorker.java new file mode 100644 index 00000000..ce0d28a0 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatRefreshWorker.java @@ -0,0 +1,91 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service; + +import jakarta.annotation.PreDestroy; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.config.OrderStatProperties; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.OrderStatRefreshQueuePO; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * 异步消费 ec_order_stat_refresh_queue(独立线程池,不与导入消费者共用)。 + */ +@Service +public class OrderStatRefreshWorker { + + private static final Logger log = LoggerFactory.getLogger(OrderStatRefreshWorker.class); + + private final OrderStatProperties properties; + private final OrderStatRefreshCoordinator coordinator; + private final ExecutorService executorService; + private final AtomicBoolean running = new AtomicBoolean(false); + + public OrderStatRefreshWorker(OrderStatProperties properties, + OrderStatRefreshCoordinator coordinator) { + this.properties = properties; + this.coordinator = coordinator; + int pool = Math.max(1, properties.getRefreshWorker().getPoolSize()); + this.executorService = Executors.newFixedThreadPool(pool); + } + + @jakarta.annotation.PostConstruct + public void start() { + if (!properties.getRefreshWorker().isEnabled()) { + log.info("OrderStatRefreshWorker disabled by config"); + return; + } + if (running.compareAndSet(false, true)) { + int pool = properties.getRefreshWorker().getPoolSize(); + for (int i = 0; i < pool; i++) { + executorService.submit(this::pollLoop); + } + log.info("OrderStatRefreshWorker started, poolSize={}", pool); + } + } + + @PreDestroy + public void stop() { + if (running.compareAndSet(true, false)) { + executorService.shutdown(); + try { + if (!executorService.awaitTermination(15, TimeUnit.SECONDS)) { + executorService.shutdownNow(); + } + } catch (InterruptedException e) { + executorService.shutdownNow(); + Thread.currentThread().interrupt(); + } + log.info("OrderStatRefreshWorker stopped"); + } + } + + private void pollLoop() { + long interval = Math.max(500L, properties.getRefreshWorker().getPollIntervalMs()); + while (running.get()) { + try { + OrderStatRefreshQueuePO item = coordinator.fetchAndLockPending(); + if (item != null) { + coordinator.processQueueItem(item); + } else { + Thread.sleep(interval); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + break; + } catch (Exception e) { + log.error("OrderStatRefreshWorker poll error", e); + try { + Thread.sleep(interval); + } catch (InterruptedException ie) { + Thread.currentThread().interrupt(); + break; + } + } + } + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatRollupService.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatRollupService.java new file mode 100644 index 00000000..a7a3e298 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatRollupService.java @@ -0,0 +1,30 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service; + +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper.OrderStatDailyMapper; + +import java.time.LocalDate; + +/** 日表变更后 rollup 月表、年表。 */ +@Service +public class OrderStatRollupService { + + private final OrderStatDailyMapper orderStatDailyMapper; + + public OrderStatRollupService(OrderStatDailyMapper orderStatDailyMapper) { + this.orderStatDailyMapper = orderStatDailyMapper; + } + + @Transactional(rollbackFor = Exception.class) + public void rollupAfterDailyChange(Long companyId, Long shopId, LocalDate statDate) { + LocalDate statMonth = statDate.withDayOfMonth(1); + int statYear = statDate.getYear(); + orderStatDailyMapper.rollupMonthlyShop(companyId, shopId, statMonth); + orderStatDailyMapper.rollupYearlyShop(companyId, shopId, statYear); + orderStatDailyMapper.rollupMonthlyProduct(companyId, shopId, statMonth); + orderStatDailyMapper.rollupYearlyProduct(companyId, shopId, statYear); + orderStatDailyMapper.rollupMonthlySpec(companyId, shopId, statMonth); + orderStatDailyMapper.rollupYearlySpec(companyId, shopId, statYear); + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/support/OrderStatParamHelper.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/support/OrderStatParamHelper.java new file mode 100644 index 00000000..74c8c7d8 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/support/OrderStatParamHelper.java @@ -0,0 +1,48 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support; + +import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Set; + +/** 将 OrderStatusStatSets 转为 MyBatis IN 列表参数。 */ +public final class OrderStatParamHelper { + + private OrderStatParamHelper() { + } + + public static List statusList(java.util.Collection ids) { + if (ids == null || ids.isEmpty()) { + return List.of(-1L); + } + List list = new ArrayList<>(ids); + Collections.sort(list); + return list; + } + + public static List unionList(OrderStatusStatSets stat) { + return statusList(stat.getUnionStatusIds()); + } + + public static List salesList(OrderStatusStatSets stat) { + return statusList(stat.getSalesIds()); + } + + public static List refundList(OrderStatusStatSets stat) { + return statusList(stat.getRefundIds()); + } + + public static List productCostList(OrderStatusStatSets stat) { + return statusList(stat.getProductCostIds()); + } + + public static List freightCostList(OrderStatusStatSets stat) { + return statusList(stat.getFreightCostIds()); + } + + public static List otherCostList(OrderStatusStatSets stat) { + return statusList(stat.getOtherCostIds()); + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/support/RefreshSource.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/support/RefreshSource.java new file mode 100644 index 00000000..69c743e5 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/support/RefreshSource.java @@ -0,0 +1,13 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support; + +/** + * 汇总 refresh 触发来源。 + */ +public enum RefreshSource { + IMPORT, + CRUD, + STATUS_CHANGE, + MANUAL, + BACKFILL, + AUTO_MISS +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/support/StatDirtyKey.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/support/StatDirtyKey.java new file mode 100644 index 00000000..8d5ff15d --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/support/StatDirtyKey.java @@ -0,0 +1,16 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support; + +import java.time.LocalDate; +import java.util.Objects; + +/** + * 待刷新维度:(公司, 店铺, 自然日)。 + */ +public record StatDirtyKey(Long companyId, Long shopId, LocalDate statDate) { + + public StatDirtyKey { + Objects.requireNonNull(companyId, "companyId"); + Objects.requireNonNull(shopId, "shopId"); + Objects.requireNonNull(statDate, "statDate"); + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/status/service/impl/OrderStatusServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/status/service/impl/OrderStatusServiceImpl.java index 1bd098c6..6e348986 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/status/service/impl/OrderStatusServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/status/service/impl/OrderStatusServiceImpl.java @@ -3,9 +3,12 @@ package top.xyquan.ecomdmbbackend.modules.ecom.order.status.service.impl; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.beans.BeanUtils; +import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import top.xyquan.ecomdmbbackend.common.exception.BusinessException; +import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatRebuildService; import top.xyquan.ecomdmbbackend.modules.ecom.order.status.mapper.OrderStatusMapper; import top.xyquan.ecomdmbbackend.modules.ecom.order.status.model.dto.CreateOrderStatusDTO; import top.xyquan.ecomdmbbackend.modules.ecom.order.status.model.dto.PatchOrderStatusDTO; @@ -15,7 +18,9 @@ import top.xyquan.ecomdmbbackend.modules.ecom.order.status.model.vo.OrderStatusV import top.xyquan.ecomdmbbackend.modules.ecom.order.status.service.OrderStatusService; import top.xyquan.ecomdmbbackend.utils.CurrentUserContext; +import java.time.LocalDate; import java.util.List; +import java.util.Objects; import java.util.stream.Collectors; /** @@ -25,9 +30,15 @@ import java.util.stream.Collectors; public class OrderStatusServiceImpl extends ServiceImpl implements OrderStatusService { private final CurrentUserContext currentUserContext; + private final OrderStatRebuildService orderStatRebuildService; + private final OrderMapper orderMapper; - public OrderStatusServiceImpl(CurrentUserContext currentUserContext) { + public OrderStatusServiceImpl(CurrentUserContext currentUserContext, + @Lazy OrderStatRebuildService orderStatRebuildService, + OrderMapper orderMapper) { this.currentUserContext = currentUserContext; + this.orderStatRebuildService = orderStatRebuildService; + this.orderMapper = orderMapper; } /** @@ -99,6 +110,9 @@ public class OrderStatusServiceImpl extends ServiceImpl orderWrapper = new LambdaQueryWrapper<>(); orderWrapper.eq(OrderPO::getCompanyId, companyId) diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/ShopOverviewStatisticsServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/ShopOverviewStatisticsServiceImpl.java index 086acdb5..0518c34f 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/ShopOverviewStatisticsServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/ShopOverviewStatisticsServiceImpl.java @@ -7,6 +7,10 @@ import top.xyquan.ecomdmbbackend.modules.ecom.brushorder.mapper.BrushOrderMapper import top.xyquan.ecomdmbbackend.modules.ecom.category.model.po.CategoryPO; import top.xyquan.ecomdmbbackend.modules.ecom.category.service.CategoryService; import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper; +import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatReadFacade; +import top.xyquan.ecomdmbbackend.modules.ecom.overview.service.CompanyOverviewService; import top.xyquan.ecomdmbbackend.modules.ecom.promotion.mapper.PromotionFeeMapper; import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.ShopOverviewQueryDTO; import top.xyquan.ecomdmbbackend.modules.ecom.brushorder.model.po.BrushOrderPO; @@ -20,6 +24,7 @@ import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.po.PromotionFeePO; import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO; import top.xyquan.ecomdmbbackend.modules.ecom.shop.monthlytarget.mapper.ShopMonthlyTargetMapper; import top.xyquan.ecomdmbbackend.modules.ecom.shop.monthlytarget.model.po.ShopMonthlyTargetPO; +import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.vo.CompanyOverviewVO; import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.vo.ShopOverviewStatisticsVO; import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductService; import top.xyquan.ecomdmbbackend.modules.ecom.overview.service.ShopOverviewStatisticsService; @@ -60,6 +65,8 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics private final ProductSpecMapper productSpecMapper; private final OrderStatusStatResolver orderStatusStatResolver; private final CategoryService categoryService; + private final OrderStatReadFacade orderStatReadFacade; + private final CompanyOverviewService companyOverviewService; public ShopOverviewStatisticsServiceImpl(CurrentUserContext currentUserContext, OrderMapper orderMapper, @@ -70,7 +77,9 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics ProductService productService, ProductSpecMapper productSpecMapper, OrderStatusStatResolver orderStatusStatResolver, - CategoryService categoryService) { + CategoryService categoryService, + OrderStatReadFacade orderStatReadFacade, + CompanyOverviewService companyOverviewService) { this.currentUserContext = currentUserContext; this.orderMapper = orderMapper; this.promotionFeeMapper = promotionFeeMapper; @@ -81,6 +90,8 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics this.productSpecMapper = productSpecMapper; this.orderStatusStatResolver = orderStatusStatResolver; this.categoryService = categoryService; + this.orderStatReadFacade = orderStatReadFacade; + this.companyOverviewService = companyOverviewService; } /** @@ -128,6 +139,10 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics throw new BusinessException("店铺不存在"); } + if (orderStatReadFacade.usesDailyStatSource()) { + return getShopOverviewFromStat(queryDTO, companyId, shop, startDate, endDate, stat); + } + // 查询订单数据(该店铺) LambdaQueryWrapper orderWrapper = new LambdaQueryWrapper<>(); orderWrapper.eq(OrderPO::getCompanyId, companyId) @@ -1013,5 +1028,165 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics total.setProfitAfterTax(profitAfterTax.setScale(2, RoundingMode.HALF_UP)); return total; } + + /** 汇总表读路径:单店概览 */ + private ShopOverviewStatisticsVO getShopOverviewFromStat(ShopOverviewQueryDTO queryDTO, + Long companyId, ShopPO shop, + LocalDate startDate, LocalDate endDate, + OrderStatusStatSets stat) { + List shopIds = List.of(queryDTO.getShopId()); + OrderStatMetricsDTO cur = orderStatReadFacade.sumShopMetrics(companyId, shopIds, startDate, endDate); + LocalDate lastStart = startDate.minusMonths(1); + LocalDate lastEnd = endDate.minusMonths(1); + OrderStatMetricsDTO lastMonth = orderStatReadFacade.sumShopMetrics(companyId, shopIds, lastStart, lastEnd); + + List promoRows = orderStatReadFacade.loadPromotionRows( + companyId, shopIds, startDate, endDate); + List brushRows = orderStatReadFacade.loadBrushRows( + companyId, shopIds, startDate.atStartOfDay(), endDate.atTime(23, 59, 59)); + BigDecimal totalPromo = promoRows.stream().map(r -> r.getFeeAmount() != null ? r.getFeeAmount() : BigDecimal.ZERO) + .reduce(BigDecimal.ZERO, BigDecimal::add); + BigDecimal totalBrush = brushRows.stream().map(r -> r.getBrushAmount() != null ? r.getBrushAmount() : BigDecimal.ZERO) + .reduce(BigDecimal.ZERO, BigDecimal::add); + + BigDecimal totalSales = cur.getSalesAmount() != null ? cur.getSalesAmount() : BigDecimal.ZERO; + BigDecimal refund = cur.getRefundAmount() != null ? cur.getRefundAmount() : BigDecimal.ZERO; + int orderCount = cur.getSalesOrderCount() != null ? cur.getSalesOrderCount() : 0; + BigDecimal orderCost = nz(cur.getProductCost()).add(nz(cur.getFreightCost())).add(nz(cur.getOtherCost())); + + ShopOverviewStatisticsVO vo = new ShopOverviewStatisticsVO(); + vo.setShopId(shop.getId()); + vo.setShopName(shop.getName()); + vo.setTotalSalesAmount(totalSales); + vo.setTotalOrderCount(orderCount); + vo.setRefundAmount(refund); + vo.setAverageOrderValue(orderCount > 0 + ? totalSales.divide(BigDecimal.valueOf(orderCount), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO); + vo.setTotalPromotionFee(totalPromo); + vo.setAverageFeeRatio(totalSales.signum() > 0 ? totalPromo.divide(totalSales, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO); + BigDecimal profitBeforeTax = totalSales.subtract(orderCost).subtract(refund).subtract(totalPromo).subtract(totalBrush); + vo.setTotalProfitBeforeTax(profitBeforeTax); + BigDecimal tax = toSalesTaxAmount(totalSales, refund); + vo.setTotalTaxAmount(tax); + vo.setTotalNetProfitAfterTax(profitBeforeTax.subtract(tax).setScale(2, RoundingMode.HALF_UP)); + vo.setTotalROI(totalPromo.signum() > 0 + ? totalSales.subtract(refund).divide(totalPromo, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO); + BigDecimal lastSales = lastMonth.getSalesAmount() != null ? lastMonth.getSalesAmount() : BigDecimal.ZERO; + if (lastSales.signum() > 0) { + vo.setMonthOverMonthGrowth(totalSales.subtract(lastSales).divide(lastSales, 4, RoundingMode.HALF_UP) + .multiply(new BigDecimal("100"))); + } else if (totalSales.signum() > 0) { + vo.setMonthOverMonthGrowth(new BigDecimal("100")); + } else { + vo.setMonthOverMonthGrowth(BigDecimal.ZERO); + } + + calculateTargetData(vo, companyId, queryDTO.getShopId(), startDate, endDate, totalSales, orderCount); + + List daily = orderStatReadFacade.sumShopMetricsByDay(companyId, shopIds, startDate, endDate); + vo.setSalesAmountTrend(buildShopTrendFromStat(daily, startDate, endDate, OrderStatMetricsDTO::getSalesAmount)); + vo.setOrderCountTrend(buildShopTrendFromStat(daily, startDate, endDate, + m -> BigDecimal.valueOf(m.getSalesOrderCount() != null ? m.getSalesOrderCount() : 0))); + + List orderRows = orderStatReadFacade.loadShopProductRows( + companyId, shopIds, startDate, endDate, stat); + CompanyOverviewVO.WorkbenchTableBundle bundle = companyOverviewService.buildWorkbenchSummaryTablesFromAgg( + taxRate, companyId, List.of(shop), orderRows, promoRows, brushRows, startDate, endDate); + vo.setProductOverview(mapProductOverview(bundle.getProductTable())); + vo.setCategoryOverview(mapCategoryOverview(bundle.getCategoryTable())); + fillProductSalesTop10(vo); + return vo; + } + + private ShopOverviewStatisticsVO.TrendData buildShopTrendFromStat(List daily, + LocalDate start, LocalDate end, + java.util.function.Function fn) { + Map map = new HashMap<>(); + for (OrderStatMetricsDTO d : daily) { + if (d.getStatDate() != null) { + map.put(d.getStatDate(), fn.apply(d)); + } + } + List items = new ArrayList<>(); + BigDecimal total = BigDecimal.ZERO; + for (LocalDate d = start; !d.isAfter(end); d = d.plusDays(1)) { + BigDecimal v = map.getOrDefault(d, BigDecimal.ZERO); + ShopOverviewStatisticsVO.TrendDataItem item = new ShopOverviewStatisticsVO.TrendDataItem(); + item.setDate(d); + item.setValue(v); + items.add(item); + total = total.add(v); + } + ShopOverviewStatisticsVO.TrendData trend = new ShopOverviewStatisticsVO.TrendData(); + trend.setDailyDataList(items); + trend.setTotal(total); + return trend; + } + + private static ShopOverviewStatisticsVO.ProductOverview mapProductOverview(CompanyOverviewVO.CategoryOverview table) { + if (table == null) { + return new ShopOverviewStatisticsVO.ProductOverview(); + } + ShopOverviewStatisticsVO.ProductOverview po = new ShopOverviewStatisticsVO.ProductOverview(); + po.setTotal(mapCategorySummaryToProductTotal(table.getTotal())); + if (table.getCategories() != null) { + po.setProducts(table.getCategories().stream().map(c -> { + ShopOverviewStatisticsVO.ProductSummary p = new ShopOverviewStatisticsVO.ProductSummary(); + p.setProductId(c.getCategoryId()); + p.setProductName(c.getCategoryName()); + p.setSalesAmount(c.getSalesAmount()); + p.setOrderCount(c.getOrderCount()); + p.setProfitAfterTax(c.getProfitAfterTax()); + return p; + }).collect(Collectors.toList())); + } + return po; + } + + private static ShopOverviewStatisticsVO.CategoryOverview mapCategoryOverview(CompanyOverviewVO.CategoryOverview table) { + if (table == null) { + return new ShopOverviewStatisticsVO.CategoryOverview(); + } + ShopOverviewStatisticsVO.CategoryOverview co = new ShopOverviewStatisticsVO.CategoryOverview(); + co.setTotal(mapCategorySummaryToShopCategoryTotal(table.getTotal())); + if (table.getCategories() != null) { + co.setCategories(table.getCategories().stream().map(c -> { + ShopOverviewStatisticsVO.CategorySummary s = new ShopOverviewStatisticsVO.CategorySummary(); + s.setCategoryId(c.getCategoryId()); + s.setCategoryName(c.getCategoryName()); + s.setSalesAmount(c.getSalesAmount()); + s.setOrderCount(c.getOrderCount()); + s.setProfitAfterTax(c.getProfitAfterTax()); + return s; + }).collect(Collectors.toList())); + } + return co; + } + + private static ShopOverviewStatisticsVO.ProductSummary mapCategorySummaryToProductTotal(CompanyOverviewVO.CategorySummary t) { + ShopOverviewStatisticsVO.ProductSummary p = new ShopOverviewStatisticsVO.ProductSummary(); + if (t == null) { + return p; + } + p.setSalesAmount(t.getSalesAmount()); + p.setOrderCount(t.getOrderCount()); + p.setProfitAfterTax(t.getProfitAfterTax()); + return p; + } + + private static ShopOverviewStatisticsVO.CategorySummary mapCategorySummaryToShopCategoryTotal(CompanyOverviewVO.CategorySummary t) { + ShopOverviewStatisticsVO.CategorySummary s = new ShopOverviewStatisticsVO.CategorySummary(); + if (t == null) { + return s; + } + s.setSalesAmount(t.getSalesAmount()); + s.setOrderCount(t.getOrderCount()); + s.setProfitAfterTax(t.getProfitAfterTax()); + return s; + } + + private static BigDecimal nz(BigDecimal v) { + return v != null ? v : BigDecimal.ZERO; + } } diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/product/overview/service/impl/ProductOverviewServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/product/overview/service/impl/ProductOverviewServiceImpl.java index 67f524f0..72663237 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/product/overview/service/impl/ProductOverviewServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/product/overview/service/impl/ProductOverviewServiceImpl.java @@ -3,8 +3,10 @@ package top.xyquan.ecomdmbbackend.modules.ecom.product.overview.service.impl; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import org.springframework.stereotype.Service; import top.xyquan.ecomdmbbackend.common.exception.BusinessException; -import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper; import top.xyquan.ecomdmbbackend.modules.ecom.order.model.po.OrderPO; +import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatReadFacade; import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatResolver; import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets; import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductPO; @@ -44,6 +46,7 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { private final ProductSpecMapper productSpecMapper; private final ShopMonthlyTargetMapper shopMonthlyTargetMapper; private final ShopService shopService; + private final OrderStatReadFacade orderStatReadFacade; public ProductOverviewServiceImpl(CurrentUserContext currentUserContext, OrderMapper orderMapper, @@ -52,7 +55,8 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { ProductService productService, ProductSpecMapper productSpecMapper, ShopMonthlyTargetMapper shopMonthlyTargetMapper, - ShopService shopService) { + ShopService shopService, + OrderStatReadFacade orderStatReadFacade) { this.currentUserContext = currentUserContext; this.orderMapper = orderMapper; this.promotionFeeMapper = promotionFeeMapper; @@ -61,6 +65,7 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { this.productSpecMapper = productSpecMapper; this.shopMonthlyTargetMapper = shopMonthlyTargetMapper; this.shopService = shopService; + this.orderStatReadFacade = orderStatReadFacade; } private void applyProductOverviewOrderScope(LambdaQueryWrapper wrapper, @@ -133,6 +138,11 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { OrderStatusStatSets stat = orderStatusStatResolver.resolve(companyId); List unionStatusIds = stat.getUnionStatusIds(); + if (orderStatReadFacade.usesDailyStatSource()) { + return getProductOverviewFromStat(queryDTO, companyId, product, filterShopId, + startDate, endDate, taxRate, stat); + } + // 查询订单数据 LambdaQueryWrapper orderWrapper = new LambdaQueryWrapper<>(); applyProductOverviewOrderScope(orderWrapper, companyId, queryDTO.getProductId(), filterShopId, @@ -819,4 +829,218 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { .limit(10) .collect(Collectors.toList()); } + + /** 汇总表读路径:商品概览 */ + private ProductOverviewVO getProductOverviewFromStat(ProductOverviewQueryDTO queryDTO, + Long companyId, ProductPO product, + Long filterShopId, + LocalDate startDate, LocalDate endDate, + BigDecimal taxRate, OrderStatusStatSets stat) { + List shopIds; + if (filterShopId != null) { + shopIds = List.of(filterShopId); + } else { + shopIds = shopService.lambdaQuery().eq(ShopPO::getCompanyId, companyId).list() + .stream().map(ShopPO::getId).filter(Objects::nonNull).toList(); + } + + OrderStatMetricsDTO cur = orderStatReadFacade.sumProductForOne( + companyId, shopIds, queryDTO.getProductId(), startDate, endDate); + long dayCount = ChronoUnit.DAYS.between(startDate, endDate) + 1; + LocalDate lastStart = startDate.minusDays(dayCount); + LocalDate lastEnd = startDate.minusDays(1); + OrderStatMetricsDTO last = orderStatReadFacade.sumProductForOne( + companyId, shopIds, queryDTO.getProductId(), lastStart, lastEnd); + + BigDecimal totalSales = nz(cur.getSalesAmount()); + BigDecimal totalRefund = nz(cur.getRefundAmount()); + int totalOrderCount = cur.getSalesOrderCount() != null ? cur.getSalesOrderCount() : 0; + BigDecimal totalCost = nz(cur.getProductCost()).add(nz(cur.getFreightCost())).add(nz(cur.getOtherCost())); + + List promotionFees = new ArrayList<>(); + if (!shopIds.isEmpty()) { + LambdaQueryWrapper promoWrapper = new LambdaQueryWrapper<>(); + promoWrapper.eq(PromotionFeePO::getCompanyId, companyId) + .in(PromotionFeePO::getShopId, shopIds) + .ge(PromotionFeePO::getFeeDate, startDate) + .le(PromotionFeePO::getFeeDate, endDate); + promotionFees = promotionFeeMapper.selectList(promoWrapper); + } + BigDecimal shopSalesDenominator = orderStatReadFacade.sumShopMetrics(companyId, shopIds, startDate, endDate) + .getSalesAmount(); + BigDecimal totalPromotionFee = computeAttributedPromotionFromStat( + queryDTO.getProductId(), product, shopSalesDenominator, promotionFees); + + ProductOverviewVO vo = new ProductOverviewVO(); + vo.setProductId(product.getId()); + vo.setProductName(product.getName()); + vo.setTotalSalesAmount(totalSales); + vo.setTotalOrderCount(totalOrderCount); + vo.setAverageFeeRatio(totalSales.signum() > 0 + ? totalPromotionFee.divide(totalSales, 4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100)) + .setScale(2, RoundingMode.HALF_UP) : BigDecimal.ZERO); + BigDecimal tax = salesTaxOnNetSales(totalSales, totalRefund, taxRate); + vo.setTotalTaxAmount(tax); + vo.setTotalNetProfitAfterTax(totalSales.subtract(totalCost).subtract(totalRefund) + .subtract(totalPromotionFee).subtract(tax).setScale(2, RoundingMode.HALF_UP)); + vo.setTotalROI(totalPromotionFee.signum() > 0 + ? totalSales.subtract(totalRefund).divide(totalPromotionFee, 4, RoundingMode.HALF_UP) + : BigDecimal.ZERO); + vo.setMonthOverMonthGrowth(growthPct(totalSales, nz(last.getSalesAmount()))); + + vo.setSalesAmountTrend(buildTrendFromStatDaily( + orderStatReadFacade.sumProductByDayForOne(companyId, shopIds, queryDTO.getProductId(), startDate, endDate), + startDate, endDate, OrderStatMetricsDTO::getSalesAmount)); + vo.setOrderCountTrend(buildTrendFromStatDaily( + orderStatReadFacade.sumProductByDayForOne(companyId, shopIds, queryDTO.getProductId(), startDate, endDate), + startDate, endDate, m -> BigDecimal.valueOf(m.getSalesOrderCount() != null ? m.getSalesOrderCount() : 0))); + + vo.setSpecSummaries(buildSpecSummaryFromStat( + orderStatReadFacade.sumSpecMetrics(companyId, shopIds, queryDTO.getProductId(), startDate, endDate), + taxRate, totalPromotionFee, totalSales)); + vo.setSpecSalesTop10(buildSpecTop10FromStat( + orderStatReadFacade.sumSpecMetrics(companyId, shopIds, queryDTO.getProductId(), startDate, endDate))); + return vo; + } + + private BigDecimal computeAttributedPromotionFromStat(Long productId, ProductPO product, + BigDecimal shopSalesTotal, + List promotionFees) { + if (promotionFees == null || promotionFees.isEmpty()) { + return BigDecimal.ZERO; + } + BigDecimal direct = BigDecimal.ZERO; + BigDecimal ratioPool = BigDecimal.ZERO; + for (PromotionFeePO fee : promotionFees) { + BigDecimal amt = fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO; + if (fee.getProductId() != null && fee.getProductId().equals(productId)) { + direct = direct.add(amt); + } else if (fee.getCategoryId() != null && product.getCategoryId() != null + && fee.getCategoryId().equals(product.getCategoryId())) { + direct = direct.add(amt); + } else if (fee.getProductId() == null && fee.getCategoryId() == null) { + ratioPool = ratioPool.add(amt); + } + } + BigDecimal productSales = orderStatReadFacade.sumProductForOne( + product.getCompanyId(), List.of(), productId, + promotionFees.get(0).getFeeDate(), promotionFees.get(0).getFeeDate()).getSalesAmount(); + if (shopSalesTotal != null && shopSalesTotal.signum() > 0 && ratioPool.signum() > 0) { + direct = direct.add(ratioPool.multiply(productSales).divide(shopSalesTotal, 4, RoundingMode.HALF_UP)); + } + return direct; + } + + private ProductOverviewVO.TrendData buildTrendFromStatDaily(List daily, + LocalDate start, LocalDate end, + java.util.function.Function fn) { + Map map = new HashMap<>(); + for (OrderStatMetricsDTO d : daily) { + if (d.getStatDate() != null) { + map.put(d.getStatDate(), fn.apply(d)); + } + } + List items = new ArrayList<>(); + BigDecimal total = BigDecimal.ZERO; + for (LocalDate d = start; !d.isAfter(end); d = d.plusDays(1)) { + BigDecimal v = map.getOrDefault(d, BigDecimal.ZERO); + ProductOverviewVO.TrendDataItem item = new ProductOverviewVO.TrendDataItem(); + item.setDate(d); + item.setValue(v); + items.add(item); + total = total.add(v); + } + ProductOverviewVO.TrendData trend = new ProductOverviewVO.TrendData(); + trend.setDailyDataList(items); + trend.setTotal(total); + return trend; + } + + private ProductOverviewVO.SpecSummary buildSpecSummaryFromStat(List specRows, + BigDecimal taxRate, + BigDecimal totalPromo, + BigDecimal totalSales) { + if (specRows == null || specRows.isEmpty()) { + return buildEmptySpecSummary(); + } + Set specIds = specRows.stream().map(OrderStatMetricsDTO::getProductSpecId) + .filter(Objects::nonNull).collect(Collectors.toSet()); + Map specMap = productSpecMapper.selectBatchIds(specIds).stream() + .collect(Collectors.toMap(ProductSpecPO::getId, s -> s, (a, b) -> a)); + + List items = new ArrayList<>(); + for (OrderStatMetricsDTO m : specRows) { + ProductSpecPO spec = specMap.get(m.getProductSpecId()); + BigDecimal sales = nz(m.getSalesAmount()); + BigDecimal promoShare = totalSales.signum() > 0 + ? totalPromo.multiply(sales).divide(totalSales, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO; + ProductOverviewVO.SpecSummaryItem item = new ProductOverviewVO.SpecSummaryItem(); + item.setSpecId(m.getProductSpecId()); + item.setSpecName(spec != null ? spec.getName() : "未知规格"); + item.setSpecCode(spec != null ? spec.getSpecCode() : null); + item.setSalesAmount(sales); + item.setOrderCount(m.getSalesOrderCount() != null ? m.getSalesOrderCount() : 0); + item.setQuantity(m.getQuantitySum() != null ? m.getQuantitySum() : 0); + item.setProductCost(nz(m.getProductCost())); + item.setShippingCost(nz(m.getFreightCost())); + item.setOtherCost(nz(m.getOtherCost())); + item.setOrderCost(item.getProductCost().add(item.getShippingCost()).add(item.getOtherCost())); + item.setRefundAmount(nz(m.getRefundAmount())); + item.setPromotionFee(promoShare); + item.setSalesTaxAmount(salesTaxOnNetSales(sales, item.getRefundAmount(), taxRate)); + item.setProfitAfterTax(sales.subtract(item.getOrderCost()).subtract(item.getRefundAmount()) + .subtract(promoShare).subtract(item.getSalesTaxAmount()).setScale(2, RoundingMode.HALF_UP)); + items.add(item); + } + ProductOverviewVO.SpecSummary summary = new ProductOverviewVO.SpecSummary(); + summary.setList(items); + summary.setTotal(buildSpecTotal(items)); + return summary; + } + + private static ProductOverviewVO.SpecSummaryTotal buildSpecTotal(List items) { + ProductOverviewVO.SpecSummaryTotal total = new ProductOverviewVO.SpecSummaryTotal(); + total.setSalesAmount(items.stream().map(ProductOverviewVO.SpecSummaryItem::getSalesAmount) + .reduce(BigDecimal.ZERO, BigDecimal::add)); + total.setOrderCount(items.stream().mapToInt(i -> i.getOrderCount() != null ? i.getOrderCount() : 0).sum()); + total.setQuantity(items.stream().mapToInt(i -> i.getQuantity() != null ? i.getQuantity() : 0).sum()); + return total; + } + + private List buildSpecTop10FromStat(List specRows) { + if (specRows == null) { + return List.of(); + } + Set specIds = specRows.stream().map(OrderStatMetricsDTO::getProductSpecId) + .filter(Objects::nonNull).collect(Collectors.toSet()); + Map specMap = specIds.isEmpty() ? Map.of() + : productSpecMapper.selectBatchIds(specIds).stream() + .collect(Collectors.toMap(ProductSpecPO::getId, s -> s, (a, b) -> a)); + return specRows.stream() + .sorted(Comparator.comparingInt((OrderStatMetricsDTO m) -> + m.getSalesOrderCount() != null ? m.getSalesOrderCount() : 0).reversed()) + .limit(10) + .map(m -> { + ProductSpecPO spec = specMap.get(m.getProductSpecId()); + ProductOverviewVO.SpecSalesRankItem item = new ProductOverviewVO.SpecSalesRankItem(); + item.setSpecId(m.getProductSpecId()); + item.setSpecName(spec != null ? spec.getName() : "未知规格"); + item.setSpecCode(spec != null ? spec.getSpecCode() : null); + item.setOrderCount(m.getSalesOrderCount()); + item.setSalesAmount(nz(m.getSalesAmount())); + return item; + }).collect(Collectors.toList()); + } + + private static BigDecimal growthPct(BigDecimal cur, BigDecimal prev) { + if (prev.signum() > 0) { + return cur.subtract(prev).divide(prev, 4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100)) + .setScale(2, RoundingMode.HALF_UP); + } + return cur.signum() > 0 ? new BigDecimal("100.00") : BigDecimal.ZERO; + } + + private static BigDecimal nz(BigDecimal v) { + return v != null ? v : BigDecimal.ZERO; + } } diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/product/service/impl/ProductSpecServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/product/service/impl/ProductSpecServiceImpl.java index 0eff44b7..8288b43e 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/product/service/impl/ProductSpecServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/product/service/impl/ProductSpecServiceImpl.java @@ -21,10 +21,15 @@ import top.xyquan.ecomdmbbackend.modules.ecom.product.model.vo.ProductSpecVO; import top.xyquan.ecomdmbbackend.modules.ecom.product.model.vo.ProductVO; import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductService; import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductSpecService; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.OrderShopStatDateRow; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatCrudCoordinator; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support.StatDirtyKey; import top.xyquan.ecomdmbbackend.utils.CurrentUserContext; import java.math.BigDecimal; +import java.util.HashSet; import java.util.List; +import java.util.Set; import java.util.stream.Collectors; /** @@ -36,12 +41,15 @@ public class ProductSpecServiceImpl extends ServiceImpl affected = + orderMapper.selectOrphanOrderStatDatesBySpecCode(companyId, code); + orderMapper.linkOrdersBySpecCodeWhenSpecIdNull(companyId, code, productSpecId); + if (affected != null && !affected.isEmpty()) { + Set keys = new HashSet<>(); + for (OrderShopStatDateRow row : affected) { + if (row.getShopId() != null && row.getStatDate() != null) { + keys.add(new StatDirtyKey(companyId, row.getShopId(), row.getStatDate())); + } + } + orderStatCrudCoordinator.enqueueDirtyKeys(keys); + } } /** diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/promotion/service/impl/PromotionFeeServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/promotion/service/impl/PromotionFeeServiceImpl.java index 971a2426..d15f63df 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/promotion/service/impl/PromotionFeeServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/promotion/service/impl/PromotionFeeServiceImpl.java @@ -3,7 +3,6 @@ package top.xyquan.ecomdmbbackend.modules.ecom.promotion.service.impl; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import lombok.RequiredArgsConstructor; import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -18,6 +17,7 @@ import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.dto.UpdatePromotio import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.po.PromotionFeePO; import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.vo.BatchImportPromotionFeeResultVO; import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.vo.PromotionFeeVO; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.FeeStatCrudCoordinator; import top.xyquan.ecomdmbbackend.modules.ecom.promotion.service.PromotionFeeService; import top.xyquan.ecomdmbbackend.modules.ecom.promotion.service.PromotionFeeTypeService; import top.xyquan.ecomdmbbackend.modules.ecom.category.model.po.CategoryPO; @@ -35,7 +35,6 @@ import java.util.stream.Collectors; * 推广费记录服务实现类 */ @Service -@RequiredArgsConstructor public class PromotionFeeServiceImpl implements PromotionFeeService { private final PromotionFeeMapper promotionFeeMapper; @@ -44,7 +43,23 @@ public class PromotionFeeServiceImpl implements PromotionFeeService { private final PromotionFeeTypeService promotionFeeTypeService; private final ProductService productService; private final CategoryService categoryService; + private final FeeStatCrudCoordinator feeStatCrudCoordinator; + public PromotionFeeServiceImpl(PromotionFeeMapper promotionFeeMapper, + CurrentUserContext currentUserContext, + ShopService shopService, + PromotionFeeTypeService promotionFeeTypeService, + ProductService productService, + CategoryService categoryService, + FeeStatCrudCoordinator feeStatCrudCoordinator) { + this.promotionFeeMapper = promotionFeeMapper; + this.currentUserContext = currentUserContext; + this.shopService = shopService; + this.promotionFeeTypeService = promotionFeeTypeService; + this.productService = productService; + this.categoryService = categoryService; + this.feeStatCrudCoordinator = feeStatCrudCoordinator; + } /** * 创建推广费记录 @@ -62,6 +77,7 @@ public class PromotionFeeServiceImpl implements PromotionFeeService { po.setUpdateBy(currentUserContext.getCurrentUserId()); promotionFeeMapper.insert(po); + feeStatCrudCoordinator.afterPromotionFeeSaved(null, po); return po.getId(); } @@ -83,6 +99,7 @@ public class PromotionFeeServiceImpl implements PromotionFeeService { po.setUpdateBy(currentUserContext.getCurrentUserId()); po.setCompanyId(companyId); promotionFeeMapper.updateById(po); + feeStatCrudCoordinator.afterPromotionFeeSaved(existing, po); } /** @@ -98,6 +115,7 @@ public class PromotionFeeServiceImpl implements PromotionFeeService { throw new BusinessException("推广费记录不存在"); } promotionFeeMapper.deleteById(id); + feeStatCrudCoordinator.afterPromotionFeeDeleted(existing); } /** diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/workbench/service/impl/WorkbenchExportServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/workbench/service/impl/WorkbenchExportServiceImpl.java index f0a77b40..356c8134 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/workbench/service/impl/WorkbenchExportServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/workbench/service/impl/WorkbenchExportServiceImpl.java @@ -3,10 +3,8 @@ package top.xyquan.ecomdmbbackend.modules.ecom.workbench.service.impl; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import org.springframework.stereotype.Service; import top.xyquan.ecomdmbbackend.common.exception.BusinessException; -import top.xyquan.ecomdmbbackend.modules.ecom.brushorder.mapper.BrushOrderMapper; -import top.xyquan.ecomdmbbackend.modules.ecom.brushorder.model.po.BrushOrderPO; -import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper; -import top.xyquan.ecomdmbbackend.modules.ecom.order.model.po.OrderPO; +import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatReadFacade; import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatResolver; import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets; import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.CategoryExportDTO; @@ -16,8 +14,6 @@ import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.vo.CompanyOverviewV import top.xyquan.ecomdmbbackend.modules.ecom.overview.service.CategoryExportExcelService; import top.xyquan.ecomdmbbackend.modules.ecom.overview.service.CompanyOverviewService; import top.xyquan.ecomdmbbackend.modules.ecom.overview.service.ExportService; -import top.xyquan.ecomdmbbackend.modules.ecom.promotion.mapper.PromotionFeeMapper; -import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.po.PromotionFeePO; import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO; import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopService; import top.xyquan.ecomdmbbackend.modules.ecom.workbench.model.dto.WorkbenchExportDTO; @@ -28,7 +24,6 @@ import top.xyquan.ecomdmbbackend.utils.CurrentUserContext; import java.math.BigDecimal; import java.time.LocalDate; import java.time.LocalDateTime; -import java.util.Collections; import java.util.List; import java.util.Objects; @@ -42,34 +37,28 @@ public class WorkbenchExportServiceImpl implements WorkbenchExportService { private static final BigDecimal DEFAULT_TAX_RATE = new BigDecimal("0.04"); private final CurrentUserContext currentUserContext; - private final OrderMapper orderMapper; private final ShopService shopService; private final OrderStatusStatResolver orderStatusStatResolver; - private final PromotionFeeMapper promotionFeeMapper; - private final BrushOrderMapper brushOrderMapper; private final CompanyOverviewService companyOverviewService; private final ExportService exportService; private final CategoryExportExcelService categoryExportExcelService; + private final OrderStatReadFacade orderStatReadFacade; public WorkbenchExportServiceImpl( CurrentUserContext currentUserContext, - OrderMapper orderMapper, ShopService shopService, OrderStatusStatResolver orderStatusStatResolver, - PromotionFeeMapper promotionFeeMapper, - BrushOrderMapper brushOrderMapper, CompanyOverviewService companyOverviewService, ExportService exportService, - CategoryExportExcelService categoryExportExcelService) { + CategoryExportExcelService categoryExportExcelService, + OrderStatReadFacade orderStatReadFacade) { this.currentUserContext = currentUserContext; - this.orderMapper = orderMapper; this.shopService = shopService; this.orderStatusStatResolver = orderStatusStatResolver; - this.promotionFeeMapper = promotionFeeMapper; - this.brushOrderMapper = brushOrderMapper; this.companyOverviewService = companyOverviewService; this.exportService = exportService; this.categoryExportExcelService = categoryExportExcelService; + this.orderStatReadFacade = orderStatReadFacade; } /** @@ -136,12 +125,11 @@ public class WorkbenchExportServiceImpl implements WorkbenchExportService { "商品名称"); } - /** 拉取订单/推广/刷单后调用 {@link CompanyOverviewService#buildWorkbenchSummaryTables},各 export 共用 */ + /** 拉取汇总表/明细聚合后构建四表,与 {@link WorkbenchServiceImpl#financeSlice} 口径一致 */ private CompanyOverviewVO.WorkbenchTableBundle loadSummaryTables(WorkbenchExportDTO dto) { Long companyId = currentUserContext.getCurrentCompanyId(); DateRange range = parseDateRange(toQuery(dto)); OrderStatusStatSets stat = orderStatusStatResolver.resolve(companyId); - List unionStatusIds = stat.getUnionStatusIds(); List shops = loadFilteredShops(companyId, dto.getPlatformId(), dto.getShopId()); if (shops.isEmpty()) { @@ -149,21 +137,17 @@ public class WorkbenchExportServiceImpl implements WorkbenchExportService { } List shopIds = shops.stream().map(ShopPO::getId).filter(Objects::nonNull).toList(); - List orders = loadOrders(companyId, shopIds, range.startDateTime(), range.endDateTime(), unionStatusIds); - List promotionFees = loadPromotionFees(companyId, shopIds, range.startDate(), range.endDate()); - List brushOrders = loadBrushOrders(companyId, shopIds, range.startDateTime(), range.endDateTime()); + List orderRows = orderStatReadFacade.loadShopProductRows( + companyId, shopIds, range.startDate(), range.endDate(), stat); + List promotionRows = orderStatReadFacade.loadPromotionRows( + companyId, shopIds, range.startDate(), range.endDate()); + List brushRows = orderStatReadFacade.loadBrushRows( + companyId, shopIds, range.startDateTime(), range.endDateTime()); BigDecimal taxRate = dto.getTaxRate() != null ? dto.getTaxRate() : DEFAULT_TAX_RATE; - return companyOverviewService.buildWorkbenchSummaryTables( - taxRate, - companyId, - shops, - orders, - promotionFees, - brushOrders, - stat, - range.startDate(), - range.endDate()); + return companyOverviewService.buildWorkbenchSummaryTablesFromAgg( + taxRate, companyId, shops, orderRows, promotionRows, brushRows, + range.startDate(), range.endDate()); } /** 导出 DTO 与查询 DTO 字段对齐,仅用于复用 {@link #parseDateRange} */ @@ -214,51 +198,6 @@ public class WorkbenchExportServiceImpl implements WorkbenchExportService { return shopService.list(w); } - /** 计入销售额状态的订单列表,与 {@link WorkbenchServiceImpl#loadOrders} 一致 */ - private List loadOrders(Long companyId, List shopIds, - LocalDateTime start, LocalDateTime end, List unionStatusIds) { - if (shopIds.isEmpty()) { - return Collections.emptyList(); - } - LambdaQueryWrapper orderWrapper = new LambdaQueryWrapper<>(); - orderWrapper.eq(OrderPO::getCompanyId, companyId) - .in(OrderPO::getShopId, shopIds) - .ge(OrderPO::getOrderTime, start) - .le(OrderPO::getOrderTime, end); - if (!unionStatusIds.isEmpty()) { - orderWrapper.in(OrderPO::getStatusId, unionStatusIds); - } else { - orderWrapper.isNull(OrderPO::getId); - } - return orderMapper.selectList(orderWrapper); - } - - /** 区间内推广费(按费用日) */ - private List loadPromotionFees(Long companyId, List shopIds, LocalDate start, LocalDate end) { - if (shopIds.isEmpty()) { - return Collections.emptyList(); - } - LambdaQueryWrapper w = new LambdaQueryWrapper<>(); - w.eq(PromotionFeePO::getCompanyId, companyId) - .in(PromotionFeePO::getShopId, shopIds) - .ge(PromotionFeePO::getFeeDate, start) - .le(PromotionFeePO::getFeeDate, end); - return promotionFeeMapper.selectList(w); - } - - /** 区间内刷单(按刷单时间) */ - private List loadBrushOrders(Long companyId, List shopIds, LocalDateTime start, LocalDateTime end) { - if (shopIds.isEmpty()) { - return Collections.emptyList(); - } - LambdaQueryWrapper w = new LambdaQueryWrapper<>(); - w.eq(BrushOrderPO::getCompanyId, companyId) - .in(BrushOrderPO::getShopId, shopIds) - .ge(BrushOrderPO::getBrushTime, start) - .le(BrushOrderPO::getBrushTime, end); - return brushOrderMapper.selectList(w); - } - /** 查询时间闭区间辅助 record */ private record DateRange(LocalDate startDate, LocalDate endDate) { LocalDateTime startDateTime() { diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/workbench/service/impl/WorkbenchServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/workbench/service/impl/WorkbenchServiceImpl.java index 3c6bd619..8184f780 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/workbench/service/impl/WorkbenchServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/workbench/service/impl/WorkbenchServiceImpl.java @@ -9,6 +9,7 @@ import top.xyquan.ecomdmbbackend.modules.ecom.category.model.po.CategoryPO; import top.xyquan.ecomdmbbackend.modules.ecom.category.service.CategoryService; import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper; import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper; +import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatReadFacade; import top.xyquan.ecomdmbbackend.modules.ecom.order.model.po.OrderPO; import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatResolver; import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets; @@ -87,7 +88,7 @@ public class WorkbenchServiceImpl implements WorkbenchService { private final ProductMapper productMapper; private final CategoryService categoryService; private final PlatformMapper platformMapper; - private final OrderStatAggMapper orderStatAggMapper; + private final OrderStatReadFacade orderStatReadFacade; private final CompanyOverviewService companyOverviewService; public WorkbenchServiceImpl(CurrentUserContext currentUserContext, @@ -100,7 +101,7 @@ public class WorkbenchServiceImpl implements WorkbenchService { ProductMapper productMapper, CategoryService categoryService, PlatformMapper platformMapper, - OrderStatAggMapper orderStatAggMapper, + OrderStatReadFacade orderStatReadFacade, CompanyOverviewService companyOverviewService) { this.currentUserContext = currentUserContext; this.orderMapper = orderMapper; @@ -112,7 +113,7 @@ public class WorkbenchServiceImpl implements WorkbenchService { this.productMapper = productMapper; this.categoryService = categoryService; this.platformMapper = platformMapper; - this.orderStatAggMapper = orderStatAggMapper; + this.orderStatReadFacade = orderStatReadFacade; this.companyOverviewService = companyOverviewService; } @@ -224,20 +225,17 @@ public class WorkbenchServiceImpl implements WorkbenchService { return new ShopContext(taxRate, companyId, range, stat, shops, shopIds, shopById); } - /** 当前区间 SQL-1/2/4/5 */ + /** 当前区间 SQL-1/2/4/5(汇总表或明细回退) */ private SqlAggBundle loadSqlAgg(ShopContext ctx) { - OrderStatusStatSets stat = ctx.stat(); - List orderRows = orderStatAggMapper.aggregateByShopProduct( - ctx.companyId(), ctx.shopIds(), ctx.range().startDateTime(), ctx.range().endDateTime(), - stat.getUnionStatusIds(), statusList(stat.getSalesIds()), statusList(stat.getRefundIds()), - statusList(stat.getProductCostIds()), statusList(stat.getFreightCostIds()), statusList(stat.getOtherCostIds())); - List dailyRows = orderStatAggMapper.aggregateDaily( - ctx.companyId(), ctx.shopIds(), ctx.range().startDateTime(), ctx.range().endDateTime(), - stat.getUnionStatusIds(), statusList(stat.getSalesIds()), statusList(stat.getRefundIds()), - statusList(stat.getProductCostIds()), statusList(stat.getFreightCostIds()), statusList(stat.getOtherCostIds())); - List promotionRows = orderStatAggMapper.aggregatePromotionFees( - ctx.companyId(), ctx.shopIds(), ctx.range().startDate(), ctx.range().endDate()); - List brushRows = orderStatAggMapper.aggregateBrushFees( + LocalDate start = ctx.range().startDate(); + LocalDate end = ctx.range().endDate(); + List orderRows = orderStatReadFacade.loadShopProductRows( + ctx.companyId(), ctx.shopIds(), start, end, ctx.stat()); + List dailyRows = orderStatReadFacade.loadDailyRows( + ctx.companyId(), ctx.shopIds(), start, end, ctx.stat()); + List promotionRows = orderStatReadFacade.loadPromotionRows( + ctx.companyId(), ctx.shopIds(), start, end); + List brushRows = orderStatReadFacade.loadBrushRows( ctx.companyId(), ctx.shopIds(), ctx.range().startDateTime(), ctx.range().endDateTime()); return new SqlAggBundle(orderRows, dailyRows, promotionRows, brushRows); } @@ -247,38 +245,27 @@ public class WorkbenchServiceImpl implements WorkbenchService { OrderStatusStatSets stat = ctx.stat(); DateRange lastRange = lastMonthSameSpan(ctx.range()); DateRange yoyRange = new DateRange(ctx.range().startDate().minusYears(1), ctx.range().endDate().minusYears(1)); - LocalDateTime scanStart = minTime(lastRange.startDateTime(), yoyRange.startDateTime(), ctx.range().startDateTime()); - LocalDateTime scanEnd = maxTime(lastRange.endDateTime(), yoyRange.endDateTime(), ctx.range().endDateTime()); - OrderStatAggMapper.PeriodKpiRow orderKpi = orderStatAggMapper.aggregatePeriodKpi( - ctx.companyId(), ctx.shopIds(), scanStart, scanEnd, - ctx.range().startDateTime(), ctx.range().endDateTime(), - lastRange.startDateTime(), lastRange.endDateTime(), - yoyRange.startDateTime(), yoyRange.endDateTime(), - stat.getUnionStatusIds(), statusList(stat.getSalesIds()), statusList(stat.getRefundIds()), - statusList(stat.getProductCostIds()), statusList(stat.getFreightCostIds()), statusList(stat.getOtherCostIds())); - if (orderKpi == null) { - orderKpi = new OrderStatAggMapper.PeriodKpiRow(); - } + OrderStatAggMapper.PeriodKpiRow orderKpi = orderStatReadFacade.loadPeriodKpi( + ctx.companyId(), ctx.shopIds(), + ctx.range().startDate(), ctx.range().endDate(), + lastRange.startDate(), lastRange.endDate(), + yoyRange.startDate(), yoyRange.endDate(), stat); LocalDate feeScanStart = minDate(lastRange.startDate(), yoyRange.startDate(), ctx.range().startDate()); LocalDate feeScanEnd = maxDate(lastRange.endDate(), yoyRange.endDate(), ctx.range().endDate()); - OrderStatAggMapper.FeeKpiRow promoKpi = orderStatAggMapper.aggregatePromotionPeriodKpi( + OrderStatAggMapper.FeeKpiRow promoKpi = orderStatReadFacade.loadPromotionPeriodKpi( ctx.companyId(), ctx.shopIds(), feeScanStart, feeScanEnd, ctx.range().startDate(), ctx.range().endDate(), lastRange.startDate(), lastRange.endDate(), yoyRange.startDate(), yoyRange.endDate()); - if (promoKpi == null) { - promoKpi = new OrderStatAggMapper.FeeKpiRow(); - } - OrderStatAggMapper.FeeKpiRow brushKpi = orderStatAggMapper.aggregateBrushPeriodKpi( - ctx.companyId(), ctx.shopIds(), scanStart, scanEnd, + OrderStatAggMapper.FeeKpiRow brushKpi = orderStatReadFacade.loadBrushPeriodKpi( + ctx.companyId(), ctx.shopIds(), + minTime(lastRange.startDateTime(), yoyRange.startDateTime(), ctx.range().startDateTime()), + maxTime(lastRange.endDateTime(), yoyRange.endDateTime(), ctx.range().endDateTime()), ctx.range().startDateTime(), ctx.range().endDateTime(), lastRange.startDateTime(), lastRange.endDateTime(), yoyRange.startDateTime(), yoyRange.endDateTime()); - if (brushKpi == null) { - brushKpi = new OrderStatAggMapper.FeeKpiRow(); - } return new ComparePeriodBundle(lastRange, yoyRange, totalsFromPeriodKpi(orderKpi, promoKpi, brushKpi, PeriodSlice.PREV, ctx.taxRate()), diff --git a/ecom-dmb-backend/src/main/resources/application.yml b/ecom-dmb-backend/src/main/resources/application.yml index e09453ed..d47fc33b 100644 --- a/ecom-dmb-backend/src/main/resources/application.yml +++ b/ecom-dmb-backend/src/main/resources/application.yml @@ -41,6 +41,21 @@ spring: min-idle: 0 max-wait: -1ms +# 订单统计读模型 +order-stat: + stat-source: daily + auto-refresh-on-miss: true + refresh-worker: + enabled: true + pool-size: 4 + poll-interval-ms: 2000 + cache: + enabled: true + ttl-history-seconds: 86400 + ttl-today-seconds: 900 + nightly-rebuild-enabled: false + nightly-rebuild-cron: "0 30 2 * * ?" + # JWT配置 # ⚠️ 生产环境必须通过环境变量 JWT_SECRET 覆盖,默认值仅用于本地开发 jwt: diff --git a/ecom-dmb-backend/src/main/resources/mapper/order/stat/FeeStatDailyMapper.xml b/ecom-dmb-backend/src/main/resources/mapper/order/stat/FeeStatDailyMapper.xml new file mode 100644 index 00000000..9868d0d6 --- /dev/null +++ b/ecom-dmb-backend/src/main/resources/mapper/order/stat/FeeStatDailyMapper.xml @@ -0,0 +1,94 @@ + + + + + + DELETE FROM ec_promotion_fee_stat_daily + WHERE company_id = #{companyId} AND shop_id = #{shopId} AND stat_date = #{statDate} + + + + INSERT INTO ec_promotion_fee_stat_daily ( + company_id, shop_id, product_id, category_id, stat_date, fee_amount + ) VALUES + + (#{r.companyId}, #{r.shopId}, #{r.productId}, #{r.categoryId}, #{r.statDate}, #{r.feeAmount}) + + + + + INSERT INTO ec_promotion_fee_stat_monthly ( + company_id, shop_id, product_id, category_id, stat_month, fee_amount + ) + SELECT company_id, shop_id, product_id, category_id, #{statMonth}, SUM(fee_amount) + FROM ec_promotion_fee_stat_daily + WHERE company_id = #{companyId} AND shop_id = #{shopId} + AND stat_date >= #{statMonth} + AND stat_date < DATE_ADD(#{statMonth}, INTERVAL 1 MONTH) + GROUP BY company_id, shop_id, product_id, category_id + ON DUPLICATE KEY UPDATE fee_amount = VALUES(fee_amount), update_time = CURRENT_TIMESTAMP + + + + INSERT INTO ec_promotion_fee_stat_yearly ( + company_id, shop_id, product_id, category_id, stat_year, fee_amount + ) + SELECT company_id, shop_id, product_id, category_id, #{statYear}, SUM(fee_amount) + FROM ec_promotion_fee_stat_monthly + WHERE company_id = #{companyId} AND shop_id = #{shopId} AND YEAR(stat_month) = #{statYear} + GROUP BY company_id, shop_id, product_id, category_id + ON DUPLICATE KEY UPDATE fee_amount = VALUES(fee_amount), update_time = CURRENT_TIMESTAMP + + + + DELETE FROM ec_brush_fee_stat_daily + WHERE company_id = #{companyId} AND shop_id = #{shopId} AND stat_date = #{statDate} + + + + INSERT INTO ec_brush_fee_stat_daily (company_id, shop_id, stat_date, brush_amount) + VALUES (#{companyId}, #{shopId}, #{statDate}, #{brushAmount}) + ON DUPLICATE KEY UPDATE brush_amount = VALUES(brush_amount), update_time = CURRENT_TIMESTAMP + + + + INSERT INTO ec_brush_fee_stat_monthly (company_id, shop_id, stat_month, brush_amount) + SELECT company_id, shop_id, #{statMonth}, SUM(brush_amount) + FROM ec_brush_fee_stat_daily + WHERE company_id = #{companyId} AND shop_id = #{shopId} + AND stat_date >= #{statMonth} + AND stat_date < DATE_ADD(#{statMonth}, INTERVAL 1 MONTH) + GROUP BY company_id, shop_id + ON DUPLICATE KEY UPDATE brush_amount = VALUES(brush_amount), update_time = CURRENT_TIMESTAMP + + + + INSERT INTO ec_brush_fee_stat_yearly (company_id, shop_id, stat_year, brush_amount) + SELECT company_id, shop_id, #{statYear}, SUM(brush_amount) + FROM ec_brush_fee_stat_monthly + WHERE company_id = #{companyId} AND shop_id = #{shopId} AND YEAR(stat_month) = #{statYear} + GROUP BY company_id, shop_id + ON DUPLICATE KEY UPDATE brush_amount = VALUES(brush_amount), update_time = CURRENT_TIMESTAMP + + + + + + diff --git a/ecom-dmb-backend/src/main/resources/mapper/order/stat/OrderStatDailyMapper.xml b/ecom-dmb-backend/src/main/resources/mapper/order/stat/OrderStatDailyMapper.xml new file mode 100644 index 00000000..69a08b8b --- /dev/null +++ b/ecom-dmb-backend/src/main/resources/mapper/order/stat/OrderStatDailyMapper.xml @@ -0,0 +1,230 @@ + + + + + + INSERT INTO ec_order_stat_daily_shop ( + company_id, shop_id, platform_id, stat_date, + sales_amount, refund_amount, sales_order_count, + product_cost, freight_cost, other_cost, + gmv_amount, gmv_order_count, stat_version + ) VALUES ( + #{companyId}, #{shopId}, #{platformId}, #{statDate}, + #{salesAmount}, #{refundAmount}, #{salesOrderCount}, + #{productCost}, #{freightCost}, #{otherCost}, + #{gmvAmount}, #{gmvOrderCount}, #{statVersion} + ) + ON DUPLICATE KEY UPDATE + platform_id = VALUES(platform_id), + sales_amount = VALUES(sales_amount), + refund_amount = VALUES(refund_amount), + sales_order_count = VALUES(sales_order_count), + product_cost = VALUES(product_cost), + freight_cost = VALUES(freight_cost), + other_cost = VALUES(other_cost), + gmv_amount = VALUES(gmv_amount), + gmv_order_count = VALUES(gmv_order_count), + stat_version = VALUES(stat_version), + update_time = CURRENT_TIMESTAMP + + + + DELETE FROM ec_order_stat_daily_product + WHERE company_id = #{companyId} AND shop_id = #{shopId} AND stat_date = #{statDate} + + + + INSERT INTO ec_order_stat_daily_product ( + company_id, shop_id, product_id, category_id, stat_date, + sales_amount, refund_amount, sales_order_count, + product_cost, freight_cost, other_cost, stat_version + ) VALUES + + (#{r.companyId}, #{r.shopId}, #{r.productId}, #{r.categoryId}, #{r.statDate}, + #{r.salesAmount}, #{r.refundAmount}, #{r.salesOrderCount}, + #{r.productCost}, #{r.freightCost}, #{r.otherCost}, #{r.statVersion}) + + + + + DELETE FROM ec_order_stat_daily_spec + WHERE company_id = #{companyId} AND shop_id = #{shopId} AND stat_date = #{statDate} + + + + INSERT INTO ec_order_stat_daily_spec ( + company_id, shop_id, product_id, product_spec_id, stat_date, + sales_amount, refund_amount, sales_order_count, quantity_sum, + product_cost, freight_cost, other_cost, stat_version + ) VALUES + + (#{r.companyId}, #{r.shopId}, #{r.productId}, #{r.productSpecId}, #{r.statDate}, + #{r.salesAmount}, #{r.refundAmount}, #{r.salesOrderCount}, #{r.quantitySum}, + #{r.productCost}, #{r.freightCost}, #{r.otherCost}, #{r.statVersion}) + + + + + + INSERT INTO ec_order_stat_monthly_shop ( + company_id, shop_id, platform_id, stat_month, + sales_amount, refund_amount, sales_order_count, + product_cost, freight_cost, other_cost, gmv_amount, gmv_order_count, stat_version + ) + SELECT company_id, shop_id, MAX(platform_id), + #{statMonth}, + SUM(sales_amount), SUM(refund_amount), SUM(sales_order_count), + SUM(product_cost), SUM(freight_cost), SUM(other_cost), + SUM(gmv_amount), SUM(gmv_order_count), MAX(stat_version) + FROM ec_order_stat_daily_shop + WHERE company_id = #{companyId} AND shop_id = #{shopId} + AND stat_date >= #{statMonth} + AND stat_date < DATE_ADD(#{statMonth}, INTERVAL 1 MONTH) + GROUP BY company_id, shop_id + ON DUPLICATE KEY UPDATE + platform_id = VALUES(platform_id), + sales_amount = VALUES(sales_amount), + refund_amount = VALUES(refund_amount), + sales_order_count = VALUES(sales_order_count), + product_cost = VALUES(product_cost), + freight_cost = VALUES(freight_cost), + other_cost = VALUES(other_cost), + gmv_amount = VALUES(gmv_amount), + gmv_order_count = VALUES(gmv_order_count), + stat_version = VALUES(stat_version), + update_time = CURRENT_TIMESTAMP + + + + INSERT INTO ec_order_stat_yearly_shop ( + company_id, shop_id, platform_id, stat_year, + sales_amount, refund_amount, sales_order_count, + product_cost, freight_cost, other_cost, gmv_amount, gmv_order_count, stat_version + ) + SELECT company_id, shop_id, MAX(platform_id), + #{statYear}, + SUM(sales_amount), SUM(refund_amount), SUM(sales_order_count), + SUM(product_cost), SUM(freight_cost), SUM(other_cost), + SUM(gmv_amount), SUM(gmv_order_count), MAX(stat_version) + FROM ec_order_stat_monthly_shop + WHERE company_id = #{companyId} AND shop_id = #{shopId} + AND YEAR(stat_month) = #{statYear} + GROUP BY company_id, shop_id + ON DUPLICATE KEY UPDATE + platform_id = VALUES(platform_id), + sales_amount = VALUES(sales_amount), + refund_amount = VALUES(refund_amount), + sales_order_count = VALUES(sales_order_count), + product_cost = VALUES(product_cost), + freight_cost = VALUES(freight_cost), + other_cost = VALUES(other_cost), + gmv_amount = VALUES(gmv_amount), + gmv_order_count = VALUES(gmv_order_count), + stat_version = VALUES(stat_version), + update_time = CURRENT_TIMESTAMP + + + + INSERT INTO ec_order_stat_monthly_product ( + company_id, shop_id, product_id, category_id, stat_month, + sales_amount, refund_amount, sales_order_count, + product_cost, freight_cost, other_cost, stat_version + ) + SELECT company_id, shop_id, product_id, category_id, + #{statMonth}, + SUM(sales_amount), SUM(refund_amount), SUM(sales_order_count), + SUM(product_cost), SUM(freight_cost), SUM(other_cost), MAX(stat_version) + FROM ec_order_stat_daily_product + WHERE company_id = #{companyId} AND shop_id = #{shopId} + AND stat_date >= #{statMonth} + AND stat_date < DATE_ADD(#{statMonth}, INTERVAL 1 MONTH) + GROUP BY company_id, shop_id, product_id, category_id + ON DUPLICATE KEY UPDATE + sales_amount = VALUES(sales_amount), + refund_amount = VALUES(refund_amount), + sales_order_count = VALUES(sales_order_count), + product_cost = VALUES(product_cost), + freight_cost = VALUES(freight_cost), + other_cost = VALUES(other_cost), + stat_version = VALUES(stat_version), + update_time = CURRENT_TIMESTAMP + + + + INSERT INTO ec_order_stat_yearly_product ( + company_id, shop_id, product_id, category_id, stat_year, + sales_amount, refund_amount, sales_order_count, + product_cost, freight_cost, other_cost, stat_version + ) + SELECT company_id, shop_id, product_id, category_id, + #{statYear}, + SUM(sales_amount), SUM(refund_amount), SUM(sales_order_count), + SUM(product_cost), SUM(freight_cost), SUM(other_cost), MAX(stat_version) + FROM ec_order_stat_monthly_product + WHERE company_id = #{companyId} AND shop_id = #{shopId} + AND YEAR(stat_month) = #{statYear} + GROUP BY company_id, shop_id, product_id, category_id + ON DUPLICATE KEY UPDATE + sales_amount = VALUES(sales_amount), + refund_amount = VALUES(refund_amount), + sales_order_count = VALUES(sales_order_count), + product_cost = VALUES(product_cost), + freight_cost = VALUES(freight_cost), + other_cost = VALUES(other_cost), + stat_version = VALUES(stat_version), + update_time = CURRENT_TIMESTAMP + + + + INSERT INTO ec_order_stat_monthly_spec ( + company_id, shop_id, product_id, product_spec_id, stat_month, + sales_amount, refund_amount, sales_order_count, quantity_sum, + product_cost, freight_cost, other_cost, stat_version + ) + SELECT company_id, shop_id, product_id, product_spec_id, + #{statMonth}, + SUM(sales_amount), SUM(refund_amount), SUM(sales_order_count), SUM(quantity_sum), + SUM(product_cost), SUM(freight_cost), SUM(other_cost), MAX(stat_version) + FROM ec_order_stat_daily_spec + WHERE company_id = #{companyId} AND shop_id = #{shopId} + AND stat_date >= #{statMonth} + AND stat_date < DATE_ADD(#{statMonth}, INTERVAL 1 MONTH) + GROUP BY company_id, shop_id, product_id, product_spec_id + ON DUPLICATE KEY UPDATE + sales_amount = VALUES(sales_amount), + refund_amount = VALUES(refund_amount), + sales_order_count = VALUES(sales_order_count), + quantity_sum = VALUES(quantity_sum), + product_cost = VALUES(product_cost), + freight_cost = VALUES(freight_cost), + other_cost = VALUES(other_cost), + stat_version = VALUES(stat_version), + update_time = CURRENT_TIMESTAMP + + + + INSERT INTO ec_order_stat_yearly_spec ( + company_id, shop_id, product_id, product_spec_id, stat_year, + sales_amount, refund_amount, sales_order_count, quantity_sum, + product_cost, freight_cost, other_cost, stat_version + ) + SELECT company_id, shop_id, product_id, product_spec_id, + #{statYear}, + SUM(sales_amount), SUM(refund_amount), SUM(sales_order_count), SUM(quantity_sum), + SUM(product_cost), SUM(freight_cost), SUM(other_cost), MAX(stat_version) + FROM ec_order_stat_monthly_spec + WHERE company_id = #{companyId} AND shop_id = #{shopId} + AND YEAR(stat_month) = #{statYear} + GROUP BY company_id, shop_id, product_id, product_spec_id + ON DUPLICATE KEY UPDATE + sales_amount = VALUES(sales_amount), + refund_amount = VALUES(refund_amount), + sales_order_count = VALUES(sales_order_count), + quantity_sum = VALUES(quantity_sum), + product_cost = VALUES(product_cost), + freight_cost = VALUES(freight_cost), + other_cost = VALUES(other_cost), + stat_version = VALUES(stat_version), + update_time = CURRENT_TIMESTAMP + + diff --git a/ecom-dmb-backend/src/main/resources/mapper/order/stat/OrderStatQueryMapper.xml b/ecom-dmb-backend/src/main/resources/mapper/order/stat/OrderStatQueryMapper.xml new file mode 100644 index 00000000..a89aaebe --- /dev/null +++ b/ecom-dmb-backend/src/main/resources/mapper/order/stat/OrderStatQueryMapper.xml @@ -0,0 +1,284 @@ + + + + + + company_id = #{companyId} + AND shop_id IN + #{sid} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ecom-dmb-backend/src/main/resources/mapper/order/stat/OrderStatRefreshMapper.xml b/ecom-dmb-backend/src/main/resources/mapper/order/stat/OrderStatRefreshMapper.xml new file mode 100644 index 00000000..1aea2ef5 --- /dev/null +++ b/ecom-dmb-backend/src/main/resources/mapper/order/stat/OrderStatRefreshMapper.xml @@ -0,0 +1,78 @@ + + + + + IFNULL(NULLIF(o.quantity, 0), 1) + + + INSERT IGNORE INTO ec_order_stat_refresh_queue ( + company_id, shop_id, stat_date, source, status, retry_count + ) VALUES ( + #{companyId}, #{shopId}, #{statDate}, #{source}, 'pending', 0 + ) + + + + UPDATE ec_order_stat_refresh_queue SET status = 'done', update_time = CURRENT_TIMESTAMP + WHERE id = #{id} + + + + UPDATE ec_order_stat_refresh_queue + SET status = 'failed', retry_count = #{retryCount}, update_time = CURRENT_TIMESTAMP + WHERE id = #{id} + + + + + + + +