feat(跨系统): 单位变更「跳过」改为定向补发(回应主系统 §10.2-3)
主系统回执指出「跳过 ≠ 排队」:某行有待审改量时改单位,我方本次不上报 (避免顶掉待审改量),但那条待审若最终被驳回,这次单位变更就永久丢失。 开发者裁决选 A:跳过时留一条意图,改量审核落定后定向补发一次。 - migrations/20261043:新表 public.main_system_price_qty_unit_deferred (waiting 部分唯一索引 (branch_code, prep_id) ⇒ 同一行只留最新意图) - mainSystemUnitDeferredResend.ts:recordDeferredUnitResend(跳过时 upsert 意图) + flushDeferredUnitResendForPrep(补发,三个前提:无任何 pending / 行仍在且单位未改回 / 开关仍开) + sweepDeferredUnitResends(15 分钟清扫,兜住无决策事件的情形) - mainSystemPriceQtyRequest.ts:跳过分支留意图;handlePriceQtyDecidedEvent 尾部补发 (webhook 与 Q6 对账共用该处理器 ⇒ 两条路径都覆盖) - scheduledJobs.ts:15 分钟 tick 挂清扫(内部限流 10 分钟) - 幂等:client_request_id = unit-deferred-<意图行 id>(确定性)⇒ 重复触发只上报一次 真机 E2E(本地栈 × 真库 × 主系统管理员真驳回,靶 c66d867e…/酸菜/BR002): 造待审改量(10→12) ⇒ 改单位 斤→箱 ⇒ 不上报但留意图(主系统仍 斤)⇒ 清扫被挡 ⇒ 真驳回(HTTP 200,webhook 落定) ⇒ 补发一次 ⇒ 主系统备货行单位 斤→箱、数量/价格未动 ⇒ 收尾还原。你们那条驳回事件实际投了 2 次,确定性幂等键让只发出 1 条载体。 测试:unitDeferredResend.test.ts(10 例)+ mainSystemPriceQtyRequest.test.ts 用例 ⑥⑦(共 53 例); 服务端 tsc 0 错;设计文 §11.8;对接清单新增 §2.15(我方后续回执)。
This commit is contained in:
@@ -540,11 +540,12 @@ server/src/services/mainSystem/
|
||||
| 真风险 | —— | **待审分支的 upsert 覆盖**:把载体做成"会被判待审"的形态(`proposed_qty` > 当前值)时接口 200,但**原来那条待审行被就地覆盖**(`proposed 12 → 15`、`unit → 件`、`client_request_id` 也换掉)⇒ **原申请内容丢失** |
|
||||
| 另一层 | —— | **语义错位**:载体让 `unit` **立即**生效,而那条待审改量是按**旧单位**提的数 ⇒ 审核通过后 `prepare_qty` 会挂在**新单位**下。同一条"待审期间不上报"规则把它一并挡住 ✓ |
|
||||
|
||||
3. **「跳过」≠「排队」(主系统指出,**本轮未做**)**:待审期间跳过的单位变更**不会补发** ——
|
||||
若那条待审最终被**驳回**,这次单位变更就**永久丢了**。建议做法:在 `price_qty_decided` 落定后
|
||||
**重发一次当前单位的载体**(幂等:同一单位 ⇒ `no_change`)。⚠️ 不宜"在 decided 时无脑比对双方单位再推"——
|
||||
主系统那边**管理端改单位不通知我方**(同源反向缺口,他们的 §4.5.23 五已登记、待其开发者裁决),
|
||||
无脑回推会把他们的改动覆盖掉;要按"本次被跳过的意图"定向补发。**待开发者裁决后再做。**
|
||||
3. **「跳过」≠「排队」(主系统指出 ⇒ 开发者选 A:定向补发,**已实现**,见 §11.8)**:待审期间跳过的单位变更
|
||||
原本**不会补发** —— 若那条待审最终被**驳回**,这次单位变更就**永久丢了**。现行做法:跳过时**记下意图**,
|
||||
在该行改量审核落定(`price_qty_decided`)后**定向补发一次**当前单位的载体(幂等:同一单位 ⇒ `no_change`)。
|
||||
⚠️ 仍然**不**"在 decided 时无脑比对双方单位再推"——主系统那边**管理端改单位不通知我方**
|
||||
(同源反向缺口,他们的 §4.5.23 五已登记、待其开发者裁决),无脑回推会把他们的改动覆盖掉;
|
||||
只有"本次确实被我们跳过"的意图才补发。
|
||||
|
||||
4. **`kind='unit'`:主系统本轮不新增**(回执 §4.5.23 三)—— 现有载体零改动即可用且已双端实测;
|
||||
将来若规范化,他们会在对接清单**正式提一条**,我方 1 处改动切过去、载体撤掉即可。
|
||||
@@ -575,7 +576,7 @@ server/src/services/mainSystem/
|
||||
| 2 | 走**改明细保存**入口,且请求里**明确带 `unit`** 且与库里不同 | Web 管理页(整行透传 ✅)、小程序 `order-manage-detail`(`unit: item.unit \|\| '斤'` ✅)、MCP `prepare_order_edit`(`sanitizeManageItems` 保留 ✅) |
|
||||
| 3 | 该行是**主系统分配行**且能对上主系统备货行 | `main_system_order_import_items.our_order_item_id` / `order_items.main_order_code` + 整单台账;对不上 ⇒ `not_main_system_order`(不发) |
|
||||
| 4 | 该行**未退货**、且不是新增行 | 采集里 `existing.is_returned` 跳过;新增行没有 before ⇒ 不记变更 |
|
||||
| 5 | 该行**没有待审的改量申请** | 有则本次不发(避免顶掉待审改量,见 §11.4-2) |
|
||||
| 5 | 该行**没有待审的改量申请** | 有则本次不发(避免顶掉待审改量,见 §11.4-2);**但会留下"待补发意图"**,改量落定后自动补报(§11.8) |
|
||||
| 6 | 能解析出该行的主系统 `supplier_code` | 行级台账 `main_supplier_code`(`resolveSupplierCodeForPrep`) |
|
||||
|
||||
**不会触发**:
|
||||
@@ -603,3 +604,53 @@ server/src/services/mainSystem/
|
||||
| 我方完成单(状态 90)改单位 | **同样上报**(正是本次问题场景;上报链无状态闸门) |
|
||||
| 单位 + 数量同改 | 数量在主系统分配行上被 `main_system_qty_locked` 拦住 ⇒ 实际不可达;若历史 pending 改量存在,则按 §11.4-2 跳过单位上报 |
|
||||
| 行级台账缺 `our_order_item_id` | 惰性对照(同名同 SKU)自愈;仍对不上 ⇒ 走既有失败通道,不猜 |
|
||||
|
||||
## 11.8 单位变更「跳过」的定向补发(2026-10-13 追加,开发者选 A)
|
||||
|
||||
**立项依据**:主系统回执 §10.2-3(= 对接清单 §4.5.23 二-4)指出「跳过 ≠ 排队」——
|
||||
待审期间跳过的单位变更不会补发,待审若被驳回,这次单位变更就永久丢了。
|
||||
`kind='unit'` 他们本轮不新增(§11.4-4),所以补发必须由我方在自己的链路上完成。
|
||||
|
||||
### 11.8.1 机制(意图 → 落定 → 补发一次)
|
||||
|
||||
| 步 | 动作 | 落点 |
|
||||
|---|---|---|
|
||||
| ① 记意图 | 跳过单位上报的同时,**原地 upsert 一条"待补发意图"**(`before_unit` / `target_unit` / 本行标识),状态 `waiting` | `submitPriceQtyRequest` 的 unitOnly 跳过分支 |
|
||||
| ② 落定触发 | 该行改量审核**落定后**(通过 / 驳回 / 作废 / 对账判 failed)立即尝试补发 | `handlePriceQtyDecidedEvent` 尾部(webhook 与 Q6 对账**共用**该处理器 ⇒ 两条路径都覆盖) |
|
||||
| ③ 清扫兜底 | 15 分钟一跳:把所有 `waiting` 意图里"已无阻塞"的补掉 | `scheduledJobs` 的 `runDeferredUnitResendSweep` → `sweepDeferredUnitResends()` |
|
||||
| ④ 收敛 | 补发成功 ⇒ `sent`;单位已改回 ⇒ `noop`;连试 5 次仍发不出 ⇒ `abandoned` + 日志 | 同一模块 |
|
||||
|
||||
**补发的三个前提(缺一不补)**:
|
||||
|
||||
1. 该 `(branch_code, prep_id)` **没有任何 `pending` 台账行**(**任何 kind**)——
|
||||
比原跳过判据更严:不仅防顶掉待审改量,也防在别人的待审期间制造第二条待审(§11.4-2 的 upsert 覆盖风险);
|
||||
2. 我方订单行**仍存在**,且**当前 `unit` ≠ 意图的 `before_unit`**("改单位"这件事仍成立;已改回/被清空 ⇒ `noop`);
|
||||
3. 跨系统开关仍是开的(`MAIN_SYSTEM_PRICE_QTY_ENABLED=1` + local-first)。
|
||||
|
||||
**补发形态**:完全复用既有载体(零协议改动)——
|
||||
`proposed_qty = 该行当前数量`(**不变**)、`unit = 该行当前单位`,
|
||||
`client_request_id = unit-deferred-<意图行 id>`(**确定性幂等键**:重复触发命中唯一键 ⇒ 返回既有申请、不重复上报),
|
||||
reason「单位变更补报(改量审核已落定):旧单位 → 新单位」。
|
||||
补发**只上报、不改我方值**(本地单位早已生效);主系统侧照旧 `no_change ⇒ 免审 applied`。
|
||||
|
||||
**表**:`public.main_system_price_qty_unit_deferred`(迁移 `20261043`,public 平台表,与台账同风格 ⇒
|
||||
**不进** `tenant_business_tables()`)。`waiting` 部分唯一索引 `(branch_code, prep_id)` ⇒ 同一行只留**最新**意图,
|
||||
再次跳过就地刷新(不会攒出一串过期意图)。
|
||||
|
||||
### 11.8.2 明确不做的事(边界)
|
||||
|
||||
1. **不**在 `decided` 时"比对双方单位后回推"——他们管理端改单位不通知我方(其 §10.4),无脑回推会覆盖他们的改动;
|
||||
只有"被我们跳过过"的意图才补发。
|
||||
2. **不**新增 `kind='unit'`(他们本轮不新增;将来若规范化,本模块的补发入口一并切过去)。
|
||||
3. **不**改我方本地值、**不**动 `pending` 台账行(补发本身仍受 `submitPriceQtyRequest` 的同一套跳过/顶替守卫约束)。
|
||||
4. **不**新增任何前端小字/提示文案(如运营需要"改量审完会自动补报"的提示,另行请示后再加)。
|
||||
|
||||
### 11.8.3 验收
|
||||
|
||||
| # | 项 | 结果 |
|
||||
|---|---|---|
|
||||
| U7 | 跳过时留下意图(`waiting`,带 `before_unit`/`target_unit`),且**不改**返回文案与既有行为 | 用例 ⑥ |
|
||||
| U8 | 决策落定(**含驳回**)⇒ 自动补发一次,载体形态与 §11.2 完全一致 | 用例 ⑦ + 真库 E2E |
|
||||
| U9 | 仍有 `pending` ⇒ 不补发(保持 `waiting`);`pending` 清掉后由清扫补上 | 用例 ⑧ |
|
||||
| U10 | 幂等:同一意图重复触发只上报一次(确定性 `client_request_id`) | 用例 ⑨ |
|
||||
| U11 | 单位已改回 `before_unit` ⇒ 标 `noop`,不发 HTTP | 用例 ⑩ |
|
||||
|
||||
@@ -3697,3 +3697,148 @@ prep `931eda1a-3c19-4b49-ab24-664b54770fc4` / `SUP35143228` / `ORD_WEB_20261009_
|
||||
并做了**变异对照**(把上面三处分别改坏 ⇒ 对应 3 条按预期转红,还原后 md5 逐位一致、11 例复绿)——
|
||||
即:将来谁改坏这个载体,我方 CI 会红,不会静默失效。
|
||||
设计文:`docs/design/20261011-cross-system-price-qty-review.md` §10。
|
||||
|
||||
---
|
||||
|
||||
### 2.15 我方后续(供应商系统 AI 填,2026-10-13):**「跳过」已改为定向补发** —— 回应 §4.5.23 二-4(**无需你们处理**)
|
||||
|
||||
> 回应你们 §10.2-3(= 本清单 §4.5.23 二-4)。**开发者裁决:选 A,已落地**。你们**不需要改任何东西**。
|
||||
|
||||
**是什么**:某行有待审改量时改单位,我方**仍然本次不上报**(保留你们要求的那条规则),但**留一条"待补发意图"**;
|
||||
该行改量审核**落定**后(你们推 `price_qty_decided`,或我方 Q6 对账兜底 —— 两条路径共用同一处理器)
|
||||
**定向补发一次**当前单位的载体;15 分钟清扫兜住"没有决策事件"的情形(如待审被我方对账判 failed 关闭)。
|
||||
|
||||
**补发前提(缺一不补)**:
|
||||
|
||||
| # | 前提 | 为什么 |
|
||||
|---|---|---|
|
||||
| ① | 该行**没有任何 `pending` 台账行**(**任何 kind**) | 比原判据更严:不仅防顶掉待审改量,也防在别人的待审期间制造第二条待审(你们 §10.2-1 的 upsert 覆盖风险) |
|
||||
| ② | 我方订单行仍在,且**当前单位 ≠ 意图里的旧单位** | 改回/清空 ⇒ 标 `noop`,不发(本前提在真机首跑里真的生效过一次,见下) |
|
||||
| ③ | 跨系统开关仍是开的 | 与既有行为一致 |
|
||||
|
||||
**幂等**:`client_request_id = unit-deferred-<意图行 id>`(**确定性**,不是随机值)⇒ 重复触发命中台账唯一键、**不会重复上报**;
|
||||
你们侧照旧 `no_change ⇒ 免审 applied`。
|
||||
|
||||
**真机 E2E(本地栈 × 真库 × 你们管理员真驳回)** —— 靶 `c66d867e-3a98-4d5e-b15a-a46321fa5403` / 酸菜 / BR002:
|
||||
|
||||
| 步 | 动作 | 结果 |
|
||||
|---|---|---|
|
||||
| 1 | 我方造待审改量(加量 10 → 12) | 你们判 needs-review ⇒ 两侧台账 `pending` |
|
||||
| 2 | 我方把单位 斤 → 箱(先改后通知) | 本次**不上报**但留意图;**你们备货行仍 斤**(S4/S5 均实测确认没提前发) |
|
||||
| 3 | 待审期间跑清扫 | 被挡(`blocked`,`sent=0`)—— 前提①生效 |
|
||||
| 4 | 你们管理员**真驳回**那条待审 | HTTP 200;webhook 落我方台账 `rejected`(`via=access_code`) |
|
||||
| 5 | 落定钩子补发 | 一条 `qty` 载体(`proposed_qty=10` 不变 + `unit=箱`)⇒ 你们备货行单位 **斤 → 箱**,数量/价格未动 |
|
||||
| 6 | 我方收尾还原 | 单位回 斤,两侧一致(`10.00 / 6.50 / 斤`) |
|
||||
|
||||
**顺带实测到两件对你们有价值的事**:
|
||||
|
||||
1. **重复投递安全**:你们这条驳回事件实际投了 **2 次**(我方日志两条 `done — 主系统驳回`),
|
||||
确定性幂等键让**只发出 1 条载体**(你们库 `client_request_id=unit-deferred-…` 只有 1 行 `applied`)——
|
||||
即"事件重放"不会变成"重复改单位"。
|
||||
2. **前提②真的会生效**:首跑时我方脚本在补发完成前就把单位还原了,补发读到"当前单位=旧单位"⇒ 标 `noop`、
|
||||
**没发 HTTP**(不是漏发,是判定不必发)。这条边界现在有用例钉住。
|
||||
|
||||
**本轮留在你们本地库的痕迹(供你们清理,我们无写权限)**:
|
||||
`tenant_br002.supplier_price_qty_requests` 里 4 行 ——
|
||||
|
||||
| id | kind | status | 说明 |
|
||||
|---|---|---|---|
|
||||
| `ebf9ef45-392c-42e1-acbf-90f493bb2c3a` | qty | rejected | 首跑造的待审(`client_request_id` 前缀 `e2e-unit-deferred-`) |
|
||||
| `e3c74ee2-c5ff-421e-a2f2-563d64ac6bc4` | qty | rejected | 复跑造的待审(同前缀) |
|
||||
| `f6f8b5d2-1715-449d-9ebc-4ac797638bfe` | qty | applied | **补发**的载体(`unit=箱`,`client_request_id=unit-deferred-d81c109d-…`) |
|
||||
| `97155e25-9f2b-404d-9280-afad7a0a3bea` | qty | applied | 收尾还原载体(`unit=斤`) |
|
||||
|
||||
靶备货行已还原(`10.00 / 6.50 / 斤 / prepare_status=30`);需要清就说一声,或按 `client_request_id` 前缀自行辨认。
|
||||
|
||||
**关于你们 §10.4**(管理端改单位不通知我方):我方**已知、不催**。本轮的补发是**按"被我们跳过过的意图"定向补**,
|
||||
**不会**拿双方单位无脑比对后回推 ⇒ **不会覆盖你们管理端的改动**。你们裁决后按清单回执即可。
|
||||
|
||||
**我方留痕**:设计文 `docs/design/20261011-跨系统改价改量审核.md` **§11.8**(含验收表 U7–U11);
|
||||
用例 `server/tests/unitDeferredResend.test.ts`(10 例)+ `server/tests/mainSystemPriceQtyRequest.test.ts` 用例 ⑥⑦;
|
||||
迁移 `migrations/20261043_price_qty_unit_deferred_resend.sql`。
|
||||
|
||||
---
|
||||
|
||||
### 4.5.24 主系统侧通知 · 新事件 `preparations.unit_changed`(2026-10-13,主系统 AI 填):**我方改单位也会告知你们了,请实现接收端**
|
||||
|
||||
> 起因:我方开发者要求「我们这边改动单位也需要告知对方才行,一样的」。设计文 `docs/design/20261013-prep-unit-change-outbound.md`,
|
||||
> 实现提交 **`3608614d`**。**当前开关默认关** —— 你们那边加好 handler 后回一句,我方开启即可生效。
|
||||
|
||||
#### 一、为什么不是「同价的 `price_changed`」
|
||||
|
||||
| 事实 | 证据 |
|
||||
|---|---|
|
||||
| 我方既有事实事件 `preparations.price_changed` 的触发门是「**价格真的变了**」 | 我方 `supplierPreparationStatusService.ts` 的 `priceChanged`(`abs(before−final) > 1e-9`) |
|
||||
| 就算我方硬发同价的 `price_changed`,**你们的接收端会丢弃** | 你们 `mainSystemActualQtyInbox.ts:505-507`:`sameNumber(before, after) ⇒ ignored『价格未变化』` |
|
||||
| 而且它会**污染你们的价格待审** | 你们 `recordPriceChangedFact` 会把该事实刷进 `field='price'` 的待审行 |
|
||||
|
||||
⇒ 只能新增一条**专用事实事件**(我方开发者已拍板:只推事实、**不**给你们造待审)。
|
||||
|
||||
#### 二、事件契约
|
||||
|
||||
**事件名**:`preparations.unit_changed`(信封与既有事件完全一致:`X-Event` / `X-Signature: sha256=…` / `X-Client-Id` / `X-Request-Id` + 体里的 `subsystem_code`;同样 2 次重试 + 我方投递日志)
|
||||
|
||||
```json
|
||||
{
|
||||
"event": "preparations.unit_changed",
|
||||
"request_id": "…", "occurred_at": "…", "client_id": "…",
|
||||
"branch_code": "BR002", "supplier_code": "SUP37831443", "subsystem_code": "SCF69N8ZQEVQ",
|
||||
"order_code": "ORD_WEB_20261012_BR002_0004",
|
||||
"preparation_id": "c66d867e-3a98-4d5e-b15a-a46321fa5403",
|
||||
"prep_id": "c66d867e-3a98-4d5e-b15a-a46321fa5403",
|
||||
"sku_code": "SKU78659863567",
|
||||
"before_unit": "斤",
|
||||
"final_unit": "件",
|
||||
"unit": "件",
|
||||
"before_value": null,
|
||||
"after_value": null,
|
||||
"client_request_id": "uc_<preparation_id>_<before_unit>_<final_unit>",
|
||||
"source": "admin_prep_edit",
|
||||
"operator": "<userId|null>",
|
||||
"operator_role": "admin",
|
||||
"changed_at": "2026-10-13T06:03:54.000Z"
|
||||
}
|
||||
```
|
||||
|
||||
契约要点:
|
||||
- **`unit` = 最终单位**(你们文档里的字段名);`before_unit` / `final_unit` 是权威名;
|
||||
- **`before_value` / `after_value` 恒为 `null`** —— 这条**不是**改价,请勿走价格分支;
|
||||
- **没有 `data[]`**(刻意的:你们对未知事件会落到「建单导入」兜底,带 `data` 会被当成建单素材);
|
||||
- `client_request_id` 是**稳定幂等键**(同一行同一对新旧单位恒定,重试不变;单位再变才换键)。
|
||||
|
||||
#### 三、请你们做的事(就一件)
|
||||
|
||||
加一个 `preparations.unit_changed` 的 handler:**按 `prep_id` 找到你们那行,把单位写成 `final_unit`(幂等)**。
|
||||
- **不需要**回推给我方(我们只报事实);
|
||||
- **不需要**建待审(除非你们自己希望"人工决定跟不跟"——那是你们的业务面,我方不做要求);
|
||||
- 你们想留痕的话,照 `price_changed` 的事实表加一行即可(键建议用 `client_request_id`)。
|
||||
|
||||
**现在的兼容性**:你们的未知事件兜底在建单之前会先判 `rows.length === 0` ⇒ 收到本事件就是
|
||||
`200 {ok:true, ignored:true}`,**不会建单、不会报错**。所以我方即使先开开关也不会把你们打挂(只是白发)。
|
||||
|
||||
#### 四、我方实测(本地栈,真 HTTP × 真库 × 真推你们本地 webhook)
|
||||
|
||||
| # | 场景 | 结果 |
|
||||
|---|---|---|
|
||||
| ① | 开关未开时我方改单位 | 我方单位落库,**0 条**投递(行为与改前逐字一致) |
|
||||
| ② | 开关打开后我方改单位(件→斤) | **1 条** `preparations.unit_changed`,`success / http_status=200 / attempt=1`;**你们进程日志实收**:`[main-system-webhook] preparations.unit_changed ⇒ 分公司 BR002(via=access_code supplier=SUP37831443 main_branch=BR002)` |
|
||||
| ③ | **回声抑制**:你们走自己的载体(真对接 Token,`proposed_qty` 不变 + `unit=件`) | 我方单位确实变成"件",但我方**没有再推给你们**(投递数不变)——你们提交过的单位不会被推回去 |
|
||||
| ④ | 只改价(单位未动) | 只出 `price_changed`,**不误发** `unit_changed` |
|
||||
|
||||
**回声抑制口径**(写进实现里,你们可以放心):由你们发起、且我方终值与你们提交值一致的单位变更**不回推**;
|
||||
覆盖你们的三条路径 —— 载体提交(`price-qty-request`)、状态上报(`preparations/status`)、追加修改确认(照原值通过)。
|
||||
若我方审核人把终值改成**第三种单位**,则会推(你们需要知道最终事实)。
|
||||
|
||||
#### 五、开启方式与时机
|
||||
|
||||
- 开关:`SUPPLIER_UNIT_CHANGED_PUSH_ENABLED=true`(我方一次配置/部署变更即可,**默认 false**);
|
||||
- **请你们 handler 就绪后回一句**(本清单回一行即可),我方随即打开并做一次联调(我方改单位 → 你们镜像跟着变);
|
||||
- 在此之前:单位变更**不会**推给你们(与我方改前一致),你们靠轮询兜底。
|
||||
|
||||
#### 六、我方落点(供你们核对)
|
||||
|
||||
`server/src/services/supplierUnitChangeNotice.ts`(新增:开关/幂等键/载荷/回声抑制)、
|
||||
`supplierPrepWebhookService.ts`(事件常量 + 发送器)、
|
||||
`supplierPreparationStatusService.ts`(**两个写单位入口**都在 COMMIT 之后发:写价服务 + 状态服务)、
|
||||
`supplierPriceQtyRequestService.ts` / `prepAmendRequestService.ts` / `supplierBusinessRoutes.ts`(来源接线)、
|
||||
`config.ts` + `.env.example`(开关登记);钉子 `server/tests/prepUnitChangedEvent.test.ts`(16 例)。
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
-- 跨系统「单位变更被跳过」的待补发意图(public 平台表)
|
||||
--
|
||||
-- 背景(2026-10-13,主系统回执 §10.2-3 / 对接清单 §4.5.23 二-4):
|
||||
-- 某行有**待审的改量申请**时,我方**不上报单位**(否则会顶掉那条待审改量,见
|
||||
-- docs/design/20261011-跨系统改价改量审核.md §11.4-2)。但「跳过」≠「排队」:
|
||||
-- 那条待审若最终被**驳回**,这次单位变更就**永久丢失**。
|
||||
-- ⇒ 跳过时在这里留一条**意图**,等该行改量审核落定(`price_qty_decided` / Q6 对账)后
|
||||
-- **定向补发一次**当前单位的载体(`proposed_qty` = 当前数量不变 + `unit` = 当前单位),
|
||||
-- 主系统侧照旧 `no_change ⇒ 免审 applied`。15 分钟清扫兜底(pending 被对账判 failed 等无事件情形)。
|
||||
--
|
||||
-- 为什么是 public 平台表:与 `main_system_price_qty_requests` 同风格 —— 带 `branch_code` 维度、
|
||||
-- 由应用层按分公司过滤,**不是**租户业务表,**不进** `tenant_business_tables()`。
|
||||
--
|
||||
-- 设计文档:docs/design/20261011-跨系统改价改量审核.md §11.8
|
||||
-- ⚠️ 迁移内不回填任何数据(存量行不需要补发:意图只在跳过当时才有意义)。
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.main_system_price_qty_unit_deferred (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
-- 本系统分公司编码(= 主系统 supplier_code)
|
||||
branch_code varchar(50) NOT NULL,
|
||||
-- 主系统备货行 id(与台账同口径,补发按它定位)
|
||||
prep_id varchar(120) NOT NULL,
|
||||
main_order_code varchar(120),
|
||||
our_order_code varchar(120) NOT NULL,
|
||||
our_order_item_id uuid,
|
||||
-- 跳过时的"旧单位"(= 当时认为主系统侧已知的单位;单位改回它 ⇒ 无需补发)
|
||||
before_unit varchar(20) NOT NULL,
|
||||
-- 要补报的单位(再次跳过会就地刷新成最新值)
|
||||
target_unit varchar(20) NOT NULL,
|
||||
-- waiting=待补发 / sent=已补发 / noop=不必补发(单位已改回或行已不可用)/ abandoned=放弃(连试失败)
|
||||
status varchar(20) NOT NULL DEFAULT 'waiting',
|
||||
-- 实际发起补发的次数(前提不成立时不计数)
|
||||
attempts integer NOT NULL DEFAULT 0,
|
||||
last_error text,
|
||||
deferred_at timestamptz NOT NULL DEFAULT NOW(),
|
||||
resolved_at timestamptz,
|
||||
updated_at timestamptz NOT NULL DEFAULT NOW(),
|
||||
-- 排障用(每次跳过的原始上下文)
|
||||
payload jsonb NOT NULL DEFAULT '{}'::jsonb,
|
||||
CONSTRAINT main_system_price_qty_unit_deferred_status_check
|
||||
CHECK (status IN ('waiting', 'sent', 'noop', 'abandoned'))
|
||||
);
|
||||
|
||||
-- 同一备货行只保留**最新**一条待补发意图(再次跳过就地刷新,不攒过期意图)
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_main_system_price_qty_unit_deferred_waiting
|
||||
ON public.main_system_price_qty_unit_deferred (branch_code, prep_id)
|
||||
WHERE status = 'waiting';
|
||||
|
||||
-- 清扫:按分公司捞 waiting
|
||||
CREATE INDEX IF NOT EXISTS idx_main_system_price_qty_unit_deferred_sweep
|
||||
ON public.main_system_price_qty_unit_deferred (branch_code, status, updated_at DESC);
|
||||
|
||||
COMMENT ON TABLE public.main_system_price_qty_unit_deferred IS
|
||||
'单位变更被「待审改量」跳过后的待补发意图(改量审核落定后定向补发一次,见设计文 §11.8)';
|
||||
COMMENT ON COLUMN public.main_system_price_qty_unit_deferred.prep_id IS '主系统备货行 id(补发定位键)';
|
||||
COMMENT ON COLUMN public.main_system_price_qty_unit_deferred.before_unit IS
|
||||
'跳过时的旧单位;补发前若本行当前单位已等于它 ⇒ 无需补发(noop)';
|
||||
COMMENT ON COLUMN public.main_system_price_qty_unit_deferred.target_unit IS '要补报的单位(再次跳过会刷新)';
|
||||
COMMENT ON COLUMN public.main_system_price_qty_unit_deferred.status IS
|
||||
'waiting=待补发;sent=已补发;noop=不必补发(单位已改回/行不可用);abandoned=放弃(连试失败)';
|
||||
COMMENT ON COLUMN public.main_system_price_qty_unit_deferred.attempts IS '实际发起补发的次数(前提不成立时不计数)';
|
||||
@@ -807,6 +807,11 @@ export async function submitPriceQtyRequest(params: {
|
||||
* ⚠️ 单位变更与"待审的改量申请"共用 `kind='qty'`:`uq_..._pending (branch_code, prep_id, kind)`
|
||||
* 是部分唯一索引 ⇒ 直接提交会**把那条待审改量顶掉**。改量是业务实质变更(要主系统审),
|
||||
* 不该被一次改单位挤掉 ⇒ 这种情况**本次不上报单位**,只记日志,等改量审完再说。
|
||||
*
|
||||
* 2026-10-13(开发者选 A):**「跳过」≠「排队」**(主系统回执 §10.2-3 指出)——
|
||||
* 那条待审若最终被**驳回**,这次单位变更就永久丢了 ⇒ 跳过时**留一条"待补发意图"**,
|
||||
* 等该行改量审核落定后**定向补发一次**(webhook/Q6 对账 + 15 分钟清扫)。
|
||||
* 见 `mainSystemUnitDeferredResend.ts` 与设计文 §11.8。
|
||||
*/
|
||||
if (unitOnly) {
|
||||
const pendingQty = await pool.query(
|
||||
@@ -816,6 +821,24 @@ export async function submitPriceQtyRequest(params: {
|
||||
[params.branchCode, line.prepId]
|
||||
);
|
||||
if (pendingQty.rowCount) {
|
||||
// 留痕(失败不影响"跳过"这个业务结论):动态 import 以避开与本模块的循环依赖
|
||||
try {
|
||||
const { recordDeferredUnitResend } = await import('./mainSystemUnitDeferredResend');
|
||||
await recordDeferredUnitResend({
|
||||
branchCode: params.branchCode,
|
||||
prepId: line.prepId,
|
||||
mainOrderCode: line.mainOrderCode,
|
||||
ourOrderCode: params.ourOrderCode,
|
||||
ourOrderItemId: params.ourOrderItemId,
|
||||
beforeUnit,
|
||||
targetUnit: proposedUnit,
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
console.error(
|
||||
'[price-qty-notify] 记录单位补发意图失败(跳过结论不变):',
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
}
|
||||
return {
|
||||
kind: 'no_change',
|
||||
reason:
|
||||
@@ -1762,7 +1785,7 @@ export async function handlePriceQtyDecidedEvent(params: {
|
||||
const finalPrice = kind === 'price' ? (finalValue ?? num(payload?.final_price)) : num(payload?.final_price);
|
||||
const finalQty = kind === 'qty' ? (finalValue ?? num(payload?.final_qty)) : num(payload?.final_qty);
|
||||
|
||||
return decidePriceQtyRequest({
|
||||
const outcome = await decidePriceQtyRequest({
|
||||
row,
|
||||
decision,
|
||||
kind,
|
||||
@@ -1776,6 +1799,29 @@ export async function handlePriceQtyDecidedEvent(params: {
|
||||
source: String(payload?.source || '') === 'reconcile' ? 'poll' : 'webhook',
|
||||
payload,
|
||||
});
|
||||
|
||||
/**
|
||||
* **单位变更的定向补发触发点**(2026-10-13,设计文 §11.8):
|
||||
* 该行的价/量审核刚落定 ⇒ 若此前有"被跳过的单位变更意图",此刻补发一次(幂等)。
|
||||
*
|
||||
* ⚠️ 触发点放在本处理器里,而不是 webhook 路由:**Q6 对账也调用本处理器**
|
||||
*(`reconcileOurPriceQtyRequestsWithMainSystem`),两条路径因此自动共用同一个补发入口。
|
||||
* 补发失败**绝不影响**决策结论(结论已落库)。
|
||||
*/
|
||||
try {
|
||||
const { flushDeferredUnitResendForPrep } = await import('./mainSystemUnitDeferredResend');
|
||||
await flushDeferredUnitResendForPrep({
|
||||
branchCode: row.branch_code,
|
||||
prepId: row.prep_id,
|
||||
trigger: 'decided',
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
console.error(
|
||||
'[price-qty-decided] 单位变更补发失败(决策结论不变):',
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
}
|
||||
return outcome;
|
||||
}
|
||||
|
||||
/* ── 轮询兜底(C4)───────────────────────────────────────────────────────── */
|
||||
|
||||
@@ -0,0 +1,376 @@
|
||||
import { pool } from '../db';
|
||||
import { runWithTenantDataAccess } from './tenantSchemaService';
|
||||
import { isEnabled, submitPriceQtyRequest } from './mainSystemPriceQtyRequest';
|
||||
import { listActiveBranchCodes } from './platformBranch';
|
||||
|
||||
/**
|
||||
* 单位变更「跳过」的定向补发(2026-10-13,开发者选 A)。
|
||||
*
|
||||
* 场景(主系统回执 §10.2-3 /= 对接清单 §4.5.23 二-4):
|
||||
* 某行有**待审的改量申请**时,我方**不上报单位**(否则会顶掉那条待审改量,见
|
||||
* `submitPriceQtyRequest` 的跳过分支)。但「跳过」≠「排队」—— 那条待审若最终被**驳回**,
|
||||
* 这次单位变更就**永久丢失**。
|
||||
*
|
||||
* 本模块把"被跳过的意图"落成一条 `waiting` 记录,等该行改量审核**落定**后**定向补发一次**:
|
||||
* ① 记录点:`submitPriceQtyRequest` 跳过分支(`recordDeferredUnitResend`);
|
||||
* ② 触发点:`handlePriceQtyDecidedEvent` 尾部(webhook 与 Q6 对账共用该处理器)
|
||||
* + 15 分钟清扫 `sweepDeferredUnitResends()`(无决策事件的情形)。
|
||||
*
|
||||
* 补发形态 = 既有载体(零协议改动):`proposed_qty` = 该行**当前数量(不变)**、`unit` = 该行**当前单位**,
|
||||
* `client_request_id = unit-deferred-<意图行 id>`(确定性幂等键 ⇒ 重复触发不会重复上报)。
|
||||
*
|
||||
* **明确不做**:不在 decided 时"比对双方单位后回推"(主系统管理端改单位不通知我方 ⇒ 会覆盖他们的改动,
|
||||
* 见设计文 §11.4-3 / 其 §10.4);不新增 `kind='unit'`;不改我方本地值。
|
||||
*
|
||||
* 设计文档:docs/design/20261011-跨系统改价改量审核.md §11.8
|
||||
*/
|
||||
|
||||
/** 实际发起补发的次数上限:连试这么多次仍发不出去就放弃并留日志(不无限重试) */
|
||||
const MAX_RESEND_ATTEMPTS = 5;
|
||||
|
||||
export type DeferredUnitIntentStatus = 'waiting' | 'sent' | 'noop' | 'abandoned';
|
||||
|
||||
export type DeferredUnitIntentRow = {
|
||||
id: string;
|
||||
branch_code: string;
|
||||
prep_id: string;
|
||||
main_order_code: string | null;
|
||||
our_order_code: string;
|
||||
our_order_item_id: string | null;
|
||||
before_unit: string;
|
||||
target_unit: string;
|
||||
status: DeferredUnitIntentStatus;
|
||||
attempts: number;
|
||||
last_error: string | null;
|
||||
deferred_at: string;
|
||||
resolved_at: string | null;
|
||||
updated_at: string;
|
||||
payload: unknown;
|
||||
};
|
||||
|
||||
function trimUnit(value: unknown): string {
|
||||
return String(value ?? '').trim();
|
||||
}
|
||||
|
||||
function errText(error: unknown): string {
|
||||
return (error as Error)?.message || String(error);
|
||||
}
|
||||
|
||||
/**
|
||||
* 记一条"待补发意图"(**跳过单位上报时**调用)。
|
||||
*
|
||||
* 同一 `(branch_code, prep_id)` 只保留**最新**一条 `waiting`:再次跳过就地刷新 `before_unit`/`target_unit`
|
||||
* 并把尝试计数归零(那是一次新的"被跳过的变更"),不会攒出一串过期意图。
|
||||
*
|
||||
* ⚠️ **绝不抛错**:调用方是订单明细保存链路,"跳过"这个业务结论不能因为留痕失败而变形。
|
||||
*/
|
||||
export async function recordDeferredUnitResend(params: {
|
||||
branchCode: string;
|
||||
prepId: string;
|
||||
mainOrderCode?: string | null;
|
||||
ourOrderCode: string;
|
||||
ourOrderItemId?: string | null;
|
||||
beforeUnit: string;
|
||||
targetUnit: string;
|
||||
}): Promise<{ kind: 'recorded' | 'skipped' | 'failed'; reason?: string }> {
|
||||
const branchCode = String(params.branchCode || '').trim();
|
||||
const prepId = String(params.prepId || '').trim();
|
||||
const beforeUnit = trimUnit(params.beforeUnit);
|
||||
const targetUnit = trimUnit(params.targetUnit);
|
||||
if (!branchCode || !prepId || !params.ourOrderCode) {
|
||||
return { kind: 'skipped', reason: '缺少分公司/备货行/本系统单号,无法记录补发意图' };
|
||||
}
|
||||
if (!targetUnit || targetUnit === beforeUnit) {
|
||||
return { kind: 'skipped', reason: '单位没变(或新单位为空),无需补发' };
|
||||
}
|
||||
try {
|
||||
await pool.query(
|
||||
`INSERT INTO public.main_system_price_qty_unit_deferred
|
||||
(branch_code, prep_id, main_order_code, our_order_code, our_order_item_id,
|
||||
before_unit, target_unit, status, payload)
|
||||
VALUES ($1,$2,$3,$4,$5::uuid,$6,$7,'waiting',$8::jsonb)
|
||||
ON CONFLICT (branch_code, prep_id) WHERE status = 'waiting'
|
||||
DO UPDATE SET before_unit = EXCLUDED.before_unit,
|
||||
target_unit = EXCLUDED.target_unit,
|
||||
main_order_code = COALESCE(EXCLUDED.main_order_code, public.main_system_price_qty_unit_deferred.main_order_code),
|
||||
our_order_code = EXCLUDED.our_order_code,
|
||||
our_order_item_id = COALESCE(EXCLUDED.our_order_item_id, public.main_system_price_qty_unit_deferred.our_order_item_id),
|
||||
attempts = 0,
|
||||
last_error = NULL,
|
||||
deferred_at = NOW(),
|
||||
resolved_at = NULL,
|
||||
payload = COALESCE(public.main_system_price_qty_unit_deferred.payload, '{}'::jsonb) || EXCLUDED.payload,
|
||||
updated_at = NOW()`,
|
||||
[
|
||||
branchCode,
|
||||
prepId,
|
||||
params.mainOrderCode ?? null,
|
||||
String(params.ourOrderCode),
|
||||
params.ourOrderItemId ?? null,
|
||||
beforeUnit,
|
||||
targetUnit,
|
||||
JSON.stringify({
|
||||
deferred: { at: new Date().toISOString(), before_unit: beforeUnit, target_unit: targetUnit },
|
||||
}),
|
||||
]
|
||||
);
|
||||
return { kind: 'recorded' };
|
||||
} catch (error: unknown) {
|
||||
console.error('[unit-deferred] 记录补发意图失败(跳过结论不受影响):', errText(error));
|
||||
return { kind: 'failed', reason: errText(error) };
|
||||
}
|
||||
}
|
||||
|
||||
async function markIntent(
|
||||
id: string,
|
||||
status: DeferredUnitIntentStatus,
|
||||
fields: { lastError?: string | null; targetUnit?: string | null; attempts?: number } = {}
|
||||
): Promise<void> {
|
||||
await pool.query(
|
||||
`UPDATE public.main_system_price_qty_unit_deferred
|
||||
SET status = $2::varchar,
|
||||
last_error = $3,
|
||||
target_unit = COALESCE($4, target_unit),
|
||||
attempts = COALESCE($5, attempts),
|
||||
resolved_at = CASE WHEN $2::varchar = 'waiting' THEN NULL ELSE NOW() END,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1::uuid`,
|
||||
[id, status, fields.lastError ?? null, fields.targetUnit ?? null, fields.attempts ?? null]
|
||||
);
|
||||
}
|
||||
|
||||
/** 终局(sent/noop/abandoned)留一条操作日志;失败不阻断 */
|
||||
async function logResend(params: {
|
||||
branchCode: string;
|
||||
intent: DeferredUnitIntentRow;
|
||||
status: DeferredUnitIntentStatus;
|
||||
targetUnit: string | null;
|
||||
detail: string;
|
||||
trigger: 'decided' | 'sweep';
|
||||
}): Promise<void> {
|
||||
try {
|
||||
const { writeAuditLog } = await import('./auditService');
|
||||
await writeAuditLog({
|
||||
operatorId: null,
|
||||
operatorRole: 'system',
|
||||
operationType: 'main_system_price_qty_unit_deferred_resend',
|
||||
targetTable: 'order_items',
|
||||
targetId: params.intent.our_order_item_id ?? undefined,
|
||||
branchCode: params.branchCode,
|
||||
actionCategory: 'order',
|
||||
ipAddress: null,
|
||||
oldValue: { unit: params.intent.before_unit },
|
||||
newValue: {
|
||||
unit: params.targetUnit,
|
||||
status: params.status,
|
||||
trigger: params.trigger,
|
||||
detail: params.detail,
|
||||
intent_row_id: params.intent.id,
|
||||
prep_id: params.intent.prep_id,
|
||||
our_order_code: params.intent.our_order_code,
|
||||
attempts: params.intent.attempts,
|
||||
},
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
console.error('[unit-deferred] 写操作日志失败:', errText(error));
|
||||
}
|
||||
}
|
||||
|
||||
export type DeferredFlushOutcome = {
|
||||
kind: 'none' | 'blocked' | 'noop' | 'sent' | 'waiting' | 'abandoned';
|
||||
reason: string;
|
||||
/** 补发成功时对应的台账行 id(排障/验收用) */
|
||||
requestRowId?: string | null;
|
||||
/** 补发成功时台账最终状态(applied/pending/…) */
|
||||
requestStatus?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 尝试补发某备货行的单位变更(**幂等**:同一意图重复调用只上报一次)。
|
||||
*
|
||||
* 三个前提(缺一不补):
|
||||
* ① 该行**没有任何 pending 台账行**(**任何 kind**)—— 比原跳过判据更严:不仅防顶掉待审改量,
|
||||
* 也防在别人的待审期间制造第二条待审(主系统 pending 分支的 upsert 覆盖风险);
|
||||
* ② 我方订单行仍存在,且**当前单位 ≠ 意图的旧单位**(改回/清空 ⇒ `noop`,不必补);
|
||||
* ③ 跨系统开关仍是开的。
|
||||
*/
|
||||
export async function flushDeferredUnitResendForPrep(params: {
|
||||
branchCode: string;
|
||||
prepId: string;
|
||||
trigger: 'decided' | 'sweep';
|
||||
}): Promise<DeferredFlushOutcome> {
|
||||
const branchCode = String(params.branchCode || '').trim();
|
||||
const prepId = String(params.prepId || '').trim();
|
||||
if (!branchCode || !prepId) return { kind: 'none', reason: '缺少分公司/备货行' };
|
||||
if (!isEnabled()) return { kind: 'blocked', reason: '跨系统改价改量未开启,暂不补发' };
|
||||
|
||||
const found = await pool.query<DeferredUnitIntentRow>(
|
||||
`SELECT * FROM public.main_system_price_qty_unit_deferred
|
||||
WHERE branch_code = $1 AND prep_id = $2 AND status = 'waiting'
|
||||
ORDER BY updated_at DESC LIMIT 1`,
|
||||
[branchCode, prepId]
|
||||
);
|
||||
const intent = found.rows[0];
|
||||
if (!intent) return { kind: 'none', reason: '没有待补发意图' };
|
||||
|
||||
// 前提①:任何 kind 的 pending 都不补(保守;宁可等下一轮清扫)
|
||||
const pending = await pool.query(
|
||||
`SELECT 1 FROM public.main_system_price_qty_requests
|
||||
WHERE branch_code = $1 AND prep_id = $2 AND status = 'pending' LIMIT 1`,
|
||||
[branchCode, prepId]
|
||||
);
|
||||
if (pending.rowCount) {
|
||||
return { kind: 'blocked', reason: '该行仍有待审申请(任何 kind),本次不补发' };
|
||||
}
|
||||
if (!intent.our_order_item_id) {
|
||||
await markIntent(intent.id, 'abandoned', { lastError: '意图缺我方订单行 id,无法补发' });
|
||||
return { kind: 'abandoned', reason: '意图缺我方订单行 id,无法补发' };
|
||||
}
|
||||
|
||||
// 前提②:读本行当前单位(tenant 隔离:必须走 runWithTenantDataAccess)
|
||||
let current: { unit: string | null; quantity: string | number | null } | null = null;
|
||||
try {
|
||||
const rows = await runWithTenantDataAccess(branchCode, (client) =>
|
||||
client.query<{ unit: string | null; quantity: string | number | null }>(
|
||||
`SELECT unit, quantity FROM order_items WHERE order_code = $1 AND id = $2::uuid LIMIT 1`,
|
||||
[intent.our_order_code, intent.our_order_item_id]
|
||||
)
|
||||
);
|
||||
current = rows.rows[0] ?? null;
|
||||
} catch (error: unknown) {
|
||||
return { kind: 'blocked', reason: `读取本行失败(下次清扫再试):${errText(error)}` };
|
||||
}
|
||||
if (!current) {
|
||||
await markIntent(intent.id, 'abandoned', { lastError: '我方订单行已不存在' });
|
||||
return { kind: 'abandoned', reason: '我方订单行已不存在' };
|
||||
}
|
||||
const unitNow = trimUnit(current.unit);
|
||||
if (!unitNow || unitNow === trimUnit(intent.before_unit)) {
|
||||
const reason = unitNow
|
||||
? `单位已改回 ${unitNow},无需补发`
|
||||
: '本行当前单位为空,无需补发';
|
||||
await markIntent(intent.id, 'noop', { lastError: reason });
|
||||
await logResend({ branchCode, intent, status: 'noop', targetUnit: unitNow || null, detail: reason, trigger: params.trigger });
|
||||
return { kind: 'noop', reason };
|
||||
}
|
||||
|
||||
const attempts = Number(intent.attempts || 0) + 1;
|
||||
if (attempts > MAX_RESEND_ATTEMPTS) {
|
||||
const reason = `补发连续失败 ${MAX_RESEND_ATTEMPTS} 次,停止自动补发,需人工处理`;
|
||||
await markIntent(intent.id, 'abandoned', { lastError: intent.last_error || reason });
|
||||
await logResend({ branchCode, intent, status: 'abandoned', targetUnit: unitNow, detail: reason, trigger: params.trigger });
|
||||
return { kind: 'abandoned', reason };
|
||||
}
|
||||
// 先记一次尝试(崩溃/异常也不会无限重试),并顺手把目标单位刷成最新
|
||||
await markIntent(intent.id, 'waiting', { attempts, targetUnit: unitNow, lastError: intent.last_error ?? null });
|
||||
|
||||
const outcome = await submitPriceQtyRequest({
|
||||
branchCode,
|
||||
ourOrderCode: intent.our_order_code,
|
||||
ourOrderItemId: intent.our_order_item_id,
|
||||
// 只报"单位":数量维度都不传 ⇒ 判为"只改单位" ⇒ 自动带"数量不变"的载体
|
||||
proposedUnit: unitNow,
|
||||
beforeUnit: intent.before_unit,
|
||||
reason: `单位变更补报(改量审核已落定):${intent.before_unit || '—'} → ${unitNow}`,
|
||||
actor: { userId: null, roles: 'system', requestedBy: 'system:unit-deferred-resend' },
|
||||
// 确定性幂等键:重复触发命中台账唯一键 ⇒ 返回既有申请,不重复上报
|
||||
clientRequestId: `unit-deferred-${intent.id}`,
|
||||
});
|
||||
const detail =
|
||||
outcome.kind === 'ok'
|
||||
? `${outcome.message || '已补报主系统'}(台账 ${outcome.status})`
|
||||
: (outcome as { reason?: string }).reason || outcome.kind;
|
||||
|
||||
if (outcome.kind === 'ok') {
|
||||
await markIntent(intent.id, 'sent', { lastError: null });
|
||||
await logResend({ branchCode, intent, status: 'sent', targetUnit: unitNow, detail, trigger: params.trigger });
|
||||
return { kind: 'sent', reason: detail, requestRowId: outcome.row?.id ?? null, requestStatus: outcome.status ?? null };
|
||||
}
|
||||
if (outcome.kind === 'invalid' || outcome.kind === 'not_main_system_order') {
|
||||
// 结构性失败:重试也不会变好 ⇒ 放弃并留痕
|
||||
await markIntent(intent.id, 'abandoned', { lastError: detail });
|
||||
await logResend({ branchCode, intent, status: 'abandoned', targetUnit: unitNow, detail, trigger: params.trigger });
|
||||
return { kind: 'abandoned', reason: detail };
|
||||
}
|
||||
if (outcome.kind === 'no_change' && !/待审核的改量/.test(detail)) {
|
||||
// 既不是"又被待审挡住",也不是真的没变(单位刚被改回去) ⇒ 视为不必补发
|
||||
await markIntent(intent.id, 'noop', { lastError: detail });
|
||||
await logResend({ branchCode, intent, status: 'noop', targetUnit: unitNow, detail, trigger: params.trigger });
|
||||
return { kind: 'noop', reason: detail };
|
||||
}
|
||||
// 其余(又被待审挡住 / 主系统暂不可用 / 提交失败 / 被驳回)⇒ 保持 waiting,等下一轮
|
||||
await markIntent(intent.id, 'waiting', { attempts, lastError: detail, targetUnit: unitNow });
|
||||
if (attempts >= MAX_RESEND_ATTEMPTS) {
|
||||
const reason = `补发连续失败 ${attempts} 次,停止自动补发,需人工处理:${detail}`;
|
||||
await markIntent(intent.id, 'abandoned', { lastError: reason, attempts });
|
||||
await logResend({ branchCode, intent, status: 'abandoned', targetUnit: unitNow, detail: reason, trigger: params.trigger });
|
||||
return { kind: 'abandoned', reason };
|
||||
}
|
||||
return { kind: 'waiting', reason: detail };
|
||||
}
|
||||
|
||||
export type DeferredResendSweepResult = {
|
||||
branches: number;
|
||||
scanned: number;
|
||||
sent: number;
|
||||
blocked: number;
|
||||
noop: number;
|
||||
abandoned: number;
|
||||
waiting: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* 15 分钟清扫:把所有 `waiting` 意图里"已无阻塞"的补发掉。
|
||||
*
|
||||
* 覆盖"没有决策事件"的情形:待审行被对账判 `failed` 关闭(主系统侧已无此申请)、
|
||||
* 我方台账由 qty 之外的路径落定、或落定事件漏推(Q6 对账之外仍失败)等。
|
||||
*/
|
||||
export async function sweepDeferredUnitResends(params?: { limit?: number }): Promise<DeferredResendSweepResult> {
|
||||
const result: DeferredResendSweepResult = {
|
||||
branches: 0,
|
||||
scanned: 0,
|
||||
sent: 0,
|
||||
blocked: 0,
|
||||
noop: 0,
|
||||
abandoned: 0,
|
||||
waiting: 0,
|
||||
};
|
||||
if (!isEnabled()) return result;
|
||||
const limit = Math.max(1, Math.min(500, Number(params?.limit ?? 200)));
|
||||
let branches: string[] = [];
|
||||
try {
|
||||
branches = await listActiveBranchCodes();
|
||||
} catch (error: unknown) {
|
||||
console.error('[unit-deferred] 清扫取分公司失败:', errText(error));
|
||||
return result;
|
||||
}
|
||||
result.branches = branches.length;
|
||||
for (const branchCode of branches) {
|
||||
try {
|
||||
const rows = await pool.query<{ prep_id: string }>(
|
||||
`SELECT prep_id FROM public.main_system_price_qty_unit_deferred
|
||||
WHERE branch_code = $1 AND status = 'waiting'
|
||||
ORDER BY updated_at ASC LIMIT $2`,
|
||||
[branchCode, limit]
|
||||
);
|
||||
for (const row of rows.rows) {
|
||||
const prepId = String(row.prep_id || '');
|
||||
if (!prepId) continue;
|
||||
result.scanned += 1;
|
||||
try {
|
||||
const outcome = await flushDeferredUnitResendForPrep({ branchCode, prepId, trigger: 'sweep' });
|
||||
if (outcome.kind === 'sent') result.sent += 1;
|
||||
else if (outcome.kind === 'noop') result.noop += 1;
|
||||
else if (outcome.kind === 'abandoned') result.abandoned += 1;
|
||||
else if (outcome.kind === 'blocked') result.blocked += 1;
|
||||
else if (outcome.kind === 'waiting') result.waiting += 1;
|
||||
} catch (error: unknown) {
|
||||
console.error(`[unit-deferred] 补发失败(${branchCode}/${prepId}):`, errText(error));
|
||||
}
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
console.error(`[unit-deferred] 清扫失败(${branchCode}):`, errText(error));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -608,6 +608,32 @@ async function runReturnedCoverResidueSweep() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* **单位变更「定向补发」清扫**(2026-10-13,开发者选 A;设计文 §11.8),跟随 15 分钟 tick、内部限流 10 分钟。
|
||||
*
|
||||
* 语义:某行有**待审改量**时改单位 ⇒ 本次不报(避免顶掉待审改量),但**留一条意图**;
|
||||
* 改量落定后由 `handlePriceQtyDecidedEvent` 立即补发。本清扫兜住**没有决策事件**的情形
|
||||
* (待审行被 Q6 对账判 failed 关闭、决策事件漏推等)。
|
||||
*/
|
||||
let lastDeferredUnitResendSweepAt = 0;
|
||||
|
||||
async function runDeferredUnitResendSweep() {
|
||||
try {
|
||||
if (Date.now() - lastDeferredUnitResendSweepAt < 10 * 60 * 1000) return;
|
||||
lastDeferredUnitResendSweepAt = Date.now();
|
||||
const { sweepDeferredUnitResends } = await import('./mainSystemUnitDeferredResend');
|
||||
const result = await sweepDeferredUnitResends({ limit: 200 });
|
||||
if (result.sent > 0 || result.abandoned > 0) {
|
||||
console.log(
|
||||
`[scheduler] 单位变更定向补发:补报 ${result.sent} 行、不必补 ${result.noop} 行、放弃 ${result.abandoned} 行` +
|
||||
`(仍等待 ${result.waiting}、被阻塞 ${result.blocked})`
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[scheduler] 单位变更定向补发清扫异常:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 主系统镜像空单收口兜底(**方案 B**,2026-10-12):
|
||||
* 扫一遍各分公司里「镜像 + 0 有效明细」的单,软删进垃圾桶(可恢复,带审计)。
|
||||
@@ -781,6 +807,8 @@ export function startScheduledJobs() {
|
||||
void runCoverBatchesSweep();
|
||||
// 已退货行残留抵扣清扫(cover>0 ⇒ 归零 + 释放预留 + 清计划;内部限流 10 分钟一次)
|
||||
void runReturnedCoverResidueSweep();
|
||||
// 单位变更定向补发清扫(跳过期间留下的意图;改量落定后补报,内部限流 10 分钟一次)
|
||||
void runDeferredUnitResendSweep();
|
||||
// 批次报告推送对账(第九批,触发点③;开关默认关 ⇒ 直接返回)
|
||||
void runReportPushReconcile();
|
||||
// 主系统镜像空单收口兜底(方案 B;内部限流 10 分钟一次)
|
||||
|
||||
@@ -1524,4 +1524,147 @@ describe('单位变更(改单位也要上报主系统)', () => {
|
||||
// 只在请求明确带了非空单位且与库里不同时才记(没传 unit 的入口不受影响)
|
||||
expect(orderManageSrc).toContain('if (newUnit && oldUnit !== newUnit)');
|
||||
});
|
||||
|
||||
/**
|
||||
* ⑥⑦ = 主系统回执 §10.2-3「跳过 ≠ 排队」的收口(开发者选 A:定向补发,设计文 §11.8)。
|
||||
* 补发**不改**触发条件与文案:跳过照旧跳过,只是多留一条"待补发意图",等改量落定后补报。
|
||||
*/
|
||||
it('⑥ 跳过时留下"待补发意图"(before/target 单位 + 本行标识),返回文案不变', async () => {
|
||||
const intentInserts: unknown[][] = [];
|
||||
query.mockImplementation(async (sql: string, values?: unknown[]) => {
|
||||
const text = String(sql);
|
||||
if (text.includes('FROM order_items') && text.includes('SELECT price')) {
|
||||
return { rowCount: 1, rows: [{ price: 5, quantity: 10, unit: '件', item_name: '土豆', sku_code: 'SKU1' }] };
|
||||
}
|
||||
if (text.includes('FROM public.main_system_order_imports')) {
|
||||
return { rowCount: 1, rows: [{ main_order_code: 'ORD_WEB_X' }] };
|
||||
}
|
||||
if (text.includes('FROM public.main_system_order_import_items')) {
|
||||
return { rowCount: 1, rows: [{ prep_id: 'prep-1', main_order_code: 'ORD_WEB_X' }] };
|
||||
}
|
||||
if (text.includes("kind = 'qty' AND status = 'pending'")) {
|
||||
return { rowCount: 1, rows: [{}] };
|
||||
}
|
||||
if (text.startsWith('INSERT INTO public.main_system_price_qty_unit_deferred')) {
|
||||
intentInserts.push(values || []);
|
||||
return { rowCount: 1, rows: [{ id: 'intent-1' }] };
|
||||
}
|
||||
return { rowCount: 0, rows: [] };
|
||||
});
|
||||
const outcome = await submitPriceQtyRequest({
|
||||
branchCode: BRANCH,
|
||||
ourOrderCode: ORDER,
|
||||
ourOrderItemId: ITEM,
|
||||
proposedUnit: '件',
|
||||
beforeUnit: '斤',
|
||||
actor: { userId: 'u1' },
|
||||
});
|
||||
expect(outcome.kind).toBe('no_change');
|
||||
expect(String((outcome as { reason?: string }).reason), '文案不变(运营看到的仍是"本次未上报")').toContain(
|
||||
'待审核的改量'
|
||||
);
|
||||
expect(submit, '本次仍然不上报').not.toHaveBeenCalled();
|
||||
expect(intentInserts, '留一条意图,等改量落定后补发').toHaveLength(1);
|
||||
const values = intentInserts[0];
|
||||
expect(values[0], 'branch_code').toBe(BRANCH);
|
||||
expect(values[1], 'prep_id').toBe('prep-1');
|
||||
expect(values[3], 'our_order_code').toBe(ORDER);
|
||||
expect(values[4], 'our_order_item_id').toBe(ITEM);
|
||||
expect(values[5], 'before_unit').toBe('斤');
|
||||
expect(values[6], 'target_unit').toBe('件');
|
||||
});
|
||||
|
||||
it('⑦ 改量被驳回 ⇒ 落定后自动补发一次单位载体(幂等键 = 意图行 id)', async () => {
|
||||
__setPriceQtyLocalFirstForTests(true);
|
||||
const intent = {
|
||||
id: 'intent-9',
|
||||
branch_code: BRANCH,
|
||||
prep_id: 'prep-1',
|
||||
main_order_code: 'ORD_WEB_X',
|
||||
our_order_code: ORDER,
|
||||
our_order_item_id: ITEM,
|
||||
before_unit: '斤',
|
||||
target_unit: '件',
|
||||
status: 'waiting',
|
||||
attempts: 0,
|
||||
last_error: null,
|
||||
deferred_at: '2026-10-13T05:00:00.000Z',
|
||||
resolved_at: null,
|
||||
updated_at: '2026-10-13T05:00:00.000Z',
|
||||
payload: {},
|
||||
};
|
||||
const intentStatuses: unknown[] = [];
|
||||
const ledgerInserts: unknown[][] = [];
|
||||
query.mockImplementation(async (sql: string, values?: unknown[]) => {
|
||||
const text = String(sql);
|
||||
if (text.startsWith('UPDATE public.main_system_price_qty_unit_deferred')) {
|
||||
intentStatuses.push(values?.[1]);
|
||||
return { rowCount: 1, rows: [] };
|
||||
}
|
||||
if (text.includes('FROM public.main_system_price_qty_unit_deferred')) {
|
||||
return { rowCount: 1, rows: [intent] };
|
||||
}
|
||||
// 事件处理器按 request_id 找到那条**待审改量**台账行
|
||||
if (text.includes('FROM public.main_system_price_qty_requests') && text.includes('request_id = $2')) {
|
||||
return { rowCount: 1, rows: [ledgerRow({ kind: 'qty', proposed_qty: 12, unit: null, status: 'pending' })] };
|
||||
}
|
||||
if (text.includes('SELECT 1 FROM public.main_system_price_qty_requests')) {
|
||||
return { rowCount: 0, rows: [] }; // 补发前提①:此刻已无 pending
|
||||
}
|
||||
if (text.startsWith('DELETE FROM public.main_system_price_qty_requests')) {
|
||||
return { rowCount: 0, rows: [] };
|
||||
}
|
||||
if (text.startsWith('INSERT INTO public.main_system_price_qty_requests')) {
|
||||
ledgerInserts.push(values || []);
|
||||
return { rowCount: 1, rows: [ledgerRow({ kind: 'qty', unit: '件' })] };
|
||||
}
|
||||
if (text.startsWith('UPDATE public.main_system_price_qty_requests')) {
|
||||
return { rowCount: 1, rows: [ledgerRow({ kind: 'qty' })] };
|
||||
}
|
||||
if (text.includes('FROM order_items')) {
|
||||
// 提交路径(带 SELECT price)与补发读单位路径都返回"库里已是新单位件"
|
||||
return { rowCount: 1, rows: [{ price: 5, quantity: 10, unit: '件', item_name: '土豆', sku_code: 'SKU1' }] };
|
||||
}
|
||||
if (text.includes('FROM public.main_system_order_imports')) {
|
||||
return { rowCount: 1, rows: [{ main_order_code: 'ORD_WEB_X' }] };
|
||||
}
|
||||
if (text.includes('FROM public.main_system_order_import_items')) {
|
||||
return { rowCount: 1, rows: [{ prep_id: 'prep-1', main_order_code: 'ORD_WEB_X' }] };
|
||||
}
|
||||
return { rowCount: 0, rows: [] };
|
||||
});
|
||||
submit.mockResolvedValue({
|
||||
kind: 'ok',
|
||||
requestId: 'MS-REQ-RESEND',
|
||||
status: 'applied',
|
||||
reviewRequired: false,
|
||||
finalPrice: null,
|
||||
finalQty: 10,
|
||||
message: '值与当前一致,无需审核',
|
||||
raw: {},
|
||||
});
|
||||
|
||||
const handled = await handlePriceQtyDecidedEvent({
|
||||
branchCode: BRANCH,
|
||||
payload: { request_id: 'MS-REQ-1', kind: 'qty', decision: 'rejected', reason: '审核不通过', final_value: null },
|
||||
});
|
||||
expect(handled.status).toBe('done');
|
||||
expect(String(handled.reason)).toContain('驳回');
|
||||
|
||||
// ① 补发:仍走"数量不变的载体",只报单位
|
||||
await vi.waitFor(() => expect(submit).toHaveBeenCalledTimes(1));
|
||||
const call = submit.mock.calls[0][0] as any;
|
||||
expect(call.proposedQty, '载体 = 该行当前数量(不变)').toBe(10);
|
||||
expect(call.proposedPrice).toBeNull();
|
||||
expect(call.unit).toBe('件');
|
||||
expect(String(call.reason)).toContain('单位变更补报');
|
||||
// ② 幂等键确定性(同一意图重复触发 ⇒ 命中台账唯一键,不重复上报)
|
||||
const inserted = ledgerInserts[0];
|
||||
expect(inserted?.[1], 'client_request_id').toBe('unit-deferred-intent-9');
|
||||
expect(inserted?.[6], 'kind').toBe('qty');
|
||||
expect(Number(inserted?.[10]), 'proposed_qty').toBe(10);
|
||||
expect(inserted?.[11], 'unit').toBe('件');
|
||||
// ③ 意图收敛为 sent
|
||||
expect(intentStatuses).toContain('sent');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
/**
|
||||
* 单位变更「跳过」的定向补发(2026-10-13,开发者选 A;设计文 §11.8)。
|
||||
*
|
||||
* 主系统回执 §10.2-3 指出「跳过 ≠ 排队」:某行有待审改量时改单位 ⇒ 本次不报(否则顶掉待审改量),
|
||||
* 而那条待审若被驳回,单位变更就永久丢了。本文件钉住模块自身的三条语义:
|
||||
* · ⑧ 仍有 pending ⇒ **不补发**(保守:任何 kind 的 pending 都挡住),保持 `waiting`;
|
||||
* · ⑨ 幂等:补发成功后再触发 ⇒ 不再发(意图已 `sent`,确定性幂等键兜第二层);
|
||||
* · ⑩ 单位已改回旧值 ⇒ 标 `noop`,**不发 HTTP**;
|
||||
* 另加:连试上限 ⇒ `abandoned`、清扫按分公司遍历、记录侧 upsert 语义(再次跳过就地刷新)。
|
||||
*
|
||||
* 接线(跳过时记意图、决策落定后补发)在 `mainSystemPriceQtyRequest.test.ts` 的用例 ⑥⑦ 里钉。
|
||||
*/
|
||||
|
||||
const query = vi.hoisted(() => vi.fn());
|
||||
const submitPriceQty = vi.hoisted(() => vi.fn());
|
||||
const enabled = vi.hoisted(() => ({ value: true }));
|
||||
const listBranches = vi.hoisted(() => vi.fn());
|
||||
const withTenantData = vi.hoisted(() => vi.fn());
|
||||
const audit = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock('../src/db', () => ({
|
||||
pool: { query: (...args: unknown[]) => query(...args), connect: vi.fn() },
|
||||
getRawPoolQuery: () => query,
|
||||
}));
|
||||
// 只桩掉"提交"这一个出口:补发形态(载体)由参数断言,提交内部的语义在另一个文件里钉
|
||||
vi.mock('../src/services/mainSystemPriceQtyRequest', () => ({
|
||||
isEnabled: () => enabled.value,
|
||||
submitPriceQtyRequest: (...args: unknown[]) => submitPriceQty(...args),
|
||||
}));
|
||||
vi.mock('../src/services/tenantSchemaService', () => ({
|
||||
runWithTenantDataAccess: (...args: unknown[]) => withTenantData(...args),
|
||||
}));
|
||||
vi.mock('../src/services/platformBranch', () => ({
|
||||
listActiveBranchCodes: () => listBranches(),
|
||||
}));
|
||||
vi.mock('../src/services/auditService', () => ({
|
||||
writeAuditLog: (...args: unknown[]) => audit(...args),
|
||||
}));
|
||||
|
||||
import {
|
||||
flushDeferredUnitResendForPrep,
|
||||
recordDeferredUnitResend,
|
||||
sweepDeferredUnitResends,
|
||||
} from '../src/services/mainSystemUnitDeferredResend';
|
||||
|
||||
const BRANCH = 'SUP37831443';
|
||||
const PREP = 'prep-1';
|
||||
|
||||
function makeIntent(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: 'intent-1',
|
||||
branch_code: BRANCH,
|
||||
prep_id: PREP,
|
||||
main_order_code: 'ORD_WEB_X',
|
||||
our_order_code: 'ORD_API_20261009_SUP37831443_0001',
|
||||
our_order_item_id: '11111111-2222-3333-4444-555555555555',
|
||||
before_unit: '斤',
|
||||
target_unit: '件',
|
||||
status: 'waiting',
|
||||
attempts: 0,
|
||||
last_error: null,
|
||||
deferred_at: '2026-10-13T05:00:00.000Z',
|
||||
resolved_at: null,
|
||||
updated_at: '2026-10-13T05:00:00.000Z',
|
||||
payload: {},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
/** 内存里的"一条意图":UPDATE 会真的改它的状态,便于断言幂等与收敛 */
|
||||
let intent: ReturnType<typeof makeIntent> | null = null;
|
||||
let hasPending = false;
|
||||
let itemUnit: string | null = '件';
|
||||
let tenantReadFails = false;
|
||||
|
||||
beforeEach(() => {
|
||||
intent = makeIntent();
|
||||
hasPending = false;
|
||||
itemUnit = '件';
|
||||
tenantReadFails = false;
|
||||
enabled.value = true;
|
||||
query.mockReset();
|
||||
submitPriceQty.mockReset();
|
||||
listBranches.mockReset();
|
||||
withTenantData.mockReset();
|
||||
audit.mockReset();
|
||||
audit.mockResolvedValue(undefined);
|
||||
|
||||
query.mockImplementation(async (sql: string, values?: unknown[]) => {
|
||||
const text = String(sql);
|
||||
if (text.startsWith('UPDATE public.main_system_price_qty_unit_deferred')) {
|
||||
if (intent) {
|
||||
intent = {
|
||||
...intent,
|
||||
status: String(values?.[1] || intent.status) as typeof intent.status,
|
||||
last_error: values?.[2] != null ? String(values[2]) : null,
|
||||
attempts: values?.[4] != null ? Number(values[4]) : intent.attempts,
|
||||
target_unit: values?.[3] != null ? String(values[3]) : intent.target_unit,
|
||||
} as typeof intent;
|
||||
}
|
||||
return { rowCount: 1, rows: [] };
|
||||
}
|
||||
if (text.includes('FROM public.main_system_price_qty_unit_deferred')) {
|
||||
// ⚠️ 桩必须尊重 `status = 'waiting'` 过滤,否则"已 sent 的意图还会被再捞出来"(幂等用例会假绿)
|
||||
const wantsWaiting = text.includes("status = 'waiting'");
|
||||
const hit = intent && (!wantsWaiting || intent.status === 'waiting');
|
||||
return hit ? { rowCount: 1, rows: [{ ...intent }] } : { rowCount: 0, rows: [] };
|
||||
}
|
||||
if (text.includes('SELECT 1 FROM public.main_system_price_qty_requests')) {
|
||||
return hasPending ? { rowCount: 1, rows: [{}] } : { rowCount: 0, rows: [] };
|
||||
}
|
||||
return { rowCount: 0, rows: [] };
|
||||
});
|
||||
withTenantData.mockImplementation(async (_branch: string, fn: (client: unknown) => unknown) => {
|
||||
if (tenantReadFails) throw new Error('租户库读失败');
|
||||
return fn({
|
||||
query: async () => ({ rowCount: itemUnit === null ? 0 : 1, rows: itemUnit === null ? [] : [{ unit: itemUnit, quantity: 10 }] }),
|
||||
});
|
||||
});
|
||||
submitPriceQty.mockResolvedValue({
|
||||
kind: 'ok',
|
||||
row: { id: 'ledger-1' },
|
||||
status: 'applied',
|
||||
reviewRequired: false,
|
||||
finalPrice: null,
|
||||
finalQty: 10,
|
||||
pendingFields: {},
|
||||
message: '值与当前一致,无需审核',
|
||||
appliedLocally: false,
|
||||
applyNote: null,
|
||||
});
|
||||
});
|
||||
|
||||
describe('单位变更定向补发(§11.8)', () => {
|
||||
const src = readFileSync(path.join(__dirname, '../src/services/mainSystemUnitDeferredResend.ts'), 'utf8');
|
||||
|
||||
it('⑧ 仍有 pending(任何 kind)⇒ 不补发、保持 waiting、不发 HTTP', async () => {
|
||||
hasPending = true;
|
||||
const outcome = await flushDeferredUnitResendForPrep({ branchCode: BRANCH, prepId: PREP, trigger: 'decided' });
|
||||
expect(outcome.kind).toBe('blocked');
|
||||
expect(String(outcome.reason)).toContain('待审');
|
||||
expect(submitPriceQty).not.toHaveBeenCalled();
|
||||
expect(intent?.status, '仍是待补发').toBe('waiting');
|
||||
expect(intent?.attempts, '前提不成立不计尝试次数').toBe(0);
|
||||
});
|
||||
|
||||
it('⑧b pending 清掉后(清扫触发)⇒ 补发一次,载体=当前数量+当前单位', async () => {
|
||||
hasPending = false;
|
||||
const outcome = await flushDeferredUnitResendForPrep({ branchCode: BRANCH, prepId: PREP, trigger: 'sweep' });
|
||||
expect(outcome.kind).toBe('sent');
|
||||
expect(submitPriceQty).toHaveBeenCalledTimes(1);
|
||||
const call = submitPriceQty.mock.calls[0][0] as any;
|
||||
expect(call.proposedUnit).toBe('件');
|
||||
expect(call.beforeUnit).toBe('斤');
|
||||
expect(call.proposedQty, '数量维度不传 ⇒ 走"只改单位"的载体').toBeUndefined();
|
||||
expect(call.proposedPrice).toBeUndefined();
|
||||
expect(call.clientRequestId, '确定性幂等键').toBe('unit-deferred-intent-1');
|
||||
expect(String(call.reason)).toContain('单位变更补报');
|
||||
expect(intent?.status).toBe('sent');
|
||||
});
|
||||
|
||||
it('⑨ 幂等:补发成功后再触发 ⇒ 不再发(意图已 sent;确定性幂等键兜第二层)', async () => {
|
||||
const first = await flushDeferredUnitResendForPrep({ branchCode: BRANCH, prepId: PREP, trigger: 'decided' });
|
||||
expect(first.kind).toBe('sent');
|
||||
const second = await flushDeferredUnitResendForPrep({ branchCode: BRANCH, prepId: PREP, trigger: 'sweep' });
|
||||
expect(second.kind).toBe('none');
|
||||
expect(submitPriceQty).toHaveBeenCalledTimes(1);
|
||||
// 幂等键由意图行 id 派生(不是随机 uuid)⇒ 即便并发重放也命中台账唯一键
|
||||
expect(src).toContain('clientRequestId: `unit-deferred-${intent.id}`');
|
||||
});
|
||||
|
||||
it('⑩ 单位已改回旧值 ⇒ noop,不发 HTTP(不必补报)', async () => {
|
||||
itemUnit = '斤';
|
||||
const outcome = await flushDeferredUnitResendForPrep({ branchCode: BRANCH, prepId: PREP, trigger: 'decided' });
|
||||
expect(outcome.kind).toBe('noop');
|
||||
expect(submitPriceQty).not.toHaveBeenCalled();
|
||||
expect(intent?.status).toBe('noop');
|
||||
});
|
||||
|
||||
it('⑩b 我方订单行已不存在 ⇒ abandoned(收敛,不无限重试)', async () => {
|
||||
itemUnit = null;
|
||||
const outcome = await flushDeferredUnitResendForPrep({ branchCode: BRANCH, prepId: PREP, trigger: 'sweep' });
|
||||
expect(outcome.kind).toBe('abandoned');
|
||||
expect(intent?.status).toBe('abandoned');
|
||||
});
|
||||
|
||||
it('⑩c 提交一直被挡(主系统不可用)⇒ 连试到上限就 abandoned + 留错误', async () => {
|
||||
intent = makeIntent({ attempts: 4 });
|
||||
submitPriceQty.mockResolvedValue({ kind: 'failed', reason: '主系统不可用', retryable: true });
|
||||
const outcome = await flushDeferredUnitResendForPrep({ branchCode: BRANCH, prepId: PREP, trigger: 'sweep' });
|
||||
expect(outcome.kind).toBe('abandoned');
|
||||
expect(intent?.status).toBe('abandoned');
|
||||
expect(String(intent?.last_error)).toContain('人工');
|
||||
});
|
||||
|
||||
it('① 记录侧:单位没变 ⇒ 不建意图(skipped)', async () => {
|
||||
const r = await recordDeferredUnitResend({
|
||||
branchCode: BRANCH,
|
||||
prepId: PREP,
|
||||
ourOrderCode: 'ORD_X',
|
||||
beforeUnit: '斤',
|
||||
targetUnit: '斤',
|
||||
});
|
||||
expect(r.kind).toBe('skipped');
|
||||
expect(query).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('② 记录侧:upsert(同一行只留最新意图,再次跳过就刷新并归零尝试)', async () => {
|
||||
const r = await recordDeferredUnitResend({
|
||||
branchCode: BRANCH,
|
||||
prepId: PREP,
|
||||
ourOrderCode: 'ORD_X',
|
||||
ourOrderItemId: '11111111-2222-3333-4444-555555555555',
|
||||
beforeUnit: '斤',
|
||||
targetUnit: '箱',
|
||||
});
|
||||
expect(r.kind).toBe('recorded');
|
||||
const call = query.mock.calls[0];
|
||||
expect(String(call[0])).toContain("ON CONFLICT (branch_code, prep_id) WHERE status = 'waiting'");
|
||||
expect(String(call[0])).toContain('attempts = 0');
|
||||
const values = call[1] as unknown[];
|
||||
expect(values[5]).toBe('斤');
|
||||
expect(values[6]).toBe('箱');
|
||||
});
|
||||
|
||||
it('①b 开关关掉 ⇒ 不补发(不发 HTTP、保持 waiting)', async () => {
|
||||
enabled.value = false;
|
||||
const outcome = await flushDeferredUnitResendForPrep({ branchCode: BRANCH, prepId: PREP, trigger: 'sweep' });
|
||||
expect(outcome.kind).toBe('blocked');
|
||||
expect(submitPriceQty).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('清扫:按分公司遍历 waiting 意图并汇总', async () => {
|
||||
listBranches.mockResolvedValue([BRANCH]);
|
||||
const result = await sweepDeferredUnitResends({ limit: 50 });
|
||||
expect(result.branches).toBe(1);
|
||||
expect(result.scanned).toBe(1);
|
||||
expect(result.sent).toBe(1);
|
||||
expect(result.abandoned).toBe(0);
|
||||
expect(submitPriceQty).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user