mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-23 23:19:19 +08:00
feat: 完成拼多多订单同步,订单转换,bi计算三层设计
This commit is contained in:
@@ -0,0 +1,616 @@
|
||||
# 订单同步 / 转换 / BI 日汇聚设计
|
||||
|
||||
> 文档版本:**v1.3**
|
||||
> 范围:前端触发全量同步任务 + 增量同步开关 → 渠道日/增量同步 → 转换 MQ → 内部 `ec_order` → BI 日汇聚(Mongo + BI 侧快照互斥);**BI 写侧模块分层**
|
||||
> 首个落地渠道:**拼多多(PDD)**;消息契约按平台可扩展
|
||||
> 相关文档:
|
||||
> - [拼多多订单同步设计](../sql/design/ec/ec_pdd_order_sync_design.md)(渠道镜像层)
|
||||
> - [订单统计读模型方案](./订单统计读模型方案.md)(旧 MySQL 日/月/年读模型)
|
||||
> - [ec_order_stat_design.sql](../sql/design/ec/ec_order_stat_design.sql)(指标列口径)
|
||||
|
||||
---
|
||||
|
||||
## 1. 目标与边界
|
||||
|
||||
### 1.1 目标
|
||||
|
||||
| 能力 | 说明 |
|
||||
|------|------|
|
||||
| 全量同步任务 | 由**前端点击创建**;按成交日逐日拉取渠道订单;每天成功后进入转换 |
|
||||
| 增量同步开关 | 由**前端 per-shop 开关**控制;与全量**并行**运行 |
|
||||
| 订单转换 | 各 channel 模块内消费共用转换队列,写入 `ec_order` / `ec_order_item` |
|
||||
| BI 日汇聚 | 仅做**日**汇总;写入 **MongoDB**;全量计算带 MySQL 事务快照时间 |
|
||||
| 全量/增量计算互斥 | 增量消息带订单更新时间;落在快照时间范围内则跳过,范围外则计算 |
|
||||
| BI 模块归属 | 日汇聚**写侧**落在 `modules/bi`,按子域分层,禁止在 `bi` 根目录平铺;分析查看类接口日后迁入 `bi`,**包名另定,本文不预设** |
|
||||
|
||||
### 1.2 边界(本版不做)
|
||||
|
||||
- 不做月 / 年 rollup(旧 `ec_order_stat_monthly_*` / `yearly_*` 不迁移到本管线)
|
||||
- 不做推广费 / 刷单日表进 Mongo(仍走现有小表逻辑,读路径改造另期)
|
||||
- **不定义**工作台 / 概览等分析查看接口在 `bi` 下的目录命名(迁入与命名另期设计)
|
||||
- **切读 Mongo 另期**;现有读接口暂仍留在 `modules/ec`
|
||||
- 不做非 PDD 渠道实现(契约预留 `platform`)
|
||||
|
||||
### 1.3 现状锚点
|
||||
|
||||
- PDD day / incremental / repair 已落 `channel_pdd_*`;扩展点 `PddOrderAfterSyncListener` 尚无业务实现
|
||||
- `modules/bi` 为空目录;Mongo / RabbitMQ 已有依赖与配置,无业务 publisher / consumer
|
||||
- 工作台 / 概览 / 统计导出目前仍在 `modules/ec`(日后迁 `bi`,命名另定)
|
||||
- 前端店铺「同步订单」仅为 day / incremental 模式选择,无全量任务与增量开关
|
||||
|
||||
---
|
||||
|
||||
## 2.1 并发与队列约定(实现对齐)
|
||||
|
||||
| 侧 | 队列 | 同店 full / inc |
|
||||
|----|------|-----------------|
|
||||
| 同步 | `order.sync.pdd.full` / `order.sync.pdd.inc` | **可并行**(独立 Redis 锁:`…:full:lock` / `…:inc:lock`) |
|
||||
| 转换 | `order.convert.pdd`(共用) | **串行**(`order:convert:lock:{shopId}`);增量按渠道主键定位 + `platform_updated_at` 新旧比对,**不再**写转换侧 Redis 快照 |
|
||||
| BI | `bi.stat.full` / `bi.stat.inc` | **串行**(`bi:stat:lock:{company}:{shop}`);全量持久化 `bi:stat:snapshot:…` |
|
||||
|
||||
任务入口(全量任务 / 按日 / 增量 Job / 手动增量)均 **只投递 MQ**,由 consumer 执行;补单仍可同步执行后投递 INC 转换。
|
||||
|
||||
---
|
||||
|
||||
## 2. 总体链路
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
FE[Frontend]
|
||||
FullTask[FullSyncTask]
|
||||
IncJob[IncrementalSync]
|
||||
ChSync[ChannelDayOrIncSync]
|
||||
ConvQ[ConvertQueue_shared]
|
||||
Conv[ChannelConvertConsumer]
|
||||
EcOrder[ec_order]
|
||||
FullCalcQ[BiFullCalcQueue]
|
||||
IncCalcQ[BiIncCalcQueue]
|
||||
BiFull[BiFullConsumer]
|
||||
BiInc[BiIncConsumer]
|
||||
Mongo[(MongoDailyAgg)]
|
||||
|
||||
FE -->|create_full_task| FullTask
|
||||
FE -->|toggle_inc| IncJob
|
||||
FullTask -->|per_day| ChSync
|
||||
IncJob --> ChSync
|
||||
ChSync -->|day_done / page_done| ConvQ
|
||||
ConvQ --> Conv
|
||||
Conv --> EcOrder
|
||||
Conv -->|full_day_done| FullCalcQ
|
||||
Conv -->|per_order_delta| IncCalcQ
|
||||
FullCalcQ --> BiFull
|
||||
IncCalcQ --> BiInc
|
||||
BiFull -->|snapshot_recompute| Mongo
|
||||
BiInc -->|skip_or_$inc_delta| Mongo
|
||||
```
|
||||
|
||||
### 2.1 时序(全量一日)
|
||||
|
||||
```
|
||||
FE 创建全量任务(shop, dateFrom, dateTo) // 默认近 90 天
|
||||
→ 按天串行同步 channel_pdd_*
|
||||
→ 每同步完 1 天 → publish OrderConvertMessage(
|
||||
mode=FULL_DAY, statDate=day, orders=[{channelOrderId}, ...])
|
||||
→ Convert:开事务批量 channel → ec_order(写入 platform_updated_at)
|
||||
→ publish BiFullCalcMessage(company, shop, statDate)
|
||||
→ BI:开事务快照按日重算 → 写 Mongo,document 记录 dbSnapshotTime
|
||||
```
|
||||
|
||||
### 2.2 时序(增量)
|
||||
|
||||
```
|
||||
FE 打开店铺增量开关
|
||||
→ IncrementalJob 扫 enabled 店铺
|
||||
→ doIncremental:按页 upsert channel_pdd_*
|
||||
→ 每同步完一页 → publish OrderConvertMessage(
|
||||
mode=INC, orders=[{channelOrderId}, ...])
|
||||
→ Convert:按渠道主键查镜像;内部单用 platform_code + source_order_id 定位
|
||||
· 内部无此单 → 新增并算贡献差发 BI inc
|
||||
· 内部已有:channel.pdd_updated_at 不晚于 ec_order.platform_updated_at → 跳过
|
||||
· 渠道更新时间更新 → 覆盖转换;对比转换前后贡献,算出各聚合字段加减量
|
||||
· 每完成一单(按受影响 statDate)→ publish BiIncCalcMessage(
|
||||
deltas..., internalOrderUpdateTime=ec_order.update_time)
|
||||
→ BI:对比 document.dbSnapshotTime(最新全量事务快照时间)
|
||||
· internalOrderUpdateTime ≤ dbSnapshotTime → 跳过
|
||||
· 在外 → 把消息里的 delta $inc 累加到 document(不按日重算)
|
||||
```
|
||||
|
||||
全量任务运行中**不阻塞**增量 Job;转换侧靠平台更新时间幂等;BI 全量/增量同店串行,靠 Mongo `dbSnapshotTime` + 会话快照互斥。
|
||||
|
||||
---
|
||||
|
||||
## 3. 前端控制面
|
||||
|
||||
### 3.1 全量同步任务
|
||||
|
||||
| 项 | 约定 |
|
||||
|----|------|
|
||||
| 入口 | 店铺列表 / 店铺详情:「全量同步订单」 |
|
||||
| 参数 | `shopId`、`dateFrom`、`dateTo`(成交日,Asia/Shanghai);前端默认近 **90** 天 |
|
||||
| 行为 | 创建后端任务后立即返回 `taskId`;前端轮询或刷新任务状态 |
|
||||
| 进度 | 总天数、已完成日、失败日、当前处理日、状态(PENDING / RUNNING / SUCCESS / FAILED / CANCELLED) |
|
||||
| 约束 | 同店同时仅允许一个 RUNNING 全量任务;与现有 day sync 共用店级 Redis 锁 |
|
||||
|
||||
后端任务表建议:`channel_order_full_sync_task`(渠道通用)或 PDD 专用 `channel_pdd_order_full_sync_task`。
|
||||
|
||||
字段建议:
|
||||
|
||||
| 字段 | 说明 |
|
||||
|------|------|
|
||||
| `id` | 任务 ID |
|
||||
| `company_id` / `shop_id` | 租户与店铺 |
|
||||
| `platform_code` | 如 `pdd` |
|
||||
| `date_from` / `date_to` | 成交日闭区间 |
|
||||
| `current_date` | 当前处理日 |
|
||||
| `total_days` / `done_days` / `failed_days` | 进度 |
|
||||
| `status` | 见上 |
|
||||
| `last_error` | 最近失败原因 |
|
||||
| `create_time` / `update_time` / `finish_time` | 时间戳 |
|
||||
|
||||
执行策略:
|
||||
|
||||
1. 按天**串行**调用现有 day sync(沿用 `pdd.order.list.get`、店锁、限流)
|
||||
2. **每天渠道同步成功后**立刻发转换消息(不等整个区间结束)
|
||||
3. 某日失败:记入失败日,任务可配置为「暂停等待重试」或「跳过继续」;默认**暂停**,前端可点重试从失败日继续
|
||||
|
||||
### 3.2 增量同步开关
|
||||
|
||||
| 项 | 约定 |
|
||||
|----|------|
|
||||
| 入口 | 店铺维度 Switch:「开启增量同步」 |
|
||||
| 存储 | `ec_shop.order_inc_sync_enabled`;运行态在 `channel_pdd_order_inc_sync` |
|
||||
| Job | 仅处理开关开启且未出错暂停的店;关闭后不再拉增量、不再发 INC 转换 |
|
||||
| 与 YAML | 全局 `pdd.order-sync.incremental-job-enabled` 仍作总闸;单店开关为细粒度 |
|
||||
|
||||
开关默认 `false`(需前端显式打开);落在 `ec_shop.order_inc_sync_enabled`。
|
||||
|
||||
API 建议:
|
||||
|
||||
- `POST /api/channel/pdd/order/sync/full-task` — 创建全量任务
|
||||
- `GET /api/channel/pdd/order/sync/full-task/{taskId}` — 查询进度
|
||||
- `POST /api/channel/pdd/order/sync/incremental/toggle` — `{ shopId, enabled }`
|
||||
- `GET /api/channel/pdd/order/sync/incremental/status?shopId=` — 查询开关与游标
|
||||
|
||||
---
|
||||
|
||||
## 4. RabbitMQ 拓扑与消息契约
|
||||
|
||||
依赖已具备:`spring-boot-starter-amqp` + `spring.rabbitmq.*`。本管线首次引入业务 Exchange / Queue。
|
||||
|
||||
### 4.1 拓扑
|
||||
|
||||
| 名称 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| `ecom.order.topic` | Topic Exchange | 订单管线统一交换机 |
|
||||
| `order.convert.pdd` | Queue | PDD 转换队列(全量日 + 增量共用) |
|
||||
| `order.convert.pdd.dlq` | Queue | 转换死信 |
|
||||
| `bi.stat.full` | Queue | BI 全日重算 |
|
||||
| `bi.stat.full.dlq` | Queue | 全量计算死信 |
|
||||
| `bi.stat.inc` | Queue | BI 增量 delta 累加 |
|
||||
| `bi.stat.inc.dlq` | Queue | 增量计算死信 |
|
||||
|
||||
RoutingKey:
|
||||
|
||||
| Key | 绑定队列 |
|
||||
|-----|----------|
|
||||
| `order.convert.pdd` | `order.convert.pdd` |
|
||||
| `bi.stat.full` | `bi.stat.full` |
|
||||
| `bi.stat.inc` | `bi.stat.inc` |
|
||||
|
||||
后续渠道:新增 `order.convert.{platform}` 队列,绑定 `order.convert.{platform}`;BI 队列与平台无关。
|
||||
|
||||
### 4.2 消息:订单转换(全量 + 增量共用)
|
||||
|
||||
```json
|
||||
{
|
||||
"messageId": "uuid",
|
||||
"companyId": 1,
|
||||
"shopId": 10,
|
||||
"platform": "pdd",
|
||||
"mode": "FULL_DAY",
|
||||
"statDate": "2026-07-01",
|
||||
"orders": [
|
||||
{ "channelOrderId": 101 },
|
||||
{ "channelOrderId": 102 }
|
||||
],
|
||||
"syncBatchId": "taskId:2026-07-01",
|
||||
"taskId": 55,
|
||||
"occurredAt": "2026-07-28T16:00:00+08:00"
|
||||
}
|
||||
```
|
||||
|
||||
| 字段 | FULL_DAY | INC |
|
||||
|------|----------|-----|
|
||||
| `mode` | `FULL_DAY` | `INC` |
|
||||
| `statDate` | 必填(成交日) | 可空 |
|
||||
| `orders` | 当日同步到的渠道镜像主键列表;可空则按店+日查渠道表 | 必填(本页 upsert 的渠道镜像主键) |
|
||||
| `syncBatchId` / `taskId` | 全量任务追踪 | 可选 |
|
||||
|
||||
约定:
|
||||
|
||||
- **全量日转换与增量转换走同一转换队列**(按平台分队列)
|
||||
- 生产者:全量「每天同步完」/ 增量「每页同步完」publish;补单 repair 仍经 Listener;**禁止**在 sync 线程内做重转换
|
||||
|
||||
### 4.3 消息:BI 全量日计算
|
||||
|
||||
```json
|
||||
{
|
||||
"messageId": "uuid",
|
||||
"companyId": 1,
|
||||
"shopId": 10,
|
||||
"platformCode": "pdd",
|
||||
"statDate": "2026-07-01",
|
||||
"syncBatchId": "taskId:2026-07-01",
|
||||
"occurredAt": "2026-07-28T16:01:00+08:00"
|
||||
}
|
||||
```
|
||||
|
||||
### 4.4 消息:BI 增量计算(转换侧已算好 delta)
|
||||
|
||||
```json
|
||||
{
|
||||
"messageId": "uuid",
|
||||
"companyId": 1,
|
||||
"shopId": 10,
|
||||
"platformCode": "pdd",
|
||||
"statDate": "2026-07-01",
|
||||
"internalOrderUpdateTime": "2026-07-28T16:01:30+08:00",
|
||||
"orderId": 9001,
|
||||
"channelOrderId": 101,
|
||||
"shopDelta": { "salesAmount": 12.3, "gmvOrderCount": 1, "...": "..." },
|
||||
"productDeltas": [
|
||||
{ "productId": 1, "categoryId": 2, "metrics": { "salesAmount": 12.3 } }
|
||||
],
|
||||
"specDeltas": [
|
||||
{ "productId": 1, "productSpecId": 9, "metrics": { "salesAmount": 12.3 } }
|
||||
],
|
||||
"occurredAt": "2026-07-28T16:01:30+08:00"
|
||||
}
|
||||
```
|
||||
|
||||
| 字段 | 说明 |
|
||||
|------|------|
|
||||
| `statDate` | 受影响自然日 = `DATE(ec_order.order_time)`(Asia/Shanghai) |
|
||||
| `internalOrderUpdateTime` | 转换完成时内部订单更新时间(与文档/会话 `dbSnapshotTime` 比较) |
|
||||
| `shopDelta` / `productDeltas` / `specDeltas` | 转换侧算出的各聚合字段加减量(可正可负) |
|
||||
| `orderId` / `channelOrderId` | 排查用 |
|
||||
|
||||
一笔增量订单按受影响 `statDate` 各发一条;跨日改单会发多条。BI 侧只做跳过判断与 `$inc` 累加,不再按日重算。
|
||||
|
||||
---
|
||||
|
||||
## 5. Channel 转换层(以 PDD 为例)
|
||||
|
||||
### 5.1 包与职责
|
||||
|
||||
建议路径:`modules/channel/pdd/order/convert/`
|
||||
|
||||
| 组件 | 职责 |
|
||||
|------|------|
|
||||
| `PddOrderConvertMqPublisher` | sync 成功后发 `OrderConvertMessage` |
|
||||
| `PddOrderConvertConsumer` | 消费 `order.convert.pdd` |
|
||||
| `PddOrderConvertService` | `channel_pdd_order(+item)` → `ec_order(+item)` |
|
||||
| `PddOrderStatusMapper` | PDD 状态整型 → 内部 `OrderStatus` |
|
||||
| `PddBiCalcPublisher` | 转换完成后发 `bi.stat.full` / `bi.stat.inc` |
|
||||
|
||||
投递策略(固定):
|
||||
|
||||
1. **全量 day / bootstrap**:每同步完一天 → publish `mode=FULL_DAY` + 当日 `orders[{id, updateTime}]`(列表可空则消费者按 `shopId+statDate` 查渠道表)
|
||||
2. **incremental**:每同步完一页 → publish `mode=INC` + 本页 `orders`
|
||||
3. **repair**:经 `PddOrderAfterSyncListener` publish `mode=INC` + refs;日常增量不再经 Listener
|
||||
|
||||
全量任务保证「一天同步完 → 一条转换消息」。
|
||||
|
||||
### 5.2 映射规则(摘要)
|
||||
|
||||
| 内部字段 | 来源 |
|
||||
|----------|------|
|
||||
| `platform_order_no` | `channel_pdd_order.order_sn` |
|
||||
| `source` | 固定 `sync` |
|
||||
| `source_order_id` | `channel_pdd_order.id` |
|
||||
| `platform_code` | `pdd` |
|
||||
| `shop_id` / `company_id` | 上下文 |
|
||||
| 金额 / 邮费 / 优惠 | 与渠道镜像同构字段 |
|
||||
| `order_time` | PDD `created_time`(统计日键) |
|
||||
| `confirm_time` 等 | 对应渠道时间字段 |
|
||||
| `last_mapped_time` | 本次转换完成时间 |
|
||||
| 明细商品绑定 | 与现有导入逻辑对齐(`outer_id` / 平台货品 id → `product_id` / `product_sku_id`;未匹配为 0) |
|
||||
|
||||
幂等键:`(company_id, platform_order_no)`(或现有 UK)。重复转换覆盖更新金额、状态、明细(先删后插或按行 upsert)。
|
||||
|
||||
### 5.3 转换逻辑与发 BI 消息
|
||||
|
||||
| mode | 行为 |
|
||||
|------|------|
|
||||
| `FULL_DAY` | 开事务批量转换(按消息渠道主键或店+成交日查渠道表)→ 写 `ec_order.platform_updated_at` ← 渠道 `pdd_updated_at` → 发 **一条** `bi.stat.full`(**不**再写转换侧 Redis 快照) |
|
||||
| `INC` | 逐单按 `channelOrderId` 查渠道镜像;内部用 `platform_code + source_order_id` 定位:无单则新增;有单则仅当 `channel.pdd_updated_at` **严格晚于** `ec_order.platform_updated_at` 时覆盖转换;用转换前后贡献差算出 delta,按受影响 `statDate` 各发一条 `bi.stat.inc`;`internalOrderUpdateTime` = 转换后 `ec_order.update_time` |
|
||||
|
||||
部分失败:FULL_DAY 不发 full 消息,转换消息进重试/DLQ;INC 仅对实际转换成功的订单发 inc 消息。
|
||||
|
||||
---
|
||||
|
||||
## 6. BI 日汇聚(Mongo)
|
||||
|
||||
写侧消费者与聚合服务落在 `modules/bi/orderstat`(模块整体划分见 §8.3,禁止在 `bi` 根目录平铺)。
|
||||
|
||||
### 6.1 集合与维度
|
||||
|
||||
仅日维度,三张集合(对齐旧 `ec_order_stat_daily_shop` / `_product` / `_spec`,**无**月/年):
|
||||
|
||||
| 集合名 | 唯一键 |
|
||||
|--------|--------|
|
||||
| `bi_order_stat_daily_shop` | `(companyId, shopId, statDate)` |
|
||||
| `bi_order_stat_daily_product` | `(companyId, shopId, productId, categoryId, statDate)` |
|
||||
| `bi_order_stat_daily_spec` | `(companyId, shopId, productSpecId, statDate)` |
|
||||
|
||||
`productId=0` 表示未匹配商品;`categoryId=0` 表示未分类;`productSpecId=0` 表示未绑定规格。
|
||||
`categoryId` 为订单写入时快照,商品改类目不回算历史(与旧设计一致)。
|
||||
|
||||
建议索引:
|
||||
|
||||
- shop:`{ companyId: 1, shopId: 1, statDate: 1 }` unique;`{ companyId: 1, statDate: 1 }`;`{ companyId: 1, platformCode: 1, statDate: 1 }`
|
||||
- product:unique 复合键如上;`{ companyId: 1, categoryId: 1, statDate: 1 }`;`{ companyId: 1, productId: 1, statDate: 1 }`
|
||||
- spec:unique 复合键如上;`{ companyId: 1, productId: 1, statDate: 1 }`
|
||||
|
||||
`spring.data.mongodb.auto-index-creation=false`,索引由迁移脚本或启动显式创建。
|
||||
|
||||
### 6.2 Document 字段(指标对齐旧日表)
|
||||
|
||||
公共指标列含义与 [ec_order_stat_design.sql](../sql/design/ec/ec_order_stat_design.sql) / `OrderStatusStatSets` 一致:
|
||||
|
||||
| 字段 | 口径 |
|
||||
|------|------|
|
||||
| `salesAmount` | 实际销售额:`SUM(received_amount)`,状态 ∈ salesStatusIds |
|
||||
| `salesOrderCount` | 实际销售单量 |
|
||||
| `salesQuantitySum` | 实际销量件数:`qty = IFNULL(NULLIF(quantity,0), 1)` |
|
||||
| `gmvAmount` | 总 GMV:全状态 `SUM(received_amount)` |
|
||||
| `gmvOrderCount` | GMV 单量 |
|
||||
| `gmvQuantitySum` | GMV 销量件数 |
|
||||
| `refundAmount` | 退款金额(refundStatusIds) |
|
||||
| `productCost` | 商品成本 × qty(productCostStatusIds) |
|
||||
| `freightCost` | 运费成本 × qty(freightCostStatusIds) |
|
||||
| `otherCost` | 其他成本 × qty(otherCostStatusIds) |
|
||||
|
||||
#### 店铺日文档示例
|
||||
|
||||
```json
|
||||
{
|
||||
"_id": "ObjectId",
|
||||
"companyId": 1,
|
||||
"shopId": 10,
|
||||
"platformCode": "pdd",
|
||||
"statDate": "2026-07-01",
|
||||
"salesAmount": 0,
|
||||
"salesOrderCount": 0,
|
||||
"salesQuantitySum": 0,
|
||||
"gmvAmount": 0,
|
||||
"gmvOrderCount": 0,
|
||||
"gmvQuantitySum": 0,
|
||||
"refundAmount": 0,
|
||||
"productCost": 0,
|
||||
"freightCost": 0,
|
||||
"otherCost": 0,
|
||||
"statVersion": 0,
|
||||
"dbSnapshotTime": "2026-07-28T16:02:00.123+08:00",
|
||||
"computedAt": "2026-07-28T16:02:05.000+08:00",
|
||||
"computeMode": "FULL"
|
||||
}
|
||||
```
|
||||
|
||||
#### 商品日文档额外键
|
||||
|
||||
`productId`, `categoryId`(其余指标字段同上)。
|
||||
|
||||
#### 规格日文档额外键
|
||||
|
||||
`productId`, `productSpecId`(其余指标字段同上)。
|
||||
|
||||
#### 元数据字段(本管线新增)
|
||||
|
||||
| 字段 | 说明 |
|
||||
|------|------|
|
||||
| `dbSnapshotTime` | **最新一次全量计算**开启 MySQL 事务快照的时刻;增量用 `internalOrderUpdateTime` 与之比较。**仅全量写入/更新**;增量 `$inc` 不抬高该字段 |
|
||||
| `statVersion` | 与 `OrderStatusStatSets` 重算批次对齐;配置变更全量 rebuild 时递增 |
|
||||
| `computedAt` | 本次写入完成时间 |
|
||||
| `computeMode` | `FULL` / `INC` |
|
||||
|
||||
金额字段 Mongo 中用 `Decimal128` 或存字符串/分(实现选 **Decimal128**,与 Java `BigDecimal` 对齐)。
|
||||
|
||||
### 6.3 全量计算消费者
|
||||
|
||||
对 `(companyId, shopId, statDate)`:
|
||||
|
||||
1. 获取 Redis 计算锁:`bi:stat:lock:{companyId}:{shopId}:{statDate}`(TTL 需覆盖最坏重算时间)
|
||||
2. MySQL:`START TRANSACTION WITH CONSISTENT SNAPSHOT`(或等价一致读),记录 **`dbSnapshotTime = now(会话开启时刻)`**
|
||||
3. 在快照内按 `order_time` 落在该自然日、限定 `shop_id`,读取 `ec_order` / `ec_order_item`,用 `OrderStatusStatSets` 口径聚合三维
|
||||
4. **覆盖写** Mongo 三集合该日该店相关文档(先删该店该日旧 product/spec 再插入,或 bulk upsert;shop 单文档 replace)
|
||||
5. 所有文档写入相同的 `dbSnapshotTime`、`computeMode=FULL`
|
||||
6. 提交/结束快照事务,释放锁
|
||||
|
||||
全量是「该日真相」:同键覆盖,天然幂等。
|
||||
|
||||
### 6.4 增量计算与快照互斥
|
||||
|
||||
比较键:消息 **`internalOrderUpdateTime`** vs 文档/会话 **`dbSnapshotTime`**。
|
||||
增量指标变化由**转换侧**算好放在消息里;BI 侧只做跳过判断与 Mongo `$inc`。全量/增量消息**同店串行**。
|
||||
|
||||
| 场景 | 行为 |
|
||||
|------|------|
|
||||
| 存在进行中的全量锁,且已暴露会话 `snapshotTime`,`internalOrderUpdateTime <= snapshotTime` | **ack 跳过** |
|
||||
| 存在进行中的全量锁,且 `internalOrderUpdateTime > snapshotTime` | **延后重试**,等全量写完后再比文档 `dbSnapshotTime` |
|
||||
| 无进行中全量;文档存在且 `internalOrderUpdateTime <= dbSnapshotTime` | **ack 跳过** |
|
||||
| 无进行中全量;文档不存在,或 `internalOrderUpdateTime > dbSnapshotTime` | 对 shop/product/spec **`$inc` 累加消息 delta**,`computeMode=INC`,**不更新** `dbSnapshotTime`(无文档时新建,`dbSnapshotTime` 为空,仅全量填充) |
|
||||
|
||||
说明:
|
||||
|
||||
- 「快照时间范围内」= **`internalOrderUpdateTime <= dbSnapshotTime`**
|
||||
- 全量进行中把 `snapshotTime` 登记到 Redis 锁元数据;落库后以 Mongo `dbSnapshotTime` 为准
|
||||
- 同店串行锁;delta 累加幂等依赖「快照跳过 + 至少一次投递下的业务可接受重复风险」——必要时后续可加 messageId 去重
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
IncMsg[BiIncCalcMessage]
|
||||
Lock{全量锁存在?}
|
||||
CmpSession{internalOrderUpdateTime <= session.snapshotTime?}
|
||||
Skip1[ack 跳过]
|
||||
Delay[延迟重试]
|
||||
ReadDoc[读 Mongo dbSnapshotTime]
|
||||
CmpDoc{文档存在且 internalOrderUpdateTime <= dbSnapshotTime?}
|
||||
Skip2[ack 跳过]
|
||||
ApplyDelta["$inc 累加 delta"]
|
||||
|
||||
IncMsg --> Lock
|
||||
Lock -->|是| CmpSession
|
||||
CmpSession -->|是| Skip1
|
||||
CmpSession -->|否| Delay
|
||||
Lock -->|否| ReadDoc
|
||||
ReadDoc --> CmpDoc
|
||||
CmpDoc -->|是| Skip2
|
||||
CmpDoc -->|否| ApplyDelta
|
||||
```
|
||||
|
||||
### 6.5 与旧 MySQL 读模型关系
|
||||
|
||||
- 本管线产出 Mongo 日汇聚;现有工作台 / 概览 / 导出仍在 `modules/ec`,可按 [订单统计读模型方案](./订单统计读模型方案.md) 读 MySQL 或在线聚合
|
||||
- 分析查看接口日后迁入 `bi`(**目录命名另定**);**切读 Mongo 另开任务**
|
||||
- 旧月/年表不再由本管线维护;长期区间查询若切 Mongo,由读侧按日 SUM
|
||||
|
||||
---
|
||||
|
||||
## 7. 失败、幂等与运维
|
||||
|
||||
| 环节 | 策略 |
|
||||
|------|------|
|
||||
| 渠道 sync | 沿用店锁、限流、游标;全量任务失败日可重试 |
|
||||
| 转换 | 至少一次投递;DB 幂等 `(company_id, platform_order_no)` |
|
||||
| BI 全量 | 覆盖写;同 `statDate` 重复消息安全 |
|
||||
| BI 增量 | 跳过或 `$inc` delta;延迟重试设最大次数后进 DLQ |
|
||||
| DLQ | `*.dlq` + 告警日志字段:`messageId` / `taskId` / `syncBatchId` / `statDate` / `shopId` |
|
||||
| 日志 | 结构化:platform、mode、耗时、跳过原因(`SKIP_IN_SNAPSHOT` / `DELAY_FULL_RUNNING`) |
|
||||
|
||||
消费者建议:`acknowledge-mode=auto` 下保证处理成功才返回;失败抛错触发重试策略(可后续改为 manual ack)。`default-requeue-rejected=false` 时需配置死信,避免丢消息。
|
||||
|
||||
---
|
||||
|
||||
## 8. 附录:实现落点清单
|
||||
|
||||
### 8.1 前端(`ecom-dmb-frontend`)
|
||||
|
||||
| 项 | 说明 |
|
||||
|----|------|
|
||||
| 全量任务创建 UI | 日期区间 + 确认;提交后展示进度(完成日 / 失败日) |
|
||||
| 增量开关 | 店铺列表或详情 Switch,调用 toggle API |
|
||||
| API 封装 | `full-task` / `toggle` / `status` 与现有 `order-sync/apis.ts` 并列 |
|
||||
|
||||
现有 `PddOrderSyncModal` 的 day/incremental 手动单次同步可保留作运维补拉;全量任务与增量开关为正式管线入口。
|
||||
|
||||
### 8.2 后端 Channel PDD
|
||||
|
||||
| 路径建议 | 内容 |
|
||||
|----------|------|
|
||||
| `.../order/sync/controller` | 全量任务、增量 toggle API |
|
||||
| `.../order/sync/service` | FullSyncTask 状态机 + 按日调用现有 day sync |
|
||||
| `.../order/sync/job` | IncrementalJob 过滤 `ec_shop.order_inc_sync_enabled` |
|
||||
| `.../order/sync/hook` | Listener 实现:仅 publish INC 转换消息 |
|
||||
| `.../order/convert/*` | Consumer、映射、BI publisher |
|
||||
| 表结构 | 全量任务表;增量状态表;`ec_shop` 增量开关;已废弃 sync_cursor |
|
||||
|
||||
### 8.3 后端 BI 模块划分(写侧;禁止平铺)
|
||||
|
||||
`modules/bi` **按子域分包 + 子域内分层**(对齐 `channel/pdd/order/sync` 习惯),禁止把 consumer / service / document 直接堆在 `modules/bi` 根下。
|
||||
|
||||
本阶段**只定义写侧与基础设施**目录。工作台 / 概览等分析查看接口日后迁入 `bi` 时再单独设计包名,本文不预设 `workbench` / `shopoverview` 等路径。
|
||||
|
||||
```
|
||||
modules/bi/
|
||||
├── infra/ # 基础设施(横切,无业务接口)
|
||||
│ ├── config/ # RabbitBiConfig、Mongo 索引初始化等
|
||||
│ └── lock/ # BiStatComputeLock(Redis 锁 + session snapshotTime)
|
||||
├── messaging/ # BI 计算消息契约(也可下沉 common)
|
||||
│ ├── BiMqConstants.java
|
||||
│ ├── BiFullCalcMessage.java
|
||||
│ └── BiIncCalcMessage.java
|
||||
└── orderstat/ # 日汇聚【写侧】——本管线核心
|
||||
├── consumer/
|
||||
│ ├── BiStatFullConsumer.java
|
||||
│ └── BiStatIncConsumer.java
|
||||
├── service/
|
||||
│ ├── OrderDailyStatComputeService.java # 共用按日聚合(读 ec_order)
|
||||
│ └── impl/
|
||||
├── model/
|
||||
│ └── document/ # Mongo @Document:DailyShop / DailyProduct / DailySpec
|
||||
└── repository/ # MongoTemplate / MongoRepository
|
||||
```
|
||||
|
||||
分层约定(`orderstat` 等业务子域内部):
|
||||
|
||||
| 层 | 职责 |
|
||||
|----|------|
|
||||
| `service` | 用例编排;按日聚合写 Mongo |
|
||||
| `model/document` | Mongo 持久化模型 |
|
||||
| `repository` | 仅数据访问 |
|
||||
| `consumer` | 仅 MQ 入口,立刻委托 `service`(与 channel sync 同原则) |
|
||||
|
||||
依赖方向:`bi.orderstat` → `ec`(读订单等);分析查看迁入前 **禁止** 为迁接口而反向依赖。日后读侧迁入时保持 `bi` → `ec`(主数据),禁止 `ec` → `bi`。
|
||||
|
||||
### 8.4 公共消息
|
||||
|
||||
| 建议位置 | 内容 |
|
||||
|----------|------|
|
||||
| `modules/bi/messaging` | BI 计算消息 DTO、队列名常量(首选) |
|
||||
| `modules/common/mq`(可选) | 若 channel 不能依赖 `bi` 包,将 `BiFullCalcMessage` / `BiIncCalcMessage` 下沉 common;转换消息 `OrderConvertMessage` 放 common 或 channel |
|
||||
|
||||
推荐依赖:`channel` → `common`(发 BI 消息);`bi.orderstat` → `common` / 本模块 `messaging`。避免 `channel` ↔ `bi` 循环依赖。
|
||||
|
||||
### 8.5 配置项(示意)
|
||||
|
||||
```yaml
|
||||
# channel-pdd.yml 增补
|
||||
pdd:
|
||||
order-sync:
|
||||
full-task-enabled: true
|
||||
incremental-job-enabled: true # 总闸
|
||||
# 单店开关在 DB
|
||||
|
||||
# 新建或 application.yml
|
||||
ecom:
|
||||
mq:
|
||||
order-convert-exchange: ecom.order.topic
|
||||
bi:
|
||||
stat:
|
||||
lock-ttl-seconds: 600
|
||||
inc-delay-ms: 5000
|
||||
inc-max-retry: 20
|
||||
```
|
||||
|
||||
### 8.6 建议实现顺序
|
||||
|
||||
1. 建立 `modules/bi` 写侧骨架(`infra` / `messaging` / `orderstat`)——**先分层再写类**
|
||||
2. MQ 基础设施(`bi.infra.config`)+ 消息 DTO(空消费者可先打日志)
|
||||
3. PDD 转换层 + 写 `ec_order` + 发 BI 消息
|
||||
4. `bi.orderstat` 全量消费者 + Mongo document / repository / 索引
|
||||
5. `bi.orderstat` 增量消费者 + 快照跳过
|
||||
6. 全量任务 API + 前端创建/进度
|
||||
7. 增量开关 API + 前端 Switch + Job 过滤
|
||||
8.(后续另案)分析查看接口迁入 `bi`(命名另定)+ 读路径切 Mongo
|
||||
|
||||
---
|
||||
|
||||
## 9. 固定决策摘要
|
||||
|
||||
| 决策 | 选择 |
|
||||
|------|------|
|
||||
| 文档路径 | `docs/订单同步转换与BI日汇聚设计.md` |
|
||||
| BI 包结构 | 写侧子域划分 + 域内分层;禁止 `modules/bi` 根目录平铺 |
|
||||
| 分析查看接口 | 日后迁 `bi`;**本文不预设目录名**;现仍留 `ec` |
|
||||
| 日维度 | shop + product + spec;无月/年;无推广费/刷单 |
|
||||
| 转换队列 | 全量日与增量**共用**(按平台分队列) |
|
||||
| BI 队列 | 全量 / 增量**分两个队列** |
|
||||
| 全量计算 | MySQL consistent snapshot + 按日重算覆盖写 Mongo,写入 `dbSnapshotTime` |
|
||||
| 增量转换 | 消息带渠道主键;内部用 `platform_code + source_order_id` 定位;对比 `ec_order.platform_updated_at` vs 渠道 `pdd_updated_at`;跳过或转换并产出 delta |
|
||||
| 增量计算 | 转换侧算 delta 并带 `internalOrderUpdateTime`;BI:`internalOrderUpdateTime <= dbSnapshotTime` 跳过,否则 `$inc`;全量进行中且更新更晚则延后 |
|
||||
| 增量写 Mongo | `$inc` 累加,不抬高 `dbSnapshotTime` |
|
||||
| 投递转换 | 全量按天 / 增量按页 publish(消息带渠道镜像主键);Listener 仅 repair |
|
||||
| 转换侧快照 | **取消** Redis 全量转换快照;新旧判断落在订单行上的平台更新时间 |
|
||||
| 全量默认区间 | 近 90 天 |
|
||||
| 读模型 | 本管线只写 Mongo;切读另期 |
|
||||
@@ -170,7 +170,8 @@ CREATE TABLE `ec_order` (
|
||||
`remark` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '商家备注',
|
||||
`import_task_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '导入任务ID(source=import 时;弱关联,无 FK)',
|
||||
`confirm` tinyint NOT NULL DEFAULT 1 COMMENT '确认(0-否 1-是)',
|
||||
`last_mapped_time` datetime NULL DEFAULT NULL COMMENT '最近一次由平台镜像映射/更新时间',
|
||||
`platform_updated_at` datetime NULL DEFAULT NULL COMMENT '平台侧订单更新时间(如 PDD updated_at);增量转换新旧比对用',
|
||||
`last_mapped_time` datetime NULL DEFAULT NULL COMMENT '最近一次由平台镜像映射到本表的本地时间',
|
||||
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
`create_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '创建人ID(审计,无 FK)',
|
||||
@@ -438,6 +439,7 @@ CREATE TABLE `ec_shop` (
|
||||
`logo_image_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT 'logo图片ID',
|
||||
`platform_code` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '平台代码(软约定枚举,无平台表)',
|
||||
`external_shop_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '外部店铺ID(如拼多多 mall_id;与 platform_code 组合关联平台店铺)',
|
||||
`order_inc_sync_enabled` tinyint NOT NULL DEFAULT 0 COMMENT '订单增量同步开关:0关 1开(产品配置,与渠道运行态分离)',
|
||||
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
`create_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '创建人ID',
|
||||
@@ -446,6 +448,7 @@ CREATE TABLE `ec_shop` (
|
||||
UNIQUE INDEX `uk_ec_shop_company_platform_external`(`company_id` ASC, `platform_code` ASC, `external_shop_id` ASC) USING BTREE COMMENT '同一公司同一平台下外部店铺ID唯一(NULL 可重复,手工店)',
|
||||
INDEX `idx_company_id`(`company_id` ASC) USING BTREE,
|
||||
INDEX `idx_platform_code`(`platform_code` ASC) USING BTREE,
|
||||
INDEX `idx_ec_shop_order_inc_sync`(`platform_code` ASC, `order_inc_sync_enabled` ASC) USING BTREE COMMENT '增量同步 Job 扫描',
|
||||
INDEX `fk_ec_shop_logo_image`(`logo_image_id` ASC) USING BTREE,
|
||||
INDEX `fk_ec_shop_creator`(`create_by` ASC) USING BTREE,
|
||||
INDEX `fk_ec_shop_updater`(`update_by` ASC) USING BTREE,
|
||||
|
||||
@@ -15,31 +15,34 @@
|
||||
-- 映射路径:channel_pdd_order(+item) → 转换器 → ec_order(+item);其他平台同理各建镜像表再统一转入
|
||||
-- 2. 主表 + 明细表覆盖列表查询、对账、物流、状态同步;gift_list / promotion_detail_list /
|
||||
-- order_tag_list 等嵌套结构写入 raw_response
|
||||
-- 3. 幂等键 uk(company_id, order_sn);同步进度按店存在 channel_pdd_order_sync_cursor,
|
||||
-- 不以 max(pdd_updated_at) 代替游标(空窗口会卡住)
|
||||
-- 3. 幂等键 uk(company_id, order_sn)
|
||||
-- 4. 主表仅存脱敏收件信息(*_mask);明文地址/电话不落独立列(完整报文在 raw_response)
|
||||
-- 5. 同步策略详见 channel_pdd_order_sync_design.md
|
||||
-- 限流(官方 FAQ):商家限流=单店铺;接口总限流=全平台所有店铺/所有 ISV
|
||||
-- 例:pdd.order.list.get 商家 10000次/60秒,接口总 17500次/10秒
|
||||
-- 6. SDK 未内置限流;出站前按「店铺 + API」经 PddPopRateLimiter,触限阻塞/退避,不推进游标
|
||||
-- 7. 同步控制面(已废弃 channel_pdd_order_sync_cursor):
|
||||
-- · 增量开关:ec_shop.order_inc_sync_enabled
|
||||
-- · 增量运行态(游标/出错暂停):channel_pdd_order_inc_sync(每店一行)
|
||||
-- · 全量任务进度:channel_pdd_order_full_sync_task
|
||||
-- ========================================
|
||||
|
||||
-- ========================================
|
||||
-- 拼多多订单同步游标表(按店铺 + 同步类型)
|
||||
-- sync_type:
|
||||
-- bootstrap = 历史回补(按成交时间推进)
|
||||
-- incremental = 日常增量(按更新时间推进)
|
||||
-- ========================================
|
||||
DROP TABLE IF EXISTS `channel_pdd_order_item`;
|
||||
DROP TABLE IF EXISTS `channel_pdd_order`;
|
||||
DROP TABLE IF EXISTS `channel_pdd_order_full_sync_task`;
|
||||
DROP TABLE IF EXISTS `channel_pdd_order_inc_sync`;
|
||||
DROP TABLE IF EXISTS `channel_pdd_order_sync_cursor`;
|
||||
CREATE TABLE `channel_pdd_order_sync_cursor` (
|
||||
|
||||
-- ========================================
|
||||
-- 拼多多订单增量同步状态表(每店一行;开关在 ec_shop)
|
||||
-- status: 0停用 1正常 2出错暂停(Job 跳过 status=2,直至人工恢复)
|
||||
-- ========================================
|
||||
CREATE TABLE `channel_pdd_order_inc_sync` (
|
||||
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID',
|
||||
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
|
||||
`shop_id` bigint UNSIGNED NOT NULL COMMENT '内部店铺ID(ec_shop.id)',
|
||||
`pdd_auth_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '拼多多授权ID(channel_pdd_auth.id)',
|
||||
`sync_type` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '同步类型:bootstrap | incremental',
|
||||
`last_cursor_at` datetime NULL DEFAULT NULL COMMENT '已成功同步到的时间游标(bootstrap=成交时间;incremental=更新时间)',
|
||||
`last_cursor_at` datetime NULL DEFAULT NULL COMMENT '已成功同步到的更新时间游标',
|
||||
`overlap_seconds` int NOT NULL DEFAULT 120 COMMENT '窗口重叠秒数(防边界漏单,默认 120)',
|
||||
`status` tinyint NOT NULL DEFAULT 1 COMMENT '状态:0停用 1正常 2出错暂停',
|
||||
`last_error` varchar(1000) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '最近一次错误信息',
|
||||
@@ -47,13 +50,39 @@ CREATE TABLE `channel_pdd_order_sync_cursor` (
|
||||
`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 INDEX `uk_channel_pdd_order_sync_cursor_shop_type`(`shop_id` ASC, `sync_type` ASC) USING BTREE,
|
||||
INDEX `idx_channel_pdd_order_sync_cursor_company`(`company_id` ASC) USING BTREE,
|
||||
INDEX `idx_channel_pdd_order_sync_cursor_status`(`status` ASC) USING BTREE,
|
||||
CONSTRAINT `fk_channel_pdd_order_sync_cursor_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_channel_pdd_order_sync_cursor_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_channel_pdd_order_sync_cursor_auth` FOREIGN KEY (`pdd_auth_id`) REFERENCES `channel_pdd_auth` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
|
||||
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '拼多多-订单同步游标表' ROW_FORMAT = Dynamic;
|
||||
UNIQUE INDEX `uk_channel_pdd_order_inc_sync_shop`(`shop_id` ASC) USING BTREE,
|
||||
INDEX `idx_channel_pdd_order_inc_sync_company`(`company_id` ASC) USING BTREE,
|
||||
INDEX `idx_channel_pdd_order_inc_sync_status`(`status` ASC) USING BTREE,
|
||||
CONSTRAINT `fk_channel_pdd_order_inc_sync_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_channel_pdd_order_inc_sync_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_channel_pdd_order_inc_sync_auth` FOREIGN KEY (`pdd_auth_id`) REFERENCES `channel_pdd_auth` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
|
||||
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '拼多多-订单增量同步状态表' ROW_FORMAT = Dynamic;
|
||||
|
||||
-- ========================================
|
||||
-- 拼多多订单全量同步任务表(按成交日区间串行回补)
|
||||
-- status: PENDING / RUNNING / SUCCESS / FAILED / CANCELLED
|
||||
-- ========================================
|
||||
CREATE TABLE `channel_pdd_order_full_sync_task` (
|
||||
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID',
|
||||
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
|
||||
`shop_id` bigint UNSIGNED NOT NULL COMMENT '内部店铺ID(ec_shop.id)',
|
||||
`platform_code` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'pdd' COMMENT '平台编码',
|
||||
`date_from` date NOT NULL COMMENT '成交日起(含)',
|
||||
`date_to` date NOT NULL COMMENT '成交日止(含)',
|
||||
`current_date` date NULL DEFAULT NULL COMMENT '当前处理成交日',
|
||||
`total_days` int NOT NULL DEFAULT 0 COMMENT '区间总天数',
|
||||
`done_days` int NOT NULL DEFAULT 0 COMMENT '已完成天数',
|
||||
`failed_days` int NOT NULL DEFAULT 0 COMMENT '失败天数',
|
||||
`status` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'PENDING' COMMENT 'PENDING/RUNNING/SUCCESS/FAILED/CANCELLED',
|
||||
`last_error` varchar(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '最近一次错误信息',
|
||||
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
`finish_time` timestamp NULL DEFAULT NULL COMMENT '结束时间',
|
||||
PRIMARY KEY (`id`) USING BTREE,
|
||||
INDEX `idx_channel_pdd_order_full_sync_task_shop_status`(`company_id` ASC, `shop_id` ASC, `status` ASC) USING BTREE,
|
||||
CONSTRAINT `fk_channel_pdd_order_full_sync_task_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_channel_pdd_order_full_sync_task_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 = '拼多多-订单全量同步任务表' ROW_FORMAT = Dynamic;
|
||||
|
||||
-- ========================================
|
||||
-- 拼多多订单主表
|
||||
|
||||
@@ -49,7 +49,7 @@ ec_shop (platform_code=pdd, external_shop_id=mall_id)
|
||||
|
||||
**切窗**:目标区间按 **24 小时** 切段;每段翻页直到 `has_next=false`。
|
||||
|
||||
**游标**:`channel_pdd_order_sync_cursor.sync_type='bootstrap'`,`last_cursor_at` = 已完成回补的成交时间上界(从旧往新推进)。
|
||||
**进度**:有界全量任务写 `channel_pdd_order_full_sync_task`(`current_date` / `done_days`);不再使用 bootstrap 游标表。
|
||||
|
||||
回补 QPS 高、易触限:必须走统一限流器,并建议限制「同时回补店铺数」(默认 1~2)。
|
||||
|
||||
@@ -66,10 +66,12 @@ ec_shop (platform_code=pdd, external_shop_id=mall_id)
|
||||
| `use_has_next` | true | 正序翻页即可 |
|
||||
| `overlap_seconds` | 120 | 窗口重叠,防边界漏单 |
|
||||
|
||||
**切窗**:从游标 `last_cursor_at - overlap` 拉到 `now`,切成 **≤30 分钟** 窗口;窗口之间重叠 `overlap_seconds`。
|
||||
**切窗**:从 `channel_pdd_order_inc_sync.last_cursor_at - overlap` 拉到 `now`,切成 **≤30 分钟** 窗口;窗口之间重叠 `overlap_seconds`。
|
||||
|
||||
**游标推进**:窗口成功后,将 `last_cursor_at` 设为本窗口 `end_updated_at`(下一次再减 overlap 起拉)。
|
||||
|
||||
**开关**:`ec_shop.order_inc_sync_enabled`;Job 仅扫已开启且 `inc_sync.status≠2` 的店。
|
||||
|
||||
**分页注意**:若不用 `use_has_next` 而按 `total_count` 分页,SDK 要求**从最后一页倒序往回取**,否则可能漏单。本设计默认 `use_has_next=true`,避免倒序复杂度。
|
||||
|
||||
多店串行或受控并行(默认串行扫店),所有出站调用共享应用级限流配额。
|
||||
@@ -78,7 +80,7 @@ ec_shop (platform_code=pdd, external_shop_id=mall_id)
|
||||
|
||||
管理端传入 `order_sn` 列表,或对账发现缺失时调用 `pdd.order.information.get`,单条走同一 upsert。
|
||||
|
||||
不推进 bootstrap/incremental 游标;同样经限流器出站。
|
||||
不推进增量游标;同样经限流器出站。
|
||||
|
||||
## 4. 落库与幂等
|
||||
|
||||
@@ -97,12 +99,17 @@ ec_shop (platform_code=pdd, external_shop_id=mall_id)
|
||||
- 推荐:按 `order_id` **先删后插**,避免 SKU 变更残留;或按 `(order_id, sku_id)` upsert。
|
||||
- `gift_list` / `promotion_detail_list` / `order_tag_list` 只进主表 `raw_response`。
|
||||
|
||||
### 4.3 游标 `channel_pdd_order_sync_cursor`
|
||||
### 4.3 增量状态 `channel_pdd_order_inc_sync`(已废弃 `channel_pdd_order_sync_cursor`)
|
||||
|
||||
- `uk(shop_id, sync_type)`,`sync_type ∈ {bootstrap, incremental}`。
|
||||
- `uk(shop_id)`,每店一行。
|
||||
- 开关在 `ec_shop.order_inc_sync_enabled`,本表只存运行态。
|
||||
- **不要**用 `MAX(pdd_updated_at)` 代替游标:空窗口会导致进度停滞或回拉过大。
|
||||
- `status`:`0` 停用 / `1` 正常 / `2` 出错暂停。
|
||||
|
||||
### 4.4 全量任务 `channel_pdd_order_full_sync_task`
|
||||
|
||||
- 有界区间回补进度与状态;失败写 `last_error` / `FAILED`。
|
||||
|
||||
## 5. 防漏单清单
|
||||
|
||||
1. 增量必须用 `updated_at` 接口,不能只用成交时间列表。
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
-- 订单同步控制面重构(对齐 sql/design/ec):
|
||||
-- 1. ec_shop 增加增量开关 order_inc_sync_enabled
|
||||
-- 2. 新建 channel_pdd_order_inc_sync(增量运行态,每店一行)
|
||||
-- 3. 从 channel_pdd_order_sync_cursor 迁移 incremental 游标后废弃该表
|
||||
-- 注:channel_pdd_order_full_sync_task 已预先创建,本脚本不再建表
|
||||
|
||||
ALTER TABLE `ec_shop`
|
||||
ADD COLUMN `order_inc_sync_enabled` tinyint NOT NULL DEFAULT 0
|
||||
COMMENT '订单增量同步开关:0关 1开(产品配置,与渠道运行态分离)'
|
||||
AFTER `external_shop_id`;
|
||||
|
||||
ALTER TABLE `ec_shop`
|
||||
ADD INDEX `idx_ec_shop_order_inc_sync` (`platform_code` ASC, `order_inc_sync_enabled` ASC);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `channel_pdd_order_inc_sync` (
|
||||
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID',
|
||||
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
|
||||
`shop_id` bigint UNSIGNED NOT NULL COMMENT '内部店铺ID(ec_shop.id)',
|
||||
`pdd_auth_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '拼多多授权ID(channel_pdd_auth.id)',
|
||||
`last_cursor_at` datetime NULL DEFAULT NULL COMMENT '已成功同步到的更新时间游标',
|
||||
`overlap_seconds` int NOT NULL DEFAULT 120 COMMENT '窗口重叠秒数(防边界漏单,默认 120)',
|
||||
`status` tinyint NOT NULL DEFAULT 1 COMMENT '状态:0停用 1正常 2出错暂停',
|
||||
`last_error` varchar(1000) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '最近一次错误信息',
|
||||
`last_success_time` datetime NULL DEFAULT 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,
|
||||
UNIQUE INDEX `uk_channel_pdd_order_inc_sync_shop`(`shop_id` ASC) USING BTREE,
|
||||
INDEX `idx_channel_pdd_order_inc_sync_company`(`company_id` ASC) USING BTREE,
|
||||
INDEX `idx_channel_pdd_order_inc_sync_status`(`status` ASC) USING BTREE,
|
||||
CONSTRAINT `fk_channel_pdd_order_inc_sync_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_channel_pdd_order_inc_sync_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_channel_pdd_order_inc_sync_auth` FOREIGN KEY (`pdd_auth_id`) REFERENCES `channel_pdd_auth` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
|
||||
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '拼多多-订单增量同步状态表';
|
||||
|
||||
-- 迁移旧游标表中的 incremental 行(开关需在前端重新打开,写入 ec_shop.order_inc_sync_enabled)
|
||||
INSERT INTO `channel_pdd_order_inc_sync` (
|
||||
`company_id`, `shop_id`, `pdd_auth_id`, `last_cursor_at`, `overlap_seconds`,
|
||||
`status`, `last_error`, `last_success_time`, `create_time`, `update_time`
|
||||
)
|
||||
SELECT
|
||||
`company_id`, `shop_id`, `pdd_auth_id`, `last_cursor_at`,
|
||||
IFNULL(`overlap_seconds`, 120), IFNULL(`status`, 1),
|
||||
`last_error`, `last_success_time`, `create_time`, `update_time`
|
||||
FROM `channel_pdd_order_sync_cursor`
|
||||
WHERE `sync_type` = 'incremental'
|
||||
ON DUPLICATE KEY UPDATE
|
||||
`pdd_auth_id` = VALUES(`pdd_auth_id`),
|
||||
`last_cursor_at` = VALUES(`last_cursor_at`),
|
||||
`overlap_seconds` = VALUES(`overlap_seconds`),
|
||||
`status` = VALUES(`status`),
|
||||
`last_error` = VALUES(`last_error`),
|
||||
`last_success_time` = VALUES(`last_success_time`);
|
||||
|
||||
DROP TABLE IF EXISTS `channel_pdd_order_sync_cursor`;
|
||||
@@ -0,0 +1,5 @@
|
||||
-- 内部订单增加平台侧更新时间,供增量转换新旧比对
|
||||
ALTER TABLE `ec_order`
|
||||
ADD COLUMN `platform_updated_at` datetime NULL DEFAULT NULL
|
||||
COMMENT '平台侧订单更新时间(如 PDD updated_at);增量转换新旧比对用'
|
||||
AFTER `confirm`;
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package top.xyquan.ecomdmbbackend.common.mq;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* 渠道订单引用:镜像表主键。
|
||||
* 转换侧按 id 查渠道镜像;内部单用 platform_code + source_order_id 定位。
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class ChannelOrderRef {
|
||||
|
||||
/** 渠道镜像订单主键(如 channel_pdd_order.id) */
|
||||
private Long channelOrderId;
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package top.xyquan.ecomdmbbackend.common.mq;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class OrderConvertMessage {
|
||||
|
||||
private String messageId;
|
||||
private Long companyId;
|
||||
private Long shopId;
|
||||
private String platform;
|
||||
private OrderConvertMode mode;
|
||||
/** FULL_DAY 必填:成交自然日 yyyy-MM-dd */
|
||||
private String statDate;
|
||||
/** 渠道镜像订单主键列表(增量按页必带;全量日可带,空则按店+成交日查渠道表) */
|
||||
private List<ChannelOrderRef> orders;
|
||||
private String syncBatchId;
|
||||
private Long taskId;
|
||||
private OffsetDateTime occurredAt;
|
||||
private Integer retryCount;
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package top.xyquan.ecomdmbbackend.common.mq;
|
||||
|
||||
/**
|
||||
* 订单转换消息模式:全量日与增量共用同一转换队列。
|
||||
*/
|
||||
public enum OrderConvertMode {
|
||||
FULL_DAY,
|
||||
INC
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package top.xyquan.ecomdmbbackend.common.mq;
|
||||
|
||||
/**
|
||||
* 订单同步 / 转换 / BI 管线 MQ 常量。
|
||||
*/
|
||||
public final class OrderMqConstants {
|
||||
|
||||
public static final String EXCHANGE = "ecom.order.topic";
|
||||
|
||||
public static final String RK_ORDER_SYNC_PDD_FULL = "order.sync.pdd.full";
|
||||
public static final String QUEUE_ORDER_SYNC_PDD_FULL = "order.sync.pdd.full";
|
||||
public static final String QUEUE_ORDER_SYNC_PDD_FULL_DLQ = "order.sync.pdd.full.dlq";
|
||||
|
||||
public static final String RK_ORDER_SYNC_PDD_INC = "order.sync.pdd.inc";
|
||||
public static final String QUEUE_ORDER_SYNC_PDD_INC = "order.sync.pdd.inc";
|
||||
public static final String QUEUE_ORDER_SYNC_PDD_INC_DLQ = "order.sync.pdd.inc.dlq";
|
||||
|
||||
public static final String RK_ORDER_CONVERT_PDD = "order.convert.pdd";
|
||||
public static final String QUEUE_ORDER_CONVERT_PDD = "order.convert.pdd";
|
||||
public static final String QUEUE_ORDER_CONVERT_PDD_DLQ = "order.convert.pdd.dlq";
|
||||
|
||||
public static final String RK_BI_STAT_FULL = "bi.stat.full";
|
||||
public static final String QUEUE_BI_STAT_FULL = "bi.stat.full";
|
||||
public static final String QUEUE_BI_STAT_FULL_DLQ = "bi.stat.full.dlq";
|
||||
|
||||
public static final String RK_BI_STAT_INC = "bi.stat.inc";
|
||||
public static final String QUEUE_BI_STAT_INC = "bi.stat.inc";
|
||||
public static final String QUEUE_BI_STAT_INC_DLQ = "bi.stat.inc.dlq";
|
||||
|
||||
private OrderMqConstants() {
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.infra.config;
|
||||
|
||||
import org.bson.types.Decimal128;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.springframework.data.convert.ReadingConverter;
|
||||
import org.springframework.data.convert.WritingConverter;
|
||||
import org.springframework.data.mongodb.core.convert.MongoCustomConversions;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* BigDecimal 存 Decimal128,避免默认写成字符串导致 $inc / 数值运算失败。
|
||||
*/
|
||||
@Configuration
|
||||
public class BiMongoConversionsConfig {
|
||||
|
||||
@Bean
|
||||
public MongoCustomConversions mongoCustomConversions() {
|
||||
return new MongoCustomConversions(List.of(
|
||||
new BigDecimalToDecimal128Converter(),
|
||||
new Decimal128ToBigDecimalConverter()));
|
||||
}
|
||||
|
||||
@WritingConverter
|
||||
static class BigDecimalToDecimal128Converter implements Converter<BigDecimal, Decimal128> {
|
||||
@Override
|
||||
public Decimal128 convert(BigDecimal source) {
|
||||
return new Decimal128(source);
|
||||
}
|
||||
}
|
||||
|
||||
@ReadingConverter
|
||||
static class Decimal128ToBigDecimalConverter implements Converter<Decimal128, BigDecimal> {
|
||||
@Override
|
||||
public BigDecimal convert(Decimal128 source) {
|
||||
return source.bigDecimalValue();
|
||||
}
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.infra.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "ecom.bi.stat")
|
||||
public class BiStatProperties {
|
||||
|
||||
/** 全量计算锁 TTL(秒) */
|
||||
private long lockTtlSeconds = 600;
|
||||
|
||||
/** 增量遇全量进行中时延迟毫秒 */
|
||||
private long incDelayMs = 5000;
|
||||
|
||||
/** 增量延迟最大重试次数 */
|
||||
private int incMaxRetry = 20;
|
||||
}
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.infra.config;
|
||||
|
||||
import org.springframework.amqp.core.Binding;
|
||||
import org.springframework.amqp.core.BindingBuilder;
|
||||
import org.springframework.amqp.core.Queue;
|
||||
import org.springframework.amqp.core.QueueBuilder;
|
||||
import org.springframework.amqp.core.TopicExchange;
|
||||
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
|
||||
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
|
||||
import org.springframework.amqp.rabbit.core.RabbitTemplate;
|
||||
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
|
||||
import org.springframework.amqp.support.converter.MessageConverter;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.OrderMqConstants;
|
||||
|
||||
@Configuration
|
||||
public class RabbitBiConfig {
|
||||
|
||||
@Bean
|
||||
public MessageConverter jacksonMessageConverter() {
|
||||
return new Jackson2JsonMessageConverter();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory, MessageConverter jacksonMessageConverter) {
|
||||
RabbitTemplate template = new RabbitTemplate(connectionFactory);
|
||||
template.setMessageConverter(jacksonMessageConverter);
|
||||
return template;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(
|
||||
ConnectionFactory connectionFactory, MessageConverter jacksonMessageConverter) {
|
||||
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
|
||||
factory.setConnectionFactory(connectionFactory);
|
||||
factory.setMessageConverter(jacksonMessageConverter);
|
||||
return factory;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public TopicExchange orderTopicExchange() {
|
||||
return new TopicExchange(OrderMqConstants.EXCHANGE, true, false);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue orderConvertPddQueue() {
|
||||
return QueueBuilder.durable(OrderMqConstants.QUEUE_ORDER_CONVERT_PDD)
|
||||
.withArgument("x-dead-letter-exchange", "")
|
||||
.withArgument("x-dead-letter-routing-key", OrderMqConstants.QUEUE_ORDER_CONVERT_PDD_DLQ)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue orderConvertPddDlq() {
|
||||
return QueueBuilder.durable(OrderMqConstants.QUEUE_ORDER_CONVERT_PDD_DLQ).build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Binding orderConvertPddBinding(Queue orderConvertPddQueue, TopicExchange orderTopicExchange) {
|
||||
return BindingBuilder.bind(orderConvertPddQueue)
|
||||
.to(orderTopicExchange)
|
||||
.with(OrderMqConstants.RK_ORDER_CONVERT_PDD);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue biStatFullQueue() {
|
||||
return QueueBuilder.durable(OrderMqConstants.QUEUE_BI_STAT_FULL)
|
||||
.withArgument("x-dead-letter-exchange", "")
|
||||
.withArgument("x-dead-letter-routing-key", OrderMqConstants.QUEUE_BI_STAT_FULL_DLQ)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue biStatFullDlq() {
|
||||
return QueueBuilder.durable(OrderMqConstants.QUEUE_BI_STAT_FULL_DLQ).build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Binding biStatFullBinding(Queue biStatFullQueue, TopicExchange orderTopicExchange) {
|
||||
return BindingBuilder.bind(biStatFullQueue)
|
||||
.to(orderTopicExchange)
|
||||
.with(OrderMqConstants.RK_BI_STAT_FULL);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue biStatIncQueue() {
|
||||
return QueueBuilder.durable(OrderMqConstants.QUEUE_BI_STAT_INC)
|
||||
.withArgument("x-dead-letter-exchange", "")
|
||||
.withArgument("x-dead-letter-routing-key", OrderMqConstants.QUEUE_BI_STAT_INC_DLQ)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue biStatIncDlq() {
|
||||
return QueueBuilder.durable(OrderMqConstants.QUEUE_BI_STAT_INC_DLQ).build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Binding biStatIncBinding(Queue biStatIncQueue, TopicExchange orderTopicExchange) {
|
||||
return BindingBuilder.bind(biStatIncQueue)
|
||||
.to(orderTopicExchange)
|
||||
.with(OrderMqConstants.RK_BI_STAT_INC);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue orderSyncPddFullQueue() {
|
||||
return QueueBuilder.durable(OrderMqConstants.QUEUE_ORDER_SYNC_PDD_FULL)
|
||||
.withArgument("x-dead-letter-exchange", "")
|
||||
.withArgument("x-dead-letter-routing-key", OrderMqConstants.QUEUE_ORDER_SYNC_PDD_FULL_DLQ)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue orderSyncPddFullDlq() {
|
||||
return QueueBuilder.durable(OrderMqConstants.QUEUE_ORDER_SYNC_PDD_FULL_DLQ).build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Binding orderSyncPddFullBinding(Queue orderSyncPddFullQueue, TopicExchange orderTopicExchange) {
|
||||
return BindingBuilder.bind(orderSyncPddFullQueue)
|
||||
.to(orderTopicExchange)
|
||||
.with(OrderMqConstants.RK_ORDER_SYNC_PDD_FULL);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue orderSyncPddIncQueue() {
|
||||
return QueueBuilder.durable(OrderMqConstants.QUEUE_ORDER_SYNC_PDD_INC)
|
||||
.withArgument("x-dead-letter-exchange", "")
|
||||
.withArgument("x-dead-letter-routing-key", OrderMqConstants.QUEUE_ORDER_SYNC_PDD_INC_DLQ)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue orderSyncPddIncDlq() {
|
||||
return QueueBuilder.durable(OrderMqConstants.QUEUE_ORDER_SYNC_PDD_INC_DLQ).build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Binding orderSyncPddIncBinding(Queue orderSyncPddIncQueue, TopicExchange orderTopicExchange) {
|
||||
return BindingBuilder.bind(orderSyncPddIncQueue)
|
||||
.to(orderTopicExchange)
|
||||
.with(OrderMqConstants.RK_ORDER_SYNC_PDD_INC);
|
||||
}
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.infra.lock;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.infra.config.BiStatProperties;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* BI 同店串行锁(全量/增量共用)。
|
||||
* 全量抢锁时登记会话 snapshotTime(事务快照开启时刻),供进行中的增量跳过/延后;
|
||||
* 持久化的「最新全量快照时间」以 Mongo 文档 dbSnapshotTime 为准。
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class BiStatComputeLock {
|
||||
|
||||
private static final String LOCK_PREFIX = "bi:stat:lock:";
|
||||
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
private final BiStatProperties biStatProperties;
|
||||
|
||||
/** 同店串行:key = companyId:shopId */
|
||||
public Optional<Session> tryLock(Long companyId, Long shopId, Instant snapshotTimeOrNull) {
|
||||
String key = lockKey(companyId, shopId);
|
||||
String token = UUID.randomUUID().toString();
|
||||
long ttl = Math.max(biStatProperties.getLockTtlSeconds(), 60);
|
||||
Boolean ok = stringRedisTemplate.opsForValue()
|
||||
.setIfAbsent(key + ":hold", token, Duration.ofSeconds(ttl));
|
||||
if (!Boolean.TRUE.equals(ok)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
Map<String, String> meta = new HashMap<>();
|
||||
meta.put("token", token);
|
||||
if (snapshotTimeOrNull != null) {
|
||||
meta.put("snapshotTime", String.valueOf(snapshotTimeOrNull.toEpochMilli()));
|
||||
}
|
||||
stringRedisTemplate.opsForHash().putAll(key, meta);
|
||||
stringRedisTemplate.expire(key, Duration.ofSeconds(ttl));
|
||||
return Optional.of(new Session(key, token, snapshotTimeOrNull));
|
||||
}
|
||||
|
||||
public Optional<Instant> peekSessionSnapshot(Long companyId, Long shopId) {
|
||||
Object v = stringRedisTemplate.opsForHash().get(lockKey(companyId, shopId), "snapshotTime");
|
||||
return parseInstant(v);
|
||||
}
|
||||
|
||||
public boolean isLocked(Long companyId, Long shopId) {
|
||||
return Boolean.TRUE.equals(stringRedisTemplate.hasKey(lockKey(companyId, shopId) + ":hold"));
|
||||
}
|
||||
|
||||
public void unlock(Session session) {
|
||||
if (session == null) {
|
||||
return;
|
||||
}
|
||||
String holdKey = session.key() + ":hold";
|
||||
String current = stringRedisTemplate.opsForValue().get(holdKey);
|
||||
if (session.token().equals(current)) {
|
||||
stringRedisTemplate.delete(holdKey);
|
||||
stringRedisTemplate.delete(session.key());
|
||||
}
|
||||
}
|
||||
|
||||
private static String lockKey(Long companyId, Long shopId) {
|
||||
return LOCK_PREFIX + companyId + ":" + shopId;
|
||||
}
|
||||
|
||||
private static Optional<Instant> parseInstant(Object v) {
|
||||
if (v == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
try {
|
||||
return Optional.of(Instant.ofEpochMilli(Long.parseLong(v.toString())));
|
||||
} catch (NumberFormatException e) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
public record Session(String key, String token, Instant snapshotTime) {
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.messaging;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class BiFullCalcMessage {
|
||||
|
||||
private String messageId;
|
||||
private Long companyId;
|
||||
private Long shopId;
|
||||
private String platformCode;
|
||||
/** yyyy-MM-dd */
|
||||
private String statDate;
|
||||
private String syncBatchId;
|
||||
private OffsetDateTime occurredAt;
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.messaging;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 增量计算消息:转换侧算好各维度加减量,BI 侧按快照决定跳过或累加。
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class BiIncCalcMessage {
|
||||
|
||||
private String messageId;
|
||||
private Long companyId;
|
||||
private Long shopId;
|
||||
private String platformCode;
|
||||
/** yyyy-MM-dd */
|
||||
private String statDate;
|
||||
/**
|
||||
* 转换完成时内部订单的更新时间(ec_order.update_time / last_mapped_time)。
|
||||
* BI 与 Mongo 文档 dbSnapshotTime(最新一次全量事务快照开启时间)比较:≤ 快照则跳过。
|
||||
*/
|
||||
private OffsetDateTime internalOrderUpdateTime;
|
||||
private Long orderId;
|
||||
private Long channelOrderId;
|
||||
private BiStatMetricDelta shopDelta;
|
||||
private List<BiProductStatDelta> productDeltas;
|
||||
private List<BiSpecStatDelta> specDeltas;
|
||||
private OffsetDateTime occurredAt;
|
||||
private Integer retryCount;
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.messaging;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class BiProductStatDelta {
|
||||
|
||||
private Long productId;
|
||||
private Long categoryId;
|
||||
private BiStatMetricDelta metrics;
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.messaging;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class BiSpecStatDelta {
|
||||
|
||||
private Long productId;
|
||||
private Long productSpecId;
|
||||
private BiStatMetricDelta metrics;
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.messaging;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/** 单维度指标增量(可正可负) */
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class BiStatMetricDelta {
|
||||
|
||||
private BigDecimal salesAmount;
|
||||
private Integer salesOrderCount;
|
||||
private Integer salesQuantitySum;
|
||||
private BigDecimal gmvAmount;
|
||||
private Integer gmvOrderCount;
|
||||
private Integer gmvQuantitySum;
|
||||
private BigDecimal refundAmount;
|
||||
private BigDecimal productCost;
|
||||
private BigDecimal freightCost;
|
||||
private BigDecimal otherCost;
|
||||
|
||||
public static BiStatMetricDelta zeros() {
|
||||
return BiStatMetricDelta.builder()
|
||||
.salesAmount(BigDecimal.ZERO)
|
||||
.salesOrderCount(0)
|
||||
.salesQuantitySum(0)
|
||||
.gmvAmount(BigDecimal.ZERO)
|
||||
.gmvOrderCount(0)
|
||||
.gmvQuantitySum(0)
|
||||
.refundAmount(BigDecimal.ZERO)
|
||||
.productCost(BigDecimal.ZERO)
|
||||
.freightCost(BigDecimal.ZERO)
|
||||
.otherCost(BigDecimal.ZERO)
|
||||
.build();
|
||||
}
|
||||
|
||||
public BiStatMetricDelta negate() {
|
||||
return BiStatMetricDelta.builder()
|
||||
.salesAmount(nz(salesAmount).negate())
|
||||
.salesOrderCount(-(salesOrderCount == null ? 0 : salesOrderCount))
|
||||
.salesQuantitySum(-(salesQuantitySum == null ? 0 : salesQuantitySum))
|
||||
.gmvAmount(nz(gmvAmount).negate())
|
||||
.gmvOrderCount(-(gmvOrderCount == null ? 0 : gmvOrderCount))
|
||||
.gmvQuantitySum(-(gmvQuantitySum == null ? 0 : gmvQuantitySum))
|
||||
.refundAmount(nz(refundAmount).negate())
|
||||
.productCost(nz(productCost).negate())
|
||||
.freightCost(nz(freightCost).negate())
|
||||
.otherCost(nz(otherCost).negate())
|
||||
.build();
|
||||
}
|
||||
|
||||
public BiStatMetricDelta plus(BiStatMetricDelta o) {
|
||||
if (o == null) {
|
||||
return this;
|
||||
}
|
||||
return BiStatMetricDelta.builder()
|
||||
.salesAmount(nz(salesAmount).add(nz(o.salesAmount)))
|
||||
.salesOrderCount(nzi(salesOrderCount) + nzi(o.salesOrderCount))
|
||||
.salesQuantitySum(nzi(salesQuantitySum) + nzi(o.salesQuantitySum))
|
||||
.gmvAmount(nz(gmvAmount).add(nz(o.gmvAmount)))
|
||||
.gmvOrderCount(nzi(gmvOrderCount) + nzi(o.gmvOrderCount))
|
||||
.gmvQuantitySum(nzi(gmvQuantitySum) + nzi(o.gmvQuantitySum))
|
||||
.refundAmount(nz(refundAmount).add(nz(o.refundAmount)))
|
||||
.productCost(nz(productCost).add(nz(o.productCost)))
|
||||
.freightCost(nz(freightCost).add(nz(o.freightCost)))
|
||||
.otherCost(nz(otherCost).add(nz(o.otherCost)))
|
||||
.build();
|
||||
}
|
||||
|
||||
public BiStatMetricDelta minus(BiStatMetricDelta o) {
|
||||
return plus(o == null ? null : o.negate());
|
||||
}
|
||||
|
||||
public boolean isAllZero() {
|
||||
return nz(salesAmount).signum() == 0
|
||||
&& nzi(salesOrderCount) == 0
|
||||
&& nzi(salesQuantitySum) == 0
|
||||
&& nz(gmvAmount).signum() == 0
|
||||
&& nzi(gmvOrderCount) == 0
|
||||
&& nzi(gmvQuantitySum) == 0
|
||||
&& nz(refundAmount).signum() == 0
|
||||
&& nz(productCost).signum() == 0
|
||||
&& nz(freightCost).signum() == 0
|
||||
&& nz(otherCost).signum() == 0;
|
||||
}
|
||||
|
||||
private static BigDecimal nz(BigDecimal v) {
|
||||
return v != null ? v : BigDecimal.ZERO;
|
||||
}
|
||||
|
||||
private static int nzi(Integer v) {
|
||||
return v != null ? v : 0;
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.consumer;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.amqp.rabbit.annotation.RabbitListener;
|
||||
import org.springframework.amqp.rabbit.core.RabbitTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.OrderMqConstants;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.infra.config.BiStatProperties;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiFullCalcMessage;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.service.OrderDailyStatComputeService;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.OffsetDateTime;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class BiStatFullConsumer {
|
||||
|
||||
private final OrderDailyStatComputeService computeService;
|
||||
private final BiStatProperties biStatProperties;
|
||||
private final RabbitTemplate rabbitTemplate;
|
||||
|
||||
@RabbitListener(queues = OrderMqConstants.QUEUE_BI_STAT_FULL)
|
||||
public void onMessage(BiFullCalcMessage message) {
|
||||
if (message == null || message.getCompanyId() == null || message.getShopId() == null
|
||||
|| message.getStatDate() == null) {
|
||||
log.warn("BI full 消息非法: {}", message);
|
||||
return;
|
||||
}
|
||||
LocalDate statDate = LocalDate.parse(message.getStatDate());
|
||||
log.info("收到 BI 全量计算 messageId={} shopId={} statDate={}",
|
||||
message.getMessageId(), message.getShopId(), statDate);
|
||||
boolean ok = computeService.tryComputeFull(
|
||||
message.getCompanyId(),
|
||||
message.getShopId(),
|
||||
statDate,
|
||||
message.getPlatformCode());
|
||||
if (!ok) {
|
||||
delayAndRepublish(message);
|
||||
}
|
||||
}
|
||||
|
||||
private void delayAndRepublish(BiFullCalcMessage message) {
|
||||
try {
|
||||
Thread.sleep(Math.max(biStatProperties.getIncDelayMs(), 100));
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IllegalStateException("BI full 延迟被中断", e);
|
||||
}
|
||||
message.setOccurredAt(OffsetDateTime.now());
|
||||
log.info("BI full 店锁占用,延后重投 messageId={} shopId={}",
|
||||
message.getMessageId(), message.getShopId());
|
||||
rabbitTemplate.convertAndSend(
|
||||
OrderMqConstants.EXCHANGE, OrderMqConstants.RK_BI_STAT_FULL, message);
|
||||
}
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.consumer;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.amqp.rabbit.annotation.RabbitListener;
|
||||
import org.springframework.amqp.rabbit.core.RabbitTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.OrderMqConstants;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.infra.config.BiStatProperties;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.infra.lock.BiStatComputeLock;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiIncCalcMessage;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailyShopDoc;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.repository.BiOrderStatDailyRepository;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* BI 增量:与同店全量串行。
|
||||
* 比较消息中的内部订单更新时间 vs Mongo 文档最新全量快照时间(dbSnapshotTime);
|
||||
* 在快照内(≤)跳过,在外(>)才 $inc。全量进行中则按会话快照同样规则跳过或延后。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class BiStatIncConsumer {
|
||||
|
||||
private final BiStatComputeLock computeLock;
|
||||
private final BiOrderStatDailyRepository repository;
|
||||
private final BiStatProperties biStatProperties;
|
||||
private final RabbitTemplate rabbitTemplate;
|
||||
|
||||
@RabbitListener(queues = OrderMqConstants.QUEUE_BI_STAT_INC)
|
||||
public void onMessage(BiIncCalcMessage message) {
|
||||
if (message == null || message.getCompanyId() == null || message.getShopId() == null
|
||||
|| message.getStatDate() == null || message.getInternalOrderUpdateTime() == null) {
|
||||
log.warn("BI inc 消息非法: {}", message);
|
||||
return;
|
||||
}
|
||||
LocalDate statDate = LocalDate.parse(message.getStatDate());
|
||||
Instant internalUpdated = message.getInternalOrderUpdateTime().toInstant();
|
||||
|
||||
// 全量进行中:同店串行;内部更新时间已在会话快照内则跳过,否则等全量结束后再比文档
|
||||
if (computeLock.isLocked(message.getCompanyId(), message.getShopId())) {
|
||||
Optional<Instant> sessionSnapshot =
|
||||
computeLock.peekSessionSnapshot(message.getCompanyId(), message.getShopId());
|
||||
if (sessionSnapshot.isPresent() && !internalUpdated.isAfter(sessionSnapshot.get())) {
|
||||
log.info("BI inc 跳过(全量会话快照内) messageId={} shopId={} statDate={}",
|
||||
message.getMessageId(), message.getShopId(), statDate);
|
||||
return;
|
||||
}
|
||||
delayAndRepublish(message);
|
||||
return;
|
||||
}
|
||||
|
||||
Optional<BiOrderStatDailyShopDoc> shopDoc =
|
||||
repository.findShop(message.getCompanyId(), message.getShopId(), statDate);
|
||||
if (withinFullSnapshot(shopDoc, internalUpdated)) {
|
||||
log.info("BI inc 跳过(文档全量快照内) messageId={} shopId={} statDate={}",
|
||||
message.getMessageId(), message.getShopId(), statDate);
|
||||
return;
|
||||
}
|
||||
|
||||
Optional<BiStatComputeLock.Session> session =
|
||||
computeLock.tryLock(message.getCompanyId(), message.getShopId(), null);
|
||||
if (session.isEmpty()) {
|
||||
delayAndRepublish(message);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
shopDoc = repository.findShop(message.getCompanyId(), message.getShopId(), statDate);
|
||||
if (withinFullSnapshot(shopDoc, internalUpdated)) {
|
||||
log.info("BI inc 跳过(抢锁后文档全量快照内) shopId={} statDate={}",
|
||||
message.getShopId(), statDate);
|
||||
return;
|
||||
}
|
||||
repository.applyIncDeltas(
|
||||
message.getCompanyId(),
|
||||
message.getShopId(),
|
||||
message.getPlatformCode(),
|
||||
statDate,
|
||||
message.getShopDelta(),
|
||||
message.getProductDeltas(),
|
||||
message.getSpecDeltas());
|
||||
log.info("BI inc delta 已累加 shopId={} statDate={} orderId={}",
|
||||
message.getShopId(), statDate, message.getOrderId());
|
||||
} finally {
|
||||
computeLock.unlock(session.get());
|
||||
}
|
||||
}
|
||||
|
||||
/** 内部订单更新时间 ≤ 文档最新全量快照时间 → 已包含在全量结果中 */
|
||||
private static boolean withinFullSnapshot(Optional<BiOrderStatDailyShopDoc> shopDoc,
|
||||
Instant internalUpdated) {
|
||||
return shopDoc.isPresent()
|
||||
&& shopDoc.get().getDbSnapshotTime() != null
|
||||
&& !internalUpdated.isAfter(shopDoc.get().getDbSnapshotTime());
|
||||
}
|
||||
|
||||
private void delayAndRepublish(BiIncCalcMessage message) {
|
||||
int retry = message.getRetryCount() == null ? 0 : message.getRetryCount();
|
||||
if (retry >= biStatProperties.getIncMaxRetry()) {
|
||||
throw new IllegalStateException("BI inc 延迟重试超限: " + message.getMessageId());
|
||||
}
|
||||
try {
|
||||
Thread.sleep(Math.max(biStatProperties.getIncDelayMs(), 100));
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IllegalStateException("BI inc 延迟被中断", e);
|
||||
}
|
||||
message.setRetryCount(retry + 1);
|
||||
message.setOccurredAt(OffsetDateTime.now());
|
||||
rabbitTemplate.convertAndSend(
|
||||
OrderMqConstants.EXCHANGE, OrderMqConstants.RK_BI_STAT_INC, message);
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.data.annotation.Id;
|
||||
import org.springframework.data.mongodb.core.index.CompoundIndex;
|
||||
import org.springframework.data.mongodb.core.index.CompoundIndexes;
|
||||
import org.springframework.data.mongodb.core.mapping.Document;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
|
||||
@Data
|
||||
@Document(collection = "bi_order_stat_daily_product")
|
||||
@CompoundIndexes({
|
||||
@CompoundIndex(
|
||||
name = "uk_company_shop_prod_cat_date",
|
||||
def = "{'companyId':1,'shopId':1,'productId':1,'categoryId':1,'statDate':1}",
|
||||
unique = true)
|
||||
})
|
||||
public class BiOrderStatDailyProductDoc {
|
||||
|
||||
@Id
|
||||
private String id;
|
||||
|
||||
private Long companyId;
|
||||
private Long shopId;
|
||||
private Long productId;
|
||||
private Long categoryId;
|
||||
private LocalDate statDate;
|
||||
|
||||
private BigDecimal salesAmount = BigDecimal.ZERO;
|
||||
private Integer salesOrderCount = 0;
|
||||
private Integer salesQuantitySum = 0;
|
||||
private BigDecimal gmvAmount = BigDecimal.ZERO;
|
||||
private Integer gmvOrderCount = 0;
|
||||
private Integer gmvQuantitySum = 0;
|
||||
private BigDecimal refundAmount = BigDecimal.ZERO;
|
||||
private BigDecimal productCost = BigDecimal.ZERO;
|
||||
private BigDecimal freightCost = BigDecimal.ZERO;
|
||||
private BigDecimal otherCost = BigDecimal.ZERO;
|
||||
|
||||
private Integer statVersion = 0;
|
||||
private Instant dbSnapshotTime;
|
||||
private Instant computedAt;
|
||||
private String computeMode;
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.data.annotation.Id;
|
||||
import org.springframework.data.mongodb.core.index.CompoundIndex;
|
||||
import org.springframework.data.mongodb.core.index.CompoundIndexes;
|
||||
import org.springframework.data.mongodb.core.mapping.Document;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
|
||||
@Data
|
||||
@Document(collection = "bi_order_stat_daily_shop")
|
||||
@CompoundIndexes({
|
||||
@CompoundIndex(name = "uk_company_shop_date", def = "{'companyId':1,'shopId':1,'statDate':1}", unique = true),
|
||||
@CompoundIndex(name = "idx_company_date", def = "{'companyId':1,'statDate':1}")
|
||||
})
|
||||
public class BiOrderStatDailyShopDoc {
|
||||
|
||||
@Id
|
||||
private String id;
|
||||
|
||||
private Long companyId;
|
||||
private Long shopId;
|
||||
private String platformCode;
|
||||
private LocalDate statDate;
|
||||
|
||||
private BigDecimal salesAmount = BigDecimal.ZERO;
|
||||
private Integer salesOrderCount = 0;
|
||||
private Integer salesQuantitySum = 0;
|
||||
private BigDecimal gmvAmount = BigDecimal.ZERO;
|
||||
private Integer gmvOrderCount = 0;
|
||||
private Integer gmvQuantitySum = 0;
|
||||
private BigDecimal refundAmount = BigDecimal.ZERO;
|
||||
private BigDecimal productCost = BigDecimal.ZERO;
|
||||
private BigDecimal freightCost = BigDecimal.ZERO;
|
||||
private BigDecimal otherCost = BigDecimal.ZERO;
|
||||
|
||||
private Integer statVersion = 0;
|
||||
/** 最新一次全量计算开启 MySQL 事务快照的时间;增量用内部订单更新时间与之比较 */
|
||||
private Instant dbSnapshotTime;
|
||||
private Instant computedAt;
|
||||
private String computeMode;
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.data.annotation.Id;
|
||||
import org.springframework.data.mongodb.core.index.CompoundIndex;
|
||||
import org.springframework.data.mongodb.core.index.CompoundIndexes;
|
||||
import org.springframework.data.mongodb.core.mapping.Document;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
|
||||
@Data
|
||||
@Document(collection = "bi_order_stat_daily_spec")
|
||||
@CompoundIndexes({
|
||||
@CompoundIndex(
|
||||
name = "uk_company_shop_spec_date",
|
||||
def = "{'companyId':1,'shopId':1,'productSpecId':1,'statDate':1}",
|
||||
unique = true)
|
||||
})
|
||||
public class BiOrderStatDailySpecDoc {
|
||||
|
||||
@Id
|
||||
private String id;
|
||||
|
||||
private Long companyId;
|
||||
private Long shopId;
|
||||
private Long productId;
|
||||
private Long productSpecId;
|
||||
private LocalDate statDate;
|
||||
|
||||
private BigDecimal salesAmount = BigDecimal.ZERO;
|
||||
private Integer salesOrderCount = 0;
|
||||
private Integer salesQuantitySum = 0;
|
||||
private BigDecimal gmvAmount = BigDecimal.ZERO;
|
||||
private Integer gmvOrderCount = 0;
|
||||
private Integer gmvQuantitySum = 0;
|
||||
private BigDecimal refundAmount = BigDecimal.ZERO;
|
||||
private BigDecimal productCost = BigDecimal.ZERO;
|
||||
private BigDecimal freightCost = BigDecimal.ZERO;
|
||||
private BigDecimal otherCost = BigDecimal.ZERO;
|
||||
|
||||
private Integer statVersion = 0;
|
||||
private Instant dbSnapshotTime;
|
||||
private Instant computedAt;
|
||||
private String computeMode;
|
||||
}
|
||||
+247
@@ -0,0 +1,247 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.repository;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.bson.types.Decimal128;
|
||||
import org.springframework.data.mongodb.core.MongoTemplate;
|
||||
import org.springframework.data.mongodb.core.query.Criteria;
|
||||
import org.springframework.data.mongodb.core.query.Query;
|
||||
import org.springframework.data.mongodb.core.query.Update;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiProductStatDelta;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiSpecStatDelta;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiStatMetricDelta;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailyProductDoc;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailyShopDoc;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailySpecDoc;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
public class BiOrderStatDailyRepository {
|
||||
|
||||
private final MongoTemplate mongoTemplate;
|
||||
|
||||
public Optional<BiOrderStatDailyShopDoc> findShop(Long companyId, Long shopId, LocalDate statDate) {
|
||||
Query q = Query.query(Criteria.where("companyId").is(companyId)
|
||||
.and("shopId").is(shopId)
|
||||
.and("statDate").is(statDate));
|
||||
return Optional.ofNullable(mongoTemplate.findOne(q, BiOrderStatDailyShopDoc.class));
|
||||
}
|
||||
|
||||
public void replaceShopDay(BiOrderStatDailyShopDoc shopDoc,
|
||||
List<BiOrderStatDailyProductDoc> products,
|
||||
List<BiOrderStatDailySpecDoc> specs) {
|
||||
Long companyId = shopDoc.getCompanyId();
|
||||
Long shopId = shopDoc.getShopId();
|
||||
LocalDate statDate = shopDoc.getStatDate();
|
||||
|
||||
Query dayQ = Query.query(Criteria.where("companyId").is(companyId)
|
||||
.and("shopId").is(shopId)
|
||||
.and("statDate").is(statDate));
|
||||
|
||||
findShop(companyId, shopId, statDate).ifPresentOrElse(existing -> {
|
||||
shopDoc.setId(existing.getId());
|
||||
if (!"FULL".equals(shopDoc.getComputeMode()) && existing.getDbSnapshotTime() != null) {
|
||||
shopDoc.setDbSnapshotTime(existing.getDbSnapshotTime());
|
||||
}
|
||||
mongoTemplate.save(shopDoc);
|
||||
}, () -> mongoTemplate.insert(shopDoc));
|
||||
|
||||
mongoTemplate.remove(dayQ, BiOrderStatDailyProductDoc.class);
|
||||
mongoTemplate.remove(dayQ, BiOrderStatDailySpecDoc.class);
|
||||
if (products != null && !products.isEmpty()) {
|
||||
mongoTemplate.insertAll(products);
|
||||
}
|
||||
if (specs != null && !specs.isEmpty()) {
|
||||
mongoTemplate.insertAll(specs);
|
||||
}
|
||||
}
|
||||
|
||||
/** 将转换侧算出的增量累加到日文档(无文档则按 delta 新建)。 */
|
||||
public void applyIncDeltas(Long companyId, Long shopId, String platformCode, LocalDate statDate,
|
||||
BiStatMetricDelta shopDelta,
|
||||
List<BiProductStatDelta> productDeltas,
|
||||
List<BiSpecStatDelta> specDeltas) {
|
||||
Instant now = Instant.now();
|
||||
Optional<BiOrderStatDailyShopDoc> existing = findShop(companyId, shopId, statDate);
|
||||
if (existing.isEmpty()) {
|
||||
BiOrderStatDailyShopDoc shop = new BiOrderStatDailyShopDoc();
|
||||
shop.setCompanyId(companyId);
|
||||
shop.setShopId(shopId);
|
||||
shop.setPlatformCode(platformCode);
|
||||
shop.setStatDate(statDate);
|
||||
applyMetricToShop(shop, shopDelta);
|
||||
shop.setComputeMode("INC");
|
||||
shop.setComputedAt(now);
|
||||
mongoTemplate.insert(shop);
|
||||
} else {
|
||||
Query q = Query.query(Criteria.where("companyId").is(companyId)
|
||||
.and("shopId").is(shopId)
|
||||
.and("statDate").is(statDate));
|
||||
Update u = metricIncUpdate(shopDelta);
|
||||
u.set("computedAt", now).set("computeMode", "INC");
|
||||
if (platformCode != null) {
|
||||
u.set("platformCode", platformCode);
|
||||
}
|
||||
mongoTemplate.updateFirst(q, u, BiOrderStatDailyShopDoc.class);
|
||||
}
|
||||
|
||||
if (productDeltas != null) {
|
||||
for (BiProductStatDelta pd : productDeltas) {
|
||||
if (pd.getMetrics() == null || pd.getMetrics().isAllZero()) {
|
||||
continue;
|
||||
}
|
||||
long productId = pd.getProductId() != null ? pd.getProductId() : 0L;
|
||||
long categoryId = pd.getCategoryId() != null ? pd.getCategoryId() : 0L;
|
||||
Query pq = Query.query(Criteria.where("companyId").is(companyId)
|
||||
.and("shopId").is(shopId)
|
||||
.and("productId").is(productId)
|
||||
.and("categoryId").is(categoryId)
|
||||
.and("statDate").is(statDate));
|
||||
BiOrderStatDailyProductDoc found = mongoTemplate.findOne(pq, BiOrderStatDailyProductDoc.class);
|
||||
if (found == null) {
|
||||
BiOrderStatDailyProductDoc doc = new BiOrderStatDailyProductDoc();
|
||||
doc.setCompanyId(companyId);
|
||||
doc.setShopId(shopId);
|
||||
doc.setProductId(productId);
|
||||
doc.setCategoryId(categoryId);
|
||||
doc.setStatDate(statDate);
|
||||
applyMetricToProduct(doc, pd.getMetrics());
|
||||
doc.setComputeMode("INC");
|
||||
doc.setComputedAt(now);
|
||||
mongoTemplate.insert(doc);
|
||||
} else {
|
||||
Update u = metricIncUpdate(pd.getMetrics());
|
||||
u.set("computedAt", now).set("computeMode", "INC");
|
||||
mongoTemplate.updateFirst(pq, u, BiOrderStatDailyProductDoc.class);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (specDeltas != null) {
|
||||
for (BiSpecStatDelta sd : specDeltas) {
|
||||
if (sd.getMetrics() == null || sd.getMetrics().isAllZero()) {
|
||||
continue;
|
||||
}
|
||||
long productId = sd.getProductId() != null ? sd.getProductId() : 0L;
|
||||
long specId = sd.getProductSpecId() != null ? sd.getProductSpecId() : 0L;
|
||||
Query sq = Query.query(Criteria.where("companyId").is(companyId)
|
||||
.and("shopId").is(shopId)
|
||||
.and("productSpecId").is(specId)
|
||||
.and("statDate").is(statDate));
|
||||
BiOrderStatDailySpecDoc found = mongoTemplate.findOne(sq, BiOrderStatDailySpecDoc.class);
|
||||
if (found == null) {
|
||||
BiOrderStatDailySpecDoc doc = new BiOrderStatDailySpecDoc();
|
||||
doc.setCompanyId(companyId);
|
||||
doc.setShopId(shopId);
|
||||
doc.setProductId(productId);
|
||||
doc.setProductSpecId(specId);
|
||||
doc.setStatDate(statDate);
|
||||
applyMetricToSpec(doc, sd.getMetrics());
|
||||
doc.setComputeMode("INC");
|
||||
doc.setComputedAt(now);
|
||||
mongoTemplate.insert(doc);
|
||||
} else {
|
||||
Update u = metricIncUpdate(sd.getMetrics());
|
||||
u.set("computedAt", now).set("computeMode", "INC");
|
||||
mongoTemplate.updateFirst(sq, u, BiOrderStatDailySpecDoc.class);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Update metricIncUpdate(BiStatMetricDelta d) {
|
||||
Update u = new Update();
|
||||
if (d == null) {
|
||||
return u;
|
||||
}
|
||||
inc(u, "salesAmount", d.getSalesAmount());
|
||||
inc(u, "salesOrderCount", d.getSalesOrderCount());
|
||||
inc(u, "salesQuantitySum", d.getSalesQuantitySum());
|
||||
inc(u, "gmvAmount", d.getGmvAmount());
|
||||
inc(u, "gmvOrderCount", d.getGmvOrderCount());
|
||||
inc(u, "gmvQuantitySum", d.getGmvQuantitySum());
|
||||
inc(u, "refundAmount", d.getRefundAmount());
|
||||
inc(u, "productCost", d.getProductCost());
|
||||
inc(u, "freightCost", d.getFreightCost());
|
||||
inc(u, "otherCost", d.getOtherCost());
|
||||
return u;
|
||||
}
|
||||
|
||||
private static void inc(Update u, String field, Number v) {
|
||||
if (v == null) {
|
||||
return;
|
||||
}
|
||||
if (v instanceof BigDecimal bd) {
|
||||
if (bd.signum() == 0) {
|
||||
return;
|
||||
}
|
||||
u.inc(field, new Decimal128(bd));
|
||||
return;
|
||||
}
|
||||
if (v instanceof Integer i && i == 0) {
|
||||
return;
|
||||
}
|
||||
u.inc(field, v);
|
||||
}
|
||||
|
||||
private static void applyMetricToShop(BiOrderStatDailyShopDoc doc, BiStatMetricDelta d) {
|
||||
if (d == null) {
|
||||
return;
|
||||
}
|
||||
doc.setSalesAmount(nz(d.getSalesAmount()));
|
||||
doc.setSalesOrderCount(nzi(d.getSalesOrderCount()));
|
||||
doc.setSalesQuantitySum(nzi(d.getSalesQuantitySum()));
|
||||
doc.setGmvAmount(nz(d.getGmvAmount()));
|
||||
doc.setGmvOrderCount(nzi(d.getGmvOrderCount()));
|
||||
doc.setGmvQuantitySum(nzi(d.getGmvQuantitySum()));
|
||||
doc.setRefundAmount(nz(d.getRefundAmount()));
|
||||
doc.setProductCost(nz(d.getProductCost()));
|
||||
doc.setFreightCost(nz(d.getFreightCost()));
|
||||
doc.setOtherCost(nz(d.getOtherCost()));
|
||||
}
|
||||
|
||||
private static void applyMetricToProduct(BiOrderStatDailyProductDoc doc, BiStatMetricDelta d) {
|
||||
if (d == null) {
|
||||
return;
|
||||
}
|
||||
doc.setSalesAmount(nz(d.getSalesAmount()));
|
||||
doc.setSalesOrderCount(nzi(d.getSalesOrderCount()));
|
||||
doc.setSalesQuantitySum(nzi(d.getSalesQuantitySum()));
|
||||
doc.setGmvAmount(nz(d.getGmvAmount()));
|
||||
doc.setGmvOrderCount(nzi(d.getGmvOrderCount()));
|
||||
doc.setGmvQuantitySum(nzi(d.getGmvQuantitySum()));
|
||||
doc.setRefundAmount(nz(d.getRefundAmount()));
|
||||
doc.setProductCost(nz(d.getProductCost()));
|
||||
doc.setFreightCost(nz(d.getFreightCost()));
|
||||
doc.setOtherCost(nz(d.getOtherCost()));
|
||||
}
|
||||
|
||||
private static void applyMetricToSpec(BiOrderStatDailySpecDoc doc, BiStatMetricDelta d) {
|
||||
if (d == null) {
|
||||
return;
|
||||
}
|
||||
doc.setSalesAmount(nz(d.getSalesAmount()));
|
||||
doc.setSalesOrderCount(nzi(d.getSalesOrderCount()));
|
||||
doc.setSalesQuantitySum(nzi(d.getSalesQuantitySum()));
|
||||
doc.setGmvAmount(nz(d.getGmvAmount()));
|
||||
doc.setGmvOrderCount(nzi(d.getGmvOrderCount()));
|
||||
doc.setGmvQuantitySum(nzi(d.getGmvQuantitySum()));
|
||||
doc.setRefundAmount(nz(d.getRefundAmount()));
|
||||
doc.setProductCost(nz(d.getProductCost()));
|
||||
doc.setFreightCost(nz(d.getFreightCost()));
|
||||
doc.setOtherCost(nz(d.getOtherCost()));
|
||||
}
|
||||
|
||||
private static BigDecimal nz(BigDecimal v) {
|
||||
return v != null ? v : BigDecimal.ZERO;
|
||||
}
|
||||
|
||||
private static int nzi(Integer v) {
|
||||
return v != null ? v : 0;
|
||||
}
|
||||
}
|
||||
+381
@@ -0,0 +1,381 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.infra.lock.BiStatComputeLock;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailyProductDoc;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailyShopDoc;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailySpecDoc;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.repository.BiOrderStatDailyRepository;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.mapper.OrderItemMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.mapper.OrderMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.po.OrderItemPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.po.OrderPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.status.support.OrderStatusStatResolver;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.status.support.OrderStatusStatSets;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.mapper.ProductMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductPO;
|
||||
|
||||
import org.springframework.transaction.TransactionDefinition;
|
||||
import org.springframework.transaction.support.DefaultTransactionDefinition;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class OrderDailyStatComputeService {
|
||||
|
||||
private final OrderMapper orderMapper;
|
||||
private final OrderItemMapper orderItemMapper;
|
||||
private final ProductMapper productMapper;
|
||||
private final OrderStatusStatResolver orderStatusStatResolver;
|
||||
private final BiOrderStatDailyRepository repository;
|
||||
private final BiStatComputeLock computeLock;
|
||||
private final PlatformTransactionManager transactionManager;
|
||||
|
||||
/**
|
||||
* 全量:同店串行锁 + MySQL 事务一致读重算;
|
||||
* 将事务快照开启时间写入 Mongo 文档 dbSnapshotTime(最新全量计算快照时间)。
|
||||
*/
|
||||
public boolean tryComputeFull(Long companyId, Long shopId, LocalDate statDate, String platformCode) {
|
||||
// 快照时刻在抢锁时登记,供进行中的增量与会话快照比较
|
||||
Instant snapshotTime = Instant.now();
|
||||
Optional<BiStatComputeLock.Session> sessionOpt =
|
||||
computeLock.tryLock(companyId, shopId, snapshotTime);
|
||||
if (sessionOpt.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
BiStatComputeLock.Session session = sessionOpt.get();
|
||||
try {
|
||||
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
|
||||
def.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ);
|
||||
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
|
||||
TransactionTemplate tt = new TransactionTemplate(transactionManager, def);
|
||||
tt.executeWithoutResult(status -> {
|
||||
DayAgg agg = aggregateDay(companyId, shopId, statDate, platformCode);
|
||||
persist(agg, snapshotTime, "FULL");
|
||||
});
|
||||
return true;
|
||||
} finally {
|
||||
computeLock.unlock(session);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated 增量已改为消费端 $inc delta,不再按日重算。
|
||||
*/
|
||||
public boolean tryComputeInc(Long companyId, Long shopId, LocalDate statDate, String platformCode) {
|
||||
Optional<BiStatComputeLock.Session> sessionOpt =
|
||||
computeLock.tryLock(companyId, shopId, null);
|
||||
if (sessionOpt.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
BiStatComputeLock.Session session = sessionOpt.get();
|
||||
try {
|
||||
DayAgg agg = aggregateDay(companyId, shopId, statDate, platformCode);
|
||||
persist(agg, null, "INC");
|
||||
return true;
|
||||
} finally {
|
||||
computeLock.unlock(session);
|
||||
}
|
||||
}
|
||||
|
||||
/** @deprecated 使用 {@link #tryComputeFull} */
|
||||
public void computeFull(Long companyId, Long shopId, LocalDate statDate, String platformCode) {
|
||||
if (!tryComputeFull(companyId, shopId, statDate, platformCode)) {
|
||||
throw new IllegalStateException("BI 店铺计算锁占用中: " + companyId + "/" + shopId);
|
||||
}
|
||||
}
|
||||
|
||||
/** @deprecated 使用 {@link #tryComputeInc} */
|
||||
public void computeInc(Long companyId, Long shopId, LocalDate statDate, String platformCode) {
|
||||
if (!tryComputeInc(companyId, shopId, statDate, platformCode)) {
|
||||
throw new IllegalStateException("BI 店铺计算锁占用中: " + companyId + "/" + shopId);
|
||||
}
|
||||
}
|
||||
|
||||
private DayAgg aggregateDay(Long companyId, Long shopId, LocalDate statDate, String platformCode) {
|
||||
LocalDateTime start = statDate.atStartOfDay();
|
||||
LocalDateTime end = statDate.plusDays(1).atStartOfDay();
|
||||
List<OrderPO> orders = orderMapper.selectList(new LambdaQueryWrapper<OrderPO>()
|
||||
.eq(OrderPO::getCompanyId, companyId)
|
||||
.eq(OrderPO::getShopId, shopId)
|
||||
.ge(OrderPO::getOrderTime, start)
|
||||
.lt(OrderPO::getOrderTime, end));
|
||||
OrderStatusStatSets stat = orderStatusStatResolver.resolve(companyId);
|
||||
|
||||
Map<Long, List<OrderItemPO>> itemsByOrder = new HashMap<>();
|
||||
if (!orders.isEmpty()) {
|
||||
List<Long> orderIds = orders.stream().map(OrderPO::getId).toList();
|
||||
List<OrderItemPO> items = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItemPO>()
|
||||
.in(OrderItemPO::getOrderId, orderIds));
|
||||
for (OrderItemPO item : items) {
|
||||
itemsByOrder.computeIfAbsent(item.getOrderId(), k -> new ArrayList<>()).add(item);
|
||||
}
|
||||
}
|
||||
|
||||
Set<Long> productIds = itemsByOrder.values().stream()
|
||||
.flatMap(List::stream)
|
||||
.map(OrderItemPO::getProductId)
|
||||
.filter(id -> id != null && id > 0)
|
||||
.collect(Collectors.toSet());
|
||||
Map<Long, Long> categoryByProduct = new HashMap<>();
|
||||
if (!productIds.isEmpty()) {
|
||||
List<ProductPO> products = productMapper.selectBatchIds(productIds);
|
||||
for (ProductPO p : products) {
|
||||
categoryByProduct.put(p.getId(), p.getCategoryId() != null ? p.getCategoryId() : 0L);
|
||||
}
|
||||
}
|
||||
|
||||
Metric shop = new Metric();
|
||||
Map<String, Metric> productMap = new HashMap<>();
|
||||
Map<String, Metric> specMap = new HashMap<>();
|
||||
Map<String, DimKey> productKeys = new HashMap<>();
|
||||
Map<String, DimKey> specKeys = new HashMap<>();
|
||||
|
||||
for (OrderPO order : orders) {
|
||||
List<OrderItemPO> items = itemsByOrder.getOrDefault(order.getId(), List.of());
|
||||
int qtySum = OrderStatusStatSets.totalQuantity(items);
|
||||
if (qtySum <= 0 && items.isEmpty()) {
|
||||
qtySum = 1;
|
||||
}
|
||||
BigDecimal pay = nz(order.getPayAmount());
|
||||
boolean sales = stat.includesSales(order.getStatus());
|
||||
boolean refund = stat.includesRefund(order.getStatus());
|
||||
|
||||
shop.gmvAmount = shop.gmvAmount.add(pay);
|
||||
shop.gmvOrderCount++;
|
||||
shop.gmvQuantitySum += qtySum;
|
||||
if (sales) {
|
||||
shop.salesAmount = shop.salesAmount.add(pay);
|
||||
shop.salesOrderCount++;
|
||||
shop.salesQuantitySum += qtySum;
|
||||
}
|
||||
if (refund) {
|
||||
shop.refundAmount = shop.refundAmount.add(pay);
|
||||
}
|
||||
|
||||
Set<String> countedProductSales = new HashSet<>();
|
||||
Set<String> countedProductGmv = new HashSet<>();
|
||||
Set<String> countedSpecSales = new HashSet<>();
|
||||
Set<String> countedSpecGmv = new HashSet<>();
|
||||
|
||||
if (items.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
for (OrderItemPO item : items) {
|
||||
long productId = item.getProductId() != null ? item.getProductId() : 0L;
|
||||
long categoryId = categoryByProduct.getOrDefault(productId, 0L);
|
||||
long specId = item.getProductSkuId() != null ? item.getProductSkuId() : 0L;
|
||||
int qty = OrderStatusStatSets.quantity(item);
|
||||
BigDecimal linePay = allocateLine(pay, item, items);
|
||||
|
||||
String pk = companyId + ":" + shopId + ":" + productId + ":" + categoryId;
|
||||
Metric pm = productMap.computeIfAbsent(pk, k -> new Metric());
|
||||
productKeys.putIfAbsent(pk, new DimKey(productId, categoryId, 0L));
|
||||
pm.gmvAmount = pm.gmvAmount.add(linePay);
|
||||
pm.gmvQuantitySum += qty;
|
||||
if (countedProductGmv.add(pk)) {
|
||||
pm.gmvOrderCount++;
|
||||
}
|
||||
if (sales) {
|
||||
pm.salesAmount = pm.salesAmount.add(linePay);
|
||||
pm.salesQuantitySum += qty;
|
||||
if (countedProductSales.add(pk)) {
|
||||
pm.salesOrderCount++;
|
||||
}
|
||||
}
|
||||
if (refund) {
|
||||
pm.refundAmount = pm.refundAmount.add(linePay);
|
||||
}
|
||||
pm.productCost = pm.productCost.add(stat.productCostForStats(order, item));
|
||||
pm.freightCost = pm.freightCost.add(stat.freightCostForStats(order, item));
|
||||
pm.otherCost = pm.otherCost.add(stat.otherCostForStats(order, item));
|
||||
|
||||
String sk = companyId + ":" + shopId + ":" + specId;
|
||||
Metric sm = specMap.computeIfAbsent(sk, k -> new Metric());
|
||||
specKeys.putIfAbsent(sk, new DimKey(productId, 0L, specId));
|
||||
sm.gmvAmount = sm.gmvAmount.add(linePay);
|
||||
sm.gmvQuantitySum += qty;
|
||||
if (countedSpecGmv.add(sk)) {
|
||||
sm.gmvOrderCount++;
|
||||
}
|
||||
if (sales) {
|
||||
sm.salesAmount = sm.salesAmount.add(linePay);
|
||||
sm.salesQuantitySum += qty;
|
||||
if (countedSpecSales.add(sk)) {
|
||||
sm.salesOrderCount++;
|
||||
}
|
||||
}
|
||||
if (refund) {
|
||||
sm.refundAmount = sm.refundAmount.add(linePay);
|
||||
}
|
||||
sm.productCost = sm.productCost.add(stat.productCostForStats(order, item));
|
||||
sm.freightCost = sm.freightCost.add(stat.freightCostForStats(order, item));
|
||||
sm.otherCost = sm.otherCost.add(stat.otherCostForStats(order, item));
|
||||
|
||||
shop.productCost = shop.productCost.add(stat.productCostForStats(order, item));
|
||||
shop.freightCost = shop.freightCost.add(stat.freightCostForStats(order, item));
|
||||
shop.otherCost = shop.otherCost.add(stat.otherCostForStats(order, item));
|
||||
}
|
||||
}
|
||||
|
||||
String platform = platformCode;
|
||||
if (platform == null && !orders.isEmpty()) {
|
||||
platform = orders.get(0).getPlatformCode();
|
||||
}
|
||||
|
||||
return new DayAgg(companyId, shopId, statDate, platform, shop, productMap, productKeys, specMap, specKeys);
|
||||
}
|
||||
|
||||
private void persist(DayAgg agg, Instant snapshotTime, String mode) {
|
||||
Instant now = Instant.now();
|
||||
BiOrderStatDailyShopDoc shopDoc = new BiOrderStatDailyShopDoc();
|
||||
shopDoc.setCompanyId(agg.companyId());
|
||||
shopDoc.setShopId(agg.shopId());
|
||||
shopDoc.setPlatformCode(agg.platformCode());
|
||||
shopDoc.setStatDate(agg.statDate());
|
||||
applyMetric(shopDoc, agg.shop());
|
||||
shopDoc.setDbSnapshotTime(snapshotTime);
|
||||
shopDoc.setComputedAt(now);
|
||||
shopDoc.setComputeMode(mode);
|
||||
|
||||
List<BiOrderStatDailyProductDoc> products = new ArrayList<>();
|
||||
for (Map.Entry<String, Metric> e : agg.productMap().entrySet()) {
|
||||
DimKey key = agg.productKeys().get(e.getKey());
|
||||
BiOrderStatDailyProductDoc doc = new BiOrderStatDailyProductDoc();
|
||||
doc.setCompanyId(agg.companyId());
|
||||
doc.setShopId(agg.shopId());
|
||||
doc.setProductId(key.productId());
|
||||
doc.setCategoryId(key.categoryId());
|
||||
doc.setStatDate(agg.statDate());
|
||||
applyMetric(doc, e.getValue());
|
||||
doc.setDbSnapshotTime(snapshotTime);
|
||||
doc.setComputedAt(now);
|
||||
doc.setComputeMode(mode);
|
||||
products.add(doc);
|
||||
}
|
||||
|
||||
List<BiOrderStatDailySpecDoc> specs = new ArrayList<>();
|
||||
for (Map.Entry<String, Metric> e : agg.specMap().entrySet()) {
|
||||
DimKey key = agg.specKeys().get(e.getKey());
|
||||
BiOrderStatDailySpecDoc doc = new BiOrderStatDailySpecDoc();
|
||||
doc.setCompanyId(agg.companyId());
|
||||
doc.setShopId(agg.shopId());
|
||||
doc.setProductId(key.productId());
|
||||
doc.setProductSpecId(key.specId());
|
||||
doc.setStatDate(agg.statDate());
|
||||
applyMetric(doc, e.getValue());
|
||||
doc.setDbSnapshotTime(snapshotTime);
|
||||
doc.setComputedAt(now);
|
||||
doc.setComputeMode(mode);
|
||||
specs.add(doc);
|
||||
}
|
||||
|
||||
repository.replaceShopDay(shopDoc, products, specs);
|
||||
log.info("BI 日汇聚完成 mode={} companyId={} shopId={} statDate={} ordersShopGmv={}",
|
||||
mode, agg.companyId(), agg.shopId(), agg.statDate(), agg.shop().gmvOrderCount);
|
||||
}
|
||||
|
||||
private static void applyMetric(BiOrderStatDailyShopDoc doc, Metric m) {
|
||||
doc.setSalesAmount(m.salesAmount);
|
||||
doc.setSalesOrderCount(m.salesOrderCount);
|
||||
doc.setSalesQuantitySum(m.salesQuantitySum);
|
||||
doc.setGmvAmount(m.gmvAmount);
|
||||
doc.setGmvOrderCount(m.gmvOrderCount);
|
||||
doc.setGmvQuantitySum(m.gmvQuantitySum);
|
||||
doc.setRefundAmount(m.refundAmount);
|
||||
doc.setProductCost(m.productCost);
|
||||
doc.setFreightCost(m.freightCost);
|
||||
doc.setOtherCost(m.otherCost);
|
||||
}
|
||||
|
||||
private static void applyMetric(BiOrderStatDailyProductDoc doc, Metric m) {
|
||||
doc.setSalesAmount(m.salesAmount);
|
||||
doc.setSalesOrderCount(m.salesOrderCount);
|
||||
doc.setSalesQuantitySum(m.salesQuantitySum);
|
||||
doc.setGmvAmount(m.gmvAmount);
|
||||
doc.setGmvOrderCount(m.gmvOrderCount);
|
||||
doc.setGmvQuantitySum(m.gmvQuantitySum);
|
||||
doc.setRefundAmount(m.refundAmount);
|
||||
doc.setProductCost(m.productCost);
|
||||
doc.setFreightCost(m.freightCost);
|
||||
doc.setOtherCost(m.otherCost);
|
||||
}
|
||||
|
||||
private static void applyMetric(BiOrderStatDailySpecDoc doc, Metric m) {
|
||||
doc.setSalesAmount(m.salesAmount);
|
||||
doc.setSalesOrderCount(m.salesOrderCount);
|
||||
doc.setSalesQuantitySum(m.salesQuantitySum);
|
||||
doc.setGmvAmount(m.gmvAmount);
|
||||
doc.setGmvOrderCount(m.gmvOrderCount);
|
||||
doc.setGmvQuantitySum(m.gmvQuantitySum);
|
||||
doc.setRefundAmount(m.refundAmount);
|
||||
doc.setProductCost(m.productCost);
|
||||
doc.setFreightCost(m.freightCost);
|
||||
doc.setOtherCost(m.otherCost);
|
||||
}
|
||||
|
||||
/** 按行金额占比分摊订单实收;无行金额则均分。 */
|
||||
private static BigDecimal allocateLine(BigDecimal orderPay, OrderItemPO item, List<OrderItemPO> items) {
|
||||
BigDecimal totalLine = BigDecimal.ZERO;
|
||||
for (OrderItemPO i : items) {
|
||||
totalLine = totalLine.add(nz(i.getLineAmount()));
|
||||
}
|
||||
if (totalLine.compareTo(BigDecimal.ZERO) > 0) {
|
||||
return orderPay.multiply(nz(item.getLineAmount())).divide(totalLine, 4, java.math.RoundingMode.HALF_UP);
|
||||
}
|
||||
if (items.isEmpty()) {
|
||||
return orderPay;
|
||||
}
|
||||
return orderPay.divide(BigDecimal.valueOf(items.size()), 4, java.math.RoundingMode.HALF_UP);
|
||||
}
|
||||
|
||||
private static BigDecimal nz(BigDecimal v) {
|
||||
return v != null ? v : BigDecimal.ZERO;
|
||||
}
|
||||
|
||||
private static final class Metric {
|
||||
BigDecimal salesAmount = BigDecimal.ZERO;
|
||||
int salesOrderCount;
|
||||
int salesQuantitySum;
|
||||
BigDecimal gmvAmount = BigDecimal.ZERO;
|
||||
int gmvOrderCount;
|
||||
int gmvQuantitySum;
|
||||
BigDecimal refundAmount = BigDecimal.ZERO;
|
||||
BigDecimal productCost = BigDecimal.ZERO;
|
||||
BigDecimal freightCost = BigDecimal.ZERO;
|
||||
BigDecimal otherCost = BigDecimal.ZERO;
|
||||
}
|
||||
|
||||
private record DimKey(long productId, long categoryId, long specId) {
|
||||
}
|
||||
|
||||
private record DayAgg(
|
||||
Long companyId,
|
||||
Long shopId,
|
||||
LocalDate statDate,
|
||||
String platformCode,
|
||||
Metric shop,
|
||||
Map<String, Metric> productMap,
|
||||
Map<String, DimKey> productKeys,
|
||||
Map<String, Metric> specMap,
|
||||
Map<String, DimKey> specKeys) {
|
||||
}
|
||||
}
|
||||
+206
@@ -0,0 +1,206 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.support;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiProductStatDelta;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiSpecStatDelta;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiStatMetricDelta;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.po.OrderItemPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.po.OrderPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.status.support.OrderStatusStatSets;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.mapper.ProductMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductPO;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
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;
|
||||
|
||||
/**
|
||||
* 单笔内部订单对日汇聚的贡献(转换侧算增量 delta 用)。
|
||||
*/
|
||||
@Component
|
||||
public class OrderStatContributionCalculator {
|
||||
|
||||
private final ProductMapper productMapper;
|
||||
|
||||
public OrderStatContributionCalculator(ProductMapper productMapper) {
|
||||
this.productMapper = productMapper;
|
||||
}
|
||||
|
||||
public OrderContribution contribute(OrderPO order, List<OrderItemPO> items, OrderStatusStatSets stat) {
|
||||
if (order == null || order.getOrderTime() == null) {
|
||||
return null;
|
||||
}
|
||||
LocalDate statDate = order.getOrderTime().toLocalDate();
|
||||
List<OrderItemPO> safeItems = items != null ? items : List.of();
|
||||
int qtySum = OrderStatusStatSets.totalQuantity(safeItems);
|
||||
if (qtySum <= 0 && safeItems.isEmpty()) {
|
||||
qtySum = 1;
|
||||
}
|
||||
BigDecimal pay = nz(order.getPayAmount());
|
||||
boolean sales = stat.includesSales(order.getStatus());
|
||||
boolean refund = stat.includesRefund(order.getStatus());
|
||||
|
||||
BiStatMetricDelta shop = BiStatMetricDelta.zeros();
|
||||
shop.setGmvAmount(pay);
|
||||
shop.setGmvOrderCount(1);
|
||||
shop.setGmvQuantitySum(qtySum);
|
||||
if (sales) {
|
||||
shop.setSalesAmount(pay);
|
||||
shop.setSalesOrderCount(1);
|
||||
shop.setSalesQuantitySum(qtySum);
|
||||
}
|
||||
if (refund) {
|
||||
shop.setRefundAmount(pay);
|
||||
}
|
||||
|
||||
Map<String, BiStatMetricDelta> productMap = new HashMap<>();
|
||||
Map<String, long[]> productKeys = new HashMap<>();
|
||||
Map<String, BiStatMetricDelta> specMap = new HashMap<>();
|
||||
Map<String, long[]> specKeys = new HashMap<>();
|
||||
|
||||
Map<Long, Long> categoryByProduct = loadCategories(safeItems);
|
||||
|
||||
for (OrderItemPO item : safeItems) {
|
||||
long productId = item.getProductId() != null ? item.getProductId() : 0L;
|
||||
long categoryId = categoryByProduct.getOrDefault(productId, 0L);
|
||||
long specId = item.getProductSkuId() != null ? item.getProductSkuId() : 0L;
|
||||
int qty = OrderStatusStatSets.quantity(item);
|
||||
BigDecimal linePay = allocateLine(pay, item, safeItems);
|
||||
|
||||
String pk = productId + ":" + categoryId;
|
||||
BiStatMetricDelta pm = productMap.computeIfAbsent(pk, k -> BiStatMetricDelta.zeros());
|
||||
productKeys.putIfAbsent(pk, new long[]{productId, categoryId});
|
||||
pm.setGmvAmount(nz(pm.getGmvAmount()).add(linePay));
|
||||
pm.setGmvQuantitySum(nzi(pm.getGmvQuantitySum()) + qty);
|
||||
if (sales) {
|
||||
pm.setSalesAmount(nz(pm.getSalesAmount()).add(linePay));
|
||||
pm.setSalesQuantitySum(nzi(pm.getSalesQuantitySum()) + qty);
|
||||
}
|
||||
if (refund) {
|
||||
pm.setRefundAmount(nz(pm.getRefundAmount()).add(linePay));
|
||||
}
|
||||
BigDecimal pc = stat.productCostForStats(order, item);
|
||||
BigDecimal fc = stat.freightCostForStats(order, item);
|
||||
BigDecimal oc = stat.otherCostForStats(order, item);
|
||||
pm.setProductCost(nz(pm.getProductCost()).add(pc));
|
||||
pm.setFreightCost(nz(pm.getFreightCost()).add(fc));
|
||||
pm.setOtherCost(nz(pm.getOtherCost()).add(oc));
|
||||
|
||||
String sk = String.valueOf(specId);
|
||||
BiStatMetricDelta sm = specMap.computeIfAbsent(sk, k -> BiStatMetricDelta.zeros());
|
||||
specKeys.putIfAbsent(sk, new long[]{productId, specId});
|
||||
sm.setGmvAmount(nz(sm.getGmvAmount()).add(linePay));
|
||||
sm.setGmvQuantitySum(nzi(sm.getGmvQuantitySum()) + qty);
|
||||
if (sales) {
|
||||
sm.setSalesAmount(nz(sm.getSalesAmount()).add(linePay));
|
||||
sm.setSalesQuantitySum(nzi(sm.getSalesQuantitySum()) + qty);
|
||||
}
|
||||
if (refund) {
|
||||
sm.setRefundAmount(nz(sm.getRefundAmount()).add(linePay));
|
||||
}
|
||||
sm.setProductCost(nz(sm.getProductCost()).add(pc));
|
||||
sm.setFreightCost(nz(sm.getFreightCost()).add(fc));
|
||||
sm.setOtherCost(nz(sm.getOtherCost()).add(oc));
|
||||
|
||||
shop.setProductCost(nz(shop.getProductCost()).add(pc));
|
||||
shop.setFreightCost(nz(shop.getFreightCost()).add(fc));
|
||||
shop.setOtherCost(nz(shop.getOtherCost()).add(oc));
|
||||
}
|
||||
|
||||
// 订单计数:商品/规格维度每单计 1 次(有明细时)
|
||||
if (!safeItems.isEmpty()) {
|
||||
for (BiStatMetricDelta pm : productMap.values()) {
|
||||
pm.setGmvOrderCount(1);
|
||||
if (sales) {
|
||||
pm.setSalesOrderCount(1);
|
||||
}
|
||||
}
|
||||
for (BiStatMetricDelta sm : specMap.values()) {
|
||||
sm.setGmvOrderCount(1);
|
||||
if (sales) {
|
||||
sm.setSalesOrderCount(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
List<BiProductStatDelta> products = new ArrayList<>();
|
||||
for (Map.Entry<String, BiStatMetricDelta> e : productMap.entrySet()) {
|
||||
long[] k = productKeys.get(e.getKey());
|
||||
products.add(BiProductStatDelta.builder()
|
||||
.productId(k[0])
|
||||
.categoryId(k[1])
|
||||
.metrics(e.getValue())
|
||||
.build());
|
||||
}
|
||||
List<BiSpecStatDelta> specs = new ArrayList<>();
|
||||
for (Map.Entry<String, BiStatMetricDelta> e : specMap.entrySet()) {
|
||||
long[] k = specKeys.get(e.getKey());
|
||||
specs.add(BiSpecStatDelta.builder()
|
||||
.productId(k[0])
|
||||
.productSpecId(k[1])
|
||||
.metrics(e.getValue())
|
||||
.build());
|
||||
}
|
||||
|
||||
return OrderContribution.builder()
|
||||
.statDate(statDate)
|
||||
.shop(shop)
|
||||
.products(products)
|
||||
.specs(specs)
|
||||
.build();
|
||||
}
|
||||
|
||||
private Map<Long, Long> loadCategories(List<OrderItemPO> items) {
|
||||
Map<Long, Long> map = new HashMap<>();
|
||||
List<Long> ids = items.stream()
|
||||
.map(OrderItemPO::getProductId)
|
||||
.filter(id -> id != null && id > 0)
|
||||
.distinct()
|
||||
.toList();
|
||||
if (ids.isEmpty()) {
|
||||
return map;
|
||||
}
|
||||
for (ProductPO p : productMapper.selectBatchIds(ids)) {
|
||||
map.put(p.getId(), p.getCategoryId() != null ? p.getCategoryId() : 0L);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
private static BigDecimal allocateLine(BigDecimal orderPay, OrderItemPO item, List<OrderItemPO> items) {
|
||||
BigDecimal totalLine = BigDecimal.ZERO;
|
||||
for (OrderItemPO i : items) {
|
||||
totalLine = totalLine.add(nz(i.getLineAmount()));
|
||||
}
|
||||
if (totalLine.compareTo(BigDecimal.ZERO) > 0) {
|
||||
return orderPay.multiply(nz(item.getLineAmount())).divide(totalLine, 4, RoundingMode.HALF_UP);
|
||||
}
|
||||
if (items.isEmpty()) {
|
||||
return orderPay;
|
||||
}
|
||||
return orderPay.divide(BigDecimal.valueOf(items.size()), 4, RoundingMode.HALF_UP);
|
||||
}
|
||||
|
||||
private static BigDecimal nz(BigDecimal v) {
|
||||
return v != null ? v : BigDecimal.ZERO;
|
||||
}
|
||||
|
||||
private static int nzi(Integer v) {
|
||||
return v != null ? v : 0;
|
||||
}
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
public static class OrderContribution {
|
||||
private LocalDate statDate;
|
||||
private BiStatMetricDelta shop;
|
||||
private List<BiProductStatDelta> products;
|
||||
private List<BiSpecStatDelta> specs;
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.consumer;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.amqp.rabbit.annotation.RabbitListener;
|
||||
import org.springframework.amqp.rabbit.core.RabbitTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.OrderConvertMessage;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.OrderMqConstants;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.infra.config.BiStatProperties;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.lock.OrderConvertShopLock;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.service.PddOrderConvertService;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Optional;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class PddOrderConvertConsumer {
|
||||
|
||||
private static final ZoneId ZONE = ZoneId.of("Asia/Shanghai");
|
||||
|
||||
private final PddOrderConvertService convertService;
|
||||
private final OrderConvertShopLock convertShopLock;
|
||||
private final BiStatProperties biStatProperties;
|
||||
private final RabbitTemplate rabbitTemplate;
|
||||
|
||||
@RabbitListener(queues = OrderMqConstants.QUEUE_ORDER_CONVERT_PDD)
|
||||
public void onMessage(OrderConvertMessage message) {
|
||||
if (message == null || message.getCompanyId() == null || message.getShopId() == null
|
||||
|| message.getMode() == null) {
|
||||
log.warn("转换消息非法: {}", message);
|
||||
return;
|
||||
}
|
||||
log.info("收到转换消息 mode={} shopId={} statDate={} orders={} messageId={}",
|
||||
message.getMode(), message.getShopId(), message.getStatDate(),
|
||||
message.getOrders() != null ? message.getOrders().size() : 0, message.getMessageId());
|
||||
|
||||
Optional<OrderConvertShopLock.Session> sessionOpt = convertShopLock.tryLock(message.getShopId());
|
||||
if (sessionOpt.isEmpty()) {
|
||||
delayAndRepublish(message);
|
||||
return;
|
||||
}
|
||||
OrderConvertShopLock.Session session = sessionOpt.get();
|
||||
try {
|
||||
convertService.convert(message);
|
||||
} finally {
|
||||
convertShopLock.unlock(session);
|
||||
}
|
||||
}
|
||||
|
||||
private void delayAndRepublish(OrderConvertMessage message) {
|
||||
int retry = message.getRetryCount() == null ? 0 : message.getRetryCount();
|
||||
if (retry >= biStatProperties.getIncMaxRetry()) {
|
||||
throw new IllegalStateException("转换延迟重试超限: " + message.getMessageId());
|
||||
}
|
||||
try {
|
||||
Thread.sleep(Math.max(biStatProperties.getIncDelayMs(), 100));
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IllegalStateException("转换延迟被中断", e);
|
||||
}
|
||||
message.setRetryCount(retry + 1);
|
||||
message.setOccurredAt(OffsetDateTime.now(ZONE));
|
||||
rabbitTemplate.convertAndSend(
|
||||
OrderMqConstants.EXCHANGE, OrderMqConstants.RK_ORDER_CONVERT_PDD, message);
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.lock;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* 转换侧同店串行锁(全量日 / 增量共用一把锁)。
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class OrderConvertShopLock {
|
||||
|
||||
private static final String LOCK_PREFIX = "order:convert:lock:";
|
||||
private static final long LOCK_TTL_SECONDS = 600;
|
||||
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
|
||||
public Optional<Session> tryLock(Long shopId) {
|
||||
String key = LOCK_PREFIX + shopId;
|
||||
String token = UUID.randomUUID().toString();
|
||||
Boolean ok = stringRedisTemplate.opsForValue()
|
||||
.setIfAbsent(key, token, Duration.ofSeconds(LOCK_TTL_SECONDS));
|
||||
if (!Boolean.TRUE.equals(ok)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(new Session(key, token));
|
||||
}
|
||||
|
||||
public boolean isLocked(Long shopId) {
|
||||
return Boolean.TRUE.equals(stringRedisTemplate.hasKey(LOCK_PREFIX + shopId));
|
||||
}
|
||||
|
||||
public void unlock(Session session) {
|
||||
if (session == null) {
|
||||
return;
|
||||
}
|
||||
String current = stringRedisTemplate.opsForValue().get(session.key());
|
||||
if (session.token().equals(current)) {
|
||||
stringRedisTemplate.delete(session.key());
|
||||
}
|
||||
}
|
||||
|
||||
public record Session(String key, String token) {
|
||||
}
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.messaging;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.amqp.rabbit.core.RabbitTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.OrderMqConstants;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiFullCalcMessage;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiIncCalcMessage;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiProductStatDelta;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiSpecStatDelta;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiStatMetricDelta;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.platform.model.enums.PlatformCode;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class PddBiCalcPublisher {
|
||||
|
||||
private static final ZoneId ZONE = ZoneId.of("Asia/Shanghai");
|
||||
|
||||
private final RabbitTemplate rabbitTemplate;
|
||||
|
||||
public void publishFull(Long companyId, Long shopId, LocalDate statDate, String syncBatchId) {
|
||||
BiFullCalcMessage msg = BiFullCalcMessage.builder()
|
||||
.messageId(UUID.randomUUID().toString())
|
||||
.companyId(companyId)
|
||||
.shopId(shopId)
|
||||
.platformCode(PlatformCode.PDD.getCode())
|
||||
.statDate(statDate.toString())
|
||||
.syncBatchId(syncBatchId)
|
||||
.occurredAt(OffsetDateTime.now(ZONE))
|
||||
.build();
|
||||
rabbitTemplate.convertAndSend(OrderMqConstants.EXCHANGE, OrderMqConstants.RK_BI_STAT_FULL, msg);
|
||||
log.info("已投递 BI full shopId={} statDate={}", shopId, statDate);
|
||||
}
|
||||
|
||||
public void publishIncDelta(Long companyId, Long shopId, LocalDate statDate,
|
||||
OffsetDateTime internalOrderUpdateTime, Long orderId, Long channelOrderId,
|
||||
BiStatMetricDelta shopDelta,
|
||||
List<BiProductStatDelta> productDeltas,
|
||||
List<BiSpecStatDelta> specDeltas) {
|
||||
if (shopDelta != null && shopDelta.isAllZero()
|
||||
&& (productDeltas == null || productDeltas.isEmpty())
|
||||
&& (specDeltas == null || specDeltas.isEmpty())) {
|
||||
return;
|
||||
}
|
||||
BiIncCalcMessage msg = BiIncCalcMessage.builder()
|
||||
.messageId(UUID.randomUUID().toString())
|
||||
.companyId(companyId)
|
||||
.shopId(shopId)
|
||||
.platformCode(PlatformCode.PDD.getCode())
|
||||
.statDate(statDate.toString())
|
||||
.internalOrderUpdateTime(internalOrderUpdateTime)
|
||||
.orderId(orderId)
|
||||
.channelOrderId(channelOrderId)
|
||||
.shopDelta(shopDelta)
|
||||
.productDeltas(productDeltas)
|
||||
.specDeltas(specDeltas)
|
||||
.occurredAt(OffsetDateTime.now(ZONE))
|
||||
.retryCount(0)
|
||||
.build();
|
||||
rabbitTemplate.convertAndSend(OrderMqConstants.EXCHANGE, OrderMqConstants.RK_BI_STAT_INC, msg);
|
||||
log.info("已投递 BI inc delta shopId={} statDate={} orderId={}", shopId, statDate, orderId);
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.messaging;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.amqp.rabbit.core.RabbitTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.ChannelOrderRef;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.OrderConvertMessage;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.OrderConvertMode;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.OrderMqConstants;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.platform.model.enums.PlatformCode;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class PddOrderConvertPublisher {
|
||||
|
||||
private static final ZoneId ZONE = ZoneId.of("Asia/Shanghai");
|
||||
|
||||
private final RabbitTemplate rabbitTemplate;
|
||||
|
||||
public void publishFullDay(Long companyId, Long shopId, LocalDate statDate,
|
||||
List<ChannelOrderRef> orders, Long taskId) {
|
||||
OrderConvertMessage msg = OrderConvertMessage.builder()
|
||||
.messageId(UUID.randomUUID().toString())
|
||||
.companyId(companyId)
|
||||
.shopId(shopId)
|
||||
.platform(PlatformCode.PDD.getCode())
|
||||
.mode(OrderConvertMode.FULL_DAY)
|
||||
.statDate(statDate.toString())
|
||||
.orders(orders != null ? orders : List.of())
|
||||
.syncBatchId(taskId != null ? taskId + ":" + statDate : "day:" + shopId + ":" + statDate)
|
||||
.taskId(taskId)
|
||||
.occurredAt(OffsetDateTime.now(ZONE))
|
||||
.retryCount(0)
|
||||
.build();
|
||||
rabbitTemplate.convertAndSend(
|
||||
OrderMqConstants.EXCHANGE, OrderMqConstants.RK_ORDER_CONVERT_PDD, msg);
|
||||
log.info("已投递 FULL_DAY 转换消息 shopId={} statDate={} orders={}",
|
||||
shopId, statDate, orders != null ? orders.size() : 0);
|
||||
}
|
||||
|
||||
public void publishInc(Long companyId, Long shopId, List<ChannelOrderRef> orders) {
|
||||
if (orders == null || orders.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
OrderConvertMessage msg = OrderConvertMessage.builder()
|
||||
.messageId(UUID.randomUUID().toString())
|
||||
.companyId(companyId)
|
||||
.shopId(shopId)
|
||||
.platform(PlatformCode.PDD.getCode())
|
||||
.mode(OrderConvertMode.INC)
|
||||
.orders(orders)
|
||||
.occurredAt(OffsetDateTime.now(ZONE))
|
||||
.retryCount(0)
|
||||
.build();
|
||||
rabbitTemplate.convertAndSend(
|
||||
OrderMqConstants.EXCHANGE, OrderMqConstants.RK_ORDER_CONVERT_PDD, msg);
|
||||
log.info("已投递 INC 转换消息 shopId={} orders={}", shopId, orders.size());
|
||||
}
|
||||
|
||||
public static ChannelOrderRef ref(Long channelOrderId) {
|
||||
if (channelOrderId == null) {
|
||||
return null;
|
||||
}
|
||||
return ChannelOrderRef.builder().channelOrderId(channelOrderId).build();
|
||||
}
|
||||
}
|
||||
+385
@@ -0,0 +1,385 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.TransactionDefinition;
|
||||
import org.springframework.transaction.support.DefaultTransactionDefinition;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import org.springframework.util.StringUtils;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.ChannelOrderRef;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.OrderConvertMessage;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.OrderConvertMode;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiProductStatDelta;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiSpecStatDelta;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiStatMetricDelta;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.support.OrderStatContributionCalculator;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.messaging.PddBiCalcPublisher;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.support.PddOrderStatusMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.mapper.PddOrderItemMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.mapper.PddOrderMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.model.po.PddOrderItemPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.model.po.PddOrderPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.mapper.OrderItemMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.mapper.OrderMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.po.OrderItemPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.po.OrderPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.status.model.enums.OrderStatus;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.status.support.OrderStatusStatResolver;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.status.support.OrderStatusStatSets;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.platform.model.enums.PlatformCode;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductSkuCostPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductSkuPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.service.ProductSkuCostService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.service.ProductSkuService;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class PddOrderConvertService {
|
||||
|
||||
private static final ZoneId ZONE = ZoneId.of("Asia/Shanghai");
|
||||
|
||||
private final PddOrderMapper pddOrderMapper;
|
||||
private final PddOrderItemMapper pddOrderItemMapper;
|
||||
private final OrderMapper orderMapper;
|
||||
private final OrderItemMapper orderItemMapper;
|
||||
private final ProductSkuService productSkuService;
|
||||
private final ProductSkuCostService productSkuCostService;
|
||||
private final PddBiCalcPublisher biCalcPublisher;
|
||||
private final PlatformTransactionManager transactionManager;
|
||||
private final OrderStatContributionCalculator contributionCalculator;
|
||||
private final OrderStatusStatResolver orderStatusStatResolver;
|
||||
|
||||
public void convert(OrderConvertMessage message) {
|
||||
if (message.getMode() == OrderConvertMode.FULL_DAY) {
|
||||
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
|
||||
def.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ);
|
||||
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
|
||||
TransactionTemplate tt = new TransactionTemplate(transactionManager, def);
|
||||
tt.executeWithoutResult(status -> convertFullDay(message));
|
||||
return;
|
||||
}
|
||||
convertInc(message);
|
||||
}
|
||||
|
||||
private void convertFullDay(OrderConvertMessage message) {
|
||||
List<PddOrderPO> channelOrders = loadChannelOrders(message);
|
||||
LocalDateTime mappedAt = LocalDateTime.now(ZONE);
|
||||
for (PddOrderPO channel : channelOrders) {
|
||||
upsertInternalOrder(channel, mappedAt);
|
||||
}
|
||||
LocalDate statDate = message.getStatDate() != null
|
||||
? LocalDate.parse(message.getStatDate())
|
||||
: LocalDate.now(ZONE);
|
||||
biCalcPublisher.publishFull(
|
||||
message.getCompanyId(), message.getShopId(), statDate, message.getSyncBatchId());
|
||||
}
|
||||
|
||||
/**
|
||||
* 增量:消息带渠道镜像主键列表;按 id 查渠道单。
|
||||
* 内部单用 platform_code + source_order_id 定位:无则新增;有则仅当渠道更新时间更新时覆盖,并产出 BI delta。
|
||||
*/
|
||||
private void convertInc(OrderConvertMessage message) {
|
||||
List<ChannelOrderRef> refs = message.getOrders() != null ? message.getOrders() : List.of();
|
||||
if (refs.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
OrderStatusStatSets stat = orderStatusStatResolver.resolve(message.getCompanyId());
|
||||
LocalDateTime mappedAt = LocalDateTime.now(ZONE);
|
||||
|
||||
for (ChannelOrderRef ref : refs) {
|
||||
if (ref == null || ref.getChannelOrderId() == null) {
|
||||
continue;
|
||||
}
|
||||
PddOrderPO channel = pddOrderMapper.selectById(ref.getChannelOrderId());
|
||||
if (channel == null
|
||||
|| !Objects.equals(channel.getCompanyId(), message.getCompanyId())
|
||||
|| !Objects.equals(channel.getShopId(), message.getShopId())) {
|
||||
log.warn("INC 转换跳过:渠道单不存在或不匹配 channelOrderId={}", ref.getChannelOrderId());
|
||||
continue;
|
||||
}
|
||||
|
||||
OrderPO oldOrder = findInternalBySource(channel);
|
||||
if (oldOrder != null && !isChannelNewer(channel, oldOrder)) {
|
||||
log.info("跳过 INC 转换(内部已是最新) channelOrderId={} platformUpdatedAt={}",
|
||||
channel.getId(), oldOrder.getPlatformUpdatedAt());
|
||||
continue;
|
||||
}
|
||||
|
||||
List<OrderItemPO> oldItems = List.of();
|
||||
if (oldOrder != null) {
|
||||
oldItems = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItemPO>()
|
||||
.eq(OrderItemPO::getOrderId, oldOrder.getId()));
|
||||
}
|
||||
OrderStatContributionCalculator.OrderContribution oldContrib =
|
||||
contributionCalculator.contribute(oldOrder, oldItems, stat);
|
||||
|
||||
OrderPO neu = upsertInternalOrder(channel, mappedAt);
|
||||
// 以库中最新 update_time 为准(转换完成时刻),供 BI 与全量快照比较
|
||||
OrderPO refreshed = orderMapper.selectById(neu.getId());
|
||||
LocalDateTime internalUpdated = refreshed != null && refreshed.getUpdateTime() != null
|
||||
? refreshed.getUpdateTime()
|
||||
: (neu.getLastMappedTime() != null ? neu.getLastMappedTime() : mappedAt);
|
||||
List<OrderItemPO> newItems = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItemPO>()
|
||||
.eq(OrderItemPO::getOrderId, neu.getId()));
|
||||
OrderStatContributionCalculator.OrderContribution newContrib =
|
||||
contributionCalculator.contribute(refreshed != null ? refreshed : neu, newItems, stat);
|
||||
|
||||
OffsetDateTime internalOrderUpdateTime = internalUpdated.atZone(ZONE).toOffsetDateTime();
|
||||
emitIncDeltas(message, channel.getId(), neu.getId(), internalOrderUpdateTime, oldContrib, newContrib);
|
||||
}
|
||||
}
|
||||
|
||||
private OrderPO findInternalBySource(PddOrderPO channel) {
|
||||
return orderMapper.selectOne(new LambdaQueryWrapper<OrderPO>()
|
||||
.eq(OrderPO::getCompanyId, channel.getCompanyId())
|
||||
.eq(OrderPO::getPlatformCode, PlatformCode.PDD.getCode())
|
||||
.eq(OrderPO::getSourceOrderId, channel.getId())
|
||||
.last("LIMIT 1"));
|
||||
}
|
||||
|
||||
/** 渠道更新时间严格晚于内部已记录的平台更新时间,或内部尚未记录时,视为需要转换。 */
|
||||
private static boolean isChannelNewer(PddOrderPO channel, OrderPO internal) {
|
||||
if (internal.getPlatformUpdatedAt() == null) {
|
||||
return true;
|
||||
}
|
||||
if (channel.getPddUpdatedAt() == null) {
|
||||
return true;
|
||||
}
|
||||
return channel.getPddUpdatedAt().isAfter(internal.getPlatformUpdatedAt());
|
||||
}
|
||||
|
||||
private void emitIncDeltas(OrderConvertMessage message, Long channelOrderId, Long orderId,
|
||||
OffsetDateTime internalOrderUpdateTime,
|
||||
OrderStatContributionCalculator.OrderContribution oldC,
|
||||
OrderStatContributionCalculator.OrderContribution newC) {
|
||||
Map<LocalDate, BiStatMetricDelta> shopByDate = new HashMap<>();
|
||||
Map<LocalDate, Map<String, BiProductStatDelta>> prodByDate = new HashMap<>();
|
||||
Map<LocalDate, Map<String, BiSpecStatDelta>> specByDate = new HashMap<>();
|
||||
|
||||
applyContrib(shopByDate, prodByDate, specByDate, oldC, true);
|
||||
applyContrib(shopByDate, prodByDate, specByDate, newC, false);
|
||||
|
||||
for (LocalDate date : shopByDate.keySet()) {
|
||||
BiStatMetricDelta shopDelta = shopByDate.getOrDefault(date, BiStatMetricDelta.zeros());
|
||||
List<BiProductStatDelta> products = new ArrayList<>(
|
||||
prodByDate.getOrDefault(date, Map.of()).values());
|
||||
products.removeIf(p -> p.getMetrics() == null || p.getMetrics().isAllZero());
|
||||
List<BiSpecStatDelta> specs = new ArrayList<>(
|
||||
specByDate.getOrDefault(date, Map.of()).values());
|
||||
specs.removeIf(s -> s.getMetrics() == null || s.getMetrics().isAllZero());
|
||||
biCalcPublisher.publishIncDelta(
|
||||
message.getCompanyId(), message.getShopId(), date, internalOrderUpdateTime,
|
||||
orderId, channelOrderId, shopDelta, products, specs);
|
||||
}
|
||||
}
|
||||
|
||||
private void applyContrib(Map<LocalDate, BiStatMetricDelta> shopByDate,
|
||||
Map<LocalDate, Map<String, BiProductStatDelta>> prodByDate,
|
||||
Map<LocalDate, Map<String, BiSpecStatDelta>> specByDate,
|
||||
OrderStatContributionCalculator.OrderContribution c,
|
||||
boolean subtract) {
|
||||
if (c == null || c.getStatDate() == null) {
|
||||
return;
|
||||
}
|
||||
LocalDate d = c.getStatDate();
|
||||
BiStatMetricDelta shop = c.getShop() != null ? c.getShop() : BiStatMetricDelta.zeros();
|
||||
shopByDate.merge(d, subtract ? shop.negate() : shop, BiStatMetricDelta::plus);
|
||||
|
||||
Map<String, BiProductStatDelta> pm = prodByDate.computeIfAbsent(d, k -> new HashMap<>());
|
||||
if (c.getProducts() != null) {
|
||||
for (BiProductStatDelta p : c.getProducts()) {
|
||||
String key = p.getProductId() + ":" + p.getCategoryId();
|
||||
BiStatMetricDelta m = p.getMetrics() != null ? p.getMetrics() : BiStatMetricDelta.zeros();
|
||||
BiStatMetricDelta delta = subtract ? m.negate() : m;
|
||||
pm.merge(key, BiProductStatDelta.builder()
|
||||
.productId(p.getProductId())
|
||||
.categoryId(p.getCategoryId())
|
||||
.metrics(delta)
|
||||
.build(),
|
||||
(a, b) -> BiProductStatDelta.builder()
|
||||
.productId(a.getProductId())
|
||||
.categoryId(a.getCategoryId())
|
||||
.metrics(a.getMetrics().plus(b.getMetrics()))
|
||||
.build());
|
||||
}
|
||||
}
|
||||
Map<String, BiSpecStatDelta> sm = specByDate.computeIfAbsent(d, k -> new HashMap<>());
|
||||
if (c.getSpecs() != null) {
|
||||
for (BiSpecStatDelta s : c.getSpecs()) {
|
||||
String key = String.valueOf(s.getProductSpecId());
|
||||
BiStatMetricDelta m = s.getMetrics() != null ? s.getMetrics() : BiStatMetricDelta.zeros();
|
||||
BiStatMetricDelta delta = subtract ? m.negate() : m;
|
||||
sm.merge(key, BiSpecStatDelta.builder()
|
||||
.productId(s.getProductId())
|
||||
.productSpecId(s.getProductSpecId())
|
||||
.metrics(delta)
|
||||
.build(),
|
||||
(a, b) -> BiSpecStatDelta.builder()
|
||||
.productId(a.getProductId())
|
||||
.productSpecId(a.getProductSpecId())
|
||||
.metrics(a.getMetrics().plus(b.getMetrics()))
|
||||
.build());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private List<PddOrderPO> loadChannelOrders(OrderConvertMessage message) {
|
||||
if (message.getOrders() != null && !message.getOrders().isEmpty()) {
|
||||
List<Long> ids = message.getOrders().stream()
|
||||
.filter(Objects::nonNull)
|
||||
.map(ChannelOrderRef::getChannelOrderId)
|
||||
.filter(Objects::nonNull)
|
||||
.distinct()
|
||||
.collect(Collectors.toList());
|
||||
if (!ids.isEmpty()) {
|
||||
return pddOrderMapper.selectBatchIds(ids).stream()
|
||||
.filter(o -> Objects.equals(o.getCompanyId(), message.getCompanyId())
|
||||
&& Objects.equals(o.getShopId(), message.getShopId()))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
}
|
||||
if (message.getMode() == OrderConvertMode.FULL_DAY && message.getStatDate() != null) {
|
||||
LocalDate day = LocalDate.parse(message.getStatDate());
|
||||
LocalDateTime start = day.atStartOfDay();
|
||||
LocalDateTime end = day.plusDays(1).atStartOfDay();
|
||||
return pddOrderMapper.selectList(new LambdaQueryWrapper<PddOrderPO>()
|
||||
.eq(PddOrderPO::getCompanyId, message.getCompanyId())
|
||||
.eq(PddOrderPO::getShopId, message.getShopId())
|
||||
.and(w -> w
|
||||
.nested(n -> n.isNotNull(PddOrderPO::getConfirmTime)
|
||||
.ge(PddOrderPO::getConfirmTime, start)
|
||||
.lt(PddOrderPO::getConfirmTime, end))
|
||||
.or(n -> n.isNull(PddOrderPO::getConfirmTime)
|
||||
.ge(PddOrderPO::getCreatedTime, start)
|
||||
.lt(PddOrderPO::getCreatedTime, end))));
|
||||
}
|
||||
return List.of();
|
||||
}
|
||||
|
||||
private OrderPO upsertInternalOrder(PddOrderPO channel, LocalDateTime mappedAt) {
|
||||
OrderPO existing = findInternalBySource(channel);
|
||||
if (existing == null) {
|
||||
// 兼容:早期仅按平台单号落库、尚未写 source_order_id 的行
|
||||
existing = orderMapper.selectOne(new LambdaQueryWrapper<OrderPO>()
|
||||
.eq(OrderPO::getCompanyId, channel.getCompanyId())
|
||||
.eq(OrderPO::getShopId, channel.getShopId())
|
||||
.eq(OrderPO::getPlatformOrderNo, channel.getOrderSn())
|
||||
.last("LIMIT 1"));
|
||||
}
|
||||
|
||||
OrderPO order = existing != null ? existing : new OrderPO();
|
||||
order.setCompanyId(channel.getCompanyId());
|
||||
order.setShopId(channel.getShopId());
|
||||
order.setPlatformCode(PlatformCode.PDD.getCode());
|
||||
OrderStatus status = PddOrderStatusMapper.map(channel.getOrderStatus(), channel.getRefundStatus());
|
||||
order.setStatus(status.getCode());
|
||||
order.setPlatformOrderNo(channel.getOrderSn());
|
||||
order.setSource("sync");
|
||||
order.setSourceOrderId(channel.getId());
|
||||
order.setPayAmount(channel.getPayAmount());
|
||||
order.setGoodsAmount(channel.getGoodsAmount());
|
||||
order.setDiscountAmount(channel.getDiscountAmount());
|
||||
order.setPostage(channel.getPostage());
|
||||
order.setPlatformDiscount(channel.getPlatformDiscount());
|
||||
order.setSellerDiscount(channel.getSellerDiscount());
|
||||
order.setLogisticsId(channel.getLogisticsId() != null ? String.valueOf(channel.getLogisticsId()) : null);
|
||||
order.setTrackingNumber(channel.getTrackingNumber());
|
||||
order.setOrderTime(channel.getCreatedTime());
|
||||
order.setPayTime(channel.getPayTime());
|
||||
order.setConfirmTime(channel.getConfirmTime());
|
||||
order.setShippingTime(channel.getShippingTime());
|
||||
order.setReceiveTime(channel.getReceiveTime());
|
||||
order.setProvince(channel.getProvince());
|
||||
order.setCity(channel.getCity());
|
||||
order.setTown(channel.getTown());
|
||||
order.setReceiverNameMask(channel.getReceiverNameMask());
|
||||
order.setReceiverPhoneMask(channel.getReceiverPhoneMask());
|
||||
order.setReceiverAddressMask(channel.getReceiverAddressMask());
|
||||
order.setBuyerMemo(channel.getBuyerMemo());
|
||||
order.setRemark(channel.getRemark());
|
||||
order.setConfirm(1);
|
||||
order.setPlatformUpdatedAt(channel.getPddUpdatedAt());
|
||||
order.setLastMappedTime(mappedAt);
|
||||
|
||||
if (existing == null) {
|
||||
orderMapper.insert(order);
|
||||
} else {
|
||||
orderMapper.updateById(order);
|
||||
orderItemMapper.delete(new LambdaQueryWrapper<OrderItemPO>()
|
||||
.eq(OrderItemPO::getOrderId, order.getId()));
|
||||
}
|
||||
|
||||
List<PddOrderItemPO> channelItems = pddOrderItemMapper.selectList(new LambdaQueryWrapper<PddOrderItemPO>()
|
||||
.eq(PddOrderItemPO::getOrderId, channel.getId()));
|
||||
int lineNo = 1;
|
||||
for (PddOrderItemPO ci : channelItems) {
|
||||
orderItemMapper.insert(mapItem(order, ci, lineNo++));
|
||||
}
|
||||
return order;
|
||||
}
|
||||
|
||||
private OrderItemPO mapItem(OrderPO order, PddOrderItemPO ci, int lineNo) {
|
||||
OrderItemPO item = new OrderItemPO();
|
||||
item.setOrderId(order.getId());
|
||||
item.setCompanyId(order.getCompanyId());
|
||||
item.setShopId(order.getShopId());
|
||||
item.setLineNo(lineNo);
|
||||
item.setPlatformGoodsId(ci.getGoodsId());
|
||||
item.setPlatformSkuId(ci.getSkuId());
|
||||
item.setLinkProductName(ci.getGoodsName());
|
||||
item.setLinkSkuName(ci.getGoodsSpec());
|
||||
item.setGoodsImg(ci.getGoodsImg());
|
||||
item.setQuantity(ci.getGoodsCount() != null && ci.getGoodsCount() > 0 ? ci.getGoodsCount() : 1);
|
||||
item.setUnitPrice(ci.getGoodsPrice());
|
||||
if (ci.getGoodsPrice() != null && item.getQuantity() != null) {
|
||||
item.setLineAmount(ci.getGoodsPrice().multiply(BigDecimal.valueOf(item.getQuantity())));
|
||||
}
|
||||
|
||||
Long productId = 0L;
|
||||
Long skuId = 0L;
|
||||
String skuCode = null;
|
||||
if (StringUtils.hasText(ci.getOuterId())) {
|
||||
ProductSkuPO sku = productSkuService.getByCompanyIdAndSkuCode(order.getCompanyId(), ci.getOuterId().trim());
|
||||
if (sku != null) {
|
||||
productId = sku.getProductId() != null ? sku.getProductId() : 0L;
|
||||
skuId = sku.getId();
|
||||
skuCode = sku.getSkuCode();
|
||||
ProductSkuCostPO cost = productSkuCostService.getCurrentCost(sku.getId());
|
||||
if (cost != null) {
|
||||
item.setProductCost(cost.getProductCost());
|
||||
item.setShippingCost(cost.getShippingCost());
|
||||
item.setOtherCost(cost.getOtherCost());
|
||||
}
|
||||
}
|
||||
}
|
||||
item.setProductId(productId);
|
||||
item.setProductSkuId(skuId);
|
||||
item.setSkuCode(skuCode != null ? skuCode : ci.getOuterId());
|
||||
if (item.getProductCost() == null) {
|
||||
item.setProductCost(BigDecimal.ZERO);
|
||||
}
|
||||
if (item.getShippingCost() == null) {
|
||||
item.setShippingCost(BigDecimal.ZERO);
|
||||
}
|
||||
if (item.getOtherCost() == null) {
|
||||
item.setOtherCost(BigDecimal.ZERO);
|
||||
}
|
||||
return item;
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.support;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.status.model.enums.OrderStatus;
|
||||
|
||||
/**
|
||||
* 拼多多订单/售后状态 → 内部 {@link OrderStatus}。
|
||||
* <p>
|
||||
* order_status: 1 待发货, 2 已发货待签收, 3 已签收<br>
|
||||
* refund_status: 1 无售后或关闭, 2 售后处理中, 3 退款中, 4 退款成功
|
||||
*/
|
||||
public final class PddOrderStatusMapper {
|
||||
|
||||
private PddOrderStatusMapper() {
|
||||
}
|
||||
|
||||
public static OrderStatus map(Integer orderStatus, Integer refundStatus) {
|
||||
if (refundStatus != null) {
|
||||
if (refundStatus == 4) {
|
||||
return OrderStatus.REFUNDED;
|
||||
}
|
||||
if (refundStatus == 2 || refundStatus == 3) {
|
||||
return OrderStatus.REFUNDING;
|
||||
}
|
||||
}
|
||||
if (orderStatus == null) {
|
||||
return OrderStatus.UNKNOWN;
|
||||
}
|
||||
return switch (orderStatus) {
|
||||
case 1 -> OrderStatus.PENDING_SHIPMENT;
|
||||
case 2 -> OrderStatus.SHIPPED;
|
||||
case 3 -> OrderStatus.COMPLETED;
|
||||
default -> OrderStatus.UNKNOWN;
|
||||
};
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.consumer;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.amqp.rabbit.annotation.RabbitListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.OrderMqConstants;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.messaging.PddSyncFullMessage;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.service.PddOrderFullSyncTaskExecutor;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class PddOrderSyncFullConsumer {
|
||||
|
||||
private final PddOrderFullSyncTaskExecutor fullSyncTaskExecutor;
|
||||
|
||||
@RabbitListener(queues = OrderMqConstants.QUEUE_ORDER_SYNC_PDD_FULL)
|
||||
public void onMessage(PddSyncFullMessage message) {
|
||||
if (message == null || message.getCompanyId() == null || message.getShopId() == null
|
||||
|| message.getDateFrom() == null || message.getDateTo() == null) {
|
||||
log.warn("全量同步消息非法: {}", message);
|
||||
return;
|
||||
}
|
||||
log.info("收到全量同步消息 taskId={} shopId={} {}~{}",
|
||||
message.getTaskId(), message.getShopId(), message.getDateFrom(), message.getDateTo());
|
||||
fullSyncTaskExecutor.execute(message);
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.consumer;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.amqp.rabbit.annotation.RabbitListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.OrderMqConstants;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.messaging.PddSyncIncMessage;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.service.PddOrderSyncService;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class PddOrderSyncIncConsumer {
|
||||
|
||||
private final PddOrderSyncService pddOrderSyncService;
|
||||
|
||||
@RabbitListener(queues = OrderMqConstants.QUEUE_ORDER_SYNC_PDD_INC)
|
||||
public void onMessage(PddSyncIncMessage message) {
|
||||
if (message == null || message.getCompanyId() == null || message.getShopId() == null) {
|
||||
log.warn("增量同步消息非法: {}", message);
|
||||
return;
|
||||
}
|
||||
log.info("收到增量同步消息 shopId={} messageId={}", message.getShopId(), message.getMessageId());
|
||||
pddOrderSyncService.syncIncrementalInternal(message.getCompanyId(), message.getShopId());
|
||||
}
|
||||
}
|
||||
+86
-10
@@ -8,56 +8,132 @@ import org.springframework.format.annotation.DateTimeFormat;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.messaging.PddOrderSyncPublisher;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.PddOrderSyncShopContext;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.dto.PddOrderFullSyncTaskCreateDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.dto.PddOrderIncrementalToggleDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.dto.PddOrderRepairDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.dto.PddOrderSyncDayDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.vo.PddOrderFullSyncTaskVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.vo.PddOrderIncrementalStatusVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.vo.PddOrderSyncResultVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.service.PddOrderFullSyncTaskService;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.service.PddOrderSyncContextResolver;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.service.PddOrderSyncService;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 拼多多订单同步(手动触发)。落库仅 channel_pdd_*,不写内部 ec_order。
|
||||
* 拼多多订单同步:执行类接口入队;补单仍同步执行。
|
||||
*/
|
||||
@Tag(name = "拼多多-订单同步", description = "按天回补 / 增量 / 补单")
|
||||
@Tag(name = "拼多多-订单同步", description = "按天回补 / 增量 / 补单 / 全量任务 / 增量开关")
|
||||
@RestController
|
||||
@RequestMapping("/api/channel/pdd/order/sync")
|
||||
public class PddOrderSyncController {
|
||||
|
||||
private final PddOrderSyncService pddOrderSyncService;
|
||||
private final PddOrderFullSyncTaskService fullSyncTaskService;
|
||||
private final PddOrderSyncPublisher syncPublisher;
|
||||
private final PddOrderSyncContextResolver contextResolver;
|
||||
|
||||
public PddOrderSyncController(PddOrderSyncService pddOrderSyncService) {
|
||||
public PddOrderSyncController(PddOrderSyncService pddOrderSyncService,
|
||||
PddOrderFullSyncTaskService fullSyncTaskService,
|
||||
PddOrderSyncPublisher syncPublisher,
|
||||
PddOrderSyncContextResolver contextResolver) {
|
||||
this.pddOrderSyncService = pddOrderSyncService;
|
||||
this.fullSyncTaskService = fullSyncTaskService;
|
||||
this.syncPublisher = syncPublisher;
|
||||
this.contextResolver = contextResolver;
|
||||
}
|
||||
|
||||
@Operation(summary = "按成交日同步一天", description = "调用 pdd.order.list.get,按 confirm_time 拉取指定自然日订单并 upsert")
|
||||
@Operation(summary = "按成交日同步一天(入队)")
|
||||
@PostMapping("/day")
|
||||
@RequirePermission(value = "biz:pdd:order:sync", description = "拼多多订单同步", allowSuper = true)
|
||||
public ApiResponse<PddOrderSyncResultVO> syncDay(@Valid @RequestBody PddOrderSyncDayDTO dto) {
|
||||
return ApiResponse.success("同步完成", pddOrderSyncService.syncByConfirmDate(dto));
|
||||
PddOrderSyncShopContext ctx = contextResolver.resolveForCurrentCompany(dto.getShopId());
|
||||
syncPublisher.publishFullRange(ctx.getCompanyId(), ctx.getShopId(), dto.getConfirmDate(), dto.getConfirmDate());
|
||||
return ApiResponse.success("已入队", PddOrderSyncResultVO.builder()
|
||||
.mode("day")
|
||||
.shopId(dto.getShopId())
|
||||
.fetchedCount(0)
|
||||
.upsertedCount(0)
|
||||
.skippedCount(0)
|
||||
.errors(List.of())
|
||||
.build());
|
||||
}
|
||||
|
||||
@Operation(summary = "按成交日范围回补", description = "多天回补,内部按天切窗")
|
||||
@Operation(summary = "按成交日范围回补(入队)")
|
||||
@PostMapping("/bootstrap")
|
||||
@RequirePermission(value = "biz:pdd:order:sync", description = "拼多多订单同步", allowSuper = true)
|
||||
public ApiResponse<PddOrderSyncResultVO> bootstrap(
|
||||
@Parameter(description = "内部店铺 ID") @RequestParam Long shopId,
|
||||
@Parameter(description = "开始日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
|
||||
@Parameter(description = "结束日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
|
||||
return ApiResponse.success("回补完成", pddOrderSyncService.bootstrapByConfirmRange(shopId, startDate, endDate));
|
||||
PddOrderSyncShopContext ctx = contextResolver.resolveForCurrentCompany(shopId);
|
||||
syncPublisher.publishFullRange(ctx.getCompanyId(), ctx.getShopId(), startDate, endDate);
|
||||
return ApiResponse.success("已入队", PddOrderSyncResultVO.builder()
|
||||
.mode("bootstrap")
|
||||
.shopId(shopId)
|
||||
.fetchedCount(0)
|
||||
.upsertedCount(0)
|
||||
.skippedCount(0)
|
||||
.errors(List.of())
|
||||
.build());
|
||||
}
|
||||
|
||||
@Operation(summary = "增量同步", description = "调用 pdd.order.number.list.increment.get,按 updated_at 推进游标")
|
||||
@Operation(summary = "增量同步(入队)")
|
||||
@PostMapping("/incremental")
|
||||
@RequirePermission(value = "biz:pdd:order:sync", description = "拼多多订单同步", allowSuper = true)
|
||||
public ApiResponse<PddOrderSyncResultVO> incremental(
|
||||
@Parameter(description = "内部店铺 ID") @RequestParam Long shopId) {
|
||||
return ApiResponse.success("增量同步完成", pddOrderSyncService.syncIncremental(shopId));
|
||||
PddOrderSyncShopContext ctx = contextResolver.resolveForCurrentCompany(shopId);
|
||||
syncPublisher.publishInc(ctx.getCompanyId(), ctx.getShopId());
|
||||
return ApiResponse.success("已入队", PddOrderSyncResultVO.builder()
|
||||
.mode("incremental")
|
||||
.shopId(shopId)
|
||||
.fetchedCount(0)
|
||||
.upsertedCount(0)
|
||||
.skippedCount(0)
|
||||
.errors(List.of())
|
||||
.build());
|
||||
}
|
||||
|
||||
@Operation(summary = "按订单号补拉", description = "调用 pdd.order.information.get")
|
||||
@Operation(summary = "按订单号补拉", description = "同步执行;完成后投递 INC 转换")
|
||||
@PostMapping("/repair")
|
||||
@RequirePermission(value = "biz:pdd:order:sync", description = "拼多多订单同步", allowSuper = true)
|
||||
public ApiResponse<PddOrderSyncResultVO> repair(@Valid @RequestBody PddOrderRepairDTO dto) {
|
||||
return ApiResponse.success("补单完成", pddOrderSyncService.repair(dto));
|
||||
}
|
||||
|
||||
@Operation(summary = "创建全量同步任务", description = "写任务表并入全量同步队列")
|
||||
@PostMapping("/full-task")
|
||||
@RequirePermission(value = "biz:pdd:order:sync", description = "拼多多订单同步", allowSuper = true)
|
||||
public ApiResponse<PddOrderFullSyncTaskVO> createFullTask(
|
||||
@Valid @RequestBody PddOrderFullSyncTaskCreateDTO dto) {
|
||||
return ApiResponse.success("任务已入队", fullSyncTaskService.createTask(dto));
|
||||
}
|
||||
|
||||
@Operation(summary = "查询全量同步任务")
|
||||
@GetMapping("/full-task/{taskId}")
|
||||
@RequirePermission(value = "biz:pdd:order:sync", description = "拼多多订单同步", allowSuper = true)
|
||||
public ApiResponse<PddOrderFullSyncTaskVO> getFullTask(@PathVariable Long taskId) {
|
||||
return ApiResponse.success(fullSyncTaskService.getTask(taskId));
|
||||
}
|
||||
|
||||
@Operation(summary = "增量同步开关")
|
||||
@PostMapping("/incremental/toggle")
|
||||
@RequirePermission(value = "biz:pdd:order:sync", description = "拼多多订单同步", allowSuper = true)
|
||||
public ApiResponse<PddOrderIncrementalStatusVO> toggleIncremental(
|
||||
@Valid @RequestBody PddOrderIncrementalToggleDTO dto) {
|
||||
return ApiResponse.success(fullSyncTaskService.toggleIncremental(dto));
|
||||
}
|
||||
|
||||
@Operation(summary = "查询增量同步开关状态")
|
||||
@GetMapping("/incremental/status")
|
||||
@RequirePermission(value = "biz:pdd:order:sync", description = "拼多多订单同步", allowSuper = true)
|
||||
public ApiResponse<PddOrderIncrementalStatusVO> incrementalStatus(
|
||||
@Parameter(description = "内部店铺 ID") @RequestParam Long shopId) {
|
||||
return ApiResponse.success(fullSyncTaskService.incrementalStatus(shopId));
|
||||
}
|
||||
}
|
||||
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.hook;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.ChannelOrderRef;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.messaging.PddOrderConvertPublisher;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 仅补单路径投递 INC 转换;日常增量已在 sync 按页投递。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class PddOrderConvertAfterSyncListener implements PddOrderAfterSyncListener {
|
||||
|
||||
private final PddOrderConvertPublisher convertPublisher;
|
||||
|
||||
@Override
|
||||
public void onOrdersUpserted(Long companyId, Long shopId, List<Long> pddOrderIds, String syncMode) {
|
||||
if (pddOrderIds == null || pddOrderIds.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
if (!"repair".equals(syncMode)) {
|
||||
return;
|
||||
}
|
||||
List<ChannelOrderRef> refs = new ArrayList<>();
|
||||
for (Long id : pddOrderIds) {
|
||||
ChannelOrderRef ref = PddOrderConvertPublisher.ref(id);
|
||||
if (ref != null) {
|
||||
refs.add(ref);
|
||||
}
|
||||
}
|
||||
convertPublisher.publishInc(companyId, shopId, refs);
|
||||
}
|
||||
}
|
||||
+13
-22
@@ -5,10 +5,8 @@ import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.mapper.PddOrderSyncCursorMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.po.PddOrderSyncCursorPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.service.PddOrderSyncService;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.messaging.PddOrderSyncPublisher;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.service.PddOrderFullSyncTaskService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.platform.model.enums.PlatformCode;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.mapper.ShopMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
|
||||
@@ -18,7 +16,7 @@ import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 定时增量同步已绑定外部店的拼多多店铺;跳过增量游标 status=2(出错暂停)。
|
||||
* 定时将开启增量开关的店铺投入增量同步队列(与全量队列可并行)。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@@ -26,21 +24,22 @@ import java.util.Set;
|
||||
public class PddOrderIncrementalSyncJob {
|
||||
|
||||
private final ShopMapper shopMapper;
|
||||
private final PddOrderSyncCursorMapper cursorMapper;
|
||||
private final PddOrderSyncService pddOrderSyncService;
|
||||
private final PddOrderFullSyncTaskService fullSyncTaskService;
|
||||
private final PddOrderSyncPublisher syncPublisher;
|
||||
|
||||
public PddOrderIncrementalSyncJob(ShopMapper shopMapper,
|
||||
PddOrderSyncCursorMapper cursorMapper,
|
||||
PddOrderSyncService pddOrderSyncService) {
|
||||
PddOrderFullSyncTaskService fullSyncTaskService,
|
||||
PddOrderSyncPublisher syncPublisher) {
|
||||
this.shopMapper = shopMapper;
|
||||
this.cursorMapper = cursorMapper;
|
||||
this.pddOrderSyncService = pddOrderSyncService;
|
||||
this.fullSyncTaskService = fullSyncTaskService;
|
||||
this.syncPublisher = syncPublisher;
|
||||
}
|
||||
|
||||
@Scheduled(cron = "${pdd.order-sync.incremental-cron:0 */5 * * * ?}")
|
||||
public void run() {
|
||||
List<ShopPO> shops = shopMapper.selectList(new LambdaQueryWrapper<ShopPO>()
|
||||
.eq(ShopPO::getPlatformCode, PlatformCode.PDD.getCode())
|
||||
.eq(ShopPO::getOrderIncSyncEnabled, 1)
|
||||
.isNotNull(ShopPO::getExternalShopId)
|
||||
.ne(ShopPO::getExternalShopId, ""));
|
||||
Set<Long> done = new HashSet<>();
|
||||
@@ -48,23 +47,15 @@ public class PddOrderIncrementalSyncJob {
|
||||
if (!done.add(shop.getId())) {
|
||||
continue;
|
||||
}
|
||||
if (isIncrementalPaused(shop.getId())) {
|
||||
if (fullSyncTaskService.isIncrementalPaused(shop.getId())) {
|
||||
log.debug("跳过出错暂停的增量店铺 shopId={}", shop.getId());
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
pddOrderSyncService.syncIncrementalInternal(shop.getCompanyId(), shop.getId());
|
||||
syncPublisher.publishInc(shop.getCompanyId(), shop.getId());
|
||||
} catch (Exception e) {
|
||||
log.warn("定时增量同步失败 shopId={}: {}", shop.getId(), e.getMessage());
|
||||
log.warn("投递增量同步失败 shopId={}: {}", shop.getId(), e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isIncrementalPaused(Long shopId) {
|
||||
PddOrderSyncCursorPO cursor = cursorMapper.selectOne(new LambdaQueryWrapper<PddOrderSyncCursorPO>()
|
||||
.eq(PddOrderSyncCursorPO::getShopId, shopId)
|
||||
.eq(PddOrderSyncCursorPO::getSyncType, PddOrderSyncCursorPO.TYPE_INCREMENTAL)
|
||||
.last("LIMIT 1"));
|
||||
return cursor != null && Integer.valueOf(2).equals(cursor.getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.po.PddOrderFullSyncTaskPO;
|
||||
|
||||
@Mapper
|
||||
public interface PddOrderFullSyncTaskMapper extends BaseMapper<PddOrderFullSyncTaskPO> {
|
||||
}
|
||||
+2
-4
@@ -1,11 +1,9 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.po.PddOrderSyncCursorPO;
|
||||
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.po.PddOrderIncSyncPO;
|
||||
|
||||
@Mapper
|
||||
public interface PddOrderSyncCursorMapper extends BaseMapper<PddOrderSyncCursorPO> {
|
||||
public interface PddOrderIncSyncMapper extends BaseMapper<PddOrderIncSyncPO> {
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.messaging;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.amqp.rabbit.core.RabbitTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.OrderMqConstants;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.UUID;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class PddOrderSyncPublisher {
|
||||
|
||||
private static final ZoneId ZONE = ZoneId.of("Asia/Shanghai");
|
||||
|
||||
private final RabbitTemplate rabbitTemplate;
|
||||
|
||||
public void publishFullTask(Long taskId, Long companyId, Long shopId,
|
||||
LocalDate dateFrom, LocalDate dateTo) {
|
||||
PddSyncFullMessage msg = PddSyncFullMessage.builder()
|
||||
.messageId(UUID.randomUUID().toString())
|
||||
.taskId(taskId)
|
||||
.companyId(companyId)
|
||||
.shopId(shopId)
|
||||
.dateFrom(dateFrom)
|
||||
.dateTo(dateTo)
|
||||
.occurredAt(OffsetDateTime.now(ZONE))
|
||||
.retryCount(0)
|
||||
.build();
|
||||
rabbitTemplate.convertAndSend(
|
||||
OrderMqConstants.EXCHANGE, OrderMqConstants.RK_ORDER_SYNC_PDD_FULL, msg);
|
||||
log.info("已投递全量同步任务消息 taskId={} shopId={} {}~{}",
|
||||
taskId, shopId, dateFrom, dateTo);
|
||||
}
|
||||
|
||||
public void publishFullRange(Long companyId, Long shopId, LocalDate dateFrom, LocalDate dateTo) {
|
||||
PddSyncFullMessage msg = PddSyncFullMessage.builder()
|
||||
.messageId(UUID.randomUUID().toString())
|
||||
.companyId(companyId)
|
||||
.shopId(shopId)
|
||||
.dateFrom(dateFrom)
|
||||
.dateTo(dateTo)
|
||||
.occurredAt(OffsetDateTime.now(ZONE))
|
||||
.retryCount(0)
|
||||
.build();
|
||||
rabbitTemplate.convertAndSend(
|
||||
OrderMqConstants.EXCHANGE, OrderMqConstants.RK_ORDER_SYNC_PDD_FULL, msg);
|
||||
log.info("已投递全量同步区间消息 shopId={} {}~{}", shopId, dateFrom, dateTo);
|
||||
}
|
||||
|
||||
public void publishInc(Long companyId, Long shopId) {
|
||||
PddSyncIncMessage msg = PddSyncIncMessage.builder()
|
||||
.messageId(UUID.randomUUID().toString())
|
||||
.companyId(companyId)
|
||||
.shopId(shopId)
|
||||
.occurredAt(OffsetDateTime.now(ZONE))
|
||||
.retryCount(0)
|
||||
.build();
|
||||
rabbitTemplate.convertAndSend(
|
||||
OrderMqConstants.EXCHANGE, OrderMqConstants.RK_ORDER_SYNC_PDD_INC, msg);
|
||||
log.info("已投递增量同步消息 shopId={}", shopId);
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.messaging;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.OffsetDateTime;
|
||||
|
||||
/**
|
||||
* 全量同步入队:有 taskId 则按任务表推进;否则按 dateFrom~dateTo 直接拉。
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class PddSyncFullMessage {
|
||||
|
||||
private String messageId;
|
||||
/** 可空:手动按日/区间且不落任务表时为空 */
|
||||
private Long taskId;
|
||||
private Long companyId;
|
||||
private Long shopId;
|
||||
private LocalDate dateFrom;
|
||||
private LocalDate dateTo;
|
||||
private OffsetDateTime occurredAt;
|
||||
private Integer retryCount;
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.messaging;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class PddSyncIncMessage {
|
||||
|
||||
private String messageId;
|
||||
private Long companyId;
|
||||
private Long shopId;
|
||||
private OffsetDateTime occurredAt;
|
||||
private Integer retryCount;
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
@Data
|
||||
public class PddOrderFullSyncTaskCreateDTO {
|
||||
|
||||
@NotNull
|
||||
private Long shopId;
|
||||
|
||||
@NotNull
|
||||
private LocalDate dateFrom;
|
||||
|
||||
@NotNull
|
||||
private LocalDate dateTo;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class PddOrderIncrementalToggleDTO {
|
||||
|
||||
@NotNull
|
||||
private Long shopId;
|
||||
|
||||
@NotNull
|
||||
private Boolean enabled;
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.*;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@TableName("channel_pdd_order_full_sync_task")
|
||||
public class PddOrderFullSyncTaskPO {
|
||||
|
||||
public static final String STATUS_PENDING = "PENDING";
|
||||
public static final String STATUS_RUNNING = "RUNNING";
|
||||
public static final String STATUS_SUCCESS = "SUCCESS";
|
||||
public static final String STATUS_FAILED = "FAILED";
|
||||
public static final String STATUS_CANCELLED = "CANCELLED";
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@TableField("company_id")
|
||||
private Long companyId;
|
||||
|
||||
@TableField("shop_id")
|
||||
private Long shopId;
|
||||
|
||||
@TableField("platform_code")
|
||||
private String platformCode;
|
||||
|
||||
@TableField("date_from")
|
||||
private LocalDate dateFrom;
|
||||
|
||||
@TableField("date_to")
|
||||
private LocalDate dateTo;
|
||||
|
||||
@TableField("current_date")
|
||||
private LocalDate currentDate;
|
||||
|
||||
@TableField("total_days")
|
||||
private Integer totalDays;
|
||||
|
||||
@TableField("done_days")
|
||||
private Integer doneDays;
|
||||
|
||||
@TableField("failed_days")
|
||||
private Integer failedDays;
|
||||
|
||||
@TableField("status")
|
||||
private String status;
|
||||
|
||||
@TableField("last_error")
|
||||
private String lastError;
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
|
||||
@TableField("finish_time")
|
||||
private LocalDateTime finishTime;
|
||||
}
|
||||
+11
-11
@@ -1,16 +1,20 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.*;
|
||||
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.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@TableName("channel_pdd_order_sync_cursor")
|
||||
public class PddOrderSyncCursorPO {
|
||||
@TableName("channel_pdd_order_inc_sync")
|
||||
public class PddOrderIncSyncPO {
|
||||
|
||||
public static final String TYPE_BOOTSTRAP = "bootstrap";
|
||||
public static final String TYPE_INCREMENTAL = "incremental";
|
||||
/** 出错暂停:Job 跳过直至开关重新打开或人工恢复 */
|
||||
public static final int STATUS_PAUSED = 2;
|
||||
public static final int STATUS_OK = 1;
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
@@ -24,16 +28,12 @@ public class PddOrderSyncCursorPO {
|
||||
@TableField("pdd_auth_id")
|
||||
private Long pddAuthId;
|
||||
|
||||
@TableField("sync_type")
|
||||
private String syncType;
|
||||
|
||||
@TableField("last_cursor_at")
|
||||
private LocalDateTime lastCursorAt;
|
||||
|
||||
@TableField("overlap_seconds")
|
||||
private Integer overlapSeconds;
|
||||
|
||||
/** 0停用 1正常 2出错暂停 */
|
||||
@TableField("status")
|
||||
private Integer status;
|
||||
|
||||
@@ -43,9 +43,9 @@ public class PddOrderSyncCursorPO {
|
||||
@TableField("last_success_time")
|
||||
private LocalDateTime lastSuccessTime;
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
@TableField("create_time")
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
@TableField("update_time")
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.vo;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
public class PddOrderFullSyncTaskVO {
|
||||
|
||||
private Long id;
|
||||
private Long shopId;
|
||||
private LocalDate dateFrom;
|
||||
private LocalDate dateTo;
|
||||
private LocalDate currentDate;
|
||||
private Integer totalDays;
|
||||
private Integer doneDays;
|
||||
private Integer failedDays;
|
||||
private String status;
|
||||
private String lastError;
|
||||
private LocalDateTime createTime;
|
||||
private LocalDateTime finishTime;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.vo;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
public class PddOrderIncrementalStatusVO {
|
||||
|
||||
private Long shopId;
|
||||
private Boolean enabled;
|
||||
private Integer cursorStatus;
|
||||
private String lastError;
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.service;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.mapper.PddOrderFullSyncTaskMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.messaging.PddSyncFullMessage;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.po.PddOrderFullSyncTaskPO;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 消费全量同步队列:有 taskId 则回写任务进度,否则直接按区间同步。
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class PddOrderFullSyncTaskExecutor {
|
||||
|
||||
private final PddOrderFullSyncTaskMapper taskMapper;
|
||||
private final PddOrderSyncService pddOrderSyncService;
|
||||
|
||||
public void execute(PddSyncFullMessage message) {
|
||||
if (message.getTaskId() != null) {
|
||||
executeTask(message.getTaskId());
|
||||
return;
|
||||
}
|
||||
LocalDate day = message.getDateFrom();
|
||||
while (!day.isAfter(message.getDateTo())) {
|
||||
pddOrderSyncService.syncByConfirmDateForTask(
|
||||
message.getCompanyId(), message.getShopId(), day, null);
|
||||
day = day.plusDays(1);
|
||||
}
|
||||
}
|
||||
|
||||
public void executeTask(Long taskId) {
|
||||
PddOrderFullSyncTaskPO task = taskMapper.selectById(taskId);
|
||||
if (task == null) {
|
||||
return;
|
||||
}
|
||||
task.setStatus(PddOrderFullSyncTaskPO.STATUS_RUNNING);
|
||||
taskMapper.updateById(task);
|
||||
|
||||
LocalDate day = task.getDateFrom();
|
||||
if (task.getCurrentDate() != null && task.getDoneDays() != null && task.getDoneDays() > 0) {
|
||||
day = task.getCurrentDate().plusDays(1);
|
||||
}
|
||||
try {
|
||||
while (!day.isAfter(task.getDateTo())) {
|
||||
task.setCurrentDate(day);
|
||||
taskMapper.updateById(task);
|
||||
pddOrderSyncService.syncByConfirmDateForTask(
|
||||
task.getCompanyId(), task.getShopId(), day, task.getId());
|
||||
task.setDoneDays((task.getDoneDays() == null ? 0 : task.getDoneDays()) + 1);
|
||||
taskMapper.updateById(task);
|
||||
day = day.plusDays(1);
|
||||
}
|
||||
task.setStatus(PddOrderFullSyncTaskPO.STATUS_SUCCESS);
|
||||
task.setFinishTime(LocalDateTime.now());
|
||||
task.setLastError(null);
|
||||
taskMapper.updateById(task);
|
||||
} catch (Exception e) {
|
||||
log.error("全量同步任务失败 taskId={}", taskId, e);
|
||||
task.setFailedDays((task.getFailedDays() == null ? 0 : task.getFailedDays()) + 1);
|
||||
task.setStatus(PddOrderFullSyncTaskPO.STATUS_FAILED);
|
||||
task.setLastError(e.getMessage() != null && e.getMessage().length() > 500
|
||||
? e.getMessage().substring(0, 500) : e.getMessage());
|
||||
task.setFinishTime(LocalDateTime.now());
|
||||
taskMapper.updateById(task);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.config.PddOrderSyncProperties;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.mapper.PddOrderFullSyncTaskMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.mapper.PddOrderIncSyncMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.messaging.PddOrderSyncPublisher;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.PddOrderSyncShopContext;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.dto.PddOrderFullSyncTaskCreateDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.dto.PddOrderIncrementalToggleDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.po.PddOrderFullSyncTaskPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.po.PddOrderIncSyncPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.vo.PddOrderFullSyncTaskVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.vo.PddOrderIncrementalStatusVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.platform.model.enums.PlatformCode;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.mapper.ShopMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
|
||||
|
||||
import java.time.temporal.ChronoUnit;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class PddOrderFullSyncTaskService {
|
||||
|
||||
private final PddOrderFullSyncTaskMapper taskMapper;
|
||||
private final PddOrderIncSyncMapper incSyncMapper;
|
||||
private final ShopMapper shopMapper;
|
||||
private final PddOrderSyncContextResolver contextResolver;
|
||||
private final PddOrderSyncPublisher syncPublisher;
|
||||
private final PddOrderSyncProperties syncProperties;
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public PddOrderFullSyncTaskVO createTask(PddOrderFullSyncTaskCreateDTO dto) {
|
||||
if (dto.getDateTo().isBefore(dto.getDateFrom())) {
|
||||
throw new BusinessException("结束日期不能早于开始日期");
|
||||
}
|
||||
PddOrderSyncShopContext ctx = contextResolver.resolveForCurrentCompany(dto.getShopId());
|
||||
|
||||
Long running = taskMapper.selectCount(new LambdaQueryWrapper<PddOrderFullSyncTaskPO>()
|
||||
.eq(PddOrderFullSyncTaskPO::getShopId, dto.getShopId())
|
||||
.in(PddOrderFullSyncTaskPO::getStatus,
|
||||
PddOrderFullSyncTaskPO.STATUS_PENDING, PddOrderFullSyncTaskPO.STATUS_RUNNING));
|
||||
if (running != null && running > 0) {
|
||||
throw new BusinessException("该店铺已有进行中的全量同步任务");
|
||||
}
|
||||
|
||||
int totalDays = (int) ChronoUnit.DAYS.between(dto.getDateFrom(), dto.getDateTo()) + 1;
|
||||
PddOrderFullSyncTaskPO task = new PddOrderFullSyncTaskPO();
|
||||
task.setCompanyId(ctx.getCompanyId());
|
||||
task.setShopId(ctx.getShopId());
|
||||
task.setPlatformCode(PlatformCode.PDD.getCode());
|
||||
task.setDateFrom(dto.getDateFrom());
|
||||
task.setDateTo(dto.getDateTo());
|
||||
task.setTotalDays(totalDays);
|
||||
task.setDoneDays(0);
|
||||
task.setFailedDays(0);
|
||||
task.setStatus(PddOrderFullSyncTaskPO.STATUS_PENDING);
|
||||
taskMapper.insert(task);
|
||||
|
||||
syncPublisher.publishFullTask(
|
||||
task.getId(), task.getCompanyId(), task.getShopId(),
|
||||
task.getDateFrom(), task.getDateTo());
|
||||
return toVo(task);
|
||||
}
|
||||
|
||||
public PddOrderFullSyncTaskVO getTask(Long taskId) {
|
||||
PddOrderFullSyncTaskPO task = taskMapper.selectById(taskId);
|
||||
if (task == null) {
|
||||
throw new BusinessException("全量同步任务不存在");
|
||||
}
|
||||
PddOrderSyncShopContext ctx = contextResolver.resolveForCurrentCompany(task.getShopId());
|
||||
if (!ctx.getCompanyId().equals(task.getCompanyId())) {
|
||||
throw new BusinessException("无权查看该任务");
|
||||
}
|
||||
return toVo(task);
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public PddOrderIncrementalStatusVO toggleIncremental(PddOrderIncrementalToggleDTO dto) {
|
||||
PddOrderSyncShopContext ctx = contextResolver.resolveForCurrentCompany(dto.getShopId());
|
||||
ShopPO shop = shopMapper.selectById(ctx.getShopId());
|
||||
if (shop == null) {
|
||||
throw new BusinessException("店铺不存在");
|
||||
}
|
||||
boolean enabled = Boolean.TRUE.equals(dto.getEnabled());
|
||||
shop.setOrderIncSyncEnabled(enabled ? 1 : 0);
|
||||
shopMapper.updateById(shop);
|
||||
|
||||
PddOrderIncSyncPO state = getOrCreateIncState(ctx);
|
||||
if (enabled && Integer.valueOf(PddOrderIncSyncPO.STATUS_PAUSED).equals(state.getStatus())) {
|
||||
state.setStatus(PddOrderIncSyncPO.STATUS_OK);
|
||||
state.setLastError(null);
|
||||
incSyncMapper.updateById(state);
|
||||
}
|
||||
return incrementalStatus(ctx.getShopId());
|
||||
}
|
||||
|
||||
public PddOrderIncrementalStatusVO incrementalStatus(Long shopId) {
|
||||
PddOrderSyncShopContext ctx = contextResolver.resolveForCurrentCompany(shopId);
|
||||
ShopPO shop = shopMapper.selectById(ctx.getShopId());
|
||||
PddOrderIncSyncPO state = findIncState(ctx.getShopId());
|
||||
boolean enabled = shop != null && Integer.valueOf(1).equals(shop.getOrderIncSyncEnabled());
|
||||
return PddOrderIncrementalStatusVO.builder()
|
||||
.shopId(shopId)
|
||||
.enabled(enabled)
|
||||
.cursorStatus(state != null ? state.getStatus() : null)
|
||||
.lastError(state != null ? state.getLastError() : null)
|
||||
.build();
|
||||
}
|
||||
|
||||
public boolean isIncrementalEnabled(Long shopId) {
|
||||
ShopPO shop = shopMapper.selectById(shopId);
|
||||
return shop != null && Integer.valueOf(1).equals(shop.getOrderIncSyncEnabled());
|
||||
}
|
||||
|
||||
public boolean isIncrementalPaused(Long shopId) {
|
||||
PddOrderIncSyncPO state = findIncState(shopId);
|
||||
return state != null && Integer.valueOf(PddOrderIncSyncPO.STATUS_PAUSED).equals(state.getStatus());
|
||||
}
|
||||
|
||||
private PddOrderIncSyncPO findIncState(Long shopId) {
|
||||
return incSyncMapper.selectOne(new LambdaQueryWrapper<PddOrderIncSyncPO>()
|
||||
.eq(PddOrderIncSyncPO::getShopId, shopId)
|
||||
.last("LIMIT 1"));
|
||||
}
|
||||
|
||||
private PddOrderIncSyncPO getOrCreateIncState(PddOrderSyncShopContext ctx) {
|
||||
PddOrderIncSyncPO existing = findIncState(ctx.getShopId());
|
||||
if (existing != null) {
|
||||
return existing;
|
||||
}
|
||||
PddOrderIncSyncPO state = new PddOrderIncSyncPO();
|
||||
state.setCompanyId(ctx.getCompanyId());
|
||||
state.setShopId(ctx.getShopId());
|
||||
state.setPddAuthId(ctx.getAuth().getId());
|
||||
state.setOverlapSeconds(syncProperties.getOverlapSeconds());
|
||||
state.setStatus(PddOrderIncSyncPO.STATUS_OK);
|
||||
incSyncMapper.insert(state);
|
||||
return state;
|
||||
}
|
||||
|
||||
private static PddOrderFullSyncTaskVO toVo(PddOrderFullSyncTaskPO task) {
|
||||
return PddOrderFullSyncTaskVO.builder()
|
||||
.id(task.getId())
|
||||
.shopId(task.getShopId())
|
||||
.dateFrom(task.getDateFrom())
|
||||
.dateTo(task.getDateTo())
|
||||
.currentDate(task.getCurrentDate())
|
||||
.totalDays(task.getTotalDays())
|
||||
.doneDays(task.getDoneDays())
|
||||
.failedDays(task.getFailedDays())
|
||||
.status(task.getStatus())
|
||||
.lastError(task.getLastError())
|
||||
.createTime(task.getCreateTime())
|
||||
.finishTime(task.getFinishTime())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+99
-89
@@ -6,13 +6,15 @@ import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.ChannelOrderRef;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.messaging.PddOrderConvertPublisher;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.config.PddOrderSyncProperties;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.hook.PddOrderAfterSyncListener;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.mapper.PddOrderSyncCursorMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.mapper.PddOrderIncSyncMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.PddOrderSyncShopContext;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.dto.PddOrderRepairDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.dto.PddOrderSyncDayDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.po.PddOrderSyncCursorPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.po.PddOrderIncSyncPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.vo.PddOrderSyncResultVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.PddPopRateLimitedException;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.order.PddOrderPopApiClient;
|
||||
@@ -30,82 +32,72 @@ import java.util.UUID;
|
||||
/**
|
||||
* 拼多多订单同步门面:day(按天回补)/ incremental / repair。
|
||||
* 只写 channel_pdd_*;转内部订单通过 {@link PddOrderAfterSyncListener}。
|
||||
* 全量进度看 full_sync_task;增量游标看 channel_pdd_order_inc_sync。
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class PddOrderSyncService {
|
||||
|
||||
private static final ZoneId ZONE = ZoneId.of("Asia/Shanghai");
|
||||
private static final String LOCK_PREFIX = "pdd:order:sync:lock:";
|
||||
private static final String LOCK_FULL_PREFIX = "pdd:order:sync:full:lock:";
|
||||
private static final String LOCK_INC_PREFIX = "pdd:order:sync:inc:lock:";
|
||||
|
||||
private final PddOrderSyncContextResolver contextResolver;
|
||||
private final PddOrderPopApiClient apiClient;
|
||||
private final PddOrderUpsertService upsertService;
|
||||
private final PddOrderSyncCursorMapper cursorMapper;
|
||||
private final PddOrderIncSyncMapper incSyncMapper;
|
||||
private final PddOrderSyncProperties syncProperties;
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
private final ShopMapper shopMapper;
|
||||
private final List<PddOrderAfterSyncListener> afterSyncListeners;
|
||||
private final PddOrderConvertPublisher convertPublisher;
|
||||
|
||||
public PddOrderSyncService(PddOrderSyncContextResolver contextResolver,
|
||||
PddOrderPopApiClient apiClient,
|
||||
PddOrderUpsertService upsertService,
|
||||
PddOrderSyncCursorMapper cursorMapper,
|
||||
PddOrderIncSyncMapper incSyncMapper,
|
||||
PddOrderSyncProperties syncProperties,
|
||||
StringRedisTemplate stringRedisTemplate,
|
||||
ShopMapper shopMapper,
|
||||
List<PddOrderAfterSyncListener> afterSyncListeners) {
|
||||
List<PddOrderAfterSyncListener> afterSyncListeners,
|
||||
PddOrderConvertPublisher convertPublisher) {
|
||||
this.contextResolver = contextResolver;
|
||||
this.apiClient = apiClient;
|
||||
this.upsertService = upsertService;
|
||||
this.cursorMapper = cursorMapper;
|
||||
this.incSyncMapper = incSyncMapper;
|
||||
this.syncProperties = syncProperties;
|
||||
this.stringRedisTemplate = stringRedisTemplate;
|
||||
this.shopMapper = shopMapper;
|
||||
this.afterSyncListeners = afterSyncListeners != null ? afterSyncListeners : List.of();
|
||||
this.convertPublisher = convertPublisher;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按成交日同步一天(list.get,窗口 ≤24h)。
|
||||
*/
|
||||
public PddOrderSyncResultVO syncByConfirmDate(PddOrderSyncDayDTO dto) {
|
||||
PddOrderSyncShopContext ctx = contextResolver.resolveForCurrentCompany(dto.getShopId());
|
||||
return withShopLock(ctx.getShopId(), () -> doSyncConfirmRange(ctx, dto.getConfirmDate(), dto.getConfirmDate(), "day"));
|
||||
return withFullLock(ctx.getShopId(), () -> doSyncConfirmRange(ctx, dto.getConfirmDate(), dto.getConfirmDate(), "day", null));
|
||||
}
|
||||
|
||||
/**
|
||||
* 按成交日起止回补(多天切 24h 窗)。
|
||||
*/
|
||||
public PddOrderSyncResultVO bootstrapByConfirmRange(Long shopId, LocalDate startDate, LocalDate endDate) {
|
||||
if (startDate == null || endDate == null || endDate.isBefore(startDate)) {
|
||||
throw new BusinessException("回补日期范围无效");
|
||||
}
|
||||
PddOrderSyncShopContext ctx = contextResolver.resolveForCurrentCompany(shopId);
|
||||
return withShopLock(ctx.getShopId(), () -> doSyncConfirmRange(ctx, startDate, endDate, "bootstrap"));
|
||||
return withFullLock(ctx.getShopId(), () -> doSyncConfirmRange(ctx, startDate, endDate, "bootstrap", null));
|
||||
}
|
||||
|
||||
/**
|
||||
* 增量:按 updated_at 从游标拉到现在(≤30min 切窗)。
|
||||
*/
|
||||
public PddOrderSyncResultVO syncIncremental(Long shopId) {
|
||||
PddOrderSyncShopContext ctx = contextResolver.resolveForCurrentCompany(shopId);
|
||||
return withShopLock(ctx.getShopId(), () -> doIncremental(ctx));
|
||||
return withIncLock(ctx.getShopId(), () -> doIncremental(ctx));
|
||||
}
|
||||
|
||||
/**
|
||||
* Job 用:按公司扫店(当前实现:对传入 shopId 做增量)。
|
||||
*/
|
||||
public PddOrderSyncResultVO syncIncrementalInternal(Long companyId, Long shopId) {
|
||||
PddOrderSyncShopContext ctx = contextResolver.resolve(companyId, shopId);
|
||||
return withShopLock(ctx.getShopId(), () -> doIncremental(ctx));
|
||||
return withIncLock(ctx.getShopId(), () -> doIncremental(ctx));
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 order_sn 补单。
|
||||
*/
|
||||
public PddOrderSyncResultVO repair(PddOrderRepairDTO dto) {
|
||||
PddOrderSyncShopContext ctx = contextResolver.resolveForCurrentCompany(dto.getShopId());
|
||||
return withShopLock(ctx.getShopId(), () -> {
|
||||
return withIncLock(ctx.getShopId(), () -> {
|
||||
List<Long> upsertedIds = new ArrayList<>();
|
||||
List<String> errors = new ArrayList<>();
|
||||
int fetched = 0;
|
||||
@@ -132,7 +124,6 @@ public class PddOrderSyncService {
|
||||
}
|
||||
} catch (PddPopRateLimitedException e) {
|
||||
errors.add(e.getMessage());
|
||||
// 补单不推进、不改写 bootstrap/incremental 游标
|
||||
break;
|
||||
} catch (Exception e) {
|
||||
log.warn("补单失败 orderSn={}: {}", orderSn, e.getMessage());
|
||||
@@ -158,16 +149,23 @@ public class PddOrderSyncService {
|
||||
.ne(ShopPO::getExternalShopId, ""));
|
||||
}
|
||||
|
||||
public PddOrderSyncResultVO syncByConfirmDateForTask(Long companyId, Long shopId, LocalDate day, Long taskId) {
|
||||
PddOrderSyncShopContext ctx = contextResolver.resolve(companyId, shopId);
|
||||
return withFullLock(ctx.getShopId(), () -> doSyncConfirmRange(ctx, day, day, "day", taskId));
|
||||
}
|
||||
|
||||
private PddOrderSyncResultVO doSyncConfirmRange(PddOrderSyncShopContext ctx,
|
||||
LocalDate startDate,
|
||||
LocalDate endDate,
|
||||
String mode) {
|
||||
String mode,
|
||||
Long taskId) {
|
||||
List<Long> upsertedIds = new ArrayList<>();
|
||||
List<String> errors = new ArrayList<>();
|
||||
int fetched = 0;
|
||||
int upserted = 0;
|
||||
try {
|
||||
for (LocalDate day = startDate; !day.isAfter(endDate); day = day.plusDays(1)) {
|
||||
List<ChannelOrderRef> dayRefs = new ArrayList<>();
|
||||
LocalDateTime dayStart = day.atStartOfDay();
|
||||
LocalDateTime dayEnd = day.plusDays(1).atStartOfDay().minusSeconds(1);
|
||||
long startTs = dayStart.atZone(ZONE).toEpochSecond();
|
||||
@@ -179,31 +177,33 @@ public class PddOrderSyncService {
|
||||
ctx.getMallId(), ctx.getAccessToken(), startTs, endTs, page);
|
||||
for (PddOrderPopApiClient.RawOrder raw : pageData.orders()) {
|
||||
fetched++;
|
||||
Long id = upsertService.upsert(ctx, raw.snapshot(), raw.raw(), false);
|
||||
if (id != null) {
|
||||
upsertedIds.add(id);
|
||||
PddOrderUpsertService.UpsertResult ur =
|
||||
upsertService.upsertWithMeta(ctx, raw.snapshot(), raw.raw(), false);
|
||||
if (ur != null && ur.id() != null) {
|
||||
ChannelOrderRef ref = PddOrderConvertPublisher.ref(ur.id());
|
||||
if (ref != null) {
|
||||
dayRefs.add(ref);
|
||||
}
|
||||
upsertedIds.add(ur.id());
|
||||
upserted++;
|
||||
}
|
||||
}
|
||||
hasNext = pageData.hasNext();
|
||||
page++;
|
||||
}
|
||||
saveCursorSuccess(ctx, PddOrderSyncCursorPO.TYPE_BOOTSTRAP, dayEnd);
|
||||
convertPublisher.publishFullDay(
|
||||
ctx.getCompanyId(), ctx.getShopId(), day, dayRefs, taskId);
|
||||
}
|
||||
} catch (PddPopRateLimitedException e) {
|
||||
errors.add(e.getMessage());
|
||||
noteRateLimit(ctx, PddOrderSyncCursorPO.TYPE_BOOTSTRAP, e.getMessage());
|
||||
} catch (BusinessException e) {
|
||||
errors.add(e.getMessage());
|
||||
markCursorError(ctx, PddOrderSyncCursorPO.TYPE_BOOTSTRAP, e.getMessage());
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
log.error("按成交日同步失败 shopId={}", ctx.getShopId(), e);
|
||||
errors.add(e.getMessage());
|
||||
markCursorError(ctx, PddOrderSyncCursorPO.TYPE_BOOTSTRAP, e.getMessage());
|
||||
throw new BusinessException("同步失败: " + e.getMessage());
|
||||
}
|
||||
notifyListeners(ctx, upsertedIds, mode);
|
||||
return PddOrderSyncResultVO.builder()
|
||||
.mode(mode)
|
||||
.shopId(ctx.getShopId())
|
||||
@@ -221,9 +221,9 @@ public class PddOrderSyncService {
|
||||
int upserted = 0;
|
||||
int overlap = Math.max(syncProperties.getOverlapSeconds(), 0);
|
||||
LocalDateTime now = LocalDateTime.now(ZONE);
|
||||
PddOrderSyncCursorPO cursor = getOrCreateCursor(ctx, PddOrderSyncCursorPO.TYPE_INCREMENTAL);
|
||||
LocalDateTime cursorAt = cursor.getLastCursorAt() != null
|
||||
? cursor.getLastCursorAt()
|
||||
PddOrderIncSyncPO state = getOrCreateIncState(ctx);
|
||||
LocalDateTime cursorAt = state.getLastCursorAt() != null
|
||||
? state.getLastCursorAt()
|
||||
: now.minusMinutes(30);
|
||||
LocalDateTime pullStart = cursorAt.minusSeconds(overlap);
|
||||
if (pullStart.isAfter(now)) {
|
||||
@@ -237,7 +237,6 @@ public class PddOrderSyncService {
|
||||
if (windowEnd.isAfter(now)) {
|
||||
windowEnd = now;
|
||||
}
|
||||
// 保证窗口不超过 30 分钟
|
||||
if (Duration.between(windowStart, windowEnd).toSeconds() > 30 * 60) {
|
||||
windowEnd = windowStart.plusMinutes(30).minusSeconds(1);
|
||||
}
|
||||
@@ -252,35 +251,43 @@ public class PddOrderSyncService {
|
||||
while (hasNext) {
|
||||
PddOrderPopApiClient.ListPage pageData = apiClient.fetchOrderListByUpdatedAt(
|
||||
ctx.getMallId(), ctx.getAccessToken(), startTs, endTs, page);
|
||||
List<ChannelOrderRef> pageRefs = new ArrayList<>();
|
||||
for (PddOrderPopApiClient.RawOrder raw : pageData.orders()) {
|
||||
fetched++;
|
||||
Long id = upsertService.upsert(ctx, raw.snapshot(), raw.raw(), false);
|
||||
if (id != null) {
|
||||
upsertedIds.add(id);
|
||||
PddOrderUpsertService.UpsertResult ur =
|
||||
upsertService.upsertWithMeta(ctx, raw.snapshot(), raw.raw(), false);
|
||||
if (ur != null && ur.id() != null) {
|
||||
ChannelOrderRef ref = PddOrderConvertPublisher.ref(ur.id());
|
||||
if (ref != null) {
|
||||
pageRefs.add(ref);
|
||||
}
|
||||
upsertedIds.add(ur.id());
|
||||
upserted++;
|
||||
}
|
||||
}
|
||||
if (!pageRefs.isEmpty()) {
|
||||
convertPublisher.publishInc(ctx.getCompanyId(), ctx.getShopId(), pageRefs);
|
||||
}
|
||||
hasNext = pageData.hasNext();
|
||||
page++;
|
||||
}
|
||||
saveCursorSuccess(ctx, PddOrderSyncCursorPO.TYPE_INCREMENTAL, windowEnd);
|
||||
saveIncSuccess(ctx, windowEnd);
|
||||
windowStart = windowEnd;
|
||||
}
|
||||
} catch (PddPopRateLimitedException e) {
|
||||
errors.add(e.getMessage());
|
||||
noteRateLimit(ctx, PddOrderSyncCursorPO.TYPE_INCREMENTAL, e.getMessage());
|
||||
noteIncRateLimit(ctx, e.getMessage());
|
||||
} catch (BusinessException e) {
|
||||
errors.add(e.getMessage());
|
||||
markCursorError(ctx, PddOrderSyncCursorPO.TYPE_INCREMENTAL, e.getMessage());
|
||||
markIncError(ctx, e.getMessage());
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
log.error("增量同步失败 shopId={}", ctx.getShopId(), e);
|
||||
errors.add(e.getMessage());
|
||||
markCursorError(ctx, PddOrderSyncCursorPO.TYPE_INCREMENTAL, e.getMessage());
|
||||
markIncError(ctx, e.getMessage());
|
||||
throw new BusinessException("增量同步失败: " + e.getMessage());
|
||||
}
|
||||
|
||||
notifyListeners(ctx, upsertedIds, "incremental");
|
||||
return PddOrderSyncResultVO.builder()
|
||||
.mode("incremental")
|
||||
.shopId(ctx.getShopId())
|
||||
@@ -291,59 +298,55 @@ public class PddOrderSyncService {
|
||||
.build();
|
||||
}
|
||||
|
||||
private PddOrderSyncCursorPO getOrCreateCursor(PddOrderSyncShopContext ctx, String syncType) {
|
||||
PddOrderSyncCursorPO existing = cursorMapper.selectOne(new LambdaQueryWrapper<PddOrderSyncCursorPO>()
|
||||
.eq(PddOrderSyncCursorPO::getShopId, ctx.getShopId())
|
||||
.eq(PddOrderSyncCursorPO::getSyncType, syncType)
|
||||
private PddOrderIncSyncPO getOrCreateIncState(PddOrderSyncShopContext ctx) {
|
||||
PddOrderIncSyncPO existing = incSyncMapper.selectOne(new LambdaQueryWrapper<PddOrderIncSyncPO>()
|
||||
.eq(PddOrderIncSyncPO::getShopId, ctx.getShopId())
|
||||
.last("LIMIT 1"));
|
||||
if (existing != null) {
|
||||
return existing;
|
||||
}
|
||||
PddOrderSyncCursorPO cursor = new PddOrderSyncCursorPO();
|
||||
cursor.setCompanyId(ctx.getCompanyId());
|
||||
cursor.setShopId(ctx.getShopId());
|
||||
cursor.setPddAuthId(ctx.getAuth().getId());
|
||||
cursor.setSyncType(syncType);
|
||||
cursor.setOverlapSeconds(syncProperties.getOverlapSeconds());
|
||||
cursor.setStatus(1);
|
||||
cursorMapper.insert(cursor);
|
||||
return cursor;
|
||||
PddOrderIncSyncPO state = new PddOrderIncSyncPO();
|
||||
state.setCompanyId(ctx.getCompanyId());
|
||||
state.setShopId(ctx.getShopId());
|
||||
state.setPddAuthId(ctx.getAuth().getId());
|
||||
state.setOverlapSeconds(syncProperties.getOverlapSeconds());
|
||||
state.setStatus(PddOrderIncSyncPO.STATUS_OK);
|
||||
incSyncMapper.insert(state);
|
||||
return state;
|
||||
}
|
||||
|
||||
private void saveCursorSuccess(PddOrderSyncShopContext ctx, String syncType, LocalDateTime cursorAt) {
|
||||
PddOrderSyncCursorPO cursor = getOrCreateCursor(ctx, syncType);
|
||||
cursor.setLastCursorAt(cursorAt);
|
||||
cursor.setStatus(1);
|
||||
cursor.setLastError(null);
|
||||
cursor.setLastSuccessTime(LocalDateTime.now(ZONE));
|
||||
cursor.setPddAuthId(ctx.getAuth().getId());
|
||||
cursor.setOverlapSeconds(syncProperties.getOverlapSeconds());
|
||||
cursorMapper.updateById(cursor);
|
||||
private void saveIncSuccess(PddOrderSyncShopContext ctx, LocalDateTime cursorAt) {
|
||||
PddOrderIncSyncPO state = getOrCreateIncState(ctx);
|
||||
state.setLastCursorAt(cursorAt);
|
||||
state.setStatus(PddOrderIncSyncPO.STATUS_OK);
|
||||
state.setLastError(null);
|
||||
state.setLastSuccessTime(LocalDateTime.now(ZONE));
|
||||
state.setPddAuthId(ctx.getAuth().getId());
|
||||
state.setOverlapSeconds(syncProperties.getOverlapSeconds());
|
||||
incSyncMapper.updateById(state);
|
||||
}
|
||||
|
||||
/** 业务失败:游标 status=2,Job 将跳过直至人工恢复。 */
|
||||
private void markCursorError(PddOrderSyncShopContext ctx, String syncType, String error) {
|
||||
private void markIncError(PddOrderSyncShopContext ctx, String error) {
|
||||
try {
|
||||
PddOrderSyncCursorPO cursor = getOrCreateCursor(ctx, syncType);
|
||||
cursor.setStatus(2);
|
||||
cursor.setLastError(truncateError(error));
|
||||
cursorMapper.updateById(cursor);
|
||||
PddOrderIncSyncPO state = getOrCreateIncState(ctx);
|
||||
state.setStatus(PddOrderIncSyncPO.STATUS_PAUSED);
|
||||
state.setLastError(truncateError(error));
|
||||
incSyncMapper.updateById(state);
|
||||
} catch (Exception e) {
|
||||
log.warn("写入同步游标错误失败: {}", e.getMessage());
|
||||
log.warn("写入增量状态错误失败: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/** 限流:只记 last_error,保持可调度(不置 status=2),不推进游标。 */
|
||||
private void noteRateLimit(PddOrderSyncShopContext ctx, String syncType, String error) {
|
||||
private void noteIncRateLimit(PddOrderSyncShopContext ctx, String error) {
|
||||
try {
|
||||
PddOrderSyncCursorPO cursor = getOrCreateCursor(ctx, syncType);
|
||||
if (cursor.getStatus() == null || cursor.getStatus() == 0) {
|
||||
cursor.setStatus(1);
|
||||
PddOrderIncSyncPO state = getOrCreateIncState(ctx);
|
||||
if (state.getStatus() == null || state.getStatus() == 0) {
|
||||
state.setStatus(PddOrderIncSyncPO.STATUS_OK);
|
||||
}
|
||||
cursor.setLastError(truncateError(error));
|
||||
cursorMapper.updateById(cursor);
|
||||
state.setLastError(truncateError(error));
|
||||
incSyncMapper.updateById(state);
|
||||
} catch (Exception e) {
|
||||
log.warn("写入限流备注失败: {}", e.getMessage());
|
||||
log.warn("写入增量限流备注失败: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -367,13 +370,20 @@ public class PddOrderSyncService {
|
||||
}
|
||||
}
|
||||
|
||||
private <T> T withShopLock(Long shopId, SyncAction<T> action) {
|
||||
private <T> T withFullLock(Long shopId, SyncAction<T> action) {
|
||||
return withTypedLock(LOCK_FULL_PREFIX + shopId, "该店铺全量同步进行中,请稍后重试", action);
|
||||
}
|
||||
|
||||
private <T> T withIncLock(Long shopId, SyncAction<T> action) {
|
||||
return withTypedLock(LOCK_INC_PREFIX + shopId, "该店铺增量同步进行中,请稍后重试", action);
|
||||
}
|
||||
|
||||
private <T> T withTypedLock(String key, String busyMessage, SyncAction<T> action) {
|
||||
String token = UUID.randomUUID().toString();
|
||||
String key = LOCK_PREFIX + shopId;
|
||||
Boolean ok = stringRedisTemplate.opsForValue()
|
||||
.setIfAbsent(key, token, Duration.ofSeconds(Math.max(syncProperties.getLockTtlSeconds(), 60)));
|
||||
if (!Boolean.TRUE.equals(ok)) {
|
||||
throw new BusinessException("该店铺正在同步中,请稍后重试");
|
||||
throw new BusinessException(busyMessage);
|
||||
}
|
||||
try {
|
||||
return action.run();
|
||||
|
||||
+13
-2
@@ -52,6 +52,13 @@ public class PddOrderUpsertService {
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public Long upsert(PddOrderSyncShopContext ctx, PddOrderApiSnapshot snapshot, Object rawSdkObject, boolean force) {
|
||||
UpsertResult r = upsertWithMeta(ctx, snapshot, rawSdkObject, force);
|
||||
return r != null ? r.id() : null;
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public UpsertResult upsertWithMeta(PddOrderSyncShopContext ctx, PddOrderApiSnapshot snapshot,
|
||||
Object rawSdkObject, boolean force) {
|
||||
if (snapshot == null || !StringUtils.hasText(snapshot.getOrderSn())) {
|
||||
return null;
|
||||
}
|
||||
@@ -63,7 +70,7 @@ public class PddOrderUpsertService {
|
||||
|
||||
if (!force && existing != null && existing.getPddUpdatedAt() != null && remoteUpdated != null
|
||||
&& !existing.getPddUpdatedAt().isBefore(remoteUpdated)) {
|
||||
return existing.getId();
|
||||
return new UpsertResult(existing.getId(), existing.getPddUpdatedAt());
|
||||
}
|
||||
|
||||
PddOrderPO order = existing != null ? existing : new PddOrderPO();
|
||||
@@ -111,7 +118,11 @@ public class PddOrderUpsertService {
|
||||
}
|
||||
|
||||
replaceItems(order, snapshot);
|
||||
return order.getId();
|
||||
LocalDateTime updatedAt = order.getPddUpdatedAt() != null ? order.getPddUpdatedAt() : order.getLastSyncTime();
|
||||
return new UpsertResult(order.getId(), updatedAt);
|
||||
}
|
||||
|
||||
public record UpsertResult(Long id, LocalDateTime pddUpdatedAt) {
|
||||
}
|
||||
|
||||
private void replaceItems(PddOrderPO order, PddOrderApiSnapshot snapshot) {
|
||||
|
||||
+4
@@ -108,6 +108,10 @@ public class OrderPO {
|
||||
@TableField("confirm")
|
||||
private Integer confirm;
|
||||
|
||||
/** 平台侧订单更新时间(渠道镜像同步过来的 updated_at) */
|
||||
@TableField("platform_updated_at")
|
||||
private LocalDateTime platformUpdatedAt;
|
||||
|
||||
@TableField("last_mapped_time")
|
||||
private LocalDateTime lastMappedTime;
|
||||
|
||||
|
||||
+6
@@ -50,6 +50,12 @@ public class ShopPO {
|
||||
@TableField("external_shop_id")
|
||||
private String externalShopId;
|
||||
|
||||
/**
|
||||
* 订单增量同步开关:0关 1开
|
||||
*/
|
||||
@TableField("order_inc_sync_enabled")
|
||||
private Integer orderIncSyncEnabled;
|
||||
|
||||
/**
|
||||
* 创建时间
|
||||
*/
|
||||
|
||||
@@ -15,7 +15,7 @@ spring:
|
||||
password: redis_qinghua
|
||||
database: 2
|
||||
mongodb:
|
||||
uri: mongodb://qinghua:mongo_qinghua@192.168.3.100:27017/ecom_dmb_dev
|
||||
uri: mongodb://ecom_dmb_dev:ecom_dmb_dev@192.168.3.100:27017/ecom_dmb_dev
|
||||
rabbitmq:
|
||||
host: 192.168.3.100
|
||||
username: qinghua
|
||||
|
||||
@@ -54,6 +54,24 @@ spring:
|
||||
default-requeue-rejected: false
|
||||
|
||||
# 订单统计读模型(汇总表已删,待重构前关闭写入与 miss 补算)
|
||||
# BI 日汇聚、License、系统初始化(合并为单一 ecom 根键,避免 DuplicateKeyException)
|
||||
ecom:
|
||||
bi:
|
||||
stat:
|
||||
lock-ttl-seconds: 600
|
||||
inc-delay-ms: 5000
|
||||
inc-max-retry: 20
|
||||
license:
|
||||
license-file: config/license.key
|
||||
revocation-file: config/revoked.jti
|
||||
revalidate-interval: 10
|
||||
init:
|
||||
auto-init: true
|
||||
company-name: 系统公司
|
||||
admin-login-code: admin
|
||||
admin-real-name: 超级管理员
|
||||
admin-phone: 13800000001
|
||||
admin-password: admin123
|
||||
|
||||
# 导入任务 Redis Stream 队列(DB 为真相源,Redis 负责调度)
|
||||
import-task:
|
||||
@@ -133,17 +151,3 @@ oss:
|
||||
bucket-name: xyquan
|
||||
|
||||
# 拼多多渠道配置见 config/channel-pdd.yml
|
||||
|
||||
# License 授权(开关与公钥见 LicenseEnforcement 源码硬编码)
|
||||
ecom:
|
||||
license:
|
||||
license-file: config/license.key
|
||||
revocation-file: config/revoked.jti
|
||||
revalidate-interval: 10
|
||||
init:
|
||||
auto-init: true
|
||||
company-name: 系统公司
|
||||
admin-login-code: admin
|
||||
admin-real-name: 超级管理员
|
||||
admin-phone: 13800000001
|
||||
admin-password: admin123
|
||||
|
||||
@@ -6,7 +6,7 @@ pdd:
|
||||
client-id: 9b71d887c8dc4b46998dedfdeca9b866
|
||||
client-secret: c626f640a6fd5f56b2c8c009a5eb2d5683e6b955
|
||||
# 须与开放平台应用回调一致;经网关时注意 /api-dev 与后端 /api 前缀
|
||||
redirect-uri: https://ecbi.newloop.top/api-dev/api/channel/pdd/auth/callback
|
||||
redirect-uri: https://ecbi.newloop.top/dev/api/channel/pdd/auth/callback
|
||||
authorize-url: https://fuwu.pinduoduo.com/service-market/auth
|
||||
state-ttl-seconds: 600
|
||||
|
||||
@@ -52,3 +52,4 @@ pdd:
|
||||
lock-ttl-seconds: 600
|
||||
incremental-job-enabled: true
|
||||
incremental-cron: "0 */5 * * * ?"
|
||||
full-task-enabled: true
|
||||
|
||||
@@ -22,3 +22,49 @@ export async function syncPddOrdersIncrementalApi(shopId: number) {
|
||||
{ params: { shopId } },
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建全量同步任务(异步按日)
|
||||
*/
|
||||
export async function createPddFullSyncTaskApi(data: {
|
||||
shopId: number;
|
||||
dateFrom: string;
|
||||
dateTo: string;
|
||||
}) {
|
||||
return requestClient.post<PddOrderSyncVO.FullTask>(
|
||||
'/channel/pdd/order/sync/full-task',
|
||||
data,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询全量同步任务
|
||||
*/
|
||||
export async function getPddFullSyncTaskApi(taskId: number) {
|
||||
return requestClient.get<PddOrderSyncVO.FullTask>(
|
||||
`/channel/pdd/order/sync/full-task/${taskId}`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 增量同步开关
|
||||
*/
|
||||
export async function togglePddIncrementalSyncApi(data: {
|
||||
shopId: number;
|
||||
enabled: boolean;
|
||||
}) {
|
||||
return requestClient.post<PddOrderSyncVO.IncrementalStatus>(
|
||||
'/channel/pdd/order/sync/incremental/toggle',
|
||||
data,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询增量同步开关状态
|
||||
*/
|
||||
export async function getPddIncrementalSyncStatusApi(shopId: number) {
|
||||
return requestClient.get<PddOrderSyncVO.IncrementalStatus>(
|
||||
'/channel/pdd/order/sync/incremental/status',
|
||||
{ params: { shopId } },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -10,4 +10,26 @@ export namespace PddOrderSyncVO {
|
||||
skippedCount: number;
|
||||
errors?: string[];
|
||||
}
|
||||
|
||||
export interface FullTask {
|
||||
id: number;
|
||||
shopId: number;
|
||||
dateFrom: string;
|
||||
dateTo: string;
|
||||
currentDate?: string;
|
||||
totalDays: number;
|
||||
doneDays: number;
|
||||
failedDays: number;
|
||||
status: string;
|
||||
lastError?: string;
|
||||
createTime?: string;
|
||||
finishTime?: string;
|
||||
}
|
||||
|
||||
export interface IncrementalStatus {
|
||||
shopId: number;
|
||||
enabled: boolean;
|
||||
cursorStatus?: number;
|
||||
lastError?: string;
|
||||
}
|
||||
}
|
||||
|
||||
+155
-13
@@ -1,17 +1,22 @@
|
||||
<script lang="ts" setup>
|
||||
import type { ShopVO } from '#/api/ecommerce/shop/types';
|
||||
import type { PddOrderSyncVO } from '#/api/ecommerce/pdd/order-sync';
|
||||
import type { Dayjs } from 'dayjs';
|
||||
|
||||
import { computed, ref } from 'vue';
|
||||
import { computed, onBeforeUnmount, ref } from 'vue';
|
||||
|
||||
import { useVbenModal } from '@vben/common-ui';
|
||||
|
||||
import { DatePicker, Form, message, Radio } from 'ant-design-vue';
|
||||
import { DatePicker, Form, message, Progress, Radio, Switch } from 'ant-design-vue';
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
import {
|
||||
createPddFullSyncTaskApi,
|
||||
getPddFullSyncTaskApi,
|
||||
getPddIncrementalSyncStatusApi,
|
||||
syncPddOrdersByDayApi,
|
||||
syncPddOrdersIncrementalApi,
|
||||
togglePddIncrementalSyncApi,
|
||||
} from '#/api/ecommerce/pdd/order-sync';
|
||||
|
||||
interface Emits {
|
||||
@@ -22,13 +27,21 @@ const emit = defineEmits<Emits>();
|
||||
|
||||
const shop = ref<null | ShopVO.Info>(null);
|
||||
const loading = ref(false);
|
||||
const mode = ref<'day' | 'incremental'>('day');
|
||||
const mode = ref<'day' | 'full' | 'incremental'>('full');
|
||||
const confirmDate = ref<Dayjs>(dayjs().subtract(1, 'day'));
|
||||
const range = ref<[Dayjs, Dayjs]>([
|
||||
dayjs().subtract(90, 'day'),
|
||||
dayjs().subtract(1, 'day'),
|
||||
]);
|
||||
const incrementalEnabled = ref(false);
|
||||
const fullTask = ref<null | PddOrderSyncVO.FullTask>(null);
|
||||
let pollTimer: null | ReturnType<typeof setInterval> = null;
|
||||
|
||||
const [Modal, modalApi] = useVbenModal({
|
||||
draggable: true,
|
||||
class: 'w-[480px]',
|
||||
class: 'w-[520px]',
|
||||
onCancel() {
|
||||
stopPoll();
|
||||
modalApi.close();
|
||||
},
|
||||
onConfirm() {
|
||||
@@ -40,15 +53,99 @@ const modalTitle = computed(() =>
|
||||
shop.value ? `同步拼多多订单 - ${shop.value.name}` : '同步拼多多订单',
|
||||
);
|
||||
|
||||
const taskProgressPercent = computed(() => {
|
||||
if (!fullTask.value || !fullTask.value.totalDays) return 0;
|
||||
return Math.min(
|
||||
100,
|
||||
Math.round((fullTask.value.doneDays / fullTask.value.totalDays) * 100),
|
||||
);
|
||||
});
|
||||
|
||||
function stopPoll() {
|
||||
if (pollTimer) {
|
||||
clearInterval(pollTimer);
|
||||
pollTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadIncrementalStatus() {
|
||||
if (!shop.value) return;
|
||||
try {
|
||||
const status = await getPddIncrementalSyncStatusApi(shop.value.id);
|
||||
incrementalEnabled.value = !!status.enabled;
|
||||
} catch (error) {
|
||||
console.error('加载增量开关失败:', error);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleToggleIncremental(checked: boolean | string | number) {
|
||||
if (!shop.value) return;
|
||||
const enabled = !!checked;
|
||||
try {
|
||||
const status = await togglePddIncrementalSyncApi({
|
||||
shopId: shop.value.id,
|
||||
enabled,
|
||||
});
|
||||
incrementalEnabled.value = !!status.enabled;
|
||||
message.success(enabled ? '已开启增量同步' : '已关闭增量同步');
|
||||
} catch (error) {
|
||||
incrementalEnabled.value = !enabled;
|
||||
console.error('切换增量开关失败:', error);
|
||||
message.error('切换增量开关失败');
|
||||
}
|
||||
}
|
||||
|
||||
async function pollFullTask(taskId: number) {
|
||||
stopPoll();
|
||||
pollTimer = setInterval(async () => {
|
||||
try {
|
||||
const task = await getPddFullSyncTaskApi(taskId);
|
||||
fullTask.value = task;
|
||||
if (task.status === 'SUCCESS' || task.status === 'FAILED' || task.status === 'CANCELLED') {
|
||||
stopPoll();
|
||||
modalApi.setState({ confirmLoading: false });
|
||||
loading.value = false;
|
||||
if (task.status === 'SUCCESS') {
|
||||
message.success(
|
||||
`全量同步完成:${task.doneDays}/${task.totalDays} 天`,
|
||||
);
|
||||
emit('success');
|
||||
} else {
|
||||
message.error(task.lastError || '全量同步失败');
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('轮询全量任务失败:', error);
|
||||
}
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
async function handleSubmit() {
|
||||
if (!shop.value) return;
|
||||
if (mode.value === 'day' && !confirmDate.value) {
|
||||
message.warning('请选择成交日期');
|
||||
return;
|
||||
}
|
||||
if (mode.value === 'full' && (!range.value?.[0] || !range.value?.[1])) {
|
||||
message.warning('请选择全量同步日期区间');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
loading.value = true;
|
||||
modalApi.setState({ confirmLoading: true });
|
||||
|
||||
if (mode.value === 'full') {
|
||||
const task = await createPddFullSyncTaskApi({
|
||||
shopId: shop.value.id,
|
||||
dateFrom: range.value[0].format('YYYY-MM-DD'),
|
||||
dateTo: range.value[1].format('YYYY-MM-DD'),
|
||||
});
|
||||
fullTask.value = task;
|
||||
message.success('全量同步任务已创建,正在后台执行');
|
||||
pollFullTask(task.id);
|
||||
return;
|
||||
}
|
||||
|
||||
const result =
|
||||
mode.value === 'day'
|
||||
? await syncPddOrdersByDayApi({
|
||||
@@ -62,7 +159,9 @@ async function handleSubmit() {
|
||||
? `;注意:${result.errors[0]}`
|
||||
: '';
|
||||
message.success(
|
||||
`同步完成:拉取 ${result.fetchedCount},入库 ${result.upsertedCount}${errHint}`,
|
||||
mode.value === 'day' || mode.value === 'incremental'
|
||||
? '已入队,后台同步中'
|
||||
: `同步完成:拉取 ${result.fetchedCount},入库 ${result.upsertedCount}${errHint}`,
|
||||
);
|
||||
emit('success');
|
||||
modalApi.close();
|
||||
@@ -70,34 +169,66 @@ async function handleSubmit() {
|
||||
console.error('同步拼多多订单失败:', error);
|
||||
message.error('同步拼多多订单失败');
|
||||
} finally {
|
||||
loading.value = false;
|
||||
modalApi.setState({ confirmLoading: false });
|
||||
if (mode.value !== 'full') {
|
||||
loading.value = false;
|
||||
modalApi.setState({ confirmLoading: false });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function open(record: ShopVO.Info) {
|
||||
async function open(record: ShopVO.Info) {
|
||||
shop.value = record;
|
||||
mode.value = 'day';
|
||||
mode.value = 'full';
|
||||
confirmDate.value = dayjs().subtract(1, 'day');
|
||||
range.value = [dayjs().subtract(90, 'day'), dayjs().subtract(1, 'day')];
|
||||
fullTask.value = null;
|
||||
stopPoll();
|
||||
await loadIncrementalStatus();
|
||||
modalApi.open();
|
||||
}
|
||||
|
||||
onBeforeUnmount(() => stopPoll());
|
||||
|
||||
defineExpose({ open });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Modal :title="modalTitle" content-class="px-5 py-4">
|
||||
<Form layout="vertical">
|
||||
<Form.Item label="自动增量同步">
|
||||
<div class="flex items-center gap-3">
|
||||
<Switch
|
||||
:checked="incrementalEnabled"
|
||||
checked-children="开"
|
||||
un-checked-children="关"
|
||||
@change="handleToggleIncremental"
|
||||
/>
|
||||
<span class="text-xs text-slate-500">开启后定时 Job 会拉取该店增量并转换</span>
|
||||
</div>
|
||||
</Form.Item>
|
||||
<Form.Item label="同步方式">
|
||||
<Radio.Group v-model:value="mode">
|
||||
<Radio value="full">全量同步任务(按日区间)</Radio>
|
||||
<Radio value="day">按成交日同步一天</Radio>
|
||||
<Radio value="incremental">增量同步(状态变更)</Radio>
|
||||
<Radio value="incremental">手动增量一次</Radio>
|
||||
</Radio.Group>
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
v-if="mode === 'day'"
|
||||
v-if="mode === 'full'"
|
||||
label="成交日期区间"
|
||||
extra="按天串行拉取;每天成功后自动进入转换与 BI 日汇聚"
|
||||
>
|
||||
<DatePicker.RangePicker
|
||||
v-model:value="range"
|
||||
class="w-full"
|
||||
:allow-clear="false"
|
||||
format="YYYY-MM-DD"
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
v-else-if="mode === 'day'"
|
||||
label="成交日期"
|
||||
extra="按拼多多成交时间(confirm_time)拉取该自然日订单,写入外部订单表"
|
||||
extra="按拼多多成交时间(confirm_time)拉取该自然日订单"
|
||||
>
|
||||
<DatePicker
|
||||
v-model:value="confirmDate"
|
||||
@@ -106,9 +237,20 @@ defineExpose({ open });
|
||||
format="YYYY-MM-DD"
|
||||
/>
|
||||
</Form.Item>
|
||||
<p v-else class="text-xs text-slate-500">
|
||||
<p v-else class="mb-3 text-xs text-slate-500">
|
||||
按订单更新时间拉取自上次游标以来的变更,用于发货/售后等状态同步。
|
||||
</p>
|
||||
<div v-if="fullTask" class="rounded border border-slate-200 p-3">
|
||||
<div class="mb-2 text-sm">
|
||||
任务 #{{ fullTask.id }} · {{ fullTask.status }} ·
|
||||
{{ fullTask.doneDays }}/{{ fullTask.totalDays }} 天
|
||||
<span v-if="fullTask.currentDate">(当前 {{ fullTask.currentDate }})</span>
|
||||
</div>
|
||||
<Progress :percent="taskProgressPercent" size="small" />
|
||||
<p v-if="fullTask.lastError" class="mt-2 text-xs text-red-500">
|
||||
{{ fullTask.lastError }}
|
||||
</p>
|
||||
</div>
|
||||
</Form>
|
||||
</Modal>
|
||||
</template>
|
||||
|
||||
Reference in New Issue
Block a user