feat(订单统计): 落地读模型汇总表与 refresh 写入链路,工作台/概览/导出切读 daily 汇总并补充 Admin rebuild 与对账

This commit is contained in:
小蟑螂
2026-06-01 15:45:31 +08:00
parent e1d90ccba3
commit b19f6d60f9
58 changed files with 5332 additions and 131 deletions
@@ -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 默认关闭 |
@@ -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 对应月/年行
-- =============================================================================
@@ -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 = '订单统计日汇总待刷新队列';
@@ -5,9 +5,11 @@ import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication @SpringBootApplication
@EnableAsync @EnableAsync
@EnableScheduling
@MapperScan( @MapperScan(
basePackages = "top.xyquan.ecomdmbbackend.modules", basePackages = "top.xyquan.ecomdmbbackend.modules",
annotationClass = Mapper.class annotationClass = Mapper.class
@@ -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.shop.model.po.ShopPO;
import top.xyquan.ecomdmbbackend.modules.ecom.brushorder.model.vo.BrushOrderVO; 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.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.ProductService;
import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductSpecService; import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductSpecService;
import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopService; import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopService;
@@ -38,13 +39,16 @@ public class BrushOrderServiceImpl extends ServiceImpl<BrushOrderMapper, BrushOr
private final ShopService shopService; private final ShopService shopService;
private final ProductService productService; private final ProductService productService;
private final ProductSpecService productSpecService; private final ProductSpecService productSpecService;
private final FeeStatCrudCoordinator feeStatCrudCoordinator;
public BrushOrderServiceImpl(CurrentUserContext currentUserContext, ShopService shopService, public BrushOrderServiceImpl(CurrentUserContext currentUserContext, ShopService shopService,
ProductService productService, ProductSpecService productSpecService) { ProductService productService, ProductSpecService productSpecService,
FeeStatCrudCoordinator feeStatCrudCoordinator) {
this.currentUserContext = currentUserContext; this.currentUserContext = currentUserContext;
this.shopService = shopService; this.shopService = shopService;
this.productService = productService; this.productService = productService;
this.productSpecService = productSpecService; this.productSpecService = productSpecService;
this.feeStatCrudCoordinator = feeStatCrudCoordinator;
} }
/** /**
@@ -96,6 +100,7 @@ public class BrushOrderServiceImpl extends ServiceImpl<BrushOrderMapper, BrushOr
// 保存刷单记录 // 保存刷单记录
this.save(brushOrder); this.save(brushOrder);
feeStatCrudCoordinator.afterBrushOrderSaved(null, brushOrder);
// 转换为VO并返回 // 转换为VO并返回
return convertToVO(brushOrder); return convertToVO(brushOrder);
@@ -144,6 +149,8 @@ public class BrushOrderServiceImpl extends ServiceImpl<BrushOrderMapper, BrushOr
} }
// 更新刷单记录 // 更新刷单记录
BrushOrderPO before = new BrushOrderPO();
BeanUtils.copyProperties(existingBrushOrder, before);
existingBrushOrder.setShopId(updateBrushOrderDTO.getShopId()); existingBrushOrder.setShopId(updateBrushOrderDTO.getShopId());
existingBrushOrder.setProductId(updateBrushOrderDTO.getProductId()); existingBrushOrder.setProductId(updateBrushOrderDTO.getProductId());
existingBrushOrder.setProductSpecId(updateBrushOrderDTO.getProductSpecId()); existingBrushOrder.setProductSpecId(updateBrushOrderDTO.getProductSpecId());
@@ -157,6 +164,7 @@ public class BrushOrderServiceImpl extends ServiceImpl<BrushOrderMapper, BrushOr
// 保存更新 // 保存更新
this.updateById(existingBrushOrder); this.updateById(existingBrushOrder);
feeStatCrudCoordinator.afterBrushOrderSaved(before, existingBrushOrder);
// 转换为VO并返回 // 转换为VO并返回
return convertToVO(existingBrushOrder); return convertToVO(existingBrushOrder);
@@ -180,6 +188,7 @@ public class BrushOrderServiceImpl extends ServiceImpl<BrushOrderMapper, BrushOr
} }
// 硬删除刷单记录 // 硬删除刷单记录
feeStatCrudCoordinator.afterBrushOrderDeleted(existingBrushOrder);
this.removeById(id); this.removeById(id);
} }
@@ -6,6 +6,9 @@ import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductSpecPO;
import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopProductRelationPO; import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopProductRelationPO;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*; import java.util.*;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
@@ -192,6 +195,11 @@ public class ImportRuntimeContext {
// 进度回调(主线程设置,workers 调用,线程安全包装) // 进度回调(主线程设置,workers 调用,线程安全包装)
transient volatile BiConsumer<Integer, Integer> progressCallback; transient volatile BiConsumer<Integer, Integer> progressCallback;
/** 本任务涉及、需 refresh 汇总表的自然日(order_time → Asia/Shanghai DATE) */
private final Set<LocalDate> dirtyStatDates = ConcurrentHashMap.newKeySet();
private static final ZoneId STAT_ZONE = ZoneId.of("Asia/Shanghai");
/** 本次订单导入的字段映射(仅主线程在 process 入口设置,用于「有变更才更新」时按映射比较) */ /** 本次订单导入的字段映射(仅主线程在 process 入口设置,用于「有变更才更新」时按映射比较) */
private transient Map<String, MappingField> orderImportFieldMapping; private transient Map<String, MappingField> orderImportFieldMapping;
@@ -243,6 +251,33 @@ public class ImportRuntimeContext {
public Set<String> getPendingRelationKeys() { return pendingRelationKeys; } public Set<String> getPendingRelationKeys() { return pendingRelationKeys; }
public Set<String> getPendingPlatformOrderNos() { return pendingPlatformOrderNos; } public Set<String> getPendingPlatformOrderNos() { return pendingPlatformOrderNos; }
public Set<LocalDate> 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<String> target, String rawValue) { public void addNormalizedValue(Set<String> target, String rawValue) {
@@ -3,6 +3,8 @@ package top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.impl;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException; import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.model.po.ImportTaskPO; 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.ImportTaskService;
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.SseNotificationService; 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.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.service.OrderService;
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.service.OrderStatusService; import top.xyquan.ecomdmbbackend.modules.ecom.order.status.service.OrderStatusService;
import top.xyquan.ecomdmbbackend.modules.ecom.product.mapper.ProductMapper; 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.CharsetDecoder;
import java.nio.charset.CodingErrorAction; import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets; 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.List;
import java.util.Map; import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
@@ -43,6 +53,8 @@ import java.util.stream.Collectors;
@Service @Service
public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorService { public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorService {
private static final Logger log = LoggerFactory.getLogger(ImportTaskProcessorServiceImpl.class);
private final ImportTaskService importTaskService; private final ImportTaskService importTaskService;
private final ProductSpecService productSpecService; private final ProductSpecService productSpecService;
private final OrderMapper orderMapper; private final OrderMapper orderMapper;
@@ -60,6 +72,8 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
private final OrderImportProcessor orderImportProcessor; private final OrderImportProcessor orderImportProcessor;
private final ProductSpecImportHelper productSpecImportHelper; private final ProductSpecImportHelper productSpecImportHelper;
private final PromotionFeeImportProcessor promotionFeeImportProcessor; private final PromotionFeeImportProcessor promotionFeeImportProcessor;
private final OrderStatRefreshCoordinator orderStatRefreshCoordinator;
private final FeeStatRefreshService feeStatRefreshService;
public ImportTaskProcessorServiceImpl(ImportTaskService importTaskService, public ImportTaskProcessorServiceImpl(ImportTaskService importTaskService,
OrderService orderService, OrderService orderService,
@@ -75,7 +89,9 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
SqlSessionFactory sqlSessionFactory, SqlSessionFactory sqlSessionFactory,
OssService ossService, OssService ossService,
SysFileService sysFileService, SysFileService sysFileService,
PromotionFeeImportProcessor promotionFeeImportProcessor) { PromotionFeeImportProcessor promotionFeeImportProcessor,
OrderStatRefreshCoordinator orderStatRefreshCoordinator,
FeeStatRefreshService feeStatRefreshService) {
this.importTaskService = importTaskService; this.importTaskService = importTaskService;
this.productSpecService = productSpecService; this.productSpecService = productSpecService;
this.orderMapper = orderMapper; this.orderMapper = orderMapper;
@@ -89,6 +105,8 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
this.ossService = ossService; this.ossService = ossService;
this.sysFileService = sysFileService; this.sysFileService = sysFileService;
this.promotionFeeImportProcessor = promotionFeeImportProcessor; this.promotionFeeImportProcessor = promotionFeeImportProcessor;
this.orderStatRefreshCoordinator = orderStatRefreshCoordinator;
this.feeStatRefreshService = feeStatRefreshService;
// 初始化 helper 和 processor // 初始化 helper 和 processor
this.productSpecImportHelper = new ProductSpecImportHelper( this.productSpecImportHelper = new ProductSpecImportHelper(
@@ -216,11 +234,42 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
String message = result.failCount > 0 ? summary + "\n" + result.errorMessages.toString() : summary; String message = result.failCount > 0 ? summary + "\n" + result.errorMessages.toString() : summary;
updateTaskStatus(task.getId(), finalStatus, message, result.totalCount, result.successCount, result.failCount); updateTaskStatus(task.getId(), finalStatus, message, result.totalCount, result.successCount, result.failCount);
// 明细写入成功后:异步排队 refresh 汇总表(不阻塞导入线程)
enqueueOrderStatRefreshAfterImport(task, context);
} finally { } finally {
if (tempOssFile != null && tempOssFile.exists()) tempOssFile.delete(); 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<LocalDate> dates = new HashSet<>(context.getDirtyStatDates());
try {
List<LocalDate> 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 { private void processPromotionFeeImport(ImportTaskPO task) throws Exception {
com.fasterxml.jackson.databind.JsonNode rootNode; com.fasterxml.jackson.databind.JsonNode rootNode;
try { try {
@@ -285,12 +334,28 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
message += "\n" + result.detailMessage; message += "\n" + result.detailMessage;
} }
updateTaskStatus(task.getId(), finalStatus, message, result.totalCount, result.successCount, result.failCount); updateTaskStatus(task.getId(), finalStatus, message, result.totalCount, result.successCount, result.failCount);
refreshFeeStatAfterPromotionImport(task, feeDateStr, result.successCount);
} finally { } finally {
if (tempOssFile != null && tempOssFile.exists()) tempOssFile.delete(); 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) { private ImportRuntimeContext.MappingConfig parseMappingConfig(String mappingJson) {
try { try {
if (mappingJson == null || mappingJson.trim().isEmpty()) { if (mappingJson == null || mappingJson.trim().isEmpty()) {
@@ -1080,6 +1080,13 @@ public class OrderImportProcessor {
r.rowNumber, r.platformOrderNo, r.order, r.rowNumber, r.platformOrderNo, r.order,
r.order.getId(), updateMsg, r.order.getId(), updateMsg,
r.dto != null && Boolean.TRUE.equals(r.dto.getOrderTimeEmptyInInput())); 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); context.pendingOrders.add(pending);
if (r.platformOrderNo != null && !r.platformOrderNo.trim().isEmpty()) { if (r.platformOrderNo != null && !r.platformOrderNo.trim().isEmpty()) {
synchronized (context.pendingOrderByPlatformNo) { synchronized (context.pendingOrderByPlatformNo) {
@@ -1612,6 +1619,11 @@ public class OrderImportProcessor {
if (existing != null) { if (existing != null) {
existing.updateData(newOrderPO, existingId, newUpdateMsg, newRowNumber, existing.updateData(newOrderPO, existingId, newUpdateMsg, newRowNumber,
newOrderTimeEmptyInInput); newOrderTimeEmptyInInput);
if (newOrderPO != null && newOrderPO.getOrderTime() != null) {
context.markOrderStatDirty(newOrderPO.getShopId(), newOrderPO.getOrderTime());
}
OrderPO snap = context.existingOrderSnapshotByPlatformNo.get(normalized);
context.markOrderStatDirtyFromSnapshot(snap);
} }
} }
return true; return true;
@@ -4,10 +4,15 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update; 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.model.po.OrderPO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.OrderShopStatDateRow;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.List;
/** /**
* 订单Mapper接口 * 订单Mapper接口
@@ -43,4 +48,40 @@ public interface OrderMapper extends BaseMapper<OrderPO> {
int linkOrdersBySpecCodeWhenSpecIdNull(@Param("companyId") Long companyId, int linkOrdersBySpecCodeWhenSpecIdNull(@Param("companyId") Long companyId,
@Param("specCode") String specCode, @Param("specCode") String specCode,
@Param("productSpecId") Long productSpecId); @Param("productSpecId") Long productSpecId);
/** 导入任务完成后兜底:该任务写入订单涉及的自然日 */
@Select("SELECT DISTINCT DATE(order_time) FROM ec_order WHERE import_task_id = #{importTaskId}")
List<LocalDate> 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<LocalDate> 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<OrderShopStatDateRow> selectOrphanOrderStatDatesBySpecCode(
@Param("companyId") Long companyId,
@Param("specCode") String specCode);
} }
@@ -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.shop.model.vo.ShopVO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductService; import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductService;
import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductSpecService; 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.modules.ecom.shop.service.ShopService;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext; import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.time.ZoneId;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
@@ -51,15 +56,18 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
private final ProductService productService; private final ProductService productService;
private final ProductSpecService productSpecService; private final ProductSpecService productSpecService;
private final OrderStatusService orderStatusService; private final OrderStatusService orderStatusService;
private final OrderStatCrudCoordinator orderStatCrudCoordinator;
public OrderServiceImpl(CurrentUserContext currentUserContext, ShopService shopService, public OrderServiceImpl(CurrentUserContext currentUserContext, ShopService shopService,
ProductService productService, ProductSpecService productSpecService, ProductService productService, ProductSpecService productSpecService,
OrderStatusService orderStatusService) { OrderStatusService orderStatusService,
OrderStatCrudCoordinator orderStatCrudCoordinator) {
this.currentUserContext = currentUserContext; this.currentUserContext = currentUserContext;
this.shopService = shopService; this.shopService = shopService;
this.productService = productService; this.productService = productService;
this.productSpecService = productSpecService; this.productSpecService = productSpecService;
this.orderStatusService = orderStatusService; this.orderStatusService = orderStatusService;
this.orderStatCrudCoordinator = orderStatCrudCoordinator;
} }
/** /**
@@ -131,6 +139,7 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
// 保存订单 // 保存订单
this.save(order); this.save(order);
orderStatCrudCoordinator.afterOrderSaved(null, order);
// 转换为VO并返回 // 转换为VO并返回
return convertToVO(order); return convertToVO(order);
@@ -236,8 +245,11 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
// 更新订单 // 更新订单
this.updateById(order); this.updateById(order);
OrderPO after = this.getById(id);
orderStatCrudCoordinator.afterOrderSaved(existingOrder, after);
// 转换为VO并返回 // 转换为VO并返回
return convertToVO(order); return convertToVO(after != null ? after : order);
} }
/** /**
@@ -257,6 +269,7 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
} }
// 硬删除订单(外键约束会自动处理相关数据) // 硬删除订单(外键约束会自动处理相关数据)
orderStatCrudCoordinator.afterOrderDeleted(existingOrder);
this.removeById(id); this.removeById(id);
} }
@@ -283,10 +296,12 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
LambdaQueryWrapper<OrderPO> wrapper = new LambdaQueryWrapper<>(); LambdaQueryWrapper<OrderPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OrderPO::getCompanyId, companyId) wrapper.eq(OrderPO::getCompanyId, companyId)
.in(OrderPO::getId, uniqueIds); .in(OrderPO::getId, uniqueIds);
long matched = this.count(wrapper); List<OrderPO> toRemove = this.list(wrapper);
long matched = toRemove.size();
if (matched != uniqueIds.size()) { if (matched != uniqueIds.size()) {
throw new BusinessException("存在无效订单或无权删除的订单"); throw new BusinessException("存在无效订单或无权删除的订单");
} }
orderStatCrudCoordinator.afterOrdersDeletedBatch(toRemove);
this.remove(wrapper); this.remove(wrapper);
} }
@@ -485,7 +500,26 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
public int syncCostsToOrders(Long specId, java.math.BigDecimal productCost, public int syncCostsToOrders(Long specId, java.math.BigDecimal productCost,
java.math.BigDecimal shippingCost, java.math.BigDecimal otherCost, java.math.BigDecimal shippingCost, java.math.BigDecimal otherCost,
java.time.LocalDateTime startTime, java.time.LocalDateTime endTime) { 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<OrderPO> affected = list(new LambdaQueryWrapper<OrderPO>()
.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<StatDirtyKey> 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 @Override
@@ -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;
}
}
@@ -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<Long> 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<OrderStatRebuildTaskPO> 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<OrderStatReconcileService.ReconcileReport> 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);
}
}
@@ -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<CompanyPO> 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);
}
}
@@ -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<PromotionFeeStatDailyPO> {
void deletePromotionDaily(@Param("companyId") Long companyId,
@Param("shopId") Long shopId,
@Param("statDate") LocalDate statDate);
void batchInsertPromotionDaily(@Param("list") List<PromotionFeeStatDailyPO> 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<PromotionFeeAggRow> 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;
}
}
@@ -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<OrderStatDailyShopPO> {
void upsertDailyShop(OrderStatDailyShopPO row);
void deleteDailyProduct(@Param("companyId") Long companyId,
@Param("shopId") Long shopId,
@Param("statDate") LocalDate statDate);
void batchInsertDailyProduct(@Param("list") List<OrderStatDailyProductPO> list);
void deleteDailySpec(@Param("companyId") Long companyId,
@Param("shopId") Long shopId,
@Param("statDate") LocalDate statDate);
void batchInsertDailySpec(@Param("list") List<OrderStatDailySpecPO> 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);
}
@@ -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<Long> shopIds,
@Param("startDate") LocalDate startDate,
@Param("endDate") LocalDate endDate);
List<OrderStatMetricsDTO> sumDailyShopByDay(@Param("companyId") Long companyId,
@Param("shopIds") List<Long> shopIds,
@Param("startDate") LocalDate startDate,
@Param("endDate") LocalDate endDate);
List<OrderStatMetricsDTO> sumDailyShopByShop(@Param("companyId") Long companyId,
@Param("shopIds") List<Long> shopIds,
@Param("startDate") LocalDate startDate,
@Param("endDate") LocalDate endDate);
List<OrderStatMetricsDTO> sumDailyProductByCategory(@Param("companyId") Long companyId,
@Param("shopIds") List<Long> shopIds,
@Param("startDate") LocalDate startDate,
@Param("endDate") LocalDate endDate);
List<OrderStatMetricsDTO> sumDailyProductByProduct(@Param("companyId") Long companyId,
@Param("shopIds") List<Long> shopIds,
@Param("startDate") LocalDate startDate,
@Param("endDate") LocalDate endDate);
List<OrderStatMetricsDTO> sumDailyProductByShopProduct(@Param("companyId") Long companyId,
@Param("shopIds") List<Long> shopIds,
@Param("startDate") LocalDate startDate,
@Param("endDate") LocalDate endDate);
OrderStatMetricsDTO sumDailyProductForOneProduct(@Param("companyId") Long companyId,
@Param("shopIds") List<Long> shopIds,
@Param("productId") Long productId,
@Param("startDate") LocalDate startDate,
@Param("endDate") LocalDate endDate);
List<OrderStatMetricsDTO> sumDailyProductByDayForOneProduct(@Param("companyId") Long companyId,
@Param("shopIds") List<Long> shopIds,
@Param("productId") Long productId,
@Param("startDate") LocalDate startDate,
@Param("endDate") LocalDate endDate);
List<OrderStatMetricsDTO> sumMonthlyProductByCategory(@Param("companyId") Long companyId,
@Param("shopIds") List<Long> shopIds,
@Param("startMonth") LocalDate startMonth,
@Param("endMonth") LocalDate endMonth);
List<OrderStatMetricsDTO> sumMonthlyProductByProduct(@Param("companyId") Long companyId,
@Param("shopIds") List<Long> shopIds,
@Param("startMonth") LocalDate startMonth,
@Param("endMonth") LocalDate endMonth);
List<OrderStatMetricsDTO> sumYearlyProductByCategory(@Param("companyId") Long companyId,
@Param("shopIds") List<Long> shopIds,
@Param("startYear") int startYear,
@Param("endYear") int endYear);
List<OrderStatMetricsDTO> sumYearlyProductByProduct(@Param("companyId") Long companyId,
@Param("shopIds") List<Long> shopIds,
@Param("startYear") int startYear,
@Param("endYear") int endYear);
List<OrderStatMetricsDTO> sumDailySpecBySpec(@Param("companyId") Long companyId,
@Param("shopIds") List<Long> shopIds,
@Param("productId") Long productId,
@Param("startDate") LocalDate startDate,
@Param("endDate") LocalDate endDate);
List<OrderStatMetricsDTO> sumMonthlySpecBySpec(@Param("companyId") Long companyId,
@Param("shopIds") List<Long> shopIds,
@Param("productId") Long productId,
@Param("startMonth") LocalDate startMonth,
@Param("endMonth") LocalDate endMonth);
List<OrderStatMetricsDTO> sumYearlySpecBySpec(@Param("companyId") Long companyId,
@Param("shopIds") List<Long> shopIds,
@Param("productId") Long productId,
@Param("startYear") int startYear,
@Param("endYear") int endYear);
int countDailyShopRows(@Param("companyId") Long companyId,
@Param("shopIds") List<Long> shopIds,
@Param("startDate") LocalDate startDate,
@Param("endDate") LocalDate endDate);
}
@@ -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<OrderStatRebuildTaskPO> {
}
@@ -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<OrderStatRefreshQueuePO> {
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<SpecDayRow> aggregateSpecByShopDay(
@Param("companyId") Long companyId,
@Param("shopId") Long shopId,
@Param("start") LocalDateTime start,
@Param("end") LocalDateTime end,
@Param("unionStatusIds") List<Long> unionStatusIds,
@Param("salesStatusIds") List<Long> salesStatusIds,
@Param("refundStatusIds") List<Long> refundStatusIds,
@Param("productCostStatusIds") List<Long> productCostStatusIds,
@Param("freightCostStatusIds") List<Long> freightCostStatusIds,
@Param("otherCostStatusIds") List<Long> 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;
}
}
@@ -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;
}
@@ -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;
}
}
@@ -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;
}
@@ -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;
}
@@ -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;
}
@@ -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;
}
@@ -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;
}
@@ -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;
}
@@ -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;
}
@@ -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;
}
@@ -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<ShopDay> keys = new HashSet<>();
addPromotionKey(keys, before);
addPromotionKey(keys, after);
runAfterCommit(keys);
}
public void afterPromotionFeeDeleted(PromotionFeePO before) {
Set<ShopDay> keys = new HashSet<>();
addPromotionKey(keys, before);
runAfterCommit(keys);
}
public void afterBrushOrderSaved(BrushOrderPO before, BrushOrderPO after) {
Set<ShopDay> keys = new HashSet<>();
addBrushKey(keys, before);
addBrushKey(keys, after);
runAfterCommit(keys);
}
public void afterBrushOrderDeleted(BrushOrderPO before) {
Set<ShopDay> keys = new HashSet<>();
addBrushKey(keys, before);
runAfterCommit(keys);
}
private void runAfterCommit(Set<ShopDay> 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<ShopDay> 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<ShopDay> 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) {}
}
@@ -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<FeeStatDailyMapper.PromotionFeeAggRow> rows =
feeStatDailyMapper.aggregatePromotionByShopDay(companyId, shopId, statDate);
if (rows == null || rows.isEmpty()) {
return;
}
List<PromotionFeeStatDailyPO> 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);
}
}
@@ -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<String, Object> redisTemplate;
public OrderStatCacheService(OrderStatProperties properties,
RedisTemplate<String, Object> 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> T get(String cacheKey, Class<T> 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;
}
}
@@ -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<StatDirtyKey> keys = new HashSet<>();
addKey(keys, before);
addKey(keys, after);
runAfterCommit(keys, true);
}
/** 单条删除后 */
public void afterOrderDeleted(OrderPO before) {
Set<StatDirtyKey> keys = new HashSet<>();
addKey(keys, before);
runAfterCommit(keys, true);
}
/** 批量删除:异步入队(避免一次 refresh 过多) */
public void afterOrdersDeletedBatch(List<OrderPO> removed) {
if (removed == null || removed.isEmpty()) {
return;
}
Set<StatDirtyKey> keys = new HashSet<>();
for (OrderPO o : removed) {
addKey(keys, o);
}
runAfterCommit(keys, false);
}
/** 规格补链等批量影响:异步入队 */
public void enqueueDirtyKeys(Collection<StatDirtyKey> 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<StatDirtyKey> 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<StatDirtyKey> 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<StatDirtyKey> 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<StatDirtyKey> 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));
}
}
@@ -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<ShopPO> shops,
LocalDate startDate, LocalDate endDate,
BigDecimal taxRate, OrderStatusStatSets stat) {
List<Long> 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<OrderStatAggMapper.PromotionRow> promoRows = orderStatReadFacade.loadPromotionRows(
companyId, shopIds, startDate, endDate);
List<OrderStatAggMapper.BrushRow> 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<OrderStatAggMapper.ShopProductRow> 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<CompanyOverviewVO.ShopSalesRatio> buildShopSalesRatios(Long companyId, List<Long> shopIds,
List<ShopPO> shops,
LocalDate start, LocalDate end,
BigDecimal totalSales) {
List<OrderStatMetricsDTO> byShop = orderStatReadFacade.sumShopMetricsByShop(companyId, shopIds, start, end);
Map<Long, BigDecimal> salesMap = new HashMap<>();
for (OrderStatMetricsDTO m : byShop) {
if (m.getShopId() != null) {
salesMap.put(m.getShopId(), nz(m.getSalesAmount()));
}
}
List<CompanyOverviewVO.ShopSalesRatio> 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<Long> shopIds,
LocalDate start, LocalDate end) {
List<OrderStatMetricsDTO> daily = orderStatReadFacade.sumShopMetricsByDay(companyId, shopIds, start, end);
Map<LocalDate, BigDecimal> 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<Long> shopIds,
LocalDate start, LocalDate end) {
List<OrderStatMetricsDTO> daily = orderStatReadFacade.sumShopMetricsByDay(companyId, shopIds, start, end);
Map<LocalDate, BigDecimal> 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<LocalDate, BigDecimal> map) {
List<CompanyOverviewVO.TrendDataItem> 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<CompanyOverviewVO.ShopEfficiencyQuadrant> buildShopEfficiency(
CompanyOverviewVO.ShopOverview shopOverview) {
if (shopOverview == null || shopOverview.getShops() == null) {
return List.of();
}
List<CompanyOverviewVO.ShopEfficiencyQuadrant> 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;
}
}
@@ -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<Long> 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<OrderStatMetricsDTO> sumShopMetricsByDay(Long companyId, List<Long> shopIds,
LocalDate startDate, LocalDate endDate) {
requireDailySource();
ensureStatReady(companyId, shopIds, startDate, endDate);
List<OrderStatMetricsDTO> rows = orderStatQueryMapper.sumDailyShopByDay(companyId, shopIds, startDate, endDate);
return rows != null ? rows : Collections.emptyList();
}
public List<OrderStatMetricsDTO> sumShopMetricsByShop(Long companyId, List<Long> shopIds,
LocalDate startDate, LocalDate endDate) {
requireDailySource();
ensureStatReady(companyId, shopIds, startDate, endDate);
List<OrderStatMetricsDTO> rows = orderStatQueryMapper.sumDailyShopByShop(companyId, shopIds, startDate, endDate);
return rows != null ? rows : Collections.emptyList();
}
public List<OrderStatMetricsDTO> sumProductMetricsByCategory(Long companyId, List<Long> 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<OrderStatMetricsDTO> sumProductMetricsByProduct(Long companyId, List<Long> 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<OrderStatMetricsDTO> sumSpecMetricsBySpec(Long companyId, List<Long> 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(不阻塞读路径)。
* <p>
* 若区间内无 ec_order 明细(如同比去年、未来日期),空汇总结果是正确口径,不应打日志或入队。
*/
public void ensureStatReady(Long companyId, List<Long> 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<LocalDate> 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<OrderStatMetricsDTO> nullSafe(List<OrderStatMetricsDTO> 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
}
}
@@ -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<OrderStatAggMapper.ShopProductRow> loadShopProductRows(Long companyId, List<Long> 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<Long, Long> platformByShop = platformByShop(shopIds);
List<OrderStatMetricsDTO> rows = orderStatQueryMapper.sumDailyProductByShopProduct(
companyId, shopIds, startDate, endDate);
if (rows == null || rows.isEmpty()) {
return Collections.emptyList();
}
List<OrderStatAggMapper.ShopProductRow> 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<OrderStatAggMapper.DailyRow> loadDailyRows(Long companyId, List<Long> 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<OrderStatMetricsDTO> rows = orderStatQueryService.sumShopMetricsByDay(
companyId, shopIds, startDate, endDate);
List<OrderStatAggMapper.DailyRow> 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<Long> 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<Long> shopIds,
LocalDate startDate, LocalDate endDate) {
if (!usesDailyStatSource()) {
OrderStatusStatSets stat = OrderStatusStatSets.from(List.of());
List<OrderStatAggMapper.ShopProductRow> 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<OrderStatMetricsDTO> sumShopMetricsByDay(Long companyId, List<Long> shopIds,
LocalDate startDate, LocalDate endDate) {
if (!usesDailyStatSource()) {
return Collections.emptyList();
}
return orderStatQueryService.sumShopMetricsByDay(companyId, shopIds, startDate, endDate);
}
public List<OrderStatMetricsDTO> sumShopMetricsByShop(Long companyId, List<Long> shopIds,
LocalDate startDate, LocalDate endDate) {
if (!usesDailyStatSource()) {
return Collections.emptyList();
}
orderStatQueryService.ensureStatReady(companyId, shopIds, startDate, endDate);
List<OrderStatMetricsDTO> rows = orderStatQueryMapper.sumDailyShopByShop(
companyId, shopIds, startDate, endDate);
return rows != null ? rows : Collections.emptyList();
}
public OrderStatMetricsDTO sumProductForOne(Long companyId, List<Long> 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<OrderStatMetricsDTO> sumProductByDayForOne(Long companyId, List<Long> shopIds, Long productId,
LocalDate startDate, LocalDate endDate) {
if (!usesDailyStatSource()) {
return Collections.emptyList();
}
orderStatQueryService.ensureStatReady(companyId, shopIds, startDate, endDate);
List<OrderStatMetricsDTO> rows = orderStatQueryMapper.sumDailyProductByDayForOneProduct(
companyId, shopIds, productId, startDate, endDate);
return rows != null ? rows : Collections.emptyList();
}
public List<OrderStatMetricsDTO> sumSpecMetrics(Long companyId, List<Long> shopIds, Long productId,
LocalDate startDate, LocalDate endDate) {
if (!usesDailyStatSource()) {
return Collections.emptyList();
}
return orderStatQueryService.sumSpecMetricsBySpec(companyId, shopIds, productId, startDate, endDate);
}
/** 推广/刷单仍走明细表 SQL(数据量小) */
public List<OrderStatAggMapper.PromotionRow> loadPromotionRows(Long companyId, List<Long> shopIds,
LocalDate startDate, LocalDate endDate) {
List<OrderStatAggMapper.PromotionRow> rows = orderStatAggMapper.aggregatePromotionFees(
companyId, shopIds, startDate, endDate);
return rows != null ? rows : Collections.emptyList();
}
public List<OrderStatAggMapper.BrushRow> loadBrushRows(Long companyId, List<Long> shopIds,
LocalDateTime start, LocalDateTime end) {
List<OrderStatAggMapper.BrushRow> rows = orderStatAggMapper.aggregateBrushFees(
companyId, shopIds, start, end);
return rows != null ? rows : Collections.emptyList();
}
public OrderStatAggMapper.FeeKpiRow loadPromotionPeriodKpi(Long companyId, List<Long> 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<Long> 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<Long, Long> platformByShop(List<Long> 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;
}
}
@@ -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<OrderStatRebuildTaskMapper, OrderStatRebuildTaskPO> {
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<Long> 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<LocalDate> 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<Long> resolveShopIds(Long companyId, Long shopId) {
if (shopId != null) {
return List.of(shopId);
}
return shopService.list(new LambdaQueryWrapper<ShopPO>().eq(ShopPO::getCompanyId, companyId))
.stream().map(ShopPO::getId).toList();
}
}
@@ -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<ShopPO> shops = shopService.lambdaQuery().eq(ShopPO::getCompanyId, companyId).list();
if (shops.isEmpty()) {
report.setMessage("无店铺");
return report;
}
OrderStatusStatSets stat = orderStatusStatResolver.resolve(companyId);
List<SampleKey> 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<OrderStatAggMapper.ShopProductRow> 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<SampleKey> pickSamples(Long companyId, List<ShopPO> shops,
LocalDate start, LocalDate end, int sampleSize) {
List<SampleKey> pool = new ArrayList<>();
for (ShopPO shop : shops) {
List<LocalDate> 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<Long> list(java.util.Set<Long> 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<ReconcileItem> 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<ReconcileItem> getItems() { return items; }
public void setItems(List<ReconcileItem> 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; }
}
}
@@ -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<OrderStatRefreshMapper, OrderStatRefreshQueuePO> {
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<LocalDate> statDates, RefreshSource source) {
if (companyId == null || shopId == null || statDates == null || statDates.isEmpty()) {
return 0;
}
Set<LocalDate> 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<StatDirtyKey> 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<OrderStatRefreshQueuePO> 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);
}
}
}
}
@@ -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<Long> shopIds = List.of(shopId);
List<OrderStatAggMapper.ShopProductRow> 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<OrderStatDailyProductPO> dailyProducts = buildProductRows(companyId, shopId, statDate, productRows);
if (!dailyProducts.isEmpty()) {
orderStatDailyMapper.batchInsertDailyProduct(dailyProducts);
}
orderStatDailyMapper.deleteDailySpec(companyId, shopId, statDate);
List<OrderStatRefreshMapper.SpecDayRow> 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<OrderStatDailySpecPO> 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<OrderStatAggMapper.ShopProductRow> 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<OrderStatDailyProductPO> buildProductRows(Long companyId, Long shopId, LocalDate statDate,
List<OrderStatAggMapper.ShopProductRow> rows) {
List<OrderStatDailyProductPO> 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<OrderStatDailySpecPO> buildSpecRows(Long companyId, Long shopId, LocalDate statDate,
List<OrderStatRefreshMapper.SpecDayRow> rows) {
List<OrderStatDailySpecPO> 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;
}
}
@@ -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;
}
}
}
}
}
@@ -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);
}
}
@@ -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<Long> statusList(java.util.Collection<Long> ids) {
if (ids == null || ids.isEmpty()) {
return List.of(-1L);
}
List<Long> list = new ArrayList<>(ids);
Collections.sort(list);
return list;
}
public static List<Long> unionList(OrderStatusStatSets stat) {
return statusList(stat.getUnionStatusIds());
}
public static List<Long> salesList(OrderStatusStatSets stat) {
return statusList(stat.getSalesIds());
}
public static List<Long> refundList(OrderStatusStatSets stat) {
return statusList(stat.getRefundIds());
}
public static List<Long> productCostList(OrderStatusStatSets stat) {
return statusList(stat.getProductCostIds());
}
public static List<Long> freightCostList(OrderStatusStatSets stat) {
return statusList(stat.getFreightCostIds());
}
public static List<Long> otherCostList(OrderStatusStatSets stat) {
return statusList(stat.getOtherCostIds());
}
}
@@ -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
}
@@ -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");
}
}
@@ -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.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException; 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.mapper.OrderStatusMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.model.dto.CreateOrderStatusDTO; import top.xyquan.ecomdmbbackend.modules.ecom.order.status.model.dto.CreateOrderStatusDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.model.dto.PatchOrderStatusDTO; 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.modules.ecom.order.status.service.OrderStatusService;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext; import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.time.LocalDate;
import java.util.List; import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
@@ -25,9 +30,15 @@ import java.util.stream.Collectors;
public class OrderStatusServiceImpl extends ServiceImpl<OrderStatusMapper, OrderStatusPO> implements OrderStatusService { public class OrderStatusServiceImpl extends ServiceImpl<OrderStatusMapper, OrderStatusPO> implements OrderStatusService {
private final CurrentUserContext currentUserContext; 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.currentUserContext = currentUserContext;
this.orderStatRebuildService = orderStatRebuildService;
this.orderMapper = orderMapper;
} }
/** /**
@@ -99,6 +110,9 @@ public class OrderStatusServiceImpl extends ServiceImpl<OrderStatusMapper, Order
throw new BusinessException("状态名称已存在"); throw new BusinessException("状态名称已存在");
} }
// 更新前快照五维开关,用于检测是否需全公司 rebuild
OrderStatusPO beforeStat = snapshotStatDimensions(existingStatus);
// 更新订单状态 // 更新订单状态
OrderStatusPO orderStatus = new OrderStatusPO(); OrderStatusPO orderStatus = new OrderStatusPO();
BeanUtils.copyProperties(updateOrderStatusDTO, orderStatus); BeanUtils.copyProperties(updateOrderStatusDTO, orderStatus);
@@ -111,6 +125,8 @@ public class OrderStatusServiceImpl extends ServiceImpl<OrderStatusMapper, Order
// 更新订单状态 // 更新订单状态
this.updateById(orderStatus); this.updateById(orderStatus);
maybeScheduleCompanyRebuild(companyId, beforeStat, snapshotStatDimensions(orderStatus));
// 转换为VO并返回 // 转换为VO并返回
return convertToVO(orderStatus); return convertToVO(orderStatus);
} }
@@ -133,6 +149,8 @@ public class OrderStatusServiceImpl extends ServiceImpl<OrderStatusMapper, Order
throw new BusinessException("订单状态不存在"); throw new BusinessException("订单状态不存在");
} }
OrderStatusPO beforeStat = snapshotStatDimensions(existingStatus);
if (patchDTO.getIncludeSalesAmount() != null) { if (patchDTO.getIncludeSalesAmount() != null) {
existingStatus.setIncludeSalesAmount(patchDTO.getIncludeSalesAmount()); existingStatus.setIncludeSalesAmount(patchDTO.getIncludeSalesAmount());
} }
@@ -151,6 +169,7 @@ public class OrderStatusServiceImpl extends ServiceImpl<OrderStatusMapper, Order
existingStatus.setUpdateBy(currentUserContext.getCurrentUserId()); existingStatus.setUpdateBy(currentUserContext.getCurrentUserId());
this.updateById(existingStatus); this.updateById(existingStatus);
maybeScheduleCompanyRebuild(companyId, beforeStat, snapshotStatDimensions(existingStatus));
return convertToVO(existingStatus); return convertToVO(existingStatus);
} }
@@ -174,6 +193,9 @@ public class OrderStatusServiceImpl extends ServiceImpl<OrderStatusMapper, Order
// 检查是否有订单使用此状态 // 检查是否有订单使用此状态
// TODO: 这里可以添加检查逻辑,如果有订单使用此状态,可以阻止删除或提示 // TODO: 这里可以添加检查逻辑,如果有订单使用此状态,可以阻止删除或提示
// 删除后统计口径集合变化,需全公司 rebuild
scheduleCompanyRebuild(companyId);
// 删除订单状态 // 删除订单状态
this.removeById(id); this.removeById(id);
} }
@@ -232,6 +254,45 @@ public class OrderStatusServiceImpl extends ServiceImpl<OrderStatusMapper, Order
return vo; return vo;
} }
/** 五维统计开关是否变化(影响历史汇总列含义) */
private static boolean statDimensionsChanged(OrderStatusPO before, OrderStatusPO after) {
if (before == null || after == null) {
return false;
}
return !Objects.equals(before.getIncludeSalesAmount(), after.getIncludeSalesAmount())
|| !Objects.equals(before.getIncludeProductCost(), after.getIncludeProductCost())
|| !Objects.equals(before.getIncludeFreightCost(), after.getIncludeFreightCost())
|| !Objects.equals(before.getIncludeOtherCost(), after.getIncludeOtherCost())
|| !Objects.equals(before.getIncludeRefund(), after.getIncludeRefund());
}
private static OrderStatusPO snapshotStatDimensions(OrderStatusPO src) {
OrderStatusPO copy = new OrderStatusPO();
copy.setIncludeSalesAmount(src.getIncludeSalesAmount());
copy.setIncludeProductCost(src.getIncludeProductCost());
copy.setIncludeFreightCost(src.getIncludeFreightCost());
copy.setIncludeOtherCost(src.getIncludeOtherCost());
copy.setIncludeRefund(src.getIncludeRefund());
return copy;
}
private void maybeScheduleCompanyRebuild(Long companyId, OrderStatusPO before, OrderStatusPO after) {
if (!statDimensionsChanged(before, after)) {
return;
}
scheduleCompanyRebuild(companyId);
}
/** 状态配置变更后异步全公司 backfill */
private void scheduleCompanyRebuild(Long companyId) {
LocalDate start = orderMapper.selectMinOrderDateByCompany(companyId);
LocalDate end = orderMapper.selectMaxOrderDateByCompany(companyId);
if (start == null || end == null) {
return;
}
orderStatRebuildService.scheduleRebuild(companyId, null, start, end);
}
/** 创建时未传的统计开关默认:前四项参与(等同原 auto_statistics=1),退款不参与 */ /** 创建时未传的统计开关默认:前四项参与(等同原 auto_statistics=1),退款不参与 */
private void applyStatDefaultsForCreate(OrderStatusPO p) { private void applyStatDefaultsForCreate(OrderStatusPO p) {
if (p.getIncludeSalesAmount() == null) { if (p.getIncludeSalesAmount() == null) {
@@ -1,6 +1,7 @@
package top.xyquan.ecomdmbbackend.modules.ecom.order.status.support; package top.xyquan.ecomdmbbackend.modules.ecom.order.status.support;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.model.po.OrderStatusPO; import top.xyquan.ecomdmbbackend.modules.ecom.order.status.model.po.OrderStatusPO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.service.OrderStatusService; import top.xyquan.ecomdmbbackend.modules.ecom.order.status.service.OrderStatusService;
@@ -15,7 +16,7 @@ public class OrderStatusStatResolver {
private final OrderStatusService orderStatusService; private final OrderStatusService orderStatusService;
public OrderStatusStatResolver(OrderStatusService orderStatusService) { public OrderStatusStatResolver(@Lazy OrderStatusService orderStatusService) {
this.orderStatusService = orderStatusService; this.orderStatusService = orderStatusService;
} }
@@ -4,8 +4,10 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException; import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.modules.ecom.brushorder.mapper.BrushOrderMapper; import top.xyquan.ecomdmbbackend.modules.ecom.brushorder.mapper.BrushOrderMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper; 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.OrderStatOverviewAssembler;
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatReadFacade;
import top.xyquan.ecomdmbbackend.modules.ecom.platform.mapper.PlatformMapper; import top.xyquan.ecomdmbbackend.modules.ecom.platform.mapper.PlatformMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.platform.model.po.PlatformPO; import top.xyquan.ecomdmbbackend.modules.ecom.platform.model.po.PlatformPO;
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.mapper.PromotionFeeMapper; import top.xyquan.ecomdmbbackend.modules.ecom.promotion.mapper.PromotionFeeMapper;
@@ -64,6 +66,8 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
private final ProductSpecMapper productSpecMapper; private final ProductSpecMapper productSpecMapper;
private final CategoryService categoryService; private final CategoryService categoryService;
private final PlatformMapper platformMapper; private final PlatformMapper platformMapper;
private final OrderStatReadFacade orderStatReadFacade;
private final OrderStatOverviewAssembler orderStatOverviewAssembler;
public CompanyOverviewServiceImpl(CurrentUserContext currentUserContext, public CompanyOverviewServiceImpl(CurrentUserContext currentUserContext,
OrderMapper orderMapper, OrderMapper orderMapper,
@@ -75,7 +79,9 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
ProductMapper productMapper, ProductMapper productMapper,
ProductSpecMapper productSpecMapper, ProductSpecMapper productSpecMapper,
CategoryService categoryService, CategoryService categoryService,
PlatformMapper platformMapper) { PlatformMapper platformMapper,
OrderStatReadFacade orderStatReadFacade,
OrderStatOverviewAssembler orderStatOverviewAssembler) {
this.currentUserContext = currentUserContext; this.currentUserContext = currentUserContext;
this.orderMapper = orderMapper; this.orderMapper = orderMapper;
this.promotionFeeMapper = promotionFeeMapper; this.promotionFeeMapper = promotionFeeMapper;
@@ -87,6 +93,8 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
this.productSpecMapper = productSpecMapper; this.productSpecMapper = productSpecMapper;
this.categoryService = categoryService; this.categoryService = categoryService;
this.platformMapper = platformMapper; this.platformMapper = platformMapper;
this.orderStatReadFacade = orderStatReadFacade;
this.orderStatOverviewAssembler = orderStatOverviewAssembler;
} }
/** /**
@@ -150,6 +158,15 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
throw new BusinessException("当前公司没有店铺"); throw new BusinessException("当前公司没有店铺");
} }
// 汇总表读路径
if (orderStatReadFacade.usesDailyStatSource()) {
CompanyOverviewVO statVo = orderStatOverviewAssembler.buildCompanyOverview(
companyId, shops, startDate, endDate, taxRate, stat);
calculateTargetData(statVo, companyId, startDate, endDate,
statVo.getTotalSalesAmount(), statVo.getTotalOrderCount());
return statVo;
}
// 查询订单数据(所有店铺) // 查询订单数据(所有店铺)
LambdaQueryWrapper<OrderPO> orderWrapper = new LambdaQueryWrapper<>(); LambdaQueryWrapper<OrderPO> orderWrapper = new LambdaQueryWrapper<>();
orderWrapper.eq(OrderPO::getCompanyId, companyId) orderWrapper.eq(OrderPO::getCompanyId, companyId)
@@ -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.model.po.CategoryPO;
import top.xyquan.ecomdmbbackend.modules.ecom.category.service.CategoryService; 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.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.promotion.mapper.PromotionFeeMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.ShopOverviewQueryDTO; import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.ShopOverviewQueryDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.brushorder.model.po.BrushOrderPO; 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.model.po.ShopPO;
import top.xyquan.ecomdmbbackend.modules.ecom.shop.monthlytarget.mapper.ShopMonthlyTargetMapper; 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.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.overview.model.vo.ShopOverviewStatisticsVO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductService; import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductService;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.service.ShopOverviewStatisticsService; import top.xyquan.ecomdmbbackend.modules.ecom.overview.service.ShopOverviewStatisticsService;
@@ -60,6 +65,8 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics
private final ProductSpecMapper productSpecMapper; private final ProductSpecMapper productSpecMapper;
private final OrderStatusStatResolver orderStatusStatResolver; private final OrderStatusStatResolver orderStatusStatResolver;
private final CategoryService categoryService; private final CategoryService categoryService;
private final OrderStatReadFacade orderStatReadFacade;
private final CompanyOverviewService companyOverviewService;
public ShopOverviewStatisticsServiceImpl(CurrentUserContext currentUserContext, public ShopOverviewStatisticsServiceImpl(CurrentUserContext currentUserContext,
OrderMapper orderMapper, OrderMapper orderMapper,
@@ -70,7 +77,9 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics
ProductService productService, ProductService productService,
ProductSpecMapper productSpecMapper, ProductSpecMapper productSpecMapper,
OrderStatusStatResolver orderStatusStatResolver, OrderStatusStatResolver orderStatusStatResolver,
CategoryService categoryService) { CategoryService categoryService,
OrderStatReadFacade orderStatReadFacade,
CompanyOverviewService companyOverviewService) {
this.currentUserContext = currentUserContext; this.currentUserContext = currentUserContext;
this.orderMapper = orderMapper; this.orderMapper = orderMapper;
this.promotionFeeMapper = promotionFeeMapper; this.promotionFeeMapper = promotionFeeMapper;
@@ -81,6 +90,8 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics
this.productSpecMapper = productSpecMapper; this.productSpecMapper = productSpecMapper;
this.orderStatusStatResolver = orderStatusStatResolver; this.orderStatusStatResolver = orderStatusStatResolver;
this.categoryService = categoryService; this.categoryService = categoryService;
this.orderStatReadFacade = orderStatReadFacade;
this.companyOverviewService = companyOverviewService;
} }
/** /**
@@ -128,6 +139,10 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics
throw new BusinessException("店铺不存在"); throw new BusinessException("店铺不存在");
} }
if (orderStatReadFacade.usesDailyStatSource()) {
return getShopOverviewFromStat(queryDTO, companyId, shop, startDate, endDate, stat);
}
// 查询订单数据(该店铺) // 查询订单数据(该店铺)
LambdaQueryWrapper<OrderPO> orderWrapper = new LambdaQueryWrapper<>(); LambdaQueryWrapper<OrderPO> orderWrapper = new LambdaQueryWrapper<>();
orderWrapper.eq(OrderPO::getCompanyId, companyId) orderWrapper.eq(OrderPO::getCompanyId, companyId)
@@ -1013,5 +1028,165 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics
total.setProfitAfterTax(profitAfterTax.setScale(2, RoundingMode.HALF_UP)); total.setProfitAfterTax(profitAfterTax.setScale(2, RoundingMode.HALF_UP));
return total; return total;
} }
/** 汇总表读路径:单店概览 */
private ShopOverviewStatisticsVO getShopOverviewFromStat(ShopOverviewQueryDTO queryDTO,
Long companyId, ShopPO shop,
LocalDate startDate, LocalDate endDate,
OrderStatusStatSets stat) {
List<Long> 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<OrderStatAggMapper.PromotionRow> promoRows = orderStatReadFacade.loadPromotionRows(
companyId, shopIds, startDate, endDate);
List<OrderStatAggMapper.BrushRow> 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<OrderStatMetricsDTO> 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<OrderStatAggMapper.ShopProductRow> 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<OrderStatMetricsDTO> daily,
LocalDate start, LocalDate end,
java.util.function.Function<OrderStatMetricsDTO, BigDecimal> fn) {
Map<LocalDate, BigDecimal> map = new HashMap<>();
for (OrderStatMetricsDTO d : daily) {
if (d.getStatDate() != null) {
map.put(d.getStatDate(), fn.apply(d));
}
}
List<ShopOverviewStatisticsVO.TrendDataItem> 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;
}
} }
@@ -3,8 +3,10 @@ package top.xyquan.ecomdmbbackend.modules.ecom.product.overview.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException; 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.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.OrderStatusStatResolver;
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets; import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets;
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductPO; 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 ProductSpecMapper productSpecMapper;
private final ShopMonthlyTargetMapper shopMonthlyTargetMapper; private final ShopMonthlyTargetMapper shopMonthlyTargetMapper;
private final ShopService shopService; private final ShopService shopService;
private final OrderStatReadFacade orderStatReadFacade;
public ProductOverviewServiceImpl(CurrentUserContext currentUserContext, public ProductOverviewServiceImpl(CurrentUserContext currentUserContext,
OrderMapper orderMapper, OrderMapper orderMapper,
@@ -52,7 +55,8 @@ public class ProductOverviewServiceImpl implements ProductOverviewService {
ProductService productService, ProductService productService,
ProductSpecMapper productSpecMapper, ProductSpecMapper productSpecMapper,
ShopMonthlyTargetMapper shopMonthlyTargetMapper, ShopMonthlyTargetMapper shopMonthlyTargetMapper,
ShopService shopService) { ShopService shopService,
OrderStatReadFacade orderStatReadFacade) {
this.currentUserContext = currentUserContext; this.currentUserContext = currentUserContext;
this.orderMapper = orderMapper; this.orderMapper = orderMapper;
this.promotionFeeMapper = promotionFeeMapper; this.promotionFeeMapper = promotionFeeMapper;
@@ -61,6 +65,7 @@ public class ProductOverviewServiceImpl implements ProductOverviewService {
this.productSpecMapper = productSpecMapper; this.productSpecMapper = productSpecMapper;
this.shopMonthlyTargetMapper = shopMonthlyTargetMapper; this.shopMonthlyTargetMapper = shopMonthlyTargetMapper;
this.shopService = shopService; this.shopService = shopService;
this.orderStatReadFacade = orderStatReadFacade;
} }
private void applyProductOverviewOrderScope(LambdaQueryWrapper<OrderPO> wrapper, private void applyProductOverviewOrderScope(LambdaQueryWrapper<OrderPO> wrapper,
@@ -133,6 +138,11 @@ public class ProductOverviewServiceImpl implements ProductOverviewService {
OrderStatusStatSets stat = orderStatusStatResolver.resolve(companyId); OrderStatusStatSets stat = orderStatusStatResolver.resolve(companyId);
List<Long> unionStatusIds = stat.getUnionStatusIds(); List<Long> unionStatusIds = stat.getUnionStatusIds();
if (orderStatReadFacade.usesDailyStatSource()) {
return getProductOverviewFromStat(queryDTO, companyId, product, filterShopId,
startDate, endDate, taxRate, stat);
}
// 查询订单数据 // 查询订单数据
LambdaQueryWrapper<OrderPO> orderWrapper = new LambdaQueryWrapper<>(); LambdaQueryWrapper<OrderPO> orderWrapper = new LambdaQueryWrapper<>();
applyProductOverviewOrderScope(orderWrapper, companyId, queryDTO.getProductId(), filterShopId, applyProductOverviewOrderScope(orderWrapper, companyId, queryDTO.getProductId(), filterShopId,
@@ -819,4 +829,218 @@ public class ProductOverviewServiceImpl implements ProductOverviewService {
.limit(10) .limit(10)
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
/** 汇总表读路径:商品概览 */
private ProductOverviewVO getProductOverviewFromStat(ProductOverviewQueryDTO queryDTO,
Long companyId, ProductPO product,
Long filterShopId,
LocalDate startDate, LocalDate endDate,
BigDecimal taxRate, OrderStatusStatSets stat) {
List<Long> 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<PromotionFeePO> promotionFees = new ArrayList<>();
if (!shopIds.isEmpty()) {
LambdaQueryWrapper<PromotionFeePO> 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<PromotionFeePO> 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<OrderStatMetricsDTO> daily,
LocalDate start, LocalDate end,
java.util.function.Function<OrderStatMetricsDTO, BigDecimal> fn) {
Map<LocalDate, BigDecimal> map = new HashMap<>();
for (OrderStatMetricsDTO d : daily) {
if (d.getStatDate() != null) {
map.put(d.getStatDate(), fn.apply(d));
}
}
List<ProductOverviewVO.TrendDataItem> 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<OrderStatMetricsDTO> specRows,
BigDecimal taxRate,
BigDecimal totalPromo,
BigDecimal totalSales) {
if (specRows == null || specRows.isEmpty()) {
return buildEmptySpecSummary();
}
Set<Long> specIds = specRows.stream().map(OrderStatMetricsDTO::getProductSpecId)
.filter(Objects::nonNull).collect(Collectors.toSet());
Map<Long, ProductSpecPO> specMap = productSpecMapper.selectBatchIds(specIds).stream()
.collect(Collectors.toMap(ProductSpecPO::getId, s -> s, (a, b) -> a));
List<ProductOverviewVO.SpecSummaryItem> 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<ProductOverviewVO.SpecSummaryItem> 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<ProductOverviewVO.SpecSalesRankItem> buildSpecTop10FromStat(List<OrderStatMetricsDTO> specRows) {
if (specRows == null) {
return List.of();
}
Set<Long> specIds = specRows.stream().map(OrderStatMetricsDTO::getProductSpecId)
.filter(Objects::nonNull).collect(Collectors.toSet());
Map<Long, ProductSpecPO> 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;
}
} }
@@ -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.model.vo.ProductVO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductService; import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductService;
import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductSpecService; 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 top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
@@ -36,12 +41,15 @@ public class ProductSpecServiceImpl extends ServiceImpl<ProductSpecMapper, Produ
private final CurrentUserContext currentUserContext; private final CurrentUserContext currentUserContext;
private final ProductService productService; private final ProductService productService;
private final OrderMapper orderMapper; private final OrderMapper orderMapper;
private final OrderStatCrudCoordinator orderStatCrudCoordinator;
public ProductSpecServiceImpl(CurrentUserContext currentUserContext, ProductService productService, public ProductSpecServiceImpl(CurrentUserContext currentUserContext, ProductService productService,
OrderMapper orderMapper) { OrderMapper orderMapper,
OrderStatCrudCoordinator orderStatCrudCoordinator) {
this.currentUserContext = currentUserContext; this.currentUserContext = currentUserContext;
this.productService = productService; this.productService = productService;
this.orderMapper = orderMapper; this.orderMapper = orderMapper;
this.orderStatCrudCoordinator = orderStatCrudCoordinator;
} }
/** /**
@@ -63,7 +71,19 @@ public class ProductSpecServiceImpl extends ServiceImpl<ProductSpecMapper, Produ
if (specCode == null || specCode.isBlank()) { if (specCode == null || specCode.isBlank()) {
return; return;
} }
orderMapper.linkOrdersBySpecCodeWhenSpecIdNull(companyId, specCode.trim(), productSpecId); String code = specCode.trim();
List<OrderShopStatDateRow> affected =
orderMapper.selectOrphanOrderStatDatesBySpecCode(companyId, code);
orderMapper.linkOrdersBySpecCodeWhenSpecIdNull(companyId, code, productSpecId);
if (affected != null && !affected.isEmpty()) {
Set<StatDirtyKey> 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);
}
} }
/** /**
@@ -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.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; 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.po.PromotionFeePO;
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.vo.BatchImportPromotionFeeResultVO; 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.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.PromotionFeeService;
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.service.PromotionFeeTypeService; import top.xyquan.ecomdmbbackend.modules.ecom.promotion.service.PromotionFeeTypeService;
import top.xyquan.ecomdmbbackend.modules.ecom.category.model.po.CategoryPO; import top.xyquan.ecomdmbbackend.modules.ecom.category.model.po.CategoryPO;
@@ -35,7 +35,6 @@ import java.util.stream.Collectors;
* 推广费记录服务实现类 * 推广费记录服务实现类
*/ */
@Service @Service
@RequiredArgsConstructor
public class PromotionFeeServiceImpl implements PromotionFeeService { public class PromotionFeeServiceImpl implements PromotionFeeService {
private final PromotionFeeMapper promotionFeeMapper; private final PromotionFeeMapper promotionFeeMapper;
@@ -44,7 +43,23 @@ public class PromotionFeeServiceImpl implements PromotionFeeService {
private final PromotionFeeTypeService promotionFeeTypeService; private final PromotionFeeTypeService promotionFeeTypeService;
private final ProductService productService; private final ProductService productService;
private final CategoryService categoryService; 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()); po.setUpdateBy(currentUserContext.getCurrentUserId());
promotionFeeMapper.insert(po); promotionFeeMapper.insert(po);
feeStatCrudCoordinator.afterPromotionFeeSaved(null, po);
return po.getId(); return po.getId();
} }
@@ -83,6 +99,7 @@ public class PromotionFeeServiceImpl implements PromotionFeeService {
po.setUpdateBy(currentUserContext.getCurrentUserId()); po.setUpdateBy(currentUserContext.getCurrentUserId());
po.setCompanyId(companyId); po.setCompanyId(companyId);
promotionFeeMapper.updateById(po); promotionFeeMapper.updateById(po);
feeStatCrudCoordinator.afterPromotionFeeSaved(existing, po);
} }
/** /**
@@ -98,6 +115,7 @@ public class PromotionFeeServiceImpl implements PromotionFeeService {
throw new BusinessException("推广费记录不存在"); throw new BusinessException("推广费记录不存在");
} }
promotionFeeMapper.deleteById(id); promotionFeeMapper.deleteById(id);
feeStatCrudCoordinator.afterPromotionFeeDeleted(existing);
} }
/** /**
@@ -3,10 +3,8 @@ package top.xyquan.ecomdmbbackend.modules.ecom.workbench.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException; import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.modules.ecom.brushorder.mapper.BrushOrderMapper; import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.brushorder.model.po.BrushOrderPO; import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatReadFacade;
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.status.support.OrderStatusStatResolver; 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.order.status.support.OrderStatusStatSets;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.CategoryExportDTO; 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.CategoryExportExcelService;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.service.CompanyOverviewService; import top.xyquan.ecomdmbbackend.modules.ecom.overview.service.CompanyOverviewService;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.service.ExportService; 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.model.po.ShopPO;
import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopService; import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopService;
import top.xyquan.ecomdmbbackend.modules.ecom.workbench.model.dto.WorkbenchExportDTO; 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.math.BigDecimal;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Objects; 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 static final BigDecimal DEFAULT_TAX_RATE = new BigDecimal("0.04");
private final CurrentUserContext currentUserContext; private final CurrentUserContext currentUserContext;
private final OrderMapper orderMapper;
private final ShopService shopService; private final ShopService shopService;
private final OrderStatusStatResolver orderStatusStatResolver; private final OrderStatusStatResolver orderStatusStatResolver;
private final PromotionFeeMapper promotionFeeMapper;
private final BrushOrderMapper brushOrderMapper;
private final CompanyOverviewService companyOverviewService; private final CompanyOverviewService companyOverviewService;
private final ExportService exportService; private final ExportService exportService;
private final CategoryExportExcelService categoryExportExcelService; private final CategoryExportExcelService categoryExportExcelService;
private final OrderStatReadFacade orderStatReadFacade;
public WorkbenchExportServiceImpl( public WorkbenchExportServiceImpl(
CurrentUserContext currentUserContext, CurrentUserContext currentUserContext,
OrderMapper orderMapper,
ShopService shopService, ShopService shopService,
OrderStatusStatResolver orderStatusStatResolver, OrderStatusStatResolver orderStatusStatResolver,
PromotionFeeMapper promotionFeeMapper,
BrushOrderMapper brushOrderMapper,
CompanyOverviewService companyOverviewService, CompanyOverviewService companyOverviewService,
ExportService exportService, ExportService exportService,
CategoryExportExcelService categoryExportExcelService) { CategoryExportExcelService categoryExportExcelService,
OrderStatReadFacade orderStatReadFacade) {
this.currentUserContext = currentUserContext; this.currentUserContext = currentUserContext;
this.orderMapper = orderMapper;
this.shopService = shopService; this.shopService = shopService;
this.orderStatusStatResolver = orderStatusStatResolver; this.orderStatusStatResolver = orderStatusStatResolver;
this.promotionFeeMapper = promotionFeeMapper;
this.brushOrderMapper = brushOrderMapper;
this.companyOverviewService = companyOverviewService; this.companyOverviewService = companyOverviewService;
this.exportService = exportService; this.exportService = exportService;
this.categoryExportExcelService = categoryExportExcelService; 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) { private CompanyOverviewVO.WorkbenchTableBundle loadSummaryTables(WorkbenchExportDTO dto) {
Long companyId = currentUserContext.getCurrentCompanyId(); Long companyId = currentUserContext.getCurrentCompanyId();
DateRange range = parseDateRange(toQuery(dto)); DateRange range = parseDateRange(toQuery(dto));
OrderStatusStatSets stat = orderStatusStatResolver.resolve(companyId); OrderStatusStatSets stat = orderStatusStatResolver.resolve(companyId);
List<Long> unionStatusIds = stat.getUnionStatusIds();
List<ShopPO> shops = loadFilteredShops(companyId, dto.getPlatformId(), dto.getShopId()); List<ShopPO> shops = loadFilteredShops(companyId, dto.getPlatformId(), dto.getShopId());
if (shops.isEmpty()) { if (shops.isEmpty()) {
@@ -149,21 +137,17 @@ public class WorkbenchExportServiceImpl implements WorkbenchExportService {
} }
List<Long> shopIds = shops.stream().map(ShopPO::getId).filter(Objects::nonNull).toList(); List<Long> shopIds = shops.stream().map(ShopPO::getId).filter(Objects::nonNull).toList();
List<OrderPO> orders = loadOrders(companyId, shopIds, range.startDateTime(), range.endDateTime(), unionStatusIds); List<OrderStatAggMapper.ShopProductRow> orderRows = orderStatReadFacade.loadShopProductRows(
List<PromotionFeePO> promotionFees = loadPromotionFees(companyId, shopIds, range.startDate(), range.endDate()); companyId, shopIds, range.startDate(), range.endDate(), stat);
List<BrushOrderPO> brushOrders = loadBrushOrders(companyId, shopIds, range.startDateTime(), range.endDateTime()); List<OrderStatAggMapper.PromotionRow> promotionRows = orderStatReadFacade.loadPromotionRows(
companyId, shopIds, range.startDate(), range.endDate());
List<OrderStatAggMapper.BrushRow> brushRows = orderStatReadFacade.loadBrushRows(
companyId, shopIds, range.startDateTime(), range.endDateTime());
BigDecimal taxRate = dto.getTaxRate() != null ? dto.getTaxRate() : DEFAULT_TAX_RATE; BigDecimal taxRate = dto.getTaxRate() != null ? dto.getTaxRate() : DEFAULT_TAX_RATE;
return companyOverviewService.buildWorkbenchSummaryTables( return companyOverviewService.buildWorkbenchSummaryTablesFromAgg(
taxRate, taxRate, companyId, shops, orderRows, promotionRows, brushRows,
companyId, range.startDate(), range.endDate());
shops,
orders,
promotionFees,
brushOrders,
stat,
range.startDate(),
range.endDate());
} }
/** 导出 DTO 与查询 DTO 字段对齐,仅用于复用 {@link #parseDateRange} */ /** 导出 DTO 与查询 DTO 字段对齐,仅用于复用 {@link #parseDateRange} */
@@ -214,51 +198,6 @@ public class WorkbenchExportServiceImpl implements WorkbenchExportService {
return shopService.list(w); return shopService.list(w);
} }
/** 计入销售额状态的订单列表,与 {@link WorkbenchServiceImpl#loadOrders} 一致 */
private List<OrderPO> loadOrders(Long companyId, List<Long> shopIds,
LocalDateTime start, LocalDateTime end, List<Long> unionStatusIds) {
if (shopIds.isEmpty()) {
return Collections.emptyList();
}
LambdaQueryWrapper<OrderPO> 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<PromotionFeePO> loadPromotionFees(Long companyId, List<Long> shopIds, LocalDate start, LocalDate end) {
if (shopIds.isEmpty()) {
return Collections.emptyList();
}
LambdaQueryWrapper<PromotionFeePO> 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<BrushOrderPO> loadBrushOrders(Long companyId, List<Long> shopIds, LocalDateTime start, LocalDateTime end) {
if (shopIds.isEmpty()) {
return Collections.emptyList();
}
LambdaQueryWrapper<BrushOrderPO> 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 */ /** 查询时间闭区间辅助 record */
private record DateRange(LocalDate startDate, LocalDate endDate) { private record DateRange(LocalDate startDate, LocalDate endDate) {
LocalDateTime startDateTime() { LocalDateTime startDateTime() {
@@ -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.category.service.CategoryService;
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper; 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.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.model.po.OrderPO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatResolver; 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.order.status.support.OrderStatusStatSets;
@@ -87,7 +88,7 @@ public class WorkbenchServiceImpl implements WorkbenchService {
private final ProductMapper productMapper; private final ProductMapper productMapper;
private final CategoryService categoryService; private final CategoryService categoryService;
private final PlatformMapper platformMapper; private final PlatformMapper platformMapper;
private final OrderStatAggMapper orderStatAggMapper; private final OrderStatReadFacade orderStatReadFacade;
private final CompanyOverviewService companyOverviewService; private final CompanyOverviewService companyOverviewService;
public WorkbenchServiceImpl(CurrentUserContext currentUserContext, public WorkbenchServiceImpl(CurrentUserContext currentUserContext,
@@ -100,7 +101,7 @@ public class WorkbenchServiceImpl implements WorkbenchService {
ProductMapper productMapper, ProductMapper productMapper,
CategoryService categoryService, CategoryService categoryService,
PlatformMapper platformMapper, PlatformMapper platformMapper,
OrderStatAggMapper orderStatAggMapper, OrderStatReadFacade orderStatReadFacade,
CompanyOverviewService companyOverviewService) { CompanyOverviewService companyOverviewService) {
this.currentUserContext = currentUserContext; this.currentUserContext = currentUserContext;
this.orderMapper = orderMapper; this.orderMapper = orderMapper;
@@ -112,7 +113,7 @@ public class WorkbenchServiceImpl implements WorkbenchService {
this.productMapper = productMapper; this.productMapper = productMapper;
this.categoryService = categoryService; this.categoryService = categoryService;
this.platformMapper = platformMapper; this.platformMapper = platformMapper;
this.orderStatAggMapper = orderStatAggMapper; this.orderStatReadFacade = orderStatReadFacade;
this.companyOverviewService = companyOverviewService; this.companyOverviewService = companyOverviewService;
} }
@@ -224,20 +225,17 @@ public class WorkbenchServiceImpl implements WorkbenchService {
return new ShopContext(taxRate, companyId, range, stat, shops, shopIds, shopById); 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) { private SqlAggBundle loadSqlAgg(ShopContext ctx) {
OrderStatusStatSets stat = ctx.stat(); LocalDate start = ctx.range().startDate();
List<OrderStatAggMapper.ShopProductRow> orderRows = orderStatAggMapper.aggregateByShopProduct( LocalDate end = ctx.range().endDate();
ctx.companyId(), ctx.shopIds(), ctx.range().startDateTime(), ctx.range().endDateTime(), List<OrderStatAggMapper.ShopProductRow> orderRows = orderStatReadFacade.loadShopProductRows(
stat.getUnionStatusIds(), statusList(stat.getSalesIds()), statusList(stat.getRefundIds()), ctx.companyId(), ctx.shopIds(), start, end, ctx.stat());
statusList(stat.getProductCostIds()), statusList(stat.getFreightCostIds()), statusList(stat.getOtherCostIds())); List<OrderStatAggMapper.DailyRow> dailyRows = orderStatReadFacade.loadDailyRows(
List<OrderStatAggMapper.DailyRow> dailyRows = orderStatAggMapper.aggregateDaily( ctx.companyId(), ctx.shopIds(), start, end, ctx.stat());
ctx.companyId(), ctx.shopIds(), ctx.range().startDateTime(), ctx.range().endDateTime(), List<OrderStatAggMapper.PromotionRow> promotionRows = orderStatReadFacade.loadPromotionRows(
stat.getUnionStatusIds(), statusList(stat.getSalesIds()), statusList(stat.getRefundIds()), ctx.companyId(), ctx.shopIds(), start, end);
statusList(stat.getProductCostIds()), statusList(stat.getFreightCostIds()), statusList(stat.getOtherCostIds())); List<OrderStatAggMapper.BrushRow> brushRows = orderStatReadFacade.loadBrushRows(
List<OrderStatAggMapper.PromotionRow> promotionRows = orderStatAggMapper.aggregatePromotionFees(
ctx.companyId(), ctx.shopIds(), ctx.range().startDate(), ctx.range().endDate());
List<OrderStatAggMapper.BrushRow> brushRows = orderStatAggMapper.aggregateBrushFees(
ctx.companyId(), ctx.shopIds(), ctx.range().startDateTime(), ctx.range().endDateTime()); ctx.companyId(), ctx.shopIds(), ctx.range().startDateTime(), ctx.range().endDateTime());
return new SqlAggBundle(orderRows, dailyRows, promotionRows, brushRows); return new SqlAggBundle(orderRows, dailyRows, promotionRows, brushRows);
} }
@@ -247,38 +245,27 @@ public class WorkbenchServiceImpl implements WorkbenchService {
OrderStatusStatSets stat = ctx.stat(); OrderStatusStatSets stat = ctx.stat();
DateRange lastRange = lastMonthSameSpan(ctx.range()); DateRange lastRange = lastMonthSameSpan(ctx.range());
DateRange yoyRange = new DateRange(ctx.range().startDate().minusYears(1), ctx.range().endDate().minusYears(1)); 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( OrderStatAggMapper.PeriodKpiRow orderKpi = orderStatReadFacade.loadPeriodKpi(
ctx.companyId(), ctx.shopIds(), scanStart, scanEnd, ctx.companyId(), ctx.shopIds(),
ctx.range().startDateTime(), ctx.range().endDateTime(), ctx.range().startDate(), ctx.range().endDate(),
lastRange.startDateTime(), lastRange.endDateTime(), lastRange.startDate(), lastRange.endDate(),
yoyRange.startDateTime(), yoyRange.endDateTime(), yoyRange.startDate(), yoyRange.endDate(), stat);
stat.getUnionStatusIds(), statusList(stat.getSalesIds()), statusList(stat.getRefundIds()),
statusList(stat.getProductCostIds()), statusList(stat.getFreightCostIds()), statusList(stat.getOtherCostIds()));
if (orderKpi == null) {
orderKpi = new OrderStatAggMapper.PeriodKpiRow();
}
LocalDate feeScanStart = minDate(lastRange.startDate(), yoyRange.startDate(), ctx.range().startDate()); LocalDate feeScanStart = minDate(lastRange.startDate(), yoyRange.startDate(), ctx.range().startDate());
LocalDate feeScanEnd = maxDate(lastRange.endDate(), yoyRange.endDate(), ctx.range().endDate()); 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.companyId(), ctx.shopIds(), feeScanStart, feeScanEnd,
ctx.range().startDate(), ctx.range().endDate(), ctx.range().startDate(), ctx.range().endDate(),
lastRange.startDate(), lastRange.endDate(), lastRange.startDate(), lastRange.endDate(),
yoyRange.startDate(), yoyRange.endDate()); yoyRange.startDate(), yoyRange.endDate());
if (promoKpi == null) { OrderStatAggMapper.FeeKpiRow brushKpi = orderStatReadFacade.loadBrushPeriodKpi(
promoKpi = new OrderStatAggMapper.FeeKpiRow(); ctx.companyId(), ctx.shopIds(),
} minTime(lastRange.startDateTime(), yoyRange.startDateTime(), ctx.range().startDateTime()),
OrderStatAggMapper.FeeKpiRow brushKpi = orderStatAggMapper.aggregateBrushPeriodKpi( maxTime(lastRange.endDateTime(), yoyRange.endDateTime(), ctx.range().endDateTime()),
ctx.companyId(), ctx.shopIds(), scanStart, scanEnd,
ctx.range().startDateTime(), ctx.range().endDateTime(), ctx.range().startDateTime(), ctx.range().endDateTime(),
lastRange.startDateTime(), lastRange.endDateTime(), lastRange.startDateTime(), lastRange.endDateTime(),
yoyRange.startDateTime(), yoyRange.endDateTime()); yoyRange.startDateTime(), yoyRange.endDateTime());
if (brushKpi == null) {
brushKpi = new OrderStatAggMapper.FeeKpiRow();
}
return new ComparePeriodBundle(lastRange, yoyRange, return new ComparePeriodBundle(lastRange, yoyRange,
totalsFromPeriodKpi(orderKpi, promoKpi, brushKpi, PeriodSlice.PREV, ctx.taxRate()), totalsFromPeriodKpi(orderKpi, promoKpi, brushKpi, PeriodSlice.PREV, ctx.taxRate()),
@@ -41,6 +41,21 @@ spring:
min-idle: 0 min-idle: 0
max-wait: -1ms 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配置
# ⚠️ 生产环境必须通过环境变量 JWT_SECRET 覆盖,默认值仅用于本地开发 # ⚠️ 生产环境必须通过环境变量 JWT_SECRET 覆盖,默认值仅用于本地开发
jwt: jwt:
@@ -0,0 +1,94 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper.FeeStatDailyMapper">
<delete id="deletePromotionDaily">
DELETE FROM ec_promotion_fee_stat_daily
WHERE company_id = #{companyId} AND shop_id = #{shopId} AND stat_date = #{statDate}
</delete>
<insert id="batchInsertPromotionDaily">
INSERT INTO ec_promotion_fee_stat_daily (
company_id, shop_id, product_id, category_id, stat_date, fee_amount
) VALUES
<foreach collection="list" item="r" separator=",">
(#{r.companyId}, #{r.shopId}, #{r.productId}, #{r.categoryId}, #{r.statDate}, #{r.feeAmount})
</foreach>
</insert>
<insert id="rollupPromotionMonthly">
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 &gt;= #{statMonth}
AND stat_date &lt; 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>
<insert id="rollupPromotionYearly">
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
</insert>
<delete id="deleteBrushDaily">
DELETE FROM ec_brush_fee_stat_daily
WHERE company_id = #{companyId} AND shop_id = #{shopId} AND stat_date = #{statDate}
</delete>
<insert id="upsertBrushDaily">
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>
<insert id="rollupBrushMonthly">
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 &gt;= #{statMonth}
AND stat_date &lt; 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>
<insert id="rollupBrushYearly">
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
</insert>
<select id="aggregatePromotionByShopDay"
resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper.FeeStatDailyMapper$PromotionFeeAggRow">
SELECT
IFNULL(f.product_id, 0) AS productId,
IFNULL(f.category_id, 0) AS categoryId,
SUM(IFNULL(f.fee_amount, 0)) AS feeAmount
FROM ec_promotion_fee f
WHERE f.company_id = #{companyId}
AND f.shop_id = #{shopId}
AND f.fee_date = #{statDate}
GROUP BY IFNULL(f.product_id, 0), IFNULL(f.category_id, 0)
</select>
<select id="aggregateBrushByShopDay" resultType="java.math.BigDecimal">
SELECT IFNULL(SUM(IFNULL(b.brush_amount, 0)), 0)
FROM ec_brush_order b
WHERE b.company_id = #{companyId}
AND b.shop_id = #{shopId}
AND DATE(b.brush_time) = #{statDate}
</select>
</mapper>
@@ -0,0 +1,230 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper.OrderStatDailyMapper">
<insert id="upsertDailyShop">
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
</insert>
<delete id="deleteDailyProduct">
DELETE FROM ec_order_stat_daily_product
WHERE company_id = #{companyId} AND shop_id = #{shopId} AND stat_date = #{statDate}
</delete>
<insert id="batchInsertDailyProduct">
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
<foreach collection="list" item="r" separator=",">
(#{r.companyId}, #{r.shopId}, #{r.productId}, #{r.categoryId}, #{r.statDate},
#{r.salesAmount}, #{r.refundAmount}, #{r.salesOrderCount},
#{r.productCost}, #{r.freightCost}, #{r.otherCost}, #{r.statVersion})
</foreach>
</insert>
<delete id="deleteDailySpec">
DELETE FROM ec_order_stat_daily_spec
WHERE company_id = #{companyId} AND shop_id = #{shopId} AND stat_date = #{statDate}
</delete>
<insert id="batchInsertDailySpec">
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
<foreach collection="list" item="r" separator=",">
(#{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})
</foreach>
</insert>
<!-- 月/年 rollup:从日表 SUM 写入对应粒度表 -->
<insert id="rollupMonthlyShop">
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 &gt;= #{statMonth}
AND stat_date &lt; 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>
<insert id="rollupYearlyShop">
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>
<insert id="rollupMonthlyProduct">
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 &gt;= #{statMonth}
AND stat_date &lt; 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>
<insert id="rollupYearlyProduct">
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>
<insert id="rollupMonthlySpec">
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 &gt;= #{statMonth}
AND stat_date &lt; 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>
<insert id="rollupYearlySpec">
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
</insert>
</mapper>
@@ -0,0 +1,284 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper.OrderStatQueryMapper">
<sql id="shopFilter">
company_id = #{companyId}
AND shop_id IN
<foreach collection="shopIds" item="sid" open="(" separator="," close=")">#{sid}</foreach>
</sql>
<select id="sumDailyShop" resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO">
SELECT
COALESCE(SUM(sales_amount), 0) AS salesAmount,
COALESCE(SUM(refund_amount), 0) AS refundAmount,
COALESCE(SUM(sales_order_count), 0) AS salesOrderCount,
COALESCE(SUM(product_cost), 0) AS productCost,
COALESCE(SUM(freight_cost), 0) AS freightCost,
COALESCE(SUM(other_cost), 0) AS otherCost,
COALESCE(SUM(gmv_amount), 0) AS gmvAmount,
COALESCE(SUM(gmv_order_count), 0) AS gmvOrderCount
FROM ec_order_stat_daily_shop
WHERE <include refid="shopFilter"/>
AND stat_date &gt;= #{startDate}
AND stat_date &lt;= #{endDate}
</select>
<select id="sumDailyShopByDay" resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO">
SELECT
stat_date AS statDate,
COALESCE(SUM(sales_amount), 0) AS salesAmount,
COALESCE(SUM(refund_amount), 0) AS refundAmount,
COALESCE(SUM(sales_order_count), 0) AS salesOrderCount,
COALESCE(SUM(product_cost), 0) AS productCost,
COALESCE(SUM(freight_cost), 0) AS freightCost,
COALESCE(SUM(other_cost), 0) AS otherCost,
COALESCE(SUM(gmv_amount), 0) AS gmvAmount,
COALESCE(SUM(gmv_order_count), 0) AS gmvOrderCount
FROM ec_order_stat_daily_shop
WHERE <include refid="shopFilter"/>
AND stat_date &gt;= #{startDate}
AND stat_date &lt;= #{endDate}
GROUP BY stat_date
ORDER BY stat_date
</select>
<select id="sumDailyShopByShop" resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO">
SELECT
shop_id AS shopId,
MAX(platform_id) AS platformId,
COALESCE(SUM(sales_amount), 0) AS salesAmount,
COALESCE(SUM(refund_amount), 0) AS refundAmount,
COALESCE(SUM(sales_order_count), 0) AS salesOrderCount,
COALESCE(SUM(product_cost), 0) AS productCost,
COALESCE(SUM(freight_cost), 0) AS freightCost,
COALESCE(SUM(other_cost), 0) AS otherCost,
COALESCE(SUM(gmv_amount), 0) AS gmvAmount,
COALESCE(SUM(gmv_order_count), 0) AS gmvOrderCount
FROM ec_order_stat_daily_shop
WHERE <include refid="shopFilter"/>
AND stat_date &gt;= #{startDate}
AND stat_date &lt;= #{endDate}
GROUP BY shop_id
</select>
<select id="sumDailyProductByCategory" resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO">
SELECT
category_id AS categoryId,
COALESCE(SUM(sales_amount), 0) AS salesAmount,
COALESCE(SUM(refund_amount), 0) AS refundAmount,
COALESCE(SUM(sales_order_count), 0) AS salesOrderCount,
COALESCE(SUM(product_cost), 0) AS productCost,
COALESCE(SUM(freight_cost), 0) AS freightCost,
COALESCE(SUM(other_cost), 0) AS otherCost
FROM ec_order_stat_daily_product
WHERE <include refid="shopFilter"/>
AND stat_date &gt;= #{startDate}
AND stat_date &lt;= #{endDate}
GROUP BY category_id
</select>
<select id="sumDailyProductByProduct" resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO">
SELECT
product_id AS productId,
MAX(category_id) AS categoryId,
COALESCE(SUM(sales_amount), 0) AS salesAmount,
COALESCE(SUM(refund_amount), 0) AS refundAmount,
COALESCE(SUM(sales_order_count), 0) AS salesOrderCount,
COALESCE(SUM(product_cost), 0) AS productCost,
COALESCE(SUM(freight_cost), 0) AS freightCost,
COALESCE(SUM(other_cost), 0) AS otherCost
FROM ec_order_stat_daily_product
WHERE <include refid="shopFilter"/>
AND stat_date &gt;= #{startDate}
AND stat_date &lt;= #{endDate}
GROUP BY product_id
</select>
<select id="sumDailyProductByShopProduct" resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO">
SELECT
shop_id AS shopId,
product_id AS productId,
MAX(category_id) AS categoryId,
COALESCE(SUM(sales_amount), 0) AS salesAmount,
COALESCE(SUM(refund_amount), 0) AS refundAmount,
COALESCE(SUM(sales_order_count), 0) AS salesOrderCount,
COALESCE(SUM(product_cost), 0) AS productCost,
COALESCE(SUM(freight_cost), 0) AS freightCost,
COALESCE(SUM(other_cost), 0) AS otherCost
FROM ec_order_stat_daily_product
WHERE <include refid="shopFilter"/>
AND stat_date &gt;= #{startDate}
AND stat_date &lt;= #{endDate}
GROUP BY shop_id, product_id
</select>
<select id="sumDailyProductForOneProduct" resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO">
SELECT
COALESCE(SUM(sales_amount), 0) AS salesAmount,
COALESCE(SUM(refund_amount), 0) AS refundAmount,
COALESCE(SUM(sales_order_count), 0) AS salesOrderCount,
COALESCE(SUM(product_cost), 0) AS productCost,
COALESCE(SUM(freight_cost), 0) AS freightCost,
COALESCE(SUM(other_cost), 0) AS otherCost
FROM ec_order_stat_daily_product
WHERE company_id = #{companyId}
AND product_id = #{productId}
AND stat_date &gt;= #{startDate}
AND stat_date &lt;= #{endDate}
<if test="shopIds != null and shopIds.size() &gt; 0">
AND shop_id IN
<foreach collection="shopIds" item="sid" open="(" separator="," close=")">#{sid}</foreach>
</if>
</select>
<select id="sumDailyProductByDayForOneProduct" resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO">
SELECT
stat_date AS statDate,
COALESCE(SUM(sales_amount), 0) AS salesAmount,
COALESCE(SUM(refund_amount), 0) AS refundAmount,
COALESCE(SUM(sales_order_count), 0) AS salesOrderCount,
COALESCE(SUM(product_cost), 0) AS productCost,
COALESCE(SUM(freight_cost), 0) AS freightCost,
COALESCE(SUM(other_cost), 0) AS otherCost
FROM ec_order_stat_daily_product
WHERE company_id = #{companyId}
AND product_id = #{productId}
AND stat_date &gt;= #{startDate}
AND stat_date &lt;= #{endDate}
<if test="shopIds != null and shopIds.size() &gt; 0">
AND shop_id IN
<foreach collection="shopIds" item="sid" open="(" separator="," close=")">#{sid}</foreach>
</if>
GROUP BY stat_date
ORDER BY stat_date
</select>
<select id="sumMonthlyProductByCategory" resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO">
SELECT
category_id AS categoryId,
COALESCE(SUM(sales_amount), 0) AS salesAmount,
COALESCE(SUM(refund_amount), 0) AS refundAmount,
COALESCE(SUM(sales_order_count), 0) AS salesOrderCount,
COALESCE(SUM(product_cost), 0) AS productCost,
COALESCE(SUM(freight_cost), 0) AS freightCost,
COALESCE(SUM(other_cost), 0) AS otherCost
FROM ec_order_stat_monthly_product
WHERE <include refid="shopFilter"/>
AND stat_month &gt;= #{startMonth}
AND stat_month &lt;= #{endMonth}
GROUP BY category_id
</select>
<select id="sumMonthlyProductByProduct" resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO">
SELECT
product_id AS productId,
MAX(category_id) AS categoryId,
COALESCE(SUM(sales_amount), 0) AS salesAmount,
COALESCE(SUM(refund_amount), 0) AS refundAmount,
COALESCE(SUM(sales_order_count), 0) AS salesOrderCount,
COALESCE(SUM(product_cost), 0) AS productCost,
COALESCE(SUM(freight_cost), 0) AS freightCost,
COALESCE(SUM(other_cost), 0) AS otherCost
FROM ec_order_stat_monthly_product
WHERE <include refid="shopFilter"/>
AND stat_month &gt;= #{startMonth}
AND stat_month &lt;= #{endMonth}
GROUP BY product_id
</select>
<select id="sumYearlyProductByCategory" resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO">
SELECT
category_id AS categoryId,
COALESCE(SUM(sales_amount), 0) AS salesAmount,
COALESCE(SUM(refund_amount), 0) AS refundAmount,
COALESCE(SUM(sales_order_count), 0) AS salesOrderCount,
COALESCE(SUM(product_cost), 0) AS productCost,
COALESCE(SUM(freight_cost), 0) AS freightCost,
COALESCE(SUM(other_cost), 0) AS otherCost
FROM ec_order_stat_yearly_product
WHERE <include refid="shopFilter"/>
AND stat_year &gt;= #{startYear}
AND stat_year &lt;= #{endYear}
GROUP BY category_id
</select>
<select id="sumYearlyProductByProduct" resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO">
SELECT
product_id AS productId,
MAX(category_id) AS categoryId,
COALESCE(SUM(sales_amount), 0) AS salesAmount,
COALESCE(SUM(refund_amount), 0) AS refundAmount,
COALESCE(SUM(sales_order_count), 0) AS salesOrderCount,
COALESCE(SUM(product_cost), 0) AS productCost,
COALESCE(SUM(freight_cost), 0) AS freightCost,
COALESCE(SUM(other_cost), 0) AS otherCost
FROM ec_order_stat_yearly_product
WHERE <include refid="shopFilter"/>
AND stat_year &gt;= #{startYear}
AND stat_year &lt;= #{endYear}
GROUP BY product_id
</select>
<select id="sumDailySpecBySpec" resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO">
SELECT
product_spec_id AS productSpecId,
COALESCE(SUM(sales_amount), 0) AS salesAmount,
COALESCE(SUM(refund_amount), 0) AS refundAmount,
COALESCE(SUM(sales_order_count), 0) AS salesOrderCount,
COALESCE(SUM(quantity_sum), 0) AS quantitySum,
COALESCE(SUM(product_cost), 0) AS productCost,
COALESCE(SUM(freight_cost), 0) AS freightCost,
COALESCE(SUM(other_cost), 0) AS otherCost
FROM ec_order_stat_daily_spec
WHERE <include refid="shopFilter"/>
AND product_id = #{productId}
AND stat_date &gt;= #{startDate}
AND stat_date &lt;= #{endDate}
GROUP BY product_spec_id
</select>
<select id="sumMonthlySpecBySpec" resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO">
SELECT
product_spec_id AS productSpecId,
COALESCE(SUM(sales_amount), 0) AS salesAmount,
COALESCE(SUM(refund_amount), 0) AS refundAmount,
COALESCE(SUM(sales_order_count), 0) AS salesOrderCount,
COALESCE(SUM(quantity_sum), 0) AS quantitySum,
COALESCE(SUM(product_cost), 0) AS productCost,
COALESCE(SUM(freight_cost), 0) AS freightCost,
COALESCE(SUM(other_cost), 0) AS otherCost
FROM ec_order_stat_monthly_spec
WHERE <include refid="shopFilter"/>
AND product_id = #{productId}
AND stat_month &gt;= #{startMonth}
AND stat_month &lt;= #{endMonth}
GROUP BY product_spec_id
</select>
<select id="sumYearlySpecBySpec" resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO">
SELECT
product_spec_id AS productSpecId,
COALESCE(SUM(sales_amount), 0) AS salesAmount,
COALESCE(SUM(refund_amount), 0) AS refundAmount,
COALESCE(SUM(sales_order_count), 0) AS salesOrderCount,
COALESCE(SUM(quantity_sum), 0) AS quantitySum,
COALESCE(SUM(product_cost), 0) AS productCost,
COALESCE(SUM(freight_cost), 0) AS freightCost,
COALESCE(SUM(other_cost), 0) AS otherCost
FROM ec_order_stat_yearly_spec
WHERE <include refid="shopFilter"/>
AND product_id = #{productId}
AND stat_year &gt;= #{startYear}
AND stat_year &lt;= #{endYear}
GROUP BY product_spec_id
</select>
<select id="countDailyShopRows" resultType="int">
SELECT COUNT(*)
FROM ec_order_stat_daily_shop
WHERE <include refid="shopFilter"/>
AND stat_date &gt;= #{startDate}
AND stat_date &lt;= #{endDate}
</select>
</mapper>
@@ -0,0 +1,78 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper.OrderStatRefreshMapper">
<sql id="qty">IFNULL(NULLIF(o.quantity, 0), 1)</sql>
<insert id="insertPendingIgnore">
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
)
</insert>
<update id="markDone">
UPDATE ec_order_stat_refresh_queue SET status = 'done', update_time = CURRENT_TIMESTAMP
WHERE id = #{id}
</update>
<update id="markFailed">
UPDATE ec_order_stat_refresh_queue
SET status = 'failed', retry_count = #{retryCount}, update_time = CURRENT_TIMESTAMP
WHERE id = #{id}
</update>
<!-- fetchAndLockPending 由 Service 层 MyBatis-Plus + FOR UPDATE SKIP LOCKED 实现 -->
<select id="countGmvOrdersByShopDay" resultType="java.lang.Integer">
SELECT COUNT(*)
FROM ec_order o
WHERE o.company_id = #{companyId}
AND o.shop_id = #{shopId}
AND o.order_time &gt;= #{start}
AND o.order_time &lt;= #{end}
</select>
<select id="aggregateSpecByShopDay"
resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper.OrderStatRefreshMapper$SpecDayRow">
SELECT
IFNULL(ps.product_id, 0) AS productId,
IFNULL(o.product_spec_id, 0) AS productSpecId,
SUM(CASE WHEN o.status_id IN
<foreach collection="salesStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
THEN o.received_amount ELSE 0 END) AS salesAmount,
SUM(CASE WHEN o.status_id IN
<foreach collection="salesStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
THEN 1 ELSE 0 END) AS orderCount,
SUM(CASE WHEN o.status_id IN
<foreach collection="refundStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
THEN o.received_amount ELSE 0 END) AS refundAmount,
SUM(CASE WHEN o.status_id IN
<foreach collection="salesStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
THEN <include refid="qty"/> ELSE 0 END) AS quantitySum,
SUM(CASE WHEN o.status_id IN
<foreach collection="productCostStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
THEN o.product_cost * <include refid="qty"/> ELSE 0 END) AS productCost,
SUM(CASE WHEN o.status_id IN
<foreach collection="freightCostStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
THEN o.shipping_cost * <include refid="qty"/> ELSE 0 END) AS freightCost,
SUM(CASE WHEN o.status_id IN
<foreach collection="otherCostStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
THEN o.other_cost * <include refid="qty"/> ELSE 0 END) AS otherCost
FROM ec_order o
LEFT JOIN ec_product_spec ps ON ps.id = o.product_spec_id
WHERE o.company_id = #{companyId}
AND o.shop_id = #{shopId}
AND o.order_time &gt;= #{start}
AND o.order_time &lt;= #{end}
<choose>
<when test="unionStatusIds != null and unionStatusIds.size() > 0">
AND o.status_id IN
<foreach collection="unionStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
</when>
<otherwise>AND 1 = 0</otherwise>
</choose>
GROUP BY IFNULL(o.product_spec_id, 0), IFNULL(ps.product_id, 0)
</select>
</mapper>