feat(main-system): 免入库单取货链路 + 实收数量「事实登记 + 事后同步」
免入库(主系统骑手上门取货): - 50 展示「待取货」、副文案「待主系统骑手上门取货」、不建我方配送任务(守卫与开关解耦) - 我方 50 即回写备货完成;两开关(SKIP_INBOUND_AWAIT_PICKUP / FULFILLMENT_EVENTS)改默认开 核货事实镜像(「核货完毕」标记): - 按主系统 lookup 的 actual_qty 落台账,新增 GET/POST /orders/:orderCode/main-system-prep-facts[/refresh] - 详情行内显示「核货完毕」(含核货量),分配对账兜底刷新 实收数量/单位口径变更(对方先改 + 我方事后同步): - 台账加 applied_at;inbound 与 picking_check 同为事实登记(驳回不回滚) - 同意才落我方值:免入库改装车核货量、送仓改验收实收(已入库走既有库存调整)、已结算/已结案只留痕 - 计划量与金额一起改,并同步结算投影(syncStatementsForOrderSafe) - 审核页语义改「主系统实际值(已生效)/ 是否同步」+ 已处理历史(双方时间与落值结论) 台账对照与回写修复: - 行级对照改整单一次性(同名商品不再重复认领)+ 存量纠正 healOrderPrepMapping - 堵住客户绑定回填旁路(免入库单不再被派我方骑手) - 回写触发函数改对象参数(修 branch/order 传反导致的静默不回写) 文档:设计文档 4 篇 +《给主系统 AI 的对接改造清单》§2.9(第六批契约) 回归:服务端全量与 HEAD 基线一致(24 个失败文件同集合);前端 140 文件 / 699 测试全绿;tsc 双端干净
This commit is contained in:
@@ -0,0 +1,457 @@
|
||||
# 主系统分配单:按配送日合并、缺货流转、禁止删除(2026-10-10)
|
||||
|
||||
> 开发者当轮定稿的四条口径(逐条对应下方设计):
|
||||
> 1. **不能是 6 个订单** —— 同一**配送日**的全部分配行合成**一张**本系统订单;
|
||||
> 2. 客户区分:暂时把**主系统订单号写进明细备注**(主系统开放接口不回传客户,已列入给主系统 AI 的清单);
|
||||
> 3. 主系统来的订单**不能删订单、不能删商品**,只保留一个**缺货**按钮 ⇒ 报主系统 `status=40`(转自采)+ 我方该行标记缺货、从待备货里剔除;
|
||||
> 4. 删除限制**前端 + 后端 + 通用数据网关旁路**三层都要拦。
|
||||
|
||||
## 1. 改前事实(实测,2026-10-10)
|
||||
|
||||
| # | 事实 | 证据 |
|
||||
|---|---|---|
|
||||
| F1 | 一张主系统订单 = 一张本系统订单 | 订单列表出现 6 张 `ORD_API_20261008_SUP37831443_0002…0007`,客户都是同一个占位客户 `MAIN_SUP37831443`,配送日全是 2026-10-09 |
|
||||
| F2 | 主系统开放接口的行里**没有客户** | `supplierPreparationOpenApiShape.ts` 只回 `order_code/delivery_date/item_name/prepare_qty/purchase_price/skip_inbound/is_direct_delivery…`,无 `customer_code`/`customer_name` |
|
||||
| F3 | 主系统 `POST /preparations/status` 的 **`status=40` 就是「供应商报缺货 → 转自采」** | 主系统 `supplierPreparationStatusService`:`if (status === 40) { … transferPreparationStockoutToPurchase({ prepId, stockoutReason }) }`;接口另收 `stockout_reason` |
|
||||
| F4 | 我方已有同一套缺货原语(克隆自同源) | 本仓 `src/services/preparationStockoutService.ts`:`transferPreparationStockoutToPurchase` 会把备货行置 `prepare_status=40 / is_stockout / transferred_to_purchase`,并把原采购单 `purchase_status=40` |
|
||||
| F5 | 订单删除走专用路由;通用网关可裸删 | `POST /orders/delete → moveOrderToTrash`;通用数据网关只有 `DENY_DELETE_TABLES = {customers}`,`orders`/`order_items` 不在其中 |
|
||||
|
||||
## 2. 设计
|
||||
|
||||
### 2.1 合并键:`(分公司, 配送日)`
|
||||
|
||||
新增日级占坑表(平台表,`public`):
|
||||
|
||||
```
|
||||
public.main_system_daily_order_imports (
|
||||
branch_code, delivery_date, our_order_code, created_at, updated_at,
|
||||
UNIQUE (branch_code, delivery_date)
|
||||
)
|
||||
```
|
||||
|
||||
- 导入时先把主系统备货行**按 `delivery_date` 分组**(缺失时退回 `task_day`),每个配送日一张本系统订单;
|
||||
- 占坑语义沿用建单那条已经验证过的做法:`INSERT … ON CONFLICT (branch_code, delivery_date) DO UPDATE … WHERE our_order_code IS NULL AND created_at < now() - interval '10 minutes' RETURNING id`,
|
||||
占不到坑且已有单号 ⇒ 该日订单已存在,转「行级追加」;占不到坑且**没有**单号(说明另一次导入正在建单)⇒ 本轮跳过,下轮再来;
|
||||
- 建单成功后回填 `our_order_code`;崩溃遗留的「无单号坑位」10 分钟后可被重新占用(不会永久卡单)。
|
||||
|
||||
订单号仍由 `allocateOrderCode({ channel: 'API', branchCode })` 生成(不改单号规则),客户仍是占位客户 `MAIN_<分公司>`。
|
||||
|
||||
### 2.2 来源主系统订单:落列 + 详情两级分组(**2026-10-10 改版**)
|
||||
|
||||
> 首版把主系统单号写进了 `order_items.remark`;开发者看到界面后否决:**"别整成备注"**,
|
||||
> 要一级按订单、二级按分类地分组区分。改版如下。
|
||||
|
||||
- **行属性**:`order_items.main_order_code`(新列,migration `20261015`)记「这一行来自哪张主系统订单」。
|
||||
为什么是列:备注是业务字段;而详情表是前端直连 `order_items`(`select('*')`),
|
||||
平台台账 `public.main_system_order_import_items` 前端根本读不到。原生录单/手加行该列为 NULL。
|
||||
- **详情表两级分组**(开关「按订单分组」,**默认开启**):一级 = 主系统订单(显示单号),二级 = 商品分类;
|
||||
无来源的行归到「本系统录单」并排在最后。开关关闭 ⇒ 退回原来的"只按分类"。
|
||||
- 落列时机:建单/追加后按「商品名 + 出现次序」写一次(只补 `IS NULL`,幂等);
|
||||
**存量行**由每轮对账**惰性补齐**(迁移回填不了:迁移无租户上下文 + FORCE RLS ⇒ 0 行)。
|
||||
- 整单台账 `public.main_system_order_imports` **保持一行一张主系统订单**,合并后**多行指向同一个 `our_order_code`**;
|
||||
行级台账 `main_system_order_import_items` 不变(`prep_id` 唯一),照旧承担退货跟随与回写的定位。
|
||||
- **同商品不并行**:同一商品来自两张主系统单 ⇒ 我们这边**两行**。理由:退货红冲与发车回写按**主系统备货行**定位,并成一行就分不清该冲哪一行。
|
||||
|
||||
### 2.3 缺货流转(详情页「缺货」按钮)
|
||||
|
||||
> ⚠️ **语义澄清(开发者 2026-10-10 追加)**:这条链路调的是**主系统给供应商的接口**,
|
||||
> 转的是 **主系统自采**(主系统自己去买),**不是子系统自采**。
|
||||
> 所以我方**只许把这一行连同它自己的待处理采购/备货一起清掉**,**绝不允许**新建采购单;
|
||||
> 本仓 `preparationStockoutService.transferPreparationStockoutToPurchase` 是「我方供货商供不了 ⇒ 我们改自采」
|
||||
> 的**另一套语义**(会 INSERT 采购单),**本流程禁止调用**(单测已钉:`INSERT INTO purchase_orders` 断言为「不得出现」)。
|
||||
|
||||
1. 先在行级台账按 `our_order_item_id` 找到 `prep_id`(找不到则按商品名惰性对照一次);找不到 ⇒ 409「该明细不是主系统分配的,不能用缺货」;
|
||||
2. 报主系统 `POST /preparations/status { id, status: 40, stockout_reason }`(复用既有 `writebackMainSystemPreparationStatus`,新增可选 `stockoutReason`);
|
||||
3. 主系统成功(`updated>=1`,或返回 `already_completed`/`transferred_to_purchase` 这类"结果已达成")后,**在同一个事务里**收口我方履约:
|
||||
- **把这一行从本地清掉**(开发者 2026-10-10 追加:「点击缺货了,它就不该存在于本地的订单中,
|
||||
包括本地的自采单与备货单里都不该存在这个」):
|
||||
先按既有「取消履约」判据确认还能硬删(`orderItemHasInspectionInbound` /
|
||||
`orderItemHasCompletedPreparation` / `orderItemHasCompletedPurchase` 三条都为假),
|
||||
再复用 `removeOrderItemForMainSystemReturn` 删订单行 **+ 它的待处理采购/备货/履约行**
|
||||
(该原语同事务内还写红冲依据留痕、建"取消履约"售后单并重算受影响结算);
|
||||
- 删行后**重算订单头金额/重量**(口径与「改明细」一致:未退货行 `amount` 之和 + `sumWeightInJin`)——
|
||||
既有的独立删行入口都不重算,缺货是新流程,不能一上线就让列表金额挂着已删的商品;
|
||||
- 台账记 `disposition='skipped_stockout'` + 原因(退货跟随只处理 `imported` 行 ⇒ 不会再来红冲这张已不存在的行;
|
||||
同时 `our_order_item_id` 保留指向已删行 ⇒ 下一轮对账不会把这行又"补"回来);
|
||||
- **已有货物事实的行不给"缺货"**(已入库/备货完成/采购完成 ⇒ 409 让走售后退货),绝不悄悄改成红冲;
|
||||
- 幂等:我方已标缺货的行(含改造前只打标签没删行的历史行)再点 ⇒ **不重复发 HTTP,但仍做本地清理**;
|
||||
- **操作日志必须留痕**(开发者 2026-10-10:「操作日志需要记录点击过缺货」):
|
||||
写 `operation_logs.operation_type = 'main_system_stockout'`(`action_category='order'`,`target_table='order_items'`),
|
||||
`old_value` = 行快照(品名/sku/数量/单位/售价/金额)+ 订单号,
|
||||
`new_value` = `{ main_order_code, prep_id, reason, main_system_status:40, already_reported, trigger, local_removal }`;
|
||||
`trigger='user'`(详情页点击,带操作人/角色/IP)或 `trigger='reconcile'`(对账自动跟随,操作人为空 = 系统);
|
||||
`local_removal` = `removed` / `missing`(重复点击、本地已清)/ `blocked`(有货物事实未剔除)。写失败不阻断主流程;
|
||||
4. 主系统不可用(5xx/超时)⇒ 不落任何本地状态,返回可重试错误;重复点击 ⇒ 幂等(台账已有 `stockout_reported_at` 直接返回成功);
|
||||
5. **不动金额**:该行售价/金额是否清零属财务口径,本次不改(见 §6)。
|
||||
|
||||
### 2.4 禁止删除(三层)
|
||||
|
||||
| 层 | 改法 |
|
||||
|---|---|
|
||||
| 列表页 | 主系统订单那行**不渲染「删除」**(后端列表接口新增 `is_main_system_order` 标记,前端据此判断,不用猜客户编码前缀) |
|
||||
| 详情页 | 主系统订单**不渲染「删除明细」**;同一位置显示「缺货」按钮(未缺货且未红冲的行才可点) |
|
||||
| 后端(订单) | `moveOrderToTrash` 前置守卫:该订单在 `main_system_order_imports` 里有对照 ⇒ 409 `main_system_order_locked`(订单不能删) |
|
||||
| 后端(明细) | `syncOrderManageItems` 前置守卫:主系统订单的**既有行不得从入参里消失** ⇒ 409(商品不能删);退货跟随仍可红冲(它不走这条链路) |
|
||||
| 通用网关 | `DENY_DELETE_TABLES` 增加 `orders`、`order_items` —— 删订单/删明细只能走带守卫与级联的专用路由(与 `customers` 同一处置) |
|
||||
|
||||
### 2.5 自动跟随:主系统转走 ⇒ 本地不该存在(**2026-10-10 追加口径**)
|
||||
|
||||
> 开发者原话:「只需主系统那边是转移了、没有再次分配给这个供应商,那么本地就不该存在」。
|
||||
|
||||
不能只靠详情页那个按钮(要有人盯着界面才点得到),主系统那边的流转随时发生;本地挂着一行
|
||||
"其实已经不属于我们"的商品会一直卡在"未完成采购"里。所以在**导入对账收尾**加了一步
|
||||
(`settleRowsNoLongerOurs`,定时对账每轮跑,无需开关):
|
||||
|
||||
**判据**(`isPreparationNoLongerOurs`,来自真实主系统对"被转自采的蚝油行"的实测):
|
||||
|
||||
| 观测 | 结论 |
|
||||
|---|---|
|
||||
| 该行**已不在** `view=active`,且 `lookup`:`found=true` + **`prepare_status=40`** | 主系统把它**转自采**了(主系统 `transferPreparationStockoutToPurchase` 落的就是 40)⇒ 本地剔除 |
|
||||
| 该行已不在 active,且 `lookup`:`reassigned=true` 且 `current_supplier_code ≠ 我们` | 被**改派**给别人(含 `INTERNAL`)⇒ 本地剔除 |
|
||||
| `found=false`(行被删了) | **不认**:退货/取消交给开关控制的退货跟随去判,避免把退货误当缺货清掉 |
|
||||
| 还在我们名下(st=10/20/30) | 不动 |
|
||||
|
||||
**剔除动作**与按钮完全共用 `removeLocalLineForStockout`(删订单行 + 它的待处理采购/备货/履约 + 重算订单头;
|
||||
已有货物事实的行不删、只记一行日志)。
|
||||
|
||||
**"又分配回来"会自动补回**:剔除时把台账对照清掉并记 `skipped_stockout`
|
||||
(`markPrepStockoutRemoved`);只要该行重新出现在 active 里,导入侧就会重新建行,
|
||||
`recordImportedPrepItems` 的 CASE 会把处置**复位为 `imported`**(新增分支,条件 = 本次真的配到了订单行)。
|
||||
反过来,只要它还在"已转自采"状态(不在 active),就什么都不会发生。
|
||||
|
||||
**成本**:只对"台账说 imported(我们建了行)**且**本轮 active 里已经没有"的行做 lookup,
|
||||
通常只有极少数行;没有候选就一次 HTTP 都不发;`lookup` 不可用时整步跳过(宁可下一轮再说,不凭猜删数据)。
|
||||
|
||||
### 2.6 客户口径:**主系统就是子系统的客户**(2026-10-10 最终口径)
|
||||
|
||||
> 开发者原话:「需要这个 —— 相当于主系统就是子系统的客户,这个设计是没有问题的;
|
||||
> 后续主系统给子系统的订单,相当于默认就是这个客户下的单,这样就好确保流程正常。」
|
||||
|
||||
- 每个分公司一行客户:`MAIN_<分公司>`,名称「主系统订单(<分公司>)」,**它就是"主系统"这个客户**;
|
||||
主系统分配过来的订单**默认挂在这个客户名下**——与录单必填客户、订单/结算/客户对账按
|
||||
`customer_code` 归集完全一致,整条流程(录单 → 备货 → 验收 → 分拣 → 配送 → 结算)不需要任何特例分支。
|
||||
- 因此该客户在**客户管理、客户下拉、统计与结算里正常展示、正常参与**;
|
||||
`customers.source = 'main_system'` 只作**来源区分**(便于报表区分"主系统客户"与本地客户),**不用于隐藏**。
|
||||
- **决策留痕**:中间曾按"隐藏式技术占位"实现(客户管理/下拉/筛选过滤掉它),开发者随后澄清并撤回该方案;
|
||||
撤回记录见 `migrations/20261017_customers_source_comment.sql`。
|
||||
- 该客户的两个坑(已修,见 §8.1):建号时状态必须落在客户状态域 `10/20/30/40/50` 内(曾错写 1 → 客户页白屏)。
|
||||
|
||||
### 2.7 客户名与送货地址(开发者 2026-10-10 口径,分两步落地)
|
||||
|
||||
> 「将名字改为 **主系统下单的那家公司的名字加上编号**(避免已经存在一样的客户)作为这个客户名。」
|
||||
> 「主系统下单,子系统这边看到的应该是送到 **主系统分公司的仓库地址**;如果没有,就等操作员自己填;
|
||||
> 后面主系统要是还没填,因为在子系统眼中就是一个客户,**用上次填写的就行**。」
|
||||
|
||||
**第一步(本次已落地,不需要主系统配合)**
|
||||
- 备货行的 `branch_code`(**主系统其实一直在回,只是 webhook 会剥掉**)接进我方模型,随行快照落台账 —— 为"按下单分公司建客户"备好数据;
|
||||
- **地址复用链**:导入建单时按 ① 客户档案 `customers.address` → ② 该客户**最近一张填过地址的订单**;
|
||||
命中 ② 就**回写客户档案**("这个客户的地址应该是已经存在了的"),都没有则留空等操作员在订单里填。
|
||||
|
||||
**第二步(主系统 P1-10 已交付;见 `docs/给主系统AI的对接改造清单.md`)**
|
||||
- ✅ **默认送货地址 = `branch_address`**(2026-10-11 落地,见 §8.3):仓库地址 → 客户档案 → 上次填写的 → 空;
|
||||
- ✅ 客户从"一个分公司一个"升级为"**一个主系统下单分公司一个**",**客户名 = 分公司名**(开发者 2026-10-11 定稿:
|
||||
「主系统的分公司名字就是客户名字」),客户编码 `MAIN_<分公司编码>`;名字被别的客户占用才加 `-2`/`-3` ——
|
||||
2026-10-11 落地,见 §8.4;
|
||||
- ✅ 存量订单按台账 `main_branch_code` / 主系统单号里的 `…_BR002_…` 段回填归属(只动我们自己库)——2026-10-11 已执行,见 §8.4。
|
||||
|
||||
## 3. 影响面
|
||||
|
||||
| 面 | 影响 | 处置 |
|
||||
|---|---|---|
|
||||
| 退货跟随 | 台账键不变(按 `prep_id`),合并只改 `our_order_code` 指向 | 不改判定矩阵;`unknown`/`suspended` 语义不变 |
|
||||
| 发车回写 | 按 `prep_id` 定位 | 不变 |
|
||||
| 同商品多主系统单 | 我们这边多行、每行一个备注 | 已知代价,换红冲可定位(§2.2) |
|
||||
| 原生录单订单 | 无台账行 ⇒ `is_main_system_order=false`、缺货按钮不出现、删除照旧 | 必须保持零影响(验收项 V4) |
|
||||
| 结算/财务 | 合并后一张单多个客户来源,但**客户仍是一个占位客户**,金额口径不变 | 不动财务逻辑 |
|
||||
| 存量数据 | 本地已按"一主系统单一张单"导入的 6 张单不会自动合并 | 本次验收里做一次**本地重置 + 重导**(删我们自己的导入单与台账,主系统数据不动),把 6 张并成 1 张 |
|
||||
|
||||
## 4. 不做的事
|
||||
|
||||
- 不按客户拆单(开发者已选"先按配送日合并 + 备注区分");
|
||||
- 不做部分缺货(主系统整行转自采);
|
||||
- 不把缺货行的金额清零(待财务口径确认);
|
||||
- 不改主系统任何数据(只调它已开放的 `preparations/status`);
|
||||
- 不改前端既有文案(只**移除**两处删除按钮、**新增**一个「缺货」按钮与确认框,文案见 §7 待确认项)。
|
||||
|
||||
## 5. 需要主系统补的(追加到给主系统 AI 的清单)
|
||||
|
||||
| # | 需求 | 为什么 |
|
||||
|---|---|---|
|
||||
| P1-9 | 备货行(`GET /preparations` 与 webhook payload)增加 `customer_code` / `customer_name`(或订单级 `customer_name`) | 合并后一张单里混着多个客户的货,子系统管理员要能按客户区分;现在只能靠主系统订单号 |
|
||||
|
||||
## 6. 待确认(本次不做,先记录)
|
||||
|
||||
- 缺货行在**我方订单金额与结算**里是保留原额、清零、还是单独一栏"缺货扣减";
|
||||
- 缺货后是否需要主系统回传新的采购来源(自采单号)以便我们对账。
|
||||
|
||||
## 7. 验收标准(可执行)
|
||||
|
||||
| # | 验收项 | 判据 |
|
||||
|---|---|---|
|
||||
| V1 | 同一配送日的 N 张主系统单 ⇒ **1 张**本系统订单 | 重导后该配送日只有 1 张 `ORD_API_*`,行数 = 全部未缺货备货行 |
|
||||
| V2 | 明细备注带主系统单号 | 每行 `remark` = `主系统单 ORD_WEB_…`,同商品两行各自带自己的单号 |
|
||||
| V3 | 行级台账仍逐行对照 | 台账行数 = 备货行数,`our_order_item_id` 全部非空且指向合并单里的行 |
|
||||
| V4 | 原生订单零影响 | 原生单 `is_main_system_order=false`;删除按钮照旧;缺货接口拒绝 |
|
||||
| V5 | 缺货按钮 | 报主系统成功 ⇒ 台账 `stockout_reported_at` 有值、该行待处理采购单 `purchase_status=40`、进度不再计"未完成采购";主系统不可用 ⇒ 本地无变化 + 可重试 |
|
||||
| V6 | 禁删(四层) | 列表/详情无删除入口;`POST /orders/delete` 409;改明细漏行 409;`/api/data` 裸删 orders/order_items 被拒 |
|
||||
| V7 | 幂等 | 同一轮对账重复跑不新建单、不重复追加行;缺货重复点不重复转自采 |
|
||||
| V8 | 回归 | `server` 测试套失败集合与基线一致;设计门禁与改造前一致 |
|
||||
|
||||
## 8. 回滚
|
||||
|
||||
- 代码:本次改动集中在导入服务、日级占坑表、两条守卫、一个缺货接口与两处前端按钮;`git revert` 对应文件即可;
|
||||
- 数据:日级占坑表可整表删除(仅记录"哪个配送日已有单"),既有订单与台账不需要回改;
|
||||
- 缺货:已报给主系统的转自采**不可回滚**(主系统侧事实),本地只需恢复采购单状态(`purchase_status` 由 40 改回 10)即可重走流程。
|
||||
|
||||
## 8.1 事故与修复:占位客户 `status=1` 导致客户管理页白屏(2026-10-10)
|
||||
|
||||
**现场**:打开「客户管理」整页白屏,控制台 `Cannot read properties of undefined (reading 'bgColor')`
|
||||
(`CustomerManagement.tsx` 里 `statusMap[c.status || 10].bgColor`)。
|
||||
|
||||
**根因(本次改造引入)**:导入用的占位客户 `MAIN_<分公司>` 建号时写了 `status = 1`
|
||||
(当时按"启用"直觉写的 1),而客户状态域是 **10/20/30/40/50** ⇒ `statusMap[1]` 为 `undefined`。
|
||||
|
||||
**三层修复**:
|
||||
1. 建号改用 `status = 10`(`IMPORT_CUSTOMER_STATUS`);
|
||||
2. **自愈**:每轮导入的每个配送日入口都 `ensureImportCustomer`,发现状态不在域内即改回 10
|
||||
(放在入口而不是只在建单时调用 —— 否则"本轮没有新行"时永远不自愈);
|
||||
3. 前端兜底:`statusMap[c.status || 10] ?? statusMap[10]`,状态值异常只退化为"正常"样式,不再整页白屏。
|
||||
|
||||
**实测**:两个分公司占位客户 `1 → 10`(各跑一轮真实对账即自愈,未手工改库);客户页相关前端测试 8 例全绿。
|
||||
|
||||
## 8.2 环境配置同源(2026-10-10):AI 功能恢复 + 隔离项不变
|
||||
|
||||
**现象**:子系统 AI 功能整体不可用。
|
||||
**根因**:`server/.env` 缺 11 个键 —— `ARK_API_KEY`/`ARK_MODEL`/`ARK_BALANCE_*`(方舟模型)、
|
||||
`VOLC_ACCESS_KEY_ID/SECRET/REGION`(火山 IAM,查余额)、`MP_APPID/APPSECRET`(小程序)、
|
||||
`TENCENT_MAP_KEY/SK`(腾讯位置服务);而代码里这些键都在读 ⇒ 模型调用直接短路。
|
||||
|
||||
**处置**:从主系统 `server/.env` 拷这 11 个键进本系统 `.env`(原文件先备份到仓库外
|
||||
`/home/ubuntu/harness/suppler/.env.backup-<时间戳>`)。**隔离项逐字节核对未被覆盖**:
|
||||
`DATABASE_URL`(`supplier_delivery`)、`PORT`(3022)、`STORAGE_DIR`(`./uploads-supplier`)、
|
||||
`S3_KEY_PREFIX`(`supplier-system`)、`MAIN_SYSTEM_*`;**`JWT_SECRET` 有意不拷**(两边共用会让 token 互认)。
|
||||
|
||||
**实测**:裸模型调用返回正常(`doubao-seed-2-0-lite-260428`,≈1.9 s);录单文本三解析识别出 2 个商品
|
||||
(带 SKU 与分类,≈3.3 s);地图 provider=tencent 且 Key 已配置。
|
||||
|
||||
**文档**:`server/.env` 不随 git(`.gitignore`);11 个键的**登记**(只写名字/默认值/作用,**不含任何值**)
|
||||
已并入让 `check-env-coverage.py` 转绿的那份「环境变量总表」。
|
||||
|
||||
## 8.3 收货地址:主系统分公司仓库地址 + 明细锁后单独改地址(2026-10-11 落地)
|
||||
|
||||
开发者两问:「我需要一个编辑收货地址的功能」「当前分配过来的 是不是没有携带上主系统分公司对应的仓库地址?」
|
||||
|
||||
**事实**:确实是**没带上**。主系统 P1-10 已把 `branch_name` / `branch_address` 随三个视图 + lookup + webhook 下发
|
||||
(其 `supplierPrepFulfillmentSql.ts` 里 `PREP_BRANCH_NAME_SQL = 'b.branch_name'`),但我们一直**没有消费**这两个字段:
|
||||
`MainPreparationRow` 里根本没有,导入时的地址只走「客户档案 → 上次填写的 → 空」三跳,所以主系统分配过来的单**地址恒为空**。
|
||||
|
||||
**本次改动(两条)**:
|
||||
|
||||
| # | 改动 | 落点 |
|
||||
|---|---|---|
|
||||
| 1 | **携带仓库地址**:行模型补 `branchName` / `branchAddress`(拉取 + webhook 同口径);建单时地址优先级改为 **主系统分公司仓库地址 → 客户档案 → 上次填写的 → 空**;命中仓库地址时**只在客户档案地址为空时**补写档案(不覆盖人工维护) | `mainSystem/api/preparations.ts`、`routes/mainSystemIntegration.ts`、`mainSystemOrderImport.ts` |
|
||||
| 2 | **明细锁后也能改地址**:新增 `PATCH /orders/:orderCode/delivery-address`(**只写表头**,不碰明细、不动状态链)。门槛:订单存在、未进垃圾桶、`order_status < 90`;权限与明细编辑同口径(`order_edit`/`order_entry`/`order_manage`/`allocation_manage`,**不限管理员**,与配送日路由有意不同)。留痕 `operation_logs.order_delivery_address_edit` | `orderManageItemsService.updateOrderDeliveryAddress`、`modules/workflow/routes/orderRoutes.ts`、`utils/workflowApi.ts`、`OrderDetailDeliveryNotePanel.tsx`、`OrderManagementPage.tsx` |
|
||||
|
||||
**为什么单独开一条通道**:详情页原来只有一个随 `canEditOrderForStatus` 一起失效的地址输入框,订单一到 40/45/50
|
||||
地址就再也改不了,而"发车前改地址"恰恰是高频动作;走明细保存又会被明细锁挡住。
|
||||
|
||||
**界面**:地址旁给「编辑」按钮(表头锁定时才出现),点开就地变输入框 + 保存/取消 —— 三个按钮**复用既有
|
||||
`common.edit` / `common.save` / `common.cancel` 文案 key,未新增任何小字**。
|
||||
|
||||
**界面纪律**:入口只在 `order_status < 90` 且无编辑权限的表头态下出现(可编辑态沿用原输入框,不重复给按钮);
|
||||
保存有在途锁(`addressSaving` 期间按钮禁用);保存成功后**只就地回填本单 `delivery_address`**,
|
||||
再静默刷新列表,不改变详情 generation 语义。
|
||||
|
||||
**实测(本地真库)**:在 `ORD_API_20261009_SUP37831443_0001`(**order_status=45、地址原本为空、明细已锁**)上
|
||||
调用新通道:改 → 库值变更 + 审计 `order_delivery_address_edit` 记录改前/改后;还原 → 回到 null。探针数据已清理。
|
||||
|
||||
## 8.4 客户口径落地:一个主系统分公司 = 一个客户,客户名 = 分公司名(2026-10-11)
|
||||
|
||||
开发者口径(本轮确认):「**主系统的分公司名字就是客户名字**」,并拍板三点:
|
||||
① 客户编码用 `MAIN_<分公司编码>`(如 `MAIN_BR002`);**名字在子系统里没被占用就不加编号**;
|
||||
② 分公司名称为空时用「主系统分公司 <编码>」兜底;③ **存量订单要改挂**。
|
||||
|
||||
**改前现状(实测)**:我方只有 1 个占位客户 `MAIN_SUP37831443`,名字「主系统订单」,那张主系统单就挂在它名下。
|
||||
|
||||
**改动**:
|
||||
|
||||
| # | 内容 | 落点 |
|
||||
|---|---|---|
|
||||
| 1 | 客户解析改为**按主系统下单分公司**:编码 `MAIN_<BRxxx>`、名字 = 分公司名(空⇒兜底名)、名字被占才加 `-2`/`-3`;客户端**自愈**顺带把名字对齐(分公司改名 ⇒ 下次导入跟着改) | `mainSystemOrderImport.ensureImportCustomer` / `dedupeCustomerName` |
|
||||
| 2 | 一个配送日合并单的归属分公司 = 当日行里**出现次数最多**的 `branch_code`(实测一天一个分公司;真混合时取众数并 `console.warn`,每行分公司仍逐行落台账) | `pickDayMainBranch` |
|
||||
| 3 | 台账补 `main_branch_code` / `main_branch_name`(非空才覆盖,防 webhook 剥字段把已知值抹掉) | 迁移 `20261021_…`、`mainSystemPrepLedger` |
|
||||
| 4 | **存量改挂**:`reattributeMainSystemOrdersToBranchCustomers()` + 一次性脚本(依据:台账 `main_branch_code` → 主系统单号 `_BRxxx_` 段 → 都没有就不动);占位客户在**不再被任何订单引用**时停用(`status=40 禁用`,不删) | `mainSystemOrderImport`、`server/scripts/reattribute-main-system-branch-customers.ts` |
|
||||
|
||||
**实测(本地真库,已执行)**:
|
||||
|
||||
```
|
||||
客户:MAIN_BR002 / 名字「自贡」/ status 10 正常 / source main_system
|
||||
MAIN_SUP37831443 / 「主系统订单」/ status 40 禁用 ← 占位客户已退场
|
||||
订单:ORD_API_20261009_SUP37831443_0001 → customer_code 由 MAIN_SUP37831443 改为 MAIN_BR002
|
||||
```
|
||||
|
||||
**为什么"一天一个分公司"这个前提很重要**:合并键是「(我方分公司, 配送日)」,若某天混了多个下单分公司,
|
||||
"一张单一个客户"就会歧义。实测近 8 天(10-08 起)**每天都是 1 个(BR002:自贡)**;真出现混合时按众数归属并告警,
|
||||
不会静默丢数据(每行的分公司逐行在台账里)。
|
||||
|
||||
## 8.5 备齐回写补缺:未启用分拣时进入待配送也要回写 `status=30`(2026-10-11)
|
||||
|
||||
开发者问:「子系统商品分拣完毕;**如果没有开启分拣**,订单就是进入了待配送 —— 相当于主系统订单里这些商品
|
||||
就是备货完成。这个设置存在吧?」核对结论:**逻辑存在,但缺了一个入口**。
|
||||
|
||||
**三条进入 50(待配送)的路径与回写覆盖**:
|
||||
|
||||
| 路径 | 进入 50 的位置 | 备齐回写(`status=30`) |
|
||||
|---|---|---|
|
||||
| 分拣已完成 | `tryAdvanceOrderToDelivery`(分拣启用分支) | ✅ 由分拣服务在完成后调 `enqueueMainSystemWritebackForReadyOrder` |
|
||||
| **未启用分拣**(验收完成直接待配送) | `tryAdvanceOrderToDelivery`(`!pickingEnabled` 分支) | ❌ **此前无回写** ⇒ 只能等 15 分钟对账兜底(最多晚一轮) |
|
||||
| 免入库订单 | 同上(停在 50,我方不过配送、永不经过 50→60) | 同上;主系统要 `prepare_status >= 30` 才派配送员上门 ⇒ 晚一轮就是实打实的空等 |
|
||||
|
||||
**修复**:在 `!pickingEnabled` 分支、`UPDATE ... order_status = 50` **之后**补
|
||||
`await enqueueSkipInboundWritebackIfReady(orderCode, branchCode)` —— 复用既有 helper(三重闸门:
|
||||
回写总开关 → 免入库取货开关 → 免入库判定;判定失败只记账不抛错,交对账兜底),
|
||||
与「分拣完成」路径同款语义,不新增任何分支逻辑。
|
||||
|
||||
**测试**:`server/tests/noPickingReadyWriteback.test.ts` 3 条(含"回写必须晚于 UPDATE"的顺序断言)。
|
||||
⚠️ 首版测试用 `toContain('enqueueSkipInboundWritebackIfReady')`,**反向对照时被"把调用注释掉"骗过**
|
||||
(注释里也有同样的字符串)⇒ 已改为**先剥注释行再断言**,注入缺陷后确实转红。
|
||||
|
||||
**未改的**:分拣启用路径不动(调用方已覆盖)、对账兜底不动(继续兜进程崩溃/主系统抖动)。
|
||||
|
||||
## 8.6 回写口径定稿:默认开 + 所有单到「待配送」即回写 `status=30`(2026-10-11)
|
||||
|
||||
开发者两句话定稿:「**发车回写为什么要做成开关呢?这不应该就是一个默认的状态吗**」
|
||||
「**无论是送仓单还是免入库单,子系统到了待配送后就该让主系统的商品说明备货完成**」。
|
||||
|
||||
**改动**:
|
||||
|
||||
| # | 改动 | 落点 |
|
||||
|---|---|---|
|
||||
| 1 | 回写总开关从 **opt-in 改成默认开**(显式 `MAIN_SYSTEM_WRITEBACK=0` 才关) | `src/config.ts` |
|
||||
| 2 | 「未启用分拣」进入 50 的路径:回写对象从"仅免入库"放开到**所有单**(改用 `enqueueMainSystemWritebackForReadyOrder`) | `orderWorkflowFulfillmentService.tryAdvanceOrderToDelivery` |
|
||||
| 3 | 对账兜底:判据由「≥60 **或**(免入库 且 ≥50)」改为**「≥50 即回写」** | `mainSystemWriteback.retryPendingWritebacksForBranch` |
|
||||
|
||||
**为什么之前是关的**:回写最初作为"与主系统联调通过后再开"的安全阀(默认关),
|
||||
但这个阀门的代价是——**我方订单已到待配送、主系统仍显示"待备货"**,且**发车回写同样被挡**,
|
||||
台账 `writeback_status` 全是 `none`(从未尝试),业务上表现为"回写功能好像不存在"。
|
||||
|
||||
**实测(本地真库,开发者截图那张单)**:
|
||||
|
||||
```
|
||||
补回写 → [main-system-writeback] SUP37831443 ORD_API_20261009_SUP37831443_0001:回写 5/5 成功
|
||||
台账:5 行 writeback_status=done(退货/挂起/缺货 4 行按规则不回写)
|
||||
主系统:对应备货行 prepare_status 已由 10 → 30(未回写的仍是 10)
|
||||
```
|
||||
|
||||
**保留的纪律**:价格仍受 C5 门禁(未经改价审核确认的价不随回写携带,回写只带 `status` 与实供量);
|
||||
回写失败不阻塞发车、由对账兜底重试;未到 50 不回写(避免把未备齐的单标成已完成)。
|
||||
|
||||
## 8.7 自采入库实收回写订单(2026-10-11 开发者定稿,待实施)
|
||||
|
||||
**问题(实测)**:订单 `ORD_API_20261009_SUP37831443_0002` 的「八角」在**自采入库录了 0.6**,
|
||||
但**订单详情仍显示 0.5**(= 计划量)。
|
||||
|
||||
**根因(代码级)**:三个数据源互不相通 ——
|
||||
|
||||
| 数据源 | 表 / 字段 | 谁写 |
|
||||
|---|---|---|
|
||||
| 自采入库实收 | `self_purchase_stock_inbounds.qty`(**无 order_code / order_item_id**) | 自采入库([selfPurchaseStockInboundService.ts:983](server/src/services/selfPurchaseStockInboundService.ts)) |
|
||||
| 验收实收 | `inspections.actual_qty` | 验收 |
|
||||
| 核货实配 | `picking_items.loaded_qty` | 分拣核货 |
|
||||
| 订单详情「实收数量」实际取数 | `inspections.actual_qty` → 否则 `picking_items.loaded_qty` → 否则回退 `order_items.quantity`(计划量) | [OrderManagementPage.tsx:698-739](src/pages/orders/orderManagement/OrderManagementPage.tsx) |
|
||||
|
||||
⇒ 自采入库写的是**第三张表**,而详情只读前两者,读不到就回退计划量(0.5)。
|
||||
|
||||
**定稿口径(开发者 2026-10-11)**:**入库时把实收回写到订单侧**;且
|
||||
**① 验收实收(`inspections.actual_qty`)与 ② 核货实配(`picking_items.loaded_qty`)都会各变动一次,属预期**:
|
||||
|
||||
- **自采入库成功** ⇒ 回写 **验收实收 `inspections.actual_qty`**(经 `inspection_id → order_item_id` 唯一定位订单行);
|
||||
- **分拣核货** ⇒ 照旧写 **核货实配 `picking_items.loaded_qty`**(既有行为,不改);
|
||||
- 两者语义不同、各在自己阶段变一次,**互不覆盖**。
|
||||
|
||||
**实施清单(待做)**:
|
||||
|
||||
1. `createSelfPurchaseStockInbound` 插入成功后:若 `inspection_id` 非空且能唯一查到 `order_item_id`
|
||||
⇒ 把该订单行对应的 `inspections.actual_qty` 更新为入库 `qty`(同事务或紧随其后);查不到 ⇒ **跳过并记日志**(不猜);
|
||||
2. **独立入库 / 称台入库(无验收单、无订单行)不回写**;
|
||||
3. 作废(`voided_at` 非空)时**不回写**(或按同口径回滚)——实施时按现有作废链路确认;
|
||||
4. 测试:① 有验收的入库 ⇒ 回写生效 ② 无验收 ⇒ 不动 ③ 作废 ⇒ 不回写 ④ 详情页取数优先级不变;
|
||||
5. 验证单:`ORD_API_20261009_SUP37831443_0002` 的「八角」应显示入库值(0.6),不再是计划量 0.5。
|
||||
|
||||
**影响面**:触及**验收实收**写入(验收冻结面)⇒ 本次已获开发者明确批准(原话:「可以 开始修复…验收变动一次 核货变动一次 都没有问题呀」)。
|
||||
|
||||
## 9. 实施记录与实测(2026-10-10,真实代码 + 真实库 + 真实主系统)
|
||||
|
||||
### 9.1 改动文件
|
||||
|
||||
| 文件 | 类型 | 改动 |
|
||||
|---|---|---|
|
||||
| `migrations/20261014_main_system_daily_merge_stockout.sql` | 新增 | 日级占坑表 `public.main_system_daily_order_imports` + 各租户 `order_items` 加 `is_stockout/stockout_reason/stockout_reported_at` |
|
||||
| `migrations/20261015_order_items_main_order_code.sql` | 新增 | 各租户 `order_items` 加 `main_order_code`(来源主系统订单号;详情表一级分组键) |
|
||||
| `server/src/services/mainSystemOrderImport.ts` | 修改 | 按配送日分桶(`bucketGroupsByDeliveryDate`)+ 日级占坑(`claimDayOrder`)+ 建日单(`createDayOrder`)+ 行级追加(`appendNewRowsToDayOrder`);来源单号落 `main_order_code`(`stampMainOrderCodes`,含存量惰性补齐 `healMainOrderCodes`),**不写备注**;对账收尾自动剔除非我方行(`settleRowsNoLongerOurs` / `isPreparationNoLongerOurs`,§2.5) |
|
||||
| `server/src/services/mainSystemStockout.ts` | 新增 | 缺货:报主系统 `status=40` + **本地清干净**(`removeLocalLineForStockout`:删订单行/自采/备货 + 重算订单头),先报后改、失败不动本地;同一函数被自动跟随复用 |
|
||||
| `server/src/services/mainSystemPreparations.ts` | 修改 | 回写支持 `stockoutReason`(请求体带 `stockout_reason`) |
|
||||
| `server/src/services/orderDeleteService.ts` | 修改 | 共用守卫 `assertNotMainSystemOrder`,同时挂在**移入垃圾桶**与**彻底删除/网关特判**两个入口 → 409 `main_system_order_locked` |
|
||||
| `server/src/services/orderManageItemsService.ts` | 修改 | 主系统单在改明细里"漏行"(= 删商品)→ 409 `main_system_item_locked` |
|
||||
| `server/src/services/accessPolicy.ts` | 修改 | `DENY_DELETE_TABLES` 增 `order_items`(网关对它是裸 DELETE,绕过履约清理)。⚠️ **`orders` 有意不拉黑**:网关已把 orders delete 特判到 `deleteOrderWithDependencies`(既有测试钉住),拉黑会连它一起挡掉 |
|
||||
| `server/src/services/orderManagementQueryService.ts` | 修改 | 列表行新增 `is_main_system_order` |
|
||||
| `server/src/services/mainSystemReturnFollow.ts` | 修改 | 台账自愈按 `main_order_code` 计数(合并后多单共用一张单,按订单号数会漏自愈) |
|
||||
| `server/src/modules/workflow/routes/orderRoutes.ts` | 修改 | 新增 `POST /orders/:orderCode/items/:itemId/stockout` |
|
||||
| 前端 5 个文件 | 修改 | 列表隐藏「删除」;详情隐藏「删除明细」、换成「缺货」(含在途锁);`OrderItem`/`Order` 加字段;`workflowApi` 加 `reportOrderItemStockoutApi` |
|
||||
| `src/pages/system/OperationLogs.tsx` + `src/i18n/locales/*/system.ts` | 修改 | 缺货日志的操作类型标签与详情格式(三语) |
|
||||
| i18n 三语 | 修改 | `detail.stockout` / `detail.stockoutDone` / `detail.hintStockout` / `detail.returnedTag`(**文案待开发者确认**) |
|
||||
| `server/tests/mainSystemDayMergeAndStockout.test.ts` | 新增 | 7 例:分桶(含哨兵日兜底)、一次建单承接多张主系统单且备注各自单号、缺货四条(成功/不可用不动本地/主系统已 40/非主系统单) |
|
||||
| `server/tests/mainSystemImportClaim.test.ts` | 修改 | 断言升级为**日级**占坑(键、回填、失败释放、整单台账指向日单) |
|
||||
| `server/tests/mainSystemAppendNewRows.test.ts` | 修改 | 追加路径改为"日级占坑抢不到 → 读回已有单号 → 行级追加" |
|
||||
|
||||
### 9.2 实测
|
||||
|
||||
| # | 验收项 | 实测结果 |
|
||||
|---|---|---|
|
||||
| V1 | 同一配送日 N 张主系统单 ⇒ 1 张本系统订单 | ✅ 6 张主系统单(0001/0002/0003/0004/0005/0007)合并为 **1 张** `ORD_API_20261009_SUP37831443_0001`:10 行明细、金额 ¥1446.00、重量 52.5kg、配送日 2026-10-09、状态 30 |
|
||||
| V2 | 来源单号落列(**不写备注**) | ✅ 建单路径:9 行全部 `main_order_code` 非空、6 个来源单、`remark` 非空行数 **0**;存量 10 行走惰性补齐(只发 1 轮对账,未手工改库),补出的 6 组与改造前备注里的来源逐一吻合 |
|
||||
| V3 | 行级台账仍逐行对照 | ✅ 10 行台账全部非空且指向合并单里的行(`mapped=10/10`);整单台账 6 行都指向同一张日单 |
|
||||
| V4 | 原生单零影响 | ✅ 克隆一张"原生单"(无台账行)→ 删订单**放行**(反向对照),缺货接口对它返回 `not_main_system_item` |
|
||||
| V5 | 缺货 = 本地清干净(stub 主系统,真主系统全程未碰) | ✅ 对 `蚝油`(金额 16.00)报缺货:订单行 **9 → 8**(该商品不在剩余明细里)、采购单 **9 → 8(没有新建)**、履约行 **9 → 8**;订单头金额 **1434.00 → 1418.00**(正好减 16.00)、重量 **50.50 → 32.50**;台账 `disposition='skipped_stockout'`;主系统收到 `{id, status:40, stockout_reason}` |
|
||||
| V5d | 幂等 / 历史行自愈 | ✅ 对"改造前只打标签"的行再点 ⇒ 不发 HTTP(`alreadyReported`)但仍完成本地清理;随后真实对账 `created=0 appended=0 skipped=6`,该行**没有被补回来**(金额仍 1418.00、8 行) |
|
||||
| V5e | 已有货物事实不允许缺货 | ✅ 单测:已入库/备货完成/采购完成 ⇒ `invalid_state`,删除原语零调用、订单头零改动 |
|
||||
| V5f | **自动跟随**(stub 主系统,真主系统未碰) | ✅ 主系统把「玉兰片」转自采 ⇒ 一轮对账自动剔除:订单行 **8 → 7**、该商品采购单消失、金额 **1418.00 → 1368.00**(正好 −50.00)、台账 `skipped_stockout` 且对照清空 |
|
||||
| V5g | **重新分配后自动补回** | ✅ stub 把它放回 active ⇒ 下一轮对账 `appended=1` 补回「玉兰片」:行 **7 → 8**、金额回到 **1418.00**、台账复位 `imported` 并重新有对照 |
|
||||
| V5b | 主系统不可用 = 本地一动不动 | ✅ 500 → `unavailable`,本地三处(明细/采购/备货行)逐字段未变 |
|
||||
| V5c | 幂等 | ✅ 重复点击命中我方缺货态 ⇒ 直接成功且**零 HTTP**;主系统已是 40 时按"已达成"收口 |
|
||||
| V6 | 禁删 | ✅ 列表/详情入口隐藏;`moveOrderToTrash`(界面)与 `deleteOrderWithDependencies`(通用网关特判 + 垃圾桶彻底删除)**两个入口都** 409 `main_system_order_locked`;改明细漏行 → 409 `main_system_item_locked`(点出行名);`/api/data` 删 `order_items` → 403;`/api/data` 删 `orders` 仍走网关特判的守卫级联(既有行为,未被拉黑) |
|
||||
| V5h | **操作日志留痕** | ✅ 人工点击:`operation_logs` 落 `main_system_stockout`,带 `operator_id/role`、品名「泡海椒」、主系统单、原因、`trigger=user`、`local_removal=removed`;对账自动跟随:同一类型落一条 `operator_id=null`、`trigger=reconcile` 的记录(原因写明 `prepare_status=40`) |
|
||||
| V7 | 重复对账幂等 | ✅ 再跑一轮:`created=0 appended=0 skipped=6 failed=0`,无重复单、无重复行 |
|
||||
| V8 | 单测与回归 | 见 §9.3 |
|
||||
|
||||
**关键复用(没有动冻结面)**:缺货行之所以"自动出列待备货",是因为 `countPendingPurchases` 只数 `purchase_status IN (10,32)`、
|
||||
订单进度事实 SQL 也已排除 `40`,而备货行判定本就排除 `is_stockout` —— 本次**没有改任何门槛谓词**。
|
||||
|
||||
### 9.3 单测、套件与门禁
|
||||
|
||||
- 主系统相关的测试文件共 **43 例全绿**(`mainSystemDayMergeAndStockout` 7 + `mainSystemWriteback` 14 + `mainSystemReturnFollow` 13 + `mainSystemAppendNewRows` 5 + `mainSystemImportClaim` 4)。
|
||||
- 前端分组:`groupOrderDetailItemsForDisplay` 新增 4 例(一级/二级、同级多分类只插一次表头、无来源归「本系统录单」、关闭开关退回原行为),`src/pages/orders/orderManagement/` 下 9 个文件 57 例全绿。
|
||||
- `server` 全量套件:失败文件集合与 HEAD 基线**逐文件一致**(24 个既有失败,无新增)。
|
||||
- 设计门禁 `bash tools/design-consistency/run-all.sh`:**通过 8 / 未通过 1 / 未执行 1**。
|
||||
唯一的红是 `check-ai-cost.py`(改造前既有、且按仓库规则**不许调绿**:解析/OCR 链路未记录 token 用量);
|
||||
`check-env-coverage.py` 已于 2026-10-10 **转绿**(把 113 个代码在读、文档未登记的环境变量补进
|
||||
`docs/manual/02-环境要求与安装部署.md` 的「环境变量总表」,只写变量名/默认值/作用,不含任何密钥值)。
|
||||
`verify-facts.sh` 未执行(其连接串连不上本地库)。
|
||||
- 前端 `npx tsc --noEmit` 通过。
|
||||
|
||||
### 9.4 界面与文案(**待开发者确认**)
|
||||
|
||||
| 位置 | 变化 |
|
||||
|---|---|
|
||||
| 订单列表(主系统单那行) | **不再渲染**「删除」按钮 |
|
||||
| 订单详情明细行(主系统单) | **删除明细按钮换成「缺货」**;已退货显示「已退货」;缺货成功后**该行直接消失**(连带自采/备货),所以不需要"已缺货"标签(历史遗留的标签行也照常给按钮,点一下即清理) |
|
||||
| 系统 → 操作日志 | 新增操作类型「缺货(主系统转自采)」及详情格式(商品 · 主系统单 · 原因 · 人工点击/系统自动跟随 · 本地是否已剔除),三语已同步 |
|
||||
| 订单详情工具栏 | 新增**「按订单分组」开关(默认开启)**:开启 = 一级「主系统订单 <单号>」/ 二级「分类小计」;关闭 = 只按分类。无来源的行归「本系统录单」 |
|
||||
| 新增文案(三语已同步) | `缺货` / `已缺货` / `报缺货(主系统转自采),该商品不再需要备货` / `已退货`;缺货确认框正文:「{商品}:报缺货后,主系统会改由它自己采购(转主系统自采),本单不再需要为它备货。」(**点明「主系统自采」**,别让管理员以为是我们改自采);成功提示「{商品} 已报缺货」、失败提示「上报缺货失败」;分组开关 `按订单分组` + 提示「一级按来源主系统订单、二级按商品分类;关闭后只按分类分组」+ 一级表头 `主系统订单 {code}` / `本系统录单` |
|
||||
|
||||
按前端文案纪律,以上新增/改动文案**未经批准不视为定稿**,等你回话后我再调。
|
||||
|
||||
### 9.5 本地数据说明
|
||||
|
||||
验收时把本地**我们自己导入的 6 张单**(`ORD_API_*`,客户 `MAIN_SUP37831443`)与三张台账清掉后重导,得到 1 张日单;
|
||||
主系统数据**全程未改**(缺货验证用的是本地 stub 主系统)。重导前的 6 张单可由主系统随时重新拉取重建。
|
||||
@@ -0,0 +1,456 @@
|
||||
# 第三方订单收口:主系统履约事件接收端 + 免入库回写时机修正
|
||||
|
||||
> 立项 2026-10-10。开发者当轮指令「执行」。
|
||||
> 上游:主系统提交 `1447ea08`(设计 `ai-fresh-delivery/docs/design/20261010-supplier-prep-fulfillment-events.md`),
|
||||
> 回执见 [`../给主系统AI的对接改造清单.md`](../给主系统AI的对接改造清单.md) 的「第二批:履约状态回传」末尾。
|
||||
> 需求口径:开发者 2026-10-10 两条链路定稿(免入库等主系统确认发车、送仓等主系统入库完成)。
|
||||
|
||||
## 1. 本批做什么
|
||||
|
||||
| # | 内容 | 类型 |
|
||||
|---|---|---|
|
||||
| **C1** | 接收 `preparations.picked_up`(免入库:主系统确认发车)⇒ 我方订单收口 90 | 新增 |
|
||||
| **C2** | 接收 `preparations.inbound_completed`(送仓:该供应商行全部入库完成)⇒ 我方订单收口 90 | 新增 |
|
||||
| **C3** | R3 履约事实字段接入(`actual_qty` / `qty_diff` / `is_inbounded` / `inbound_at` / `order_departed_at`) | 新增 |
|
||||
| **C4** | 「改量待确认」本地台账(实收量 ≠ 申报量时生成,纯本地同意/拒绝) | 新增 |
|
||||
| **S4** | **修正免入库回写时机**:回写提前到"我方货备齐",并补上未启用分拣的分支 | 修正 |
|
||||
| **C5** | 拉取侧兜底:15 分钟对账用 R3 字段独立推出 C1/C2,不依赖 webhook | 新增 |
|
||||
|
||||
**明确不做**:任何反向写回;把同意/拒绝回传主系统;改主链状态常量;改财务口径;
|
||||
绕过零价闸门(见 §6 决策点)。
|
||||
|
||||
---
|
||||
|
||||
## 2. 改前实测事实(先立事实)
|
||||
|
||||
### 2.1 我方现状
|
||||
|
||||
| # | 事实 | 证据 |
|
||||
|---|---|---|
|
||||
| F1 | webhook 接收端**只认 `preparations.allocated`**,其余事件返回 `{ok:true, ignored:true}` 后丢弃 | `server/src/routes/mainSystemIntegration.ts:200-203` |
|
||||
| F2 | 主系统**已经在推**新事件,且我们已收下一条并回 200(验签通过)——但被忽略 | 主系统 `supplier_integration_webhook_deliveries`:`inbound_completed` success 200 一条;全表仅 2 条 |
|
||||
| F3 | `MainPreparationRow` **无** R3 任何字段 ⇒ 拉取与 webhook 两侧映射都会把新字段丢掉 | `server/src/services/mainSystemPreparations.ts:24-50`、`:129-155`;`mainSystemIntegration.ts:159-187` |
|
||||
| F4 | 免入库订单在**启用分拣**时:分拣完毕直接结案 90(`45→50→90`),**不经过 50→60** | `server/src/services/pickingService.ts:107-131` |
|
||||
| F5 | 免入库订单在**未启用分拣**时:**没有任何免入库分支**,走 `40→50` 并**照常建配送任务** | 全仓 `grep -rn isMainSystemSkipInboundOrder server/src` 只命中 `mainSystemPrepLedger.ts:176`(定义)+ `pickingService.ts:118-119`(唯一调用) |
|
||||
| F6 | 回写 `prepare_status=30` 只挂在 50→60(我方发车),**唯一调用点** | `server/src/services/mainSystemWriteback.ts:258`;`orderWorkflowFulfillmentService.ts:535` |
|
||||
| F7 | ⇒ **F4+F5+F6 合成真缺口**:免入库订单永不回写 `status=30`;而主系统 `ORDER_ITEM_SKIP_INBOUND_COVERED_SQL` **要求 `prepare_status >= 30`** 才算覆盖 ⇒ 主系统订单不推进 ⇒ 配送员不上门 ⇒ **R1 永不触发**(死锁) | 主系统 `supplierSkipInbound.ts:8` 起 |
|
||||
| F8 | 对账任务每 15 分钟扫 `order_status` 20–89 并调 `tryAdvanceOrderToDelivering`;但该函数**无 options 时要求"配送员已点开始配送"**(`task_status>=20 AND start_time IS NOT NULL`),否则软失败 ⇒ **停在 50 不会被自动推到 60** | `server/src/services/orderStatusReconcileService.ts:117-124`;`orderWorkflowFulfillmentService.ts:410-470` |
|
||||
| F9 | 结案入口状态限制:`completeOrderWithoutDriverDelivery` 只接受 **30 或 50**;`finalizeOrderFulfillment` 只接受 **60** | `orderWorkflowFulfillmentService.ts:569-581`、`:663-674` |
|
||||
| F10 | 结案前有**零价硬拦**:`assertNoZeroPriceItems(orderCode, db, options?.allowUnpriced, '签收')` | `orderWorkflowFulfillmentService.ts:589`;`orderZeroPriceGuard.ts:51-70` |
|
||||
| F11 | 配送任务创建**有 8 个以上调用点**(分拣收尾、验收推进、备货齐套、处理单、配送查询、极简流转…) | `grep -rn ensureDeliveryTaskForOrder server/src` |
|
||||
| F12 | 本地第三方订单测试数据已被清理(`tenant_sup37831443` / `tenant_sup92185841` 订单数均为 **0**),台账 8 行为**悬空指针** ⇒ 本批回归必须**造数**验证,不能靠现有数据 | 实测 `SELECT count(*) FROM tenant_sup*.orders` = 0 |
|
||||
|
||||
### 2.2 主系统侧(已交付,我方核过代码)
|
||||
|
||||
| # | 事实 | 证据 |
|
||||
|---|---|---|
|
||||
| M1 | `preparations.picked_up`:50→60 **事务提交后**触发,`void …catch()` 发后不管,**只推 `skip_inbound=true` 的供应商** | 主系统 `supplierPrepWebhookService.ts:224-261`;`orderWorkflowFulfillmentService.ts:534-541` |
|
||||
| M2 | `preparations.inbound_completed`:入库 **COMMIT 后**触发,判定"该供应商在本单的行全部覆盖",复用 `ORDER_ITEM_INBOUND_COVERED_SQL`,分母排除退货红冲 | `supplierPrepWebhookService.ts:270-311`;`supplierPrepFulfillmentSql.ts:152-183` |
|
||||
| M3 | **主系统侧不做持久去重**(回执 §2.1 原话)⇒ 幂等**必须我方兜** | 回执;实测 `notifyPreparationsInboundCompleted` 无去重 |
|
||||
| M4 | R3 字段已交付且三处同口径;时间字段是 **ISO 8601**(他们踩过 `String(Date)` 的坑已修) | `supplierPrepFulfillmentSql.ts`(206 行);`supplierPreparationOpenApiShape.ts:204,207,208` |
|
||||
| M5 | `is_inbounded=true` 但 `inbound_at=null` 属**正常组合**(库存全额抵扣/采购挂单无验收时间) | 回执 §2.2 |
|
||||
| M6 | R1 **从未真实投递给我方过**(投递表全量 2 条,无 `picked_up`);他们自测用的是可抛弃临时 client | 实测投递表;回执 V1 自标 ⚠️ |
|
||||
|
||||
---
|
||||
|
||||
## 3. 设计
|
||||
|
||||
### 3.1 C1/C2:事件接收端
|
||||
|
||||
**新表 `public.main_system_fulfillment_events`(平台台账,跨系统,与既有两张台账同类)**
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS public.main_system_fulfillment_events (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
branch_code varchar(50) NOT NULL, -- = 主系统 supplier_code
|
||||
event varchar(50) NOT NULL, -- preparations.picked_up | preparations.inbound_completed
|
||||
main_order_code varchar(100) NOT NULL,
|
||||
our_order_code varchar(50),
|
||||
/** pending=已收到未收口 | done=已收口 | suspended=前置未满足/被闸门拦,下轮重试 | ignored=不该处理(原生单等) */
|
||||
status varchar(20) NOT NULL DEFAULT 'pending',
|
||||
reason text,
|
||||
/** 原样存主系统载荷,便于事后核对与重放 */
|
||||
payload jsonb NOT NULL DEFAULT '{}'::jsonb,
|
||||
received_at timestamptz NOT NULL DEFAULT NOW(),
|
||||
processed_at timestamptz,
|
||||
attempts integer NOT NULL DEFAULT 0,
|
||||
updated_at timestamptz NOT NULL DEFAULT NOW(),
|
||||
UNIQUE (branch_code, event, main_order_code)
|
||||
);
|
||||
CREATE INDEX ... ON public.main_system_fulfillment_events (status, updated_at);
|
||||
```
|
||||
|
||||
- **幂等键 `(branch_code, event, main_order_code)`**:主系统事件粒度就是 `(order_code, supplier_code)`,
|
||||
而 `branch_code == supplier_code` ⇒ 三元组唯一。重复投递命中 `ON CONFLICT DO NOTHING` ⇒ 直接 200。
|
||||
- **不放进 `tenant_business_tables()`**:它与 `main_system_order_imports` / `_items` 一样是 `public` 层跨系统台账,
|
||||
不是分公司业务表(迁移里的 `assert_tenant_template_matches_business_tables()` 只校验模板表)。
|
||||
|
||||
**处理流程(收到即入库、能收口就收口)**
|
||||
|
||||
```
|
||||
webhook 到达
|
||||
├─ 验签(既有 verifyWebhookSignature,失败 401)
|
||||
├─ 事件名不是 allocated/picked_up/inbound_completed → 200 ignored(既有行为不变)
|
||||
├─ UPSERT 事件行(ON CONFLICT DO NOTHING)
|
||||
│ └─ 冲突(已处理过)→ 200 {ok:true, duplicate:true} ← 幂等兜住主系统重推
|
||||
└─ 解析 payload → 调 processFulfillmentEvent(...)
|
||||
├─ 找不到我方订单(台账无对照)→ status='ignored'(不是我们的单)
|
||||
├─ 前置未满足(见下)→ status='suspended' + reason,**返回 200**(已收下,下轮重试)
|
||||
├─ 收口成功 → status='done'
|
||||
└─ 收口抛业务错误(如零价 409)→ status='suspended' + reason,返回 200
|
||||
```
|
||||
|
||||
> **为什么业务失败也返回 200**:事件已持久化,重试由**我方对账**负责;
|
||||
> 返 5xx 会让主系统重推,而重推解决不了"我方前置未满足"。
|
||||
|
||||
**前置与收口路径(两条链路各不同)**
|
||||
|
||||
| 事件 | 我方订单要求状态 | 收口入口 | 依据 |
|
||||
|---|---|---|---|
|
||||
| **C1** `picked_up` | `order_status = 50`(待配送) | `completeOrderWithoutDriverDelivery`(接受 30/50,`skipInventorySettle:true`) | F9 |
|
||||
| **C2** `inbound_completed` | `order_status = 60`(配送中,我方已发车送仓) | `finalizeOrderFulfillment`(接受 60) | F9 |
|
||||
|
||||
- **C1** 到达但我方还在 40/45 ⇒ `suspended`,等分拣/验收推进到 50 后由对账重试;
|
||||
- **C2** 到达但我方还在 50(我方还没发车)⇒ `suspended`,等我方发车到 60 后重试;
|
||||
- 订单**已 90** ⇒ 直接 `done`(幂等命中);
|
||||
- 订单**< 40** ⇒ `suspended`(货都没备齐,可能是异常数据,人工可见)。
|
||||
|
||||
### 3.2 C3:R3 字段接入
|
||||
|
||||
在 `MainPreparationRow` 增加 5 个字段(`actualQty` / `actualQtyAt` / `qtyDiff` / `isInbounded` / `inboundAt`)
|
||||
与订单级 `orderDepartedAt`,**三处映射同改**(守 2026-10-09 的教训:只改一处会让某一路丢字段):
|
||||
|
||||
1. `mainSystemPreparations.ts` → `mapRow`(拉取 `GET /preparations`)
|
||||
2. `mainSystemIntegration.ts` → `mapWebhookRow`(webhook 载荷)
|
||||
3. `mainSystemPreparations.ts` → `lookupMainSystemPreparationStates`(`POST /preparations/lookup`)
|
||||
|
||||
⚠️ **不改既有字段语义**;`skipInbound` / `isDirectDelivery` 仍**分别独立、禁止合并判定**(供应商管理冻结)。
|
||||
|
||||
### 3.3 C4:「改量待确认」(**纯本地**)
|
||||
|
||||
收到 `qty_diff ≠ 0` 时,在**行级台账**记实收量并生成待确认:
|
||||
|
||||
- `public.main_system_order_import_items` 增列:
|
||||
`last_actual_qty numeric`、`last_actual_qty_at timestamptz`、`last_qty_diff numeric`、
|
||||
`qty_decision varchar(20) DEFAULT 'none'`(`none` / `approved` / `rejected`)、`qty_decided_at timestamptz`;
|
||||
- **展示口径**:该行一律按 `actual_qty` 展示(与主系统一致);
|
||||
- **同意** ⇒ 本地库存调整:把差额补回库存(走既有 `POST /inventory/adjust` 语义:备注必填 + 双日志);
|
||||
- **拒绝** ⇒ 什么都不做;
|
||||
- 两者都写操作日志;**零 HTTP 发往主系统**;
|
||||
- `actual_qty` 为 `null` ⇒ **不生成**待确认(只做状态联动)。
|
||||
|
||||
### 3.4 S4:免入库回写时机 + 分拣分支
|
||||
|
||||
| 落点 | 改法 |
|
||||
|---|---|
|
||||
| `pickingService.maybeAdvanceOrderAfterPickingOutbound`(F4,**启用分拣**) | 免入库订单:**不再结案 90**,改为 `45→50` 停住 + **COMMIT 后**触发回写 `status=30` |
|
||||
| `processingTaskService.maybeAdvanceOrderAfterFulfillment` 的 `!pickingEnabled` 分支(`40→50`) | 停在 50 + 触发回写(无事务,可安全触发)。**⚠️ 这是供应商分公司的实际默认路径**(实测分拣=关、库存抵扣=开),见 §8.7 |
|
||||
| `preparationFulfillmentService` 的 `30→50`(免入库**且有缺口**) | 触发回写,但**只在 `!client`(无外层事务)时**;有外层事务时交给对账兜底 |
|
||||
| `ensureDeliveryTaskForOrder`(F11 的公共入口) | 增加"主系统免入库订单不建配送任务"守卫 ⇒ **一个卡点覆盖 8 个调用方**,避免逐处打补丁 |
|
||||
| 回写触发 | 抽出 `enqueueMainSystemWritebackForReadyOrder`(直接触发)与 `enqueueSkipInboundWritebackIfReady`(判定+触发,供 50 落点复用);50→60 的既有触发**保留**(送仓链路仍靠它) |
|
||||
| **兜底(必须有)** | `retryPendingWritebacksForBranch` 对免入库在飞状态放行 `>= 50` ⇒ 任何漏触发的路径 15 分钟内补上 |
|
||||
|
||||
**为什么停在 50 是安全的**:F8 实测 `tryAdvanceOrderToDelivering` 无 options 时要求配送员已点开始,
|
||||
对账任务推不动它;且我们不再建任务 ⇒ 永远不会被自动推走,直到 C1 到达。
|
||||
|
||||
**回滚**:`MAIN_SYSTEM_FULFILLMENT_EVENTS=0` 关掉接收端;
|
||||
`MAIN_SYSTEM_SKIP_INBOUND_AWAIT_PICKUP=0` 让免入库退回"分拣完毕即结案"的旧行为(S4 整体回退)。
|
||||
|
||||
### 3.5 C5:拉取侧兜底(不依赖 webhook)
|
||||
|
||||
15 分钟对账时,对每个有台账的分公司:
|
||||
|
||||
| 链路 | 判据 | 动作 |
|
||||
|---|---|---|
|
||||
| A 免入库 | `order_departed_at` 非空 | 等价于 C1 ⇒ 收口 |
|
||||
| B 送仓 | 该单**全部行** `is_inbounded = true` 且我方订单已到 60 | 等价于 C2 ⇒ 收口 |
|
||||
|
||||
- **只对"我方已到前置状态"的订单收口**,与 §3.1 同门槛;
|
||||
- 兜底与 webhook **共用同一个 `processFulfillmentEvent` 内核**,避免两条路径分叉;
|
||||
- 每次收口都写事件台账(`source: 'reconcile'`),保证可审计。
|
||||
|
||||
---
|
||||
|
||||
## 4. 影响面
|
||||
|
||||
| 面 | 影响 | 依据 |
|
||||
|---|---|---|
|
||||
| 主链状态常量 | **零改动**(`20→30→40→45→50→60→90` 与既有异常边不动) | 无状态常量文件改动 |
|
||||
| 原生录单订单 | **零影响**:`isMainSystemSkipInboundOrder` 无台账行即 false;事件按台账定位,无台账即 `ignored` | F5 的判定函数语义 |
|
||||
| 送仓链路(普通第三方单) | 不改:仍 50→60 发车 + 既有回写 | F6 保留 |
|
||||
| 财务口径 | **不改**;零价订单**不绕过闸门**,挂 `suspended` 暴露给人 | F10;决策点见 §6 |
|
||||
| 库存 | 只有"改量待确认-同意"一条写路径,走既有调整语义(备注必填+双日志) | §3.3 |
|
||||
| 平台表名单 | 新增 `public` 表**不进** `tenant_business_tables()`(同既有两张台账) | §3.1 |
|
||||
|
||||
---
|
||||
|
||||
## 5. 验收标准(可执行)
|
||||
|
||||
| # | 验收项 | 通过标准 |
|
||||
|---|---|---|
|
||||
| V1 | C1 收口 | 造免入库第三方单到 50 ⇒ 推 `picked_up` ⇒ 订单 **90**,事件台账 `done` |
|
||||
| V2 | C2 收口 | 造送仓第三方单到 60 ⇒ 推 `inbound_completed` ⇒ 订单 **90**,事件台账 `done` |
|
||||
| V3 | **幂等** | 同一 `(branch,event,main_order)` 推两次 ⇒ 只收口一次,事件台账仍 1 行、`done`;结算单不重复 |
|
||||
| V4 | **乱序不越级** | 订单还在 45 时推 C1 ⇒ `suspended` 且订单**不动**;推进到 50 后对账重试 ⇒ 收口 |
|
||||
| V5 | 原生订单零影响 | 无台账行的原生订单收到任何事件 ⇒ `ignored`,订单与库存零变化 |
|
||||
| V6 | S4 回写时机 | 免入库单**未启用分拣**:货备齐 ⇒ 回写 `status=30` 已发出(stub 断言),且**无配送任务** |
|
||||
| V7 | S4 分拣分支 | 免入库单**启用分拣**:分拣完成 ⇒ 订单停在 **50**(不是 90)+ 已回写 |
|
||||
| V8 | 不误推 | 停在 50 的免入库单跑一轮对账 ⇒ **不被推到 60**(F8 的闸门生效) |
|
||||
| V9 | R3 字段 | 拉取 / webhook / lookup 三处都能拿到 `actual_qty`/`qty_diff`/`is_inbounded`;`null` 不被当成 0 |
|
||||
| V10 | 改量展示 | `qty_diff=-0.5` ⇒ 台账记 `last_actual_qty=9.5`、生成待确认;**同意** ⇒ 库存 +0.5 且有双日志;**拒绝** ⇒ 零变化;两者**零 HTTP** |
|
||||
| V11 | 零价不绕过 | 造 0 价行的第三方单 ⇒ 收口被拦、事件 `suspended` 且 reason 写明,**订单不结案** |
|
||||
| V12 | 拉取兜底 | 关掉 webhook,仅靠 R3 字段跑对账 ⇒ 仍能收口(C5) |
|
||||
| V13 | 回归 | `server` 全量套失败集合与 HEAD 基线**逐文件一致**;`tsc` 通过;设计门禁与改前一致 |
|
||||
|
||||
---
|
||||
|
||||
## 6. 决策点(**需开发者裁决,本批不擅自决定**)
|
||||
|
||||
| # | 事项 | 现状处置 | 为什么需要你定 |
|
||||
|---|---|---|---|
|
||||
| D1 | **零价行能否自动收口** | **不绕过**:挂 `suspended` 暴露给人(V11) | 零价闸门是财务口径的最后一道;本批遵守财务冻结,不擅自放行。若你认为"主系统导入单允许零价收口"(与导入/分配两处已传 `allowUnpriced:true` 的先例一致),我再加一行即可 |
|
||||
| D2 | 「改量待确认」的**界面与文案** | 本批**只落台账 + 服务端能力**,不做界面 | 新增界面文案属产品决策(前端文案纪律) |
|
||||
| D3 | 免入库单停在 50(待配送)的**语义展示** | 沿用「待配送」现有文案 | 实际是"等主系统上门取货",是否要单独文案由你定 |
|
||||
|
||||
---
|
||||
|
||||
## 7. 回滚
|
||||
|
||||
- **接收端**:`MAIN_SYSTEM_FULFILLMENT_EVENTS=0` ⇒ webhook 对新事件回到"200 忽略",行为与改造前一致;
|
||||
- **S4**:`MAIN_SYSTEM_SKIP_INBOUND_AWAIT_PICKUP=0` ⇒ 免入库回到"分拣完毕即结案 90"、回写回到只在 50→60;
|
||||
- **数据**:新增表与增列**纯增量**,删除表/列即可;已收口的订单**不回滚**(那是业务事实);
|
||||
- **代码**:`git revert` 对应提交。
|
||||
|
||||
---
|
||||
|
||||
## 8. 实施记录(2026-10-10 实施,真实库 + 真实代码)
|
||||
|
||||
### 8.1 改动文件
|
||||
|
||||
| 文件 | 类型 | 改动 |
|
||||
|---|---|---|
|
||||
| `migrations/20261018_main_system_fulfillment_events.sql` | **新增** | 事件台账表(幂等唯一键)+ 行级台账 6 个改量列 |
|
||||
| `server/src/services/mainSystemFulfillmentEvents.ts` | **新增** | 事件接收端:幂等占坑、收口内核、对账重试、拉取兜底 |
|
||||
| `server/src/routes/mainSystemIntegration.ts` | 修改 | webhook 分发新事件;`mapWebhookRow` 接 R3 字段 |
|
||||
| `server/src/services/mainSystemPreparations.ts` | 修改 | `MainPreparationRow` / `PrepLookupResult` 加 R3 字段;两处映射 + `isoOrNull` |
|
||||
| `server/src/services/mainSystemPrepLedger.ts` | 修改 | `recordPrepActualQty`(改量落账,变化则复位裁决)+ `listPendingQtyDecisions` |
|
||||
| `server/src/services/mainSystemWriteback.ts` | 修改 | 新增 `enqueueMainSystemWritebackForReadyOrder`;兜底重试对免入库放行 50 |
|
||||
| `server/src/services/pickingService.ts` | 修改 | 免入库分支拆新旧两口径;回写在 **COMMIT 后**触发(两个调用点) |
|
||||
| `server/src/services/orderWorkflowFulfillmentService.ts` | 修改 | `ensureDeliveryTaskForOrder` 加免入库守卫(一个卡点覆盖 8+ 调用方) |
|
||||
| `server/src/services/mainSystemOrderImport.ts` | 修改 | 15 分钟对账串入事件重试 + 拉取兜底 |
|
||||
| `server/src/config.ts` | 修改 | 两个开关(均默认关) |
|
||||
| `server/.env.example` | 修改 | 两个开关登记 |
|
||||
| `server/tests/mainSystemFulfillmentEvents.test.ts` | **新增** | 18 例 |
|
||||
| `server/tests/skipInboundWritebackTiming.test.ts` | **新增** | 10 例 |
|
||||
|
||||
### 8.2 实测
|
||||
|
||||
| # | 验收项 | 实测结果 |
|
||||
|---|---|---|
|
||||
| — | 迁移 | ✅ `Applied 20261018_main_system_fulfillment_events.sql`;实查表结构:唯一键 `(branch_code, event, main_order_code)` 在位、`idx_..._pending` 在位、行级台账 6 列全加出 |
|
||||
| **V3** | 幂等 | ✅ **真库端到端**:同键第 2 次投递 ⇒ `duplicate=true`,DB 行数仍为 **1**;同订单**另一个事件**独立占坑(事件名是键的一部分) |
|
||||
| **V5** | 无台账忽略 | ✅ **真库端到端**:台账无对照 ⇒ `ignored` + 事件落库(`attempts=1`),**不动任何订单** |
|
||||
| V1/V2/V4/V11 | 收口与前置 | ✅ 单测:50→C1 收口、60→C2 收口、45 时 C1 挂 suspended 不越级、50 时 C2 挂 suspended、已 90 幂等命中、零价 `zero_price_blocked` ⇒ suspended 且原因写明 |
|
||||
| V6/V7/V8 | S4 回写时机与分支 | ✅ 源码合同 10 例:新旧两口径都在且由开关切换、回写调用点在 **COMMIT 之后**、兜底重试对免入库放行 50、任务守卫落在公共入口、无裸写新状态值 |
|
||||
| V9 | R3 三处同改 | ✅ 合同测试钉住「同一文件两处映射 + webhook 一处映射」共 6 字段都在 |
|
||||
| V12 | 拉取兜底 | ⚠️ **代码就位,未做真机验证**(本地第三方订单测试数据已被清空,见 F12);需在联调环境造数验证 |
|
||||
| V13 | 回归 | ✅ `server` 全量套 **24 failed / 328 passed**,与文档记载基线「24 个既有失败」逐数一致;逐文件核对:24 个**全部**是既有失败(如 `pickingCompleteKeepPlanQty` 失败于 `server-go/internal/picking/writeback.go` **文件不存在**,属环境性);`tsc --noEmit` 通过;设计门禁 7 通过 / 2 既有红 / 1 未执行(与改前一致) |
|
||||
|
||||
### 8.3 实测抓出并修掉的缺陷(单元测试发现不了的那类)
|
||||
|
||||
🔴 **`markEvent` 的 SQL 参数类型冲突**:`$4` 既赋值给 `status`(varchar)又与文本字面量 `'suspended'` 比较,
|
||||
PG 报 `inconsistent types deduced for parameter $4`(`42P08`,`text versus character varying`)。
|
||||
**单测把 `pool.query` mock 掉了,所以 18 例全绿也照样漏过** —— 只有打真库才暴露。
|
||||
修法:两处都显式 `$4::text`。
|
||||
|
||||
> 这正是本仓库"实测优先于单测"的又一例证;已在该函数上写明注释以免后人改回去。
|
||||
|
||||
### 8.4 收工前对抗式自查(2026-10-10,逐条核自己的 diff)
|
||||
|
||||
查出 **3 个真问题**并已修(不是走过场):
|
||||
|
||||
| # | 严重度 | 问题 | 修法 |
|
||||
|---|---|---|---|
|
||||
| 1 | **高(性能)** | 拉取兜底**逐张主系统订单**调一次 `lookup` ⇒ 一个分公司 100 张在途单就是 **100 次外网调用/15 分钟**;500 分公司时不可接受 | 改为**一个分公司一次 lookup**(内部按 500 分片):先把全部候选订单的 `(main_order_code, sku_code)` 合并成一次请求,再按订单分组判结果。库查询也从 2N 次降到 3 次。已加**行为测试**钉住"2 张单也只调 1 次" |
|
||||
| 2 | **中(健壮性)** | `ensureDeliveryTaskForOrder` 与 `pickingService` 都在**事务持有一条连接**时调用 `isMainSystemSkipInboundOrder`,而它内部用 `pool.query` 取**第二条**连接 ⇒ 池满(`PG_POOL_MAX` 默认 30)时**自锁** | 给 `isMainSystemSkipInboundOrder` 加可选 `db` 参数,两处都传当前事务的 `client` |
|
||||
| 3 | 低(死代码) | 拉取兜底里"插入后再查一次状态、判 `done` 就跳过"是**不可达分支**(插入成功即为 `pending`;冲突已在上一句 `continue`) | 删掉,改为注释说明"抢不到坑 = 这条事实已收过" |
|
||||
|
||||
**另一处经复核后有意保留(记录理由,以免后人误改)**:
|
||||
`picked_up` 事件**不**用我方台账的 `skipInbound` 快照做前置校验。
|
||||
理由:主系统是在**发车那一刻**读 `skip_inbound` 才决定推不推,而我方台账是**导入时**的快照;
|
||||
供应商的免入库设置若在导入后变更,两边会不一致 —— 用陈旧快照去否决一个**合法**事件会把订单卡死。
|
||||
按铁律一,主系统是"它自己交付方式"的权威,我方按事实办。
|
||||
|
||||
**复查中确认无问题的关键点**(逐条核过,不是假设):
|
||||
收口入口无隐藏闸门(`assertOrderActiveForFulfillment` 只查存在与垃圾桶);
|
||||
`finalizeOrderFulfillment` 对状态 60 **不要求客户签收**(签收校验在 workflow handler 里,不在该函数内);
|
||||
`recordPrepActualQty` 的 `CASE WHEN last_actual_qty IS DISTINCT FROM $3` 取的是**旧值**(SQL 语义正确,实收量变化会正确复位裁决);
|
||||
`handleFulfillmentEvent` 不依赖 `data[]` 也能收口(载荷为空照样按事件收口)。
|
||||
|
||||
### 8.5 实测踩到的 RLS 陷阱(**验证须知**)
|
||||
|
||||
写探针直接 `SELECT ... FROM tenant_sup37831443.orders` 得到 **0 行**,
|
||||
但在 `runWithTenantDbContext` 内同一条查询得到 **1 行**(真实订单 `ORD_API_20261009_SUP37831443_0001`,状态 30)。
|
||||
根因就是本仓 `.cursor/rules/01-second-dev-supplier.mdc` 记的那条:
|
||||
**租户表对应用角色带 RLS,没有 `app.branch_code` 时静默返回 0 行**。
|
||||
⇒ 本批代码全部走 `runWithTenantDbContext`(正确);**跑验证探针拿到 0 行先怀疑 RLS,别当"数据没了"**。
|
||||
|
||||
### 8.6 开关与上线
|
||||
|
||||
两个开关**均默认关**(`=== '1'` 才生效),所以代码进主干后**线上行为逐字节不变**:
|
||||
(⚠️ 2026-10-11 起 `MAIN_SYSTEM_SKIP_INBOUND_AWAIT_PICKUP` 与 `MAIN_SYSTEM_FULFILLMENT_EVENTS`
|
||||
均改为**默认开**(写 `0` 才关),见 §9.3;下表按当时的默认值留档。)
|
||||
|
||||
```bash
|
||||
MAIN_SYSTEM_WRITEBACK=1 # 既有开关;S4 的解锁前提,必须开
|
||||
MAIN_SYSTEM_FULFILLMENT_EVENTS=1 # 开启事件接收端(收口)
|
||||
MAIN_SYSTEM_SKIP_INBOUND_AWAIT_PICKUP=1 # 免入库改为"等主系统确认发车"
|
||||
```
|
||||
|
||||
⚠️ 三个都要开:少了 `WRITEBACK`,免入库单不回写 `status=30` ⇒ 主系统不推进 ⇒ `picked_up` 永不触发。
|
||||
|
||||
### 8.7 🔴 收工复核发现的**严重疏漏**:S4 只修了一半(2026-10-10,开发者提示后查出)
|
||||
|
||||
**触发**:开发者指出「本子系统库存抵扣默认是打开的」。
|
||||
|
||||
**实测确认了两个默认值**(`getPickingWorkflowSetting` / `isStockCoverFromInventoryEnabled`):
|
||||
|
||||
| 分公司 | 分拣 | 库存抵扣 |
|
||||
|---|---|---|
|
||||
| BR001 | 开 | **开** |
|
||||
| BR002 | 关 | **开** |
|
||||
| **SUP37831443** | **关** | **开** |
|
||||
| **SUP92185841** | **关** | **开** |
|
||||
|
||||
⚠️ **上表 4 个分公司里只有后两个是「主系统供应商」**:
|
||||
`BR001 默认分公司` / `BR002 华东分公司` 是迁移 `20260607_create_branch_tenant.sql`
|
||||
**无条件 seed** 的历史演示分公司(两者创建时间戳相同到微秒),**与主系统对接无关**——
|
||||
定时对账只遍历 `profiles.account_source = 'main_supplier'`(`mainSystemOrderImport.ts:1072`),
|
||||
**碰都不会碰到它们**。本表列全是为了说明"分拣关"这个默认值的来源。
|
||||
(它们会随迁移进入全新生产库,是否清理属运维决策,见 §9。)
|
||||
|
||||
⇒ **供应商分公司(用本对接的那批)分拣是关的**。而免入库 + 库存全额抵扣的订单根本没有缺口,
|
||||
走的是 `preparationFulfillmentService` 尾部 `30→40` → `processingTaskService.maybeAdvanceOrderAfterFulfillment`
|
||||
的 `!pickingEnabled` 分支 `40→50`。
|
||||
|
||||
**我先前只改了 `pickingService`(分拣路径)⇒ 对实际默认配置等于没修**,死锁照旧。
|
||||
更糟的是:设计文档 §3.4 当时**声称**改了"未启用分拣的 40→50 路径",实际只加了"不建配送任务"的守卫,
|
||||
**回写触发是漏的** —— 属于"文档写得比代码多",本仓明令禁止的那类问题。
|
||||
|
||||
**本次补齐(三条路径全覆盖 + 一条兜底)**:
|
||||
|
||||
| 路径 | 触发点 | 事务安全性 |
|
||||
|---|---|---|
|
||||
| 启用分拣 `45→50` | `pickingService`(COMMIT 后) | 已在事务外 |
|
||||
| **未启用分拣 `40→50`**(**实际默认**) | `processingTaskService` 的 `!pickingEnabled` 分支 | 用 `pool`,无事务 ⇒ 可直接触发 |
|
||||
| 免入库+有缺口 `30→50` | `preparationFulfillmentService` | **仅 `!client` 时**触发(无外层事务);有事务时交对账 |
|
||||
| 任何漏网路径 | `retryPendingWritebacksForBranch` 放行免入库 `>= 50` | 15 分钟内补齐 |
|
||||
|
||||
并新增测试 `skipInboundWritebackTiming` 的「②b 覆盖所有把免入库单推到 50 的路径」四条,
|
||||
把"每条路都必须挂回写"钉死,**防止再次只修一半**。
|
||||
|
||||
**教训(写给后人)**:改"某类订单的某条链路"时,**不能只改自己一眼看到的那条**——
|
||||
必须先把该类订单**所有可能到达目标状态的路径**枚举出来(本仓 `grep "order_status = 50"` 就有 8 处),
|
||||
再用**真实分公司配置**确认哪条是主路径。默认值(分拣关、库存抵扣开)会决定主路径,**不能靠猜**。
|
||||
|
||||
## 9. 2026-10-11 定稿:免入库单的触发点、展示口径与开关默认
|
||||
|
||||
**触发**:开发者问「免入库单(主系统骑手取货)的备货完成回写,触发点定在我方哪个状态」,
|
||||
并选定**方案①:维持现状**(不后移、不前移),本次只把已经跑通的规则**固化**,并修掉展示面上的两处漏接。
|
||||
|
||||
### 9.1 定稿规则(两类单分开,不得合并判定)
|
||||
|
||||
| 单型 | 我方路径 | 回写主系统「备货完成 `status=30`」的触发点 | 我方收口 90 靠 |
|
||||
|---|---|---|---|
|
||||
| **免入库**(主系统骑手上门取货) | 备齐 → **50**(界面「待取货」,**不建我方配送任务**) | **一进 50 就回写** | `preparations.picked_up` 事件 |
|
||||
| **送仓**(我方发车送仓) | … → 50 → **发车 60** | **发车(50→60)时回写** | `preparations.inbound_completed` 事件 |
|
||||
|
||||
**为什么免入库不能后移到 60**:免入库单我方**不派车、永不进 60**(`MAIN_SYSTEM_SKIP_INBOUND_AWAIT_PICKUP`
|
||||
打开后不建配送任务)。回写若挂到 60 ⇒ 主系统永远收不到"备货完成" ⇒ 不派骑手 ⇒ 我方永远等不到
|
||||
`picked_up` ⇒ **双向死锁**(§2.1 F7)。
|
||||
|
||||
**为什么不能前移到 40/45**:那两个状态的含义是"验收/分拣还没完",此时报"备货完成"等于叫主系统
|
||||
来取还没备齐的货,与实际作业顺序相反。
|
||||
|
||||
### 9.2 展示口径(同一次定稿)
|
||||
|
||||
| 面 | 取值 | 说明 |
|
||||
|---|---|---|
|
||||
| 列表徽标(50) | **待取货** | 仅 `is_skip_inbound = true` 时派生(`formatOrderStatusLabel`);送仓/自建单仍「待配送」。**数据库里仍是 50,未新增状态值** |
|
||||
| 列表副文案(50) | **待主系统骑手上门取货** | `buildProgressStatusHint(..., skipInbound)`;原为「待配送员开始配送」,对免入库单是张冠李戴(我方不派车) |
|
||||
| 订单详情 | 不显示状态文案 | 详情面本就没有状态徽标/副文案,无需接线 |
|
||||
|
||||
`is_skip_inbound` 判定 = **行级台账 `bool_and(payload->>'skipInbound')`**:混合单(部分免入库/部分送仓)
|
||||
走发车流程,**不得**标成待取货;自建单/送仓单恒为 `false`。
|
||||
|
||||
⚠️ **实测踩过的两个前端坑**(都表现为"后端对了、界面还是待配送"):
|
||||
① 列表行映射器 `mapManagementOrderRow` 是**白名单**,漏带 `is_skip_inbound` ⇒ 页面拿到 `undefined`;
|
||||
② 徽标文案若直接取 i18n `orders.list.status.50`(恒为「待配送」),会把派生文案**吃掉**。
|
||||
两处都必须"派生优先",由 `src/pages/orders/orderManagement/orderManagementHelpers.skipInbound.test.ts` 钉住。
|
||||
|
||||
### 9.3 开关默认(本次改默认值)
|
||||
|
||||
| 开关 | 原默认 | **现默认** | 理由 |
|
||||
|---|---|---|---|
|
||||
| `MAIN_SYSTEM_SKIP_INBOUND_AWAIT_PICKUP` | 关(`=== '1'` 才开) | **开(`!== '0'` 才关)** | 免入库单本来就不走我方配送;写 `0` 只用于回退到"分拣完毕即结案 90"的旧行为 |
|
||||
| `MAIN_SYSTEM_FULFILLMENT_EVENTS` | 关(`=== '1'` 才开) | **开(`!== '0'` 才关)** | 与上面**成对**:免入库单停在 50 后收口 90 只能靠本接收端;写 `0` = webhook 对新事件回到「200 忽略」的旧行为(送仓单也就不再靠事件收口) |
|
||||
|
||||
⚠️ **两者是一对,必须成对开**:`SKIP` 只负责"停在 50 等骑手取货",收口 90 全靠接收端的 `picked_up`。
|
||||
接收端关着时事件是「200 收下但忽略」(**不入台账、不会重放**)⇒ 单子停在 50 **永远收不了口**。
|
||||
本机 `server/.env` 已同时设 `SKIP=1` 与 `FULFILLMENT_EVENTS=1`,重启后实测两个 flag 均为 `true`(见 §9.4)。
|
||||
|
||||
### 9.4 回归
|
||||
|
||||
- `server/tests/orderStatusDisplayAllocationHint.test.ts`:50 副文案两条(免入库 / 送仓+自建)。
|
||||
- `server/tests/mainSystemFulfillmentEvents.test.ts`:两个开关的默认值表达式 + "成对"说明必须留在配置注释里。
|
||||
- 配置实测(`tsx -e` 打印 `config.mainSystemIntegration`):`fulfillmentEventsEnabled=true`、
|
||||
`skipInboundAwaitPickup=true`、`writebackEnabled=true`。
|
||||
- `src/pages/orders/orderManagement/orderManagementHelpers.skipInbound.test.ts`:映射器不丢字段 + 50 派生「待取货」。
|
||||
- 真实库/真实代码实测:`ORD_API_20261009_SUP35143228_0001`(分公司 `SUP35143228`)后端返回
|
||||
`order_status=50`、`is_skip_inbound=true`,台账 8 行 `skipInbound=true`(`all_skip=true`)。
|
||||
|
||||
### 9.5 仍然待决(不在本次定稿内)
|
||||
|
||||
- 主系统侧改成本价 → 我方审核入口(`preparations.price_changed` 接收端)**未做**。
|
||||
- 我方 `order_status >= 60/90` 的改价/改量拦截(不直写、改发申请)**未做**。
|
||||
- §8.7 提到的历史演示分公司(BR001/BR002)是否清理:**运维决策,仍然待定**(§8.7 正文引用的"§9"即本条)。
|
||||
|
||||
### 9.6 复核补丁:「整单免入库 ⇒ 我方不得有配送任务」(2026-10-11,开发者要求核查后)
|
||||
|
||||
**核查结论(本机真实库 + 主系统只读库)**
|
||||
|
||||
| 检查项 | 结果 |
|
||||
|---|---|
|
||||
| 全库「整单免入库」单(台账 `bool_and(skipInbound)`) | 只有 `ORD_API_20261009_SUP35143228_0001`(SUP35143228,状态 50) |
|
||||
| 该单是否有我方配送任务 | **无 ✓**(误建的那张当天已删) |
|
||||
| 其它主系统单的任务(SUP37831443 ×2、SUP92185841 ×1) | **合法**:主系统 `suppliers.skip_inbound = false`(送仓),台账也全行 `false` |
|
||||
| 该免入库客户是否绑过配送员 | 未绑(`customer_delivery_assignments` 0 行)⇒ 绑定旁路当时是"哑火",不代表没问题 |
|
||||
|
||||
**原实现有三个洞,本次一并修掉**
|
||||
|
||||
| # | 洞 | 修法 |
|
||||
|---|---|---|
|
||||
| ① | `customerDeliveryBindingService.syncCustomerPendingTasks` 是**唯一绕过公共卡点**的任务创建点(客户绑定配送员 → 给该客户所有 `order_status >= 50` 的单补建任务 + 指派配送员),**没有免入库排除** | INSERT 加 `AND NOT EXISTS (${fullySkipInboundOrderExistsSql('o.order_code','COALESCE(o.branch_code, $4)')})`,复用台账里那份同语义 SQL |
|
||||
| ② | 判定用 `bool_or`(任一行免入库即为真),与展示侧 `bool_and` 不一致 ⇒ **混合单**被误判成免入库(不派车、停 50 不收口、提前回写) | 语义收敛为 **`bool_and`**;函数更名 `isMainSystemSkipInboundOrder` → **`isOrderFullySkipInbound`**,并导出 `fullySkipInboundOrderExistsSql` 供 SQL 侧复用(防两套口径漂移) |
|
||||
| ③ | 「不建配送任务」的守卫以 `MAIN_SYSTEM_SKIP_INBOUND_AWAIT_PICKUP` 为前提 —— 该开关语义是"停 50 等主系统发车才收口",按 §3.4 回滚指引写 `0` 会把配送任务**放回来** | 守卫与开关**解耦**:只看"是否整单免入库"(两种口径下都不该派我方车) |
|
||||
|
||||
**覆盖确认**:`delivery_tasks` 的创建点只有三处 —— 公共卡点 `ensureDeliveryTaskForOrder`(分拣收尾/验收推进/备货齐套/处理单/自动推进/直送/配送列表补建/历史结案等 8+ 调用方都走它)、客户绑定回填(本次已堵)、`seed-mobile-accounts` 种子脚本(不参与业务)。
|
||||
|
||||
**明确不动的地方**:`delivery_tasks` 仍在 `/api/data` 网关可写名单里(`accessPolicy.ts` 29/215 行),有 `delivery_manage` / `order_manage` 权限的账号仍可绕过守卫直插任务 —— 属平台冻结面,**本次未动**。
|
||||
|
||||
**回归**:`skipInboundWritebackTiming` 第③组新增三条(守卫不依赖开关 / 判定是 `bool_and` / 旁路必须排除);`stockCoverAndSkipInboundAdvance` 的 `bool_or` 断言同步改为 `bool_and`。真实库实测:TS 判定与 SQL 判定对四类样本(免入库 / 两张送仓 / 原生单)**逐条一致**;绑定旁路对该免入库客户可补建任务数 = **0**。
|
||||
|
||||
**复核时又抓到一个真缺陷(2026-10-11 当天修复)**
|
||||
|
||||
`orderWorkflowFulfillmentService.tryAdvanceOrderToDelivery`(未启用分拣的 `40→50` 路径,供应商分公司的实际默认路径)
|
||||
里写的是 `enqueueMainSystemWritebackForReadyOrder(orderCode, branchCode)`,而函数签名是
|
||||
`(branchCode, orderCode)` —— **两个位置参数传反**。后果:回写内核按
|
||||
`(分公司='ORD_API_…0001', 我方单号='SUP35143228')` 去查台账 ⇒ **0 行、静默返回**,
|
||||
既不抛错也不打日志(实测:写反 = **0 行**,写对 = **8 行**)。于是该路径上"到 50 就回写"实际没发生,
|
||||
只靠对账兜底 —— 分配对账(10 分钟节流一次)里会跑 `retryPendingWritebacksForBranch`(`>= 50` 放行)
|
||||
⇒ **不是永久丢失,但会延迟到下一轮对账**。
|
||||
|
||||
修法(防同类复发,不只改这一处):三个回写触发函数(`...ForReadyOrder` / `...ForDeliveredOrder` /
|
||||
`enqueueSkipInboundWritebackIfReady`)**统一改为对象参数** `{ branchCode, orderCode }`,参数不全直接跳过;
|
||||
`skipInboundWritebackTiming` 新增一条用例扫描全部调用点,**只要出现位置参数写法即判失败**。
|
||||
(两个参数同为 `string`,TypeScript 拦不住这种传反 —— 所以用结构 + 用例两道拦。)
|
||||
@@ -0,0 +1,126 @@
|
||||
# 订单明细「核货完毕」标记(主系统免入库单)
|
||||
|
||||
> 2026-10-11 开发者请求:「主系统配送员已经将肉片、五花肉核货完毕了,子系统这边收到了就给这个订单里面多加一个状态表示这个商品核货完毕,我好方便测试。」
|
||||
> 本文只做**展示层的只读事实镜像**:不新增订单状态值、不改状态链、不回写主系统。
|
||||
|
||||
## 1. 事实来源(实测,2026-10-11)
|
||||
|
||||
| 通道 | 是否带"核货"事实 | 实测结论 |
|
||||
|---|---|---|
|
||||
| webhook `preparations.actual_qty_request` | ❌ **只在"核货量 ≠ 申报量"时才推** | 主系统 `raiseActualQtyRequestAfterPickingCheck` 里 `if (!decision.mismatch) return { raised: false }`;等量核货(肉片 3.5=3.5、五花肉 20=20)**不会产生事件**,我方收件箱实测 0 行 |
|
||||
| webhook `preparations.picked_up` | ⚠️ 有,但**要等骑手确认发车** | 取货后才推;开发者要在核货完成时就看到,太晚 |
|
||||
| `GET /preparations?view=active` | ✅ 有 `actual_qty`(免入库=核货实配 `picking_items.loaded_qty`) | 但我方回写 `prepare_status=30` 后该行**离开 active 视图**,实测 `rows=0` |
|
||||
| `GET /preparations?view=archived` | ✅ 同上 | 实测可取到(肉片 3.5 / 6.2、五花肉 20) |
|
||||
| **`POST /preparations/lookup`** | ✅ **同上(与列表同一份 SQL 常量)**,且按 `id`/`sku_code` 精确查,不受视图影响 | **本方案采用**:实测 8 行取回 `actual=3.5 / 6.2 / 20`,其余 5 行 `null` |
|
||||
|
||||
结论:**"核货完毕"只能靠拉取(lookup)获得**,事件通道对"等量核货"天然静默。
|
||||
|
||||
## 2. 判定规则
|
||||
|
||||
| 单型 | 判定 | 展示 |
|
||||
|---|---|---|
|
||||
| 主系统**免入库**行(`skipInbound=true`) | 台账该行 `actualQty != null`(核货实配已产生) | 行内小标签**「核货完毕」** |
|
||||
| 主系统**送仓**行 | 不走本标记(其"入库完成"已有既有标签,避免重复语义) | 不显示 |
|
||||
| 原生录单行 | 无台账行 ⇒ 恒不显示 | 不显示 |
|
||||
|
||||
⚠️ 不用 `actualQtyAt` 做判据:实测主系统该字段对免入库行**恒为 null**(其 SQL 取的是入库/出库时刻)。
|
||||
|
||||
## 3. 设计
|
||||
|
||||
| 落点 | 做法 |
|
||||
|---|---|
|
||||
| 落库 | 台账 `public.main_system_order_import_items.payload` 只更新 5 个键:`actualQty` / `actualQtyAt` / `qtyDiff` / `isInbounded` / `inboundAt`(`payload \|\| jsonb_build_object(...)`,**不动其它键**) |
|
||||
| 拉取 | 新服务 `mainSystemActualFacts.ts`:按台账的 `prep_id` 调一次 `lookup`,落库后回读 |
|
||||
| 读取 | `GET /orders/:orderCode/main-system-prep-facts` —— **只读库、不调外部**,详情打开即可用 |
|
||||
| 刷新 | `POST /orders/:orderCode/main-system-prep-facts/refresh` —— 拉一次并落库,返回最新事实 |
|
||||
| 定时兜底 | 分配对账(每分公司每轮,≤10 分钟节流)里对"在飞且尚未核货"的主系统单刷新一次,最多 10 单/轮,失败只日志 |
|
||||
| 前端 | 详情取数时并发拉一次 GET 并在后台触发 POST 刷新;回来后按 `our_order_item_id`(缺失时按 `sku_code + supplier_code`)合并进订单行,渲染标签 |
|
||||
|
||||
**为什么 GET 不做外部调用**:主系统抖动时不能让打开详情卡到超时;刷新是显式动作(后台触发),失败静默、下轮对账补。
|
||||
|
||||
## 4. 影响面与回滚
|
||||
|
||||
- **只加不改**:不新增/修改 `order_status` 任何取值与边;不动 `picking_items` / `inspections` / 库存;不回写主系统(lookup 语义只读)。
|
||||
- 台账 payload 是**快照字段**,新增 5 个键与既有导入写法同构(导入本来就会写这 5 个键)。
|
||||
- **回滚**:前端去掉标签 + 后端去掉两条路由即可,数据面无需回滚(多出来的 payload 键不影响任何既有判定)。
|
||||
|
||||
## 5. 验收标准(可执行)
|
||||
|
||||
1. `POST /orders/ORD_API_20261009_SUP35143228_0001/main-system-prep-facts/refresh` 返回 8 行,其中「肉片 ×2 / 五花肉」`checked=true` 且带核货量,其余 5 行 `checked=false`(实测主系统侧为 3.5 / 6.2 / 20)。
|
||||
2. 订单详情里这三行出现「核货完毕」标签,其余行不出现。
|
||||
3. `GET` 路由在**主系统不可达**时仍 200(返回库内已存事实),不得 500。
|
||||
4. 送仓单/原生单不出现该标签。
|
||||
|
||||
## 6. 实施记录(2026-10-11 实测)
|
||||
|
||||
**接口实测**(真实库 + 真实主系统,`ORD_API_20261009_SUP35143228_0001`):
|
||||
|
||||
```
|
||||
落库结果: { updated: 8, lookedUp: 8 }
|
||||
肉丝 / 大猪肉三线肉 / 精品梅花肉 / 排骨 / 碎肉 → actual=null ⇒ checked=false
|
||||
肉片(主系统单 0006)→ actual=3.5 ⇒ checked=true
|
||||
肉片(主系统单 0007)→ actual=6.2 ⇒ checked=true
|
||||
五花肉(主系统单 0008)→ actual=20 ⇒ checked=true
|
||||
```
|
||||
|
||||
与开发者描述一致("配送员已经把肉片、五花肉核货完毕")。
|
||||
|
||||
**路由实测**:`GET/POST /api/workflow/orders/:orderCode/main-system-prep-facts[/refresh]` 未带凭证返回 **401**(已挂载、走鉴权),对照的未知路由返回 404。
|
||||
|
||||
## 7. 实测暴露的**台账行级对照串行**问题(本次不修,需开发者裁决)
|
||||
|
||||
本单 8 行备货里有两行「肉片」(主系统单 `…_0006` 计划 3.5 斤、`…_0007` 计划 6 斤),
|
||||
但台账 `our_order_item_id` **都指向同一个我方订单行**(6 斤那条),而 3.5 斤那条订单行
|
||||
(`main_order_code` 为 null、在详情里归到「本系统录单」组)**没有任何台账行**。
|
||||
|
||||
| 影响面 | 说明 |
|
||||
|---|---|
|
||||
| 本标记 | 已用"同一 key 多条事实且数量不一致 ⇒ 只标已核货、不给数量"兜住(宁可少显示,不显示错数) |
|
||||
| ⚠️ 跨系统回写 | 回写按 `our_order_item_id` 取我方行的实供量/售价 ⇒ **0006 行可能报的是 6 斤那条的口径**(本单两行单价相同 8.30,暂看不出差异)。属"张冠李戴"风险,**未修** |
|
||||
| 根因 | 惰性对照按「同单 + 同商品名」匹配,遇到同名商品(两行肉片)会把两行备货都认领到同一个订单行 |
|
||||
|
||||
**建议**(待批准):惰性对照改为一对一消费(同一订单行不得被两行备货认领)——代码里已有
|
||||
`listClaimedOrderItemIds` 的"避免一行两认领"思路,但只覆盖了同一次调用内的去重。
|
||||
|
||||
## 8. 修复:同名商品的对照串行(2026-10-11,开发者批准后实施)
|
||||
|
||||
**根因**(实测本单):`persistRows` **按单**调用 `recordImportedPrepItems` ⇒ 每张主系统单都拿**全量**订单行
|
||||
再算一次"名字 + 出现次序"映射,而 `mapPrepRowsToOurItems` 只在**单次调用内**消费候选(池子不跨单扣减)
|
||||
⇒ 两张单的「肉片」都先认领同一条订单行(6 斤那条);台账 upsert 又对已有对照 `COALESCE(旧值, 新值)`(优先保留)
|
||||
⇒ 错值**永不自愈**,3.5 斤那条订单行一直空着(详情掉进「本系统录单」)。
|
||||
|
||||
**实际后果(已发生,实测)**:备齐回写按台账对照取我方订单行的数量/售价 ⇒ 主系统 `…_0006` 的备货行
|
||||
`prepare_qty` 被从 **3.5 写成 6**(带超量确认位),而它自己那张订单行的数量就是 3.5 斤。
|
||||
|
||||
| 改法 | 落点 |
|
||||
|---|---|
|
||||
| 新增 `mapOrderPrepRowsToOurItems`:**整单(跨主系统单)一对一**对照;同名桶内**数量吻合优先**、缺失/并列时退回出现次序;缺货行不占位;配不上留空 | `mainSystemPrepLedger.ts` |
|
||||
| `recordImportedPrepItems` 支持外部传入对照(`mapping`),`stampMainOrderCodes` 复用**同一份**对照 ⇒ 台账与来源单号列一致 | `mainSystemPrepLedger.ts` / `mainSystemOrderImport.ts` |
|
||||
| `persistRows` **算一次**整单对照 | `mainSystemOrderImport.ts` |
|
||||
| 新增 `healOrderPrepMapping`:存量纠正,**只动** `our_order_item_id IS NULL` 或**本单内被多行共用**(重复认领指纹)的行;`order_items.main_order_code` 只对参与冲突的行重盖;挂进导入链路每轮顺手纠一次 | `mainSystemPrepLedger.ts` / `mainSystemOrderImport.ts` |
|
||||
|
||||
**本单纠正结果(真实库实测,脚本幂等可重跑)**:
|
||||
|
||||
```
|
||||
纠正结果: { ledgerFixed: 1, itemCodesFixed: 1, duplicates: ['654ec846-…'] }
|
||||
肉片(…_0006,核货 3.5)→ 订单行 5c1b8a1f…(3.50 斤) ← 原来错挂 6 斤那条
|
||||
肉片(…_0007,核货 6.2)→ 订单行 654ec846…(6.00 斤)
|
||||
order_items.main_order_code:3.5 斤 → …_0006,6 斤 → …_0007(详情里不再出现假的「本系统录单」分组)
|
||||
```
|
||||
|
||||
**回归**:`orderScopePrepMapping.test.ts`(7 条:跨单同名按数量配对 / 缺失退回次序 / 缺货不占位 / 用完留空 /
|
||||
不同商品分桶 / 导入必须整单算一次 / 纠正规则保守)。
|
||||
|
||||
## 9. 主系统 `prepare_qty=6` 的收尾(2026-10-11 实测:集成通道改不了)
|
||||
|
||||
事实(真实主系统核对):`…_0006` 肉片 `prepare_qty = 6`、`prepare_status = 30`(已锁定)、
|
||||
`actual_qty = 3.5`(**核货实配是对的**)。
|
||||
|
||||
| 方案 | 实测结果 |
|
||||
|---|---|
|
||||
| ① 我方按修正后的对照**重发一次回写**(数量 3.5) | ❌ **被主系统拒绝**:`conflict 备货已确认锁定,不可修改(缺货标记除外)` ⇒ 我方按幂等记为 `done`(`writeback_reason` 已如实记录),不会反复重试 |
|
||||
| ② 走**改量申请通道** `submitPriceQtyRequest` | ❌ **表达不了**:该通道"原值"取的是**我方订单行**的值(本来就是 3.5)⇒ 判为 `no_change`,不会提交 |
|
||||
| ③ 主系统**管理端**改这一行 | ✅ 唯一可行:主系统有 `POST /admin/preparations/status`(支持 `prepare_qty`,管理员角色),即在其备货界面把该行数量改回 3.5 |
|
||||
|
||||
**纪律**:我方**不去改主系统的库**(两系统不互改数据)。该行显示 6 属对方数据面的收尾,
|
||||
我方侧已经一致(对照已修、我方申报量 3.5、后续回写带 3.5)。
|
||||
@@ -0,0 +1,113 @@
|
||||
# 实收数量与单位:事实登记 + 事后同步(主系统发起)
|
||||
|
||||
> 2026-10-11 开发者口径(本文件为其原话落实,**未实现前不得当作现状**)。
|
||||
> 与 [`20261011-跨系统改价改量审核.md`](20261011-跨系统改价改量审核.md)(**我方向主系统**发起)是**两条反方向的链**,勿混。
|
||||
|
||||
## 1. 需求原文(开发者 2026-10-11)
|
||||
|
||||
| 场景 | 主系统动作 | 我方动作 | 驳回后果 |
|
||||
|---|---|---|---|
|
||||
| **A. 子系统送货到主系统仓库**(送仓单):主系统**入库核查** | **先按实际入库量改自己的实收** → 与子系统记录有偏差就**发请求** | 管理员决定**是否同步**:同意 ⇒ 只改**子系统自己**的值;驳回 ⇒ 子系统不改 | **主系统不回滚**(保持实际值),双方各自留痕(详情 + 时间) |
|
||||
| **B. 主系统派配送员上门取货**(免入库单):**核货** | **核货多少就是多少**,先按原流程改自己的实收数量 → 与子系统实收不一致就**告诉子系统** | 同左 | 同左 |
|
||||
|
||||
**核心原则(开发者原话)**:「双方各自记录,**自己只能改自己的,不能改别人的**」。
|
||||
⇒ 本机制的"审核"**不是改值闸门**,而是**同步 + 留痕**:对方的实际值先落定,我方只决定"我这条记录要不要跟着改"。
|
||||
|
||||
**适用范围**:**实收数量 + 单位**。
|
||||
**单价不在此链**:子系统销售价 ↔ 主系统成本价 **只要存在变动就发申请**(走 `20261011-跨系统改价改量审核.md` 那条"先审后改"的通道)。
|
||||
|
||||
## 2. 与我方既有实现的差异(2026-10-11 实测代码)
|
||||
|
||||
| # | 项 | 现状 | 结论 |
|
||||
|---|---|---|---|
|
||||
| 1 | 事实登记语义 | `FACT_NODES = {picking_check}`:核货节点驳回不回滚 | **场景 B 已符合** ✅;需把 **`node=inbound` 也纳入事实登记**(场景 A) |
|
||||
| 2 | 同意后改我方值 | ❌ **未实现**:`main_system_actual_qty_requests.final_value` 除审计日志外**无任何消费方** | 必须补:同意 ⇒ 改我方值(落点见 §3) |
|
||||
| 3 | 请求语义/文案 | 台账与审核页把对方值叫「建议值」、动作叫「审核通过」 | 改为「**主系统实际值(已生效)**」+「**是否同步到本系统**」 |
|
||||
| 4 | 对方"已生效"的凭证 | 台账只有 `before_value / proposed_value`,**无对方生效时间** | 请求必须带 **`applied_at`**(对方实际值生效时刻)并落库 |
|
||||
| 5 | 入库节点入口 | 只有核货节点在用(`node` 缺省 `picking_check`) | 新增 `node=inbound` 的接收与展示 |
|
||||
| 6 | 驳回留痕可见面 | 台账字段齐全(`decided_at / decision_reason / final_value / fact_registered`),但只有「待我审核」列表 | 补「已同步 / 已驳回」历史(双方时间 + 原因 + 实际值/最终值) |
|
||||
| 7 | 我方发起被对方驳回 | 已有:`supplier_price_qty_requests.status='rejected'` + 原因回传 | 需在页面明确展示"被主系统驳回"的详情与时间(开发者第 5 条要求) |
|
||||
|
||||
## 3. 同步落点(我方数据面,**关键**)
|
||||
|
||||
我方**没有单一"实收数量"列**,实收是**派生值**(`resolveOrderItemReceivedQty`)。所以"同意同步"必须落到下面这些真实存储:
|
||||
|
||||
| 单型 | 我方实收的事实来源 | 同意同步 = 改这里 | 风险面 |
|
||||
|---|---|---|---|
|
||||
| **免入库**(骑手取货) | `picking_items.loaded_qty`(我方装车/核货实配,`loadingQtyEditable = skipInbound`) | 改该行 `loaded_qty`(+ 单位) | 只影响展示与对账,**不牵动库存** |
|
||||
| **送仓**(我方送货入库) | `inspections.actual_qty`(我方验收入库实收) | 改该行 `actual_qty`(+ 单位) | ⚠️ **牵动库存/成本/结算**(已入库、可能已出库/已结算)⇒ 必须分级(§4) |
|
||||
|
||||
**计划量**(开发者第 3 条,**2026-10-11 已确认"一起改,账一致优先"**):同意同步时,把该订单行
|
||||
**`order_items.quantity`(计划量)与实收口径一起**改成主系统实际值,金额按行单价重算
|
||||
(`amount = quantity × price`)。**这会改客户结算单/供应商结算单的金额** ⇒ 按 §4 分级处理
|
||||
(已入库走库存调整、已结算不直改只留痕)。
|
||||
|
||||
## 4. 分级规则(**2026-10-11 开发者已批准:按分级处理**)
|
||||
|
||||
| 该行当前状态 | 处理(复用既有服务,不新写财务算法) |
|
||||
|---|---|
|
||||
| 未入库(送仓)/ 免入库行 | 直接改实收(+ 计划量与金额):免入库改 `picking_items.loaded_qty`;送仓未入库改该验收行 `actual_qty` |
|
||||
| 已入库未出库 | 走**既有** `adjustInboundInspectionQty({orderCode, skuCode, qty, branchCode, operatorId, remark})` —— 它改 `inspections.actual_qty` **并按差额调批次可用库存**(内部走 `adjustInventoryAvailableQty`,备注必填、双日志) |
|
||||
| 已出库未结算 | 同上,另在订单/审计写明差异;计划量变动同时评估已出库口径 |
|
||||
| **已生成结算单 / 已结案 90** | **不直改历史**:落一条"需财务调整"的结论 + 审计(自动走结算调整/红冲**待财务面单独批准后再接**,本期只留痕并明确提示管理员) |
|
||||
|
||||
## 5. 台账与接口(复用现有通道,最小改动)
|
||||
|
||||
| 项 | 做法 |
|
||||
|---|---|
|
||||
| 接收 | 复用 `preparations.actual_qty_request`(webhook)⇒ `public.main_system_actual_qty_requests`;新增 `node='inbound'`、`field ∈ {qty, unit}`(现有已是通用 node/field 结构);**新增 `applied_at`(对方生效时刻)** |
|
||||
| 决策回传 | 复用 `POST /api/supplier/preparations/actual-qty-decision`(`approved` / `rejected`,可带 `final_value`) |
|
||||
| 同意落值 | **新增**:同意 ⇒ 写我方落点(§3)+ 记 `final_value / decided_at / reviewer`;驳回 ⇒ **只留痕,不改任何我方值** |
|
||||
| 退回主系统失败 | 沿用现有纪律:**回传成功才落我方结论**(否则挂 `suspended`,下轮重试) |
|
||||
| 留痕可见面 | 审核页「待我审核(主系统发起)」+ 新增「已同步 / 已驳回」;每条显示:节点、字段、**主系统实际值(已生效 + 时间)**、我方原值、我方最终值、决策人、决策时间、原因 |
|
||||
| 反方向(我方发起被驳回) | 在价量申请页展示 `rejected` + 原因 + 时间(开发者第 5 条) |
|
||||
|
||||
## 6. 影响面与回滚
|
||||
|
||||
- **财务冻结面**:计划量 + 实收数量变动 ⇒ 订单金额、客户/供应商结算单、成本口径。**分级规则(§4)获批前不得实现"已结算单直改"**。
|
||||
- **库存冻结面**:送仓单改 `inspections.actual_qty` 不得直改历史流水,只能走库存调整。
|
||||
- 不新增状态值、不改状态链;不改价格通道(价格仍走"变动即发申请")。
|
||||
- **回滚**:关掉"同意落值"开关即回到"只回执 + 留痕"的现状(数据无需回滚)。
|
||||
|
||||
## 7. 验收标准(可执行)
|
||||
|
||||
1. 场景 B:主系统核货 6.2 / 我方 6 ⇒ 收到请求(带 `applied_at`);同意后我方该行实收与计划量变为 6.2、金额重算、留痕含双方时间;驳回后我方值**不变**、主系统值**不回滚**,双方各有一条拒绝记录。
|
||||
2. 场景 A:主系统入库实收 3.5 / 我方申报 6 ⇒ 同上流程,落点为 `inspections.actual_qty`;**已入库行**必须同时产生库存调整记录。
|
||||
3. 对方不可改我方数据、我方不可改对方数据:全链路只出现"我方改我方 / 对方改对方 + 互相发请求"。
|
||||
4. 我方发起的价量申请被驳回时,页面可查"被主系统驳回"的详情与时间。
|
||||
|
||||
## 8. 实施清单(设计定稿 2026-10-11,**代码未动**)
|
||||
|
||||
| # | 改动 | 落点 |
|
||||
|---|---|---|
|
||||
| 1 | 台账新增 `applied_at`(对方实际值生效时刻)+ 载荷映射 | 迁移 `migrations/2026xxxx_main_system_actual_qty_applied_at.sql`、`mainSystemActualQtyInbox.ts` |
|
||||
| 2 | `FACT_NODES` 增加 `inbound`(入库也是事实登记:驳回不回滚) | `mainSystemActualQtyInbox.ts` |
|
||||
| 3 | **同意落值**(新):按 §3 落点 + §4 分级写我方数据,全部走既有服务;驳回只留痕 | 新增 `mainSystemActualQtyApply.ts`,由 `decideActualQtyRequest` 调用 |
|
||||
| 4 | 文案/动作语义:`建议值 → 主系统实际值(已生效)`、`审核通过 → 是否同步到本系统` | `PriceQtyRequestsPage.tsx` + `zh/en/id` 三语 |
|
||||
| 5 | 留痕可见面:「已同步 / 已驳回」历史(双方时间、原因、实际值/最终值);我方发起被主系统驳回的详情+时间 | `PriceQtyRequestsPage.tsx`(价量申请区) |
|
||||
| 6 | 契约条目(**需要主系统配合**):`preparations.actual_qty_request` 增加 `node='inbound'` 与 `applied_at`;驳回回执带原因 | `docs/给主系统AI的对接改造清单.md` |
|
||||
|
||||
## 9. 实施记录(2026-10-11 第 1 批:清单 1–3 已落地)
|
||||
|
||||
| # | 项 | 落地 | 实测 |
|
||||
|---|---|---|---|
|
||||
| 1 | 台账 `applied_at`(对方实际值生效时刻) | 迁移 `migrations/20261023_main_system_actual_qty_applied_at.sql`(`IF NOT EXISTS`,已 `db:migrate` 应用);`mapActualQtyRequestPayload` 映射 `applied_at`;`recordActualQtyRequest` 落库 + 审计带上 | 迁移输出 `Applied 20261023_…` ✅ |
|
||||
| 2 | `inbound` 纳入事实登记 | `FACT_NODES = ['picking_check', 'inbound']`(驳回不回滚) | `tests/actualQtyFactSync.test.ts` + `actualQtyInbox.test.ts` 钉住 ✅ |
|
||||
| 3 | **同意才落值**(只改我方) | 新服务 `mainSystemActualQtyApply.ts`:免入库 ⇒ 惰性补核货行(`includeAllItems`,租户上下文内)+ 改 `picking_items.loaded_qty`;送仓未入库 ⇒ 改最新验收 `actual_qty`;送仓已入库 ⇒ 复用 `adjustInboundInspectionQty`(改实收 + 按差额调批次可用库存);**已结算/已结案 ⇒ 不直改历史**,只落"需财务调整";**计划量 + 金额一起改**;台账定位不到 ⇒ **不落值**(不猜) | 可逆实测(真实库,跑完已还原):`loaded_qty → 19.5`、`计划量 20 → 19.5`、`金额 180 → 175.5`;随后还原为 `20 / 180` ✅ |
|
||||
|
||||
**实测踩到并修掉的两个坑**(写给自己/后人):
|
||||
|
||||
1. `ensureSkipInboundLoadingLines` **必须在租户上下文内调用**,否则报 `relation "order_items" does not exist`(首版漏了,落值会"只改订单行、实收没落");
|
||||
2. 免入库单的核货行是**惰性补建**的:本单此前根本没有 `picking_items` 行,且本地 `suppliers` / `supplier_preparations` 为空 ⇒ 该服务的免入库条件筛不出一行;改用 `{ includeAllItems: true }`(**免入库结论来自主系统台账,比本地标记权威**)。验证期间补建的 8 行已删除,订单数据回到验证前状态。
|
||||
|
||||
## 10. 实施记录(2026-10-11 第 2 批:审核页语义与留痕视图)
|
||||
|
||||
| # | 项 | 落地 |
|
||||
|---|---|---|
|
||||
| 4 | 审核页语义:表头「最终值」→「**主系统实际值(已生效)**」+ 新增「**对方生效时间**」列;动作「通过/改值后通过/驳回」→「**同步到本系统 / 改值后同步 / 驳回(不同步)**」;区头说明改为"对方实际值已生效,这里决定是否同步(驳回只留痕、不影响对方)" | `PriceQtyRequestsPage.tsx` + `zh-CN/en/id` 三语(`colMainActual/colAppliedAt/inboxReviewNote/actApprove/actApproveWithValue/actReject`) |
|
||||
| 5 | 新增「**已处理(已同步 / 已驳回)**」历史表:商品/我方单号/节点/字段/主系统实际值/生效时间/我方最终值/状态/决策人与时间/**我方落值结果**(`payload.apply.note`,含"需财务调整"这类结论) | 同上 + 新增键 `historyTitle/historyEmpty/statusSynced/statusRejectedNoSync/colDecidedAt/colApplyNote/nodeInbound` |
|
||||
| 6 | 我方发起的价量申请:决策列补**决策时间**(被主系统驳回时能查"详情 + 时间") | 同上 |
|
||||
|
||||
**回归**:`PriceQtyRequestsPage.render.test.tsx`(动作文案/生效时间列/历史区)、`src/i18n`(三语键一致)。
|
||||
|
||||
**至此第 1、2 批全部落地**;剩余仅"主系统按 §2.9 发 `node=inbound` + `applied_at`"(已在《给主系统 AI 的对接改造清单》§2.9 提出,等对方回执)。
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,34 @@
|
||||
-- 2026-10-08 空库重放修复(供应商系统二次开发):
|
||||
--
|
||||
-- 问题:`20260627_market_invoice_api_integration.sql` 要 ALTER 的 market_prices,
|
||||
-- 其实由**排序更晚**的 `20260701_v9_full_completion.sql` 创建。
|
||||
-- 主系统库里 20260701 的执行时间是 06-27、20260627 是 06-29(当年是倒序执行的,
|
||||
-- 文件后来被改过名),所以老库没事;**全新库按文件名排序重放时必然 42P01 中断**。
|
||||
--
|
||||
-- 本文件不修改任何历史迁移的内容,只在更早的位置把该表按最终形态建出来,
|
||||
-- 使 20260627(ADD COLUMN IF NOT EXISTS price_source)与 20260701(CREATE TABLE IF NOT EXISTS)
|
||||
-- 两条都退化为幂等空操作,最终 schema 与老库一致:
|
||||
-- · 表结构取自 20260701 的定义;
|
||||
-- · price_source 是 20260627 要补的列,这里直接建进表,避免空操作后缺列。
|
||||
--
|
||||
-- 已应用过 20260627 / 20260701 的库:本文件是 IF NOT EXISTS 空操作,无任何影响。
|
||||
|
||||
CREATE TABLE IF NOT EXISTS market_prices (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
sku_code VARCHAR(50) NOT NULL,
|
||||
sku_name VARCHAR(200),
|
||||
category_code VARCHAR(50),
|
||||
market_price DECIMAL(10,2) NOT NULL DEFAULT 0,
|
||||
our_price DECIMAL(10,2) NOT NULL DEFAULT 0,
|
||||
deviation_rate DECIMAL(8,4) NOT NULL DEFAULT 0,
|
||||
price_level VARCHAR(10) NOT NULL DEFAULT 'normal',
|
||||
province VARCHAR(50) DEFAULT '四川',
|
||||
market_name VARCHAR(100) DEFAULT '批发市场',
|
||||
branch_code VARCHAR(50) REFERENCES branches(branch_code),
|
||||
price_source VARCHAR(30),
|
||||
updated_at TIMESTAMPTZ DEFAULT NOW(),
|
||||
UNIQUE(sku_code, province)
|
||||
);
|
||||
|
||||
-- 与 20260627 中同名索引保持一致(该文件仍会以 IF NOT EXISTS 执行一次)
|
||||
CREATE INDEX IF NOT EXISTS idx_market_prices_source ON market_prices(price_source);
|
||||
@@ -1,5 +1,24 @@
|
||||
-- 自定义角色可写入 user_roles:role 列从 app_role 枚举改为 TEXT(与 role_permissions 一致)
|
||||
--
|
||||
-- 2026-10-08 空库重放修复(供应商系统二次开发):
|
||||
-- 2026-09-24 那轮「空库重放修复」给早期 RLS 策略加了 `user_roles.role::text`
|
||||
-- (枚举期 / text 期都成立,语义不变),但这些策略**引用了 role 列**,
|
||||
-- 而 PostgreSQL 不允许修改被策略引用的列类型:
|
||||
-- 0A000 cannot alter type of a column used in a policy definition
|
||||
-- 于是空库重放时本迁移必失败,并连带 20260916 的外键迁移(42804)一起失败。
|
||||
--
|
||||
-- 修法:改类型前先摘下依赖该列的策略,改完按原定义装回;表达式里的 `::app_role`
|
||||
-- 改写为 `::text`(装回时该列已是 text,不改写会报 operator does not exist)。
|
||||
-- 老库(role 已是 varchar/text,条件不成立)不进这个分支,行为完全不变。
|
||||
DO $$
|
||||
DECLARE
|
||||
rec record;
|
||||
saved jsonb := '[]'::jsonb;
|
||||
-- '::app_role' 这个字面量必须运行时拼出来:
|
||||
-- 迁移器 migrate.ts 的 normalizeMigrationSql() 会把 SQL 文本里的
|
||||
-- '::app_role / ::app_role 一律删掉(把枚举字面量降级成普通字符串),
|
||||
-- 直接写死会被改写,导致下面的 replace 变成空模式、退化成"什么都不替换"。
|
||||
v_enum_cast text := chr(58) || chr(58) || 'app_role';
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
@@ -8,6 +27,69 @@ BEGIN
|
||||
AND column_name = 'role'
|
||||
AND udt_name = 'app_role'
|
||||
) THEN
|
||||
-- ① 记录并摘下所有引用了 user_roles.role 的策略
|
||||
FOR rec IN
|
||||
SELECT p.polname,
|
||||
p.polrelid::regclass::text AS relname,
|
||||
p.polcmd,
|
||||
p.polpermissive,
|
||||
pg_get_expr(p.polqual, p.polrelid) AS qual,
|
||||
pg_get_expr(p.polwithcheck, p.polrelid) AS withcheck,
|
||||
(SELECT string_agg(quote_ident(r.rolname), ', ')
|
||||
FROM pg_roles r
|
||||
WHERE r.oid = ANY(p.polroles)) AS roles
|
||||
FROM pg_policy p
|
||||
JOIN pg_depend d
|
||||
ON d.classid = 'pg_policy'::regclass
|
||||
AND d.objid = p.oid
|
||||
WHERE d.refobjid = 'public.user_roles'::regclass
|
||||
AND d.refobjsubid = (
|
||||
SELECT attnum FROM pg_attribute
|
||||
WHERE attrelid = 'public.user_roles'::regclass
|
||||
AND attname = 'role'
|
||||
)
|
||||
LOOP
|
||||
saved := saved || jsonb_build_object(
|
||||
'name', rec.polname,
|
||||
'rel', rec.relname,
|
||||
'cmd', rec.polcmd,
|
||||
'permissive', rec.polpermissive,
|
||||
'qual', rec.qual,
|
||||
'withcheck', rec.withcheck,
|
||||
'roles', rec.roles
|
||||
);
|
||||
EXECUTE format('DROP POLICY %I ON %s', rec.polname, rec.relname);
|
||||
END LOOP;
|
||||
|
||||
-- ② 改类型
|
||||
ALTER TABLE public.user_roles ALTER COLUMN role TYPE TEXT USING role::text;
|
||||
|
||||
-- ③ 按原定义装回(roles 为 NULL ⇒ TO PUBLIC)
|
||||
FOR rec IN
|
||||
SELECT * FROM jsonb_to_recordset(saved)
|
||||
AS x(name text, rel text, cmd text, permissive boolean,
|
||||
qual text, withcheck text, roles text)
|
||||
LOOP
|
||||
EXECUTE format(
|
||||
'CREATE POLICY %I ON %s AS %s FOR %s TO %s%s%s',
|
||||
rec.name,
|
||||
rec.rel,
|
||||
CASE WHEN rec.permissive THEN 'PERMISSIVE' ELSE 'RESTRICTIVE' END,
|
||||
CASE rec.cmd
|
||||
WHEN '*' THEN 'ALL'
|
||||
WHEN 'r' THEN 'SELECT'
|
||||
WHEN 'a' THEN 'INSERT'
|
||||
WHEN 'w' THEN 'UPDATE'
|
||||
WHEN 'd' THEN 'DELETE'
|
||||
END,
|
||||
COALESCE(rec.roles, 'PUBLIC'),
|
||||
CASE WHEN rec.qual IS NOT NULL
|
||||
THEN ' USING (' || replace(rec.qual, v_enum_cast, '::text') || ')'
|
||||
ELSE '' END,
|
||||
CASE WHEN rec.withcheck IS NOT NULL
|
||||
THEN ' WITH CHECK (' || replace(rec.withcheck, v_enum_cast, '::text') || ')'
|
||||
ELSE '' END
|
||||
);
|
||||
END LOOP;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
@@ -31,12 +31,21 @@ BEGIN
|
||||
END IF;
|
||||
|
||||
-- 分类名 → 分类码:每个名字必须**唯一命中**,否则整支失败(宁可失败也不要只配一半)
|
||||
--
|
||||
-- 2026-10-08 空库重放修复(供应商系统二次开发):全新库/未建分类的环境里 product_catalog
|
||||
-- 一条分类都没有,原逻辑 hits=0 直接 RAISE EXCEPTION,会让整条迁移链在空库上中断。
|
||||
-- 分类**不存在**(0 条)⇒ 该环境无此业务数据,本迁移无事可做,跳过;命中多条仍是歧义,
|
||||
-- 保持失败(不改变「宁可失败也不要只配一半」的原意)。
|
||||
FOR i IN 1..array_length(cfg_names, 1) LOOP
|
||||
EXECUTE format(
|
||||
'SELECT count(*)::int FROM %I.product_catalog
|
||||
WHERE item_type = ''category'' AND name = $1 AND COALESCE(status, 1) = 1',
|
||||
sch
|
||||
) INTO hits USING cfg_names[i];
|
||||
IF hits = 0 THEN
|
||||
RAISE NOTICE '分类「%」在 % 不存在(空库/未建分类),跳过本次扣点配置', cfg_names[i], sch;
|
||||
RETURN;
|
||||
END IF;
|
||||
IF hits <> 1 THEN
|
||||
RAISE EXCEPTION '分类「%」在 % 命中 % 条(需恰好 1 条),已中止', cfg_names[i], sch, hits;
|
||||
END IF;
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
-- 供应商系统二次开发:账号来源标记
|
||||
--
|
||||
-- 背景:本系统的「分公司管理员」账号由**主系统的供应商账号**惰性开通
|
||||
-- (登录时向主系统校验通过 → 自动建分公司 + 管理员账号)。
|
||||
-- 这类账号的密码权威在主系统,本地不校验密码;
|
||||
-- 本系统自建的员工/平台账号则完全走本地校验。
|
||||
-- 用本列区分两类账号,避免"本地密码"与"主系统密码"两套并存时
|
||||
-- 出现"用哪套能进"取决于分支顺序的问题。
|
||||
--
|
||||
-- 取值:
|
||||
-- local 本系统自建(员工、平台管理员等)—— 本地 bcrypt 校验
|
||||
-- main_supplier 由主系统供应商账号惰性开通 —— 每次登录回主系统校验,本地密码不可用
|
||||
|
||||
ALTER TABLE public.profiles
|
||||
ADD COLUMN IF NOT EXISTS account_source varchar(20) NOT NULL DEFAULT 'local';
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint WHERE conname = 'profiles_account_source_check'
|
||||
) THEN
|
||||
ALTER TABLE public.profiles
|
||||
ADD CONSTRAINT profiles_account_source_check
|
||||
CHECK (account_source IN ('local', 'main_supplier'));
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
COMMENT ON COLUMN public.profiles.account_source IS
|
||||
'账号来源:local=本系统自建(本地校验密码);main_supplier=主系统供应商账号惰性开通(回主系统校验)';
|
||||
@@ -0,0 +1,31 @@
|
||||
-- 主系统订单导入台账(供应商系统二次开发)
|
||||
--
|
||||
-- 用途:主系统把订单商品「分配」给某供应商(= 本系统某分公司)后,
|
||||
-- 本系统拉取备货行、走自己的录单流程生成订单。本表记录
|
||||
-- 「主系统订单号 → 本系统订单号」的对应关系,用于:
|
||||
-- 1. 幂等:同一张主系统订单不重复建单;
|
||||
-- 2. 追溯:此后主系统退货 / 改供时,可据此找到本系统对应订单;
|
||||
-- 3. 快照:payload 留原始备货行,便于与后续变化做对比。
|
||||
--
|
||||
-- 注意:这是 public 层的跨系统台账,不是分公司业务表,
|
||||
-- 因此不进 tenant_business_tables()(该名单只管 tenant_template 里的表)。
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.main_system_order_imports (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
branch_code varchar(50) NOT NULL,
|
||||
main_supplier_code varchar(50) NOT NULL,
|
||||
main_order_code varchar(100) NOT NULL,
|
||||
our_order_code varchar(50),
|
||||
row_count integer NOT NULL DEFAULT 0,
|
||||
/** 原始备货行快照(退货/改供对比用) */
|
||||
payload jsonb NOT NULL DEFAULT '[]'::jsonb,
|
||||
imported_at timestamptz NOT NULL DEFAULT NOW(),
|
||||
created_by uuid,
|
||||
UNIQUE (branch_code, main_order_code)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_main_system_order_imports_branch
|
||||
ON public.main_system_order_imports (branch_code, imported_at DESC);
|
||||
|
||||
COMMENT ON TABLE public.main_system_order_imports IS
|
||||
'主系统分配订单 → 本系统订单 的导入台账(含原始备货行快照与幂等键)';
|
||||
@@ -0,0 +1,170 @@
|
||||
-- 空库重放修复(供应商系统二次开发,2026-10-08)
|
||||
--
|
||||
-- 症状:在本系统(以及任何全新库)里**新建商品会失败**:
|
||||
-- column "low_stock_alert" of relation "skus" does not exist
|
||||
-- 报错来自触发器函数 public.sync_product_catalog_to_legacy()(写 product_catalog → 同步旧表 skus)。
|
||||
--
|
||||
-- 根因:又是「迁移文件改过名 → 空库按文件名排序重放 ≠ 老库当年的执行顺序」。
|
||||
-- 老库实际顺序(主系统 schema_migrations 实测):
|
||||
-- 20260914_sku_low_stock_alert.sql 09-14 16:38:37 ← 旧布尔列 + 旧函数体
|
||||
-- 20260915_low_stock_alert_default_dry_goods 09-14 16:38:37 ← 又是旧函数体
|
||||
-- 20260914_sku_low_stock_alert_qty.sql 09-15 14:25:57 ← **最后执行**:加 *_qty、删旧列、换新函数体
|
||||
-- 但按文件名排序时 `20260914_..._qty.sql` 排在 `20260915_...` **之前**,
|
||||
-- 于是空库重放的最后一次函数定义来自 20260915 的**旧函数体**,它仍在引用已被删除的
|
||||
-- `skus.low_stock_alert`;同时 20260915 又把 `low_stock_alert_default` 列加了回来
|
||||
-- (老库里该列已被退役删除)。
|
||||
--
|
||||
-- 修法:新增本迁移排在最后,把 `20260914_sku_low_stock_alert_qty.sql` 的最终形态**再执行一次**
|
||||
-- (新函数体 + 退役 low_stock_alert_default 列)。不改任何历史迁移内容。
|
||||
-- 已应用过的老库:函数体重放是幂等的、列删除有存在性判断,无副作用。
|
||||
|
||||
CREATE OR REPLACE FUNCTION public.sync_product_catalog_to_legacy()
|
||||
RETURNS TRIGGER AS $$
|
||||
DECLARE
|
||||
v_branch VARCHAR(50);
|
||||
BEGIN
|
||||
IF TG_OP = 'DELETE' THEN
|
||||
v_branch := COALESCE(OLD.branch_code, (
|
||||
SELECT branch_code FROM branches WHERE status = 1 ORDER BY branch_code LIMIT 1
|
||||
));
|
||||
IF OLD.item_type = 'category' THEN
|
||||
DELETE FROM categories
|
||||
WHERE category_code = OLD.code AND branch_code = v_branch;
|
||||
ELSE
|
||||
DELETE FROM skus WHERE sku_code = OLD.code;
|
||||
END IF;
|
||||
RETURN OLD;
|
||||
END IF;
|
||||
|
||||
v_branch := COALESCE(NEW.branch_code, (
|
||||
SELECT branch_code FROM branches WHERE status = 1 ORDER BY branch_code LIMIT 1
|
||||
));
|
||||
|
||||
IF NEW.item_type = 'category' THEN
|
||||
INSERT INTO categories (
|
||||
branch_code, category_code, parent_code, category_name, level, sort_order,
|
||||
loss_threshold, is_fresh, requires_photo_inspection,
|
||||
requires_quality_report, quality_report_type, quality_report_label,
|
||||
quality_report_share_scope, merge_same_day_fulfillment,
|
||||
status, created_at
|
||||
) VALUES (
|
||||
v_branch,
|
||||
NEW.code, NEW.parent_code, NEW.name, COALESCE(NEW.level, 1), COALESCE(NEW.sort_order, 0),
|
||||
COALESCE(NEW.loss_threshold, 5.00), COALESCE(NEW.is_fresh, true),
|
||||
COALESCE(NEW.requires_photo_inspection, true),
|
||||
COALESCE(NEW.requires_quality_report, false),
|
||||
NEW.quality_report_type,
|
||||
NEW.quality_report_label,
|
||||
COALESCE(NEW.quality_report_share_scope, 'category'),
|
||||
COALESCE(NEW.merge_same_day_fulfillment, false),
|
||||
COALESCE(NEW.status, 1),
|
||||
COALESCE(NEW.created_at, NOW())
|
||||
)
|
||||
ON CONFLICT (branch_code, category_code) DO UPDATE SET
|
||||
parent_code = EXCLUDED.parent_code,
|
||||
category_name = EXCLUDED.category_name,
|
||||
level = EXCLUDED.level,
|
||||
sort_order = EXCLUDED.sort_order,
|
||||
loss_threshold = EXCLUDED.loss_threshold,
|
||||
is_fresh = EXCLUDED.is_fresh,
|
||||
requires_photo_inspection = EXCLUDED.requires_photo_inspection,
|
||||
requires_quality_report = EXCLUDED.requires_quality_report,
|
||||
quality_report_type = EXCLUDED.quality_report_type,
|
||||
quality_report_label = EXCLUDED.quality_report_label,
|
||||
quality_report_share_scope = EXCLUDED.quality_report_share_scope,
|
||||
merge_same_day_fulfillment = EXCLUDED.merge_same_day_fulfillment,
|
||||
status = EXCLUDED.status;
|
||||
ELSE
|
||||
INSERT INTO skus (
|
||||
branch_code, sku_code, sku_name, category_code, unit, pricing_unit, pack_factors,
|
||||
spec, barcode, image_url,
|
||||
image_data, image_mime_type, is_prepackaged, brand, tax_code, tax_rate,
|
||||
default_loss_threshold, stock_mode, direct_delivery, low_stock_alert_qty, status, created_at
|
||||
) VALUES (
|
||||
v_branch, NEW.code, NEW.name, NEW.parent_code,
|
||||
COALESCE(NEW.unit, '斤'),
|
||||
COALESCE(NULLIF(TRIM(NEW.pricing_unit), ''), COALESCE(NEW.unit, '斤')),
|
||||
COALESCE(NEW.pack_factors, '{}'::jsonb),
|
||||
NEW.spec, NEW.barcode, NEW.image_url,
|
||||
NEW.image_data, NEW.image_mime_type, COALESCE(NEW.is_prepackaged, false), NEW.brand,
|
||||
NULLIF(TRIM(NEW.tax_code), ''), NEW.tax_rate,
|
||||
NEW.default_loss_threshold,
|
||||
NULLIF(TRIM(NEW.stock_mode), ''),
|
||||
COALESCE(NEW.direct_delivery, false),
|
||||
COALESCE(NEW.low_stock_alert_qty, 0),
|
||||
COALESCE(NEW.status, 1), COALESCE(NEW.created_at, NOW())
|
||||
)
|
||||
ON CONFLICT (sku_code) DO UPDATE SET
|
||||
branch_code = EXCLUDED.branch_code,
|
||||
sku_name = EXCLUDED.sku_name,
|
||||
category_code = EXCLUDED.category_code,
|
||||
unit = EXCLUDED.unit,
|
||||
pricing_unit = EXCLUDED.pricing_unit,
|
||||
pack_factors = EXCLUDED.pack_factors,
|
||||
spec = EXCLUDED.spec,
|
||||
barcode = EXCLUDED.barcode,
|
||||
image_url = EXCLUDED.image_url,
|
||||
image_data = EXCLUDED.image_data,
|
||||
image_mime_type = EXCLUDED.image_mime_type,
|
||||
is_prepackaged = EXCLUDED.is_prepackaged,
|
||||
brand = EXCLUDED.brand,
|
||||
tax_code = EXCLUDED.tax_code,
|
||||
tax_rate = EXCLUDED.tax_rate,
|
||||
default_loss_threshold = EXCLUDED.default_loss_threshold,
|
||||
stock_mode = EXCLUDED.stock_mode,
|
||||
direct_delivery = EXCLUDED.direct_delivery,
|
||||
low_stock_alert_qty = EXCLUDED.low_stock_alert_qty,
|
||||
status = EXCLUDED.status;
|
||||
END IF;
|
||||
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
-- ============================================================
|
||||
-- 4) 删除旧列(触发器已重建,不再引用)
|
||||
-- ============================================================
|
||||
DO $$
|
||||
DECLARE
|
||||
sch text;
|
||||
BEGIN
|
||||
FOR sch IN
|
||||
SELECT nspname
|
||||
FROM pg_namespace
|
||||
WHERE nspname IN ('public', 'tenant_template')
|
||||
OR nspname LIKE 'tenant_%'
|
||||
ORDER BY CASE nspname
|
||||
WHEN 'public' THEN 0
|
||||
WHEN 'tenant_template' THEN 1
|
||||
ELSE 2
|
||||
END, nspname
|
||||
LOOP
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_schema = sch AND table_name = 'skus' AND column_name = 'low_stock_alert'
|
||||
) THEN
|
||||
EXECUTE format('ALTER TABLE %I.skus DROP COLUMN low_stock_alert', sch);
|
||||
END IF;
|
||||
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_schema = sch AND table_name = 'product_catalog' AND column_name = 'low_stock_alert'
|
||||
) THEN
|
||||
EXECUTE format('ALTER TABLE %I.product_catalog DROP COLUMN low_stock_alert', sch);
|
||||
END IF;
|
||||
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_schema = sch AND table_name = 'categories' AND column_name = 'low_stock_alert_default'
|
||||
) THEN
|
||||
EXECUTE format('ALTER TABLE %I.categories DROP COLUMN low_stock_alert_default', sch);
|
||||
END IF;
|
||||
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_schema = sch AND table_name = 'product_catalog' AND column_name = 'low_stock_alert_default'
|
||||
) THEN
|
||||
EXECUTE format('ALTER TABLE %I.product_catalog DROP COLUMN low_stock_alert_default', sch);
|
||||
END IF;
|
||||
END LOOP;
|
||||
END $$;
|
||||
@@ -0,0 +1,96 @@
|
||||
-- 主系统分配订单的**行级**对照台账(供应商系统二次开发 · 2026-10-08)
|
||||
--
|
||||
-- 为什么需要它:整单台账 `public.main_system_order_imports` 只有「主系统订单号 → 本系统订单号」,
|
||||
-- 没有「主系统备货行 id → 本系统订单行 id」。而主系统对某个商品**退货**(订单里删掉该商品并红冲)
|
||||
-- 时备货行会**物理删除**、从 `view=active` 消失,本系统必须能精确定位到自己的哪一行去跟随红冲。
|
||||
-- 见 docs/design/20261008-第三方订单退货跟随与发车回写方案.md §3.1。
|
||||
--
|
||||
-- 注意:
|
||||
-- 1. 这是 public 层的跨系统对照台账,**不是分公司业务表** ⇒ 不进 tenant_business_tables()
|
||||
-- (该名单只管 tenant_template 里的表;迁移守卫 assert_tenant_template_matches_business_tables 与它无关)。
|
||||
-- 2. 不往 `order_items` 加列(订单/商品冻结面),来源标识靠本表 + `ORD_API_%` 双保险。
|
||||
-- 3. `disposition` 同时是幂等与审计依据。
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.main_system_order_import_items (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
branch_code varchar(50) NOT NULL,
|
||||
main_order_code varchar(100) NOT NULL,
|
||||
/** 主系统备货行 id —— 与本系统的对照键(幂等键的一半) */
|
||||
prep_id uuid NOT NULL,
|
||||
our_order_code varchar(50),
|
||||
our_order_item_id uuid,
|
||||
main_supplier_code varchar(50),
|
||||
/** 主系统商品编码(本系统现在没落库,导致两边两套码;先记下来便于将来对账/匹配) */
|
||||
main_sku_code varchar(100),
|
||||
item_name varchar(200),
|
||||
last_prepare_qty numeric,
|
||||
last_prepare_status integer,
|
||||
last_return_code varchar(50),
|
||||
/**
|
||||
* 本系统**最后一次在主系统 active 列表里看到这一行**的时间。
|
||||
* 判退货时必须先看它:只有"我们确实看着它在 active、后来消失了"才算退货候选;
|
||||
* 从没在 active 见过(启用跟随前就已不在,或历史回填的行)一律不自动红冲,只挂人工核对。
|
||||
* 没有这一列会在启用开关那一刻把历史已完成的行误判成退货(对抗式复查 #3 的放大效应)。
|
||||
*/
|
||||
last_seen_active_at timestamptz,
|
||||
/**
|
||||
* pending 已对照、未处置(导入前)
|
||||
* imported 已建成本系统订单行
|
||||
* completed 已在主系统正常完成归档(不是退货)
|
||||
* returned 已按退货红冲跟随
|
||||
* cancelled 已按取消履约删行
|
||||
* suspended 挂待处理(已发车/已结案/无法定位/部分数量等)
|
||||
*/
|
||||
disposition varchar(20) NOT NULL DEFAULT 'pending',
|
||||
disposition_reason text,
|
||||
disposed_at timestamptz,
|
||||
/** 发车回写主系统的结果:none | done | skipped_zero_price | suspended | rejected */
|
||||
writeback_status varchar(24) NOT NULL DEFAULT 'none',
|
||||
writeback_reason text,
|
||||
writeback_at timestamptz,
|
||||
/** 主系统原始备货行快照(用于 diff 与追溯) */
|
||||
payload jsonb NOT NULL DEFAULT '{}'::jsonb,
|
||||
created_at timestamptz NOT NULL DEFAULT NOW(),
|
||||
updated_at timestamptz NOT NULL DEFAULT NOW(),
|
||||
UNIQUE (branch_code, prep_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_main_system_import_items_order
|
||||
ON public.main_system_order_import_items (branch_code, main_order_code);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_main_system_import_items_our_order
|
||||
ON public.main_system_order_import_items (branch_code, our_order_code);
|
||||
|
||||
COMMENT ON TABLE public.main_system_order_import_items IS
|
||||
'主系统备货行 → 本系统订单行 的行级对照台账(退货跟随/回写的幂等键与审计依据)';
|
||||
|
||||
-- 存量回填:把已导入订单的 payload 行快照铺平成行级对照。
|
||||
-- 只填对照关系,**不改任何业务数据**;payload 里没有 id 的行跳过。
|
||||
INSERT INTO public.main_system_order_import_items (
|
||||
branch_code, main_order_code, prep_id, our_order_code, main_supplier_code,
|
||||
main_sku_code, item_name, last_prepare_qty, last_prepare_status, last_return_code,
|
||||
disposition, payload
|
||||
)
|
||||
SELECT
|
||||
i.branch_code,
|
||||
i.main_order_code,
|
||||
(r->>'id')::uuid,
|
||||
i.our_order_code,
|
||||
i.main_supplier_code,
|
||||
r->>'skuCode',
|
||||
r->>'itemName',
|
||||
NULLIF(r->>'prepareQty', '')::numeric,
|
||||
NULLIF(r->>'prepareStatus', '')::int,
|
||||
NULLIF(r->>'returnCode', ''),
|
||||
CASE WHEN i.our_order_code IS NULL THEN 'pending' ELSE 'imported' END,
|
||||
r
|
||||
FROM public.main_system_order_imports i
|
||||
CROSS JOIN LATERAL jsonb_array_elements(i.payload) AS r
|
||||
WHERE COALESCE(r->>'id', '') <> ''
|
||||
ON CONFLICT (branch_code, prep_id) DO NOTHING;
|
||||
|
||||
-- 说明(重要):这里**不**回填 `our_order_item_id`。
|
||||
-- 原因:迁移以应用角色(非超管)执行且**没有租户上下文**,而 `tenant_*.order_items` 挂了 RLS
|
||||
-- —— 实测无 `app.branch_code` 时可见 0 行、设置后可见 9 行,所以 SQL 里按名字回填**必然匹配不到**。
|
||||
-- 改由应用层在"退货跟随处置"时惰性对照(那时处于 runWithTenantDbContext 内,RLS 满足),
|
||||
-- 对照结果写回本表,只需成功一次。见 server/src/services/mainSystemReturnFollow.ts。
|
||||
@@ -0,0 +1,66 @@
|
||||
-- 主系统分配单:日级合并占坑表 + 明细「缺货」状态列
|
||||
-- 设计:docs/design/20261010-主系统订单按配送日合并与缺货流转.md
|
||||
-- 口径(开发者 2026-10-10 定稿):
|
||||
-- 1) 同一**配送日**的主系统备货行合成一张本系统订单(不再一主系统单一张单);
|
||||
-- 2) 主系统来的订单不能删订单/不能删商品,只能按行报「缺货」(主系统 status=40 转自采);
|
||||
-- 3) 缺货行要从"待备货/未完成采购"里剔除,但**不动金额**(金额口径待财务确认)。
|
||||
--
|
||||
-- 只做两件事:① 平台表 public.main_system_daily_order_imports(日级占坑,不进 tenant_business_tables());
|
||||
-- ② 各租户 order_items 加三列(缺货状态/原因/报缺货时间)。
|
||||
|
||||
-- ① 日级占坑表:一个 (分公司, 配送日) 只允许建一张本系统订单。
|
||||
-- 占坑用「INSERT … ON CONFLICT DO UPDATE … WHERE our_order_code IS NULL AND created_at < now()-10min
|
||||
-- RETURNING id」这套既有做法(见 main_system_order_imports):崩溃遗留的空坑 10 分钟后可被重占。
|
||||
CREATE TABLE IF NOT EXISTS public.main_system_daily_order_imports (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
branch_code VARCHAR(50) NOT NULL,
|
||||
delivery_date DATE NOT NULL,
|
||||
our_order_code VARCHAR(64),
|
||||
row_count INT NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
UNIQUE (branch_code, delivery_date)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_main_system_daily_order_our_order
|
||||
ON public.main_system_daily_order_imports (our_order_code);
|
||||
|
||||
COMMENT ON TABLE public.main_system_daily_order_imports IS
|
||||
'主系统分配单的日级占坑表:(分公司, 配送日) → 本系统订单号;一张日单承接该配送日全部主系统备货行';
|
||||
COMMENT ON COLUMN public.main_system_daily_order_imports.our_order_code IS
|
||||
'本系统订单号;NULL=正在建单(占坑未回填,超过 10 分钟视为陈旧可被重新占用)';
|
||||
|
||||
-- ② 缺货状态列:前端直连读 order_items,加列即随 select('*') 到达界面;后端据此剔除待备货。
|
||||
DO $$
|
||||
DECLARE
|
||||
sch text;
|
||||
BEGIN
|
||||
FOR sch IN
|
||||
SELECT nspname
|
||||
FROM pg_namespace
|
||||
WHERE nspname IN ('public', 'legacy_public', 'tenant_template')
|
||||
OR nspname LIKE 'tenant_%'
|
||||
LOOP
|
||||
IF to_regclass(format('%I.order_items', sch)) IS NOT NULL THEN
|
||||
EXECUTE format(
|
||||
'ALTER TABLE %I.order_items
|
||||
ADD COLUMN IF NOT EXISTS is_stockout BOOLEAN NOT NULL DEFAULT false,
|
||||
ADD COLUMN IF NOT EXISTS stockout_reason TEXT,
|
||||
ADD COLUMN IF NOT EXISTS stockout_reported_at TIMESTAMPTZ',
|
||||
sch
|
||||
);
|
||||
EXECUTE format(
|
||||
'COMMENT ON COLUMN %I.order_items.is_stockout IS ''缺货:该行供不了(主系统分配单报缺货 ⇒ 主系统转自采);不计入待备货/未完成采购''',
|
||||
sch
|
||||
);
|
||||
EXECUTE format(
|
||||
'COMMENT ON COLUMN %I.order_items.stockout_reason IS ''缺货原因(报给主系统 stockout_reason)''',
|
||||
sch
|
||||
);
|
||||
EXECUTE format(
|
||||
'COMMENT ON COLUMN %I.order_items.stockout_reported_at IS ''报缺货给主系统成功的时间;NULL=未报过''',
|
||||
sch
|
||||
);
|
||||
END IF;
|
||||
END LOOP;
|
||||
END $$;
|
||||
@@ -0,0 +1,36 @@
|
||||
-- 订单明细的「来源主系统订单号」列(2026-10-10)
|
||||
-- 设计:docs/design/20261010-主系统订单按配送日合并与缺货流转.md §2.2(改版)
|
||||
--
|
||||
-- 背景:按配送日合并后,一张本系统订单里混着多张**主系统订单**的货。
|
||||
-- 开发者 2026-10-10 明确:**不要塞进备注**(备注是业务字段),要能给管理员区分来源 ——
|
||||
-- 详情表按「一级=主系统订单 / 二级=商品分类」两级分组(界面有开关,默认开启),
|
||||
-- 所以"这一行来自哪张主系统订单"必须是**行属性**:落在本列。
|
||||
--
|
||||
-- 为什么不用现有台账 `public.main_system_order_import_items`:那张表在 public,前端读不到
|
||||
-- (数据网关名单与 RLS 都不放行),而详情表是前端直连 `order_items`。
|
||||
--
|
||||
-- 只加列,不搬数据:存量行由应用层在导入/对账时**惰性补齐**(迁移以应用角色执行、
|
||||
-- 没有租户上下文,`order_items` 有 FORCE RLS ⇒ 迁移里回填必然 0 行,见 20261013 的同款教训)。
|
||||
|
||||
DO $$
|
||||
DECLARE
|
||||
sch text;
|
||||
BEGIN
|
||||
FOR sch IN
|
||||
SELECT nspname
|
||||
FROM pg_namespace
|
||||
WHERE nspname IN ('public', 'legacy_public', 'tenant_template')
|
||||
OR nspname LIKE 'tenant_%'
|
||||
LOOP
|
||||
IF to_regclass(format('%I.order_items', sch)) IS NOT NULL THEN
|
||||
EXECUTE format(
|
||||
'ALTER TABLE %I.order_items ADD COLUMN IF NOT EXISTS main_order_code VARCHAR(64)',
|
||||
sch
|
||||
);
|
||||
EXECUTE format(
|
||||
'COMMENT ON COLUMN %I.order_items.main_order_code IS ''来源主系统订单号(主系统分配单专用;NULL=原生录单/手加行)。详情表按它做一级分组''',
|
||||
sch
|
||||
);
|
||||
END IF;
|
||||
END LOOP;
|
||||
END $$;
|
||||
@@ -0,0 +1,34 @@
|
||||
-- 客户表加「来源」列:主系统分配单的内部占位客户(2026-10-10)
|
||||
-- 设计:docs/design/20261010-主系统订单按配送日合并与缺货流转.md §2.6
|
||||
--
|
||||
-- 背景(开发者口径):「主系统分配过来的,相当于客户可能都不是子系统的客户,不该绑定子系统的客户」。
|
||||
-- 决定:**隐藏式技术占位** —— 录单入口必填客户、且订单/结算按 customer_code 归集(换掉会牵动录单
|
||||
-- 与财务口径),所以保留一行内部占位;但它在产品上**不是客户**,客户管理列表 / 客户下拉 / 客户筛选
|
||||
-- 一律不展示(打标而不是靠 `MAIN_` 前缀猜)。
|
||||
--
|
||||
-- 只加列,不回填:迁移以应用角色执行、没有租户上下文,`customers` 有 FORCE RLS ⇒ 回填必然 0 行
|
||||
-- (同 20261013/20261015 的教训)。存量占位行由应用侧惰性自愈:每轮导入都会
|
||||
-- `ensureImportCustomer`,发现 `source` 不是 `main_system` 就补上。
|
||||
|
||||
DO $$
|
||||
DECLARE
|
||||
sch text;
|
||||
BEGIN
|
||||
FOR sch IN
|
||||
SELECT nspname
|
||||
FROM pg_namespace
|
||||
WHERE nspname IN ('public', 'legacy_public', 'tenant_template')
|
||||
OR nspname LIKE 'tenant_%'
|
||||
LOOP
|
||||
IF to_regclass(format('%I.customers', sch)) IS NOT NULL THEN
|
||||
EXECUTE format(
|
||||
'ALTER TABLE %I.customers ADD COLUMN IF NOT EXISTS source VARCHAR(20)',
|
||||
sch
|
||||
);
|
||||
EXECUTE format(
|
||||
'COMMENT ON COLUMN %I.customers.source IS ''客户来源:NULL/local=本地客户;main_system=主系统分配单的内部占位(客户管理/客户下拉/客户筛选一律不展示)''',
|
||||
sch
|
||||
);
|
||||
END IF;
|
||||
END LOOP;
|
||||
END $$;
|
||||
@@ -0,0 +1,32 @@
|
||||
-- 修正 `customers.source` 的列注释(2026-10-10,口径澄清)
|
||||
--
|
||||
-- 20261016 加这一列时的注释写的是「main_system=主系统分配单的内部占位(客户管理/客户下拉/客户筛选一律不展示)」,
|
||||
-- 那是当时"隐藏式技术占位"的口径。开发者随后澄清并定为最终口径:
|
||||
--
|
||||
-- 「需要这个 —— 相当于主系统就是子系统的客户,这个设计是没有问题的;
|
||||
-- 后续主系统给子系统的订单,相当于默认就是这个客户下的单,这样就好确保流程正常。」
|
||||
--
|
||||
-- 即:**主系统就是我们(子系统)的客户**,占位客户就是这个客户本身,客户管理/客户下拉/统计里
|
||||
-- 正常展示、正常参与结算与对账("隐藏"方案已撤回)。`source` 这一列保留为**来源标记**,
|
||||
-- 便于后续按来源区分/筛选(例如报表里区分"主系统客户"与本地客户),不再用于隐藏。
|
||||
--
|
||||
-- 为什么追加一条迁移而不是改 20261016:已应用的迁移不回改(保持执行记录与文件一致)。
|
||||
|
||||
DO $$
|
||||
DECLARE
|
||||
sch text;
|
||||
BEGIN
|
||||
FOR sch IN
|
||||
SELECT nspname
|
||||
FROM pg_namespace
|
||||
WHERE nspname IN ('public', 'legacy_public', 'tenant_template')
|
||||
OR nspname LIKE 'tenant_%'
|
||||
LOOP
|
||||
IF to_regclass(format('%I.customers', sch)) IS NOT NULL THEN
|
||||
EXECUTE format(
|
||||
'COMMENT ON COLUMN %I.customers.source IS ''客户来源标记:NULL/local=本地客户;main_system=主系统的这个客户(主系统给子系统的订单默认挂它)。仅作来源区分,不用于隐藏''',
|
||||
sch
|
||||
);
|
||||
END IF;
|
||||
END LOOP;
|
||||
END $$;
|
||||
@@ -0,0 +1,77 @@
|
||||
-- 主系统履约事件台账 + 实收量(改量)落账列(供应商系统二次开发 · 2026-10-10)
|
||||
--
|
||||
-- 背景:主系统提交 `1447ea08` 交付了两个新 webhook 事件
|
||||
-- · preparations.picked_up —— 免入库:主系统确认发车(50→60),货已被取走
|
||||
-- · preparations.inbound_completed —— 送仓:该供应商在本单的备货行全部入库覆盖
|
||||
-- 并交付了 R3 履约事实字段(actual_qty / qty_diff / is_inbounded / inbound_at / order_departed_at)。
|
||||
-- 我方据此把第三方订单收口到 90。见 docs/design/20261010-第三方订单履约事件接收端与免入库回写时机.md。
|
||||
--
|
||||
-- 注意:
|
||||
-- 1. `main_system_fulfillment_events` 是 **public 层的跨系统平台台账**(与
|
||||
-- `main_system_order_imports` / `main_system_order_import_items` 同类),
|
||||
-- **不是分公司业务表** ⇒ 不进 tenant_business_tables()。迁移守卫
|
||||
-- `assert_tenant_template_matches_business_tables()` 只校验 tenant_template 里的表,与本表无关。
|
||||
-- 2. 主系统侧**不做持久去重**(其回执 §2.1 明说),所以幂等**必须由本表兜**:
|
||||
-- UNIQUE (branch_code, event, main_order_code) 就是幂等键。
|
||||
-- 3. 只加表、只加列,**不改任何既有表的结构与数据**;`qty_decision` 默认 'none'。
|
||||
|
||||
-- ── 1. 履约事件台账 ────────────────────────────────────────────────────────
|
||||
CREATE TABLE IF NOT EXISTS public.main_system_fulfillment_events (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
/** 本系统分公司编码 == 主系统 supplier_code */
|
||||
branch_code varchar(50) NOT NULL,
|
||||
/** preparations.picked_up | preparations.inbound_completed */
|
||||
event varchar(50) NOT NULL,
|
||||
/** 主系统订单号(事件的定位键) */
|
||||
main_order_code varchar(100) NOT NULL,
|
||||
/** 收口到本系统的哪张订单(合并后可能多张主系统单 → 同一张本系统单) */
|
||||
our_order_code varchar(50),
|
||||
/**
|
||||
* pending 已收到、未收口
|
||||
* done 已收口(或幂等命中:订单已是 90)
|
||||
* suspended 前置未满足/被闸门拦(如零价),由对账重试,人工可见
|
||||
* ignored 不该处理的(无台账对照 = 不是我们的单)
|
||||
*/
|
||||
status varchar(20) NOT NULL DEFAULT 'pending',
|
||||
reason text,
|
||||
/** 触发来源:webhook | reconcile */
|
||||
source varchar(20) NOT NULL DEFAULT 'webhook',
|
||||
/** 主系统原始载荷(原样留档,便于事后核对与重放) */
|
||||
payload jsonb NOT NULL DEFAULT '{}'::jsonb,
|
||||
received_at timestamptz NOT NULL DEFAULT NOW(),
|
||||
processed_at timestamptz,
|
||||
attempts integer NOT NULL DEFAULT 0,
|
||||
updated_at timestamptz NOT NULL DEFAULT NOW(),
|
||||
/** **幂等键**:主系统事件粒度就是 (order_code, supplier_code),而 branch_code == supplier_code */
|
||||
UNIQUE (branch_code, event, main_order_code)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_main_system_fulfillment_events_pending
|
||||
ON public.main_system_fulfillment_events (status, updated_at);
|
||||
|
||||
COMMENT ON TABLE public.main_system_fulfillment_events IS
|
||||
'主系统履约事件台账(picked_up / inbound_completed):幂等键 + 乱序挂起 + 审计依据';
|
||||
|
||||
-- ── 2. 行级台账补「实收量 / 改量处置」列 ───────────────────────────────────
|
||||
-- 「改量待确认」是**纯本地**动作:主系统把实际收货量作为事实流转过来,
|
||||
-- 我方展示一律按实收量,是否把差额补回库存由本地同意/拒绝决定,**不回传主系统**。
|
||||
ALTER TABLE public.main_system_order_import_items
|
||||
ADD COLUMN IF NOT EXISTS last_actual_qty numeric;
|
||||
ALTER TABLE public.main_system_order_import_items
|
||||
ADD COLUMN IF NOT EXISTS last_actual_qty_at timestamptz;
|
||||
ALTER TABLE public.main_system_order_import_items
|
||||
ADD COLUMN IF NOT EXISTS last_qty_diff numeric;
|
||||
/** none | approved | rejected —— 运营对"实收量差异"的本地裁决 */
|
||||
ALTER TABLE public.main_system_order_import_items
|
||||
ADD COLUMN IF NOT EXISTS qty_decision varchar(20) NOT NULL DEFAULT 'none';
|
||||
ALTER TABLE public.main_system_order_import_items
|
||||
ADD COLUMN IF NOT EXISTS qty_decision_reason text;
|
||||
ALTER TABLE public.main_system_order_import_items
|
||||
ADD COLUMN IF NOT EXISTS qty_decided_at timestamptz;
|
||||
|
||||
COMMENT ON COLUMN public.main_system_order_import_items.last_actual_qty IS
|
||||
'主系统流转过来的实际收货量(免入库=核货实配量;送仓=验收入库实收量);NULL=未产生';
|
||||
COMMENT ON COLUMN public.main_system_order_import_items.last_qty_diff IS
|
||||
'实际收货量 − 主系统分配量(主系统算好下发,避免两边各自四舍五入)';
|
||||
COMMENT ON COLUMN public.main_system_order_import_items.qty_decision IS
|
||||
'本地对实收量差异的裁决:none 未决 | approved 同意(差额补回库存)| rejected 拒绝(不补)。不回传主系统';
|
||||
@@ -0,0 +1,87 @@
|
||||
-- 跨系统改价 / 改量审核:我方「申请与结果」台账(public 平台表)
|
||||
--
|
||||
-- 背景(开发者 2026-10-11 口径):
|
||||
-- 本系统操作员改「主系统来源订单」的销售价(= 主系统成本价)或数量时,**默认要主系统管理员审核**;
|
||||
-- 免审例外:原值为 0/空(补价/补量)、价格改低、数量减少。免审也要上报主系统并两边留日志。
|
||||
-- 主系统审核结果通过 webhook `preparations.price_qty_decided` 回传,我们按 request_id 幂等落地。
|
||||
--
|
||||
-- 为什么是 public 平台表:与 `main_system_order_imports` / `main_system_fulfillment_events` 同风格,
|
||||
-- 带 `branch_code` 维度、由应用层按分公司过滤(本表不是租户业务表,**不进** `tenant_business_tables()`)。
|
||||
--
|
||||
-- 设计文档:docs/design/20261011-跨系统改价改量审核.md(§4 C1)
|
||||
-- ⚠️ 迁移内不回填任何数据(租户表有 FORCE RLS,回填必然 0 行;存量由应用层惰性处理)。
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.main_system_price_qty_requests (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
-- 本系统分公司编码(= 主系统 supplier_code)
|
||||
branch_code varchar(50) NOT NULL,
|
||||
-- 主系统侧申请 id(提交成功后回填);漏推时按它幂等去重
|
||||
request_id varchar(120),
|
||||
-- 我方幂等键(一次点击一个),同 (branch_code, client_request_id) 唯一
|
||||
client_request_id varchar(120) 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,
|
||||
-- 变更类型:price / qty / both
|
||||
kind varchar(10) NOT NULL,
|
||||
before_price numeric(14, 4),
|
||||
before_qty numeric(14, 4),
|
||||
proposed_price numeric(14, 4),
|
||||
proposed_qty numeric(14, 4),
|
||||
final_price numeric(14, 4),
|
||||
final_qty numeric(14, 4),
|
||||
unit varchar(20),
|
||||
-- pending=等审核 / applied=免审已生效 / approved=审核通过 / rejected=被驳回 / failed=提交失败(主系统不可用等)
|
||||
status varchar(20) NOT NULL DEFAULT 'pending',
|
||||
review_required boolean NOT NULL DEFAULT false,
|
||||
-- 我方申请理由
|
||||
reason text,
|
||||
-- 主系统判定或驳回的说明
|
||||
decision_reason text,
|
||||
requested_by varchar(200),
|
||||
decided_by varchar(200),
|
||||
decided_at timestamptz,
|
||||
-- 原始载荷(申请响应 / 回传事件),排障用
|
||||
payload jsonb NOT NULL DEFAULT '{}'::jsonb,
|
||||
created_at timestamptz NOT NULL DEFAULT NOW(),
|
||||
updated_at timestamptz NOT NULL DEFAULT NOW(),
|
||||
CONSTRAINT main_system_price_qty_requests_kind_check CHECK (kind IN ('price', 'qty', 'both')),
|
||||
CONSTRAINT main_system_price_qty_requests_status_check
|
||||
CHECK (status IN ('pending', 'applied', 'approved', 'rejected', 'failed'))
|
||||
);
|
||||
|
||||
-- 幂等:同一次点击只落一行(重试/重复提交不二次排队)
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_main_system_price_qty_requests_client
|
||||
ON public.main_system_price_qty_requests (branch_code, client_request_id);
|
||||
|
||||
-- 同一备货行的「同类型待审申请」只允许一条(新申请覆盖旧的,与主系统 overwritten 语义一致)
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_main_system_price_qty_requests_pending
|
||||
ON public.main_system_price_qty_requests (branch_code, prep_id, kind)
|
||||
WHERE status = 'pending';
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_main_system_price_qty_requests_status
|
||||
ON public.main_system_price_qty_requests (branch_code, status, updated_at DESC);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_main_system_price_qty_requests_order
|
||||
ON public.main_system_price_qty_requests (branch_code, our_order_code);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_main_system_price_qty_requests_request_id
|
||||
ON public.main_system_price_qty_requests (request_id);
|
||||
|
||||
COMMENT ON TABLE public.main_system_price_qty_requests IS
|
||||
'跨系统改价/改量申请与结果台账(我方视角;主系统审核后经 webhook 回传最终值)';
|
||||
COMMENT ON COLUMN public.main_system_price_qty_requests.branch_code IS '本系统分公司编码(= 主系统 supplier_code)';
|
||||
COMMENT ON COLUMN public.main_system_price_qty_requests.request_id IS '主系统侧申请 id(提交成功后回填,用于结果回传幂等)';
|
||||
COMMENT ON COLUMN public.main_system_price_qty_requests.client_request_id IS '我方幂等键(一次点击一个)';
|
||||
COMMENT ON COLUMN public.main_system_price_qty_requests.prep_id IS '主系统备货行 id';
|
||||
COMMENT ON COLUMN public.main_system_price_qty_requests.main_order_code IS '主系统订单号(留痕/排障)';
|
||||
COMMENT ON COLUMN public.main_system_price_qty_requests.our_order_code IS '本系统订单号';
|
||||
COMMENT ON COLUMN public.main_system_price_qty_requests.our_order_item_id IS '本系统订单行 id(价格/数量落地点)';
|
||||
COMMENT ON COLUMN public.main_system_price_qty_requests.kind IS '变更类型:price / qty / both';
|
||||
COMMENT ON COLUMN public.main_system_price_qty_requests.status IS
|
||||
'pending=等审核;applied=免审已生效;approved=审核通过;rejected=被驳回;failed=提交失败';
|
||||
COMMENT ON COLUMN public.main_system_price_qty_requests.review_required IS '主系统判定是否需要人工审核(免审=false)';
|
||||
COMMENT ON COLUMN public.main_system_price_qty_requests.final_price IS '最终值(主系统为准);applied/approved 后才有';
|
||||
COMMENT ON COLUMN public.main_system_price_qty_requests.payload IS '原始载荷(申请响应 / 回传事件),排障用';
|
||||
@@ -0,0 +1,17 @@
|
||||
-- 跨系统改价/改量台账:补「商品名 / 主系统 SKU」两列
|
||||
--
|
||||
-- 背景(开发者 2026-10-11):申请列表原来只能显示主系统备货行 UUID(`prep_id`),
|
||||
-- 操作员看不出"改的是哪个商品"。提交时我们本来就从本方订单行读到了 `item_name`,
|
||||
-- 这里把它落库,列表即可直接展示;主系统 Q4 事件里也带 `sku_code`,一并留痕。
|
||||
--
|
||||
-- 设计文档:docs/design/20261011-跨系统改价改量审核.md(§4 C1/C6)
|
||||
-- ⚠️ 迁移内不做数据回填(存量行由列表查询时按本方订单行**实时解析**,取不到才退回 UUID)。
|
||||
|
||||
ALTER TABLE public.main_system_price_qty_requests
|
||||
ADD COLUMN IF NOT EXISTS item_name varchar(200),
|
||||
ADD COLUMN IF NOT EXISTS main_sku_code varchar(120);
|
||||
|
||||
COMMENT ON COLUMN public.main_system_price_qty_requests.item_name IS
|
||||
'商品名(提交时从本方订单行读入;列表展示优先用本方订单行的实时值)';
|
||||
COMMENT ON COLUMN public.main_system_price_qty_requests.main_sku_code IS
|
||||
'主系统 SKU 编码(提交时读入 / Q4 事件回传时补写,排障用)';
|
||||
@@ -0,0 +1,21 @@
|
||||
-- 主系统行级台账:补「下单分公司」两列(编码 + 名称)
|
||||
--
|
||||
-- 背景(开发者 2026-10-11 口径):**主系统的分公司名字就是客户名字** ——
|
||||
-- 我方按「一个主系统分公司 = 一个客户」建客户,客户名 = 分公司名(如 BR002 → 「自贡」)。
|
||||
-- 名称以前只随备货行瞬时出现、落不了库;补这两列后台账自身就能回溯"这张单属于哪个分公司/客户",
|
||||
-- 存量订单改归属与事后对账都不必再回主系统取。
|
||||
--
|
||||
-- ⚠️ 不回填历史数据(存量行由 `reattributeMainSystemOrdersToBranchCustomers()` 在应用内补齐)。
|
||||
-- 设计文档:docs/design/20261010-主系统订单按配送日合并与缺货流转.md §2.7 / §8.4
|
||||
|
||||
ALTER TABLE public.main_system_order_import_items
|
||||
ADD COLUMN IF NOT EXISTS main_branch_code varchar(40),
|
||||
ADD COLUMN IF NOT EXISTS main_branch_name varchar(120);
|
||||
|
||||
COMMENT ON COLUMN public.main_system_order_import_items.main_branch_code IS
|
||||
'主系统下单分公司编码(如 BR002)——决定我方客户(客户编码 MAIN_<该值>)';
|
||||
COMMENT ON COLUMN public.main_system_order_import_items.main_branch_name IS
|
||||
'主系统下单分公司名称(如 自贡)——即我方客户名;为空时用「主系统分公司 <编码>」兜底';
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_main_import_items_main_branch
|
||||
ON public.main_system_order_import_items (branch_code, main_branch_code);
|
||||
@@ -0,0 +1,58 @@
|
||||
-- 跨系统「实收数量 / 单位」申请台账(**对方发起、我方审核**方向)
|
||||
--
|
||||
-- 背景(开发者 2026-10-11 定稿;主系统提交 b8519fbb 已交付):
|
||||
-- · 核货节点:主系统核货值是**事实登记**(先落库)⇒ 发申请告知我方,我方通过即对齐、驳回**不回滚**;
|
||||
-- · order_status >= 60(配送中及以后)改实收/单位、>= 90 改成本价 ⇒ **先审后改**(pending 期间两边都不落库);
|
||||
-- · 事件:`preparations.actual_qty_request`(收) / `preparations.actual_qty_decided`(对方结果回执);
|
||||
-- · 决策回传:我方调 `POST /api/supplier/preparations/actual-qty-decision`。
|
||||
--
|
||||
-- 与 `main_system_price_qty_requests`(**我方发起、对方审**)**方向相反、各自一张表**,互不覆盖。
|
||||
-- 设计文档:docs/design/20261011-跨系统改价改量审核.md
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.main_system_actual_qty_requests (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
branch_code varchar(64) NOT NULL,
|
||||
-- 主系统申请行 id(对方生成,幂等键)
|
||||
request_id varchar(128) NOT NULL,
|
||||
prep_id uuid,
|
||||
order_code varchar(128),
|
||||
our_order_code varchar(128),
|
||||
sku_code varchar(120),
|
||||
-- 触发节点:picking_check(核货)| admin_received_qty(对方管理端)| post_complete_price(完结后成本价)
|
||||
node varchar(40) NOT NULL,
|
||||
-- 变更字段:qty(实收数量)| unit(单位)| price(成本价,仅 post_complete_price)
|
||||
field varchar(16) NOT NULL,
|
||||
before_value numeric,
|
||||
proposed_value numeric,
|
||||
before_unit varchar(32),
|
||||
unit varchar(32),
|
||||
operator varchar(120),
|
||||
reason text,
|
||||
client_request_id varchar(160),
|
||||
status varchar(16) NOT NULL DEFAULT 'pending',
|
||||
final_value numeric,
|
||||
reviewer varchar(120),
|
||||
decided_at timestamptz,
|
||||
decision_reason text,
|
||||
-- 核货节点=事实登记(驳回不回滚);>=60/>=90=先审后改
|
||||
fact_registered boolean NOT NULL DEFAULT false,
|
||||
payload jsonb,
|
||||
created_at timestamptz NOT NULL DEFAULT NOW(),
|
||||
updated_at timestamptz NOT NULL DEFAULT NOW(),
|
||||
CONSTRAINT main_system_actual_qty_requests_status_check
|
||||
CHECK (status IN ('pending', 'approved', 'rejected', 'superseded')),
|
||||
CONSTRAINT main_system_actual_qty_requests_field_check
|
||||
CHECK (field IN ('qty', 'unit', 'price'))
|
||||
);
|
||||
|
||||
-- 幂等:同一分公司内,对方同一申请行只落一条
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_main_system_actual_qty_requests_request
|
||||
ON public.main_system_actual_qty_requests (branch_code, request_id);
|
||||
|
||||
-- 待审队列
|
||||
CREATE INDEX IF NOT EXISTS idx_main_system_actual_qty_requests_pending
|
||||
ON public.main_system_actual_qty_requests (branch_code, status, created_at DESC);
|
||||
|
||||
-- 按备货行/我方订单回查
|
||||
CREATE INDEX IF NOT EXISTS idx_main_system_actual_qty_requests_prep
|
||||
ON public.main_system_actual_qty_requests (branch_code, prep_id);
|
||||
@@ -0,0 +1,14 @@
|
||||
-- 实收数量/单位「事实登记 + 事后同步」(2026-10-11 口径变更,设计文档
|
||||
-- docs/design/20261011-实收数量与单位的事后同步.md)
|
||||
--
|
||||
-- 为什么加 `applied_at`:新口径下**主系统先改自己的实际值再发请求**,我方必须能区分
|
||||
-- 「已生效的实际值」与「待审建议值」,并能在审核页与对账里展示"对方值何时生效"。
|
||||
-- 主系统请求载荷新增字段 `applied_at`(ISO 8601);缺失时留 NULL(历史行/旧版载荷)。
|
||||
--
|
||||
-- 幂等:`IF NOT EXISTS`,可重复执行。
|
||||
|
||||
ALTER TABLE public.main_system_actual_qty_requests
|
||||
ADD COLUMN IF NOT EXISTS applied_at TIMESTAMPTZ;
|
||||
|
||||
COMMENT ON COLUMN public.main_system_actual_qty_requests.applied_at IS
|
||||
'主系统实际值在其侧生效的时刻(事实登记的时间锚点;NULL = 对方未提供,按旧口径视为建议值)';
|
||||
+70
-6
@@ -1,15 +1,49 @@
|
||||
PORT=3001
|
||||
# 供应商系统(二次开发)默认 API 端口;Web 开发服见根 webpack.config.js(3021)
|
||||
PORT=3022
|
||||
# 使用 127.0.0.1 而非 localhost,避免 Windows 下 IPv6 连接需要密码
|
||||
DATABASE_URL=postgresql://canteen:canteen123@127.0.0.1:5432/canteen_delivery
|
||||
# Docker Compose 默认由 canteen 初始化为超级用户,setup 阶段用它连接 postgres 库
|
||||
# 独立库:与主系统(canteen_delivery)完全隔离,setup 会按此 URL 建角色与库
|
||||
DATABASE_URL=postgresql://supplier:change-me@127.0.0.1:5432/supplier_delivery
|
||||
# 引导用超管连接:仅 `npm run setup` 建角色/建库时使用,应用运行不使用
|
||||
ADMIN_DATABASE_URL=postgresql://canteen:canteen123@127.0.0.1:5432/postgres
|
||||
JWT_SECRET=canteen-dev-secret-change-in-production
|
||||
JWT_SECRET=change-me-dev-secret-not-for-production
|
||||
# 本地默认开启与生产一致的租户/RLS约束;缺少 RLS 角色时拒绝启动
|
||||
RLS_REQUIRED=1
|
||||
RLS_FAIL_OPEN=0
|
||||
TENANT_WORKFLOW_SCHEMA=1
|
||||
TENANT_REQUEST_CLIENT=1
|
||||
# DATABASE_URL 为本地库时允许 setup 自动创建/校验 canteen 用户和数据库
|
||||
# 规模改造(500+ 分公司):租户清单缓存 TTL(毫秒,0=关闭缓存);新建分公司会主动失效
|
||||
TENANT_LIST_CACHE_TTL_MS=30000
|
||||
# 规模改造:定时任务逐租户并发度(1=退回串行);竞价开标 tick 默认 4(上限 8)
|
||||
SCHEDULER_TENANT_CONCURRENCY=4
|
||||
# 规模改造:主系统分配对账逐分公司并发度(1=退回串行);默认 6(上限 10)
|
||||
MAIN_SYSTEM_IMPORT_CONCURRENCY=6
|
||||
# 第三方订单退货跟随(主系统退货 → 本系统跟随红冲/取消履约):默认关,联调后设 1 开启
|
||||
MAIN_SYSTEM_RETURN_FOLLOW=0
|
||||
# 发车/备齐 → 回写主系统「备货完成」(status=30):**默认开**(`!== '0'` 才关),
|
||||
# 写 0 只用于临时停掉回写(会让主系统一直停在"待备货")。免入库单不等发车,一进 50 就回写。
|
||||
MAIN_SYSTEM_WRITEBACK=1
|
||||
# 主系统履约事件接收端(preparations.picked_up / inbound_completed)⇒ 我方第三方订单收口 90:
|
||||
# **2026-10-11 开发者定稿:默认开**,只有显式写 0 才回到「200 忽略新事件」的旧行为。
|
||||
# 设计文档:docs/design/20261010-第三方订单履约事件接收端与免入库回写时机.md §9
|
||||
MAIN_SYSTEM_FULFILLMENT_EVENTS=1
|
||||
# 免入库订单「等主系统确认发车(骑手取货)」才收口(停在 50,界面显示「待取货」),
|
||||
# 而不是我方分拣完毕即结案 90。**2026-10-11 开发者定稿:默认开**,只有显式写 0 才回退旧行为。
|
||||
# ⚠️ 与上面 MAIN_SYSTEM_FULFILLMENT_EVENTS 是**一对**(现两个默认都开,成对才是完整链路):
|
||||
# 本开关只负责"停在 50 等骑手取货",收口 90 全靠接收端的 picked_up 事件;
|
||||
# 若把接收端写 0,则事件是「200 收下但忽略」(不入台账、不重放)⇒ 单子停在 50 永远收不了口。
|
||||
MAIN_SYSTEM_SKIP_INBOUND_AWAIT_PICKUP=1
|
||||
# 跨系统改价/改量审核(提交申请 → 主系统管理员审核 → 结果回传)总开关:
|
||||
# 默认关 = 与改造前逐字节一致(含"发车回写带价格"的静默通道仍可用);
|
||||
# 主系统侧 Q1–Q4 就绪后再设 1 —— 开启后发车回写**不再**携带未经本流程确认的价格。
|
||||
# 设计文档:docs/design/20261011-跨系统改价改量审核.md
|
||||
MAIN_SYSTEM_PRICE_QTY_ENABLED=0
|
||||
# 改价/改量申请提交端点路径(一般不用改)
|
||||
# MAIN_SYSTEM_PRICE_QTY_REQUEST_PATH=/api/supplier/preparations/price-qty-request
|
||||
# 回写备货状态路径(一般不用改)
|
||||
# MAIN_SYSTEM_STATUS_PATH=/api/supplier/preparations/status
|
||||
# 实收/单位申请的决策回传路径(第五批 Q9,默认见 endpoints 表)
|
||||
# MAIN_SYSTEM_ACTUAL_QTY_DECISION_PATH=/api/supplier/preparations/actual-qty-decision
|
||||
# DATABASE_URL 为本地库时允许 setup 自动创建/校验 DATABASE_URL 中的角色和数据库
|
||||
SKIP_LOCAL_DB_SETUP=0
|
||||
# 本地默认不灌入演示/端到端账号数据
|
||||
SKIP_DEMO_SEED=1
|
||||
@@ -27,10 +61,40 @@ JWT_EXPIRES_IN=8h
|
||||
# 操作日志保留:不配按自然月(NOW()-1 month)。正整数按天(例 31)。0 关闭。不清理库存流水。
|
||||
# OPERATION_LOG_RETENTION_DAYS=31
|
||||
|
||||
STORAGE_DIR=./uploads
|
||||
# 本地文件目录:与主系统 server/uploads 隔离,勿改回 ./uploads
|
||||
# --- 主系统(AI 生鲜配送)对接 ---
|
||||
# 本系统的「分公司管理员」= 主系统的供应商账号(登录名 = 手机号),密码权威在主系统:
|
||||
# 登录时向下面这个地址校验凭据并取回供应商档案(supplier_code 用作分公司编码)。
|
||||
# 留空 = 关闭该能力(此时只有本系统自建账号能登录)。
|
||||
#
|
||||
# 【切环境就改这一行】启动日志会打印实际连的是哪个主系统,看到「⚠️ 非本地」请确认是预期环境:
|
||||
# · 本地开发(默认) MAIN_SYSTEM_BASE_URL=http://127.0.0.1:3001
|
||||
# · 上线到线上 MAIN_SYSTEM_BASE_URL=https://<线上主系统域名> ← 内网地址优先,别走公网
|
||||
MAIN_SYSTEM_BASE_URL=http://127.0.0.1:3001
|
||||
# 跨机/线上比本机慢,建议放大;本机 5000 足够
|
||||
MAIN_SYSTEM_TIMEOUT_MS=5000
|
||||
# 主系统校验端点(本期**复用其供应商登录接口**;上线前建议改为带签名 + IP 白名单的服务间端点,
|
||||
# 原因:该接口挂了 loginIpLimiter 80 次/10 分钟/IP,服务间调用是**所有供应商共用同一个 IP 配额**)
|
||||
# MAIN_SYSTEM_SUPPLIER_LOGIN_PATH=/api/supplier/login
|
||||
|
||||
# --- 主系统「进销存对接密钥」(拉取分配来的备货任务)---
|
||||
# 由主系统运营侧创建并绑定供应商:
|
||||
# POST /api/suppliers/integration-clients (body: {name})→ 明文 secret 仅返回一次
|
||||
# POST /api/suppliers/integration-clients/:clientId/suppliers (body: {supplier_code, branch_code})
|
||||
# 绑定后本系统即可用下面这套密钥,以「外部进销存」身份拉某供应商(= 本系统某分公司)的备货任务。
|
||||
# ⚠️ 供应商编码即本系统分公司编码,无需额外映射。
|
||||
MAIN_SYSTEM_INTEGRATION_CLIENT_ID=
|
||||
MAIN_SYSTEM_INTEGRATION_CLIENT_SECRET=
|
||||
# 主系统开放 API 路径(一般不用改)
|
||||
# MAIN_SYSTEM_OAUTH_PATH=/api/supplier/oauth/token
|
||||
# MAIN_SYSTEM_PREPARATIONS_PATH=/api/supplier/preparations
|
||||
|
||||
STORAGE_DIR=./uploads-supplier
|
||||
|
||||
# --- 对象存储(S3 兼容:腾讯云 COS / 阿里云 OSS)---
|
||||
# STORAGE_PROVIDER=local|s3
|
||||
# 与主系统共用同一个 COS 桶时,必须设置独立前缀实现隔离(对象键 = {S3_KEY_PREFIX}/{bucket}/{文件名})
|
||||
# S3_KEY_PREFIX=supplier-system
|
||||
# 生产 CVM 与 COS 同地域时推荐内网(免公网流量、桶可私有):
|
||||
# S3_INTERNAL_ONLY=true
|
||||
# S3_ENDPOINT=https://cos.ap-nanjing.tencentcos.cn
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
/**
|
||||
* 只读自查:主系统对接「谁缺授权 / 客户端在不在 / 台账是否成了孤儿」
|
||||
*
|
||||
* 用途(2026-10-11 事故后新增):**每次用线上库覆盖主系统本地库之后**跑一次,
|
||||
* 直接打印"缺什么 + 要补哪几条 SQL",避免再出现"某家供应商永远拉不到单却无告警"。
|
||||
*
|
||||
* 用法:
|
||||
* MAIN_SYSTEM_DB_URL_FILE=/home/ubuntu/harness/ai-fresh-delivery/server/.env \
|
||||
* npx tsx --env-file=.env scripts/check-main-system-integration.ts
|
||||
*
|
||||
* ⚠️ 全程**只读**:不写任何库;补授权的 SQL 只打印、不执行(授权属主系统数据,由他们补)。
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { Pool } from 'pg';
|
||||
import { pool } from '../src/db';
|
||||
|
||||
function mainDbUrl(): string | null {
|
||||
const direct = String(process.env.MAIN_SYSTEM_DB_URL || '').trim();
|
||||
if (direct) return direct;
|
||||
const file = String(process.env.MAIN_SYSTEM_DB_URL_FILE || '').trim();
|
||||
if (!file) return null;
|
||||
try {
|
||||
const env = readFileSync(file, 'utf8');
|
||||
const line = env.split('\n').find((l) => l.startsWith('DATABASE_URL='));
|
||||
return line ? line.slice('DATABASE_URL='.length).trim().replace(/^["']|["']$/g, '') : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const envFlag = (key: string): string => {
|
||||
try {
|
||||
const env = readFileSync('.env', 'utf8');
|
||||
const line = env.split('\n').find((l) => l.startsWith(`${key}=`));
|
||||
return line ? line.slice(key.length + 1).trim() : '(未设置)';
|
||||
} catch {
|
||||
return '(读不到 .env)';
|
||||
}
|
||||
};
|
||||
|
||||
(async () => {
|
||||
const clientId = String(process.env.MAIN_SYSTEM_INTEGRATION_CLIENT_ID || '').trim();
|
||||
console.log('=== 我方配置 ===');
|
||||
console.log('对接客户端 ID:', clientId || '(未配置)');
|
||||
console.log('MAIN_SYSTEM_AUTO_IMPORT =', envFlag('MAIN_SYSTEM_AUTO_IMPORT'));
|
||||
console.log('MAIN_SYSTEM_RETURN_FOLLOW =', envFlag('MAIN_SYSTEM_RETURN_FOLLOW'));
|
||||
console.log('MAIN_SYSTEM_WRITEBACK =', envFlag('MAIN_SYSTEM_WRITEBACK'));
|
||||
|
||||
// ① 我方需要对接的分公司(= 有 main_supplier 账号的分公司)
|
||||
const mine = await pool.query<{ branch_code: string }>(
|
||||
`SELECT DISTINCT p.branch_code
|
||||
FROM public.profiles p
|
||||
WHERE p.account_source = 'main_supplier' AND p.branch_code IS NOT NULL AND COALESCE(p.status,1) = 1
|
||||
ORDER BY p.branch_code`
|
||||
);
|
||||
const ourSuppliers = mine.rows.map((r) => String(r.branch_code));
|
||||
console.log('\n=== 我方需要对接的供应商(= 分公司)===');
|
||||
console.log(ourSuppliers.join(', ') || '(空)');
|
||||
|
||||
const url = mainDbUrl();
|
||||
if (!url) {
|
||||
console.log('\n⚠️ 未提供主系统库连接(MAIN_SYSTEM_DB_URL / MAIN_SYSTEM_DB_URL_FILE),跳过主系统侧检查');
|
||||
await pool.end();
|
||||
return;
|
||||
}
|
||||
const main = new Pool({ connectionString: url });
|
||||
|
||||
console.log('\n=== 主系统侧:对接客户端 ===');
|
||||
const client = await main
|
||||
.query<{ client_id: string; name: string | null; status: number | null; webhook_url: string | null }>(
|
||||
`SELECT client_id, name, status, webhook_url FROM public.supplier_integration_clients WHERE client_id = $1`,
|
||||
[clientId]
|
||||
)
|
||||
.catch((e) => ({ rows: [] as any[], error: e } as any));
|
||||
if (!client.rows.length) {
|
||||
console.log('❌ 客户端不存在!', client.error ? `(查询失败:${client.error.message})` : '');
|
||||
console.log(' ⇒ 覆盖库后必须重建该客户端(并把 webhook_url 指回我方),否则**所有**分公司都拉不到单');
|
||||
} else {
|
||||
const c = client.rows[0];
|
||||
console.log('✅ 客户端存在:', JSON.stringify({ name: c.name, status: c.status, webhook_url: c.webhook_url }));
|
||||
if (String(c.webhook_url || '').trim() === '') console.log(' ⚠️ webhook_url 为空 ⇒ webhook 实时通道失效(只剩对账)');
|
||||
}
|
||||
|
||||
console.log('\n=== 主系统侧:哪些供应商缺对接授权 ===');
|
||||
const authorized = new Set<string>(
|
||||
(
|
||||
await main
|
||||
.query<{ supplier_code: string }>(
|
||||
`SELECT supplier_code FROM public.supplier_integration_client_suppliers WHERE client_id = $1`,
|
||||
[clientId]
|
||||
)
|
||||
.catch(() => ({ rows: [] as any[] }))
|
||||
).rows.map((r) => String(r.supplier_code))
|
||||
);
|
||||
const exists = new Set<string>(
|
||||
(
|
||||
await main
|
||||
.query<{ supplier_code: string }>(`SELECT supplier_code FROM public.suppliers WHERE supplier_code = ANY($1::text[])`, [
|
||||
ourSuppliers,
|
||||
])
|
||||
.catch(() => ({ rows: [] as any[] }))
|
||||
).rows.map((r) => String(r.supplier_code))
|
||||
);
|
||||
const missing: string[] = [];
|
||||
for (const code of ourSuppliers) {
|
||||
const ok = authorized.has(code);
|
||||
const exist = exists.has(code);
|
||||
console.log(` ${ok ? '✅' : '❌'} ${code} | 主系统供应商档案: ${exist ? '有' : '无'} | 对接授权: ${ok ? '有' : '**缺**'}`);
|
||||
if (!ok) missing.push(code);
|
||||
}
|
||||
if (missing.length) {
|
||||
console.log('\n--- 需要主系统补的授权(只打印,不执行)---');
|
||||
for (const code of missing) {
|
||||
console.log(
|
||||
`INSERT INTO public.supplier_integration_client_suppliers (client_id, supplier_code) VALUES ('${clientId}', '${code}');`
|
||||
);
|
||||
}
|
||||
} else {
|
||||
console.log('\n✅ 授权齐全');
|
||||
}
|
||||
|
||||
// ② 我方台账是否成了孤儿(覆盖库后 prep_id 会全部失效)
|
||||
console.log('\n=== 我方行级台账 vs 主系统备货行 ===');
|
||||
const ledger = await pool.query<{ prep_id: string }>(
|
||||
`SELECT prep_id FROM public.main_system_order_import_items WHERE prep_id IS NOT NULL LIMIT 300`
|
||||
);
|
||||
const ids = ledger.rows.map((r) => String(r.prep_id));
|
||||
if (!ids.length) {
|
||||
console.log('台账为空,跳过');
|
||||
} else {
|
||||
const schemas = (
|
||||
await main.query<{ table_schema: string }>(
|
||||
`SELECT table_schema FROM information_schema.tables WHERE table_name = 'supplier_preparations' AND table_schema LIKE 'tenant_%'`
|
||||
)
|
||||
).rows.map((r) => String(r.table_schema));
|
||||
const found = new Set<string>();
|
||||
for (const sc of schemas) {
|
||||
const r = await main
|
||||
.query<{ id: string }>(`SELECT id::text AS id FROM ${sc}.supplier_preparations WHERE id = ANY($1::uuid[])`, [ids])
|
||||
.catch(() => ({ rows: [] as any[] }));
|
||||
for (const x of r.rows) found.add(String(x.id));
|
||||
}
|
||||
const orphan = ids.length - found.size;
|
||||
console.log(` 抽查台账 ${ids.length} 行 ⇒ 主系统查得到 ${found.size} 行,**孤儿 ${orphan} 行**`);
|
||||
if (orphan > 0) {
|
||||
console.log(' ⚠️ 覆盖库后属正常;但**务必先关** MAIN_SYSTEM_RETURN_FOLLOW,否则退货跟随可能把孤儿行判成退货并红冲');
|
||||
}
|
||||
}
|
||||
|
||||
await main.end();
|
||||
await pool.end();
|
||||
})().catch((e) => {
|
||||
console.error('ERR', (e as Error)?.message || e);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* 一次性运维脚本:把**存量**主系统订单从旧的单一占位客户改挂到「按主系统下单分公司」建的客户上。
|
||||
*
|
||||
* 背景(开发者 2026-10-11 口径与决策 ③):客户口径从"一个供应商一个占位客户 `MAIN_<我方分公司>`
|
||||
* (名字「主系统订单」)"升级为"**一个主系统下单分公司一个客户,客户名 = 分公司名**"(如 BR002 →「自贡」)。
|
||||
* 新口径只影响**新建单**;存量单需要本脚本改挂 `orders.customer_code`(不改订单内容)。
|
||||
*
|
||||
* 用法(本地):
|
||||
* npx tsx --env-file=.env scripts/reattribute-main-system-branch-customers.ts SUP37831443
|
||||
* # 想顺便把分公司名带进来(名字取自主系统库,只读):
|
||||
* MAIN_SYSTEM_DB_URL_FILE=/home/ubuntu/harness/ai-fresh-delivery/server/.env \
|
||||
* npx tsx --env-file=.env scripts/reattribute-main-system-branch-customers.ts SUP37831443
|
||||
*
|
||||
* 幂等:可重复执行。分公司名缺省时用「主系统分公司 <编码>」兜底;占位客户在不再被订单引用时停用(status=40)。
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { Pool } from 'pg';
|
||||
import { pool } from '../src/db';
|
||||
import { reattributeMainSystemOrdersToBranchCustomers } from '../src/services/mainSystemOrderImport';
|
||||
|
||||
function readMainDbUrl(): string | null {
|
||||
const file = String(process.env.MAIN_SYSTEM_DB_URL_FILE || '').trim();
|
||||
const direct = String(process.env.MAIN_SYSTEM_DB_URL || '').trim();
|
||||
if (direct) return direct;
|
||||
if (!file) return null;
|
||||
try {
|
||||
const env = readFileSync(file, 'utf8');
|
||||
const line = env.split('\n').find((l) => l.startsWith('DATABASE_URL='));
|
||||
if (!line) return null;
|
||||
return line.slice('DATABASE_URL='.length).trim().replace(/^["']|["']$/g, '');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
(async () => {
|
||||
const branchCodes = process.argv.slice(2).map((v) => v.trim()).filter(Boolean);
|
||||
if (!branchCodes.length) {
|
||||
console.error('用法:npx tsx --env-file=.env scripts/reattribute-main-system-branch-customers.ts <我方分公司编码…>');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
let branchNames: Record<string, string> = {};
|
||||
const mainUrl = readMainDbUrl();
|
||||
if (mainUrl) {
|
||||
const main = new Pool({ connectionString: mainUrl });
|
||||
try {
|
||||
const rows = await main.query<{ branch_code: string; branch_name: string }>(
|
||||
'SELECT branch_code, branch_name FROM public.branches'
|
||||
);
|
||||
for (const row of rows.rows) {
|
||||
branchNames[String(row.branch_code).toUpperCase()] = String(row.branch_name || '');
|
||||
}
|
||||
console.log('已读到主系统分公司名:', JSON.stringify(branchNames));
|
||||
} catch (error: unknown) {
|
||||
console.warn('读主系统分公司名失败,将用兜底名:', (error as Error)?.message || error);
|
||||
branchNames = {};
|
||||
} finally {
|
||||
await main.end().catch(() => undefined);
|
||||
}
|
||||
} else {
|
||||
console.log('未提供主系统库连接,分公司名将用「主系统分公司 <编码>」兜底');
|
||||
}
|
||||
|
||||
for (const branchCode of branchCodes) {
|
||||
const result = await reattributeMainSystemOrdersToBranchCustomers({ branchCode, branchNames });
|
||||
console.log(`\n[${branchCode}]`, JSON.stringify(result, null, 1));
|
||||
}
|
||||
await pool.end();
|
||||
})().catch((error) => {
|
||||
console.error('ERR', (error as Error)?.message || error);
|
||||
process.exit(1);
|
||||
});
|
||||
+64
-2
@@ -5,7 +5,8 @@ loadEnv();
|
||||
|
||||
const isProduction = process.env.NODE_ENV === 'production';
|
||||
|
||||
const DEV_DATABASE_URL = 'postgresql://canteen:canteen123@localhost:5432/canteen_delivery';
|
||||
// 供应商系统(二次开发):独立库,勿改回 canteen_delivery
|
||||
const DEV_DATABASE_URL = 'postgresql://supplier:change-me@localhost:5432/supplier_delivery';
|
||||
|
||||
// A10: 任意环境必须显式配置 JWT_SECRET,禁止弱默认回退
|
||||
const jwtSecret = String(process.env.JWT_SECRET || '').trim();
|
||||
@@ -45,7 +46,7 @@ function parseCorsOrigins(raw?: string): boolean | string[] {
|
||||
}
|
||||
|
||||
export const config = {
|
||||
port: Number(process.env.PORT || 3001),
|
||||
port: Number(process.env.PORT || 3022),
|
||||
databaseUrl,
|
||||
jwtSecret,
|
||||
jwtExpiresIn: process.env.JWT_EXPIRES_IN || '8h',
|
||||
@@ -68,6 +69,67 @@ export const config = {
|
||||
internalOnly: s3InternalOnly,
|
||||
},
|
||||
},
|
||||
// 主系统(AI 生鲜配送):本系统的「分公司管理员」= 主系统的供应商账号,
|
||||
// 登录时向它校验凭据并取回供应商档案(supplier_code → 分公司编码)。
|
||||
// 未配置 MAIN_SYSTEM_BASE_URL 时该能力整体关闭(供应商账号无法登录,本地账号不受影响)。
|
||||
mainSystem: {
|
||||
baseUrl: (process.env.MAIN_SYSTEM_BASE_URL || '').replace(/\/+$/, ''),
|
||||
timeoutMs: Number(process.env.MAIN_SYSTEM_TIMEOUT_MS || 5000),
|
||||
supplierLoginPath: process.env.MAIN_SYSTEM_SUPPLIER_LOGIN_PATH || '/api/supplier/login',
|
||||
},
|
||||
// 主系统「进销存对接密钥」:本系统以外部 ERP 身份拉取分配给某供应商(= 我们的分公司)的备货任务。
|
||||
// 见主系统 docs/供应商开放API接入.md §2/§7:oauth 换 token → GET /supplier/preparations。
|
||||
mainSystemIntegration: {
|
||||
clientId: process.env.MAIN_SYSTEM_INTEGRATION_CLIENT_ID || '',
|
||||
clientSecret: process.env.MAIN_SYSTEM_INTEGRATION_CLIENT_SECRET || '',
|
||||
oauthPath: process.env.MAIN_SYSTEM_OAUTH_PATH || '/api/supplier/oauth/token',
|
||||
preparationsPath: process.env.MAIN_SYSTEM_PREPARATIONS_PATH || '/api/supplier/preparations',
|
||||
/** 主系统 webhook 推送的验签密钥(在主系统侧配置 webhook_url 时一次性下发) */
|
||||
webhookSecret: process.env.MAIN_SYSTEM_WEBHOOK_SECRET || '',
|
||||
/** 定时对账(兜底)开关:默认开;webhook 是实时通道,这个是防漏推 */
|
||||
autoImportEnabled: process.env.MAIN_SYSTEM_AUTO_IMPORT !== '0',
|
||||
/** 回写备货状态路径(发车 → status=30,设计文档 20261008 §3.5) */
|
||||
statusPath: process.env.MAIN_SYSTEM_STATUS_PATH || '/api/supplier/preparations/status',
|
||||
/** 退货跟随(第三方订单):默认关(=0 时完全不检测、不处置),联调后开 */
|
||||
returnFollowEnabled: process.env.MAIN_SYSTEM_RETURN_FOLLOW === '1',
|
||||
/**
|
||||
* 回写主系统备货完成(`status=30` + 实供量 + 已审核价):**默认开**,显式 `MAIN_SYSTEM_WRITEBACK=0` 才关。
|
||||
*
|
||||
* 为什么改成默认开(开发者 2026-10-11):「发车回写为什么要做成开关呢?这不应该就是一个默认的状态吗」
|
||||
* —— 回写是业务流程的一环(主系统要靠 `prepare_status >= 30` 才会推进/派车),
|
||||
* 藏在 opt-in 开关后面会让"我方已待配送、主系统仍显示待备货"这种状态长期存在。
|
||||
*/
|
||||
writebackEnabled: process.env.MAIN_SYSTEM_WRITEBACK !== '0',
|
||||
/**
|
||||
* 主系统**履约事件**接收端(picked_up / inbound_completed)⇒ 我方订单收口 90。
|
||||
*
|
||||
* 2026-10-11 开发者定稿:**默认开**(`!== '0'` 才关)——它与下面的
|
||||
* `skipInboundAwaitPickup` 是**一对**:免入库单停在 50 等骑手取货,收口只能靠本接收端,
|
||||
* 关着时主系统的 `picked_up` 只会被「200 收下但忽略」(不入台账、不重放)⇒ 永远收不了口。
|
||||
* 写 `0` = 回退到"webhook 对新事件一律 200 忽略"的旧行为(送仓单也就不再靠事件收口)。
|
||||
* 见 docs/design/20261010-第三方订单履约事件接收端与免入库回写时机.md §9.3
|
||||
*/
|
||||
fulfillmentEventsEnabled: process.env.MAIN_SYSTEM_FULFILLMENT_EVENTS !== '0',
|
||||
/**
|
||||
* 免入库订单**等主系统确认发车(骑手取货)**才收口(停在 50,展示「待取货」),
|
||||
* 而不是我方分拣完毕即结案。
|
||||
*
|
||||
* 2026-10-11 开发者定稿:**默认开**(`!== '0'` 才关)——免入库单本来就不走我方配送,
|
||||
* 关掉只用于整体回退到 2026-10-09 的"分拣完毕即结案 90"旧行为。
|
||||
*
|
||||
* ⚠️ 与 `fulfillmentEventsEnabled` 是**一对**:只开本开关不开接收端,免入库单停在 50 后
|
||||
* `preparations.picked_up` 只会被「200 收下但忽略」(事件不入台账、不会重放)⇒ **永远收不了口**。
|
||||
*/
|
||||
skipInboundAwaitPickup: process.env.MAIN_SYSTEM_SKIP_INBOUND_AWAIT_PICKUP !== '0',
|
||||
/**
|
||||
* 跨系统**改价/改量审核**(设计文档 20261011):
|
||||
* 提交端点路径 + 总开关。默认关 = 与改造前逐字节一致(含"发车回写价格"的静默通道继续可用);
|
||||
* 主系统侧 Q1–Q4 就绪后再设 `MAIN_SYSTEM_PRICE_QTY_ENABLED=1`。
|
||||
*/
|
||||
priceQtyRequestPath:
|
||||
process.env.MAIN_SYSTEM_PRICE_QTY_REQUEST_PATH || '/api/supplier/preparations/price-qty-request',
|
||||
priceQtyEnabled: process.env.MAIN_SYSTEM_PRICE_QTY_ENABLED === '1',
|
||||
},
|
||||
};
|
||||
|
||||
if (isProduction) {
|
||||
|
||||
@@ -27,6 +27,7 @@ import catalogRoutes from './routes/catalog';
|
||||
import rolesRoutes from './routes/roles';
|
||||
import skuImageRoutes from './routes/skuImage';
|
||||
import menuGroupIconRoutes from './routes/menuGroupIcon';
|
||||
import mainSystemIntegrationRoutes from './routes/mainSystemIntegration';
|
||||
import publicTraceRoutes from './routes/publicTrace';
|
||||
import orderEntryAgentRoutes from './routes/orderEntryAgent';
|
||||
import { tenantDbMiddleware } from './middleware/tenantDbMiddleware';
|
||||
@@ -68,6 +69,8 @@ app.use(
|
||||
);
|
||||
app.use(cors({ origin: config.corsOrigins, credentials: true }));
|
||||
// A11: 普通 JSON 收紧;文件/语音走 multer 独立上限
|
||||
// webhook 验签必须基于**原始 body 字节**,所以该路径先挂 raw 解析(放在 json 之前)
|
||||
app.use('/api/integration/main-system/webhook', express.raw({ type: '*/*', limit: '2mb' }));
|
||||
app.use(express.json({ limit: '2mb' }));
|
||||
|
||||
function loginKeyGenerator(req: {
|
||||
@@ -167,6 +170,7 @@ app.use('/api/accounts', tenantDbMiddleware, accountRoutes);
|
||||
app.use('/api/dashboard', tenantDbMiddleware, dashboardRoutes);
|
||||
app.use('/api/workflow', workflowRoutes);
|
||||
app.use('/api/mcp/order-entry', tenantDbMiddleware, orderEntryAgentRoutes);
|
||||
app.use('/api/integration', tenantDbMiddleware, mainSystemIntegrationRoutes);
|
||||
app.use('/api/public', publicTraceRoutes);
|
||||
app.use('/api/modules', modulesRoutes);
|
||||
app.use('/api/catalog', tenantDbMiddleware, catalogRoutes);
|
||||
@@ -215,6 +219,17 @@ if (require.main === module) {
|
||||
: 'production(api-only)'
|
||||
: 'development';
|
||||
console.log(`API server running on 0.0.0.0:${config.port} (${mode})`);
|
||||
// 显眼地打出去连的是哪个主系统:本地开发是 127.0.0.1:3001,上线后是线上地址。
|
||||
// 这一行是为了防「以为在连本地、其实指着生产」——看到不像本地的地址就停下来确认。
|
||||
if (config.mainSystem.baseUrl) {
|
||||
const looksLocal = /^https?:\/\/(127\.0\.0\.1|localhost)(:|\/|$)/.test(config.mainSystem.baseUrl);
|
||||
console.log(
|
||||
`[main-system] 供应商账号校验将回主系统:${config.mainSystem.baseUrl}` +
|
||||
`(${looksLocal ? '本地' : '⚠️ 非本地,请确认是预期环境'};超时 ${config.mainSystem.timeoutMs}ms)`
|
||||
);
|
||||
} else {
|
||||
console.warn('[main-system] 未配置 MAIN_SYSTEM_BASE_URL:供应商账号无法登录(本系统自建账号不受影响)');
|
||||
}
|
||||
void ensureRoleDefinitionsSchema().catch((err) => {
|
||||
console.warn('role_definitions schema ensure skipped:', err?.message || err);
|
||||
});
|
||||
|
||||
+13
-10
@@ -1,7 +1,7 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { pool } from './db';
|
||||
import { setupDatabase } from './setup-db';
|
||||
import { setupDatabase, resolveAppRoleName, quotePgIdent } from './setup-db';
|
||||
import { seedPermissions } from './seed-permissions';
|
||||
import { seedDemoData } from './seed-demo-data';
|
||||
import { seedMobileAccounts } from './seed-mobile-accounts';
|
||||
@@ -91,7 +91,7 @@ async function applySqlFile(filePath: string) {
|
||||
}
|
||||
}
|
||||
|
||||
/** 生产/远程库无需在本机创建 canteen 用户与数据库 */
|
||||
/** 生产/远程库无需在本机创建应用角色与数据库 */
|
||||
function shouldRunLocalDbSetup(): boolean {
|
||||
if (process.env.SKIP_LOCAL_DB_SETUP === '1') return false;
|
||||
if (process.env.NODE_ENV === 'production') return false;
|
||||
@@ -212,15 +212,18 @@ async function main() {
|
||||
console.log('Migrations complete.');
|
||||
|
||||
if (shouldRunLocalDbSetup()) {
|
||||
// 授权目标必须是 DATABASE_URL 里的应用角色(供应商系统为 supplier);
|
||||
// 此处曾硬编码主系统角色 canteen,会把本系统库的权限授给主系统角色。
|
||||
const appRole = quotePgIdent(resolveAppRoleName());
|
||||
await pool.query(`
|
||||
GRANT ALL ON SCHEMA public TO canteen;
|
||||
GRANT ALL ON SCHEMA auth TO canteen;
|
||||
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO canteen;
|
||||
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO canteen;
|
||||
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA auth TO canteen;
|
||||
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA auth TO canteen;
|
||||
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO canteen;
|
||||
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO canteen;
|
||||
GRANT ALL ON SCHEMA public TO ${appRole};
|
||||
GRANT ALL ON SCHEMA auth TO ${appRole};
|
||||
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO ${appRole};
|
||||
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO ${appRole};
|
||||
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA auth TO ${appRole};
|
||||
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA auth TO ${appRole};
|
||||
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO ${appRole};
|
||||
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO ${appRole};
|
||||
`).catch(() => undefined);
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,21 @@ import {
|
||||
moveOrderToTrash,
|
||||
restoreOrderFromTrash,
|
||||
} from '../../../services/orderDeleteService';
|
||||
import { reportMainSystemStockout } from '../../../services/mainSystemStockout';
|
||||
import {
|
||||
listOrderActualFacts,
|
||||
refreshOrderActualFacts,
|
||||
} from '../../../services/mainSystemActualFacts';
|
||||
import {
|
||||
listActualQtyInbox,
|
||||
decideActualQtyRequest,
|
||||
} from '../../../services/mainSystemActualQtyInbox';
|
||||
import {
|
||||
isEnabled as isPriceQtyRequestEnabled,
|
||||
listPriceQtyRequests,
|
||||
submitPriceQtyRequest,
|
||||
toPriceQtyRequestDto,
|
||||
} from '../../../services/mainSystemPriceQtyRequest';
|
||||
import {
|
||||
getCustomerOrderPrefill,
|
||||
logOrderBatchAction,
|
||||
@@ -38,6 +53,7 @@ import { submitMobileCustomerOrder } from '../../../services/customerOrderSubmit
|
||||
import {
|
||||
syncOrderManageItems,
|
||||
updateOrderDeliveryDate,
|
||||
updateOrderDeliveryAddress,
|
||||
} from '../../../services/orderManageItemsService';
|
||||
import {
|
||||
isSmartAllocationEnabled,
|
||||
@@ -243,6 +259,297 @@ router.patch('/orders/:orderCode/items', authMiddleware, async (req: AuthRequest
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 明细「缺货」(开发者 2026-10-10)。
|
||||
*
|
||||
* 主系统分配过来的订单**不能删订单、不能删商品**,只留这一个动作:
|
||||
* 报主系统 `POST /preparations/status {status:40}`(主系统把该行**转自采**)⇒
|
||||
* 成功后再把我方这一行的履约收口(未完成采购作废、明细标缺货),从"待备货/未完成采购"里剔除。
|
||||
* 口径与顺序纪律见 services/mainSystemStockout.ts。
|
||||
*/
|
||||
router.post(
|
||||
'/orders/:orderCode/items/:itemId/stockout',
|
||||
authMiddleware,
|
||||
async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const ctx = await getWorkflowCtx(req);
|
||||
requireWorkflowPermission(ctx, ['order_edit', 'order_entry', 'order_manage', 'allocation_manage']);
|
||||
const orderCode = String(req.params.orderCode || '').trim();
|
||||
const itemId = String(req.params.itemId || '').trim();
|
||||
const order = await assertOrderCodeAccess(orderCode, ctx!);
|
||||
const outcome = await reportMainSystemStockout({
|
||||
branchCode: order.branch_code || ctx?.branchCode || '',
|
||||
orderCode,
|
||||
itemId,
|
||||
reason: req.body?.reason ?? req.body?.stockout_reason ?? null,
|
||||
userId: ctx?.userId ?? null,
|
||||
operatorRoles: ctx?.roles?.length ? ctx.roles.join(',') : null,
|
||||
ipAddress: req.ip || req.socket?.remoteAddress || null,
|
||||
});
|
||||
|
||||
if (outcome.kind === 'ok') {
|
||||
return res.json({
|
||||
data: {
|
||||
order_code: outcome.ourOrderCode,
|
||||
item_id: outcome.itemId,
|
||||
prep_id: outcome.prepId || null,
|
||||
already_reported: outcome.alreadyReported,
|
||||
},
|
||||
});
|
||||
}
|
||||
if (outcome.kind === 'unavailable') {
|
||||
return res.status(502).json({ error: 'main_system_unavailable', error_description: outcome.reason });
|
||||
}
|
||||
if (outcome.kind === 'rejected') {
|
||||
return res.status(400).json({ error: 'main_system_rejected', error_description: outcome.reason });
|
||||
}
|
||||
if (outcome.kind === 'not_main_system_item') {
|
||||
return res.status(400).json({ error: 'not_main_system_item', error_description: outcome.reason });
|
||||
}
|
||||
return res.status(409).json({ error: 'invalid_state', error_description: outcome.reason });
|
||||
} catch (error: any) {
|
||||
return res.status(error?.status || 500).json({
|
||||
error: error?.code || 'server_error',
|
||||
error_description: error?.message || '上报缺货失败',
|
||||
});
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* 跨系统改价 / 改量:提交申请(2026-10-11)。
|
||||
*
|
||||
* 主系统分配过来的订单行,**改销售价(= 主系统成本价)/ 改数量只能走这里**:
|
||||
* 免审项(补价、改低、减量)提交后主系统立即生效 ⇒ 我们同步落地;
|
||||
* 涨价/加量 ⇒ 主系统管理员审核,结果经 webhook `preparations.price_qty_decided` 回传。
|
||||
* 见 docs/design/20261011-跨系统改价改量审核.md(§4 C2/C6)。
|
||||
*/
|
||||
router.post(
|
||||
'/orders/:orderCode/items/:itemId/price-qty-request',
|
||||
authMiddleware,
|
||||
async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const ctx = await getWorkflowCtx(req);
|
||||
requireWorkflowPermission(ctx, ['order_edit', 'order_entry', 'order_manage', 'allocation_manage']);
|
||||
const orderCode = String(req.params.orderCode || '').trim();
|
||||
const itemId = String(req.params.itemId || '').trim();
|
||||
const order = await assertOrderCodeAccess(orderCode, ctx!);
|
||||
const branchCode = order.branch_code || ctx?.branchCode || '';
|
||||
const outcome = await submitPriceQtyRequest({
|
||||
branchCode,
|
||||
ourOrderCode: orderCode,
|
||||
ourOrderItemId: itemId,
|
||||
proposedPrice: req.body?.proposed_price ?? req.body?.price ?? null,
|
||||
proposedQty: req.body?.proposed_qty ?? req.body?.quantity ?? null,
|
||||
unit: req.body?.unit ?? null,
|
||||
reason: req.body?.reason ?? null,
|
||||
actor: {
|
||||
userId: ctx?.userId ?? null,
|
||||
roles: ctx?.roles?.length ? ctx.roles.join(',') : null,
|
||||
requestedBy: `${branchCode}:${ctx?.roles?.length ? ctx.roles.join('|') : 'operator'}:${ctx?.userId ?? ''}`,
|
||||
ipAddress: req.ip || req.socket?.remoteAddress || null,
|
||||
},
|
||||
clientRequestId: req.body?.client_request_id ?? null,
|
||||
});
|
||||
|
||||
if (outcome.kind === 'ok') {
|
||||
return res.json({
|
||||
data: {
|
||||
request: toPriceQtyRequestDto(outcome.row),
|
||||
status: outcome.status,
|
||||
review_required: outcome.reviewRequired,
|
||||
final_price: outcome.finalPrice,
|
||||
final_qty: outcome.finalQty,
|
||||
message: outcome.message,
|
||||
applied_locally: outcome.appliedLocally,
|
||||
apply_note: outcome.applyNote,
|
||||
},
|
||||
error: null,
|
||||
});
|
||||
}
|
||||
if (outcome.kind === 'disabled') {
|
||||
return res.status(503).json({ error: 'price_qty_disabled', error_description: outcome.reason });
|
||||
}
|
||||
if (outcome.kind === 'main_system_not_ready') {
|
||||
return res.status(503).json({ error: 'main_system_not_ready', error_description: outcome.reason });
|
||||
}
|
||||
if (outcome.kind === 'failed') {
|
||||
return res
|
||||
.status(outcome.retryable ? 502 : 400)
|
||||
.json({
|
||||
error: outcome.retryable ? 'main_system_unavailable' : 'main_system_rejected',
|
||||
error_description: outcome.reason,
|
||||
});
|
||||
}
|
||||
if (outcome.kind === 'not_main_system_order') {
|
||||
return res.status(400).json({ error: 'not_main_system_item', error_description: outcome.reason });
|
||||
}
|
||||
if (outcome.kind === 'no_change') {
|
||||
return res.status(400).json({ error: 'no_change', error_description: outcome.reason });
|
||||
}
|
||||
return res.status(400).json({ error: 'invalid_request', error_description: outcome.reason });
|
||||
} catch (error: any) {
|
||||
return res.status(error?.status || 500).json({
|
||||
error: error?.code || 'server_error',
|
||||
error_description: error?.message || '提交改价/改量申请失败',
|
||||
});
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* 跨系统改价 / 改量:申请列表(界面用;待审核 / 已生效 / 已通过 / 已驳回)。
|
||||
* 只读本系统台账(`public.main_system_price_qty_requests`),不触达主系统。
|
||||
*/
|
||||
router.get('/main-system/price-qty-requests', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const ctx = await getWorkflowCtx(req);
|
||||
requireWorkflowPermission(ctx, ['order_edit', 'order_entry', 'order_manage', 'allocation_manage', 'purchase_manage']);
|
||||
const requested = readOperatingBranchCode(req);
|
||||
const branchCode = getEffectiveBranchCode(ctx!, requested) || ctx?.branchCode || '';
|
||||
const status = req.query?.status ? String(req.query.status) : null;
|
||||
const ourOrderCode = req.query?.order_code ? String(req.query.order_code) : null;
|
||||
const rows = await listPriceQtyRequests({
|
||||
branchCode,
|
||||
status,
|
||||
ourOrderCode,
|
||||
limit: Number(req.query?.limit) || 100,
|
||||
});
|
||||
return res.json({
|
||||
data: rows.map((row) => toPriceQtyRequestDto(row)),
|
||||
enabled: isPriceQtyRequestEnabled(),
|
||||
error: null,
|
||||
});
|
||||
} catch (error: any) {
|
||||
return res.status(error?.status || 500).json({
|
||||
error: error?.code || 'server_error',
|
||||
error_description: error?.message || '查询改价/改量申请失败',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/* ── 对方发起、我方审核:实收数量/单位/完结后成本价申请(2026-10-11 第五批 Q8/Q9)──
|
||||
* · 列表:待我审核 + 已审历史;
|
||||
* · 审核:通过 / 改值后通过 / 驳回 —— 结论回传主系统**成功后才改本地台账**(见服务层)。
|
||||
* 核货节点(node=picking_check)为事实登记:驳回**不让对方回滚**;>=60/>=90 为先审后改。
|
||||
*/
|
||||
/**
|
||||
* 主系统备货行的**核货/入库事实**(2026-10-11,设计文档 `20261011-免入库核货完毕标记.md`)。
|
||||
*
|
||||
* · GET :**只读库**(不调外部)⇒ 主系统抖动也不会拖慢/拖挂订单详情;
|
||||
* · POST :显式拉一次 `POST /preparations/lookup` 落库后回读;失败返回 `refreshed:false` + 库内已有事实(**不 500**)。
|
||||
*
|
||||
* 只读镜像:不新增订单状态值、不改状态链、不回写主系统。
|
||||
*/
|
||||
router.get('/orders/:orderCode/main-system-prep-facts', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const ctx = await getWorkflowCtx(req);
|
||||
requireWorkflowPermission(ctx, [
|
||||
'order_manage',
|
||||
'order_view',
|
||||
'order_edit',
|
||||
'order_entry',
|
||||
'order_status_update',
|
||||
]);
|
||||
const requested = readOperatingBranchCode(req);
|
||||
const branchCode = getEffectiveBranchCode(ctx!, requested) || ctx?.branchCode || '';
|
||||
const orderCode = String(req.params.orderCode || '').trim();
|
||||
if (!orderCode) {
|
||||
return res.status(400).json({ error: 'invalid_request', error_description: '缺少订单号' });
|
||||
}
|
||||
const items = await listOrderActualFacts({ branchCode, ourOrderCode: orderCode });
|
||||
return res.json({ data: { items }, error: null });
|
||||
} catch (error: any) {
|
||||
return res.status(error?.status || 500).json({
|
||||
error: error?.code || 'server_error',
|
||||
error_description: error?.message || '读取主系统核货事实失败',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/orders/:orderCode/main-system-prep-facts/refresh', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const ctx = await getWorkflowCtx(req);
|
||||
requireWorkflowPermission(ctx, [
|
||||
'order_manage',
|
||||
'order_view',
|
||||
'order_edit',
|
||||
'order_entry',
|
||||
'order_status_update',
|
||||
]);
|
||||
const requested = readOperatingBranchCode(req);
|
||||
const branchCode = getEffectiveBranchCode(ctx!, requested) || ctx?.branchCode || '';
|
||||
const orderCode = String(req.params.orderCode || '').trim();
|
||||
if (!orderCode) {
|
||||
return res.status(400).json({ error: 'invalid_request', error_description: '缺少订单号' });
|
||||
}
|
||||
// 失败不抛:刷新是"锦上添花",详情展示必须照常(用库内已存事实)
|
||||
const outcome = await refreshOrderActualFacts({ branchCode, ourOrderCode: orderCode });
|
||||
return res.json({
|
||||
data: { items: outcome.items, refreshed: outcome.refreshed, reason: outcome.reason ?? null },
|
||||
error: null,
|
||||
});
|
||||
} catch (error: any) {
|
||||
return res.status(error?.status || 500).json({
|
||||
error: error?.code || 'server_error',
|
||||
error_description: error?.message || '刷新主系统核货事实失败',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/main-system/actual-qty-requests', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const ctx = await getWorkflowCtx(req);
|
||||
requireWorkflowPermission(ctx, ['order_edit', 'order_entry', 'order_manage', 'allocation_manage', 'purchase_manage']);
|
||||
const requested = readOperatingBranchCode(req);
|
||||
const branchCode = getEffectiveBranchCode(ctx!, requested) || ctx?.branchCode || '';
|
||||
const rows = await listActualQtyInbox({
|
||||
branchCode,
|
||||
status: req.query?.status ? String(req.query.status) : null,
|
||||
limit: Number(req.query?.limit) || 100,
|
||||
});
|
||||
return res.json({ data: rows, error: null });
|
||||
} catch (error: any) {
|
||||
return res.status(error?.status || 500).json({
|
||||
error: error?.code || 'server_error',
|
||||
error_description: error?.message || '查询待我审核的实收申请失败',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/main-system/actual-qty-requests/:id/decision', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const ctx = await getWorkflowCtx(req);
|
||||
requireWorkflowPermission(ctx, ['order_edit', 'order_entry', 'order_manage', 'allocation_manage']);
|
||||
const requested = readOperatingBranchCode(req);
|
||||
const branchCode = getEffectiveBranchCode(ctx!, requested) || ctx?.branchCode || '';
|
||||
const decision = String(req.body?.decision || '').toLowerCase();
|
||||
if (decision !== 'approved' && decision !== 'rejected') {
|
||||
return res.status(400).json({ error: 'invalid_request', error_description: '决策只能是 approved 或 rejected' });
|
||||
}
|
||||
const rawFinal = req.body?.final_value;
|
||||
const finalValue =
|
||||
rawFinal === null || rawFinal === undefined || rawFinal === '' ? null : Number(rawFinal);
|
||||
if (finalValue !== null && !Number.isFinite(finalValue)) {
|
||||
return res.status(400).json({ error: 'invalid_request', error_description: '最终值必须是数字' });
|
||||
}
|
||||
const data = await decideActualQtyRequest({
|
||||
branchCode,
|
||||
rowId: String(req.params.id || ''),
|
||||
decision,
|
||||
finalValue,
|
||||
reviewer: ctx?.userId || null,
|
||||
reason: req.body?.reason != null ? String(req.body.reason) : null,
|
||||
});
|
||||
return res.json({ data });
|
||||
} catch (error: any) {
|
||||
return res.status(error?.status || 500).json({
|
||||
error: error?.code || 'server_error',
|
||||
error_description: error?.message || '审核实收申请失败',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
router.patch('/orders/:orderCode/delivery-date', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const ctx = await getWorkflowCtx(req);
|
||||
@@ -277,6 +584,38 @@ router.patch('/orders/:orderCode/delivery-date', authMiddleware, async (req: Aut
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* 单独改「收货地址」(表头字段,不带明细,2026-10-11)。
|
||||
* 与配送日不同:地址是发车前最常见的改动,故**不限于管理员**,凡能编辑订单的人(order_edit /
|
||||
* order_entry / order_manage / allocation_manage)都可改;明细锁(40+)不拦它,`>= 90` 才拒。
|
||||
*/
|
||||
router.patch('/orders/:orderCode/delivery-address', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const ctx = await getWorkflowCtx(req);
|
||||
requireWorkflowPermission(ctx, [
|
||||
'order_edit',
|
||||
'order_entry',
|
||||
'order_manage',
|
||||
'allocation_manage',
|
||||
]);
|
||||
const orderCode = String(req.params.orderCode || '').trim();
|
||||
await assertOrderCodeAccess(orderCode, ctx);
|
||||
const data = await updateOrderDeliveryAddress({
|
||||
orderCode,
|
||||
deliveryAddress: req.body?.delivery_address ?? null,
|
||||
operatorId: ctx?.userId || null,
|
||||
operatorRoles: ctx?.roles?.length ? ctx.roles.join(',') : null,
|
||||
});
|
||||
return res.json({ data });
|
||||
} catch (error: any) {
|
||||
return res.status(error?.status || 500).json({
|
||||
error: error?.code || 'server_error',
|
||||
error_description: error?.message || '修改收货地址失败',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/orders/reprocess-allocation', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const ctx = await getWorkflowCtx(req);
|
||||
|
||||
+132
-12
@@ -45,8 +45,19 @@ import {
|
||||
} from '../services/userBindingService';
|
||||
import { mergeBindingsFromRoles, stateToBindingsInput } from '../services/roleBindingSync';
|
||||
import { assertPlatformBranchProtected } from '../services/platformBranch';
|
||||
import { ensureTenantSchemaCloned, applyTenantSearchPath } from '../services/tenantSchemaService';
|
||||
import { runInBranchSchema } from '../services/tenantSchemaFallback';
|
||||
import {
|
||||
ensureTenantSchemaCloned,
|
||||
applyTenantSearchPath,
|
||||
invalidateTenantSchemaResolveCache,
|
||||
} from '../services/tenantSchemaService';
|
||||
import { runInBranchSchema, invalidateActiveTenantBranchesCache } from '../services/tenantSchemaFallback';
|
||||
import {
|
||||
isMainSystemVerificationEnabled,
|
||||
looksLikeSupplierLoginName,
|
||||
verifySupplierCredentialOnMainSystem,
|
||||
} from '../services/mainSystemSupplierAuth';
|
||||
import { ensureMainSupplierBranchAndAdmin } from '../services/supplierBranchProvisioning';
|
||||
import { loadAuthUsersByIds } from '../services/accountLoginService';
|
||||
import { listAssignableRoleCodes } from '../services/roleDefinitionService';
|
||||
|
||||
const router = Router();
|
||||
@@ -88,13 +99,16 @@ async function jsonUnifiedSession(res: Response, user: AuthUserRow, loginNameFal
|
||||
[user.id]
|
||||
);
|
||||
const mustChangePassword = Boolean(profileResult.rows[0]?.must_change_password);
|
||||
const bindings = await getAccountBindings(user.id);
|
||||
const home_path = await resolveWebHomePath(user.id);
|
||||
// 登录时已从 public.profiles 取到分公司:把它当"优先租户"传下去,
|
||||
// 避免同一次登录把同一件事跨全部租户做 3~7 遍(规模改造 §4;未命中仍回退全扫描)。
|
||||
const loginBranchCode = user.branch_code ?? null;
|
||||
const bindings = await getAccountBindings(user.id, loginBranchCode, user.email);
|
||||
const home_path = await resolveWebHomePath(user.id, loginBranchCode, user.email);
|
||||
const session = buildSession(user);
|
||||
|
||||
let mobile_session: Awaited<ReturnType<typeof createMobileLoginResponse>> | null = null;
|
||||
if (needsMobileSession(bindings, home_path)) {
|
||||
const roleType = await resolveMobileRoleType(user.id, user.email);
|
||||
const roleType = await resolveMobileRoleType(user.id, user.email, loginBranchCode);
|
||||
if (roleType) {
|
||||
try {
|
||||
mobile_session = await createMobileLoginResponse(user.id, user.email, roleType);
|
||||
@@ -428,6 +442,69 @@ async function createAuthUser(params: {
|
||||
return runInBranchSchema(branchCode, runCreate);
|
||||
}
|
||||
|
||||
/** 该登录名是否属于「主系统供应商账号」(本地密码不可用,必须回主系统校验) */
|
||||
async function loadAccountSource(loginName: string): Promise<string | null> {
|
||||
const result = await pool.query<{ account_source: string }>(
|
||||
`SELECT account_source FROM profiles WHERE lower(username) = lower($1) LIMIT 1`,
|
||||
[loginName]
|
||||
);
|
||||
return result.rows[0]?.account_source ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 供应商账号登录:向主系统校验 → 通过则(必要时)惰性开通分公司+管理员 → 签发本系统 token。
|
||||
*
|
||||
* 三态处理是本函数的核心:
|
||||
* ok → 登录
|
||||
* invalid → 400(主系统明确说凭据不对/账号不可用)
|
||||
* unavailable → 503(**没问成**:未配置/超时/网络/5xx)。**绝不回落本地密码**,
|
||||
* 否则主系统一挂,供应商就能拿本地旧密码登进来,绕过主系统的停用与改密。
|
||||
*/
|
||||
async function handleMainSupplierLogin(
|
||||
res: Response,
|
||||
loginName: string,
|
||||
password: string,
|
||||
/**
|
||||
* 签发会话的方式:不同登录入口的响应体不同——
|
||||
* /api/auth/token → jsonTokenSession
|
||||
* /api/auth/unified-login → jsonUnifiedSession(Web 登录页用的就是这个入口)
|
||||
* ⚠️ 漏接某个入口的后果:那个入口的供应商账号会一直报"登录名或密码错误"。
|
||||
*/
|
||||
issueSession: (user: AuthUserRow) => Promise<Response> = (user) => jsonTokenSession(res, user)
|
||||
): Promise<Response> {
|
||||
const verdict = await verifySupplierCredentialOnMainSystem(loginName, password);
|
||||
|
||||
if (verdict.kind === 'unavailable') {
|
||||
console.warn(`[login] 供应商账号登录未能完成主系统校验(${verdict.reason}):${loginName}`);
|
||||
return res.status(503).json({
|
||||
error: 'main_system_unavailable',
|
||||
error_description: '主系统暂时不可用,供应商账号暂时无法登录,请稍后重试',
|
||||
});
|
||||
}
|
||||
if (verdict.kind !== 'ok') {
|
||||
return res.status(400).json({ error: 'invalid_credentials', error_description: '登录名或密码错误' });
|
||||
}
|
||||
|
||||
let provisioned: Awaited<ReturnType<typeof ensureMainSupplierBranchAndAdmin>>;
|
||||
try {
|
||||
provisioned = await ensureMainSupplierBranchAndAdmin(verdict.profile);
|
||||
} catch (error: any) {
|
||||
if (error?.code === 'login_name_taken') {
|
||||
return res.status(409).json({
|
||||
error: 'login_name_taken',
|
||||
error_description: '该手机号已被本系统内部账号占用,请联系超级管理员处理',
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
const [user] = await loadAuthUsersByIds([provisioned.userId]);
|
||||
if (!user) {
|
||||
return res.status(500).json({ error: 'server_error', error_description: '登录失败,请稍后重试' });
|
||||
}
|
||||
return issueSession(user);
|
||||
}
|
||||
|
||||
router.post('/token', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const loginName = String(req.body?.username || req.body?.login_name || req.body?.email || '').trim();
|
||||
@@ -436,6 +513,12 @@ router.post('/token', async (req: Request, res: Response) => {
|
||||
return res.status(400).json({ error: 'invalid_credentials', error_description: '登录名或密码错误' });
|
||||
}
|
||||
|
||||
// ① 主系统供应商账号:本地密码是随机不可用值,一律以主系统为准
|
||||
if (await loadAccountSource(loginName) === 'main_supplier') {
|
||||
// 必须 await:直接 return Promise 会让 reject 绕过本函数的 try/catch
|
||||
return await handleMainSupplierLogin(res, loginName, password);
|
||||
}
|
||||
|
||||
if (loginName.includes('@')) {
|
||||
const user = await verifyPassword(loginName, password);
|
||||
if (!user) {
|
||||
@@ -448,10 +531,17 @@ router.post('/token', async (req: Request, res: Response) => {
|
||||
if (outcome.kind === 'need_branch') {
|
||||
return res.json(loginOutcomeToNeedBranchJson(outcome));
|
||||
}
|
||||
if (outcome.kind !== 'ok') {
|
||||
return res.status(400).json({ error: 'invalid_credentials', error_description: '登录名或密码错误' });
|
||||
if (outcome.kind === 'ok') {
|
||||
return jsonTokenSession(res, outcome.user);
|
||||
}
|
||||
return jsonTokenSession(res, outcome.user);
|
||||
|
||||
// ② 本地没有/没通过:可能是尚未开通的主系统供应商(手机号)⇒ 惰性开通后登录
|
||||
if (looksLikeSupplierLoginName(loginName) && isMainSystemVerificationEnabled()) {
|
||||
// 同上:必须 await
|
||||
return await handleMainSupplierLogin(res, loginName, password);
|
||||
}
|
||||
|
||||
return res.status(400).json({ error: 'invalid_credentials', error_description: '登录名或密码错误' });
|
||||
} catch (error: any) {
|
||||
console.error('Login error:', error);
|
||||
if (error?.code === 'account_disabled' || error?.code === 'branch_disabled') {
|
||||
@@ -485,14 +575,29 @@ router.post('/unified-login', async (req: Request, res: Response) => {
|
||||
return res.status(400).json({ error: 'invalid_credentials', error_description: '请输入登录名和密码' });
|
||||
}
|
||||
|
||||
// ① 主系统供应商账号:与 /token 同一条通道(本地密码是随机不可用值,以主系统为准)
|
||||
if (await loadAccountSource(loginName) === 'main_supplier') {
|
||||
return await handleMainSupplierLogin(res, loginName, password, (user) =>
|
||||
jsonUnifiedSession(res, user, loginName)
|
||||
);
|
||||
}
|
||||
|
||||
const outcome = await verifyLoginNameOutcome(loginName, password, 'web');
|
||||
if (outcome.kind === 'need_branch') {
|
||||
return res.json(loginOutcomeToNeedBranchJson(outcome));
|
||||
}
|
||||
if (outcome.kind !== 'ok') {
|
||||
return res.status(400).json({ error: 'invalid_credentials', error_description: '登录名或密码错误' });
|
||||
if (outcome.kind === 'ok') {
|
||||
return jsonUnifiedSession(res, outcome.user, loginName);
|
||||
}
|
||||
return jsonUnifiedSession(res, outcome.user, loginName);
|
||||
|
||||
// ② 本地没通过:可能是尚未开通的主系统供应商(手机号)⇒ 惰性开通后登录
|
||||
if (looksLikeSupplierLoginName(loginName) && isMainSystemVerificationEnabled()) {
|
||||
return await handleMainSupplierLogin(res, loginName, password, (user) =>
|
||||
jsonUnifiedSession(res, user, loginName)
|
||||
);
|
||||
}
|
||||
|
||||
return res.status(400).json({ error: 'invalid_credentials', error_description: '登录名或密码错误' });
|
||||
} catch (error: any) {
|
||||
console.error('Unified login error:', error);
|
||||
if (error?.code === 'account_disabled' || error?.code === 'branch_disabled') {
|
||||
@@ -686,9 +791,20 @@ router.post('/admin/branches', authMiddleware, async (req: AuthRequest, res: Res
|
||||
[userId, email, passwordHash, JSON.stringify({ username, full_name: fullName })]
|
||||
);
|
||||
|
||||
// ⚠️ 必须 upsert:auth.users 上的 AFTER INSERT 触发器 on_auth_user_created →
|
||||
// handle_new_user() 会**先插一行 profiles**(id/username/full_name/avatar_url)。
|
||||
// 原来这里是裸 INSERT,必然撞 profiles_pkey(23505),再被外层 catch 的
|
||||
// /duplicate key value/ 误报成 "already_exists" —— 表现为"超管建分公司永远失败"。
|
||||
await client.query(
|
||||
`INSERT INTO profiles (id, username, full_name, phone, branch_code, status, must_change_password)
|
||||
VALUES ($1, $2, $3, $4, $5, 1, true)`,
|
||||
VALUES ($1, $2, $3, $4, $5, 1, true)
|
||||
ON CONFLICT (id) DO UPDATE SET
|
||||
username = EXCLUDED.username,
|
||||
full_name = EXCLUDED.full_name,
|
||||
phone = EXCLUDED.phone,
|
||||
branch_code = EXCLUDED.branch_code,
|
||||
status = EXCLUDED.status,
|
||||
must_change_password = EXCLUDED.must_change_password`,
|
||||
[userId, username, fullName, profilePhone, branchCode]
|
||||
);
|
||||
|
||||
@@ -922,6 +1038,10 @@ router.delete('/admin/branches/:branchCode', authMiddleware, async (req: AuthReq
|
||||
await client.query(`DELETE FROM branches WHERE branch_code = $1`, [branchCode]);
|
||||
await client.query('COMMIT');
|
||||
for (const userId of userIds) invalidateTenantContextCache(userId);
|
||||
// 分公司删除会级联删掉 tenant_schema_registry 行:租户清单(30s)与 schema 解析(60s)缓存必须一起失效,
|
||||
// 否则这段时间里审计/通知/绑定等按 active 租户遍历的路径仍会进这个已删租户(规模改造 §7 复查)
|
||||
invalidateActiveTenantBranchesCache();
|
||||
invalidateTenantSchemaResolveCache(branchCode);
|
||||
} catch (error) {
|
||||
await client.query('ROLLBACK');
|
||||
throw error;
|
||||
|
||||
@@ -0,0 +1,350 @@
|
||||
import { Router, Request, Response } from 'express';
|
||||
import crypto from 'crypto';
|
||||
import { config } from '../config';
|
||||
import { authMiddleware, AuthRequest } from '../middleware/auth';
|
||||
import { loadTenantContext } from '../services/tenantScope';
|
||||
import {
|
||||
fetchMainSystemPreparations,
|
||||
isMainSystemIntegrationEnabled,
|
||||
} from '../services/mainSystemPreparations';
|
||||
import {
|
||||
groupPreparationRows,
|
||||
importMainSystemGroups,
|
||||
importMainSystemOrders,
|
||||
listImportedMainOrders,
|
||||
} from '../services/mainSystemOrderImport';
|
||||
import {
|
||||
handleFulfillmentEvent,
|
||||
isFulfillmentEvent,
|
||||
isFulfillmentEventsEnabled,
|
||||
} from '../services/mainSystemFulfillmentEvents';
|
||||
import {
|
||||
handlePriceQtyDecidedEvent,
|
||||
isEnabled as isPriceQtyRequestEnabled,
|
||||
isPriceQtyDecidedEvent,
|
||||
} from '../services/mainSystemPriceQtyRequest';
|
||||
import { recordActualQtyRequest } from '../services/mainSystemActualQtyInbox';
|
||||
import type { MainPreparationRow } from '../services/mainSystemPreparations';
|
||||
|
||||
/**
|
||||
* 主系统对接(只读):把主系统「分配给本分公司(= 主系统某供应商)」的备货任务拉过来。
|
||||
*
|
||||
* 用途:主系统按订单把商品分配给某供应商;该供应商在本系统里是一个分公司。
|
||||
* 本系统把任务读回来后,走自己的「订单录入 → 分配 → 创建订单」流程(落单是下一步)。
|
||||
*
|
||||
* 约定:本系统的 `branches.branch_code` == 主系统的 `supplier_code`(惰性开通时就是这么建的),
|
||||
* 所以调用方只用自己登录账号的分公司即可,不需要传 supplier_code。
|
||||
*/
|
||||
const router = Router();
|
||||
|
||||
router.get('/main-system/preparations', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
if (!isMainSystemIntegrationEnabled()) {
|
||||
return res.status(503).json({
|
||||
error: 'integration_not_configured',
|
||||
error_description:
|
||||
'未配置主系统对接:需要 MAIN_SYSTEM_BASE_URL、MAIN_SYSTEM_INTEGRATION_CLIENT_ID、MAIN_SYSTEM_INTEGRATION_CLIENT_SECRET',
|
||||
});
|
||||
}
|
||||
|
||||
const ctx = await loadTenantContext(req.userId);
|
||||
const branchCode = String(ctx?.branchCode || '').trim();
|
||||
if (!branchCode) {
|
||||
return res.status(400).json({
|
||||
error: 'branch_required',
|
||||
error_description: '当前账号未绑定分公司,无法确定要拉取哪家供应商的备货任务',
|
||||
});
|
||||
}
|
||||
|
||||
const view = String(req.query?.view || 'active').trim() || 'active';
|
||||
const outcome = await fetchMainSystemPreparations(branchCode, view);
|
||||
|
||||
if (outcome.kind === 'not_configured') {
|
||||
return res.status(503).json({ error: 'integration_not_configured', error_description: outcome.reason });
|
||||
}
|
||||
if (outcome.kind === 'unavailable') {
|
||||
return res.status(502).json({ error: 'main_system_unavailable', error_description: outcome.reason });
|
||||
}
|
||||
if (outcome.kind === 'rejected') {
|
||||
return res.status(400).json({ error: 'main_system_rejected', error_description: outcome.reason });
|
||||
}
|
||||
|
||||
return res.json({
|
||||
data: {
|
||||
/** 本系统分公司编码(= 主系统 supplier_code) */
|
||||
supplier_code: outcome.supplierCode,
|
||||
/** 主系统侧的分公司编码(仅留痕/排障) */
|
||||
main_branch_code: outcome.branchCode,
|
||||
view,
|
||||
order_count: outcome.orders.length,
|
||||
row_count: outcome.rowCount,
|
||||
/** true 表示主系统返回被 LIMIT 截断(500 条),调用方不得据此判定"某行不存在" */
|
||||
truncated: Boolean(outcome.truncated),
|
||||
/** 按主系统订单号分组:一张订单的 N 个商品 */
|
||||
orders: outcome.orders,
|
||||
},
|
||||
error: null,
|
||||
});
|
||||
} catch (error: any) {
|
||||
console.error('main-system preparations error:', error);
|
||||
return res.status(500).json({ error: 'server_error', error_description: '拉取主系统备货任务失败' });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 生成订单:把主系统分配过来的备货任务,按主系统订单号分组,走本系统录单流程建单。
|
||||
* 幂等:同一主系统订单号只建一次(台账 main_system_order_imports)。
|
||||
*/
|
||||
router.post('/main-system/orders', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
if (!isMainSystemIntegrationEnabled()) {
|
||||
return res.status(503).json({
|
||||
error: 'integration_not_configured',
|
||||
error_description: '未配置主系统对接密钥,无法拉取备货任务',
|
||||
});
|
||||
}
|
||||
|
||||
const ctx = await loadTenantContext(req.userId);
|
||||
const branchCode = String(ctx?.branchCode || '').trim();
|
||||
if (!branchCode) {
|
||||
return res.status(400).json({
|
||||
error: 'branch_required',
|
||||
error_description: '当前账号未绑定分公司,无法确定要给哪家分公司建单',
|
||||
});
|
||||
}
|
||||
|
||||
const only = Array.isArray(req.body?.main_order_codes)
|
||||
? (req.body.main_order_codes as unknown[]).map((v) => String(v)).filter(Boolean)
|
||||
: undefined;
|
||||
|
||||
const outcome = await importMainSystemOrders({ branchCode, userId: req.userId ?? null, onlyMainOrderCodes: only });
|
||||
if (outcome.kind === 'not_configured') {
|
||||
return res.status(503).json({ error: 'integration_not_configured', error_description: outcome.reason });
|
||||
}
|
||||
if (outcome.kind === 'unavailable') {
|
||||
return res.status(502).json({ error: 'main_system_unavailable', error_description: outcome.reason });
|
||||
}
|
||||
return res.json({ data: outcome, error: null });
|
||||
} catch (error: any) {
|
||||
console.error('main-system import orders error:', error);
|
||||
return res.status(500).json({ error: 'server_error', error_description: '生成订单失败' });
|
||||
}
|
||||
});
|
||||
|
||||
/** 已导入台账:主系统订单号 ↔ 本系统订单号 */
|
||||
router.get('/main-system/orders', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const ctx = await loadTenantContext(req.userId);
|
||||
const branchCode = String(ctx?.branchCode || '').trim();
|
||||
if (!branchCode) {
|
||||
return res.status(400).json({ error: 'branch_required', error_description: '当前账号未绑定分公司' });
|
||||
}
|
||||
const rows = await listImportedMainOrders(branchCode, Number(req.query?.limit) || 100);
|
||||
return res.json({ data: rows, error: null });
|
||||
} catch (error: any) {
|
||||
console.error('main-system list imports error:', error);
|
||||
return res.status(500).json({ error: 'server_error', error_description: '查询导入台账失败' });
|
||||
}
|
||||
});
|
||||
|
||||
/* ── 主系统主动推送(Webhook)────────────────────────────────────────────
|
||||
* 主系统在「订单分配成功」事务提交后,对本客户端已绑定且本单涉及的供应商各 POST 一次。
|
||||
* 契约见主系统 docs/供应商开放API接入.md §3.5:
|
||||
* header X-Signature = 'sha256=' + HMAC-SHA256(webhook_secret, 原始 body 字节)
|
||||
* header X-Event = 'preparations.allocated'
|
||||
* body { event, request_id, supplier_code, order_code, data: [备货行...] }
|
||||
* 收到即建单(幂等),因此**不需要人工点击**;漏推由定时对账兜底。
|
||||
*/
|
||||
function verifyWebhookSignature(rawBody: Buffer, header: string | undefined): boolean {
|
||||
const secret = config.mainSystemIntegration.webhookSecret;
|
||||
if (!secret) return false;
|
||||
const provided = String(header || '').trim();
|
||||
if (!provided.startsWith('sha256=')) return false;
|
||||
const expected = 'sha256=' + crypto.createHmac('sha256', secret).update(rawBody).digest('hex');
|
||||
const a = Buffer.from(provided);
|
||||
const b = Buffer.from(expected);
|
||||
return a.length === b.length && crypto.timingSafeEqual(a, b);
|
||||
}
|
||||
|
||||
/** 单行原始 payload → 我们的行结构(字段口径与 GET /preparations 一致) */
|
||||
function mapWebhookRow(raw: any): MainPreparationRow {
|
||||
const num = (v: unknown) => (v === null || v === undefined || v === '' ? null : (Number.isFinite(Number(v)) ? Number(v) : null));
|
||||
const day = (v: unknown) => (v ? String(v).slice(0, 10) : null);
|
||||
return {
|
||||
id: String(raw?.id || ''),
|
||||
orderCode: String(raw?.order_code || ''),
|
||||
// ⚠️ 主系统 webhook 目前会把 branch_code 剥掉(其 deliverToTarget 里 `{ branch_code: _b, ...rest }`),
|
||||
// 所以 webhook 通道通常是 null;已在给主系统的清单里要求放开(P1-11)。
|
||||
branchCode: raw?.branch_code != null ? String(raw.branch_code) : null,
|
||||
// P1-10 同口径:分公司名 / 分公司仓库地址(webhook 通道若把这两个键也剥掉则是 null,
|
||||
// 导入主路径走 GET /preparations,地址以拉取视图为准)
|
||||
branchName: raw?.branch_name != null && String(raw.branch_name).trim() ? String(raw.branch_name).trim() : null,
|
||||
branchAddress:
|
||||
raw?.branch_address != null && String(raw.branch_address).trim()
|
||||
? String(raw.branch_address).trim()
|
||||
: null,
|
||||
skuCode: raw?.sku_code ? String(raw.sku_code) : null,
|
||||
itemName: String(raw?.item_name || raw?.display_name || ''),
|
||||
displayName: raw?.display_name ? String(raw.display_name) : null,
|
||||
prepareQty: num(raw?.prepare_qty),
|
||||
unit: raw?.unit ? String(raw.unit) : null,
|
||||
orderQty: num(raw?.order_qty),
|
||||
orderUnit: raw?.order_unit ? String(raw.order_unit) : null,
|
||||
purchasePrice: num(raw?.purchase_price),
|
||||
suggestedPrice: num(raw?.suggested_price),
|
||||
prepareStatus: num(raw?.prepare_status),
|
||||
deliveryDate: day(raw?.delivery_date),
|
||||
taskDay: day(raw?.task_day),
|
||||
isStockout: raw?.is_stockout === true,
|
||||
processingMethod: raw?.processing_method ? String(raw.processing_method) : null,
|
||||
returnCode: raw?.return_code ? String(raw.return_code) : null,
|
||||
returnReason: raw?.return_reason ? String(raw.return_reason) : null,
|
||||
requiresQualityReport: raw?.requires_quality_report === true,
|
||||
orderItemRemark: raw?.order_item_remark ? String(raw.order_item_remark) : null,
|
||||
// 主系统 2026-10-09 增量(webhook 载荷同步携带):两个事实分别独立,禁止合并判定
|
||||
skipInbound: raw?.skip_inbound === true,
|
||||
isDirectDelivery: raw?.is_direct_delivery === true,
|
||||
// 主系统 2026-10-10 R3:履约事实(只读)。与 mapRow 同口径,null 不兜底
|
||||
actualQty: num(raw?.actual_qty),
|
||||
actualQtyAt: isoOrNull(raw?.actual_qty_at),
|
||||
qtyDiff: num(raw?.qty_diff),
|
||||
isInbounded: raw?.is_inbounded === true,
|
||||
inboundAt: isoOrNull(raw?.inbound_at),
|
||||
orderDepartedAt: isoOrNull(raw?.order_departed_at),
|
||||
};
|
||||
}
|
||||
|
||||
/** 时间字段归一为 ISO 8601(主系统已统一;异常值原样保留便于排查) */
|
||||
function isoOrNull(value: unknown): string | null {
|
||||
if (value === null || value === undefined || value === '') return null;
|
||||
const date = value instanceof Date ? value : new Date(String(value));
|
||||
if (Number.isNaN(date.getTime())) return String(value);
|
||||
return date.toISOString();
|
||||
}
|
||||
|
||||
router.post('/main-system/webhook', async (req: Request, res: Response) => {
|
||||
const rawBody: Buffer = Buffer.isBuffer(req.body) ? req.body : Buffer.from(JSON.stringify(req.body ?? {}));
|
||||
try {
|
||||
if (!verifyWebhookSignature(rawBody, req.header('x-signature'))) {
|
||||
console.warn('[main-system-webhook] 验签失败,拒绝');
|
||||
return res.status(401).json({ error: 'invalid_signature' });
|
||||
}
|
||||
|
||||
const payload = JSON.parse(rawBody.toString('utf8') || '{}');
|
||||
const event = String(payload?.event || '');
|
||||
const supplierCode = String(payload?.supplier_code || '').trim();
|
||||
|
||||
/* ── 跨系统改价/改量结果回传(2026-10-11)──────────────────────────────
|
||||
* `preparations.price_qty_decided`:主系统审核完成(或免审即时生效)后回传最终值,
|
||||
* 以主系统值落地我方订单行。契约见给主系统清单第四批 Q4;
|
||||
* 我方设计见 docs/design/20261011-跨系统改价改量审核.md(§4 C3)。
|
||||
*
|
||||
* 纪律:**允许信封不带 supplier_code**(按 request_id 反查我方台账定位分公司);
|
||||
* 幂等由申请台账的终态判定兜住;业务失败返 200(重试交给对账,重推解决不了前置问题)。
|
||||
*/
|
||||
if (isPriceQtyDecidedEvent(event)) {
|
||||
if (!isPriceQtyRequestEnabled()) {
|
||||
// 开关关闭 ⇒ 与改造前一致:200 收下但忽略
|
||||
return res.json({ ok: true, ignored: true, disabled: true });
|
||||
}
|
||||
const handled = await handlePriceQtyDecidedEvent({
|
||||
branchCode: supplierCode || null,
|
||||
payload,
|
||||
});
|
||||
console.log(
|
||||
`[main-system-webhook] ${supplierCode || '(按 request_id 定位)'} ${event}:` +
|
||||
`${handled.duplicate ? '重复投递(幂等跳过)' : handled.status}` +
|
||||
`${handled.reason ? ` — ${handled.reason}` : ''}`
|
||||
);
|
||||
return res.json({ ok: true, ...handled });
|
||||
}
|
||||
|
||||
/* ── 实收数量/单位申请(2026-10-11 第五批 Q8,主系统提交 b8519fbb)─────────────
|
||||
* `preparations.actual_qty_request`:对方发起、**我方审核**。
|
||||
* · 核货节点(`node=picking_check`)= 事实登记(对方值已落库)⇒ 我方驳回**不让对方回滚**;
|
||||
* · `order_status >= 60` 改实收/单位、`>= 90` 改成本价 = 先审后改(pending 期间两边都不落库)。
|
||||
* 纪律:幂等按对方 `request_id`;业务失败返 200(重试交给对方/对账)。
|
||||
*/
|
||||
if (event === 'preparations.actual_qty_request') {
|
||||
if (!supplierCode) {
|
||||
return res.json({ ok: true, ignored: true, reason: 'missing_supplier_code' });
|
||||
}
|
||||
const recorded = await recordActualQtyRequest({ branchCode: supplierCode, payload });
|
||||
console.log(
|
||||
`[main-system-webhook] ${supplierCode} ${event}:${recorded.status}` +
|
||||
`${recorded.reason ? ` — ${recorded.reason}` : ''}`
|
||||
);
|
||||
return res.json({ ok: true, ...recorded });
|
||||
}
|
||||
|
||||
if (!supplierCode) {
|
||||
// 没有供应商编码就无法定位分公司:200 收下但忽略,避免主系统反复重试
|
||||
return res.json({ ok: true, ignored: true });
|
||||
}
|
||||
|
||||
/* ── 履约事件(2026-10-10):主系统通知"货被取走 / 已入库",我方据此收口 ──────────
|
||||
* `picked_up`(免入库,主系统确认发车)/ `inbound_completed`(送仓,全部入库完成)。
|
||||
* 契约见主系统 docs/design/20261010-supplier-prep-fulfillment-events.md;
|
||||
* 我方设计见 docs/design/20261010-第三方订单履约事件接收端与免入库回写时机.md。
|
||||
*
|
||||
* 纪律:
|
||||
* · **只收事实、只改我方自己的数据**(零反向写回);
|
||||
* · 幂等由事件台账的 UNIQUE 键兜(主系统侧明说不做持久去重);
|
||||
* · 业务失败(如零价被拦)**返回 200** —— 事件已持久化,重试由我方对账负责,
|
||||
* 返 5xx 只会让主系统重推,而重推解决不了"我方前置未满足"。
|
||||
*/
|
||||
if (isFulfillmentEvent(event)) {
|
||||
if (!isFulfillmentEventsEnabled()) {
|
||||
// 开关关闭 ⇒ 与改造前逐字节一致:200 收下但忽略
|
||||
return res.json({ ok: true, ignored: true, disabled: true });
|
||||
}
|
||||
const ackRows = (Array.isArray(payload?.data) ? payload.data : [])
|
||||
.map((raw: unknown) => mapWebhookRow(raw))
|
||||
.filter((r: MainPreparationRow) => r.id && r.orderCode);
|
||||
const handled = await handleFulfillmentEvent({
|
||||
branchCode: supplierCode,
|
||||
event,
|
||||
mainOrderCode: String(payload?.order_code || ''),
|
||||
rows: ackRows,
|
||||
payload,
|
||||
});
|
||||
console.log(
|
||||
`[main-system-webhook] ${supplierCode} ${event} ${payload?.order_code || ''}:` +
|
||||
`${handled.duplicate ? '重复投递(幂等跳过)' : handled.outcome.status}` +
|
||||
`${handled.outcome.reason ? ` — ${handled.outcome.reason}` : ''}`
|
||||
);
|
||||
return res.json({ ok: true, duplicate: handled.duplicate, ...handled.outcome });
|
||||
}
|
||||
|
||||
if (event !== 'preparations.allocated') {
|
||||
// 其它事件一律 200 收下但忽略,避免主系统反复重试
|
||||
return res.json({ ok: true, ignored: true });
|
||||
}
|
||||
|
||||
const rows = (Array.isArray(payload?.data) ? payload.data : [])
|
||||
.map((raw: unknown) => mapWebhookRow(raw))
|
||||
.filter((r: MainPreparationRow) => r.id && r.orderCode);
|
||||
if (!rows.length) return res.json({ ok: true, ignored: true });
|
||||
|
||||
// 本系统的分公司编码 == 主系统的 supplier_code
|
||||
const result = await importMainSystemGroups({
|
||||
branchCode: supplierCode,
|
||||
userId: null,
|
||||
supplierCode,
|
||||
groups: groupPreparationRows(rows),
|
||||
});
|
||||
console.log(
|
||||
`[main-system-webhook] ${supplierCode} 推送建单:新建 ${result.created} / 补行 ${result.appended} / 跳过 ${result.skipped} / 失败 ${result.failed}`
|
||||
);
|
||||
// 有失败时返回 5xx,让主系统按契约重试(最多 2 次);幂等保证不会重复建单
|
||||
if (result.failed > 0) {
|
||||
return res.status(500).json({ ok: false, ...result });
|
||||
}
|
||||
return res.json({ ok: true, ...result });
|
||||
} catch (error: any) {
|
||||
console.error('[main-system-webhook] 处理失败:', error?.message || error);
|
||||
return res.status(500).json({ error: 'server_error' });
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
createCatalogSkuForInbound,
|
||||
listSimilarSkusForInbound,
|
||||
} from '../../services/skuProvisioningService';
|
||||
import { inboundFromWeigh } from '../../services/stockInboundService';
|
||||
import { inboundFromWeigh, normalizeArchive } from '../../services/stockInboundService';
|
||||
import { createQuickCatalogCategory } from '../../services/categoryCatalogService';
|
||||
|
||||
const router = Router();
|
||||
@@ -175,6 +175,8 @@ router.post('/inventory/stock-in', authMiddleware, async (req: AuthRequest, res:
|
||||
remark: req.body?.remark,
|
||||
operatorId: req.userId || null,
|
||||
imageBase64: req.body?.image_base64 || req.body?.photo_base64,
|
||||
// 拍照入库:人工改过的规格/品牌/厂家(不传 archive = 与改前行为完全一致)
|
||||
archive: normalizeArchive(req.body?.archive),
|
||||
};
|
||||
const data = await inboundFromWeigh(input);
|
||||
return res.json({ success: true, data: { ...data, pending: false } });
|
||||
|
||||
@@ -103,12 +103,21 @@ const DENY_WRITE_TABLES = new Set([
|
||||
|
||||
/**
|
||||
* 任何账号都不允许通过通用数据接口「删除」的表:删除必须走带守卫 + 级联的专用路由
|
||||
* (customers → DELETE /customers/:customerCode)。
|
||||
* (customers → DELETE /customers/:customerCode;order_items → 订单明细保存链路)。
|
||||
*
|
||||
* 独立于 DENY_WRITE_TABLES:本名单只拦 delete,不影响 insert/update(客户新增/编辑/
|
||||
* 批量导入仍走数据网关)。放在 isSuperAdmin 短路之前判定,超管同样被拦。
|
||||
*
|
||||
* ⚠️ `orders` **有意不在本名单**:网关执行层对 `orders` 的 delete 已特判到
|
||||
* `deleteOrderWithDependencies`(带守卫与级联),拦在这里会把它一起挡掉
|
||||
* (`tests/accessPolicy.customerDelete.test.ts` 钉住了这条)。
|
||||
* 主系统分配单的"不许删"守卫加在那两个执行入口里(`moveOrderToTrash` /
|
||||
* `deleteOrderWithDependencies`),见 services/mainSystemStockout 与 orderDeleteService。
|
||||
*
|
||||
* `order_items` 于 2026-10-10 并入:网关对它是**裸 DELETE**(绕过履约清理),
|
||||
* 而开发者口径要求"主系统分配过来的商品不能删",删明细只能走订单明细保存链路。
|
||||
*/
|
||||
const DENY_DELETE_TABLES = new Set(['customers']);
|
||||
const DENY_DELETE_TABLES = new Set(['customers', 'order_items']);
|
||||
|
||||
/** 仅管理员(super_admin/admin)可写 */
|
||||
const ADMIN_WRITE_TABLES = new Set(['role_permissions', 'branches', 'system_configs']);
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { pool } from '../db';
|
||||
import { verifyPasswordHash } from '../utils/password';
|
||||
import { listActiveTenantBranches } from './tenantSchemaFallback';
|
||||
import {
|
||||
listActiveTenantBranches,
|
||||
orderTenantBranches,
|
||||
resolvePreferredTenantBranch,
|
||||
} from './tenantSchemaFallback';
|
||||
import { runWithTenantDbContext } from './tenantDbContext';
|
||||
import {
|
||||
consumeLoginBranchTicket,
|
||||
@@ -13,6 +17,7 @@ import {
|
||||
type LoginChannel,
|
||||
} from './loginBranchChoice';
|
||||
import { looksLikePhoneLogin, normalizeLoginPhone } from '../utils/loginPhone';
|
||||
import { declaredBindingKinds } from '../utils/accountBindingKinds';
|
||||
|
||||
export type MobileRoleType =
|
||||
| 'admin'
|
||||
@@ -49,25 +54,142 @@ const LOGIN_SUFFIXES = [
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* 阶段 5 后绑定表只在 tenant_*:登录无 ALS 时按 active schema 扫描首条命中。
|
||||
* 优先租户与候选顺序见 `tenantSchemaFallback.orderTenantBranches`(规模改造 §4)。
|
||||
*/
|
||||
async function queryOneInTenant(
|
||||
branchCode: string,
|
||||
sql: string,
|
||||
params: unknown[]
|
||||
): Promise<Record<string, unknown> | null> {
|
||||
const row = await runWithTenantDbContext(branchCode, async () => {
|
||||
const result = await pool.query(sql, params);
|
||||
return result.rowCount ? (result.rows[0] as Record<string, unknown>) : null;
|
||||
});
|
||||
return row;
|
||||
}
|
||||
|
||||
const PURCHASER_BINDING_SQL = `SELECT pu.purchaser_code, pu.purchaser_name FROM purchaser_users pu WHERE pu.user_id = $1 LIMIT 1`;
|
||||
const SUPPLIER_BINDING_SQL = `SELECT su.supplier_code, s.company_name
|
||||
FROM supplier_users su
|
||||
JOIN suppliers s ON s.supplier_code = su.supplier_code
|
||||
WHERE su.user_id = $1 LIMIT 1`;
|
||||
const DELIVERY_BINDING_SQL = `SELECT dpu.person_code, dp.person_name
|
||||
FROM delivery_person_users dpu
|
||||
JOIN delivery_persons dp ON dp.person_code = dpu.person_code
|
||||
WHERE dpu.user_id = $1 LIMIT 1`;
|
||||
|
||||
type LoginBindingRows = {
|
||||
purchaser: Record<string, unknown> | null;
|
||||
supplier: Record<string, unknown> | null;
|
||||
delivery: Record<string, unknown> | null;
|
||||
};
|
||||
|
||||
/** 在一个租户内把三类绑定一次查完(1 次上下文切换,而不是 3 次)。 */
|
||||
async function loadBindingRowsInTenant(userId: string, branchCode: string): Promise<LoginBindingRows> {
|
||||
return runWithTenantDbContext(branchCode, async () => {
|
||||
const [purchaser, supplier, delivery] = await Promise.all([
|
||||
pool.query(PURCHASER_BINDING_SQL, [userId]),
|
||||
pool.query(SUPPLIER_BINDING_SQL, [userId]),
|
||||
pool.query(DELIVERY_BINDING_SQL, [userId]),
|
||||
]);
|
||||
return {
|
||||
purchaser: purchaser.rowCount ? (purchaser.rows[0] as Record<string, unknown>) : null,
|
||||
supplier: supplier.rowCount ? (supplier.rows[0] as Record<string, unknown>) : null,
|
||||
delivery: delivery.rowCount ? (delivery.rows[0] as Record<string, unknown>) : null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async function loadAccountEmail(userId: string): Promise<string> {
|
||||
const result = await pool.query(`SELECT email FROM auth.users WHERE id = $1`, [userId]);
|
||||
return String(result.rows[0]?.email || '');
|
||||
}
|
||||
|
||||
/**
|
||||
* 登录期绑定解析(规模改造 §4):先只查「优先租户」。
|
||||
*
|
||||
* 短路条件(关键):优先租户里必须已经拿到这个账号**声明身份**对应的那一类绑定
|
||||
* (邮箱后缀 = 建号角色;无后缀账号只要命中任意一类即可)。
|
||||
* 只有满足它才不做跨租户回退 —— 否则一个纯采购员账号在 supplier/delivery 两类上必然落空,
|
||||
* 逐类回退会让一次登录又变成 2×N 次查询(实测 104 租户下 210 ms 的重复扫描)。
|
||||
*
|
||||
* 「声明身份不在自己分公司、却在别家」的账号(`profiles.branch_code` 与主绑定不一致,
|
||||
* 例如员工调岗后旧绑定残留)**不会**短路,仍按原顺序回退全扫描,结果与改造前一致。
|
||||
*
|
||||
* ⚠️ 短路路径与改造前**不是**逐字节等价(唯一一处,已记录在设计文档 §4.2 与验收 A10):
|
||||
* 账号在自己分公司命中声明类别后,不再合并「别家分公司的另一类绑定」,于是
|
||||
* ① `account_bindings` 会少一条跨分公司兼职条目;
|
||||
* ② 若该条目恰好是 `resolveWebHomePath` 更靠前的分支(如 delivery 账号在别家还有 purchaser 绑定),
|
||||
* 落地路径可能与改造前不同(改造前会落到 /purchaser/dashboard)。
|
||||
* 现有真实数据(13 个账号 A/B 逐字节相同)不含这类账号;存量排查见设计文档 §9 A0。
|
||||
*/
|
||||
async function loadBindingsForLogin(
|
||||
userId: string,
|
||||
preferredBranchCode?: string | null,
|
||||
email?: string | null
|
||||
): Promise<LoginBindingRows> {
|
||||
const tenants = await listActiveTenantBranches();
|
||||
const order = orderTenantBranches(tenants, preferredBranchCode);
|
||||
const preferred = resolvePreferredTenantBranch(preferredBranchCode);
|
||||
const hasPreferred = Boolean(preferred) && order[0] === preferred;
|
||||
const declared = declaredBindingKinds(email ?? (await loadAccountEmail(userId)));
|
||||
const declaredSatisfied = (rows: LoginBindingRows) =>
|
||||
declared.length > 0
|
||||
? declared.every((kind) => Boolean(rows[kind]))
|
||||
: Boolean(rows.purchaser || rows.supplier || rows.delivery);
|
||||
|
||||
// 回退扫描:原顺序、原语义(每类取首个命中)。优先租户已经查过,其结果要**并入**结果集,
|
||||
// 不能丢 —— 否则「声明类别在别家、自己分公司只有另一类绑定」的账号会少一条绑定(改造前有)。
|
||||
const found: LoginBindingRows = { purchaser: null, supplier: null, delivery: null };
|
||||
if (hasPreferred && preferred) {
|
||||
const inPreferred = await loadBindingRowsInTenant(userId, preferred);
|
||||
if (declaredSatisfied(inPreferred)) return inPreferred;
|
||||
// 只在"有声明身份"的账号上告警:移动端账号(采购员/供应商/配送员)在自己分公司查不到绑定,
|
||||
// 多半是调岗残留或绑定错配,值得记;而**后台 staff 账号本来就没有租户绑定**,
|
||||
// 每次登录都会走到这里,属正常路径,不该刷告警(2026-10-08 实测:主系统供应商管理员登录必刷)。
|
||||
if (declared.length > 0) {
|
||||
console.warn(
|
||||
`[account-bindings] 账号在 profiles.branch_code=${preferred} 内未命中声明绑定(${declared.join('/')}),回退全租户扫描(老账号 / 调岗后绑定残留)`
|
||||
);
|
||||
}
|
||||
found.purchaser = inPreferred.purchaser;
|
||||
found.supplier = inPreferred.supplier;
|
||||
found.delivery = inPreferred.delivery;
|
||||
}
|
||||
|
||||
for (const branchCodeToTry of order) {
|
||||
if (hasPreferred && branchCodeToTry === preferred) continue;
|
||||
const rows = await loadBindingRowsInTenant(userId, branchCodeToTry);
|
||||
found.purchaser = found.purchaser ?? rows.purchaser;
|
||||
found.supplier = found.supplier ?? rows.supplier;
|
||||
found.delivery = found.delivery ?? rows.delivery;
|
||||
if (found.purchaser && found.supplier && found.delivery) break;
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/**
|
||||
* 阶段 5 后绑定表只在 tenant_*:先查已知租户,未命中再按 active schema 扫描(原行为)。
|
||||
*/
|
||||
export async function queryOneAcrossActiveTenants(
|
||||
sql: string,
|
||||
params: unknown[] = []
|
||||
params: unknown[] = [],
|
||||
preferredBranchCode?: string | null
|
||||
): Promise<Record<string, unknown> | null> {
|
||||
const tenants = await listActiveTenantBranches();
|
||||
for (const t of tenants) {
|
||||
const row = await runWithTenantDbContext(t.branch_code, async () => {
|
||||
const result = await pool.query(sql, params);
|
||||
return result.rowCount ? (result.rows[0] as Record<string, unknown>) : null;
|
||||
});
|
||||
for (const branchCode of orderTenantBranches(tenants, preferredBranchCode)) {
|
||||
const row = await queryOneInTenant(branchCode, sql, params);
|
||||
if (row) return row;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function existsAcrossActiveTenants(sql: string, params: unknown[] = []): Promise<boolean> {
|
||||
const row = await queryOneAcrossActiveTenants(sql, params);
|
||||
export async function existsAcrossActiveTenants(
|
||||
sql: string,
|
||||
params: unknown[] = [],
|
||||
preferredBranchCode?: string | null
|
||||
): Promise<boolean> {
|
||||
const row = await queryOneAcrossActiveTenants(sql, params, preferredBranchCode);
|
||||
return row != null;
|
||||
}
|
||||
|
||||
@@ -297,7 +419,11 @@ export async function resolveChosenLoginUser(
|
||||
return { user, roleType: rec.roleType };
|
||||
}
|
||||
|
||||
export async function getAccountBindings(userId: string): Promise<AccountBinding[]> {
|
||||
export async function getAccountBindings(
|
||||
userId: string,
|
||||
branchCode?: string | null,
|
||||
email?: string | null
|
||||
): Promise<AccountBinding[]> {
|
||||
const bindings: AccountBinding[] = [];
|
||||
|
||||
const roles = await pool.query(
|
||||
@@ -325,10 +451,14 @@ export async function getAccountBindings(userId: string): Promise<AccountBinding
|
||||
}
|
||||
}
|
||||
|
||||
const purchaser = await queryOneAcrossActiveTenants(
|
||||
`SELECT pu.purchaser_code, pu.purchaser_name FROM purchaser_users pu WHERE pu.user_id = $1 LIMIT 1`,
|
||||
[userId]
|
||||
);
|
||||
// 规模改造 §4:三类绑定一次性在「优先租户」里查(1 次上下文切换、3 条查询)。
|
||||
// 命中任意一类即认为该账号属于这个分公司,不再为另外两类做全租户回退扫描
|
||||
// —— 否则一个纯采购员账号登录时,supplier/delivery 两类必然落空,会各触发一次 O(N) 全扫描。
|
||||
// 优先租户里**一个都没命中**(老账号 / profiles.branch_code 与绑定不一致)时,
|
||||
// 仍按原来的「按 branch_code 顺序扫首条命中」回退,结果与改造前一致。
|
||||
const bindingRows = await loadBindingsForLogin(userId, branchCode, email);
|
||||
|
||||
const purchaser = bindingRows.purchaser;
|
||||
if (purchaser) {
|
||||
bindings.push({
|
||||
kind: 'purchaser',
|
||||
@@ -338,13 +468,7 @@ export async function getAccountBindings(userId: string): Promise<AccountBinding
|
||||
});
|
||||
}
|
||||
|
||||
const supplier = await queryOneAcrossActiveTenants(
|
||||
`SELECT su.supplier_code, s.company_name
|
||||
FROM supplier_users su
|
||||
JOIN suppliers s ON s.supplier_code = su.supplier_code
|
||||
WHERE su.user_id = $1 LIMIT 1`,
|
||||
[userId]
|
||||
);
|
||||
const supplier = bindingRows.supplier;
|
||||
if (supplier) {
|
||||
bindings.push({
|
||||
kind: 'supplier',
|
||||
@@ -354,13 +478,7 @@ export async function getAccountBindings(userId: string): Promise<AccountBinding
|
||||
});
|
||||
}
|
||||
|
||||
const delivery = await queryOneAcrossActiveTenants(
|
||||
`SELECT dpu.person_code, dp.person_name
|
||||
FROM delivery_person_users dpu
|
||||
JOIN delivery_persons dp ON dp.person_code = dpu.person_code
|
||||
WHERE dpu.user_id = $1 LIMIT 1`,
|
||||
[userId]
|
||||
);
|
||||
const delivery = bindingRows.delivery;
|
||||
if (delivery) {
|
||||
bindings.push({
|
||||
kind: 'delivery',
|
||||
@@ -402,8 +520,12 @@ export async function getAccountBindings(userId: string): Promise<AccountBinding
|
||||
return bindings;
|
||||
}
|
||||
|
||||
export async function resolveWebHomePath(userId: string): Promise<string> {
|
||||
const bindings = await getAccountBindings(userId);
|
||||
export async function resolveWebHomePath(
|
||||
userId: string,
|
||||
branchCode?: string | null,
|
||||
email?: string | null
|
||||
): Promise<string> {
|
||||
const bindings = await getAccountBindings(userId, branchCode, email);
|
||||
const kinds = new Set(bindings.map((b) => b.kind));
|
||||
|
||||
const roles = await pool.query(`SELECT role::text AS role FROM public.user_roles WHERE user_id = $1`, [userId]);
|
||||
@@ -456,21 +578,27 @@ export async function resolveWebHomePath(userId: string): Promise<string> {
|
||||
return '/no-access';
|
||||
}
|
||||
|
||||
export async function resolveMobileRoleType(userId: string, email: string): Promise<MobileRoleType | null> {
|
||||
export async function resolveMobileRoleType(
|
||||
userId: string,
|
||||
email: string,
|
||||
branchCode?: string | null
|
||||
): Promise<MobileRoleType | null> {
|
||||
if (email.endsWith('@purchaser.meoo.local')) {
|
||||
return (await existsAcrossActiveTenants(`SELECT 1 FROM purchaser_users WHERE user_id = $1 LIMIT 1`, [userId]))
|
||||
return (await existsAcrossActiveTenants(`SELECT 1 FROM purchaser_users WHERE user_id = $1 LIMIT 1`, [userId], branchCode))
|
||||
? 'purchaser'
|
||||
: null;
|
||||
}
|
||||
if (email.endsWith('@supplier.meoo.local')) {
|
||||
return (await existsAcrossActiveTenants(`SELECT 1 FROM supplier_users WHERE user_id = $1 LIMIT 1`, [userId]))
|
||||
return (await existsAcrossActiveTenants(`SELECT 1 FROM supplier_users WHERE user_id = $1 LIMIT 1`, [userId], branchCode))
|
||||
? 'supplier'
|
||||
: null;
|
||||
}
|
||||
if (email.endsWith('@delivery.meoo.local')) {
|
||||
return (await existsAcrossActiveTenants(`SELECT 1 FROM delivery_person_users WHERE user_id = $1 LIMIT 1`, [
|
||||
userId,
|
||||
]))
|
||||
return (await existsAcrossActiveTenants(
|
||||
`SELECT 1 FROM delivery_person_users WHERE user_id = $1 LIMIT 1`,
|
||||
[userId],
|
||||
branchCode
|
||||
))
|
||||
? 'delivery'
|
||||
: null;
|
||||
}
|
||||
@@ -498,12 +626,12 @@ export async function resolveMobileRoleType(userId: string, email: string): Prom
|
||||
}
|
||||
|
||||
if (roleSet.has('purchaser')) {
|
||||
if (await existsAcrossActiveTenants(`SELECT 1 FROM purchaser_users WHERE user_id = $1 LIMIT 1`, [userId])) {
|
||||
if (await existsAcrossActiveTenants(`SELECT 1 FROM purchaser_users WHERE user_id = $1 LIMIT 1`, [userId], branchCode)) {
|
||||
return 'purchaser';
|
||||
}
|
||||
}
|
||||
if (roleSet.has('delivery')) {
|
||||
if (await existsAcrossActiveTenants(`SELECT 1 FROM delivery_person_users WHERE user_id = $1 LIMIT 1`, [userId])) {
|
||||
if (await existsAcrossActiveTenants(`SELECT 1 FROM delivery_person_users WHERE user_id = $1 LIMIT 1`, [userId], branchCode)) {
|
||||
return 'delivery';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { PoolClient } from 'pg';
|
||||
import { pool } from '../db';
|
||||
import { getEffectiveBranchCode, type TenantContext } from './tenantScope';
|
||||
import { notifyDeliveryTaskCreated } from './mainlineEventNotificationService';
|
||||
import { fullySkipInboundOrderExistsSql } from './mainSystemPrepLedger';
|
||||
|
||||
export interface CustomerDeliveryBindingView {
|
||||
id: string;
|
||||
@@ -184,6 +185,13 @@ async function syncCustomerPendingTasks(
|
||||
[customerCode, primary.person_code, deliveryId]
|
||||
);
|
||||
|
||||
/**
|
||||
* ⚠️ 2026-10-11:这里是**唯一绕过 `ensureDeliveryTaskForOrder` 的任务创建点**(客户绑定配送员
|
||||
* → 回填该客户所有在途单的任务与配送员)。它原先没有免入库排除,会把主系统「免入库」单
|
||||
* 也补建任务并把**我方配送员**派上去 —— 而那种单是**主系统骑手上门取货**,我方不派车。
|
||||
* 排除口径与 `isOrderFullySkipInbound` 同一份 SQL(`fullySkipInboundOrderExistsSql`),
|
||||
* 混合单(部分行免入库)**不排除**:送仓部分仍要我方发车。
|
||||
*/
|
||||
const insertResult = await client.query(
|
||||
`INSERT INTO delivery_tasks (task_code, order_code, task_status, created_at, branch_code, person_code, delivery_id)
|
||||
SELECT
|
||||
@@ -199,6 +207,7 @@ async function syncCustomerPendingTasks(
|
||||
AND COALESCE(o.order_status, 0) >= 50
|
||||
AND o.deleted_at IS NULL
|
||||
AND NOT EXISTS (SELECT 1 FROM delivery_tasks dt WHERE dt.order_code = o.order_code)
|
||||
AND NOT EXISTS (${fullySkipInboundOrderExistsSql('o.order_code', 'COALESCE(o.branch_code, $4)')})
|
||||
ON CONFLICT (order_code) WHERE (order_code IS NOT NULL AND TRIM(order_code) <> '') DO NOTHING
|
||||
RETURNING task_code, order_code, branch_code`,
|
||||
[customerCode, primary.person_code, deliveryId, branchCode]
|
||||
|
||||
@@ -68,6 +68,12 @@ export interface SubmitMobileCustomerOrderInput {
|
||||
entryChannel?: OrderEntryChannel | string | null;
|
||||
/** 解析会话ID,用于关联导入解析结果 */
|
||||
parseSessionId?: string | null;
|
||||
/**
|
||||
* 放行零价明细(提交 + 分配两处闸门)。
|
||||
* 仅「主系统分配任务导入建单」传 true:主系统给的就是成本价,那边未定价时为 0。
|
||||
* 人工录单不要传,保持"售价为 0 禁止提交"的既有约束。
|
||||
*/
|
||||
allowUnpriced?: boolean;
|
||||
}
|
||||
|
||||
export interface SubmitMobileCustomerOrderResult {
|
||||
@@ -275,7 +281,8 @@ async function prepareCustomerOrderSubmit(
|
||||
const credit = await assertCustomerCredit(input.customerCode, estimatedAmount);
|
||||
|
||||
const { isBlockZeroSaleOnSubmitEnabled } = await import('./blockZeroSaleConfigService');
|
||||
const blockZeroSale = await isBlockZeroSaleOnSubmitEnabled(input.branchCode);
|
||||
const blockZeroSale =
|
||||
input.allowUnpriced === true ? false : await isBlockZeroSaleOnSubmitEnabled(input.branchCode);
|
||||
if (blockZeroSale) {
|
||||
const zeroPricePreview = pricedItems.filter(
|
||||
(item: any) => (Number(item.price) || 0) <= 0 || item.needs_customer_price === true
|
||||
@@ -540,7 +547,7 @@ export async function submitMobileCustomerOrder(
|
||||
input.customerCode,
|
||||
input.branchCode,
|
||||
client,
|
||||
{ bidCreatedBy: input.userId }
|
||||
{ bidCreatedBy: input.userId, allowUnpriced: input.allowUnpriced === true }
|
||||
);
|
||||
if (allocation.errors.length && !allocation.deferredForBid) {
|
||||
throw Object.assign(new Error(allocation.errors.join(';')), {
|
||||
|
||||
@@ -0,0 +1,613 @@
|
||||
import { getMainSystemToken } from '../token';
|
||||
import { requestMainSystem } from '../http';
|
||||
import { mainSystemLookupPath, mainSystemPath } from '../endpoints';
|
||||
import {
|
||||
MAIN_SYSTEM_FETCH_TIMEOUT_MS,
|
||||
isMainSystemIntegrationEnabled,
|
||||
} from '../config';
|
||||
|
||||
/**
|
||||
* 主系统**备货接口**封装(读列表 / lookup / 回写状态)。
|
||||
*
|
||||
* 这一层是"接口封装"层:只有类型、字段映射与结果枚举,不含 URL 拼接、token 缓存、HTTP 细节
|
||||
* (那些在 `../endpoints.ts` / `../token.ts` / `../http.ts`)。
|
||||
*
|
||||
* 说明:`server/src/services/mainSystemPreparations.ts` 现在是本文件的**兼容门面**
|
||||
* (对外签名一字不变,5 个业务模块与 5 个测试都 import 那个路径),见其文件头注释。
|
||||
*
|
||||
* 对应关系(见 .cursor/rules/01-second-dev-supplier.mdc「两层供应商语义」):
|
||||
* 主系统的**供应商** = 本系统的**分公司**;本系统的 supplier_code 与分公司编码是同一个值。
|
||||
*/
|
||||
|
||||
/** 主系统单页上限(其 SQL 亦为 LIMIT 500);分页参数由 2026-10-09 主系统增量改造提供 */
|
||||
const PREP_PAGE_LIMIT = 500;
|
||||
/** 安全上限:最多翻 40 页(2 万行),超过即视为异常截断(不静默丢行) */
|
||||
const PREP_MAX_PAGES = 40;
|
||||
|
||||
export type MainPreparationRow = {
|
||||
/** 主系统备货行 UUID —— 落单/回写时的幂等键 */
|
||||
id: string;
|
||||
orderCode: string;
|
||||
skuCode: string | null;
|
||||
itemName: string;
|
||||
displayName: string | null;
|
||||
prepareQty: number | null;
|
||||
unit: string | null;
|
||||
orderQty: number | null;
|
||||
orderUnit: string | null;
|
||||
purchasePrice: number | null;
|
||||
suggestedPrice: number | null;
|
||||
prepareStatus: number | null;
|
||||
deliveryDate: string | null;
|
||||
taskDay: string | null;
|
||||
isStockout: boolean;
|
||||
processingMethod: string | null;
|
||||
returnCode: string | null;
|
||||
returnReason: string | null;
|
||||
requiresQualityReport: boolean;
|
||||
orderItemRemark: string | null;
|
||||
/**
|
||||
* 主系统**下单分公司**编码(= 主系统那边买东西的那家分公司,如 BR002「自贡」)。
|
||||
* 用途:子系统要按"下单的那家公司"建客户、并取它分公司的仓库地址。
|
||||
*/
|
||||
branchCode: string | null;
|
||||
/**
|
||||
* 主系统**下单分公司**名称(P1-10,如「自贡」)。
|
||||
* 用途:给该分公司的客户命名(客户名 = 分公司名 + 编号,避免重名)。
|
||||
*/
|
||||
branchName: string | null;
|
||||
/**
|
||||
* 主系统**下单分公司的仓库地址**(P1-10)。
|
||||
* 用途:自动带进我方订单的收货地址 —— 主系统下的单是送到它自己分公司的仓库。
|
||||
*/
|
||||
branchAddress: string | null;
|
||||
/** 主系统 2026-10-09 增量:该供应商是否免入库(**供应商级**事实) */
|
||||
skipInbound: boolean;
|
||||
/** 主系统 2026-10-09 增量:该行是否商品直送(**行级**事实);与 skipInbound 分别独立,禁止合并判定 */
|
||||
isDirectDelivery: boolean;
|
||||
// ── 主系统 2026-10-10 R3 履约事实(只读派生值,**不参与任何我方判定门槛**)──────────
|
||||
// ⚠️ 取不到一律 `null`(**不得用 prepareQty 冒充**):null 表示"尚未产生实收量",
|
||||
// 与 0 语义不同,调用方必须区分。
|
||||
/** 实际收货量:免入库=核货实配量;送仓=验收入库实收量 */
|
||||
actualQty: number | null;
|
||||
/** actualQty 的产生时刻(ISO 8601) */
|
||||
actualQtyAt: string | null;
|
||||
/** actualQty − prepareQty(主系统算好下发;避免两边各自四舍五入) */
|
||||
qtyDiff: number | null;
|
||||
/** 该行是否已有成功入库覆盖(主系统复用其 ORDER_ITEM_INBOUND_COVERED_SQL) */
|
||||
isInbounded: boolean;
|
||||
/** 首次成功入库时刻(ISO 8601)。⚠️ isInbounded=true 而本字段为 null 属**正常组合** */
|
||||
inboundAt: string | null;
|
||||
/** 订单级:主系统该订单实际发车时刻(delivery_tasks.start_time);未发车为 null */
|
||||
orderDepartedAt: string | null;
|
||||
};
|
||||
|
||||
export type MainOrderGroup = {
|
||||
orderCode: string;
|
||||
deliveryDate: string | null;
|
||||
taskDay: string | null;
|
||||
rows: MainPreparationRow[];
|
||||
};
|
||||
|
||||
export type MainPreparationsOutcome =
|
||||
| {
|
||||
kind: 'ok';
|
||||
supplierCode: string;
|
||||
branchCode: string | null;
|
||||
orders: MainOrderGroup[];
|
||||
rowCount: number;
|
||||
/** 主系统列表有 LIMIT 500:命中上限说明**返回不完整**,调用方不得据此判定"某行不存在" */
|
||||
truncated?: boolean;
|
||||
}
|
||||
| { kind: 'not_configured'; reason: string }
|
||||
| { kind: 'rejected'; reason: string }
|
||||
| { kind: 'unavailable'; reason: string };
|
||||
|
||||
/** 主系统备货列表的硬上限(其 SQL 为 LIMIT 500) */
|
||||
export const MAIN_SYSTEM_VIEW_LIMIT = 500;
|
||||
|
||||
export function isMainSystemPreparationsEnabled(): boolean {
|
||||
return isMainSystemIntegrationEnabled();
|
||||
}
|
||||
|
||||
/* ── 字段映射 ─────────────────────────────────────────────────────────────── */
|
||||
|
||||
function toNumber(value: unknown): number | null {
|
||||
if (value === null || value === undefined || value === '') return null;
|
||||
const n = Number(value);
|
||||
return Number.isFinite(n) ? n : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 时间字段出参归一:主系统已统一发 ISO 8601,但历史/异常值可能是其它形态。
|
||||
* 能解析成合法日期就转 ISO,否则原样返回字符串(不吞掉信息,便于排查)。
|
||||
*/
|
||||
export function isoOrNull(value: unknown): string | null {
|
||||
if (value === null || value === undefined || value === '') return null;
|
||||
const date = value instanceof Date ? value : new Date(String(value));
|
||||
if (Number.isNaN(date.getTime())) return String(value);
|
||||
return date.toISOString();
|
||||
}
|
||||
|
||||
/** 备货行原始载荷 → 我方行模型(拉取 / lookup / webhook **同口径**) */
|
||||
export function mapMainPreparationRow(raw: any): MainPreparationRow {
|
||||
return {
|
||||
id: String(raw?.id || ''),
|
||||
orderCode: String(raw?.order_code || ''),
|
||||
branchCode: raw?.branch_code != null ? String(raw.branch_code) : null,
|
||||
// P1-10:主系统 2026-10-10 起三个视图 + lookup + webhook 都带这两个字段
|
||||
branchName: raw?.branch_name != null && String(raw.branch_name).trim() ? String(raw.branch_name).trim() : null,
|
||||
branchAddress:
|
||||
raw?.branch_address != null && String(raw.branch_address).trim()
|
||||
? String(raw.branch_address).trim()
|
||||
: null,
|
||||
skuCode: raw?.sku_code ? String(raw.sku_code) : null,
|
||||
itemName: String(raw?.item_name || raw?.display_name || ''),
|
||||
displayName: raw?.display_name ? String(raw.display_name) : null,
|
||||
prepareQty: toNumber(raw?.prepare_qty),
|
||||
unit: raw?.unit ? String(raw.unit) : null,
|
||||
orderQty: toNumber(raw?.order_qty),
|
||||
orderUnit: raw?.order_unit ? String(raw.order_unit) : null,
|
||||
purchasePrice: toNumber(raw?.purchase_price),
|
||||
suggestedPrice: toNumber(raw?.suggested_price),
|
||||
prepareStatus: toNumber(raw?.prepare_status),
|
||||
deliveryDate: raw?.delivery_date ? String(raw.delivery_date).slice(0, 10) : null,
|
||||
taskDay: raw?.task_day ? String(raw.task_day).slice(0, 10) : null,
|
||||
isStockout: raw?.is_stockout === true,
|
||||
processingMethod: raw?.processing_method ? String(raw.processing_method) : null,
|
||||
returnCode: raw?.return_code ? String(raw.return_code) : null,
|
||||
returnReason: raw?.return_reason ? String(raw.return_reason) : null,
|
||||
requiresQualityReport: raw?.requires_quality_report === true,
|
||||
orderItemRemark: raw?.order_item_remark ? String(raw.order_item_remark) : null,
|
||||
// 主系统 2026-10-09 增量:两个事实**分别独立**映射,禁止合并判定(供应商管理冻结)
|
||||
skipInbound: raw?.skip_inbound === true,
|
||||
isDirectDelivery: raw?.is_direct_delivery === true,
|
||||
// 主系统 2026-10-10 R3:履约事实(只读)。null 一律保留为 null,**不用 prepare_qty 兜底**
|
||||
actualQty: toNumber(raw?.actual_qty),
|
||||
actualQtyAt: isoOrNull(raw?.actual_qty_at),
|
||||
qtyDiff: toNumber(raw?.qty_diff),
|
||||
isInbounded: raw?.is_inbounded === true,
|
||||
inboundAt: isoOrNull(raw?.inbound_at),
|
||||
orderDepartedAt: isoOrNull(raw?.order_departed_at),
|
||||
};
|
||||
}
|
||||
|
||||
/* ── 列表(分页翻全) ─────────────────────────────────────────────────────── */
|
||||
|
||||
type PrepPage = {
|
||||
rows: MainPreparationRow[];
|
||||
total: number | null;
|
||||
hasMore: boolean;
|
||||
/** 主系统未返回 has_more 时(老版本)用"本页是否满页"兜底判断 */
|
||||
limit: number;
|
||||
};
|
||||
|
||||
/** 抓主系统备货列表的**一页**(`limit`/`offset` 由 2026-10-09 增量改造提供,老版本忽略该参数)。 */
|
||||
async function fetchPreparationsPage(
|
||||
token: string,
|
||||
query: string,
|
||||
offset: number
|
||||
): Promise<{ kind: 'ok'; page: PrepPage } | { kind: 'rejected' | 'unavailable'; reason: string }> {
|
||||
const result = await requestMainSystem<any>({
|
||||
endpoint: 'preparations',
|
||||
token,
|
||||
timeoutMs: MAIN_SYSTEM_FETCH_TIMEOUT_MS,
|
||||
timeoutReason: '拉取备货超时',
|
||||
networkReasonPrefix: '拉取备货失败:',
|
||||
query: { ...parsePrepQuery(query), limit: PREP_PAGE_LIMIT, offset },
|
||||
});
|
||||
if (result.kind === 'not_configured') return { kind: 'unavailable', reason: result.reason };
|
||||
if (result.kind !== 'ok') return { kind: result.kind, reason: result.reason };
|
||||
const payload = result.data as any;
|
||||
const rows = (Array.isArray(payload?.data) ? payload.data : [])
|
||||
.map((raw: unknown) => mapMainPreparationRow(raw))
|
||||
.filter((r: MainPreparationRow) => r.id);
|
||||
const totalRaw = payload?.total;
|
||||
const total = totalRaw === undefined || totalRaw === null ? null : Number(totalRaw);
|
||||
const limit = Number(payload?.limit) > 0 ? Number(payload.limit) : PREP_PAGE_LIMIT;
|
||||
const hasMore =
|
||||
typeof payload?.has_more === 'boolean'
|
||||
? payload.has_more
|
||||
: Number.isFinite(Number(total))
|
||||
? offset + rows.length < Number(total)
|
||||
: rows.length >= limit; // 老版本没有 has_more:满页就继续翻
|
||||
return {
|
||||
kind: 'ok',
|
||||
page: { rows, total: Number.isFinite(Number(total)) ? Number(total) : null, hasMore, limit },
|
||||
};
|
||||
}
|
||||
|
||||
/** `view=active&date_from=…` 这类查询串 → 结构化 query(保持既有调用点的写法不变) */
|
||||
export function parsePrepQuery(query: string): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
for (const part of String(query || '').split('&')) {
|
||||
if (!part) continue;
|
||||
const index = part.indexOf('=');
|
||||
const key = index === -1 ? part : part.slice(0, index);
|
||||
const value = index === -1 ? '' : part.slice(index + 1);
|
||||
if (!key) continue;
|
||||
out[decodeURIComponent(key)] = decodeURIComponent(value);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉全量(**逐页翻完**,2026-10-09 起主系统支持 `limit`/`offset`/`has_more`)。
|
||||
*
|
||||
* 为什么必须翻完而不是"取一页就算":本系统靠"该行没出现在列表里"来判定主系统退货,
|
||||
* 一旦返回被 500 条截断,未返回的行会被误判成退货 → 误红冲(此前只能靠"命中上限就整轮不判定"退让)。
|
||||
*/
|
||||
async function fetchAllPrepPages(
|
||||
token: string,
|
||||
query: string,
|
||||
view: string
|
||||
): Promise<
|
||||
| { kind: 'ok'; rows: MainPreparationRow[]; total: number | null; truncated: boolean }
|
||||
| { kind: 'rejected' | 'unavailable'; reason: string }
|
||||
> {
|
||||
const all: MainPreparationRow[] = [];
|
||||
let offset = 0;
|
||||
let total: number | null = null;
|
||||
for (let page = 0; page < PREP_MAX_PAGES; page += 1) {
|
||||
const result = await fetchPreparationsPage(token, query, offset);
|
||||
if (result.kind !== 'ok') return result;
|
||||
all.push(...result.page.rows);
|
||||
total = result.page.total;
|
||||
offset += result.page.rows.length;
|
||||
if (!result.page.hasMore) return { kind: 'ok', rows: all, total, truncated: false };
|
||||
if (!result.page.rows.length) break; // 防御:has_more 为真但没返回行,避免死循环
|
||||
}
|
||||
console.warn(
|
||||
`[main-system] 备货列表翻页达到安全上限(${PREP_MAX_PAGES} 页 / ${all.length} 行),本轮按"截断"处理`
|
||||
);
|
||||
return { kind: 'ok', rows: all, total, truncated: true };
|
||||
}
|
||||
|
||||
function groupPrepRows(rows: MainPreparationRow[]): MainOrderGroup[] {
|
||||
const grouped = new Map<string, MainOrderGroup>();
|
||||
for (const row of rows) {
|
||||
const key = row.orderCode || '(无订单号)';
|
||||
if (!grouped.has(key)) {
|
||||
grouped.set(key, { orderCode: key, deliveryDate: row.deliveryDate, taskDay: row.taskDay, rows: [] });
|
||||
}
|
||||
grouped.get(key)!.rows.push(row);
|
||||
}
|
||||
return [...grouped.values()];
|
||||
}
|
||||
|
||||
/** 拉某分公司(= 主系统某供应商)的备货行并按订单号分组 */
|
||||
async function loadPreparations(params: {
|
||||
supplierCode: string;
|
||||
view: string;
|
||||
query: string;
|
||||
}): Promise<MainPreparationsOutcome> {
|
||||
if (!isMainSystemIntegrationEnabled()) {
|
||||
return {
|
||||
kind: 'not_configured',
|
||||
reason: '未配置 MAIN_SYSTEM_BASE_URL / MAIN_SYSTEM_INTEGRATION_CLIENT_ID / _SECRET',
|
||||
};
|
||||
}
|
||||
const tokenResult = await getMainSystemToken(params.supplierCode);
|
||||
if (tokenResult.kind !== 'ok') {
|
||||
return { kind: tokenResult.kind === 'not_configured' ? 'not_configured' : 'unavailable', reason: tokenResult.reason };
|
||||
}
|
||||
const result = await fetchAllPrepPages(tokenResult.token, params.query, params.view);
|
||||
if (result.kind !== 'ok') return result;
|
||||
return {
|
||||
kind: 'ok',
|
||||
supplierCode: params.supplierCode,
|
||||
branchCode: tokenResult.branchCode,
|
||||
orders: groupPrepRows(result.rows),
|
||||
rowCount: result.rows.length,
|
||||
truncated: result.truncated,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取某分公司(= 主系统某供应商)的待办备货,并按订单号分组。
|
||||
* @param supplierCode 主系统 supplier_code,本系统里就是分公司编码
|
||||
* @param view active(待办,默认)| archived | price_amend ...
|
||||
*/
|
||||
export async function fetchMainSystemPreparations(
|
||||
supplierCode: string,
|
||||
view = 'active'
|
||||
): Promise<MainPreparationsOutcome> {
|
||||
return loadPreparations({ supplierCode, view, query: `view=${encodeURIComponent(view)}` });
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉「已完成归档」备货行(`view=archived`,按配送日单日)。
|
||||
*
|
||||
* 用途(2026-10-08 退货跟随):本系统靠「备货行从 active 消失」判定主系统退货,
|
||||
* 但**正常完成**的行也会从 active 消失(转入 archived)。所以判定退货前必须先反查归档:
|
||||
* 消失 + archived 有 → 正常完成
|
||||
* 消失 + archived 无 → 退货(红冲)
|
||||
* 见 docs/design/20261008-第三方订单退货跟随与发车回写方案.md §3.2。
|
||||
*/
|
||||
export async function fetchMainSystemArchivedPreparations(
|
||||
supplierCode: string,
|
||||
range: { date?: string; dateFrom?: string; dateTo?: string }
|
||||
): Promise<MainPreparationsOutcome> {
|
||||
// ⚠️ 归档视图按 `COALESCE(prepare_time, created_at)::date`(= 归档日)过滤,**不是** delivery_date。
|
||||
// 2026-10-09 起退货判定主用 `POST /preparations/lookup`(更权威),本函数作为**备用**保留:
|
||||
// 仅当台账缺少 sku_code、无法用 lookup 时才回退到"区间反查归档"。
|
||||
const query =
|
||||
range.dateFrom && range.dateTo
|
||||
? `view=archived&date_from=${encodeURIComponent(range.dateFrom)}&date_to=${encodeURIComponent(range.dateTo)}`
|
||||
: `view=archived&date=${encodeURIComponent(String(range.date || ''))}`;
|
||||
return loadPreparations({ supplierCode, view: 'archived', query });
|
||||
}
|
||||
|
||||
/* ── lookup(逐行问状态) ─────────────────────────────────────────────────── */
|
||||
|
||||
export type PrepLookupResult = {
|
||||
orderCode: string;
|
||||
skuCode: string;
|
||||
id: string | null;
|
||||
found: boolean;
|
||||
prepareStatus: number | null;
|
||||
prepareTime: string | null;
|
||||
prepareQty: number | null;
|
||||
purchasePrice: number | null;
|
||||
unit: string | null;
|
||||
orderStatus: number | null;
|
||||
orderDeleted: boolean;
|
||||
orderItemPresent: boolean;
|
||||
isReturned: boolean;
|
||||
returnCode: string | null;
|
||||
currentSupplierCode: string | null;
|
||||
reassigned: boolean;
|
||||
// ── 主系统 2026-10-10 R3 履约事实(与 GET /preparations、webhook 载荷三处同口径)──
|
||||
actualQty: number | null;
|
||||
actualQtyAt: string | null;
|
||||
qtyDiff: number | null;
|
||||
isInbounded: boolean;
|
||||
inboundAt: string | null;
|
||||
orderDepartedAt: string | null;
|
||||
};
|
||||
|
||||
export type PrepLookupOutcome =
|
||||
| { kind: 'ok'; results: PrepLookupResult[] }
|
||||
| { kind: 'rejected'; reason: string }
|
||||
| { kind: 'unavailable'; reason: string };
|
||||
|
||||
const LOOKUP_CHUNK = 500;
|
||||
|
||||
/**
|
||||
* 逐行问状态:`POST /preparations/lookup`(主系统 2026-10-09 增量改造新增,只读)。
|
||||
*
|
||||
* 为什么用它替代"行消失 + 反查归档":它直接回答 found / order_item_present / is_returned /
|
||||
* return_code / current_supplier_code / reassigned,可**权威区分**四种事实:
|
||||
* 在途 / 已完成 / 已退货(红冲)/ 已改供 —— 不再依赖日期区间与归档视图的语义。
|
||||
* 作用域由主系统强制为本 token 的供应商;一次最多 500 条,这里自动分片。
|
||||
*/
|
||||
export async function lookupMainSystemPreparationStates(
|
||||
supplierCode: string,
|
||||
items: Array<{ orderCode: string; skuCode: string; id?: string | null }>
|
||||
): Promise<PrepLookupOutcome> {
|
||||
if (!isMainSystemIntegrationEnabled()) {
|
||||
return { kind: 'unavailable', reason: '主系统对接未配置' };
|
||||
}
|
||||
if (!items.length) return { kind: 'ok', results: [] };
|
||||
const tokenResult = await getMainSystemToken(supplierCode);
|
||||
if (tokenResult.kind !== 'ok') return { kind: 'unavailable', reason: tokenResult.reason };
|
||||
|
||||
const results: PrepLookupResult[] = [];
|
||||
for (let i = 0; i < items.length; i += LOOKUP_CHUNK) {
|
||||
const chunk = items.slice(i, i + LOOKUP_CHUNK);
|
||||
const result = await requestMainSystem<any>({
|
||||
endpoint: 'preparations',
|
||||
path: mainSystemLookupPath(),
|
||||
method: 'POST',
|
||||
token: tokenResult.token,
|
||||
timeoutMs: MAIN_SYSTEM_FETCH_TIMEOUT_MS,
|
||||
timeoutReason: '查备货状态超时',
|
||||
networkReasonPrefix: '查备货状态失败:',
|
||||
body: {
|
||||
items: chunk.map((it) => ({
|
||||
order_code: it.orderCode,
|
||||
sku_code: it.skuCode,
|
||||
...(it.id ? { id: it.id } : {}),
|
||||
})),
|
||||
},
|
||||
});
|
||||
if (result.kind === 'not_configured') return { kind: 'unavailable', reason: result.reason };
|
||||
if (result.kind !== 'ok') return { kind: result.kind, reason: result.reason };
|
||||
const payload = result.data as any;
|
||||
for (const raw of Array.isArray(payload?.data) ? payload.data : []) {
|
||||
results.push({
|
||||
orderCode: String(raw?.order_code ?? ''),
|
||||
skuCode: String(raw?.sku_code ?? ''),
|
||||
id: raw?.id != null ? String(raw.id) : null,
|
||||
found: raw?.found === true,
|
||||
prepareStatus: raw?.prepare_status != null ? Number(raw.prepare_status) : null,
|
||||
prepareTime: raw?.prepare_time != null ? String(raw.prepare_time) : null,
|
||||
prepareQty: raw?.prepare_qty != null ? Number(raw.prepare_qty) : null,
|
||||
purchasePrice: raw?.purchase_price != null ? Number(raw.purchase_price) : null,
|
||||
unit: raw?.unit != null ? String(raw.unit) : null,
|
||||
orderStatus: raw?.order_status != null ? Number(raw.order_status) : null,
|
||||
orderDeleted: raw?.order_deleted === true,
|
||||
orderItemPresent: raw?.order_item_present === true,
|
||||
isReturned: raw?.is_returned === true,
|
||||
returnCode: raw?.return_code != null ? String(raw.return_code) : null,
|
||||
currentSupplierCode: raw?.current_supplier_code != null ? String(raw.current_supplier_code) : null,
|
||||
reassigned: raw?.reassigned === true,
|
||||
// 主系统 2026-10-10 R3:与 mapMainPreparationRow 同口径(同一常量下发,三处必须一致)
|
||||
actualQty: toNumber(raw?.actual_qty),
|
||||
actualQtyAt: isoOrNull(raw?.actual_qty_at),
|
||||
qtyDiff: toNumber(raw?.qty_diff),
|
||||
isInbounded: raw?.is_inbounded === true,
|
||||
inboundAt: isoOrNull(raw?.inbound_at),
|
||||
orderDepartedAt: isoOrNull(raw?.order_departed_at),
|
||||
});
|
||||
}
|
||||
}
|
||||
return { kind: 'ok', results };
|
||||
}
|
||||
|
||||
/* ── 回写状态 ─────────────────────────────────────────────────────────────── */
|
||||
|
||||
export type WritebackSkippedRow = { id?: string | null; skuCode?: string | null; reason: string; message?: string };
|
||||
|
||||
export type WritebackOutcome =
|
||||
| {
|
||||
kind: 'ok';
|
||||
/** 主系统 2026-10-09 增量:真实写入行数(0 = 没写进去,调用方不得记 done) */
|
||||
updated: number;
|
||||
/** 被主系统主动跳过的行及原因码 */
|
||||
skipped: WritebackSkippedRow[];
|
||||
needsCustomerPrice: boolean;
|
||||
}
|
||||
/** 主系统侧该行已是完成/已锁定 —— 我们要的结果已达成(幂等),不是失败 */
|
||||
| { kind: 'already_done'; reason: string }
|
||||
| { kind: 'rejected'; reason: string }
|
||||
| { kind: 'unavailable'; reason: string };
|
||||
|
||||
/**
|
||||
* 回写备货状态(`POST /preparations/status`)。
|
||||
*
|
||||
* 用途(2026-10-08):本系统**发车** = 主系统的**备货完成**,必须回写 `status=30`,
|
||||
* 否则主系统停在备货中(`confirm_required=true` 时不进待验入库),
|
||||
* 且主系统"已发车不能点击退货"的拦截也拿不到依据。见设计文档 §3.5。
|
||||
*
|
||||
* 只回写单行;调用方负责「失败不阻塞发车」「0 价跳过」「超量带确认位」三条规则。
|
||||
*/
|
||||
export async function writebackMainSystemPreparationStatus(params: {
|
||||
supplierCode: string;
|
||||
preparationId: string;
|
||||
status: 20 | 30 | 40;
|
||||
prepareQty?: number | null;
|
||||
purchasePrice?: number | null;
|
||||
unit?: string | null;
|
||||
confirmOverQty?: boolean;
|
||||
/**
|
||||
* 缺货原因(仅 status=40 用)。主系统 `status=40` = **供应商报缺货 ⇒ 该行转自采**
|
||||
* (`transferPreparationStockoutToPurchase`),原因随请求体 `stockout_reason` 落主系统。
|
||||
*/
|
||||
stockoutReason?: string | null;
|
||||
}): Promise<WritebackOutcome> {
|
||||
if (!isMainSystemIntegrationEnabled()) {
|
||||
return { kind: 'unavailable', reason: '主系统对接未配置' };
|
||||
}
|
||||
const tokenResult = await getMainSystemToken(params.supplierCode);
|
||||
if (tokenResult.kind !== 'ok') return { kind: 'unavailable', reason: tokenResult.reason };
|
||||
|
||||
const result = await requestMainSystem<any>({
|
||||
endpoint: 'preparationsStatus',
|
||||
method: 'POST',
|
||||
token: tokenResult.token,
|
||||
timeoutMs: MAIN_SYSTEM_FETCH_TIMEOUT_MS,
|
||||
timeoutReason: '回写备货状态超时',
|
||||
networkReasonPrefix: '回写备货状态失败:',
|
||||
body: {
|
||||
id: params.preparationId,
|
||||
status: params.status,
|
||||
...(params.prepareQty === undefined ? {} : { prepare_qty: params.prepareQty }),
|
||||
...(params.purchasePrice === undefined ? {} : { purchase_price: params.purchasePrice }),
|
||||
...(params.unit === undefined ? {} : { unit: params.unit }),
|
||||
...(params.confirmOverQty ? { confirm_over_qty: true } : {}),
|
||||
// status=40 = 报缺货(主系统转自采),原因随行带上
|
||||
...(params.stockoutReason ? { stockout_reason: String(params.stockoutReason).slice(0, 200) } : {}),
|
||||
},
|
||||
// 409 分两种(主系统单 id 路径是**硬抛**,不会回 skipped[] 给我们):
|
||||
// · 备货已确认锁定/已完成 ⇒ 我们要的结果已达成 → already_done(不能记成"被拒")
|
||||
// · 该备货已流转自采 / 其它冲突 ⇒ 真的没写进去 → rejected
|
||||
// · 识别不了的 409 → unavailable(当暂态,下轮再试,避免误判)
|
||||
classify: ({ status, reason }) => {
|
||||
if (status !== 409) return null;
|
||||
if (/锁定|已完成|不可修改(缺货标记除外)/.test(reason) && !/流转自采|转自采/.test(reason)) {
|
||||
return 'ok';
|
||||
}
|
||||
if (/流转自采|转自采/.test(reason)) return 'rejected';
|
||||
return 'unavailable';
|
||||
},
|
||||
});
|
||||
|
||||
if (result.kind === 'not_configured' || result.kind === 'unavailable') {
|
||||
return { kind: 'unavailable', reason: result.reason };
|
||||
}
|
||||
if (result.kind === 'rejected') return { kind: 'rejected', reason: result.reason };
|
||||
|
||||
// 409 = 已锁定/已完成(classify 判为 ok),语义是"我们要的结果已达成"
|
||||
if (result.status === 409) return { kind: 'already_done', reason: result.reason || '备货已锁定或已完成' };
|
||||
|
||||
const payload = result.payload as any;
|
||||
// 主系统可能回 200 但实际没写入(如该行已被转采购 → 内部 continue、updated=0):
|
||||
// 显式 success:false 视为被拒,避免我们记成 done 而实际没回写(对抗式复查 #7)。
|
||||
if (payload && payload.success === false) {
|
||||
return {
|
||||
kind: 'rejected',
|
||||
reason: String(payload?.error_description || payload?.error || '主系统返回 success=false'),
|
||||
};
|
||||
}
|
||||
const updated = Number(payload?.updated);
|
||||
const skipped: WritebackSkippedRow[] = (Array.isArray(payload?.skipped) ? payload.skipped : []).map(
|
||||
(row: any) => ({
|
||||
id: row?.id != null ? String(row.id) : null,
|
||||
skuCode: row?.sku_code != null ? String(row.sku_code) : null,
|
||||
reason: String(row?.reason || 'unknown'),
|
||||
message: row?.message != null ? String(row.message) : undefined,
|
||||
})
|
||||
);
|
||||
return {
|
||||
kind: 'ok',
|
||||
// 老版本主系统不返回 updated:按"未跳过即写入"兜底,避免把正常回写误判成失败
|
||||
updated: Number.isFinite(updated) ? updated : skipped.length ? 0 : 1,
|
||||
skipped,
|
||||
needsCustomerPrice: Boolean(payload?.needs_customer_price),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 实收数量/单位申请的**决策回传**(我方审核 → 主系统落地)。
|
||||
*
|
||||
* 主系统接口:`POST /api/supplier/preparations/actual-qty-decision`
|
||||
* (主系统提交 `b8519fbb`,见 docs/给主系统AI的对接改造清单.md §4.10 Q9)
|
||||
* · `approved`:`final_value` 可选(改值后通过);不给则以对方 proposed 为准;
|
||||
* · `rejected`:**什么都不改**(核货节点连对方也不回滚——那是事实登记);
|
||||
* · 重复调用主系统侧幂等(`message='already_decided'`)。
|
||||
*/
|
||||
export async function postMainSystemActualQtyDecision(params: {
|
||||
supplierCode: string;
|
||||
requestId: string;
|
||||
decision: 'approved' | 'rejected';
|
||||
finalValue?: number | null;
|
||||
reviewer?: string | null;
|
||||
decidedAt?: string | null;
|
||||
reason?: string | null;
|
||||
}): Promise<{ kind: 'ok'; applied: boolean; finalValue: number | null; message: string | null } | { kind: 'unavailable'; reason: string }> {
|
||||
if (!isMainSystemIntegrationEnabled()) {
|
||||
return { kind: 'unavailable', reason: '主系统对接未配置' };
|
||||
}
|
||||
const tokenResult = await getMainSystemToken(params.supplierCode);
|
||||
if (tokenResult.kind !== 'ok') {
|
||||
return { kind: 'unavailable', reason: tokenResult.reason };
|
||||
}
|
||||
const result = await requestMainSystem<any>({
|
||||
endpoint: 'preparations',
|
||||
method: 'POST',
|
||||
token: tokenResult.token,
|
||||
timeoutMs: MAIN_SYSTEM_FETCH_TIMEOUT_MS,
|
||||
timeoutReason: '实收申请决策回传超时',
|
||||
networkReasonPrefix: '实收申请决策回传失败:',
|
||||
path: mainSystemPath('actualQtyDecision'),
|
||||
body: {
|
||||
request_id: params.requestId,
|
||||
decision: params.decision,
|
||||
...(params.finalValue === null || params.finalValue === undefined ? {} : { final_value: params.finalValue }),
|
||||
...(params.reviewer ? { reviewer: params.reviewer } : {}),
|
||||
...(params.decidedAt ? { decided_at: params.decidedAt } : {}),
|
||||
...(params.reason ? { reason: params.reason } : {}),
|
||||
},
|
||||
});
|
||||
if (result.kind !== 'ok') {
|
||||
return { kind: 'unavailable', reason: result.reason || '主系统未接受决策' };
|
||||
}
|
||||
const data = (result.payload as any)?.data ?? result.payload ?? {};
|
||||
return {
|
||||
kind: 'ok',
|
||||
applied: data?.applied === true,
|
||||
finalValue: data?.final_value != null ? Number(data.final_value) : null,
|
||||
message: data?.message != null ? String(data.message) : null,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
import { getMainSystemToken } from '../token';
|
||||
import { requestMainSystem } from '../http';
|
||||
import { MAIN_SYSTEM_FETCH_TIMEOUT_MS } from '../config';
|
||||
|
||||
/**
|
||||
* 主系统**跨系统改价 / 改量**接口封装(2026-10-11 起)。
|
||||
*
|
||||
* 契约来源:`docs/给主系统AI的对接改造清单.md` 第四批 Q1/Q4(我方提出,主系统待实现)。
|
||||
* · Q1 `POST /api/supplier/preparations/price-qty-request` —— 提交申请,响应直接告诉我们是
|
||||
* `applied`(免审已生效)还是 `pending`(等主系统管理员审核);
|
||||
* · 兜底:`GET /preparations?view=price_amend` 行上的 `amend_request`(主系统既有视图,已含最新申请状态),
|
||||
* 事件漏推时用它自愈。
|
||||
*
|
||||
* 纪律:本文件只做"接口封装",不含 URL 拼接 / token 缓存 / HTTP 细节(见 `../endpoints.ts` 等)。
|
||||
*/
|
||||
|
||||
export type PriceQtyKind = 'price' | 'qty' | 'both';
|
||||
|
||||
export type SubmitPriceQtyRequestInput = {
|
||||
supplierCode: string;
|
||||
/** 主系统备货行 id */
|
||||
prepId: string;
|
||||
proposedPrice?: number | null;
|
||||
proposedQty?: number | null;
|
||||
unit?: string | null;
|
||||
reason?: string | null;
|
||||
/** 身份留痕:`SUP37831443:admin:<userId>` */
|
||||
requestedBy?: string | null;
|
||||
/** 幂等键:同 `id` + 同类型 pending 覆盖,不重复排队 */
|
||||
clientRequestId: string;
|
||||
};
|
||||
|
||||
export type SubmitPriceQtyRequestOutcome =
|
||||
| {
|
||||
kind: 'ok';
|
||||
requestId: string | null;
|
||||
/** applied=免审已生效 / pending=等审核 */
|
||||
status: 'applied' | 'pending';
|
||||
reviewRequired: boolean;
|
||||
/** 只有**已决**的字段有值(主系统响应顶层 final_price/final_qty 同口径) */
|
||||
finalPrice: number | null;
|
||||
finalQty: number | null;
|
||||
/**
|
||||
* 主系统响应里的**分解决策**(2026-10-11 按其回执 §4.4):
|
||||
* 一次提交可同时含免审项与需审项 ⇒ `applied` 是已写值的部分、`pending` 是排队待审的部分。
|
||||
*/
|
||||
applied: { price?: number; qty?: number };
|
||||
pending: { price?: number; qty?: number };
|
||||
message: string | null;
|
||||
raw: unknown;
|
||||
}
|
||||
| { kind: 'not_configured'; reason: string }
|
||||
/** 主系统尚未提供该接口(404/405)—— 联调前必然遇到,单独一态便于调度方区分 */
|
||||
| { kind: 'not_supported'; reason: string }
|
||||
| { kind: 'rejected'; reason: string }
|
||||
| { kind: 'unavailable'; reason: string };
|
||||
|
||||
function toNumberOrNull(value: unknown): number | null {
|
||||
if (value === null || value === undefined || value === '') return null;
|
||||
const n = Number(value);
|
||||
return Number.isFinite(n) ? n : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交改价/改量申请(Q1)。
|
||||
*
|
||||
* 免审/要审**由主系统按统一规则判定**(避免两边规则漂移,见设计文档 §1/§3.1),
|
||||
* 我们只按响应落地:`applied` ⇒ 立即生效;`pending` ⇒ 挂起等回传。
|
||||
*/
|
||||
export async function submitMainSystemPriceQtyRequest(
|
||||
input: SubmitPriceQtyRequestInput
|
||||
): Promise<SubmitPriceQtyRequestOutcome> {
|
||||
const tokenResult = await getMainSystemToken(input.supplierCode);
|
||||
if (tokenResult.kind === 'not_configured') return { kind: 'not_configured', reason: tokenResult.reason };
|
||||
if (tokenResult.kind !== 'ok') return { kind: 'unavailable', reason: tokenResult.reason };
|
||||
|
||||
const result = await requestMainSystem<any>({
|
||||
endpoint: 'priceQtyRequest',
|
||||
method: 'POST',
|
||||
token: tokenResult.token,
|
||||
timeoutMs: MAIN_SYSTEM_FETCH_TIMEOUT_MS,
|
||||
timeoutReason: '提交改价/改量申请超时',
|
||||
networkReasonPrefix: '提交改价/改量申请失败:',
|
||||
body: {
|
||||
id: input.prepId,
|
||||
...(input.proposedPrice === undefined || input.proposedPrice === null
|
||||
? {}
|
||||
: { proposed_price: input.proposedPrice }),
|
||||
...(input.proposedQty === undefined || input.proposedQty === null ? {} : { proposed_qty: input.proposedQty }),
|
||||
...(input.unit ? { unit: input.unit } : {}),
|
||||
...(input.reason ? { reason: String(input.reason).slice(0, 200) } : {}),
|
||||
...(input.requestedBy ? { requested_by: input.requestedBy } : {}),
|
||||
client_request_id: input.clientRequestId,
|
||||
},
|
||||
// 404/405 = 主系统还没实现这个接口(联调前)⇒ 单独一态,不要当成"被拒"
|
||||
classify: ({ status }) => (status === 404 || status === 405 ? 'rejected' : null),
|
||||
});
|
||||
|
||||
if (result.kind === 'not_configured') return { kind: 'not_configured', reason: result.reason };
|
||||
if (result.kind === 'rejected' && (result.status === 404 || result.status === 405)) {
|
||||
return {
|
||||
kind: 'not_supported',
|
||||
reason: `主系统暂未提供改价/改量申请接口(HTTP ${result.status}):${result.reason}`,
|
||||
};
|
||||
}
|
||||
if (result.kind === 'rejected') return { kind: 'rejected', reason: result.reason };
|
||||
if (result.kind === 'unavailable') return { kind: 'unavailable', reason: result.reason };
|
||||
|
||||
const payload = result.payload as any;
|
||||
if (payload && payload.success === false) {
|
||||
return {
|
||||
kind: 'rejected',
|
||||
reason: String(payload?.error_description || payload?.error || '主系统返回 success=false'),
|
||||
};
|
||||
}
|
||||
const data = payload?.data && typeof payload.data === 'object' ? payload.data : payload;
|
||||
const status = String(data?.status || '').toLowerCase();
|
||||
if (status !== 'applied' && status !== 'pending') {
|
||||
// 形状不符(例如主系统返回了别的结构)⇒ 当暂态,不猜、不落地
|
||||
return {
|
||||
kind: 'unavailable',
|
||||
reason: `主系统响应缺少可识别的 status(应为 applied/pending):${JSON.stringify(data ?? null).slice(0, 200)}`,
|
||||
};
|
||||
}
|
||||
const applied: { price?: number; qty?: number } = {};
|
||||
const pending: { price?: number; qty?: number } = {};
|
||||
const readSide = (side: any, target: { price?: number; qty?: number }) => {
|
||||
const price = toNumberOrNull(side?.price);
|
||||
const qty = toNumberOrNull(side?.qty);
|
||||
if (price !== null) target.price = price;
|
||||
if (qty !== null) target.qty = qty;
|
||||
};
|
||||
readSide(data?.applied, applied);
|
||||
readSide(data?.pending, pending);
|
||||
|
||||
// 顶层 final_* 只反映已生效部分;若主系统没给分解对象(老版本),用顶层值兜底当作 applied
|
||||
const finalPrice = toNumberOrNull(data?.final_price);
|
||||
const finalQty = toNumberOrNull(data?.final_qty);
|
||||
if (!Object.keys(applied).length) {
|
||||
if (finalPrice !== null) applied.price = finalPrice;
|
||||
if (finalQty !== null) applied.qty = finalQty;
|
||||
}
|
||||
|
||||
return {
|
||||
kind: 'ok',
|
||||
requestId: data?.request_id != null ? String(data.request_id) : null,
|
||||
status: status === 'applied' ? 'applied' : 'pending',
|
||||
reviewRequired: data?.review_required === true || status === 'pending',
|
||||
finalPrice,
|
||||
finalQty,
|
||||
applied,
|
||||
pending,
|
||||
message: data?.message != null ? String(data.message) : null,
|
||||
raw: payload,
|
||||
};
|
||||
}
|
||||
|
||||
/* ── 兜底:`GET /preparations?view=price_amend` 行上的 amend_request ──────────── */
|
||||
|
||||
/** 主系统既有「追加改价」申请状态(数值口径,见主系统 `prepAmendRequestService.PREP_AMEND_STATUS`) */
|
||||
export const MAIN_SYSTEM_AMEND_STATUS = { pending: 10, approved: 20, rejected: 30 } as const;
|
||||
|
||||
export type MainSystemAmendRequest = {
|
||||
id: string | null;
|
||||
status: number | null;
|
||||
statusLabel: string | null;
|
||||
proposedPrice: number | null;
|
||||
proposedQty: number | null;
|
||||
proposedUnit: string | null;
|
||||
reviewRemark: string | null;
|
||||
requestedAt: string | null;
|
||||
};
|
||||
|
||||
export type MainSystemPriceAmendRow = {
|
||||
prepId: string;
|
||||
orderCode: string | null;
|
||||
prepareQty: number | null;
|
||||
purchasePrice: number | null;
|
||||
unit: string | null;
|
||||
amendRequest: MainSystemAmendRequest | null;
|
||||
};
|
||||
|
||||
export type PriceAmendRowsOutcome =
|
||||
| { kind: 'ok'; rows: MainSystemPriceAmendRow[] }
|
||||
| { kind: 'not_configured'; reason: string }
|
||||
| { kind: 'rejected'; reason: string }
|
||||
| { kind: 'unavailable'; reason: string };
|
||||
|
||||
/**
|
||||
* 拉「可改价视图」(兜底通道)。
|
||||
*
|
||||
* ⚠️ 行上 `amend_request` 是主系统**既有 amend 流程**的形状;本次新流程(Q4)要求主系统
|
||||
* 在同一视图里也能反映新申请的状态。字段名若有出入,以主系统实现为准并同步本文件——
|
||||
* 解析保持宽容(缺失即 null),绝不猜值。
|
||||
*/
|
||||
export async function fetchMainSystemPriceAmendRows(params: {
|
||||
supplierCode: string;
|
||||
deliveryDate?: string | null;
|
||||
}): Promise<PriceAmendRowsOutcome> {
|
||||
const tokenResult = await getMainSystemToken(params.supplierCode);
|
||||
if (tokenResult.kind === 'not_configured') return { kind: 'not_configured', reason: tokenResult.reason };
|
||||
if (tokenResult.kind !== 'ok') return { kind: 'unavailable', reason: tokenResult.reason };
|
||||
|
||||
const result = await requestMainSystem<any>({
|
||||
endpoint: 'preparations',
|
||||
token: tokenResult.token,
|
||||
timeoutMs: MAIN_SYSTEM_FETCH_TIMEOUT_MS,
|
||||
timeoutReason: '拉改价视图超时',
|
||||
networkReasonPrefix: '拉改价视图失败:',
|
||||
query: { view: 'price_amend', ...(params.deliveryDate ? { delivery_date: params.deliveryDate } : {}) },
|
||||
});
|
||||
if (result.kind === 'not_configured') return { kind: 'not_configured', reason: result.reason };
|
||||
if (result.kind !== 'ok') return { kind: result.kind, reason: result.reason };
|
||||
|
||||
const payload = result.data as any;
|
||||
const rows: MainSystemPriceAmendRow[] = (Array.isArray(payload?.data) ? payload.data : [])
|
||||
.map((raw: any): MainSystemPriceAmendRow => {
|
||||
const amend = raw?.amend_request && typeof raw.amend_request === 'object' ? raw.amend_request : null;
|
||||
return {
|
||||
prepId: String(raw?.id || ''),
|
||||
orderCode: raw?.order_code != null ? String(raw.order_code) : null,
|
||||
prepareQty: toNumberOrNull(raw?.prepare_qty),
|
||||
purchasePrice: toNumberOrNull(raw?.purchase_price),
|
||||
unit: raw?.unit != null ? String(raw.unit) : null,
|
||||
amendRequest: amend
|
||||
? {
|
||||
id: amend.id != null ? String(amend.id) : null,
|
||||
status: toNumberOrNull(amend.status),
|
||||
statusLabel: amend.status_label != null ? String(amend.status_label) : null,
|
||||
proposedPrice: toNumberOrNull(amend.proposed_price),
|
||||
proposedQty: toNumberOrNull(amend.proposed_qty),
|
||||
proposedUnit: amend.proposed_unit != null ? String(amend.proposed_unit) : null,
|
||||
reviewRemark: amend.review_remark != null ? String(amend.review_remark) : null,
|
||||
requestedAt: amend.requested_at != null ? String(amend.requested_at) : null,
|
||||
}
|
||||
: null,
|
||||
};
|
||||
})
|
||||
.filter((row: MainSystemPriceAmendRow) => row.prepId);
|
||||
return { kind: 'ok', rows };
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import { config } from '../../config';
|
||||
|
||||
/**
|
||||
* 主系统对接的**唯一配置出口**(域名 / 超时 / 凭据 / 能力开关)。
|
||||
*
|
||||
* 开发者 2026-10-11 口径:「主系统的**域名统一管理**,不能这个文件写一个、另外一个文件也写一个,
|
||||
* 不然后期域名变化维护起来复杂;采取**模块化开发**,**接口注意封装**。」
|
||||
*
|
||||
* 纪律(新增主系统调用时必须遵守):
|
||||
* · 域名只在 `MAIN_SYSTEM_BASE_URL` → `server/src/config.ts` → 本文件这一条链上流转;
|
||||
* 业务文件**禁止**读 `process.env.MAIN_SYSTEM_BASE_URL` 或 `config.mainSystem*`;
|
||||
* · 端点路径只在 `./endpoints.ts` 的端点表里拼(可被 `MAIN_SYSTEM_*_PATH` 覆盖);
|
||||
* · 业务文件**禁止**裸 `fetch()` 调主系统,一律走 `./api/*.ts` 的封装函数。
|
||||
*
|
||||
* 见 docs/design/20261011-跨系统改价改量审核.md §7。
|
||||
*/
|
||||
|
||||
/** 各端点的**默认路径**(可被环境变量覆盖,见 endpoints.ts) */
|
||||
export const MAIN_SYSTEM_DEFAULT_PATHS = {
|
||||
oauth: '/api/supplier/oauth/token',
|
||||
preparations: '/api/supplier/preparations',
|
||||
preparationsStatus: '/api/supplier/preparations/status',
|
||||
priceQtyRequest: '/api/supplier/preparations/price-qty-request',
|
||||
// 实收/单位申请的决策回传(Q9,主系统提交 b8519fbb)
|
||||
actualQtyDecision: '/api/supplier/preparations/actual-qty-decision',
|
||||
supplierLogin: '/api/supplier/login',
|
||||
} as const;
|
||||
|
||||
export type MainSystemEndpoint = keyof typeof MAIN_SYSTEM_DEFAULT_PATHS;
|
||||
|
||||
export const MAIN_SYSTEM_OAUTH_TIMEOUT_MS = 8000;
|
||||
export const MAIN_SYSTEM_FETCH_TIMEOUT_MS = 15000;
|
||||
|
||||
/** 主系统 API 基地址(未配置返回空串) */
|
||||
export function mainSystemBaseUrl(): string {
|
||||
return String(config.mainSystem.baseUrl || '');
|
||||
}
|
||||
|
||||
export function mainSystemTimeoutMs(): number {
|
||||
const value = Number(config.mainSystem.timeoutMs);
|
||||
return Number.isFinite(value) && value > 0 ? value : 5000;
|
||||
}
|
||||
|
||||
/** 进销存对接凭据(client_credentials;未配置时为空的成对值) */
|
||||
export function mainSystemCredentials(): { clientId: string; clientSecret: string } {
|
||||
return {
|
||||
clientId: String(config.mainSystemIntegration.clientId || ''),
|
||||
clientSecret: String(config.mainSystemIntegration.clientSecret || ''),
|
||||
};
|
||||
}
|
||||
|
||||
/** 进销存对接是否可用(域名 + 凭据齐备) */
|
||||
export function isMainSystemIntegrationEnabled(): boolean {
|
||||
const { clientId, clientSecret } = mainSystemCredentials();
|
||||
return Boolean(mainSystemBaseUrl() && clientId && clientSecret);
|
||||
}
|
||||
|
||||
/** 供应商账号登录校验是否可用(只需要域名) */
|
||||
export function isMainSystemLoginEnabled(): boolean {
|
||||
return Boolean(mainSystemBaseUrl());
|
||||
}
|
||||
|
||||
export function mainSystemWebhookSecret(): string {
|
||||
return String(config.mainSystemIntegration.webhookSecret || '');
|
||||
}
|
||||
|
||||
/**
|
||||
* 跨系统改价/改量审核总开关(默认关)。
|
||||
* ⚠️ 关 = 与改造前逐字节一致:提交入口停用、**发车回写继续携带价格**(静默通道保留)。
|
||||
* 见 docs/design/20261011-跨系统改价改量审核.md §7「C5 的开关纪律」。
|
||||
*/
|
||||
export function isPriceQtyRequestEnabled(): boolean {
|
||||
return config.mainSystemIntegration.priceQtyEnabled === true;
|
||||
}
|
||||
|
||||
/** 既有能力开关(供业务模块集中查阅,避免各自读 config.mainSystemIntegration) */
|
||||
export function mainSystemFeatureFlags(): {
|
||||
autoImport: boolean;
|
||||
returnFollow: boolean;
|
||||
writeback: boolean;
|
||||
fulfillmentEvents: boolean;
|
||||
skipInboundAwaitPickup: boolean;
|
||||
priceQty: boolean;
|
||||
} {
|
||||
const flags = config.mainSystemIntegration;
|
||||
return {
|
||||
autoImport: flags.autoImportEnabled !== false,
|
||||
returnFollow: flags.returnFollowEnabled === true,
|
||||
writeback: flags.writebackEnabled === true,
|
||||
fulfillmentEvents: flags.fulfillmentEventsEnabled === true,
|
||||
skipInboundAwaitPickup: flags.skipInboundAwaitPickup === true,
|
||||
priceQty: flags.priceQtyEnabled === true,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { config } from '../../config';
|
||||
import {
|
||||
MAIN_SYSTEM_DEFAULT_PATHS,
|
||||
type MainSystemEndpoint,
|
||||
mainSystemBaseUrl,
|
||||
} from './config';
|
||||
|
||||
/**
|
||||
* 主系统**端点表**:全仓唯一拼 `${baseUrl}${path}` 的地方。
|
||||
*
|
||||
* 为什么集中:主系统换域名/换路径时只改 `MAIN_SYSTEM_BASE_URL` 或对应的 `MAIN_SYSTEM_*_PATH`,
|
||||
* 不需要在业务代码里找散落的 URL 字符串(开发者 2026-10-11 要求)。
|
||||
*
|
||||
* ⚠️ 新增端点 = 本表加一行 + `./api/*.ts` 加一个封装函数;业务层只调封装函数。
|
||||
*/
|
||||
|
||||
export type { MainSystemEndpoint };
|
||||
|
||||
/** 环境变量可覆盖的端点 → 覆盖值来源 */
|
||||
function pathOverride(endpoint: MainSystemEndpoint): string | undefined {
|
||||
const flags = config.mainSystemIntegration;
|
||||
switch (endpoint) {
|
||||
case 'oauth':
|
||||
return flags.oauthPath;
|
||||
case 'preparations':
|
||||
return flags.preparationsPath;
|
||||
case 'preparationsStatus':
|
||||
return flags.statusPath;
|
||||
case 'priceQtyRequest':
|
||||
return flags.priceQtyRequestPath;
|
||||
case 'actualQtyDecision':
|
||||
return process.env.MAIN_SYSTEM_ACTUAL_QTY_DECISION_PATH;
|
||||
case 'supplierLogin':
|
||||
return config.mainSystem.supplierLoginPath;
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** 取某端点的路径(以 `/` 开头;未配置抛错,调用方应先查 enabled) */
|
||||
export function mainSystemPath(endpoint: MainSystemEndpoint): string {
|
||||
const raw = String(pathOverride(endpoint) || MAIN_SYSTEM_DEFAULT_PATHS[endpoint] || '').trim();
|
||||
if (!raw) throw new Error(`主系统端点未配置:${endpoint}`);
|
||||
return raw.startsWith('/') ? raw : `/${raw}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 备货单行的查询端点:`{preparationsPath}/lookup`(跟着 preparations 的覆盖走)。
|
||||
*/
|
||||
export function mainSystemLookupPath(): string {
|
||||
return `${mainSystemPath('preparations').replace(/\/+$/, '')}/lookup`;
|
||||
}
|
||||
|
||||
export type MainSystemQuery = Record<string, string | number | boolean | null | undefined>;
|
||||
|
||||
/** 组装完整 URL(含 query;空值自动省略)。**唯一**允许拼主系统 URL 的函数。 */
|
||||
export function buildMainSystemUrl(endpoint: MainSystemEndpoint, query?: MainSystemQuery): string {
|
||||
const base = mainSystemBaseUrl();
|
||||
if (!base) throw new Error('未配置 MAIN_SYSTEM_BASE_URL(主系统对接整体关闭)');
|
||||
const url = new URL(`${base}${mainSystemPath(endpoint)}`);
|
||||
for (const [key, value] of Object.entries(query || {})) {
|
||||
if (value === undefined || value === null || value === '') continue;
|
||||
url.searchParams.set(key, String(value));
|
||||
}
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
/** 组装完整 URL(自定义路径,如 `/lookup` 后缀端点) */
|
||||
export function buildMainSystemUrlWithPath(path: string, query?: MainSystemQuery): string {
|
||||
const base = mainSystemBaseUrl();
|
||||
if (!base) throw new Error('未配置 MAIN_SYSTEM_BASE_URL(主系统对接整体关闭)');
|
||||
const url = new URL(`${base}${path.startsWith('/') ? path : `/${path}`}`);
|
||||
for (const [key, value] of Object.entries(query || {})) {
|
||||
if (value === undefined || value === null || value === '') continue;
|
||||
url.searchParams.set(key, String(value));
|
||||
}
|
||||
return url.toString();
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import {
|
||||
MAIN_SYSTEM_FETCH_TIMEOUT_MS,
|
||||
isMainSystemIntegrationEnabled,
|
||||
} from './config';
|
||||
import {
|
||||
buildMainSystemUrl,
|
||||
buildMainSystemUrlWithPath,
|
||||
type MainSystemEndpoint,
|
||||
type MainSystemQuery,
|
||||
} from './endpoints';
|
||||
|
||||
/**
|
||||
* 主系统 HTTP **唯一出口**:超时、JSON 解析、错误归一都在这里。
|
||||
*
|
||||
* 为什么要有它(开发者 2026-10-11「接口注意封装」):
|
||||
* · 业务层不写 `fetch`、不判 HTTP 状态码、不解析 error_description;
|
||||
* · 状态码归一口径**只此一份**:401/403/408/425/429 视为**暂态**(下轮重试),
|
||||
* 其余 4xx = 被拒(不重试),5xx = 主系统不可用;
|
||||
* · 需要"409 其实是我们想要的结果已达成"这类特例时,用 `classify` 钩子,不另写一套。
|
||||
*
|
||||
* 结果四态:`ok` / `rejected` / `unavailable` / `not_configured`(与既有服务层枚举一致)。
|
||||
*/
|
||||
|
||||
export type MainSystemResult<T> =
|
||||
| {
|
||||
kind: 'ok';
|
||||
status: number;
|
||||
data: T;
|
||||
payload: unknown;
|
||||
/** 仅当 `classify` 把非 2xx 判成"其实已达成"时带上(如 409 已锁定),供调用方留痕 */
|
||||
reason?: string;
|
||||
}
|
||||
| { kind: 'rejected'; status: number; reason: string; payload: unknown }
|
||||
| { kind: 'unavailable'; status: number; reason: string; payload: unknown }
|
||||
| { kind: 'not_configured'; status: 0; reason: string; payload: null };
|
||||
|
||||
/** 自定义归类钩子:返回 null 表示按默认口径判 */
|
||||
export type MainSystemClassifyHook = (params: {
|
||||
status: number;
|
||||
reason: string;
|
||||
payload: unknown;
|
||||
}) => 'ok' | 'rejected' | 'unavailable' | null;
|
||||
|
||||
export type MainSystemRequestOptions = {
|
||||
endpoint: MainSystemEndpoint;
|
||||
/** 自定义路径(跟在端点后的子路径,如 `{preparations}/lookup`) */
|
||||
path?: string;
|
||||
method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
||||
/** Bearer token(oauth 接口自身不传) */
|
||||
token?: string | null;
|
||||
body?: unknown;
|
||||
query?: MainSystemQuery;
|
||||
timeoutMs?: number;
|
||||
/** 超时文案(保留各调用点既有措辞,便于日志比对) */
|
||||
timeoutReason?: string;
|
||||
/** 网络错误文案前缀(同上) */
|
||||
networkReasonPrefix?: string;
|
||||
classify?: MainSystemClassifyHook;
|
||||
/** 默认 true:要求域名 + 凭据齐备 */
|
||||
requireConfigured?: boolean;
|
||||
/** 测试注入 */
|
||||
fetchImpl?: typeof fetch;
|
||||
};
|
||||
|
||||
/** 暂态 4xx:令牌过期/被撤、超时、限流 —— 必须留给下一轮重试,不能记成"被拒" */
|
||||
const TRANSIENT_4XX = new Set([401, 403, 408, 425, 429]);
|
||||
|
||||
export function describeMainSystemError(payload: unknown, status: number): string {
|
||||
const p = payload as { error?: unknown; error_description?: unknown } | null;
|
||||
const text = `${p?.error || ''} ${p?.error_description || ''}`.trim();
|
||||
return text || `HTTP ${status}`;
|
||||
}
|
||||
|
||||
export async function requestMainSystem<T = any>(
|
||||
options: MainSystemRequestOptions
|
||||
): Promise<MainSystemResult<T>> {
|
||||
if (options.requireConfigured !== false && !isMainSystemIntegrationEnabled()) {
|
||||
return {
|
||||
kind: 'not_configured',
|
||||
status: 0,
|
||||
reason: '主系统对接未配置(MAIN_SYSTEM_BASE_URL / MAIN_SYSTEM_INTEGRATION_CLIENT_ID / _SECRET)',
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
|
||||
let url: string;
|
||||
try {
|
||||
url = options.path
|
||||
? buildMainSystemUrlWithPath(options.path, options.query)
|
||||
: buildMainSystemUrl(options.endpoint, options.query);
|
||||
} catch (error: any) {
|
||||
return {
|
||||
kind: 'not_configured',
|
||||
status: 0,
|
||||
reason: String(error?.message || error),
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
|
||||
const timeoutMs = options.timeoutMs ?? MAIN_SYSTEM_FETCH_TIMEOUT_MS;
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
||||
const doFetch = options.fetchImpl || fetch;
|
||||
try {
|
||||
const headers: Record<string, string> = { Accept: 'application/json' };
|
||||
if (options.token) headers.Authorization = `Bearer ${options.token}`;
|
||||
if (options.body !== undefined) headers['Content-Type'] = 'application/json';
|
||||
|
||||
const response = await doFetch(url, {
|
||||
method: options.method || 'GET',
|
||||
headers,
|
||||
...(options.body === undefined ? {} : { body: JSON.stringify(options.body) }),
|
||||
signal: controller.signal,
|
||||
});
|
||||
const payload: unknown = await response.json().catch(() => null);
|
||||
|
||||
if (!response.ok) {
|
||||
const reason = describeMainSystemError(payload, response.status);
|
||||
const custom = options.classify?.({ status: response.status, reason, payload });
|
||||
if (custom === 'ok') return { kind: 'ok', status: response.status, data: payload as T, payload, reason };
|
||||
if (custom === 'rejected') return { kind: 'rejected', status: response.status, reason, payload };
|
||||
if (custom === 'unavailable') return { kind: 'unavailable', status: response.status, reason, payload };
|
||||
if (TRANSIENT_4XX.has(response.status)) {
|
||||
return { kind: 'unavailable', status: response.status, reason, payload };
|
||||
}
|
||||
return response.status >= 400 && response.status < 500
|
||||
? { kind: 'rejected', status: response.status, reason, payload }
|
||||
: { kind: 'unavailable', status: response.status, reason, payload };
|
||||
}
|
||||
|
||||
return { kind: 'ok', status: response.status, data: payload as T, payload };
|
||||
} catch (error: any) {
|
||||
if (error?.name === 'AbortError') {
|
||||
return {
|
||||
kind: 'unavailable',
|
||||
status: 0,
|
||||
reason: options.timeoutReason || '调用主系统超时',
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
return {
|
||||
kind: 'unavailable',
|
||||
status: 0,
|
||||
reason: `${options.networkReasonPrefix || '调用主系统失败:'}${error?.message || error}`,
|
||||
payload: null,
|
||||
};
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* 主系统对接模块 —— **唯一对外入口**。
|
||||
*
|
||||
* 业务层只从这里 import;不要在业务文件里直连 `fetch`、拼主系统 URL、读 `MAIN_SYSTEM_*` 环境变量。
|
||||
* 模块分层与纪律见 `docs/design/20261011-跨系统改价改量审核.md` §7。
|
||||
*
|
||||
* 说明:既有 `server/src/services/mainSystemPreparations.ts` 是历史门面(对外签名不变,内部走本模块),
|
||||
* 老调用方保持原样即可;新增能力一律从本文件导出。
|
||||
*/
|
||||
|
||||
export {
|
||||
MAIN_SYSTEM_DEFAULT_PATHS,
|
||||
MAIN_SYSTEM_FETCH_TIMEOUT_MS,
|
||||
MAIN_SYSTEM_OAUTH_TIMEOUT_MS,
|
||||
isMainSystemIntegrationEnabled,
|
||||
isMainSystemLoginEnabled,
|
||||
isPriceQtyRequestEnabled,
|
||||
mainSystemBaseUrl,
|
||||
mainSystemCredentials,
|
||||
mainSystemFeatureFlags,
|
||||
mainSystemTimeoutMs,
|
||||
mainSystemWebhookSecret,
|
||||
} from './config';
|
||||
export type { MainSystemEndpoint } from './config';
|
||||
|
||||
export { buildMainSystemUrl, buildMainSystemUrlWithPath, mainSystemLookupPath, mainSystemPath } from './endpoints';
|
||||
|
||||
export { describeMainSystemError, requestMainSystem } from './http';
|
||||
export type { MainSystemClassifyHook, MainSystemRequestOptions, MainSystemResult } from './http';
|
||||
|
||||
export { getMainSystemToken, resetMainSystemTokenCache } from './token';
|
||||
export type { MainSystemTokenResult } from './token';
|
||||
|
||||
export {
|
||||
fetchMainSystemPriceAmendRows,
|
||||
MAIN_SYSTEM_AMEND_STATUS,
|
||||
submitMainSystemPriceQtyRequest,
|
||||
} from './api/priceQty';
|
||||
export type {
|
||||
MainSystemAmendRequest,
|
||||
MainSystemPriceAmendRow,
|
||||
PriceAmendRowsOutcome,
|
||||
PriceQtyKind,
|
||||
SubmitPriceQtyRequestInput,
|
||||
SubmitPriceQtyRequestOutcome,
|
||||
} from './api/priceQty';
|
||||
@@ -0,0 +1,81 @@
|
||||
import {
|
||||
MAIN_SYSTEM_OAUTH_TIMEOUT_MS,
|
||||
mainSystemCredentials,
|
||||
isMainSystemIntegrationEnabled,
|
||||
} from './config';
|
||||
import { requestMainSystem } from './http';
|
||||
|
||||
/**
|
||||
* 主系统对接 Token(`POST /api/supplier/oauth/token`,client_credentials)。
|
||||
*
|
||||
* 全仓**唯一**的 token 获取与缓存实现:按 `supplier_code` 分别缓存(有效期约 24h,提前 60s 过期)。
|
||||
* 其它模块不要再各写一份缓存(开发者 2026-10-11:接口注意封装)。
|
||||
*/
|
||||
|
||||
export type MainSystemTokenResult =
|
||||
| { kind: 'ok'; token: string; branchCode: string | null; expiresAt: number }
|
||||
| { kind: 'not_configured'; reason: string }
|
||||
| { kind: 'unavailable'; reason: string };
|
||||
|
||||
type CachedToken = { token: string; expiresAt: number; branchCode: string | null };
|
||||
|
||||
const tokenCache = new Map<string, CachedToken>();
|
||||
|
||||
/** 仅供测试:清空 token 缓存 */
|
||||
export function resetMainSystemTokenCache(): void {
|
||||
tokenCache.clear();
|
||||
}
|
||||
|
||||
export async function getMainSystemToken(
|
||||
supplierCode: string,
|
||||
options?: { fetchImpl?: typeof fetch; forceRefresh?: boolean }
|
||||
): Promise<MainSystemTokenResult> {
|
||||
const code = String(supplierCode || '').trim();
|
||||
if (!code) return { kind: 'unavailable', reason: '缺少 supplier_code' };
|
||||
if (!isMainSystemIntegrationEnabled()) {
|
||||
return {
|
||||
kind: 'not_configured',
|
||||
reason: '未配置 MAIN_SYSTEM_BASE_URL / MAIN_SYSTEM_INTEGRATION_CLIENT_ID / _SECRET',
|
||||
};
|
||||
}
|
||||
|
||||
if (!options?.forceRefresh) {
|
||||
const cached = tokenCache.get(code);
|
||||
if (cached && cached.expiresAt - 60_000 > Date.now()) {
|
||||
return { kind: 'ok', token: cached.token, branchCode: cached.branchCode, expiresAt: cached.expiresAt };
|
||||
}
|
||||
}
|
||||
|
||||
const { clientId, clientSecret } = mainSystemCredentials();
|
||||
const result = await requestMainSystem<any>({
|
||||
endpoint: 'oauth',
|
||||
method: 'POST',
|
||||
timeoutMs: MAIN_SYSTEM_OAUTH_TIMEOUT_MS,
|
||||
timeoutReason: 'oauth_timeout',
|
||||
networkReasonPrefix: 'oauth_network_error: ',
|
||||
body: { client_id: clientId, client_secret: clientSecret, supplier_code: code },
|
||||
fetchImpl: options?.fetchImpl,
|
||||
});
|
||||
|
||||
if (result.kind === 'not_configured') return { kind: 'not_configured', reason: result.reason };
|
||||
if (result.kind !== 'ok') {
|
||||
const payload = result.payload as { error?: unknown; error_description?: unknown } | null;
|
||||
const detail = `${payload?.error || result.reason || ''}: ${payload?.error_description || ''}`.trim();
|
||||
return { kind: 'unavailable', reason: `换取对接 Token 失败(${detail || `${result.status}`})` };
|
||||
}
|
||||
|
||||
const payload = result.data as { access_token?: unknown; expires_in?: unknown; branch_code?: unknown } | null;
|
||||
if (!payload?.access_token) {
|
||||
const detail = `${(result.payload as any)?.error || `http_${result.status}`}: ${(result.payload as any)?.error_description || ''}`.trim();
|
||||
return { kind: 'unavailable', reason: `换取对接 Token 失败(${detail})` };
|
||||
}
|
||||
|
||||
const ttlSeconds = Number(payload.expires_in) || 86400;
|
||||
const entry: CachedToken = {
|
||||
token: String(payload.access_token),
|
||||
expiresAt: Date.now() + ttlSeconds * 1000,
|
||||
branchCode: payload.branch_code ? String(payload.branch_code) : null,
|
||||
};
|
||||
tokenCache.set(code, entry);
|
||||
return { kind: 'ok', token: entry.token, branchCode: entry.branchCode, expiresAt: entry.expiresAt };
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
import { pool } from '../db';
|
||||
import { lookupMainSystemPreparationStates } from './mainSystem/api/preparations';
|
||||
import { runWithTenantDbContext } from './tenantDbContext';
|
||||
|
||||
/**
|
||||
* 主系统备货行的**核货/入库事实**镜像(2026-10-11,开发者要"核货完毕"标记)。
|
||||
*
|
||||
* 背景:主系统配送员核货后把实配量写进它们的 `picking_items.loaded_qty`,由备货行接口以
|
||||
* `actual_qty` 暴露(免入库=核货实配;送仓=验收入库实收)。**事件通道只在"核货量≠申报量"时才推**
|
||||
* (`preparations.actual_qty_request`),等量核货天然静默 ⇒ 想显示"核货完毕"只能**主动拉**。
|
||||
*
|
||||
* 通道:`POST /preparations/lookup`(与列表同一份 SQL 常量),按 `id` 精确查,**不受 active/archived 视图影响**
|
||||
* (我方回写 `prepare_status=30` 后行会离开 active 视图,实测 active=0 行)。
|
||||
*
|
||||
* 纪律:
|
||||
* · **只读外部**(lookup 是查询,不回写主系统);
|
||||
* · 只更新台账 payload 的 5 个事实键,**不动其它键**(与导入同构);
|
||||
* · 任何失败只记日志、返回 null,绝不把调用方(详情/对账)带崩。
|
||||
*
|
||||
* 见 docs/design/20261011-免入库核货完毕标记.md。
|
||||
*/
|
||||
|
||||
/** 台账 payload 里承载主系统事实的 5 个键(与导入写入的键名一致) */
|
||||
const ACTUAL_FACT_KEYS = ['actualQty', 'actualQtyAt', 'qtyDiff', 'isInbounded', 'inboundAt'] as const;
|
||||
|
||||
export type PrepActualFact = {
|
||||
/** 主系统备货行 id(台账 `prep_id`) */
|
||||
prepId: string;
|
||||
/** 我方订单行 id(台账对照;可能为 null,未对照的历史行) */
|
||||
ourOrderItemId: string | null;
|
||||
mainOrderCode: string;
|
||||
skuCode: string;
|
||||
itemName: string;
|
||||
/** 核货实配量(免入库)/ 入库实收量(送仓);null = 尚未产生 */
|
||||
actualQty: number | null;
|
||||
actualQtyAt: string | null;
|
||||
qtyDiff: number | null;
|
||||
isInbounded: boolean;
|
||||
/** 该行是否免入库(展示层用它决定要不要标"核货完毕") */
|
||||
skipInbound: boolean;
|
||||
/** 是否已核货/已入库:`actualQty != null`。⚠️ 不用 `actualQtyAt`(免入库行实测恒为 null) */
|
||||
checked: boolean;
|
||||
};
|
||||
|
||||
function toNumber(value: unknown): number | null {
|
||||
if (value === null || value === undefined || value === '') return null;
|
||||
const n = Number(value);
|
||||
return Number.isFinite(n) ? n : null;
|
||||
}
|
||||
|
||||
function toIso(value: unknown): string | null {
|
||||
if (value === null || value === undefined || value === '') return null;
|
||||
const d = value instanceof Date ? value : new Date(String(value));
|
||||
return Number.isNaN(d.getTime()) ? String(value) : d.toISOString();
|
||||
}
|
||||
|
||||
/** 读台账里该单的核货/入库事实(只读库,不调外部) */
|
||||
export async function listOrderActualFacts(params: {
|
||||
branchCode: string;
|
||||
ourOrderCode: string;
|
||||
}): Promise<PrepActualFact[]> {
|
||||
const branch = String(params.branchCode || '').trim();
|
||||
const orderCode = String(params.ourOrderCode || '').trim();
|
||||
if (!branch || !orderCode) return [];
|
||||
const result = await pool.query<{
|
||||
prep_id: string;
|
||||
our_order_item_id: string | null;
|
||||
main_order_code: string;
|
||||
main_sku_code: string | null;
|
||||
item_name: string | null;
|
||||
actual_qty: string | number | null;
|
||||
actual_qty_at: string | null;
|
||||
qty_diff: string | number | null;
|
||||
is_inbounded: boolean | null;
|
||||
skip_inbound: boolean | null;
|
||||
}>(
|
||||
`SELECT prep_id::text AS prep_id,
|
||||
our_order_item_id::text AS our_order_item_id,
|
||||
main_order_code,
|
||||
main_sku_code,
|
||||
item_name,
|
||||
payload->>'actualQty' AS actual_qty,
|
||||
payload->>'actualQtyAt' AS actual_qty_at,
|
||||
payload->>'qtyDiff' AS qty_diff,
|
||||
(payload->>'isInbounded') = 'true' AS is_inbounded,
|
||||
COALESCE(payload->>'skipInbound', 'false') = 'true' AS skip_inbound
|
||||
FROM public.main_system_order_import_items
|
||||
WHERE branch_code = $1 AND our_order_code = $2
|
||||
ORDER BY main_order_code, item_name, prep_id`,
|
||||
[branch, orderCode]
|
||||
);
|
||||
return result.rows.map((row) => {
|
||||
const actualQty = toNumber(row.actual_qty);
|
||||
return {
|
||||
prepId: String(row.prep_id),
|
||||
ourOrderItemId: row.our_order_item_id ? String(row.our_order_item_id) : null,
|
||||
mainOrderCode: String(row.main_order_code || ''),
|
||||
skuCode: row.main_sku_code ? String(row.main_sku_code) : '',
|
||||
itemName: row.item_name ? String(row.item_name) : '',
|
||||
actualQty,
|
||||
actualQtyAt: toIso(row.actual_qty_at),
|
||||
qtyDiff: toNumber(row.qty_diff),
|
||||
isInbounded: row.is_inbounded === true,
|
||||
skipInbound: row.skip_inbound === true,
|
||||
checked: actualQty !== null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 按台账 `prep_id` 调一次主系统 lookup,把 5 个事实键写回台账 payload。
|
||||
* 返回**实际更新**的行数;任何失败抛错(由调用方决定吞不吞)。
|
||||
*/
|
||||
export async function pullAndSaveOrderActualFacts(params: {
|
||||
branchCode: string;
|
||||
ourOrderCode: string;
|
||||
}): Promise<{ updated: number; lookedUp: number }> {
|
||||
const branch = String(params.branchCode || '').trim();
|
||||
const orderCode = String(params.ourOrderCode || '').trim();
|
||||
if (!branch || !orderCode) return { updated: 0, lookedUp: 0 };
|
||||
|
||||
const rows = await pool.query<{ prep_id: string; main_order_code: string; main_sku_code: string | null }>(
|
||||
`SELECT prep_id::text AS prep_id, main_order_code, main_sku_code
|
||||
FROM public.main_system_order_import_items
|
||||
WHERE branch_code = $1 AND our_order_code = $2`,
|
||||
[branch, orderCode]
|
||||
);
|
||||
if (!rows.rows.length) return { updated: 0, lookedUp: 0 };
|
||||
|
||||
const items = rows.rows.map((row) => ({
|
||||
orderCode: String(row.main_order_code || ''),
|
||||
skuCode: row.main_sku_code ? String(row.main_sku_code) : '',
|
||||
id: String(row.prep_id),
|
||||
}));
|
||||
const outcome = await lookupMainSystemPreparationStates(branch, items);
|
||||
if (outcome.kind !== 'ok') {
|
||||
throw Object.assign(new Error(`主系统备货行查询失败:${outcome.reason || outcome.kind}`), {
|
||||
code: outcome.kind,
|
||||
});
|
||||
}
|
||||
|
||||
let updated = 0;
|
||||
for (const row of outcome.results) {
|
||||
const prepId = String(row.id || '').trim();
|
||||
if (!prepId || row.found !== true) continue;
|
||||
// ⚠️ 只覆盖这 5 个键:`payload || jsonb_build_object(...)` 右侧优先,其余键原样保留
|
||||
const res = await pool.query(
|
||||
`UPDATE public.main_system_order_import_items
|
||||
SET payload = payload || jsonb_build_object(
|
||||
'actualQty', $3::numeric,
|
||||
'actualQtyAt', $4::text,
|
||||
'qtyDiff', $5::numeric,
|
||||
'isInbounded', $6::boolean,
|
||||
'inboundAt', $7::text
|
||||
)
|
||||
WHERE branch_code = $1 AND prep_id = $2::uuid`,
|
||||
[
|
||||
branch,
|
||||
prepId,
|
||||
row.actualQty,
|
||||
row.actualQtyAt,
|
||||
row.qtyDiff,
|
||||
row.isInbounded === true,
|
||||
row.inboundAt,
|
||||
]
|
||||
);
|
||||
updated += res.rowCount || 0;
|
||||
}
|
||||
return { updated, lookedUp: outcome.results.length };
|
||||
}
|
||||
|
||||
/** 拉一次并回读(供 POST 刷新路由用);失败只记日志不抛 */
|
||||
export async function refreshOrderActualFacts(params: {
|
||||
branchCode: string;
|
||||
ourOrderCode: string;
|
||||
}): Promise<{ refreshed: boolean; reason?: string; items: PrepActualFact[] }> {
|
||||
let refreshed = false;
|
||||
let reason: string | undefined;
|
||||
try {
|
||||
await pullAndSaveOrderActualFacts(params);
|
||||
refreshed = true;
|
||||
} catch (error: unknown) {
|
||||
reason = (error as Error)?.message || String(error);
|
||||
console.error(
|
||||
`[main-system-actual-facts] ${params.branchCode} ${params.ourOrderCode} 刷新失败(用库内已有事实):`,
|
||||
reason
|
||||
);
|
||||
}
|
||||
const items = await listOrderActualFacts(params);
|
||||
return { refreshed, reason, items };
|
||||
}
|
||||
|
||||
/**
|
||||
* 定时兜底:给该分公司**在飞**(我方状态 30..60)且台账还没有核货事实的主系统单刷新一次。
|
||||
*
|
||||
* 为什么要兜底:开发者要在"核货完成"后看到标记,而事件通道对等量核货静默;只靠打开详情触发
|
||||
* 会让"没人打开就看不出"。每轮最多 `maxOrders` 单、每单一次 lookup,失败只日志。
|
||||
*/
|
||||
export async function refreshInFlightActualFactsForBranch(
|
||||
branchCode: string,
|
||||
options?: { maxOrders?: number }
|
||||
): Promise<{ orders: number; refreshed: number }> {
|
||||
const branch = String(branchCode || '').trim();
|
||||
if (!branch) return { orders: 0, refreshed: 0 };
|
||||
const maxOrders = Math.max(1, Number(options?.maxOrders) || 10);
|
||||
const candidates = await runWithTenantDbContext(branch, () =>
|
||||
pool.query<{ order_code: string }>(
|
||||
`SELECT o.order_code
|
||||
FROM orders o
|
||||
WHERE o.deleted_at IS NULL
|
||||
AND COALESCE(o.order_status, 0) BETWEEN 30 AND 60
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM public.main_system_order_import_items li
|
||||
WHERE li.branch_code = o.branch_code
|
||||
AND li.our_order_code = o.order_code
|
||||
AND COALESCE(li.payload->>'skipInbound', 'false') = 'true'
|
||||
AND li.payload->>'actualQty' IS NULL
|
||||
)
|
||||
ORDER BY o.updated_at DESC NULLS LAST
|
||||
LIMIT $1`,
|
||||
[maxOrders]
|
||||
)
|
||||
);
|
||||
let refreshed = 0;
|
||||
for (const row of candidates.rows) {
|
||||
try {
|
||||
const result = await pullAndSaveOrderActualFacts({
|
||||
branchCode: branch,
|
||||
ourOrderCode: String(row.order_code),
|
||||
});
|
||||
if (result.updated > 0) refreshed += 1;
|
||||
} catch (error: unknown) {
|
||||
console.error(
|
||||
`[main-system-actual-facts] ${branch} ${row.order_code} 兜底刷新失败:`,
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
}
|
||||
}
|
||||
return { orders: candidates.rows.length, refreshed };
|
||||
}
|
||||
|
||||
export const ACTUAL_FACT_PAYLOAD_KEYS = ACTUAL_FACT_KEYS;
|
||||
@@ -0,0 +1,324 @@
|
||||
import { pool } from '../db';
|
||||
import { runWithTenantDataAccess } from './tenantSchemaService';
|
||||
import { runWithTenantDbContext } from './tenantDbContext';
|
||||
import { adjustInboundInspectionQty } from './inspectionInboundQtyAdjust';
|
||||
import { ensureSkipInboundLoadingLines } from './skipInboundLoadingService';
|
||||
import { writeAuditLog } from './auditService';
|
||||
import { syncStatementsForOrderSafe } from './financeReconciliationService';
|
||||
|
||||
/**
|
||||
* 「同意同步」落值:把主系统的**实际值**写进我方自己的记录(2026-10-11 口径,设计文档
|
||||
* `docs/design/20261011-实收数量与单位的事后同步.md`)。
|
||||
*
|
||||
* 三条纪律(开发者原话):
|
||||
* ① **自己只能改自己的**:本模块只写我方数据,**绝不**回写主系统(回执由 inbox 负责);
|
||||
* ② **驳回不调用本模块**(我方零改动,只留痕);
|
||||
* ③ **计划量跟着实收一起改**("确保账一致")⇒ `order_items.quantity` 与 `amount` 一起重算。
|
||||
*
|
||||
* 分级(§4,开发者已批准):
|
||||
* · 免入库行(`skipInbound=true`)⇒ 改 `picking_items.loaded_qty`(我方装车核货量,不牵动库存);
|
||||
* · 送仓行 **未入库** ⇒ 改该验收行 `inspections.actual_qty`(无库存批次,安全);
|
||||
* · 送仓行 **已入库** ⇒ 走既有 `adjustInboundInspectionQty`(改实收 + 按差额调批次可用库存,
|
||||
* 备注必填、双日志),**不直改库存流水**;
|
||||
* · **已结算 / 已结案 90** ⇒ **不直改历史**,只记"需财务调整"结论 + 审计(自动接结算调整待财务面批准)。
|
||||
*/
|
||||
|
||||
export type ApplyOutcome = {
|
||||
/** applied=已落值;skipped_settled=已结算/结案,不直改;failed=落值失败(已记原因) */
|
||||
status: 'applied' | 'skipped_settled' | 'failed';
|
||||
/** 人类可读结论(写进台账 payload.apply.note,审核页可见) */
|
||||
note: string;
|
||||
/** 实际改动摘要(审计/排查用) */
|
||||
changes: string[];
|
||||
};
|
||||
|
||||
type OrderedItemRow = {
|
||||
id: string;
|
||||
quantity: string | number | null;
|
||||
price: string | number | null;
|
||||
amount: string | number | null;
|
||||
unit: string | null;
|
||||
sku_code: string | null;
|
||||
item_name: string | null;
|
||||
};
|
||||
|
||||
const round3 = (n: number) => Math.round(n * 1000) / 1000;
|
||||
const round2 = (n: number) => Math.round(n * 100) / 100;
|
||||
const num = (v: unknown): number | null => {
|
||||
if (v === null || v === undefined || v === '') return null;
|
||||
const n = Number(v);
|
||||
return Number.isFinite(n) ? n : null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 落值入口。**失败不抛**:回执已经发出去了,落值失败只能记录 + 交人工,
|
||||
* 绝不能把审核动作整体回滚(否则会出现"对方已收到同意、我方却没改"的静默不一致)。
|
||||
*/
|
||||
export async function applyActualQtySyncValue(params: {
|
||||
branchCode: string;
|
||||
ourOrderCode: string;
|
||||
prepId: string | null;
|
||||
field: 'qty' | 'unit' | 'price';
|
||||
/** 我方最终采用的值(approved 时 = final_value) */
|
||||
finalValue: number | null;
|
||||
unit?: string | null;
|
||||
requestRowId: string;
|
||||
reviewer?: string | null;
|
||||
}): Promise<ApplyOutcome> {
|
||||
const branchCode = String(params.branchCode || '').trim();
|
||||
const orderCode = String(params.ourOrderCode || '').trim();
|
||||
if (!branchCode || !orderCode) {
|
||||
return { status: 'failed', note: '缺少分公司或我方订单号,无法落值', changes: [] };
|
||||
}
|
||||
try {
|
||||
const order = await runWithTenantDbContext(branchCode, () =>
|
||||
pool.query<{ order_status: number | null; customer_code: string | null }>(
|
||||
`SELECT order_status, customer_code FROM orders WHERE order_code = $1 LIMIT 1`,
|
||||
[orderCode]
|
||||
)
|
||||
);
|
||||
if (!order.rowCount) return { status: 'failed', note: '我方订单不存在', changes: [] };
|
||||
const orderStatus = Number(order.rows[0]?.order_status) || 0;
|
||||
|
||||
/**
|
||||
* 台账行级对照:`prep_id` 是权威键(主系统请求必带)。
|
||||
* 没有 `prep_id` 时**按本单该行兜底查一次**(同一 `our_order_item_id` 或同 sku 的台账行);
|
||||
* 仍查不到 ⇒ **不落值**(宁可报"无法定位",也绝不瞎猜:猜错会写错验收实收/库存)。
|
||||
*/
|
||||
const ledger = params.prepId
|
||||
? await pool.query<{ our_order_item_id: string | null; skip_inbound: boolean; main_sku_code: string | null }>(
|
||||
`SELECT our_order_item_id::text AS our_order_item_id,
|
||||
COALESCE(payload->>'skipInbound', 'false') = 'true' AS skip_inbound,
|
||||
main_sku_code
|
||||
FROM public.main_system_order_import_items
|
||||
WHERE branch_code = $1 AND prep_id = $2::uuid LIMIT 1`,
|
||||
[branchCode, params.prepId]
|
||||
)
|
||||
: { rows: [] as Array<{ our_order_item_id: string | null; skip_inbound: boolean; main_sku_code: string | null }> };
|
||||
if (!ledger.rows[0]) {
|
||||
return {
|
||||
status: 'failed',
|
||||
note: '台账里找不到该备货行的对照(prep_id 缺失或未导入)⇒ 未落值,请人工核对',
|
||||
changes: [],
|
||||
};
|
||||
}
|
||||
const skipInbound = ledger.rows[0].skip_inbound === true;
|
||||
const ourItemId = ledger.rows[0].our_order_item_id ? String(ledger.rows[0].our_order_item_id) : null;
|
||||
|
||||
const items = await runWithTenantDbContext(branchCode, () =>
|
||||
pool.query<OrderedItemRow>(
|
||||
`SELECT id::text AS id, quantity, price, amount, unit, sku_code, item_name
|
||||
FROM order_items WHERE order_code = $1 AND id = $2::uuid LIMIT 1`,
|
||||
[orderCode, ourItemId]
|
||||
)
|
||||
);
|
||||
const item = items.rows[0];
|
||||
if (!item) {
|
||||
return { status: 'failed', note: '台账对照指向的我方订单行不存在(可能已被删行)⇒ 未落值', changes: [] };
|
||||
}
|
||||
|
||||
// 已结算 / 已结案:不直改历史(财务冻结面)
|
||||
const settled = await runWithTenantDbContext(branchCode, () =>
|
||||
pool.query<{ n: number }>(
|
||||
`SELECT count(*)::int AS n FROM customer_statements WHERE order_code = $1`,
|
||||
[orderCode]
|
||||
)
|
||||
).catch(() => ({ rows: [{ n: 0 }] }));
|
||||
if (Number(settled.rows[0]?.n || 0) > 0 || orderStatus >= 90) {
|
||||
const note =
|
||||
Number(settled.rows[0]?.n || 0) > 0
|
||||
? '该单已生成客户结算单:按分级规则不直改历史,需走财务调整(本次只留痕)'
|
||||
: `订单已结案(${orderStatus}):按分级规则不直改历史,需走财务调整(本次只留痕)`;
|
||||
await writeAudit({
|
||||
params,
|
||||
branchCode,
|
||||
orderCode,
|
||||
changes: [note],
|
||||
status: 'skipped_settled',
|
||||
itemId: String(item.id),
|
||||
before: { quantity: num(item.quantity), amount: num(item.amount) },
|
||||
});
|
||||
return { status: 'skipped_settled', note, changes: [note] };
|
||||
}
|
||||
|
||||
const changes: string[] = [];
|
||||
const targetQty = params.field === 'qty' ? params.finalValue : null;
|
||||
const targetUnit = params.field === 'unit' ? (params.unit || null) : null;
|
||||
|
||||
// ① 实收落点
|
||||
if (skipInbound) {
|
||||
// 免入库单的核货行是**惰性补建**的(`ensureSkipInboundLoadingLines`,幂等):订单若还没进过
|
||||
// "装车核货"页就没有 picking_items 行,实收无处可落 ⇒ 先补行再写值。
|
||||
// 它内部会调 `ensureDeliveryTaskForOrder`,而免入库单已被守卫挡住(不建我方配送任务)✓
|
||||
// `includeAllItems: true`:本单的"免入库"结论来自**主系统台账**(比本地 suppliers 标记更权威),
|
||||
// 所以不再依赖本地的免入库/备货完成条件去筛行 —— 否则本地没有备货行/供应商档案时一行都补不出来。
|
||||
// ⚠️ 必须在**租户上下文内**调用(它内部查 order_items/supplier_preparations 等租户表,
|
||||
// 缺上下文会报 `relation "order_items" does not exist`;2026-10-11 实测踩到)
|
||||
await runWithTenantDbContext(branchCode, () =>
|
||||
ensureSkipInboundLoadingLines(orderCode, undefined, { includeAllItems: true })
|
||||
).catch(
|
||||
(error: unknown) => {
|
||||
console.error(
|
||||
`[main-system-actual-qty] ${branchCode} ${orderCode} 补核货行失败(继续尝试写值):`,
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
}
|
||||
);
|
||||
if (targetQty !== null) {
|
||||
const updated = await runWithTenantDataAccess(branchCode, async (client) =>
|
||||
client.query(
|
||||
`UPDATE picking_items SET loaded_qty = $2
|
||||
WHERE order_item_id = $1::uuid
|
||||
RETURNING id`,
|
||||
[String(item.id), round3(targetQty)]
|
||||
)
|
||||
);
|
||||
changes.push(
|
||||
updated.rowCount
|
||||
? `装车核货量 loaded_qty → ${round3(targetQty)}(${updated.rowCount} 行)`
|
||||
: '装车核货行不存在,实收未落(仅改订单行)'
|
||||
);
|
||||
}
|
||||
if (targetUnit) {
|
||||
await runWithTenantDataAccess(branchCode, async (client) =>
|
||||
client.query(`UPDATE picking_items SET unit = $2 WHERE order_item_id = $1::uuid`, [
|
||||
String(item.id),
|
||||
targetUnit,
|
||||
])
|
||||
);
|
||||
changes.push(`装车核货单位 → ${targetUnit}`);
|
||||
}
|
||||
} else if (targetQty !== null || targetUnit) {
|
||||
const sku = item.sku_code ? String(item.sku_code) : '';
|
||||
const inbound = sku
|
||||
? await runWithTenantDbContext(branchCode, () =>
|
||||
pool.query<{ n: number }>(
|
||||
`SELECT count(*)::int AS n FROM inspections
|
||||
WHERE order_code = $1 AND sku_code IS NOT DISTINCT FROM $2
|
||||
AND actual_qty IS NOT NULL AND inbound_batch_no IS NOT NULL`,
|
||||
[orderCode, sku]
|
||||
)
|
||||
)
|
||||
: { rows: [{ n: 0 }] };
|
||||
const alreadyInbound = Number(inbound.rows[0]?.n || 0) > 0;
|
||||
if (targetQty !== null && alreadyInbound) {
|
||||
// 既有服务:改验收实收 + 按差额调批次可用库存(备注必填、双日志)
|
||||
const outcome = await adjustInboundInspectionQty({
|
||||
orderCode,
|
||||
skuCode: sku,
|
||||
qty: round3(targetQty),
|
||||
branchCode,
|
||||
operatorId: params.reviewer ?? null,
|
||||
remark: `跟随主系统实际值同步(申请 ${params.requestRowId})`,
|
||||
});
|
||||
changes.push(
|
||||
outcome === 'updated'
|
||||
? `验收入库实收 → ${round3(targetQty)}(并已按差额调整批次可用库存)`
|
||||
: `验收入库实收 → ${round3(targetQty)}(⚠️ 未找到对应库存批次,库存未调整)`
|
||||
);
|
||||
} else if (targetQty !== null) {
|
||||
// 未入库:直接改该单最新一条验收的实收(无库存批次 ⇒ 不牵动库存)
|
||||
const qtyValue = round3(targetQty);
|
||||
const updated = await runWithTenantDataAccess(branchCode, async (client) =>
|
||||
client.query(
|
||||
`UPDATE inspections SET actual_qty = $3
|
||||
WHERE id = (SELECT id FROM inspections
|
||||
WHERE order_code = $1 AND sku_code IS NOT DISTINCT FROM $2
|
||||
ORDER BY inspection_time DESC NULLS LAST, created_at DESC LIMIT 1)
|
||||
RETURNING id`,
|
||||
[orderCode, sku || null, qtyValue]
|
||||
)
|
||||
);
|
||||
changes.push(
|
||||
updated.rowCount
|
||||
? `验收实收 → ${qtyValue}(未入库,无库存影响)`
|
||||
: '未找到验收行,实收未落(仅改订单行)'
|
||||
);
|
||||
}
|
||||
if (targetUnit) {
|
||||
await runWithTenantDataAccess(branchCode, async (client) =>
|
||||
client.query(
|
||||
`UPDATE inspections SET unit = $3
|
||||
WHERE id = (SELECT id FROM inspections WHERE order_code = $1 AND sku_code IS NOT DISTINCT FROM $2
|
||||
ORDER BY inspection_time DESC NULLS LAST, created_at DESC LIMIT 1)`,
|
||||
[orderCode, sku || null, targetUnit]
|
||||
)
|
||||
);
|
||||
changes.push(`验收单位 → ${targetUnit}`);
|
||||
}
|
||||
}
|
||||
|
||||
// ② 计划量 + 金额("计划量跟着实收一起变动,确保账一致")
|
||||
const beforeQty = num(item.quantity);
|
||||
const price = num(item.price);
|
||||
const nextQty: number | null = targetQty !== null ? round3(targetQty) : beforeQty;
|
||||
const nextAmount: number | null =
|
||||
nextQty !== null && price !== null ? round2(nextQty * price) : num(item.amount);
|
||||
const nextUnit = targetUnit || item.unit;
|
||||
if (nextQty !== null && (nextQty !== beforeQty || nextUnit !== item.unit)) {
|
||||
await runWithTenantDataAccess(branchCode, async (client) =>
|
||||
client.query(`UPDATE order_items SET quantity = $2, amount = $3, unit = $4 WHERE id = $1::uuid`, [
|
||||
String(item.id),
|
||||
nextQty,
|
||||
nextAmount,
|
||||
nextUnit,
|
||||
])
|
||||
);
|
||||
changes.push(
|
||||
`订单行:计划量 ${beforeQty ?? '—'} → ${nextQty}${nextUnit ? ` ${nextUnit}` : ''}、金额 → ${nextAmount ?? '—'}`
|
||||
);
|
||||
/**
|
||||
* ⚠️ **结算单是订单的投影**(2026-09-24 开发者口径,`orderSaleChangeSyncsStatements.test.ts` 钉住):
|
||||
* 凡改订单行销售字段(quantity/amount/price),必须同步重建客户 + 供应商结算投影,
|
||||
* 否则结算停在旧值。本函数只改"未结算、未结案"的单(已结算走 skipped_settled 分支),
|
||||
* 所以这里的同步会正常生效;同步失败内部已 catch(不阻断落值)。
|
||||
*/
|
||||
await syncStatementsForOrderSafe(orderCode, null);
|
||||
}
|
||||
|
||||
await writeAudit({
|
||||
params,
|
||||
branchCode,
|
||||
orderCode,
|
||||
changes,
|
||||
status: 'applied',
|
||||
itemId: String(item.id),
|
||||
before: { quantity: beforeQty, amount: num(item.amount), unit: item.unit },
|
||||
});
|
||||
return { status: 'applied', note: changes.join(';') || '无字段变化', changes };
|
||||
} catch (error: unknown) {
|
||||
const message = (error as Error)?.message || String(error);
|
||||
console.error(
|
||||
`[main-system-actual-qty] ${branchCode} ${orderCode} 同意同步落值失败(回执已发,交人工):`,
|
||||
message
|
||||
);
|
||||
return { status: 'failed', note: `落值失败(回执已发,请人工核对):${message}`, changes: [] };
|
||||
}
|
||||
}
|
||||
|
||||
async function writeAudit(input: {
|
||||
params: { requestRowId: string; field: string; finalValue: number | null; reviewer?: string | null };
|
||||
branchCode: string;
|
||||
orderCode: string;
|
||||
changes: string[];
|
||||
status: ApplyOutcome['status'];
|
||||
itemId: string;
|
||||
before: Record<string, unknown>;
|
||||
}): Promise<void> {
|
||||
await writeAuditLog({
|
||||
operatorId: input.params.reviewer ?? null,
|
||||
operatorRole: 'supplier_reviewer',
|
||||
operationType: `main_system_actual_qty_sync_${input.status}`,
|
||||
targetTable: 'order_items',
|
||||
targetId: input.itemId,
|
||||
oldValue: { ...input.before, order_code: input.orderCode },
|
||||
newValue: {
|
||||
field: input.params.field,
|
||||
final_value: input.params.finalValue,
|
||||
request_row_id: input.params.requestRowId,
|
||||
changes: input.changes,
|
||||
},
|
||||
branchCode: input.branchCode,
|
||||
actionCategory: 'order',
|
||||
}).catch(() => undefined);
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
/**
|
||||
* 「实收数量 / 单位」申请的**接收端**(对方发起 → 我方审核)。
|
||||
*
|
||||
* 主系统提交 `b8519fbb` 已交付(事件 `preparations.actual_qty_request` + 反向决策接口)。
|
||||
* 定稿语义(开发者 2026-10-11,见 docs/给主系统AI的对接改造清单.md §4.9/§4.10/§4.11):
|
||||
* · **核货节点** = 事实登记:对方值已落库,发申请只为**告知**;我方通过 ⇒ 台账对齐;
|
||||
* 带 final_value 通过 ⇒ 对方按协商值改写;我方**驳回 ⇒ 对方不回滚**(`fact_registered=true`)。
|
||||
* · **order_status >= 60**(配送中及以后改实收/单位)与 **>= 90**(完结后改成本价)
|
||||
* = 先审后改:pending 期间两边都不落库,批准按 `final_value ?? proposed_value` 落地,驳回什么都不改。
|
||||
*
|
||||
* 幂等键 = 对方的 `request_id`(同一分公司内唯一)。业务失败不抛错(webhook 不可重放,重试交给对方/对账)。
|
||||
*/
|
||||
import { pool } from '../db';
|
||||
import { writeAuditLog } from './auditService';
|
||||
import { applyActualQtySyncValue } from './mainSystemActualQtyApply';
|
||||
import { postMainSystemActualQtyDecision } from './mainSystem/api/preparations';
|
||||
|
||||
export type ActualQtyInboxRow = {
|
||||
id: string;
|
||||
branch_code: string;
|
||||
request_id: string;
|
||||
prep_id: string | null;
|
||||
order_code: string | null;
|
||||
our_order_code: string | null;
|
||||
sku_code: string | null;
|
||||
node: string;
|
||||
field: 'qty' | 'unit' | 'price';
|
||||
before_value: string | number | null;
|
||||
proposed_value: string | number | null;
|
||||
before_unit: string | null;
|
||||
unit: string | null;
|
||||
operator: string | null;
|
||||
reason: string | null;
|
||||
client_request_id: string | null;
|
||||
status: 'pending' | 'approved' | 'rejected' | 'superseded';
|
||||
final_value: string | number | null;
|
||||
reviewer: string | null;
|
||||
decided_at: string | null;
|
||||
decision_reason: string | null;
|
||||
fact_registered: boolean;
|
||||
/** 主系统实际值在其侧生效的时刻(新口径"事实登记"的时间锚点;NULL = 对方未提供) */
|
||||
applied_at: string | null;
|
||||
payload: unknown;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
};
|
||||
|
||||
/** 主系统申请行 id 的形态(UUID) */
|
||||
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
const num = (v: unknown): number | null => {
|
||||
if (v === null || v === undefined || v === '') return null;
|
||||
const n = Number(v);
|
||||
return Number.isFinite(n) ? n : null;
|
||||
};
|
||||
|
||||
/**
|
||||
* **事实登记**节点:这些节点的 `proposed_value` 是对方**已经生效**的实际值
|
||||
* (新口径 2026-10-11:对方先改自己的记录再发请求)⇒ 我方**驳回也只留痕、不让对方回滚**。
|
||||
*
|
||||
* · `picking_check`:免入库单,主系统配送员核货("核货多少就是多少");
|
||||
* · `inbound` :送仓单,主系统**入库核查**后的实际入库实收。
|
||||
*
|
||||
* 见 docs/design/20261011-实收数量与单位的事后同步.md §4。
|
||||
*/
|
||||
const FACT_NODES = new Set(['picking_check', 'inbound']);
|
||||
|
||||
/** 事件载荷 → 台账字段(字段名以对方 §4.10 的 12 个为准) */
|
||||
export function mapActualQtyRequestPayload(payload: any) {
|
||||
const fieldRaw = String(payload?.field || 'qty').toLowerCase();
|
||||
const field = fieldRaw === 'unit' ? 'unit' : fieldRaw === 'price' ? 'price' : 'qty';
|
||||
const node = String(payload?.node || '').trim() || 'picking_check';
|
||||
return {
|
||||
requestId: String(payload?.request_id || '').trim(),
|
||||
prepId: payload?.preparation_id != null ? String(payload.preparation_id) : payload?.prep_id != null ? String(payload.prep_id) : null,
|
||||
orderCode: payload?.order_code != null ? String(payload.order_code) : null,
|
||||
skuCode: payload?.sku_code != null ? String(payload.sku_code) : null,
|
||||
node,
|
||||
field: field as 'qty' | 'unit' | 'price',
|
||||
beforeValue: num(payload?.before_value),
|
||||
proposedValue: num(payload?.proposed_value),
|
||||
beforeUnit: payload?.before_unit != null ? String(payload.before_unit) : null,
|
||||
unit: payload?.unit != null ? String(payload.unit) : null,
|
||||
operator: payload?.operator != null ? String(payload.operator) : null,
|
||||
reason: payload?.reason != null ? String(payload.reason) : null,
|
||||
clientRequestId: payload?.client_request_id != null ? String(payload.client_request_id) : null,
|
||||
appliedAt:
|
||||
payload?.applied_at != null && String(payload.applied_at).trim()
|
||||
? String(payload.applied_at).trim()
|
||||
: null,
|
||||
factRegistered: FACT_NODES.has(node),
|
||||
};
|
||||
}
|
||||
|
||||
export type RecordOutcome = { status: 'recorded' | 'duplicate' | 'ignored'; reason: string; rowId: string | null };
|
||||
|
||||
/** 落库(幂等:同分公司 + 同 request_id 只落一条;重复投递返回 duplicate,不覆盖已审结论) */
|
||||
export async function recordActualQtyRequest(params: {
|
||||
branchCode: string;
|
||||
payload: any;
|
||||
}): Promise<RecordOutcome> {
|
||||
const branchCode = String(params.branchCode || '').trim();
|
||||
if (!branchCode) return { status: 'ignored', reason: '缺少分公司', rowId: null };
|
||||
const mapped = mapActualQtyRequestPayload(params.payload);
|
||||
if (!mapped.requestId) return { status: 'ignored', reason: '缺少 request_id', rowId: null };
|
||||
// 形态校验(2026-10-11 联调发现):主系统的 request_id 是**申请行 UUID**;
|
||||
// 非 UUID 说明载荷异常(或对端未校验),直接忽略、不入待审队列 ——
|
||||
// 否则会把脏 id 排进队列,审核回传时对端还会抛 PG 22P02。
|
||||
if (!UUID_RE.test(mapped.requestId)) {
|
||||
return { status: 'ignored', reason: `request_id 非 UUID,已忽略:${mapped.requestId.slice(0, 40)}`, rowId: null };
|
||||
}
|
||||
|
||||
const existing = await pool.query<{ id: string; status: string }>(
|
||||
`SELECT id, status FROM public.main_system_actual_qty_requests
|
||||
WHERE branch_code = $1 AND request_id = $2 LIMIT 1`,
|
||||
[branchCode, mapped.requestId]
|
||||
);
|
||||
if (existing.rowCount) {
|
||||
return { status: 'duplicate', reason: `已存在(${existing.rows[0].status})`, rowId: String(existing.rows[0].id) };
|
||||
}
|
||||
|
||||
// 关联我方订单(有 prep 台账就带上我们的单号,便于界面直接跳转)
|
||||
let ourOrderCode: string | null = null;
|
||||
if (mapped.prepId) {
|
||||
const link = await pool.query<{ our_order_code: string | null }>(
|
||||
`SELECT our_order_code FROM public.main_system_order_import_items
|
||||
WHERE branch_code = $1 AND prep_id = $2::uuid LIMIT 1`,
|
||||
[branchCode, mapped.prepId]
|
||||
);
|
||||
ourOrderCode = link.rows[0]?.our_order_code ? String(link.rows[0].our_order_code) : null;
|
||||
}
|
||||
|
||||
const inserted = await pool.query<ActualQtyInboxRow>(
|
||||
`INSERT INTO public.main_system_actual_qty_requests
|
||||
(branch_code, request_id, prep_id, order_code, our_order_code, sku_code, node, field,
|
||||
before_value, proposed_value, before_unit, unit, operator, reason, client_request_id,
|
||||
status, fact_registered, applied_at, payload)
|
||||
VALUES ($1,$2,$3::uuid,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,'pending',$16,$17::timestamptz,$18::jsonb)
|
||||
ON CONFLICT (branch_code, request_id) DO NOTHING
|
||||
RETURNING *`,
|
||||
[
|
||||
branchCode, mapped.requestId, mapped.prepId, mapped.orderCode, ourOrderCode, mapped.skuCode,
|
||||
mapped.node, mapped.field, mapped.beforeValue, mapped.proposedValue, mapped.beforeUnit,
|
||||
mapped.unit, mapped.operator, mapped.reason, mapped.clientRequestId,
|
||||
mapped.factRegistered, mapped.appliedAt, JSON.stringify(params.payload ?? null),
|
||||
]
|
||||
);
|
||||
const row = inserted.rows[0];
|
||||
if (!row) return { status: 'duplicate', reason: '并发重复', rowId: null };
|
||||
|
||||
await writeAuditLog({
|
||||
operatorId: null,
|
||||
operatorRole: 'main_system',
|
||||
operationType: 'main_system_actual_qty_request_received',
|
||||
targetTable: 'main_system_actual_qty_requests',
|
||||
targetId: row.id,
|
||||
oldValue: { field: row.field, before_value: row.before_value, before_unit: row.before_unit },
|
||||
newValue: {
|
||||
field: row.field,
|
||||
proposed_value: row.proposed_value,
|
||||
unit: row.unit,
|
||||
node: row.node,
|
||||
fact_registered: row.fact_registered,
|
||||
applied_at: row.applied_at,
|
||||
order_code: row.order_code,
|
||||
operator: row.operator,
|
||||
},
|
||||
branchCode,
|
||||
actionCategory: 'order',
|
||||
}).catch(() => undefined);
|
||||
|
||||
return {
|
||||
status: 'recorded',
|
||||
reason: mapped.factRegistered
|
||||
? '事实登记(对方已先改自己的实际值;驳回不回滚)'
|
||||
: '非事实登记节点(按先审后改处理)',
|
||||
rowId: row.id,
|
||||
};
|
||||
}
|
||||
|
||||
/** 待审/已审列表(界面用) */
|
||||
export async function listActualQtyInbox(params: {
|
||||
branchCode: string;
|
||||
status?: string | null;
|
||||
limit?: number;
|
||||
}): Promise<ActualQtyInboxRow[]> {
|
||||
const args: unknown[] = [params.branchCode];
|
||||
const where = ['branch_code = $1'];
|
||||
if (params.status) {
|
||||
args.push(params.status);
|
||||
where.push(`status = $${args.length}`);
|
||||
}
|
||||
args.push(Math.min(Math.max(Number(params.limit) || 100, 1), 500));
|
||||
const result = await pool.query<ActualQtyInboxRow & { item_name?: string | null }>(
|
||||
`SELECT r.*, i.item_name
|
||||
FROM public.main_system_actual_qty_requests r
|
||||
LEFT JOIN public.main_system_order_import_items i
|
||||
ON i.branch_code = r.branch_code AND i.prep_id = r.prep_id
|
||||
WHERE ${where.map((w) => w.replace(/branch_code/, 'r.branch_code').replace(/status/, 'r.status')).join(' AND ')}
|
||||
ORDER BY r.created_at DESC LIMIT $${args.length}`,
|
||||
args
|
||||
);
|
||||
return result.rows;
|
||||
}
|
||||
|
||||
export type DecideOutcome = {
|
||||
status: 'done' | 'ignored' | 'suspended';
|
||||
reason: string;
|
||||
requestRowId: string | null;
|
||||
duplicate: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* 我方审核结论 → 回传主系统(`POST /api/supplier/preparations/actual-qty-decision`)。
|
||||
*
|
||||
* · `approved`:带 `finalValue` 则按协商值落地,否则以对方 proposed 为准;
|
||||
* · `rejected`:**什么都不改**(核货节点连对方也不回滚——那是事实登记);
|
||||
* · 幂等:本地已终态 ⇒ 不再回传(`duplicate=true`)。
|
||||
*/
|
||||
export async function decideActualQtyRequest(params: {
|
||||
branchCode: string;
|
||||
rowId: string;
|
||||
decision: 'approved' | 'rejected';
|
||||
finalValue?: number | null;
|
||||
reviewer?: string | null;
|
||||
reason?: string | null;
|
||||
}): Promise<DecideOutcome> {
|
||||
const branchCode = String(params.branchCode || '').trim();
|
||||
const found = await pool.query<ActualQtyInboxRow>(
|
||||
`SELECT * FROM public.main_system_actual_qty_requests
|
||||
WHERE branch_code = $1 AND id = $2::uuid LIMIT 1`,
|
||||
[branchCode, params.rowId]
|
||||
);
|
||||
const row = found.rows[0];
|
||||
if (!row) return { status: 'ignored', reason: '申请不存在', requestRowId: null, duplicate: false };
|
||||
if (row.status !== 'pending') {
|
||||
return { status: 'done', reason: `已是终态 ${row.status}`, requestRowId: row.id, duplicate: true };
|
||||
}
|
||||
|
||||
// 对方已先落库的事实登记(核货):驳回只改我们的台账结论,不让对方回滚
|
||||
const decidedAt = new Date().toISOString();
|
||||
const finalValue =
|
||||
params.decision === 'approved'
|
||||
? (params.finalValue ?? num(row.proposed_value))
|
||||
: null;
|
||||
|
||||
const sent = await postMainSystemActualQtyDecision({
|
||||
supplierCode: branchCode,
|
||||
requestId: String(row.request_id),
|
||||
decision: params.decision,
|
||||
finalValue: typeof finalValue === 'number' ? finalValue : null,
|
||||
reviewer: params.reviewer ?? null,
|
||||
decidedAt,
|
||||
reason: params.reason ?? null,
|
||||
});
|
||||
if (sent.kind !== 'ok') {
|
||||
return {
|
||||
status: 'suspended',
|
||||
reason: `回传主系统失败,未改本地结论:${sent.reason}`,
|
||||
requestRowId: row.id,
|
||||
duplicate: false,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 同意 ⇒ **只改我方自己的记录**(2026-10-11 口径:对方已先改自己的实际值,我方决定是否同步)。
|
||||
* 落点与分级见 `mainSystemActualQtyApply.ts`;**驳回不落值**(只留痕)。
|
||||
* ⚠️ 必须先回执成功再落值(上面的 `sent.kind !== 'ok'` 早退已保证);落值失败不回滚回执,
|
||||
* 只把结论记进台账 payload.apply,交人工核对。
|
||||
*/
|
||||
let applyNote: string | null = null;
|
||||
let applyStatus: string | null = null;
|
||||
if (params.decision === 'approved' && row.our_order_code) {
|
||||
const applyOutcome = await applyActualQtySyncValue({
|
||||
branchCode,
|
||||
ourOrderCode: String(row.our_order_code),
|
||||
prepId: row.prep_id ? String(row.prep_id) : null,
|
||||
field: row.field,
|
||||
finalValue: typeof finalValue === 'number' ? finalValue : null,
|
||||
unit: row.unit,
|
||||
requestRowId: String(row.id),
|
||||
reviewer: params.reviewer ?? null,
|
||||
});
|
||||
applyNote = applyOutcome.note;
|
||||
applyStatus = applyOutcome.status;
|
||||
} else if (params.decision === 'approved') {
|
||||
applyNote = '未关联到本系统订单(台账无对照),本次只回执、未落值';
|
||||
applyStatus = 'failed';
|
||||
}
|
||||
|
||||
await pool.query(
|
||||
`UPDATE public.main_system_actual_qty_requests
|
||||
SET status = $3, final_value = $4, reviewer = $5, decided_at = $6, decision_reason = $7,
|
||||
payload = COALESCE(payload, '{}'::jsonb) || jsonb_build_object(
|
||||
'apply', jsonb_build_object('status', $8::text, 'note', $9::text, 'at', NOW())
|
||||
),
|
||||
updated_at = NOW()
|
||||
WHERE branch_code = $1 AND id = $2::uuid`,
|
||||
[
|
||||
branchCode,
|
||||
row.id,
|
||||
params.decision,
|
||||
finalValue,
|
||||
params.reviewer ?? null,
|
||||
decidedAt,
|
||||
params.reason ?? null,
|
||||
applyStatus,
|
||||
applyNote,
|
||||
]
|
||||
);
|
||||
await writeAuditLog({
|
||||
operatorId: params.reviewer ?? null,
|
||||
operatorRole: 'supplier_reviewer',
|
||||
operationType:
|
||||
params.decision === 'approved'
|
||||
? 'main_system_actual_qty_request_approved'
|
||||
: 'main_system_actual_qty_request_rejected',
|
||||
targetTable: 'main_system_actual_qty_requests',
|
||||
targetId: row.id,
|
||||
oldValue: { before_value: row.before_value, before_unit: row.before_unit, status: 'pending' },
|
||||
newValue: {
|
||||
field: row.field,
|
||||
proposed_value: row.proposed_value,
|
||||
final_value: finalValue,
|
||||
node: row.node,
|
||||
fact_registered: row.fact_registered,
|
||||
applied_at: row.applied_at,
|
||||
apply_status: applyStatus,
|
||||
apply_note: applyNote,
|
||||
reason: params.reason ?? null,
|
||||
},
|
||||
branchCode,
|
||||
actionCategory: 'order',
|
||||
}).catch(() => undefined);
|
||||
|
||||
return {
|
||||
status: 'done',
|
||||
reason:
|
||||
params.decision === 'approved'
|
||||
? `已同步到本系统(最终值 ${finalValue ?? '—'})${applyNote ? `|${applyNote}` : ''}`
|
||||
: row.fact_registered
|
||||
? '已驳回(对方为事实登记,不回滚;我方不做修改,仅留痕)'
|
||||
: '已驳回(双方均不改值)',
|
||||
requestRowId: row.id,
|
||||
duplicate: false,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,408 @@
|
||||
import { pool } from '../db';
|
||||
import { config } from '../config';
|
||||
import { runWithTenantDbContext } from './tenantDbContext';
|
||||
import {
|
||||
completeOrderWithoutDriverDelivery,
|
||||
finalizeOrderFulfillment,
|
||||
} from './orderWorkflowFulfillmentService';
|
||||
import { lookupMainSystemPreparationStates } from './mainSystemPreparations';
|
||||
import { recordPrepActualQty } from './mainSystemPrepLedger';
|
||||
import type { MainPreparationRow } from './mainSystemPreparations';
|
||||
|
||||
/**
|
||||
* 主系统**履约事件**接收端(2026-10-10)。
|
||||
*
|
||||
* 上游:主系统提交 `1447ea08` 交付两个新 webhook 事件(其设计文档
|
||||
* `ai-fresh-delivery/docs/design/20261010-supplier-prep-fulfillment-events.md`):
|
||||
* · `preparations.picked_up` 免入库:主系统**确认发车**(50→60),货已被取走
|
||||
* · `preparations.inbound_completed` 送仓:该供应商在本单的备货行**全部入库覆盖**
|
||||
*
|
||||
* 两条铁律(开发者 2026-10-10 口径,见给主系统的清单 §0.1):
|
||||
* ① **两个系统绝不互相改数据**:本模块**只读**主系统的事实、只写**我方自己**的订单状态与台账;
|
||||
* **零反向写回**(同意/拒绝改量都不回传)。
|
||||
* ② **实收量 ≠ 申报量是常态**:差异走台账(`recordPrepActualQty`),是否补库存由人工裁决,
|
||||
* 我方展示一律按实收量;**绝不因为实收少了就不收口**。
|
||||
*
|
||||
* 幂等:主系统侧**不做持久去重**(其回执 §2.1 明说),所以幂等由
|
||||
* `public.main_system_fulfillment_events` 的 `UNIQUE (branch_code, event, main_order_code)` 兜住。
|
||||
*
|
||||
* 见 docs/design/20261010-第三方订单履约事件接收端与免入库回写时机.md。
|
||||
*/
|
||||
|
||||
export type FulfillmentEventName = 'preparations.picked_up' | 'preparations.inbound_completed';
|
||||
|
||||
export const PREP_PICKED_UP_EVENT: FulfillmentEventName = 'preparations.picked_up';
|
||||
export const PREP_INBOUND_COMPLETED_EVENT: FulfillmentEventName = 'preparations.inbound_completed';
|
||||
|
||||
const FULFILLMENT_EVENTS: readonly string[] = [PREP_PICKED_UP_EVENT, PREP_INBOUND_COMPLETED_EVENT];
|
||||
|
||||
export function isFulfillmentEvent(event: unknown): event is FulfillmentEventName {
|
||||
return FULFILLMENT_EVENTS.includes(String(event || ''));
|
||||
}
|
||||
|
||||
export function isFulfillmentEventsEnabled(): boolean {
|
||||
return config.mainSystemIntegration.fulfillmentEventsEnabled;
|
||||
}
|
||||
|
||||
/** 收口结果;`status` 直接落事件台账。 */
|
||||
export type FulfillmentOutcome = {
|
||||
status: 'done' | 'suspended' | 'ignored';
|
||||
ourOrderCode: string | null;
|
||||
reason: string | null;
|
||||
};
|
||||
|
||||
/** 我方订单号:整单台账(合并后多张主系统单可指向同一张我方单) */
|
||||
async function findOurOrderCode(branchCode: string, mainOrderCode: string): Promise<string | null> {
|
||||
const result = await pool.query<{ our_order_code: string | null }>(
|
||||
`SELECT our_order_code
|
||||
FROM public.main_system_order_imports
|
||||
WHERE branch_code = $1 AND main_order_code = $2
|
||||
LIMIT 1`,
|
||||
[branchCode, mainOrderCode]
|
||||
);
|
||||
const code = result.rows[0]?.our_order_code;
|
||||
return code ? String(code) : null;
|
||||
}
|
||||
|
||||
async function readOurOrderStatus(branchCode: string, ourOrderCode: string): Promise<number | null> {
|
||||
const result = await runWithTenantDbContext(branchCode, () =>
|
||||
pool.query<{ order_status: number | null }>(
|
||||
`SELECT order_status FROM orders WHERE order_code = $1 AND deleted_at IS NULL LIMIT 1`,
|
||||
[ourOrderCode]
|
||||
)
|
||||
);
|
||||
const value = result.rows[0]?.order_status;
|
||||
return value === null || value === undefined ? null : Number(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 收口内核:**webhook 与对账兜底共用**(避免两条路径分叉)。
|
||||
*
|
||||
* 前置与入口由事件类型决定,两者都是既有结案入口,**不新增状态边、不改状态常量**:
|
||||
* · `picked_up`:我方停在 **50 待配送** ⇒ `completeOrderWithoutDriverDelivery`(接受 30/50)
|
||||
* · `inbound_completed`:我方已发车送仓至 **60** ⇒ `finalizeOrderFulfillment`(接受 60)
|
||||
*
|
||||
* 前置未满足 ⇒ `suspended`(下轮重试),**绝不越级改状态**。
|
||||
*/
|
||||
export async function concludeByFulfillmentEvent(params: {
|
||||
branchCode: string;
|
||||
event: FulfillmentEventName;
|
||||
ourOrderCode: string;
|
||||
}): Promise<FulfillmentOutcome> {
|
||||
const { branchCode, event, ourOrderCode } = params;
|
||||
const status = await readOurOrderStatus(branchCode, ourOrderCode);
|
||||
if (status === null) {
|
||||
return { status: 'ignored', ourOrderCode, reason: '我方订单不存在或已删除' };
|
||||
}
|
||||
if (status >= 90) {
|
||||
// 幂等命中:订单已结案(可能是上一次收口成功、或走了别的结案路径)
|
||||
return { status: 'done', ourOrderCode, reason: `订单已是 ${status},无需重复收口` };
|
||||
}
|
||||
|
||||
if (event === PREP_PICKED_UP_EVENT) {
|
||||
if (status === 50) {
|
||||
await runWithTenantDbContext(branchCode, () => completeOrderWithoutDriverDelivery(ourOrderCode));
|
||||
return { status: 'done', ourOrderCode, reason: '主系统确认发车 ⇒ 免入库订单收口' };
|
||||
}
|
||||
if (status >= 60) {
|
||||
// 我方已发车(例如对账提前推过)⇒ 走配送签收口径结案,结果一致
|
||||
await runWithTenantDbContext(branchCode, () => finalizeOrderFulfillment(ourOrderCode));
|
||||
return { status: 'done', ourOrderCode, reason: `订单已 ${status},按配送完成收口` };
|
||||
}
|
||||
return {
|
||||
status: 'suspended',
|
||||
ourOrderCode,
|
||||
reason: `订单当前 ${status},尚未到待配送(50),等前置满足后重试`,
|
||||
};
|
||||
}
|
||||
|
||||
// inbound_completed:送仓链路,我方必须先自己发车到 60
|
||||
if (status === 60) {
|
||||
await runWithTenantDbContext(branchCode, () => finalizeOrderFulfillment(ourOrderCode));
|
||||
return { status: 'done', ourOrderCode, reason: '主系统入库完成 ⇒ 送仓订单收口' };
|
||||
}
|
||||
return {
|
||||
status: 'suspended',
|
||||
ourOrderCode,
|
||||
reason: `订单当前 ${status},尚未发车(60),等前置满足后重试`,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 收到主系统事件(webhook 入口调用)。
|
||||
*
|
||||
* 返回 `duplicate=true` 表示本次是重复投递(已被幂等键拦下),调用方应直接回 200。
|
||||
* **业务失败不抛错**:事件已持久化,重试交给对账;抛 5xx 会让主系统重推而重推解决不了前置问题。
|
||||
*/
|
||||
export async function handleFulfillmentEvent(params: {
|
||||
branchCode: string;
|
||||
event: FulfillmentEventName;
|
||||
mainOrderCode: string;
|
||||
rows?: MainPreparationRow[];
|
||||
payload?: unknown;
|
||||
}): Promise<{ duplicate: boolean; outcome: FulfillmentOutcome }> {
|
||||
const branchCode = String(params.branchCode || '').trim();
|
||||
const mainOrderCode = String(params.mainOrderCode || '').trim();
|
||||
if (!branchCode || !mainOrderCode) {
|
||||
return {
|
||||
duplicate: false,
|
||||
outcome: { status: 'ignored', ourOrderCode: null, reason: '缺少分公司或主系统订单号' },
|
||||
};
|
||||
}
|
||||
|
||||
// ① 幂等占坑:冲突 = 这条事件已经收过(无论成功与否,重试由本模块的对账负责)
|
||||
const inserted = await pool.query<{ id: string }>(
|
||||
`INSERT INTO public.main_system_fulfillment_events
|
||||
(branch_code, event, main_order_code, payload, source)
|
||||
VALUES ($1, $2, $3, $4::jsonb, 'webhook')
|
||||
ON CONFLICT (branch_code, event, main_order_code) DO NOTHING
|
||||
RETURNING id`,
|
||||
[branchCode, params.event, mainOrderCode, JSON.stringify(params.payload ?? {})]
|
||||
);
|
||||
if (!inserted.rowCount) {
|
||||
return {
|
||||
duplicate: true,
|
||||
outcome: { status: 'done', ourOrderCode: null, reason: '重复投递,已幂等跳过' },
|
||||
};
|
||||
}
|
||||
|
||||
// ② 先把实收量事实落账(无论能否收口:事实与状态是两件事)
|
||||
await recordActualQtyFacts(branchCode, params.rows);
|
||||
|
||||
// ③ 收口
|
||||
const ourOrderCode = await findOurOrderCode(branchCode, mainOrderCode);
|
||||
if (!ourOrderCode) {
|
||||
// 不是分配给我方的单(或尚未导入)⇒ 标记 ignored,不算失败
|
||||
await markEvent(branchCode, params.event, mainOrderCode, {
|
||||
status: 'ignored',
|
||||
ourOrderCode: null,
|
||||
reason: '台账无该主系统订单的对照(非我方订单或尚未导入)',
|
||||
});
|
||||
return {
|
||||
duplicate: false,
|
||||
outcome: { status: 'ignored', ourOrderCode: null, reason: '台账无对照' },
|
||||
};
|
||||
}
|
||||
|
||||
const outcome = await safeConclude({ branchCode, event: params.event, ourOrderCode });
|
||||
await markEvent(branchCode, params.event, mainOrderCode, { ...outcome });
|
||||
return { duplicate: false, outcome };
|
||||
}
|
||||
|
||||
/** 收口包一层:业务异常(如零价 409)⇒ suspended + 原因,**不抛给调用方**。 */
|
||||
async function safeConclude(params: {
|
||||
branchCode: string;
|
||||
event: FulfillmentEventName;
|
||||
ourOrderCode: string;
|
||||
}): Promise<FulfillmentOutcome> {
|
||||
try {
|
||||
return await concludeByFulfillmentEvent(params);
|
||||
} catch (error: unknown) {
|
||||
const err = error as { message?: string; code?: string };
|
||||
// ⚠️ 零价闸门(`zero_price_blocked`)**有意不绕过**:那是财务口径的最后一道,
|
||||
// 挂 suspended 暴露给人补价。见设计文档 §6 D1。
|
||||
return {
|
||||
status: 'suspended',
|
||||
ourOrderCode: params.ourOrderCode,
|
||||
reason: `收口失败:${err?.message || String(error)}${err?.code ? `(${err.code})` : ''}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** 把 webhook 载荷里的实收量写进行级台账(`actual_qty` 为 null 的不动)。 */
|
||||
async function recordActualQtyFacts(branchCode: string, rows?: MainPreparationRow[]): Promise<void> {
|
||||
if (!rows?.length) return;
|
||||
for (const row of rows) {
|
||||
if (!row.id) continue;
|
||||
if (row.actualQty === null) continue;
|
||||
try {
|
||||
await recordPrepActualQty({
|
||||
branchCode,
|
||||
prepId: row.id,
|
||||
actualQty: row.actualQty,
|
||||
qtyDiff: row.qtyDiff,
|
||||
actualQtyAt: row.actualQtyAt,
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
// 台账写失败不阻断收口:状态是主责,数量是附加事实
|
||||
console.error(
|
||||
`[main-system-fulfillment] ${branchCode} 备货行 ${row.id} 实收量落账失败:`,
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function markEvent(
|
||||
branchCode: string,
|
||||
event: string,
|
||||
mainOrderCode: string,
|
||||
patch: { status: string; ourOrderCode: string | null; reason: string | null }
|
||||
): Promise<void> {
|
||||
await pool.query(
|
||||
// ⚠️ `$4` 必须**两处都显式转 text**:它既赋给 varchar 列、又与 text 字面量比较,
|
||||
// 不转则 PG 报 `inconsistent types deduced for parameter`(42P08,实测踩过)。
|
||||
`UPDATE public.main_system_fulfillment_events
|
||||
SET status = $4::text,
|
||||
our_order_code = COALESCE($5, our_order_code),
|
||||
reason = $6,
|
||||
processed_at = CASE WHEN $4::text = 'suspended' THEN processed_at ELSE NOW() END,
|
||||
attempts = attempts + 1,
|
||||
updated_at = NOW()
|
||||
WHERE branch_code = $1 AND event = $2 AND main_order_code = $3`,
|
||||
[branchCode, event, mainOrderCode, patch.status, patch.ourOrderCode, patch.reason]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 对账兜底:把该分公司**未收口**(pending / suspended)的事件重试一遍。
|
||||
* 由既有 15 分钟调度按分公司调用。
|
||||
*/
|
||||
export async function retryPendingFulfillmentEvents(branchCode: string): Promise<{ retried: number; done: number }> {
|
||||
if (!isFulfillmentEventsEnabled()) return { retried: 0, done: 0 };
|
||||
const branch = String(branchCode || '').trim();
|
||||
if (!branch) return { retried: 0, done: 0 };
|
||||
|
||||
const pending = await pool.query<{ event: string; main_order_code: string }>(
|
||||
`SELECT event, main_order_code
|
||||
FROM public.main_system_fulfillment_events
|
||||
WHERE branch_code = $1 AND status IN ('pending', 'suspended')
|
||||
ORDER BY updated_at
|
||||
LIMIT 100`,
|
||||
[branch]
|
||||
);
|
||||
|
||||
let done = 0;
|
||||
for (const row of pending.rows) {
|
||||
const event = String(row.event);
|
||||
if (!isFulfillmentEvent(event)) continue;
|
||||
const mainOrderCode = String(row.main_order_code);
|
||||
const ourOrderCode = await findOurOrderCode(branch, mainOrderCode);
|
||||
if (!ourOrderCode) {
|
||||
await markEvent(branch, event, mainOrderCode, {
|
||||
status: 'ignored',
|
||||
ourOrderCode: null,
|
||||
reason: '台账无该主系统订单的对照',
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const outcome = await safeConclude({ branchCode: branch, event, ourOrderCode });
|
||||
await markEvent(branch, event, mainOrderCode, { ...outcome });
|
||||
if (outcome.status === 'done') done += 1;
|
||||
}
|
||||
return { retried: pending.rowCount || 0, done };
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取侧兜底(**不依赖 webhook**):用主系统 R3 字段独立推出同样的两个事实。
|
||||
*
|
||||
* 判据(与给主系统的清单 §2.3 一致):
|
||||
* · 链路 A 免入库:`order_departed_at` 非空 ⇒ 等价于 picked_up
|
||||
* · 链路 B 送仓:该主系统订单的行**全部** `is_inbounded = true` ⇒ 等价于 inbound_completed
|
||||
*
|
||||
* ⚠️ **性能纪律(本函数的第一约束)**:一个分公司可能有几百张在途主系统订单,
|
||||
* 所以这里**只打 3 次库 + 1 次 HTTP**(`lookup` 内部再按 500 条分片),
|
||||
* **绝不逐单 lookup** —— 逐单会把 15 分钟一轮的对账打成 N 次外网调用。
|
||||
*/
|
||||
export async function reconcileFulfillmentFromPull(branchCode: string): Promise<{ checked: number; closed: number }> {
|
||||
if (!isFulfillmentEventsEnabled()) return { checked: 0, closed: 0 };
|
||||
const branch = String(branchCode || '').trim();
|
||||
if (!branch) return { checked: 0, closed: 0 };
|
||||
|
||||
// ① 该分公司「主系统订单 → 我方订单」的全部对照(一次)
|
||||
const links = await pool.query<{ main_order_code: string; our_order_code: string }>(
|
||||
`SELECT main_order_code, our_order_code
|
||||
FROM public.main_system_order_imports
|
||||
WHERE branch_code = $1 AND our_order_code IS NOT NULL`,
|
||||
[branch]
|
||||
);
|
||||
if (!links.rowCount) return { checked: 0, closed: 0 };
|
||||
|
||||
// ② 这些我方订单的状态(**一个租户一条 SQL**,不逐单查)
|
||||
const ourOrderCodes = [...new Set(links.rows.map((r) => String(r.our_order_code)))];
|
||||
const statusRows = await runWithTenantDbContext(branch, () =>
|
||||
pool.query<{ order_code: string; order_status: number | null }>(
|
||||
`SELECT order_code, order_status FROM orders
|
||||
WHERE order_code = ANY($1::text[]) AND deleted_at IS NULL`,
|
||||
[ourOrderCodes]
|
||||
)
|
||||
);
|
||||
const activeOurOrders = new Set(
|
||||
statusRows.rows
|
||||
.filter((r) => {
|
||||
const s = Number(r.order_status);
|
||||
return Number.isFinite(s) && s >= 50 && s < 90; // 只处理"已到前置状态、尚未结案"
|
||||
})
|
||||
.map((r) => String(r.order_code))
|
||||
);
|
||||
if (!activeOurOrders.size) return { checked: 0, closed: 0 };
|
||||
|
||||
const activeLinks = links.rows.filter((r) => activeOurOrders.has(String(r.our_order_code)));
|
||||
const mainOrderCodes = [...new Set(activeLinks.map((r) => String(r.main_order_code)))];
|
||||
|
||||
// ③ 这些主系统订单的备货行 SKU(一次)。
|
||||
// disposition 排除 cancelled/returned:已退货的行在**主系统侧已被排除出分母**,
|
||||
// 这里若还拿它当分母,会让该单永远判不出"全部入库完成"(拉取兜底与主系统口径保持一致)。
|
||||
const ledger = await pool.query<{ main_order_code: string; main_sku_code: string | null }>(
|
||||
`SELECT main_order_code, main_sku_code
|
||||
FROM public.main_system_order_import_items
|
||||
WHERE branch_code = $1
|
||||
AND disposition NOT IN ('cancelled', 'returned')
|
||||
AND main_order_code = ANY($2::text[])`,
|
||||
[branch, mainOrderCodes]
|
||||
);
|
||||
const items: Array<{ orderCode: string; skuCode: string }> = [];
|
||||
for (const row of ledger.rows) {
|
||||
const sku = row.main_sku_code ? String(row.main_sku_code).trim() : '';
|
||||
if (!sku) continue; // 无 SKU 的行无法 lookup(与退货跟随同款:问不到就不判定)
|
||||
items.push({ orderCode: String(row.main_order_code), skuCode: sku });
|
||||
}
|
||||
if (!items.length) return { checked: 0, closed: 0 };
|
||||
|
||||
// ④ **一次** lookup 覆盖整个分公司(内部按 500 条分片),而不是每单一次 HTTP
|
||||
const lookup = await lookupMainSystemPreparationStates(branch, items);
|
||||
if (lookup.kind !== 'ok') return { checked: 0, closed: 0 }; // 问不到不判定(与退货跟随同款纪律)
|
||||
|
||||
const byMainOrder = new Map<string, typeof lookup.results>();
|
||||
for (const r of lookup.results) {
|
||||
const key = String(r.orderCode);
|
||||
if (!byMainOrder.has(key)) byMainOrder.set(key, []);
|
||||
byMainOrder.get(key)!.push(r);
|
||||
}
|
||||
|
||||
// ⑤ 逐主系统订单判定(同一张我方订单可能被多张主系统单指向,收口幂等由结案函数自身保证)
|
||||
let checked = 0;
|
||||
let closed = 0;
|
||||
for (const [mainOrderCode, results] of byMainOrder) {
|
||||
const ourOrderCode = String(
|
||||
activeLinks.find((r) => String(r.main_order_code) === mainOrderCode)?.our_order_code || ''
|
||||
);
|
||||
if (!ourOrderCode) continue;
|
||||
checked += 1;
|
||||
|
||||
const departed = results.some((r) => r.orderDepartedAt);
|
||||
const allInbounded = results.length > 0 && results.every((r) => r.isInbounded || !r.orderItemPresent);
|
||||
const event: FulfillmentEventName | null = departed
|
||||
? PREP_PICKED_UP_EVENT
|
||||
: allInbounded
|
||||
? PREP_INBOUND_COMPLETED_EVENT
|
||||
: null;
|
||||
if (!event) continue;
|
||||
|
||||
// 幂等占坑:抢不到 = 这条事实已经收过(无论上次成功与否),本轮不再重复收口
|
||||
const inserted = await pool.query(
|
||||
`INSERT INTO public.main_system_fulfillment_events
|
||||
(branch_code, event, main_order_code, our_order_code, payload, source)
|
||||
VALUES ($1, $2, $3, $4, '{}'::jsonb, 'reconcile')
|
||||
ON CONFLICT (branch_code, event, main_order_code) DO NOTHING
|
||||
RETURNING id`,
|
||||
[branch, event, mainOrderCode, ourOrderCode]
|
||||
);
|
||||
if (!inserted.rowCount) continue;
|
||||
|
||||
const outcome = await safeConclude({ branchCode: branch, event, ourOrderCode });
|
||||
await markEvent(branch, event, mainOrderCode, { ...outcome });
|
||||
if (outcome.status === 'done') closed += 1;
|
||||
}
|
||||
return { checked, closed };
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,643 @@
|
||||
import { pool } from '../db';
|
||||
import { runWithTenantDataAccess } from './tenantSchemaService';
|
||||
|
||||
/**
|
||||
* 主系统备货行 ↔ 本系统订单行 的行级对照台账(2026-10-08)。
|
||||
*
|
||||
* 为什么需要:整单台账只有「主系统订单号 → 本系统订单号」,而主系统**退货**是把备货行
|
||||
* 物理删除(从 `view=active` 消失),本系统必须能定位到**自己的哪一行**去跟随红冲。
|
||||
* 见 docs/design/20261008-第三方订单退货跟随与发车回写方案.md §3.1。
|
||||
*
|
||||
* 表在 `public`(跨系统平台台账,**不是**分公司业务表),所以这里一律用 `public.` 限定名,
|
||||
* 并且**不需要租户上下文**。
|
||||
*/
|
||||
|
||||
export type PrepLedgerDisposition =
|
||||
| 'pending'
|
||||
| 'imported'
|
||||
| 'completed'
|
||||
| 'returned'
|
||||
| 'cancelled'
|
||||
| 'suspended'
|
||||
/** 主系统标了缺货:本系统没建对应订单行,无需回写/跟随 */
|
||||
| 'skipped_stockout';
|
||||
|
||||
export type PrepLedgerRow = {
|
||||
id: string;
|
||||
branch_code: string;
|
||||
main_order_code: string;
|
||||
prep_id: string;
|
||||
our_order_code: string | null;
|
||||
our_order_item_id: string | null;
|
||||
main_supplier_code: string | null;
|
||||
main_sku_code: string | null;
|
||||
item_name: string | null;
|
||||
last_prepare_qty: string | number | null;
|
||||
last_prepare_status: number | null;
|
||||
last_return_code: string | null;
|
||||
disposition: PrepLedgerDisposition;
|
||||
disposition_reason: string | null;
|
||||
writeback_status: string | null;
|
||||
last_seen_active_at: string | null;
|
||||
is_stockout?: boolean | null;
|
||||
payload: Record<string, unknown> | null;
|
||||
};
|
||||
|
||||
function normalizeName(value: unknown): string {
|
||||
return String(value ?? '').trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 把主系统备货行与本系统订单行对上:按**商品名 + 出现次序**一一对应
|
||||
* (同名多行时按各自的出现顺序配,不用随机/时间兜底,结果可复现)。
|
||||
* 对不上的行宁可留空 —— 退货跟随时会判「无法定位」并挂待处理,不做猜测。
|
||||
*/
|
||||
export function mapPrepRowsToOurItems(
|
||||
prepRows: Array<{ id: string; itemName: string | null }>,
|
||||
ourItems: Array<{ id: string; item_name: string | null }>
|
||||
): Map<string, string> {
|
||||
const buckets = new Map<string, string[]>();
|
||||
for (const item of ourItems) {
|
||||
const key = normalizeName(item.item_name);
|
||||
if (!key) continue;
|
||||
if (!buckets.has(key)) buckets.set(key, []);
|
||||
buckets.get(key)!.push(String(item.id));
|
||||
}
|
||||
const cursor = new Map<string, number>();
|
||||
const out = new Map<string, string>();
|
||||
for (const row of prepRows) {
|
||||
const key = normalizeName(row.itemName);
|
||||
const candidates = buckets.get(key);
|
||||
if (!candidates) continue;
|
||||
const used = cursor.get(key) ?? 0;
|
||||
if (used >= candidates.length) continue;
|
||||
out.set(String(row.id), candidates[used]);
|
||||
cursor.set(key, used + 1);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* **整单(跨主系统单)**备货行 → 本系统订单行**一对一**对照(2026-10-11 修复)。
|
||||
*
|
||||
* 为什么必须整单算(实测缺陷):一张我方订单常由多张主系统单合并而来,**同名商品会在多张单里各出现一次**
|
||||
* (本单「肉片」在 `…_0006` 计划 3.5 斤、`…_0007` 计划 6 斤)。原实现**按单各调一次** `mapPrepRowsToOurItems`,
|
||||
* 而它只在**单次调用内**消费候选(池子不跨单扣减)⇒ 两张单都先认领同一条订单行(6 斤那条),
|
||||
* 后一张单的行因为"已有对照"被跳过 ⇒ 3.5 斤那条订单行**永远配不上**(详情归到「本系统录单」、
|
||||
* 台账两条备货行指向同一订单行 ⇒ 回写把 3.5 写成 6)。
|
||||
*
|
||||
* 配对规则(同名桶内,一对一消费):
|
||||
* ① 备货行的计划量 `prepareQty` 与订单行数量 `quantity` 都存在时,**取数量最接近的**(实测可判:3.5↔3.5、6↔6);
|
||||
* ② 数量缺失/并列时退回"出现次序"(与原实现同口径,结果可复现);
|
||||
* ③ 配不上宁可留空 —— 不猜、不重复认领。
|
||||
*
|
||||
* 主系统行按 `groups` 给定顺序、组内按数组顺序取(调用方要保证顺序稳定)。
|
||||
*/
|
||||
export function mapOrderPrepRowsToOurItems(
|
||||
groups: Array<{
|
||||
orderCode: string;
|
||||
rows: Array<{ id: string; itemName: string | null; prepareQty?: number | null; isStockout?: boolean | null }>;
|
||||
}>,
|
||||
ourItems: Array<{ id: string; item_name: string | null; quantity?: number | null }>
|
||||
): Map<string, string> {
|
||||
const buckets = new Map<string, Array<{ id: string; quantity: number | null }>>();
|
||||
for (const item of ourItems) {
|
||||
const key = normalizeName(item.item_name);
|
||||
if (!key) continue;
|
||||
if (!buckets.has(key)) buckets.set(key, []);
|
||||
buckets.get(key)!.push({
|
||||
id: String(item.id),
|
||||
quantity: Number.isFinite(Number(item.quantity)) && item.quantity !== null && item.quantity !== undefined
|
||||
? Number(item.quantity)
|
||||
: null,
|
||||
});
|
||||
}
|
||||
const out = new Map<string, string>();
|
||||
for (const group of groups) {
|
||||
for (const row of group.rows) {
|
||||
if (isStockoutRow(row)) continue; // 缺货行在本系统不建订单行,不占匹配位
|
||||
const prepId = String(row.id || '').trim();
|
||||
if (!prepId || out.has(prepId)) continue;
|
||||
const candidates = buckets.get(normalizeName(row.itemName));
|
||||
if (!candidates?.length) continue;
|
||||
const wantQty =
|
||||
row.prepareQty === null || row.prepareQty === undefined || !Number.isFinite(Number(row.prepareQty))
|
||||
? null
|
||||
: Number(row.prepareQty);
|
||||
let pickIdx = 0;
|
||||
if (wantQty !== null) {
|
||||
let bestDiff = Number.POSITIVE_INFINITY;
|
||||
for (let i = 0; i < candidates.length; i += 1) {
|
||||
const q = candidates[i].quantity;
|
||||
if (q === null) continue;
|
||||
const diff = Math.abs(q - wantQty);
|
||||
if (diff < bestDiff - 1e-9) {
|
||||
bestDiff = diff;
|
||||
pickIdx = i;
|
||||
}
|
||||
}
|
||||
}
|
||||
const [picked] = candidates.splice(pickIdx, 1); // 一对一:认领后从池中扣减
|
||||
out.set(prepId, picked.id);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* **纠正"同名重复认领"的存量对照**(2026-10-11)。
|
||||
*
|
||||
* 背景:旧对照按单各算一次 ⇒ 同名商品被多张主系统单重复认领(两条备货行指向同一订单行),
|
||||
* 而台账 upsert 对已有对照是 `COALESCE(旧值, 新值)`(优先保留),**错值永远不会自愈**。
|
||||
*
|
||||
* 保守纠正规则(只动"确实错"的行,不重算正确的行):
|
||||
* · 台账 `our_order_item_id IS NULL` 且有整单对照 ⇒ 补上;
|
||||
* · 台账 `our_order_item_id` 在本单内**被多行共用**(重复认领)⇒ 按整单对照重新分配;
|
||||
* · `order_items.main_order_code` 仅对"参与重复认领的行"重盖来源单号(其余保持不动)。
|
||||
* 配不上的行**留空**(不猜)。
|
||||
*/
|
||||
export async function healOrderPrepMapping(params: {
|
||||
branchCode: string;
|
||||
ourOrderCode: string;
|
||||
}): Promise<{ ledgerFixed: number; itemCodesFixed: number; duplicates: string[] }> {
|
||||
const branch = String(params.branchCode || '').trim();
|
||||
const orderCode = String(params.ourOrderCode || '').trim();
|
||||
const result = { ledgerFixed: 0, itemCodesFixed: 0, duplicates: [] as string[] };
|
||||
if (!branch || !orderCode) return result;
|
||||
|
||||
const ourItems = await runWithTenantDataAccess(branch, async (client) =>
|
||||
client.query<{ id: string; item_name: string | null; quantity: string | number | null; main_order_code: string | null }>(
|
||||
`SELECT id::text AS id, item_name, quantity, main_order_code
|
||||
FROM order_items
|
||||
WHERE order_code = $1
|
||||
ORDER BY sort_order NULLS LAST, created_at, id`,
|
||||
[orderCode]
|
||||
)
|
||||
);
|
||||
if (!ourItems.rowCount) return result;
|
||||
|
||||
const ledgerRows = await pool.query<{
|
||||
prep_id: string;
|
||||
main_order_code: string;
|
||||
item_name: string | null;
|
||||
last_prepare_qty: string | number | null;
|
||||
our_order_item_id: string | null;
|
||||
}>(
|
||||
`SELECT prep_id::text AS prep_id, main_order_code, item_name, last_prepare_qty,
|
||||
our_order_item_id::text AS our_order_item_id
|
||||
FROM public.main_system_order_import_items
|
||||
WHERE branch_code = $1 AND our_order_code = $2
|
||||
ORDER BY main_order_code, item_name, prep_id`,
|
||||
[branch, orderCode]
|
||||
);
|
||||
if (!ledgerRows.rowCount) return result;
|
||||
|
||||
const groups: Array<{
|
||||
orderCode: string;
|
||||
rows: Array<{ id: string; itemName: string | null; prepareQty: number | null }>;
|
||||
}> = [];
|
||||
for (const row of ledgerRows.rows) {
|
||||
const groupCode = String(row.main_order_code || '');
|
||||
const bucket = groups.find((g) => g.orderCode === groupCode) ?? (() => {
|
||||
const created = { orderCode: groupCode, rows: [] as Array<{ id: string; itemName: string | null; prepareQty: number | null }> };
|
||||
groups.push(created);
|
||||
return created;
|
||||
})();
|
||||
bucket.rows.push({
|
||||
id: String(row.prep_id),
|
||||
itemName: row.item_name,
|
||||
prepareQty: row.last_prepare_qty === null ? null : Number(row.last_prepare_qty),
|
||||
});
|
||||
}
|
||||
const mapping = mapOrderPrepRowsToOurItems(
|
||||
groups,
|
||||
ourItems.rows.map((row) => ({
|
||||
id: String(row.id),
|
||||
item_name: row.item_name,
|
||||
quantity: row.quantity === null || row.quantity === undefined ? null : Number(row.quantity),
|
||||
}))
|
||||
);
|
||||
|
||||
// 本单内被多行共用的既有对照 = 旧缺陷的指纹
|
||||
const usage = new Map<string, number>();
|
||||
for (const row of ledgerRows.rows) {
|
||||
const id = row.our_order_item_id ? String(row.our_order_item_id) : '';
|
||||
if (!id) continue;
|
||||
usage.set(id, (usage.get(id) ?? 0) + 1);
|
||||
}
|
||||
const duplicated = new Set([...usage.entries()].filter(([, n]) => n > 1).map(([id]) => id));
|
||||
result.duplicates = [...duplicated];
|
||||
|
||||
const itemMainOrder = new Map(ourItems.rows.map((row) => [String(row.id), row.main_order_code]));
|
||||
/** itemId → 纠正后应挂的主系统单号(仅对参与重复认领的行重盖) */
|
||||
const regenerated = new Map<string, string>();
|
||||
|
||||
for (const row of ledgerRows.rows) {
|
||||
const prepId = String(row.prep_id);
|
||||
const stored = row.our_order_item_id ? String(row.our_order_item_id) : null;
|
||||
const shouldBe = mapping.get(prepId) ?? null;
|
||||
if (!shouldBe) continue; // 配不上:留空,不猜
|
||||
if (stored && stored !== shouldBe && !duplicated.has(stored)) continue; // 已建立且不是重复认领 ⇒ 保持
|
||||
if (stored === shouldBe) {
|
||||
if (duplicated.has(shouldBe)) regenerated.set(shouldBe, String(row.main_order_code || ''));
|
||||
continue;
|
||||
}
|
||||
const updated = await pool.query(
|
||||
`UPDATE public.main_system_order_import_items
|
||||
SET our_order_item_id = $3::uuid, updated_at = NOW()
|
||||
WHERE branch_code = $1 AND prep_id = $2::uuid`,
|
||||
[branch, prepId, shouldBe]
|
||||
);
|
||||
result.ledgerFixed += updated.rowCount || 0;
|
||||
regenerated.set(shouldBe, String(row.main_order_code || ''));
|
||||
if (stored) regenerated.set(stored, ''); // 让被"抢走"的那条行由它的新主人重盖
|
||||
}
|
||||
|
||||
for (const [itemId, mainOrderCode] of regenerated) {
|
||||
if (!mainOrderCode) continue;
|
||||
if (String(itemMainOrder.get(itemId) || '') === mainOrderCode) continue;
|
||||
const updated = await runWithTenantDataAccess(branch, async (client) =>
|
||||
client.query(`UPDATE order_items SET main_order_code = $3 WHERE order_code = $1 AND id = $2::uuid`, [
|
||||
orderCode,
|
||||
itemId,
|
||||
mainOrderCode,
|
||||
])
|
||||
);
|
||||
result.itemCodesFixed += updated.rowCount || 0;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** 主系统备货行是否标了缺货(payload 里是布尔,历史数据可能是字符串) */
|
||||
function isStockoutRow(row: { isStockout?: boolean | null }): boolean {
|
||||
const value = row?.isStockout as unknown;
|
||||
return value === true || value === 'true' || value === 1 || value === '1';
|
||||
}
|
||||
|
||||
/** 建单成功后落行级对照(幂等:同 branch+prep_id 覆盖更新)。 */
|
||||
export async function recordImportedPrepItems(params: {
|
||||
branchCode: string;
|
||||
mainOrderCode: string;
|
||||
supplierCode: string | null;
|
||||
ourOrderCode: string;
|
||||
prepRows: Array<{
|
||||
id: string;
|
||||
itemName: string | null;
|
||||
skuCode?: string | null;
|
||||
prepareQty?: number | null;
|
||||
prepareStatus?: number | null;
|
||||
returnCode?: string | null;
|
||||
isStockout?: boolean | null;
|
||||
/** 主系统下单分公司(P1-10):客户归属与客户名依据;webhook 通道可能为 null */
|
||||
branchCode?: string | null;
|
||||
branchName?: string | null;
|
||||
}>;
|
||||
ourItems: Array<{ id: string; item_name: string | null }>;
|
||||
/**
|
||||
* 可选:由调用方算好的**整单(跨主系统单)一对一对照**(`mapOrderPrepRowsToOurItems`)。
|
||||
* 一张我方订单由多张主系统单合并而来时**必须传** —— 否则同名商品会被多张单重复认领(见该函数注释)。
|
||||
*/
|
||||
mapping?: Map<string, string>;
|
||||
}): Promise<number> {
|
||||
const mapping =
|
||||
params.mapping ??
|
||||
mapPrepRowsToOurItems(
|
||||
// 缺货行在本系统**不建订单行**,不能占用「名字 + 次序」的匹配位(否则会把真实行配错位)
|
||||
params.prepRows.filter((row) => !isStockoutRow(row)),
|
||||
params.ourItems
|
||||
);
|
||||
let written = 0;
|
||||
for (const row of params.prepRows) {
|
||||
const prepId = String(row.id || '').trim();
|
||||
if (!prepId) continue;
|
||||
await pool.query(
|
||||
`INSERT INTO public.main_system_order_import_items
|
||||
(branch_code, main_order_code, prep_id, our_order_code, our_order_item_id,
|
||||
main_supplier_code, main_sku_code, item_name, last_prepare_qty, last_prepare_status,
|
||||
last_return_code, disposition, payload, main_branch_code, main_branch_name, updated_at)
|
||||
VALUES ($1,$2,$3::uuid,$4,$5::uuid,$6,$7,$8,$9,$10,$11,$12,$13::jsonb,$14,$15,NOW())
|
||||
ON CONFLICT (branch_code, prep_id) DO UPDATE
|
||||
SET our_order_code = EXCLUDED.our_order_code,
|
||||
-- ⚠️ 已建立的对照**优先保留**:重算映射可能因"另一行已被占用"而变化,覆盖会把行配错
|
||||
our_order_item_id = COALESCE(public.main_system_order_import_items.our_order_item_id, EXCLUDED.our_order_item_id),
|
||||
item_name = EXCLUDED.item_name,
|
||||
main_sku_code = COALESCE(EXCLUDED.main_sku_code, public.main_system_order_import_items.main_sku_code),
|
||||
last_prepare_qty = EXCLUDED.last_prepare_qty,
|
||||
last_prepare_status = EXCLUDED.last_prepare_status,
|
||||
last_return_code = EXCLUDED.last_return_code,
|
||||
disposition = CASE
|
||||
WHEN public.main_system_order_import_items.disposition = 'pending' THEN EXCLUDED.disposition
|
||||
-- 2026-10-10:缺货被剔除后主系统又把它分配回来 ⇒ 重新建了行,处置复位为 imported
|
||||
--(EXCLUDED.our_order_item_id 非空 = 本次真的配到了订单行;没配上就不复位)
|
||||
WHEN public.main_system_order_import_items.disposition = 'skipped_stockout'
|
||||
AND EXCLUDED.our_order_item_id IS NOT NULL
|
||||
THEN EXCLUDED.disposition
|
||||
ELSE public.main_system_order_import_items.disposition
|
||||
END,
|
||||
payload = EXCLUDED.payload,
|
||||
-- 下单分公司(客户归属依据):非空才覆盖,避免 webhook 通道剥字段时把已知值抹掉
|
||||
main_branch_code = COALESCE(EXCLUDED.main_branch_code, public.main_system_order_import_items.main_branch_code),
|
||||
main_branch_name = COALESCE(EXCLUDED.main_branch_name, public.main_system_order_import_items.main_branch_name),
|
||||
updated_at = NOW()`,
|
||||
[
|
||||
params.branchCode,
|
||||
params.mainOrderCode,
|
||||
prepId,
|
||||
params.ourOrderCode,
|
||||
mapping.get(prepId) ?? null,
|
||||
params.supplierCode,
|
||||
row.skuCode ?? null,
|
||||
row.itemName ?? null,
|
||||
row.prepareQty ?? null,
|
||||
row.prepareStatus ?? null,
|
||||
row.returnCode ?? null,
|
||||
isStockoutRow(row) ? 'skipped_stockout' : 'imported',
|
||||
JSON.stringify(row),
|
||||
// 主系统下单分公司(P1-10):客户归属与客户名的依据
|
||||
row.branchCode ? String(row.branchCode).trim().toUpperCase() : null,
|
||||
row.branchName ? String(row.branchName).trim() : null,
|
||||
]
|
||||
);
|
||||
written += 1;
|
||||
}
|
||||
return written;
|
||||
}
|
||||
|
||||
/** 该订单上已被其它备货行占用的本系统订单行 id 集合(惰性对照时排除,避免一行两认领)。 */
|
||||
export async function listClaimedOrderItemIds(params: {
|
||||
branchCode: string;
|
||||
ourOrderCode: string;
|
||||
exceptPrepId?: string;
|
||||
}): Promise<Set<string>> {
|
||||
const result = await pool.query<{ our_order_item_id: string | null }>(
|
||||
`SELECT our_order_item_id::text AS our_order_item_id
|
||||
FROM public.main_system_order_import_items
|
||||
WHERE branch_code = $1 AND our_order_code = $2 AND our_order_item_id IS NOT NULL
|
||||
AND ($3::uuid IS NULL OR prep_id <> $3::uuid)`,
|
||||
[params.branchCode, params.ourOrderCode, params.exceptPrepId ?? null]
|
||||
);
|
||||
return new Set(result.rows.map((row) => String(row.our_order_item_id)));
|
||||
}
|
||||
|
||||
/**
|
||||
* 该订单是否**整单全免入库**(该单在本台账里的**所有**备货行 `skip_inbound = true`):
|
||||
* 主系统配送员直接到我们这里取货、**我方不派车**(不建配送任务、不走进 60 的发车流程)。
|
||||
*
|
||||
* 事实来源:主系统 2026-10-09 增量在备货行暴露的 `skip_inbound`(**供应商级**),
|
||||
* 导入时已随行快照落进本台账 payload。**没有台账行 = 原生录单订单 ⇒ 一律 false**(原生流程零影响)。
|
||||
* 见 docs/design/20261009-供应商侧库存抵扣与免入库推进方案.md §3.2。
|
||||
*
|
||||
* ⚠️ **必须 `bool_and`(全行),不得退回 `bool_or`**(2026-10-11 开发者裁决):
|
||||
* 主系统按配送日把多张单合并成我方一张单,**混合单**(部分行免入库、部分行送仓)仍要我方发车送仓。
|
||||
* 用 `bool_or` 会把混合单误判成"免入库",后果是**不建配送任务(送仓部分没法发车)+ 分拣后停在 50 不收口**。
|
||||
* 展示侧(订单列表「待取货」)用的正是同一口径 `bool_and`,两处必须一致。
|
||||
* (旧名 `isMainSystemSkipInboundOrder`,语义收敛后更名;见 docs/design/20261010-…§9.6)
|
||||
*/
|
||||
export async function isOrderFullySkipInbound(params: {
|
||||
branchCode: string;
|
||||
ourOrderCode: string;
|
||||
/**
|
||||
* 可选:复用调用方已有的连接/事务。
|
||||
* ⚠️ **在事务里调用时必须传** —— 否则事务持有一条连接的同时又去 pool 取第二条,
|
||||
* 池满(`PG_POOL_MAX` 默认 30)时会自锁。`ensureDeliveryTaskForOrder` 就在事务内调用。
|
||||
*/
|
||||
db?: { query: (sql: string, values?: unknown[]) => Promise<{ rows: Array<{ skip: boolean | null }> }> };
|
||||
}): Promise<boolean> {
|
||||
const branch = String(params.branchCode || '').trim();
|
||||
const orderCode = String(params.ourOrderCode || '').trim();
|
||||
if (!branch || !orderCode) return false;
|
||||
const db = params.db ?? pool;
|
||||
const result = await db.query(
|
||||
`SELECT bool_and(COALESCE(payload->>'skipInbound', 'false') = 'true') AS skip
|
||||
FROM public.main_system_order_import_items
|
||||
WHERE branch_code = $1 AND our_order_code = $2`,
|
||||
[branch, orderCode]
|
||||
);
|
||||
return result.rows[0]?.skip === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 与 `isOrderFullySkipInbound` **同一语义**的 SQL 存在性子查询,供必须在 SQL 里排除免入库单的
|
||||
* 调用点复用 —— 避免"TS 一处口径、SQL 另一处口径"再次漂移。
|
||||
*
|
||||
* 用法(注意外层要写 `NOT EXISTS`):
|
||||
* ```ts
|
||||
* `... AND NOT EXISTS (${fullySkipInboundOrderExistsSql('o.order_code', 'o.branch_code')})`
|
||||
* ```
|
||||
* 两个参数是**代码里写死的列表达式**(不是用户输入),因此直接内插。
|
||||
* 该单在本台账**没有行**(原生录单)⇒ 子查询为空 ⇒ `EXISTS` 为假 ⇒ 不排除 ✓。
|
||||
*/
|
||||
export function fullySkipInboundOrderExistsSql(
|
||||
orderCodeExpr: string,
|
||||
branchCodeExpr: string
|
||||
): string {
|
||||
return `SELECT 1
|
||||
FROM public.main_system_order_import_items li
|
||||
WHERE li.branch_code = ${branchCodeExpr}
|
||||
AND li.our_order_code = ${orderCodeExpr}
|
||||
GROUP BY li.our_order_code
|
||||
HAVING bool_and(COALESCE(li.payload->>'skipInbound', 'false') = 'true')`;
|
||||
}
|
||||
|
||||
export async function listPrepLedgerRows(branchCode: string): Promise<PrepLedgerRow[]> {
|
||||
const result = await pool.query<PrepLedgerRow>(
|
||||
`SELECT id, branch_code, main_order_code, prep_id::text AS prep_id, our_order_code,
|
||||
our_order_item_id::text AS our_order_item_id, main_supplier_code, main_sku_code,
|
||||
item_name, last_prepare_qty, last_prepare_status, last_return_code,
|
||||
disposition, disposition_reason, writeback_status, last_seen_active_at, payload
|
||||
FROM public.main_system_order_import_items
|
||||
WHERE branch_code = $1
|
||||
ORDER BY main_order_code, item_name`,
|
||||
[branchCode]
|
||||
);
|
||||
return result.rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* 记录"本系统最后一次在主系统 active 列表里看到这一行"。
|
||||
* 退货判定必须依赖它:只有"看着它在 active、后来消失"才是退货候选;
|
||||
* 从没见过的行(启用开关前的历史数据)绝不自动红冲。
|
||||
*/
|
||||
export async function touchLastSeenActiveAt(params: {
|
||||
branchCode: string;
|
||||
prepIds: string[];
|
||||
}): Promise<void> {
|
||||
if (!params.prepIds.length) return;
|
||||
await pool.query(
|
||||
`UPDATE public.main_system_order_import_items
|
||||
SET last_seen_active_at = NOW()
|
||||
WHERE branch_code = $1 AND prep_id = ANY($2::uuid[])`,
|
||||
[params.branchCode, params.prepIds]
|
||||
);
|
||||
}
|
||||
|
||||
/** 惰性对照成功后回写(只需成功一次;见 mainSystemReturnFollow 的说明)。 */
|
||||
export async function setOurOrderItemId(params: {
|
||||
branchCode: string;
|
||||
prepId: string;
|
||||
ourOrderItemId: string;
|
||||
}): Promise<void> {
|
||||
await pool.query(
|
||||
`UPDATE public.main_system_order_import_items
|
||||
SET our_order_item_id = $3::uuid, updated_at = NOW()
|
||||
WHERE branch_code = $1 AND prep_id = $2::uuid AND our_order_item_id IS NULL`,
|
||||
[params.branchCode, params.prepId, params.ourOrderItemId]
|
||||
);
|
||||
}
|
||||
|
||||
export async function markPrepDisposition(params: {
|
||||
branchCode: string;
|
||||
prepId: string;
|
||||
disposition: PrepLedgerDisposition;
|
||||
reason?: string | null;
|
||||
}): Promise<void> {
|
||||
await pool.query(
|
||||
`UPDATE public.main_system_order_import_items
|
||||
SET disposition = $3, disposition_reason = $4, disposed_at = NOW(), updated_at = NOW()
|
||||
WHERE branch_code = $1 AND prep_id = $2::uuid`,
|
||||
[params.branchCode, params.prepId, params.disposition, params.reason ?? null]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 缺货剔除:把这一行的**订单行对照清掉**并记处置(2026-10-10)。
|
||||
*
|
||||
* 为什么要清 `our_order_item_id`:清掉之后,如果主系统**又把它分配回本供应商**(重新出现在 active
|
||||
* 列表里),导入侧就会重新建行并把处置复位为 `imported`(见 `recordImportedPrepItems` 的 CASE);
|
||||
* 只要它还在"已转自采"状态(不在 active),就什么都不会发生。
|
||||
*/
|
||||
export async function markPrepStockoutRemoved(params: {
|
||||
branchCode: string;
|
||||
prepId: string;
|
||||
reason: string;
|
||||
}): Promise<void> {
|
||||
await pool.query(
|
||||
`UPDATE public.main_system_order_import_items
|
||||
SET our_order_item_id = NULL,
|
||||
disposition = 'skipped_stockout',
|
||||
disposition_reason = $3,
|
||||
disposed_at = NOW(),
|
||||
updated_at = NOW()
|
||||
WHERE branch_code = $1 AND prep_id = $2::uuid`,
|
||||
[params.branchCode, params.prepId, params.reason]
|
||||
);
|
||||
}
|
||||
|
||||
/** 活跃行快照刷新(数量/状态/退货码变化都记下来,供审计与后续"退回"接入)。 */
|
||||
export async function updatePrepSnapshot(params: {
|
||||
branchCode: string;
|
||||
prepId: string;
|
||||
prepareQty?: number | null;
|
||||
prepareStatus?: number | null;
|
||||
returnCode?: string | null;
|
||||
}): Promise<void> {
|
||||
await pool.query(
|
||||
`UPDATE public.main_system_order_import_items
|
||||
SET last_prepare_qty = $3,
|
||||
last_prepare_status = $4,
|
||||
last_return_code = $5,
|
||||
updated_at = NOW()
|
||||
WHERE branch_code = $1 AND prep_id = $2::uuid`,
|
||||
[params.branchCode, params.prepId, params.prepareQty ?? null, params.prepareStatus ?? null, params.returnCode ?? null]
|
||||
);
|
||||
}
|
||||
|
||||
export async function markWriteback(params: {
|
||||
branchCode: string;
|
||||
prepId: string;
|
||||
status: 'done' | 'skipped_zero_price' | 'suspended' | 'rejected';
|
||||
reason?: string | null;
|
||||
}): Promise<void> {
|
||||
await pool.query(
|
||||
`UPDATE public.main_system_order_import_items
|
||||
SET writeback_status = $3, writeback_at = NOW(), writeback_reason = $4, updated_at = NOW()
|
||||
WHERE branch_code = $1 AND prep_id = $2::uuid`,
|
||||
[params.branchCode, params.prepId, params.status, params.reason ?? null]
|
||||
);
|
||||
}
|
||||
|
||||
/** 待回写/可重试的行(发车回写用)。 */
|
||||
export async function listRowsPendingWriteback(branchCode: string, orderCode: string): Promise<PrepLedgerRow[]> {
|
||||
const result = await pool.query<PrepLedgerRow>(
|
||||
`SELECT id, branch_code, main_order_code, prep_id::text AS prep_id, our_order_code,
|
||||
our_order_item_id::text AS our_order_item_id, main_supplier_code, main_sku_code,
|
||||
item_name, last_prepare_qty, last_prepare_status, last_return_code,
|
||||
disposition, disposition_reason, writeback_status, last_seen_active_at, payload
|
||||
FROM public.main_system_order_import_items
|
||||
WHERE branch_code = $1
|
||||
AND our_order_code = $2
|
||||
AND disposition IN ('imported','completed','writeback_done')
|
||||
AND COALESCE(writeback_status, 'none') <> 'done'
|
||||
ORDER BY item_name`,
|
||||
[branchCode, orderCode]
|
||||
);
|
||||
return result.rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* 记主系统流转过来的**实际收货量**(R3;2026-10-10)。
|
||||
*
|
||||
* 三条口径:
|
||||
* 1. `actualQty` 为 `null` ⇒ **不动**已有值("未产生实收量"不是"实收 0",不得覆盖);
|
||||
* 2. 实收量**真的变了**(与已存值不同)⇒ 把本地裁决 `qty_decision` 复位为 `none`,
|
||||
* 否则会出现"上次同意过 9.5、这次来了 9.0 却仍算已裁决"的漏判;
|
||||
* 3. 只写台账,**不碰订单行、不碰库存** —— 展示按实收量走读路径,补库存要人工裁决。
|
||||
*/
|
||||
export async function recordPrepActualQty(params: {
|
||||
branchCode: string;
|
||||
prepId: string;
|
||||
actualQty: number | null;
|
||||
qtyDiff: number | null;
|
||||
actualQtyAt: string | null;
|
||||
}): Promise<void> {
|
||||
if (params.actualQty === null) return;
|
||||
await pool.query(
|
||||
`UPDATE public.main_system_order_import_items
|
||||
SET last_actual_qty = $3,
|
||||
last_qty_diff = $4,
|
||||
last_actual_qty_at = COALESCE($5::timestamptz, last_actual_qty_at),
|
||||
-- 实收量变化 ⇒ 上一次裁决作废,重新待决
|
||||
qty_decision = CASE
|
||||
WHEN last_actual_qty IS DISTINCT FROM $3 THEN 'none'
|
||||
ELSE qty_decision
|
||||
END,
|
||||
qty_decision_reason = CASE
|
||||
WHEN last_actual_qty IS DISTINCT FROM $3 THEN NULL
|
||||
ELSE qty_decision_reason
|
||||
END,
|
||||
updated_at = NOW()
|
||||
WHERE branch_code = $1 AND prep_id = $2::uuid`,
|
||||
[params.branchCode, params.prepId, params.actualQty, params.qtyDiff ?? null, params.actualQtyAt ?? null]
|
||||
);
|
||||
}
|
||||
|
||||
export type QtyDecisionRow = {
|
||||
prep_id: string;
|
||||
main_order_code: string;
|
||||
our_order_code: string | null;
|
||||
our_order_item_id: string | null;
|
||||
item_name: string | null;
|
||||
last_prepare_qty: string | number | null;
|
||||
last_actual_qty: string | number | null;
|
||||
last_qty_diff: string | number | null;
|
||||
qty_decision: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* 待人工裁决的「实收量差异」行(qty_diff ≠ 0 且尚未裁决)。
|
||||
* 供后续界面与人工核对使用;本批只提供读路径,**不做自动补库存**(见设计文档 §6 D2)。
|
||||
*/
|
||||
export async function listPendingQtyDecisions(branchCode: string): Promise<QtyDecisionRow[]> {
|
||||
const result = await pool.query<QtyDecisionRow>(
|
||||
`SELECT prep_id::text AS prep_id, main_order_code, our_order_code,
|
||||
our_order_item_id::text AS our_order_item_id, item_name,
|
||||
last_prepare_qty, last_actual_qty, last_qty_diff, qty_decision
|
||||
FROM public.main_system_order_import_items
|
||||
WHERE branch_code = $1
|
||||
AND COALESCE(last_qty_diff, 0) <> 0
|
||||
AND qty_decision = 'none'
|
||||
ORDER BY main_order_code, item_name`,
|
||||
[branchCode]
|
||||
);
|
||||
return result.rows;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* 主系统备货接口 —— **兼容门面**(对外签名与行为一字不变)。
|
||||
*
|
||||
* 2026-10-11 按开发者要求「模块化开发 + 接口注意封装 + 主系统域名统一管理」做了拆分:
|
||||
* · 真实实现移到 `./mainSystem/api/preparations.ts`(接口封装层);
|
||||
* · 域名 / 端点 / HTTP / token 分别收敛到 `./mainSystem/config.ts`、`endpoints.ts`、`http.ts`、`token.ts`;
|
||||
* · 本文件保留原路径与原导出名,因为 5 个业务模块 + 5 个测试都 import 这里(测试还会 mock 本路径),
|
||||
* **不要**把调用方改成直连 `./mainSystem/*`——那样会绕过既有 mock。
|
||||
*
|
||||
* 设计文档:docs/design/20261011-跨系统改价改量审核.md §7。
|
||||
*/
|
||||
|
||||
export {
|
||||
MAIN_SYSTEM_VIEW_LIMIT,
|
||||
fetchMainSystemPreparations,
|
||||
fetchMainSystemArchivedPreparations,
|
||||
isMainSystemPreparationsEnabled as isMainSystemIntegrationEnabled,
|
||||
lookupMainSystemPreparationStates,
|
||||
mapMainPreparationRow,
|
||||
writebackMainSystemPreparationStatus,
|
||||
} from './mainSystem/api/preparations';
|
||||
|
||||
export type {
|
||||
MainOrderGroup,
|
||||
MainPreparationRow,
|
||||
MainPreparationsOutcome,
|
||||
PrepLookupOutcome,
|
||||
PrepLookupResult,
|
||||
WritebackOutcome,
|
||||
WritebackSkippedRow,
|
||||
} from './mainSystem/api/preparations';
|
||||
|
||||
/** 仅供测试:清空对接 token 缓存(原函数名保留) */
|
||||
export { resetMainSystemTokenCache as resetIntegrationTokenCache } from './mainSystem/token';
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,671 @@
|
||||
import { config } from '../config';
|
||||
import { pool } from '../db';
|
||||
import {
|
||||
fetchMainSystemArchivedPreparations,
|
||||
fetchMainSystemPreparations,
|
||||
lookupMainSystemPreparationStates,
|
||||
type MainPreparationsOutcome,
|
||||
type PrepLookupResult,
|
||||
} from './mainSystemPreparations';
|
||||
import {
|
||||
listPrepLedgerRows,
|
||||
markPrepDisposition,
|
||||
listClaimedOrderItemIds,
|
||||
recordImportedPrepItems,
|
||||
setOurOrderItemId,
|
||||
touchLastSeenActiveAt,
|
||||
updatePrepSnapshot,
|
||||
mapPrepRowsToOurItems,
|
||||
type PrepLedgerRow,
|
||||
} from './mainSystemPrepLedger';
|
||||
import { runWithTenantDbContext } from './tenantDbContext';
|
||||
import { releaseReservationsForOrderItem } from './inventoryStockCoverService';
|
||||
import {
|
||||
orderItemHasCompletedPreparation,
|
||||
orderItemHasCompletedPurchase,
|
||||
orderItemHasInspectionInbound,
|
||||
} from './orderItemReturnService';
|
||||
import { removeOrderItemForMainSystemReturn } from './orderManageItemsService';
|
||||
|
||||
/**
|
||||
* 第三方订单(主系统分配)**退货跟随**(2026-10-08)。
|
||||
*
|
||||
* 口径(开发者定稿,见 docs/design/20261008-第三方订单退货跟随与发车回写方案.md):
|
||||
* · 退货由**主系统发起**,本系统只**跟随状态**,不反向确认;
|
||||
* · 退货 = 订单里不再有这个商品(主系统已红冲)⇒ 备货行被物理删除、从 `view=active` 消失;
|
||||
* · 退回(验收不合格、要重新备货)**本次不做**,只记录 `return_code`;
|
||||
* · 不做部分退货;遇到即挂待处理。
|
||||
*
|
||||
* 判据:备货行从 active 消失后,先反查 `view=archived`(按配送日)——
|
||||
* 归档里有 = 正常完成;两边都没有 = 退货。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 单行判定结论:
|
||||
* in_flight 主系统侧还在办理,不动
|
||||
* completed 已完成(订单行仍在且未退货)
|
||||
* returned 主系统已退货红冲
|
||||
* reassigned 已改供别家供应商
|
||||
* cancelled 订单/订单行已删除(取消履约)
|
||||
* inconsistent 备货行还在但状态<30 却不在 active 列表(数据不一致,交人工)
|
||||
* unknown 问不到(不判定,下轮重试)
|
||||
*/
|
||||
export type ReturnVerdict =
|
||||
| 'in_flight'
|
||||
| 'completed'
|
||||
| 'returned'
|
||||
| 'reassigned'
|
||||
| 'cancelled'
|
||||
| 'inconsistent'
|
||||
| 'unknown';
|
||||
|
||||
export type ReturnFollowOutcome = {
|
||||
branchCode: string;
|
||||
activeRows: number;
|
||||
completed: number;
|
||||
cancelled: number;
|
||||
returned: number;
|
||||
/** 主系统把该行改给了别家供应商(我们也按退货同类处置,但单独计数) */
|
||||
reassigned: number;
|
||||
suspended: number;
|
||||
returnPendingNoted: number;
|
||||
snapshotUpdated: number;
|
||||
/** 归档查询不可用等"问不到"的情况:本轮不判定,下轮重试 */
|
||||
unknown: number;
|
||||
failed: number;
|
||||
skippedReason?: string;
|
||||
};
|
||||
|
||||
const ZERO_OUTCOME = (branchCode: string, reason: string): ReturnFollowOutcome => ({
|
||||
branchCode,
|
||||
activeRows: 0,
|
||||
completed: 0,
|
||||
cancelled: 0,
|
||||
returned: 0,
|
||||
reassigned: 0,
|
||||
suspended: 0,
|
||||
returnPendingNoted: 0,
|
||||
snapshotUpdated: 0,
|
||||
unknown: 0,
|
||||
failed: 0,
|
||||
skippedReason: reason,
|
||||
});
|
||||
|
||||
/**
|
||||
* §3.4 库存抵扣补丁(方案 ②:只作用于本流程,**不改公共红冲路径**)。
|
||||
*
|
||||
* 为什么必须补:库存抵扣的成本行是按 `order_code + sku_code` 写的、**没有 `order_item_id`**
|
||||
* (实测主力库 89 行全部为空),而公共红冲的作废 SQL 是 `WHERE order_item_id = $1`
|
||||
* ⇒ 打了折扣的行退货后"销售红冲了、成本没红冲"。
|
||||
* 幂等:amount 已是 0 的行再更新一次无副作用。
|
||||
*/
|
||||
export async function voidInventoryCoverCostForItem(
|
||||
db: { query: (text: string, params?: unknown[]) => Promise<unknown> },
|
||||
params: { orderCode: string; skuCode: string | null; remark: string }
|
||||
): Promise<void> {
|
||||
const sku = String(params.skuCode || '').trim();
|
||||
if (!sku) return;
|
||||
await db.query(
|
||||
`UPDATE cost_details
|
||||
SET amount = 0, allocated_amount = 0, status = 20,
|
||||
remark = COALESCE(NULLIF(TRIM(remark), '') || ';', '') || $3
|
||||
WHERE order_code = $1 AND sku_code = $2 AND cost_source = 'inventory_cover'`,
|
||||
[params.orderCode, sku, params.remark]
|
||||
);
|
||||
}
|
||||
|
||||
type ItemFacts = {
|
||||
itemId: string;
|
||||
skuCode: string | null;
|
||||
orderStatus: number;
|
||||
inbound: boolean;
|
||||
prepCompleted: boolean;
|
||||
purchaseCompleted: boolean;
|
||||
};
|
||||
|
||||
/** 读一次本系统订单行的履约事实(判定"删行 vs 红冲 vs 挂起"用)。租户表,必须在租户上下文里读。 */
|
||||
async function loadItemFacts(branchCode: string, orderCode: string, itemId: string): Promise<ItemFacts | null> {
|
||||
return runWithTenantDbContext(branchCode, async () => {
|
||||
const itemResult = await pool.query(
|
||||
`SELECT oi.id, oi.sku_code, oi.item_name, oi.supplier_code, oi.is_extra_dish,
|
||||
oi.quantity, oi.price, oi.amount, oi.unit_cost,
|
||||
COALESCE(oi.is_returned, false) AS is_returned, oi.return_code,
|
||||
COALESCE(o.order_status, 0) AS order_status
|
||||
FROM order_items oi
|
||||
JOIN orders o ON o.order_code = oi.order_code
|
||||
WHERE oi.id = $1::uuid AND oi.order_code = $2
|
||||
LIMIT 1`,
|
||||
[itemId, orderCode]
|
||||
);
|
||||
if (!itemResult.rowCount) return null;
|
||||
const row = itemResult.rows[0] as Record<string, unknown>;
|
||||
const target = {
|
||||
id: String(row.id),
|
||||
sku_code: (row.sku_code as string) ?? null,
|
||||
item_name: (row.item_name as string) ?? null,
|
||||
};
|
||||
const inbound = await orderItemHasInspectionInbound(pool, orderCode, target);
|
||||
const prepCompleted = !inbound && (await orderItemHasCompletedPreparation(pool, orderCode, target));
|
||||
const purchaseCompleted =
|
||||
!inbound && !prepCompleted && (await orderItemHasCompletedPurchase(pool, orderCode, target));
|
||||
return {
|
||||
itemId: String(row.id),
|
||||
skuCode: (row.sku_code as string) ?? null,
|
||||
orderStatus: Number(row.order_status) || 0,
|
||||
inbound,
|
||||
prepCompleted,
|
||||
purchaseCompleted,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 自愈:整单台账(`main_system_order_imports`)里有单号、但行级台账一行都没有的订单,
|
||||
* 用整单台账里存的 payload 快照补录行级对照。幂等(upsert),只补对照不改业务数据。
|
||||
* @returns 本次补录的行数
|
||||
*/
|
||||
async function repairMissingPrepLedgerRows(branchCode: string): Promise<number> {
|
||||
const missing = await pool.query<{
|
||||
main_order_code: string;
|
||||
our_order_code: string;
|
||||
main_supplier_code: string | null;
|
||||
payload: unknown;
|
||||
}>(
|
||||
`SELECT i.main_order_code, i.our_order_code, i.main_supplier_code, i.payload
|
||||
FROM public.main_system_order_imports i
|
||||
WHERE i.branch_code = $1
|
||||
AND i.our_order_code IS NOT NULL
|
||||
AND (
|
||||
-- 逐行比较:部分写入(前几行成功、后面失败)同样要能自愈,
|
||||
-- 不能只看"整单一行都没有"(对抗式复查 #6)
|
||||
-- ⚠️ 必须按 **main_order_code** 数,不能按 our_order_code:2026-10-10 起
|
||||
-- 同一配送日的多张主系统单共用一张本系统订单,按订单号数会让每张单都"看起来够了"。
|
||||
SELECT count(*) FROM public.main_system_order_import_items li
|
||||
WHERE li.branch_code = i.branch_code AND li.main_order_code = i.main_order_code
|
||||
) < jsonb_array_length(CASE WHEN jsonb_typeof(i.payload) = 'array' THEN i.payload ELSE '[]'::jsonb END)`,
|
||||
[branchCode]
|
||||
);
|
||||
let written = 0;
|
||||
for (const row of missing.rows) {
|
||||
const payload = Array.isArray(row.payload) ? (row.payload as Record<string, unknown>[]) : [];
|
||||
if (!payload.length) continue;
|
||||
// ⚠️ 必须**原样透传整条快照**(只规整 id):台账 `payload` 存的就是这里传进去的对象,
|
||||
// 少了 `deliveryDate` 之类字段,后续就无法反查归档(会退化成"快照缺配送日"而挂起)。
|
||||
const prepRows = payload
|
||||
.filter((raw) => String(raw?.id ?? ''))
|
||||
.map((raw) => ({ ...raw, id: String(raw.id) })) as Parameters<
|
||||
typeof recordImportedPrepItems
|
||||
>[0]['prepRows'];
|
||||
if (!prepRows.length) continue;
|
||||
const ourItems = await runWithTenantDbContext(branchCode, async () =>
|
||||
pool.query<{ id: string; item_name: string | null }>(
|
||||
`SELECT id::text AS id, item_name
|
||||
FROM order_items
|
||||
WHERE order_code = $1
|
||||
ORDER BY sort_order NULLS LAST, created_at, id`,
|
||||
[row.our_order_code]
|
||||
)
|
||||
);
|
||||
written += await recordImportedPrepItems({
|
||||
branchCode,
|
||||
mainOrderCode: row.main_order_code,
|
||||
supplierCode: row.main_supplier_code,
|
||||
ourOrderCode: row.our_order_code,
|
||||
prepRows,
|
||||
ourItems: ourItems.rows,
|
||||
});
|
||||
}
|
||||
return written;
|
||||
}
|
||||
|
||||
/**
|
||||
* 跟随主系统变化(每个第三方分公司跑一轮;由定时对账调用)。
|
||||
* 只处理**已建单**(`disposition='imported'`)且从 active 消失的行。
|
||||
*/
|
||||
export async function followMainSystemPrepChanges(
|
||||
branchCode: string,
|
||||
preloadedActive?: MainPreparationsOutcome
|
||||
): Promise<ReturnFollowOutcome> {
|
||||
if (!config.mainSystemIntegration.returnFollowEnabled) {
|
||||
return ZERO_OUTCOME(branchCode, '退货跟随未开启(MAIN_SYSTEM_RETURN_FOLLOW=1 开启)');
|
||||
}
|
||||
|
||||
// 幂等的前提是"同一时刻只有一个执行者":定时对账在分布式锁之外,多实例或人工触发会并发。
|
||||
// 用与调度同源的分布式锁按**分公司**串行(拿不到就本轮跳过,下轮再来)。见对抗式复查 #9。
|
||||
const { withDistributedLock } = await import('./distributedLock');
|
||||
const locked = await withDistributedLock(`main-system-return:${branchCode}`, 300, async () =>
|
||||
followMainSystemPrepChangesLocked(branchCode, preloadedActive)
|
||||
);
|
||||
return locked ?? ZERO_OUTCOME(branchCode, '另一个实例正在跟随该分公司,本轮跳过');
|
||||
}
|
||||
|
||||
async function followMainSystemPrepChangesLocked(
|
||||
branchCode: string,
|
||||
preloadedActive?: MainPreparationsOutcome
|
||||
): Promise<ReturnFollowOutcome> {
|
||||
const active = preloadedActive ?? (await fetchMainSystemPreparations(branchCode, 'active'));
|
||||
if (active.kind !== 'ok') {
|
||||
return ZERO_OUTCOME(branchCode, `拉取待办备货失败:${active.kind === 'unavailable' ? active.reason : active.reason}`);
|
||||
}
|
||||
|
||||
const activeRows = active.orders.flatMap((group) => group.rows);
|
||||
const activeIds = new Set(activeRows.map((row) => String(row.id)));
|
||||
|
||||
// 主系统列表 LIMIT 500:命中上限说明"返回不完整",缺失的行**不代表**它不存在 ⇒ 本轮不做退货判定
|
||||
// (否则超过 500 行的分公司会把没返回的行当成退货,直接红冲真单)。见对抗式复查 #4。
|
||||
const viewTruncated = Boolean(active.truncated);
|
||||
// 自愈:整单台账里有、行级台账里没有的订单补录一次。
|
||||
// 覆盖两种真实情况:① 建单后行级对照落库失败(当时只记了日志);② 历史数据早于本表。
|
||||
// 失败只记日志,不阻塞本轮跟随。
|
||||
try {
|
||||
const repaired = await repairMissingPrepLedgerRows(branchCode);
|
||||
if (repaired) console.log(`[main-system-return] ${branchCode} 行级对照自愈补录 ${repaired} 行`);
|
||||
} catch (error: unknown) {
|
||||
console.error(
|
||||
`[main-system-return] ${branchCode} 行级对照自愈失败:`,
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
}
|
||||
const ledger = await listPrepLedgerRows(branchCode);
|
||||
const ledgerById = new Map(ledger.map((row) => [String(row.prep_id), row]));
|
||||
|
||||
const outcome: ReturnFollowOutcome = {
|
||||
branchCode,
|
||||
activeRows: activeRows.length,
|
||||
completed: 0,
|
||||
cancelled: 0,
|
||||
returned: 0,
|
||||
reassigned: 0,
|
||||
suspended: 0,
|
||||
returnPendingNoted: 0,
|
||||
snapshotUpdated: 0,
|
||||
unknown: 0,
|
||||
failed: 0,
|
||||
};
|
||||
|
||||
// ① 活跃行:记录"最后一次在 active 见到"(退货判定的前提闸门)+ 刷新快照;
|
||||
// `return_code` 由空变非空 = 主系统**退回**(验收不合格待处理)
|
||||
await touchLastSeenActiveAt({
|
||||
branchCode,
|
||||
prepIds: activeRows
|
||||
.filter((row) => ledgerById.has(String(row.id)))
|
||||
.map((row) => String(row.id)),
|
||||
});
|
||||
for (const row of activeRows) {
|
||||
const existing = ledgerById.get(String(row.id));
|
||||
if (!existing) continue; // 未建单/未登记的行由导入流程处理
|
||||
const qtyChanged = String(existing.last_prepare_qty ?? '') !== String(row.prepareQty ?? '');
|
||||
const statusChanged = Number(existing.last_prepare_status ?? -1) !== Number(row.prepareStatus ?? -1);
|
||||
const returnCode = String(row.returnCode || '').trim() || null;
|
||||
const returnAppeared = !existing.last_return_code && returnCode;
|
||||
if (returnAppeared) {
|
||||
outcome.returnPendingNoted += 1;
|
||||
console.warn(
|
||||
`[main-system-return] ${branchCode} 备货行 ${row.id}(${row.itemName})在主系统出现待处理退回(${returnCode}),` +
|
||||
`本次只记录不处置(退回要重新备货,后续再实现)`
|
||||
);
|
||||
}
|
||||
if (qtyChanged || statusChanged || returnAppeared) {
|
||||
await updatePrepSnapshot({
|
||||
branchCode,
|
||||
prepId: String(row.id),
|
||||
prepareQty: row.prepareQty,
|
||||
prepareStatus: row.prepareStatus,
|
||||
returnCode,
|
||||
});
|
||||
outcome.snapshotUpdated += 1;
|
||||
}
|
||||
}
|
||||
|
||||
// ② 从 active 消失且尚未处置的行 → 反查归档判定「完成」还是「退货」
|
||||
const missing = viewTruncated
|
||||
? []
|
||||
: ledger.filter((row) => row.disposition === 'imported' && !activeIds.has(String(row.prep_id)));
|
||||
if (viewTruncated) {
|
||||
console.warn(
|
||||
`[main-system-return] ${branchCode} 主系统 active 返回 ${active.rowCount} 行(命中 500 上限),` +
|
||||
`本轮跳过退货判定以免误判`
|
||||
);
|
||||
}
|
||||
if (!missing.length) return outcome;
|
||||
|
||||
// ── 判定「完成 / 退货 / 改供 / 取消」────────────────────────────────────────
|
||||
// 首选主系统 2026-10-09 新增的 `POST /preparations/lookup`:**权威**回答
|
||||
// found / order_item_present / is_returned / return_code / current_supplier_code / reassigned,
|
||||
// 直接区分四种事实,不再依赖"消失 + 反查归档区间"那套推断(那套曾因归档日期键与 500 截断误判)。
|
||||
// 台账缺 sku_code(无法 lookup)时才回退到归档区间;两条路径都"问不到就不判定"。
|
||||
const lookupTargets = missing.filter((row) => String(row.main_sku_code || '').trim());
|
||||
const lookupMap = new Map<string, PrepLookupResult>();
|
||||
if (lookupTargets.length) {
|
||||
const outcomeLookup = await lookupMainSystemPreparationStates(
|
||||
branchCode,
|
||||
lookupTargets.slice(0, 2000).map((row) => ({
|
||||
orderCode: String(row.main_order_code || ''),
|
||||
skuCode: String(row.main_sku_code || ''),
|
||||
id: String(row.prep_id),
|
||||
}))
|
||||
);
|
||||
if (outcomeLookup.kind !== 'ok') {
|
||||
// 问不到 ≠ 已退货:整批不判定,下一轮重试(这是本模块的铁律)
|
||||
outcome.unknown += missing.length;
|
||||
console.warn(
|
||||
`[main-system-return] ${branchCode} lookup 不可用(${outcomeLookup.kind}: ${outcomeLookup.reason}),本轮不判定`
|
||||
);
|
||||
return outcome;
|
||||
}
|
||||
for (const item of outcomeLookup.results) {
|
||||
lookupMap.set(`${item.orderCode}::${item.skuCode}`, item);
|
||||
}
|
||||
}
|
||||
|
||||
// 兜底路径用的归档区间缓存(仅台账缺 sku_code 的行会走到)
|
||||
const today = new Date();
|
||||
const toYmd = (d: Date) => d.toISOString().slice(0, 10);
|
||||
const daysBetween = (a: Date, b: Date) => Math.floor((b.getTime() - a.getTime()) / 86400000);
|
||||
const ARCHIVE_WINDOW_DAYS = 89;
|
||||
const archivedCache = new Map<string, Set<string>>();
|
||||
const loadArchivedIds = async (fromYmd: string, toYmdStr: string): Promise<Set<string> | null> => {
|
||||
const key = `${fromYmd}~${toYmdStr}`;
|
||||
const cached = archivedCache.get(key);
|
||||
if (cached) return cached;
|
||||
const archived = await fetchMainSystemArchivedPreparations(branchCode, {
|
||||
dateFrom: fromYmd,
|
||||
dateTo: toYmdStr,
|
||||
});
|
||||
if (archived.kind !== 'ok') return null;
|
||||
const ids = new Set<string>();
|
||||
for (const group of archived.orders) for (const row of group.rows) ids.add(String(row.id));
|
||||
archivedCache.set(key, ids);
|
||||
return ids;
|
||||
};
|
||||
|
||||
for (const row of missing) {
|
||||
try {
|
||||
const prepId = String(row.prep_id);
|
||||
// 关键闸门:只有"我们**确实在 active 里见过它**、之后它不见了"才进入处置判定。
|
||||
// 从没见过的行(启用跟随前的历史数据)绝不自动红冲,只挂人工核对。
|
||||
const lastSeen = row.last_seen_active_at ? new Date(row.last_seen_active_at) : null;
|
||||
if (!lastSeen || Number.isNaN(lastSeen.getTime())) {
|
||||
outcome.suspended += 1;
|
||||
await markPrepDisposition({
|
||||
branchCode,
|
||||
prepId,
|
||||
disposition: 'suspended',
|
||||
reason: '本系统启用退货跟随前该行就已不在 active(历史行),无法判定是完成还是退货,需人工核对',
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const skuCode = String(row.main_sku_code || '').trim();
|
||||
const verdict = skuCode
|
||||
? judgeByLookup(lookupMap.get(`${row.main_order_code}::${skuCode}`))
|
||||
: await judgeByArchived(branchCode, row, { lastSeen, today, toYmd, daysBetween, ARCHIVE_WINDOW_DAYS, loadArchivedIds });
|
||||
|
||||
if (verdict === 'unknown') {
|
||||
outcome.unknown += 1;
|
||||
console.warn(`[main-system-return] ${branchCode} 备货行 ${prepId} 状态问不到,本轮不判定(下轮重试)`);
|
||||
continue;
|
||||
}
|
||||
if (verdict === 'in_flight') {
|
||||
continue; // 主系统那边还在(在途),不动
|
||||
}
|
||||
if (verdict === 'completed') {
|
||||
outcome.completed += 1;
|
||||
await markPrepDisposition({
|
||||
branchCode,
|
||||
prepId,
|
||||
disposition: 'completed',
|
||||
reason: '主系统侧该备货行已结束且订单行仍在(正常完成,非退货)',
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
// 退货 / 改供 / 取消履约:跟随处置(内部再按我们自己的履约事实分叉:删行 or 红冲)
|
||||
if (verdict === 'reassigned') outcome.reassigned += 1;
|
||||
const disposition = await disposeReturnedItem(branchCode, row, verdict);
|
||||
if (disposition === 'cancelled') outcome.cancelled += 1;
|
||||
else if (disposition === 'returned') outcome.returned += 1;
|
||||
else if (disposition === 'suspended') outcome.suspended += 1;
|
||||
else outcome.completed += 1;
|
||||
} catch (error: unknown) {
|
||||
outcome.failed += 1;
|
||||
console.error(
|
||||
`[main-system-return] ${branchCode} 备货行 ${row.prep_id} 退货跟随失败:`,
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return outcome;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 在本系统订单里按商品名对照出订单行 id(租户上下文内执行)。
|
||||
*
|
||||
* ⚠️ **必须包含已退货的行**(`is_returned=true`):退货跟随重跑、或历史行缺对照但它早已被红冲时,
|
||||
* 只有把那一行找出来,下游 `removeOrderItemForMainSystemReturn` 才能返回 `already_returned` 走幂等分支;
|
||||
* 若把已退货行排除掉,这种行会被误判成"未记录到对应订单行"而**永久挂起**。
|
||||
* 同名多行时优先取未退货的那条(`ORDER BY is_returned`)。
|
||||
*/
|
||||
async function resolveOurItemIdByName(
|
||||
branchCode: string,
|
||||
orderCode: string,
|
||||
itemName: string,
|
||||
exceptPrepId?: string
|
||||
): Promise<string> {
|
||||
const name = String(itemName || '').trim();
|
||||
if (!name) return '';
|
||||
// 排除已被同一订单其它备货行认领的订单行,避免"一行被两条备货行认领"(对抗式复查 #11)
|
||||
const claimed = await listClaimedOrderItemIds({
|
||||
branchCode,
|
||||
ourOrderCode: orderCode,
|
||||
exceptPrepId,
|
||||
});
|
||||
return runWithTenantDbContext(branchCode, async () => {
|
||||
const result = await pool.query<{ id: string; item_name: string | null }>(
|
||||
`SELECT id::text AS id, item_name
|
||||
FROM order_items
|
||||
WHERE order_code = $1
|
||||
ORDER BY COALESCE(is_returned, false), sort_order NULLS LAST, created_at, id`,
|
||||
[orderCode]
|
||||
);
|
||||
const available = result.rows.filter((item) => !claimed.has(String(item.id)));
|
||||
const mapping = mapPrepRowsToOurItems([{ id: 'probe', itemName: name }], available);
|
||||
return mapping.get('probe') ?? '';
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/** lookup 结论 → 处置动词。null = 问不到(不判定)。 */
|
||||
export function judgeByLookup(item: PrepLookupResult | undefined): ReturnVerdict {
|
||||
if (!item) return 'unknown'; // 该行没在 lookup 结果里 → 不能当成"已退货"
|
||||
if (item.found) {
|
||||
// 备货行还在主系统:>=30 视为已完成;<30 却没出现在 active 列表里 ⇒ 数据不一致,交人工
|
||||
if (item.prepareStatus != null && item.prepareStatus >= 30) return 'completed';
|
||||
return 'inconsistent';
|
||||
}
|
||||
// 备货行已不在主系统:按订单行的事实区分
|
||||
if (item.isReturned || item.returnCode) return 'returned'; // 主系统已红冲
|
||||
if (item.reassigned) return 'reassigned'; // 已改供别家
|
||||
if (item.orderDeleted || !item.orderItemPresent) return 'cancelled'; // 订单/订单行已删(取消履约)
|
||||
return 'completed'; // 订单行仍在且未退货 ⇒ 正常完成
|
||||
}
|
||||
|
||||
/** 台账缺 sku_code 时的兜底:反查归档区间(问不到 = unknown,绝不判成退货)。 */
|
||||
async function judgeByArchived(
|
||||
branchCode: string,
|
||||
row: PrepLedgerRow,
|
||||
ctx: {
|
||||
lastSeen: Date;
|
||||
today: Date;
|
||||
toYmd: (d: Date) => string;
|
||||
daysBetween: (a: Date, b: Date) => number;
|
||||
ARCHIVE_WINDOW_DAYS: number;
|
||||
loadArchivedIds: (from: string, to: string) => Promise<Set<string> | null>;
|
||||
}
|
||||
): Promise<ReturnVerdict> {
|
||||
const from = new Date(ctx.lastSeen.getTime() - 86400000);
|
||||
if (ctx.daysBetween(from, ctx.today) > ctx.ARCHIVE_WINDOW_DAYS) {
|
||||
await markPrepDisposition({
|
||||
branchCode,
|
||||
prepId: String(row.prep_id),
|
||||
disposition: 'suspended',
|
||||
reason: `台账缺主系统商品编码,且最后一次见到它在 active 是 ${ctx.toYmd(from)},已超出归档区间上限(90 天),需人工核对`,
|
||||
});
|
||||
return 'unknown';
|
||||
}
|
||||
const ids = await ctx.loadArchivedIds(ctx.toYmd(from), ctx.toYmd(ctx.today));
|
||||
if (ids === null) return 'unknown';
|
||||
return ids.has(String(row.prep_id)) ? 'completed' : 'returned';
|
||||
}
|
||||
|
||||
/**
|
||||
* 单行退货处置。返回本系统实际动作:
|
||||
* cancelled 取消履约(未采购、无账务事实 → 删行)
|
||||
* returned 退货红冲(已采购/已备货完成/已入库)
|
||||
* suspended 挂待处理(已发车/已结案/无法定位)
|
||||
* completed 该行其实已处理过(幂等命中)
|
||||
*/
|
||||
async function disposeReturnedItem(
|
||||
branchCode: string,
|
||||
row: PrepLedgerRow,
|
||||
verdict: ReturnVerdict = 'returned'
|
||||
): Promise<'cancelled' | 'returned' | 'suspended' | 'completed'> {
|
||||
const orderCode = String(row.our_order_code || '').trim();
|
||||
let itemId = String(row.our_order_item_id || '').trim();
|
||||
// 惰性对照:历史行可能没有行级对照(迁移无法在 RLS 下回填,见 20261013 迁移说明)。
|
||||
// 在租户上下文里按「同单 + 同商品名」对照一次,成功即回写台账,只需成功一次。
|
||||
if (orderCode && !itemId) {
|
||||
try {
|
||||
itemId = await resolveOurItemIdByName(
|
||||
branchCode,
|
||||
orderCode,
|
||||
String(row.item_name || ''),
|
||||
String(row.prep_id)
|
||||
);
|
||||
if (itemId) {
|
||||
await setOurOrderItemId({ branchCode, prepId: String(row.prep_id), ourOrderItemId: itemId });
|
||||
console.log(
|
||||
`[main-system-return] ${branchCode} 备货行 ${row.prep_id} 惰性对照到本系统订单行 ${itemId}`
|
||||
);
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
console.error(
|
||||
`[main-system-return] ${branchCode} 备货行 ${row.prep_id} 惰性对照失败:`,
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
}
|
||||
}
|
||||
if (!orderCode || !itemId) {
|
||||
await markPrepDisposition({
|
||||
branchCode,
|
||||
prepId: String(row.prep_id),
|
||||
disposition: 'suspended',
|
||||
reason: '主系统已退货,但本系统未记录到对应订单行(历史数据缺对照),需人工核对',
|
||||
});
|
||||
return 'suspended';
|
||||
}
|
||||
|
||||
if (verdict === 'inconsistent') {
|
||||
await markPrepDisposition({
|
||||
branchCode,
|
||||
prepId: String(row.prep_id),
|
||||
disposition: 'suspended',
|
||||
reason: '主系统侧备货行仍在但未完成、且不在待办列表里(数据不一致),需人工核对',
|
||||
});
|
||||
return 'suspended';
|
||||
}
|
||||
|
||||
const facts = await loadItemFacts(branchCode, orderCode, itemId);
|
||||
if (!facts) {
|
||||
await markPrepDisposition({
|
||||
branchCode,
|
||||
prepId: String(row.prep_id),
|
||||
disposition: 'suspended',
|
||||
reason: `未找到本系统订单行(${orderCode} / ${itemId})`,
|
||||
});
|
||||
return 'suspended';
|
||||
}
|
||||
|
||||
// 状态闸门(开发者口径):已发车(≥60)之后主系统侧会拦"不能删退货";
|
||||
// 在对方拦截上线前若仍收到,按异常挂起,**不自动红冲**(货已在路上,属"退回"语义)。
|
||||
if (facts.orderStatus >= 60) {
|
||||
await markPrepDisposition({
|
||||
branchCode,
|
||||
prepId: String(row.prep_id),
|
||||
disposition: 'suspended',
|
||||
reason: `主系统退货,但本系统订单已发车/已结案(order_status=${facts.orderStatus}),需人工处理`,
|
||||
});
|
||||
return 'suspended';
|
||||
}
|
||||
|
||||
// 全流程在该分公司的租户上下文里做(order_items / cost_details / inventory_reservations 都是租户表)。
|
||||
// §3.4 库存抵扣补丁通过 beforeRemove 钩子**进同一个事务**(设计 §3.6):
|
||||
// 补丁与红冲要么一起成功、要么一起回滚,不会留下"成本已作废但销售行还在"的不一致(复查 #5)。
|
||||
let outcome: 'deleted' | 'returned' | 'already_returned';
|
||||
try {
|
||||
outcome = await runWithTenantDbContext(branchCode, async () =>
|
||||
removeOrderItemForMainSystemReturn({
|
||||
orderCode,
|
||||
branchCode,
|
||||
itemId,
|
||||
beforeRemove: async (client) => {
|
||||
await voidInventoryCoverCostForItem(client, {
|
||||
orderCode,
|
||||
skuCode: facts.skuCode,
|
||||
remark: `主系统退货跟随(备货行 ${row.prep_id})作废库存抵扣成本`,
|
||||
});
|
||||
// 删行分支的 hardDelete 内部已释放预留(orderManageItemsService:487),这里只在红冲路径需要补
|
||||
const willRedInk = facts.inbound || facts.prepCompleted || facts.purchaseCompleted;
|
||||
if (willRedInk) await releaseReservationsForOrderItem(client, itemId);
|
||||
},
|
||||
})
|
||||
);
|
||||
} catch (error: unknown) {
|
||||
const code = (error as { code?: string })?.code;
|
||||
const status = (error as { status?: number })?.status;
|
||||
if (code === 'not_found' || status === 404) {
|
||||
// 订单行已经不在了:可能是上次删成功但台账没来得及改(此时不该无限重试)
|
||||
await markPrepDisposition({
|
||||
branchCode,
|
||||
prepId: String(row.prep_id),
|
||||
disposition: 'suspended',
|
||||
reason: '本系统订单行已不存在(可能上次已删除/对照有误),需人工核对台账',
|
||||
});
|
||||
return 'suspended';
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
if (outcome === 'already_returned') {
|
||||
await markPrepDisposition({
|
||||
branchCode,
|
||||
prepId: String(row.prep_id),
|
||||
disposition: 'returned',
|
||||
reason: '该订单行此前已退货(幂等命中)',
|
||||
});
|
||||
return 'completed';
|
||||
}
|
||||
|
||||
const disposition = outcome === 'deleted' ? 'cancelled' : 'returned';
|
||||
const why =
|
||||
verdict === 'reassigned'
|
||||
? '主系统已改供别家供应商'
|
||||
: verdict === 'cancelled'
|
||||
? '主系统已删除该商品/订单'
|
||||
: '主系统退货(红冲)';
|
||||
await markPrepDisposition({
|
||||
branchCode,
|
||||
prepId: String(row.prep_id),
|
||||
disposition,
|
||||
reason:
|
||||
outcome === 'deleted'
|
||||
? `${why}:本系统尚未采购,按取消履约删行`
|
||||
: `${why}:本系统已采购/已入库,按退货红冲跟随`,
|
||||
});
|
||||
console.log(
|
||||
`[main-system-return] ${branchCode} 备货行 ${row.prep_id} → ${disposition}(${orderCode} / ${itemId})`
|
||||
);
|
||||
return disposition as 'cancelled' | 'returned';
|
||||
}
|
||||
@@ -0,0 +1,499 @@
|
||||
import { pool } from '../db';
|
||||
import { runWithTenantDataAccess } from './tenantSchemaService';
|
||||
import { runWithTenantDbContext } from './tenantDbContext';
|
||||
import {
|
||||
lookupMainSystemPreparationStates,
|
||||
writebackMainSystemPreparationStatus,
|
||||
} from './mainSystemPreparations';
|
||||
import { removeOrderItemForMainSystemReturn } from './orderManageItemsService';
|
||||
import { loadWeightUnitFactors, sumWeightInJin } from './unitConversionService';
|
||||
import {
|
||||
orderItemHasCompletedPreparation,
|
||||
orderItemHasCompletedPurchase,
|
||||
orderItemHasInspectionInbound,
|
||||
} from './orderItemReturnService';
|
||||
import {
|
||||
listClaimedOrderItemIds,
|
||||
listPrepLedgerRows,
|
||||
markPrepStockoutRemoved,
|
||||
setOurOrderItemId,
|
||||
type PrepLedgerRow,
|
||||
} from './mainSystemPrepLedger';
|
||||
|
||||
/**
|
||||
* 主系统分配单的「缺货」(开发者 2026-10-10 口径;2026-10-10 追加澄清)。
|
||||
*
|
||||
* ⚠️ **转的是"主系统自采",不是"子系统自采"**(开发者原话:
|
||||
* 「这个缺货调用的是主系统给供应商的接口,是转移给主系统自采而不是子系统的自采」)。
|
||||
* - 主系统侧:`POST /preparations/status` 的 **status=40 = 供应商报缺货** ⇒ 主系统把该备货行
|
||||
* 转成**它自己**去采购(其 `transferPreparationStockoutToPurchase`,落 `is_stockout` + `transferred_to_purchase`);
|
||||
* - 我方:**把这一行从本地清掉**(开发者 2026-10-10 追加口径:
|
||||
* 「点击缺货了,它就不该存在于本地的订单中,包括本地的自采单与备货单里都不该存在这个」)——
|
||||
* 即删除订单行 + 它的待处理采购/备货(复用既有"取消履约"硬删原语,含红冲依据留痕与结算重算)。
|
||||
* **绝不新建任何采购**:本仓的 `preparationStockoutService.transferPreparationStockoutToPurchase`
|
||||
* 是"供货商供不了 ⇒ 我们改自采"的**另一套语义**(会 INSERT 采购单),**本流程禁止调用它**。
|
||||
* - 已经验收入库 / 备货完成 / 采购完成的行**不能"缺货"**(货物事实已经成立,硬删会抹账):
|
||||
* 直接 409 让走售后/退货,绝不悄悄改成红冲。
|
||||
*
|
||||
* 三条纪律:
|
||||
* 1. **先报主系统成功,再改我方状态**(顺序不能反:反了会出现"我方已剔除但主系统还在等我们供货");
|
||||
* 2. 幂等:我方已缺货 ⇒ 直接成功;主系统已 `prepare_status=40` ⇒ 视为已达成,同样收口;
|
||||
* 3. **不动金额**:该行售价/金额是否清零属财务口径,未获批准前一律不改。
|
||||
*/
|
||||
/**
|
||||
* 删行后重算订单头金额/重量。
|
||||
* 口径与「改明细」保存后的重算一致:金额 = 未退货行 `amount` 之和(行上的 amount 就是
|
||||
* `calcItemAmount(quantity, price)` 的落库值);重量按 `sumWeightInJin` 折算到斤。
|
||||
* 为什么必须做:既有的独立删行入口(退货跟随/售后取消履约)都**不**重算订单头,
|
||||
* 缺货是本次新流程,不能一上线就让列表金额挂着已删掉的商品。
|
||||
*/
|
||||
async function recalcOrderHeaderTotals(params: {
|
||||
branchCode: string;
|
||||
orderCode: string;
|
||||
}): Promise<void> {
|
||||
await runWithTenantDataAccess(params.branchCode, async (client) => {
|
||||
const rows = await client.query<{ quantity: string | null; unit: string | null; amount: string | null }>(
|
||||
`SELECT quantity, unit, amount
|
||||
FROM order_items
|
||||
WHERE order_code = $1 AND COALESCE(is_returned, false) = false`,
|
||||
[params.orderCode]
|
||||
);
|
||||
const totalAmount =
|
||||
Math.round(rows.rows.reduce((sum, row) => sum + (Number(row.amount) || 0), 0) * 100) / 100;
|
||||
const weightFactors = await loadWeightUnitFactors(client);
|
||||
const totalWeight = sumWeightInJin(
|
||||
rows.rows.map((row) => ({ quantity: Number(row.quantity) || 0, unit: String(row.unit || '斤') })),
|
||||
weightFactors
|
||||
);
|
||||
await client.query(
|
||||
`UPDATE orders SET total_amount = $2, total_weight = $3, updated_at = NOW() WHERE order_code = $1`,
|
||||
[params.orderCode, totalAmount, totalWeight]
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 「缺货」操作日志(开发者 2026-10-10:操作日志需要记录点击过缺货)。
|
||||
*
|
||||
* 两类触发都记:`trigger='user'`(详情页按钮)与 `trigger='reconcile'`(对账自动跟随,
|
||||
* 操作人为空 = 系统);`removal` 说明本地是否真被剔除(`missing` = 之前已清过,幂等重复点击也留痕)。
|
||||
* 写失败不阻断主流程(与订单明细保存的审计同款纪律)。
|
||||
*/
|
||||
async function writeMainSystemStockoutAuditLog(params: {
|
||||
branchCode: string;
|
||||
orderCode: string;
|
||||
itemId: string;
|
||||
prepId: string | null;
|
||||
reason: string;
|
||||
mainOrderCode: string | null;
|
||||
actor: { userId: string | null; roles: string | null };
|
||||
ipAddress: string | null;
|
||||
alreadyReported: boolean;
|
||||
trigger: 'user' | 'reconcile';
|
||||
removal: 'removed' | 'blocked' | 'missing';
|
||||
snapshot: {
|
||||
item_name: string | null;
|
||||
sku_code: string | null;
|
||||
quantity: number | null;
|
||||
unit: string | null;
|
||||
price: number | null;
|
||||
amount: number | null;
|
||||
} | null;
|
||||
}): Promise<void> {
|
||||
try {
|
||||
const { writeAuditLog } = await import('./auditService');
|
||||
await writeAuditLog({
|
||||
operatorId: params.actor.userId,
|
||||
operatorRole: params.actor.roles,
|
||||
operationType: 'main_system_stockout',
|
||||
targetTable: 'order_items',
|
||||
targetId: params.itemId,
|
||||
branchCode: params.branchCode,
|
||||
actionCategory: 'order',
|
||||
ipAddress: params.ipAddress,
|
||||
oldValue: {
|
||||
order_code: params.orderCode,
|
||||
item_id: params.itemId,
|
||||
item_name: params.snapshot?.item_name ?? null,
|
||||
sku_code: params.snapshot?.sku_code ?? null,
|
||||
quantity: params.snapshot?.quantity ?? null,
|
||||
unit: params.snapshot?.unit ?? null,
|
||||
price: params.snapshot?.price ?? null,
|
||||
amount: params.snapshot?.amount ?? null,
|
||||
},
|
||||
newValue: {
|
||||
order_code: params.orderCode,
|
||||
item_id: params.itemId,
|
||||
main_order_code: params.mainOrderCode,
|
||||
prep_id: params.prepId,
|
||||
reason: params.reason,
|
||||
// 主系统侧:status=40 = 报缺货 ⇒ **主系统**把该行转自采(不是子系统自采)
|
||||
main_system_status: 40,
|
||||
already_reported: params.alreadyReported,
|
||||
trigger: params.trigger,
|
||||
// 本地处置:removed=已从订单/自采/备货里剔除
|
||||
local_removal: params.removal,
|
||||
},
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
console.error(
|
||||
`[main-system-stockout] 操作日志写入失败 ${params.branchCode} ${params.itemId}:`,
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export type StockoutOutcome =
|
||||
| {
|
||||
kind: 'ok';
|
||||
ourOrderCode: string;
|
||||
itemId: string;
|
||||
prepId: string;
|
||||
/** true = 主系统那边已经是缺货状态(本次未重复写入) */
|
||||
alreadyReported: boolean;
|
||||
}
|
||||
| { kind: 'not_main_system_item'; reason: string }
|
||||
| { kind: 'invalid_state'; reason: string }
|
||||
| { kind: 'unavailable'; reason: string }
|
||||
| { kind: 'rejected'; reason: string };
|
||||
|
||||
/** 该订单是否是主系统分配过来的(删除/缺货守卫与界面都读这一条) */
|
||||
export async function isMainSystemImportedOrder(params: {
|
||||
branchCode: string;
|
||||
ourOrderCode: string;
|
||||
}): Promise<boolean> {
|
||||
const result = await pool.query(
|
||||
`SELECT 1 FROM public.main_system_order_imports
|
||||
WHERE branch_code = $1 AND our_order_code = $2
|
||||
LIMIT 1`,
|
||||
[params.branchCode, params.ourOrderCode]
|
||||
);
|
||||
return Boolean(result.rowCount);
|
||||
}
|
||||
|
||||
/** 该明细对应的主系统备货行(台账按 our_order_item_id 定位;没有则按名字惰性对照一次) */
|
||||
async function resolvePrepLedgerRow(params: {
|
||||
branchCode: string;
|
||||
ourOrderCode: string;
|
||||
itemId: string;
|
||||
itemName: string | null;
|
||||
}): Promise<PrepLedgerRow | null> {
|
||||
const direct = await pool.query<PrepLedgerRow>(
|
||||
`SELECT id, branch_code, main_order_code, prep_id::text AS prep_id, our_order_code,
|
||||
our_order_item_id::text AS our_order_item_id, main_supplier_code, main_sku_code,
|
||||
item_name, last_prepare_qty, last_prepare_status, last_return_code,
|
||||
disposition, disposition_reason, writeback_status, last_seen_active_at, payload
|
||||
FROM public.main_system_order_import_items
|
||||
WHERE branch_code = $1 AND our_order_item_id = $2::uuid
|
||||
LIMIT 1`,
|
||||
[params.branchCode, params.itemId]
|
||||
);
|
||||
if (direct.rowCount) return direct.rows[0];
|
||||
|
||||
// 惰性对照(与退货跟随同一套做法):同行同名的未对照行里取第一条,认领后写回,避免一行两认领
|
||||
const rows = await listPrepLedgerRows(params.branchCode);
|
||||
const name = String(params.itemName || '').trim();
|
||||
if (!name) return null;
|
||||
const candidates = rows.filter(
|
||||
(row) =>
|
||||
String(row.our_order_code || '') === params.ourOrderCode &&
|
||||
!row.our_order_item_id &&
|
||||
String(row.item_name || '').trim() === name &&
|
||||
row.disposition !== 'returned' &&
|
||||
row.disposition !== 'cancelled'
|
||||
);
|
||||
if (candidates.length !== 1) return null;
|
||||
const candidate = candidates[0];
|
||||
const claimed = await listClaimedOrderItemIds({
|
||||
branchCode: params.branchCode,
|
||||
ourOrderCode: params.ourOrderCode,
|
||||
exceptPrepId: String(candidate.prep_id),
|
||||
});
|
||||
if (claimed.has(params.itemId)) return null;
|
||||
await setOurOrderItemId({
|
||||
branchCode: params.branchCode,
|
||||
prepId: String(candidate.prep_id),
|
||||
ourOrderItemId: params.itemId,
|
||||
});
|
||||
return { ...candidate, our_order_item_id: params.itemId };
|
||||
}
|
||||
|
||||
export type StockoutRemovalResult =
|
||||
| {
|
||||
kind: 'removed';
|
||||
/** 删行前的快照(写操作日志用) */
|
||||
snapshot: {
|
||||
item_name: string | null;
|
||||
sku_code: string | null;
|
||||
quantity: number | null;
|
||||
unit: string | null;
|
||||
price: number | null;
|
||||
amount: number | null;
|
||||
};
|
||||
}
|
||||
/** 已有货物事实(已验收入库/备货完成/采购完成)或已退货 ⇒ 不能删,交售后 */
|
||||
| { kind: 'blocked'; reason: string }
|
||||
/** 本地本来就没有这一行(幂等:上一次已经清过) */
|
||||
| { kind: 'missing' };
|
||||
|
||||
/**
|
||||
* 把一行从本地**清掉**(订单行 + 它的待处理采购/备货/履约行),并重算订单头。
|
||||
*
|
||||
* 两个入口共用:① 详情页「缺货」按钮(报主系统成功之后);② 对账自动跟随
|
||||
* (主系统把该行转自采 / 改派走了 ⇒ 本地不该再存在,见 `settleRowsNoLongerOurs`)。
|
||||
* 判据用既有"取消履约"那三条 exported 谓词,保证与手工删行同口径;
|
||||
* 已有货物事实的行一律 `blocked`,绝不悄悄改成红冲。
|
||||
*/
|
||||
export async function removeLocalLineForStockout(params: {
|
||||
branchCode: string;
|
||||
orderCode: string;
|
||||
itemId: string;
|
||||
/** 台账 prep_id:给了就记处置(清对照 + skipped_stockout),供"又分配回来"时复位 */
|
||||
prepId?: string | null;
|
||||
reason: string;
|
||||
}): Promise<StockoutRemovalResult> {
|
||||
const { branchCode, orderCode, itemId, reason } = params;
|
||||
const prepId = String(params.prepId || '').trim();
|
||||
|
||||
const item = await runWithTenantDataAccess(branchCode, async (client) => {
|
||||
const result = await client.query<{
|
||||
id: string;
|
||||
item_name: string | null;
|
||||
sku_code: string | null;
|
||||
quantity: string | null;
|
||||
unit: string | null;
|
||||
price: string | null;
|
||||
amount: string | null;
|
||||
is_returned: boolean;
|
||||
}>(
|
||||
`SELECT id::text AS id, item_name, sku_code, quantity, unit, price, amount,
|
||||
COALESCE(is_returned, false) AS is_returned
|
||||
FROM order_items
|
||||
WHERE id = $1::uuid AND order_code = $2
|
||||
LIMIT 1`,
|
||||
[itemId, orderCode]
|
||||
);
|
||||
return result.rows[0] ?? null;
|
||||
});
|
||||
if (!item) return { kind: 'missing' };
|
||||
if (item.is_returned) return { kind: 'blocked', reason: '该商品已退货' };
|
||||
|
||||
const blocked = await runWithTenantDataAccess(branchCode, async (client) => {
|
||||
const target = { id: itemId, sku_code: item.sku_code, item_name: item.item_name };
|
||||
if (await orderItemHasInspectionInbound(client, orderCode, target)) return '已验收入库';
|
||||
if (await orderItemHasCompletedPreparation(client, orderCode, target)) return '备货已完成';
|
||||
if (await orderItemHasCompletedPurchase(client, orderCode, target)) return '采购已完成';
|
||||
return null;
|
||||
});
|
||||
if (blocked) return { kind: 'blocked', reason: `该商品${blocked},不能再按缺货剔除(请走售后退货处理)` };
|
||||
|
||||
// 自建租户上下文:删除原语内部用 `pool.connect()` + 未限定表名,没上下文会 42P01
|
||||
const removal = await runWithTenantDbContext(branchCode, () =>
|
||||
removeOrderItemForMainSystemReturn({ orderCode, branchCode, itemId })
|
||||
);
|
||||
if (removal === 'already_returned') return { kind: 'blocked', reason: '该商品已退货' };
|
||||
if (removal !== 'deleted') {
|
||||
return { kind: 'blocked', reason: '该商品已有货物事实(转红冲处理),请走售后退货' };
|
||||
}
|
||||
|
||||
if (prepId) {
|
||||
await markPrepStockoutRemoved({
|
||||
branchCode,
|
||||
prepId,
|
||||
reason,
|
||||
}).catch((error: unknown) => {
|
||||
console.error(
|
||||
`[main-system-stockout] 台账处置落库失败 ${branchCode} ${prepId}:`,
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// 删行后订单头金额/重量必须跟着走
|
||||
await recalcOrderHeaderTotals({ branchCode, orderCode }).catch((error: unknown) => {
|
||||
console.error(
|
||||
`[main-system-stockout] 订单头重算失败 ${branchCode} ${orderCode}:`,
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
kind: 'removed',
|
||||
snapshot: {
|
||||
item_name: item.item_name,
|
||||
sku_code: item.sku_code,
|
||||
quantity: item.quantity == null ? null : Number(item.quantity),
|
||||
unit: item.unit,
|
||||
price: item.price == null ? null : Number(item.price),
|
||||
amount: item.amount == null ? null : Number(item.amount),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 报缺货:主系统 status=40 转自采 + 我方收口。
|
||||
* 调用方(路由)必须已确认操作权限并处于租户上下文。
|
||||
*/
|
||||
export async function reportMainSystemStockout(params: {
|
||||
branchCode: string;
|
||||
orderCode: string;
|
||||
itemId: string;
|
||||
reason?: string | null;
|
||||
userId?: string | null;
|
||||
/** 操作日志用:操作人角色与来源 IP(路由层传,缺省也能写) */
|
||||
operatorRoles?: string | null;
|
||||
ipAddress?: string | null;
|
||||
}): Promise<StockoutOutcome> {
|
||||
const branchCode = String(params.branchCode || '').trim();
|
||||
const orderCode = String(params.orderCode || '').trim();
|
||||
const itemId = String(params.itemId || '').trim();
|
||||
const reason = String(params.reason || '').trim().slice(0, 200) || '缺货';
|
||||
|
||||
if (!branchCode || !orderCode || !itemId) {
|
||||
return { kind: 'invalid_state', reason: '缺少分公司、订单号或明细 id' };
|
||||
}
|
||||
if (!(await isMainSystemImportedOrder({ branchCode, ourOrderCode: orderCode }))) {
|
||||
return { kind: 'not_main_system_item', reason: '该订单不是主系统分配过来的,不能用「缺货」' };
|
||||
}
|
||||
|
||||
const item = await runWithTenantDataAccess(branchCode, async (client) => {
|
||||
const result = await client.query<{
|
||||
id: string;
|
||||
item_name: string | null;
|
||||
sku_code: string | null;
|
||||
is_returned: boolean;
|
||||
is_stockout: boolean;
|
||||
stockout_reported_at: string | null;
|
||||
}>(
|
||||
`SELECT id::text AS id, item_name, sku_code, COALESCE(is_returned, false) AS is_returned,
|
||||
COALESCE(is_stockout, false) AS is_stockout, stockout_reported_at
|
||||
FROM order_items
|
||||
WHERE id = $1::uuid AND order_code = $2
|
||||
LIMIT 1`,
|
||||
[itemId, orderCode]
|
||||
);
|
||||
return result.rows[0] ?? null;
|
||||
});
|
||||
if (!item) {
|
||||
return { kind: 'invalid_state', reason: '订单明细不存在或不属于该订单' };
|
||||
}
|
||||
if (item.is_returned) {
|
||||
return { kind: 'invalid_state', reason: '该商品已退货,不能再报缺货' };
|
||||
}
|
||||
const ledgerRow = await resolvePrepLedgerRow({
|
||||
branchCode,
|
||||
ourOrderCode: orderCode,
|
||||
itemId,
|
||||
itemName: item.item_name,
|
||||
});
|
||||
const prepId = String(ledgerRow?.prep_id || '');
|
||||
|
||||
// ① 先报主系统:status=40 ⇒ 主系统把该行转自采(**主系统**自采,不是我们)
|
||||
let alreadyReported = false;
|
||||
if (item.is_stockout) {
|
||||
// 已报过(幂等;也覆盖"改造前只打标签没删行"的历史行):不重复发 HTTP,
|
||||
// **但本地清理照做** —— 否则这些行永远删不掉(界面也已经不给再点了)。
|
||||
alreadyReported = true;
|
||||
} else if (!ledgerRow) {
|
||||
return {
|
||||
kind: 'not_main_system_item',
|
||||
reason: '这一行找不到对应的主系统备货行(对照缺失),请先在子系统里核对后再报缺货',
|
||||
};
|
||||
} else {
|
||||
const writeback = await writebackMainSystemPreparationStatus({
|
||||
supplierCode: branchCode,
|
||||
preparationId: prepId,
|
||||
status: 40,
|
||||
stockoutReason: reason,
|
||||
});
|
||||
if (writeback.kind === 'ok') {
|
||||
alreadyReported = false;
|
||||
} else if (writeback.kind === 'already_done') {
|
||||
alreadyReported = true;
|
||||
} else if (writeback.kind === 'unavailable') {
|
||||
// 主系统未确认写入 ⇒ 本地一律不动,让用户稍后重试
|
||||
// (顺序纪律:不能出现"我方已剔除、主系统还在等我们供货")。
|
||||
// 先问一次 lookup:主系统那边已经是 40(缺货)时按"已达成"处理,避免永远点不动。
|
||||
const looked = await lookupMainSystemPreparationStates(branchCode, [
|
||||
{ orderCode: String(ledgerRow.main_order_code || ''), skuCode: String(ledgerRow.main_sku_code || ''), id: prepId },
|
||||
]).catch(() => null);
|
||||
const state = looked?.kind === 'ok' ? looked.results.find((row) => row.id === prepId) : undefined;
|
||||
if (state?.found && Number(state.prepareStatus) === 40) {
|
||||
alreadyReported = true;
|
||||
} else {
|
||||
return { kind: 'unavailable', reason: writeback.reason || '主系统未确认,请稍后重试' };
|
||||
}
|
||||
} else {
|
||||
return { kind: 'rejected', reason: writeback.reason || '主系统拒绝了本次缺货上报' };
|
||||
}
|
||||
}
|
||||
|
||||
// ② 本地**清干净**(开发者 2026-10-10:缺货了本地就不该再有这个商品)
|
||||
const removed = await removeLocalLineForStockout({
|
||||
branchCode,
|
||||
orderCode,
|
||||
itemId,
|
||||
prepId,
|
||||
reason: `本系统报缺货(主系统转自采):${reason}`,
|
||||
});
|
||||
if (removed.kind === 'blocked') {
|
||||
return { kind: 'invalid_state', reason: removed.reason };
|
||||
}
|
||||
|
||||
// ③ 操作日志:**点过缺货**必须留痕(开发者 2026-10-10 要求)
|
||||
await writeMainSystemStockoutAuditLog({
|
||||
branchCode,
|
||||
orderCode,
|
||||
itemId,
|
||||
prepId: prepId || null,
|
||||
reason,
|
||||
mainOrderCode: String(ledgerRow?.main_order_code || '') || null,
|
||||
actor: { userId: params.userId ?? null, roles: params.operatorRoles ?? null },
|
||||
ipAddress: params.ipAddress ?? null,
|
||||
alreadyReported,
|
||||
trigger: 'user',
|
||||
removal: removed.kind,
|
||||
snapshot: removed.kind === 'removed' ? removed.snapshot : null,
|
||||
});
|
||||
|
||||
return { kind: 'ok', ourOrderCode: orderCode, itemId, prepId, alreadyReported };
|
||||
}
|
||||
|
||||
/**
|
||||
* 对账自动跟随的「缺货」也要进操作日志(操作人为空 = 系统触发)。
|
||||
* 由 `settleRowsNoLongerOurs` 调用;失败不阻断。
|
||||
*/
|
||||
export async function logAutoStockoutRemoval(params: {
|
||||
branchCode: string;
|
||||
orderCode: string;
|
||||
itemId: string;
|
||||
prepId: string;
|
||||
/** 来源主系统订单号(写进日志详情,便于按单排查) */
|
||||
mainOrderCode?: string | null;
|
||||
itemName: string | null;
|
||||
reason: string;
|
||||
removal: 'removed' | 'blocked' | 'missing';
|
||||
snapshot: {
|
||||
item_name: string | null;
|
||||
sku_code: string | null;
|
||||
quantity: number | null;
|
||||
unit: string | null;
|
||||
price: number | null;
|
||||
amount: number | null;
|
||||
} | null;
|
||||
}): Promise<void> {
|
||||
await writeMainSystemStockoutAuditLog({
|
||||
branchCode: params.branchCode,
|
||||
orderCode: params.orderCode,
|
||||
itemId: params.itemId,
|
||||
prepId: params.prepId,
|
||||
reason: params.reason,
|
||||
mainOrderCode: String(params.mainOrderCode || '') || null,
|
||||
actor: { userId: null, roles: null },
|
||||
ipAddress: null,
|
||||
alreadyReported: true,
|
||||
trigger: 'reconcile',
|
||||
removal: params.removal,
|
||||
snapshot: params.snapshot,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
import { config } from '../config';
|
||||
|
||||
/**
|
||||
* 向主系统(AI 生鲜配送)校验「供应商账号」的凭据,并取回供应商档案。
|
||||
*
|
||||
* 背景(见 .cursor/rules/01-second-dev-supplier.mdc「两层供应商语义」):
|
||||
* 本系统的「分公司」= 主系统的「供应商」;本系统的「供应商」= 厂商(与主系统无关)。
|
||||
* 本系统的分公司管理员账号就是主系统的供应商账号(登录名 = 手机号),
|
||||
* 密码权威在主系统 —— 因此登录时必须回主系统校验,本地不保存可用密码。
|
||||
*
|
||||
* 实现说明:本期直接复用主系统**已有的** `POST /api/supplier/login`
|
||||
* (实测返回体含 profile.supplier.supplier_code / company_name,正好是开通分公司所需字段),
|
||||
* 这样**无需改动主系统**即可先跑通登录链路。
|
||||
* 生产化建议:主系统另加一个带签名 + IP 白名单 + 限流的服务间端点,
|
||||
* 不要把无限流的对客登录接口长期当作服务间校验通道(已记入规则文档待办)。
|
||||
*/
|
||||
|
||||
/** 中国大陆手机号:本系统的分公司管理员登录名就是手机号 */
|
||||
const MAINLAND_PHONE_RE = /^1[3-9]\d{9}$/;
|
||||
|
||||
export type MainSupplierProfile = {
|
||||
/** 主系统供应商编码,用作本系统的分公司编码(如 SUP37831443) */
|
||||
supplierCode: string;
|
||||
/** 主系统供应商名称,用作分公司名称 */
|
||||
companyName: string;
|
||||
/** 联系人(主系统账号的 full_name) */
|
||||
contactName: string;
|
||||
/** 登录手机号 */
|
||||
phone: string;
|
||||
/** 主系统侧的分公司与名称(仅留痕/排障用,不参与本系统建模) */
|
||||
mainBranchCode: string | null;
|
||||
mainBranchName: string | null;
|
||||
};
|
||||
|
||||
export type MainSupplierVerifyOutcome =
|
||||
/**
|
||||
* 校验通过。
|
||||
* ok = 凭据正确
|
||||
* invalid = 主系统**明确答复**凭据不对/账号不可用(密码错、已停用、需选分公司)
|
||||
* unavailable = **没问成**(未配置、超时、网络错、5xx)—— 调用方必须 fail closed
|
||||
*/
|
||||
| { kind: 'ok'; profile: MainSupplierProfile }
|
||||
| { kind: 'invalid'; reason: string }
|
||||
| { kind: 'unavailable'; reason: string };
|
||||
|
||||
export function looksLikeSupplierLoginName(loginName: string): boolean {
|
||||
return MAINLAND_PHONE_RE.test(String(loginName || '').trim());
|
||||
}
|
||||
|
||||
export function isMainSystemVerificationEnabled(): boolean {
|
||||
return Boolean(config.mainSystem.baseUrl);
|
||||
}
|
||||
|
||||
export async function verifySupplierCredentialOnMainSystem(
|
||||
username: string,
|
||||
password: string
|
||||
): Promise<MainSupplierVerifyOutcome> {
|
||||
const { baseUrl, timeoutMs, supplierLoginPath } = config.mainSystem;
|
||||
if (!baseUrl) {
|
||||
return { kind: 'unavailable', reason: 'main_system_not_configured' };
|
||||
}
|
||||
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
||||
try {
|
||||
const response = await fetch(`${baseUrl}${supplierLoginPath}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
// ⚠️ 绝不记录 password;此处只发往主系统
|
||||
body: JSON.stringify({ username, password }),
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
const raw = await response.text();
|
||||
let payload: any = null;
|
||||
try {
|
||||
payload = raw ? JSON.parse(raw) : null;
|
||||
} catch {
|
||||
payload = null;
|
||||
}
|
||||
|
||||
// ⚠️ 只有「主系统**明确拒绝了这个凭据**」才叫 invalid;其余非 2xx 一律算 unavailable(没问成)。
|
||||
//
|
||||
// 实测(2026-10-08 核对主系统 index.ts:110-114):主系统对 /api/supplier/login 挂了
|
||||
// loginIpLimiter 80 次/10 分钟/**IP** + loginLimiter 30 次/10 分钟/账号。
|
||||
// 我们是从本系统这一台机器**服务间**调用 ⇒ 所有供应商共用同一个 IP 配额,
|
||||
// 超过就会拿到 429。若把 429 当成"凭据错",供应商会看到"密码错误"而百思不得其解,
|
||||
// 还会把"主系统限流"误判成"密码被改"。必须归到 unavailable(→ 503)。
|
||||
const CREDENTIAL_REJECTION_STATUS = new Set([400, 401, 403]);
|
||||
if (!response.ok && !CREDENTIAL_REJECTION_STATUS.has(response.status)) {
|
||||
console.warn(`[main-auth] 主系统校验返回 ${response.status}(非凭据拒绝),按不可用处理`);
|
||||
return { kind: 'unavailable', reason: `main_http_${response.status}` };
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
return { kind: 'invalid', reason: String(payload?.error || `main_http_${response.status}`) };
|
||||
}
|
||||
|
||||
// 主系统要求先选分公司(一个账号挂多个供应商):本期不支持,按登录失败处理并留痕
|
||||
if (payload?.need_branch) {
|
||||
console.warn(`[main-auth] 账号命中多个分公司(need_branch),本期不支持:${username}`);
|
||||
return { kind: 'invalid', reason: 'need_branch' };
|
||||
}
|
||||
|
||||
const supplier = payload?.profile?.supplier;
|
||||
const supplierCode = String(supplier?.supplier_code || '').trim();
|
||||
if (!supplierCode) {
|
||||
console.warn(`[main-auth] 主系统返回缺少 supplier_code:${username}`);
|
||||
return { kind: 'invalid', reason: 'supplier_code_missing' };
|
||||
}
|
||||
|
||||
return {
|
||||
kind: 'ok',
|
||||
profile: {
|
||||
supplierCode,
|
||||
companyName: String(supplier?.company_name || '').trim() || supplierCode,
|
||||
contactName: String(payload?.profile?.full_name || '').trim(),
|
||||
phone: String(payload?.profile?.phone || username).trim(),
|
||||
mainBranchCode: payload?.profile?.branch_code ?? null,
|
||||
mainBranchName: payload?.profile?.branch_name ?? null,
|
||||
},
|
||||
};
|
||||
} catch (error: any) {
|
||||
const aborted = error?.name === 'AbortError';
|
||||
console.warn(`[main-auth] 主系统校验未完成(${aborted ? 'timeout' : 'network_error'}):${error?.message || error}`);
|
||||
return { kind: 'unavailable', reason: aborted ? 'timeout' : 'network_error' };
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,390 @@
|
||||
import { config } from '../config';
|
||||
import { pool } from '../db';
|
||||
import { writebackMainSystemPreparationStatus } from './mainSystemPreparations';
|
||||
import { getApprovedFinalValues, isEnabled as isPriceQtyRequestEnabled } from './mainSystemPriceQtyRequest';
|
||||
import {
|
||||
listRowsPendingWriteback,
|
||||
markWriteback,
|
||||
mapPrepRowsToOurItems,
|
||||
isOrderFullySkipInbound,
|
||||
setOurOrderItemId,
|
||||
type PrepLedgerRow,
|
||||
} from './mainSystemPrepLedger';
|
||||
import { runWithTenantDbContext } from './tenantDbContext';
|
||||
|
||||
/**
|
||||
* 发车 → 回写主系统「备货完成」(2026-10-08)。
|
||||
*
|
||||
* 为什么必须回写:
|
||||
* 1. 主系统 `confirm_required=true`(默认)时,**必须收到 `status=30` 才进入待验入库**,
|
||||
* 否则整条验收/结算链停住;
|
||||
* 2. 开发者已确认"已发车了主系统不能点击删除退货"——那道拦截的依据正是**我们已发车**,
|
||||
* 而主系统唯一的信息来源就是这次回写。
|
||||
* 见 docs/design/20261008-第三方订单退货跟随与发车回写方案.md §3.5。
|
||||
*
|
||||
* 三条硬规则(都不得影响发车本身):
|
||||
* ① 出网 HTTP 永远在数据库事务之外;失败只记账 + 下轮重试;
|
||||
* ② 我价 ≤ 0 的行**跳过回写**(主系统完成时价格校验可能拒 0),不因一行卡住整单;
|
||||
* ③ 实供量 > 主系统备货量时带 `confirm_over_qty`;仍被拒则记 rejected 挂人工。
|
||||
*/
|
||||
|
||||
export type WritebackRunOutcome = {
|
||||
orderCode: string;
|
||||
attempted: number;
|
||||
done: number;
|
||||
/** 主系统侧已是完成(幂等跳过),等价于成功 */
|
||||
alreadyDone: number;
|
||||
skippedZeroPrice: number;
|
||||
rejected: number;
|
||||
unavailable: number;
|
||||
};
|
||||
|
||||
type OurItemRow = {
|
||||
id: string;
|
||||
sku_code: string | null;
|
||||
item_name: string | null;
|
||||
quantity: string | number | null;
|
||||
unit: string | null;
|
||||
price: string | number | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 回写某张已发车订单的全部备货行。**非阻塞调用方**(发车流程)不应 await 其失败。
|
||||
* 本函数自身不抛错:任何异常都记进台账并返回统计。
|
||||
*/
|
||||
export async function writebackDeliveredOrderToMainSystem(
|
||||
branchCode: string,
|
||||
orderCode: string
|
||||
): Promise<WritebackRunOutcome> {
|
||||
const outcome: WritebackRunOutcome = {
|
||||
orderCode,
|
||||
attempted: 0,
|
||||
done: 0,
|
||||
alreadyDone: 0,
|
||||
skippedZeroPrice: 0,
|
||||
rejected: 0,
|
||||
unavailable: 0,
|
||||
};
|
||||
if (!config.mainSystemIntegration.writebackEnabled) return outcome;
|
||||
|
||||
let rows: PrepLedgerRow[] = [];
|
||||
let ourItems = new Map<string, OurItemRow>();
|
||||
try {
|
||||
rows = await listRowsPendingWriteback(branchCode, orderCode);
|
||||
if (!rows.length) return outcome;
|
||||
const items = await runWithTenantDbContext(branchCode, async () =>
|
||||
pool.query<OurItemRow>(
|
||||
`SELECT id::text AS id, sku_code, item_name, quantity, unit, price
|
||||
FROM order_items
|
||||
WHERE order_code = $1
|
||||
ORDER BY sort_order NULLS LAST, created_at, id`,
|
||||
[orderCode]
|
||||
)
|
||||
);
|
||||
ourItems = new Map(items.rows.map((row) => [String(row.id), row]));
|
||||
|
||||
// 惰性对照:历史行可能没有行级对照(迁移无法在 RLS 下回填,见 20261013 迁移说明)。
|
||||
// 这里按「同单 + 同商品名」对照一次并回写台账,成功一次即可。
|
||||
if (rows.some((row) => !row.our_order_item_id)) {
|
||||
const taken = new Set(
|
||||
rows.filter((row) => row.our_order_item_id).map((row) => String(row.our_order_item_id))
|
||||
);
|
||||
const unmapped = rows.filter((row) => !row.our_order_item_id);
|
||||
// 候选里排除已被同单其它备货行占用的订单行(避免一行被两条备货行认领,复查 #11)
|
||||
const available = items.rows.filter((item) => !taken.has(String(item.id)));
|
||||
const mapping = mapPrepRowsToOurItems(
|
||||
unmapped.map((row) => ({ id: String(row.prep_id), itemName: row.item_name })),
|
||||
available
|
||||
);
|
||||
for (const row of unmapped) {
|
||||
const resolved = mapping.get(String(row.prep_id));
|
||||
if (!resolved) continue;
|
||||
row.our_order_item_id = resolved;
|
||||
await setOurOrderItemId({ branchCode, prepId: String(row.prep_id), ourOrderItemId: resolved });
|
||||
}
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
console.error(
|
||||
`[main-system-writeback] ${branchCode} ${orderCode} 读取待回写行失败:`,
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
return outcome;
|
||||
}
|
||||
|
||||
for (const row of rows) {
|
||||
const item = row.our_order_item_id ? ourItems.get(String(row.our_order_item_id)) : undefined;
|
||||
if (!item) {
|
||||
await markWriteback({
|
||||
branchCode,
|
||||
prepId: String(row.prep_id),
|
||||
status: 'suspended',
|
||||
reason: '未找到对应订单行,无法回写',
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const price = Number(item.price);
|
||||
if (!Number.isFinite(price) || price <= 0) {
|
||||
outcome.skippedZeroPrice += 1;
|
||||
await markWriteback({
|
||||
branchCode,
|
||||
prepId: String(row.prep_id),
|
||||
status: 'skipped_zero_price',
|
||||
reason: '本系统该行销售价为 0,跳过回写(避免被主系统价格校验拒绝),补价后再回写',
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const qty = Number(item.quantity);
|
||||
const allocatedQty = Number(row.last_prepare_qty);
|
||||
const overQty =
|
||||
Number.isFinite(qty) && Number.isFinite(allocatedQty) && allocatedQty > 0 && qty > allocatedQty + 1e-9;
|
||||
|
||||
// C5「堵住静默通道」(设计文档 20261011 §4/§7):
|
||||
// 改价/改量审核总开关打开后,只有**经本流程确认**的价格才允许随回写进入主系统;
|
||||
// 否则等于绕过主系统审核直接改它的成本价。开关关闭(默认)= 与改造前逐字节一致。
|
||||
let purchasePriceForWriteback: number | undefined = price;
|
||||
let priceGateNote = '';
|
||||
if (isPriceQtyRequestEnabled()) {
|
||||
const approved = await getApprovedFinalValues({ branchCode, prepId: String(row.prep_id) });
|
||||
const approvedPrice = approved?.finalPrice ?? null;
|
||||
if (approvedPrice === null || Math.abs(approvedPrice - price) > 1e-6) {
|
||||
purchasePriceForWriteback = undefined;
|
||||
priceGateNote = ';价格未经改价审核流程确认,本次不回写价格';
|
||||
}
|
||||
}
|
||||
|
||||
outcome.attempted += 1;
|
||||
const result = await writebackMainSystemPreparationStatus({
|
||||
supplierCode: branchCode,
|
||||
preparationId: String(row.prep_id),
|
||||
status: 30,
|
||||
prepareQty: Number.isFinite(qty) ? qty : null,
|
||||
purchasePrice: purchasePriceForWriteback,
|
||||
unit: item.unit ?? null,
|
||||
confirmOverQty: overQty,
|
||||
});
|
||||
|
||||
if (result.kind === 'ok') {
|
||||
// 主系统 2026-10-09 起回传 updated / skipped:**updated=0 说明没写进去**,不得记 done。
|
||||
if (result.updated >= 1) {
|
||||
outcome.done += 1;
|
||||
await markWriteback({
|
||||
branchCode,
|
||||
prepId: String(row.prep_id),
|
||||
status: 'done',
|
||||
reason: `已回写备货完成(数量 ${qty},单价 ${price}${overQty ? ',超量已带确认位' : ''}${priceGateNote})`,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const skip =
|
||||
result.skipped.find((s) => s.id && s.id === String(row.prep_id)) ??
|
||||
result.skipped.find((s) => s.skuCode && s.skuCode === String(item.sku_code || '')) ??
|
||||
result.skipped[0];
|
||||
if (!skip) {
|
||||
// 主系统只说"没写进去"却没给原因:当**暂态**处理,下轮兜底重试;绝不记 done
|
||||
outcome.unavailable += 1;
|
||||
await markWriteback({
|
||||
branchCode,
|
||||
prepId: String(row.prep_id),
|
||||
status: 'suspended',
|
||||
reason: '主系统返回 updated=0 且未给出跳过原因,下轮重试',
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const reason = skip.reason;
|
||||
const detail = skip.message ? `${skip.message}(${reason})` : reason;
|
||||
if (reason === 'already_completed') {
|
||||
// 主系统侧已是备货完成 → 幂等命中,等价于成功
|
||||
outcome.alreadyDone += 1;
|
||||
await markWriteback({
|
||||
branchCode,
|
||||
prepId: String(row.prep_id),
|
||||
status: 'done',
|
||||
reason: `主系统侧已是备货完成(幂等跳过):${detail}`,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (reason === 'row_not_updated') {
|
||||
// UPDATE 影响 0 行(并发改走/删除)→ 暂态,下轮兜底重试
|
||||
outcome.unavailable += 1;
|
||||
await markWriteback({
|
||||
branchCode,
|
||||
prepId: String(row.prep_id),
|
||||
status: 'suspended',
|
||||
reason: `主系统未写入(${detail}),下轮重试`,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
// transferred_to_purchase / status_regression 等:重试也不会好 → 不再重试
|
||||
outcome.rejected += 1;
|
||||
await markWriteback({
|
||||
branchCode,
|
||||
prepId: String(row.prep_id),
|
||||
status: 'rejected',
|
||||
reason: `主系统跳过未写入:${detail}`,
|
||||
});
|
||||
console.warn(`[main-system-writeback] ${branchCode} 备货行 ${row.prep_id} 未写入:${detail}`);
|
||||
continue;
|
||||
}
|
||||
if (result.kind === 'already_done') {
|
||||
outcome.alreadyDone += 1;
|
||||
await markWriteback({
|
||||
branchCode,
|
||||
prepId: String(row.prep_id),
|
||||
status: 'done',
|
||||
reason: `主系统侧已是完成/已锁定(幂等命中):${result.reason}`,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (result.kind === 'rejected') {
|
||||
outcome.rejected += 1;
|
||||
await markWriteback({
|
||||
branchCode,
|
||||
prepId: String(row.prep_id),
|
||||
status: 'rejected',
|
||||
reason: `主系统拒绝:${result.reason}`,
|
||||
});
|
||||
console.warn(`[main-system-writeback] ${branchCode} 备货行 ${row.prep_id} 被主系统拒绝:${result.reason}`);
|
||||
continue;
|
||||
}
|
||||
outcome.unavailable += 1;
|
||||
await markWriteback({
|
||||
branchCode,
|
||||
prepId: String(row.prep_id),
|
||||
status: 'suspended',
|
||||
reason: `主系统暂不可用:${result.reason}`,
|
||||
});
|
||||
}
|
||||
|
||||
if (outcome.attempted || outcome.skippedZeroPrice) {
|
||||
console.log(
|
||||
`[main-system-writeback] ${branchCode} ${orderCode}:回写 ${outcome.done}/${outcome.attempted} 成功` +
|
||||
`(另 ${outcome.alreadyDone} 条主系统侧已完成),0 价跳过 ${outcome.skippedZeroPrice},` +
|
||||
`被拒 ${outcome.rejected},暂不可用 ${outcome.unavailable}`
|
||||
);
|
||||
}
|
||||
return outcome;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发车成功后触发(**非阻塞**):不 await、不抛错,回写失败绝不影响发车结果。
|
||||
* 调用点见 orderWorkflowFulfillmentService.tryAdvanceOrderToDelivering(50→60 唯一写入点)。
|
||||
*/
|
||||
export function enqueueMainSystemWritebackForDeliveredOrder(params: {
|
||||
branchCode: string | null;
|
||||
orderCode: string;
|
||||
}): void {
|
||||
const branch = String(params?.branchCode || '').trim();
|
||||
const code = String(params?.orderCode || '').trim();
|
||||
if (!config.mainSystemIntegration.writebackEnabled) return;
|
||||
// 缺分公司/单号直接跳过:回写内核按 (分公司, 我方单号) 定位台账,
|
||||
// 参数不全只会静默 0 行(2026-10-11 复核:原先位置参数被写反过一次,故改为对象参数)
|
||||
if (!branch || !code) return;
|
||||
void writebackDeliveredOrderToMainSystem(branch, code).catch((error: unknown) => {
|
||||
console.error(
|
||||
`[main-system-writeback] ${branch} ${code} 回写异常:`,
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* **我方货备齐**时触发(2026-10-10 新增)。
|
||||
*
|
||||
* 为什么需要它:主系统「免入库」订单我方**不过配送**(不经过 50→60),
|
||||
* 而回写原来只挂在 50→60 ⇒ 免入库单**永远不回写 `status=30`**;
|
||||
* 而主系统的免入库覆盖判据要求 `prepare_status >= 30` ⇒ 主系统订单不推进 ⇒
|
||||
* 配送员不上门 ⇒ `preparations.picked_up` 永不触发(死锁,见设计文档 §2.1 F7)。
|
||||
*
|
||||
* 必须在**事务提交后**调用(HTTP 永不在事务内);与发车回写共用同一内核与同款纪律:
|
||||
* 非阻塞、失败只记账、由对账兜底重试。
|
||||
*/
|
||||
export function enqueueMainSystemWritebackForReadyOrder(params: {
|
||||
branchCode: string | null;
|
||||
orderCode: string;
|
||||
}): void {
|
||||
const branch = String(params?.branchCode || '').trim();
|
||||
const code = String(params?.orderCode || '').trim();
|
||||
if (!config.mainSystemIntegration.writebackEnabled) return;
|
||||
// 同 `...ForDeliveredOrder`:参数不全就跳过,别拿去查台账(只会 0 行、白跑一趟)
|
||||
if (!branch || !code) return;
|
||||
void writebackDeliveredOrderToMainSystem(branch, code).catch((error: unknown) => {
|
||||
console.error(
|
||||
`[main-system-writeback] ${branch} ${code} 备齐回写异常:`,
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 「我方货备齐」的统一判定 + 触发(2026-10-10 补)。
|
||||
*
|
||||
* 只对**主系统免入库**订单生效;不是免入库单、或没有台账对照(原生订单)⇒ 什么都不做。
|
||||
*
|
||||
* ⚠️ **事务纪律(必须遵守)**:只能在**数据库事务之外**调用,或只在传入的语句已自动提交之后调用。
|
||||
* - `processingTaskService.maybeAdvanceOrderAfterFulfillment`:用 `pool`,无事务 ⇒ 可调;
|
||||
* - `preparationFulfillmentService.tryAdvanceOrderToInspection`:**只在 `!client` 时**可调
|
||||
* (无 client 即 `pool`,UPDATE 已自动提交);传了 client 说明在调用方事务里,
|
||||
* 此时**不要调**,交给 15 分钟对账的 `retryPendingWritebacksForBranch` 兜底。
|
||||
*/
|
||||
export async function enqueueSkipInboundWritebackIfReady(
|
||||
params: {
|
||||
branchCode: string | null;
|
||||
orderCode: string;
|
||||
db?: { query: (sql: string, values?: unknown[]) => Promise<{ rows: Array<{ skip: boolean | null }> }> };
|
||||
}
|
||||
): Promise<void> {
|
||||
const branch = String(params?.branchCode || '').trim();
|
||||
const code = String(params?.orderCode || '').trim();
|
||||
const db = params?.db;
|
||||
if (!config.mainSystemIntegration.writebackEnabled) return;
|
||||
if (!config.mainSystemIntegration.skipInboundAwaitPickup) return;
|
||||
if (!branch || !code) return;
|
||||
try {
|
||||
const skipInbound = await isOrderFullySkipInbound({ branchCode: branch, ourOrderCode: code, db });
|
||||
if (!skipInbound) return;
|
||||
} catch (error: unknown) {
|
||||
// 判定失败只是漏一次即时回写,对账会补 —— 但绝不能把调用方的业务流程带崩
|
||||
console.error(
|
||||
`[main-system-writeback] ${branch} ${code} 免入库判定失败(交对账兜底):`,
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
return;
|
||||
}
|
||||
enqueueMainSystemWritebackForReadyOrder({ branchCode: branch, orderCode: code });
|
||||
}
|
||||
|
||||
/**
|
||||
* 兜底重试:把该分公司「已发车但未回写成功」的行补一次(进程崩溃/主系统抖动后的补偿)。
|
||||
* 由定时对账按分公司调用,成本只与"待回写量"有关。
|
||||
*/
|
||||
export async function retryPendingWritebacksForBranch(branchCode: string): Promise<number> {
|
||||
if (!config.mainSystemIntegration.writebackEnabled) return 0;
|
||||
const pending = await pool.query<{ our_order_code: string }>(
|
||||
`SELECT DISTINCT our_order_code
|
||||
FROM public.main_system_order_import_items
|
||||
WHERE branch_code = $1
|
||||
AND our_order_code IS NOT NULL
|
||||
-- skipped_zero_price 也纳入:运营补价后由下一轮自动补回写(否则该行永远不会被回写)
|
||||
AND COALESCE(writeback_status, 'none') IN ('none', 'suspended', 'skipped_zero_price')
|
||||
AND disposition IN ('imported', 'completed')`,
|
||||
[branchCode]
|
||||
);
|
||||
let done = 0;
|
||||
for (const row of pending.rows) {
|
||||
const orderCode = String(row.our_order_code || '').trim();
|
||||
if (!orderCode) continue;
|
||||
const status = await runWithTenantDbContext(branchCode, async () =>
|
||||
pool.query(`SELECT order_status FROM orders WHERE order_code = $1 LIMIT 1`, [orderCode])
|
||||
);
|
||||
const orderStatus = Number(status.rows[0]?.order_status);
|
||||
// 2026-10-11 定稿:**任何单**(送仓/免入库)只要已到「待配送(50)」就该回写 `status=30`
|
||||
// —— 主系统要靠它显示"备货完成"并推进后续(免入库更依赖它派车,见设计文档 20261010 §2.1 F7)。
|
||||
// 未到 50(还在备货/验收)不回写,避免把未备齐的单标记成已完成。
|
||||
if (orderStatus < 50) continue;
|
||||
const result = await writebackDeliveredOrderToMainSystem(branchCode, orderCode);
|
||||
done += result.done;
|
||||
}
|
||||
return done;
|
||||
}
|
||||
@@ -87,6 +87,15 @@ export interface ReprocessOrderResult {
|
||||
|
||||
/** 关智能分配时的调用意图 */
|
||||
export type ReprocessAllocationOptions = {
|
||||
/**
|
||||
* 放行零价明细。默认 false(硬拦)。
|
||||
* 只有两条路径会传 true,都来自主系统分配过来的备货任务(主系统的成本价=我们的销售价,
|
||||
* 那边没定价时就是 0;用户 2026-10-08 明确允许这类订单零价):
|
||||
* 1) 导入建单,`customerOrderSubmitService` 透传;
|
||||
* 2) 同一主订单后来追加分配的行,`syncOrderManageItems({ allowUnpriced: true })`。
|
||||
* 其它入口(Web 改明细、小程序改单、手动分配)一律保持硬拦。
|
||||
*/
|
||||
allowUnpriced?: boolean;
|
||||
/**
|
||||
* 关模式下:true=确认分配(空供应商转自采,要求全覆盖);
|
||||
* false/缺省=仅落已有供应商备货,未指定行保持待分配、不升 30、不报履约不全。
|
||||
@@ -1755,7 +1764,7 @@ async function reprocessOrderAllocationUnlocked(
|
||||
// 闸门读取失败不阻断分配
|
||||
}
|
||||
|
||||
await assertNoZeroPriceItems(orderCode, client, false, '分配');
|
||||
await assertNoZeroPriceItems(orderCode, client, options.allowUnpriced === true, '分配');
|
||||
|
||||
const smartEnabled = await isSmartAllocationEnabled(effectiveBranch);
|
||||
result.smartAllocationEnabled = smartEnabled;
|
||||
|
||||
@@ -283,6 +283,30 @@ async function resolveOperatorName(userId: string, client: PoolClient): Promise<
|
||||
}
|
||||
|
||||
/** 移入垃圾桶:保留明细与履约数据,财务/列表不再计入(B7: deleted_at=已取消,附 cancel_reason) */
|
||||
/**
|
||||
* 主系统分配过来的订单**禁止删除**(开发者 2026-10-10)。
|
||||
* 台账里有对照(`main_system_order_imports.our_order_code`)即认定;
|
||||
* 原生订单不受影响(反向对照见 tests/mainSystemDayMergeAndStockout.test.ts 与实测)。
|
||||
*/
|
||||
async function assertNotMainSystemOrder(
|
||||
client: { query: (text: string, values?: unknown[]) => Promise<{ rowCount: number | null }> },
|
||||
orderCode: string,
|
||||
branchCode: string | null
|
||||
): Promise<void> {
|
||||
const imported = await client.query(
|
||||
`SELECT 1 FROM public.main_system_order_imports
|
||||
WHERE branch_code = $1 AND our_order_code = $2
|
||||
LIMIT 1`,
|
||||
[branchCode, orderCode]
|
||||
);
|
||||
if (imported.rowCount) {
|
||||
throw Object.assign(
|
||||
new Error('主系统分配过来的订单不能删除;商品供不了请用明细上的「缺货」'),
|
||||
{ status: 409, code: 'main_system_order_locked' }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function moveOrderToTrash(
|
||||
orderCode: string,
|
||||
ctx: TenantContext,
|
||||
@@ -316,6 +340,11 @@ export async function moveOrderToTrash(
|
||||
throw Object.assign(new Error('订单已在垃圾桶中'), { status: 409, code: 'already_trashed' });
|
||||
}
|
||||
|
||||
// 主系统分配过来的订单**不能删**(开发者 2026-10-10 口径):它是主系统备货任务的镜像,
|
||||
// 删掉会让退货跟随/发车回写失去锚点,而主系统那边仍认为我们在备货。
|
||||
// "这单供不了"要用明细上的「缺货」按钮(报主系统 status=40 转自采)。
|
||||
await assertNotMainSystemOrder(client, code, order.branch_code || ctx.branchCode || null);
|
||||
|
||||
const itemSnapshot = await loadOrderItemSnapshot(client, code);
|
||||
const operatorName = await resolveOperatorName(ctx.userId, client);
|
||||
const updated = await client.query(
|
||||
@@ -564,6 +593,10 @@ export async function deleteOrderWithDependencies(
|
||||
code: 'not_trashed',
|
||||
});
|
||||
}
|
||||
// 主系统分配过来的订单**不能删**(开发者 2026-10-10):这是通用数据网关
|
||||
// (`/api/data` 的 orders delete 特判)与"垃圾桶彻底删除"共用的入口,
|
||||
// 只拦 `moveOrderToTrash` 会漏掉这两条路。
|
||||
await assertNotMainSystemOrder(client, code, order.branch_code || ctx.branchCode || null);
|
||||
|
||||
const itemSnapshot = await loadOrderItemSnapshot(client, code);
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
reprocessOrderAllocation,
|
||||
syncOpenPurchaseQtyForOrder,
|
||||
syncPurchaseQtyFromFulfillments,
|
||||
type ReprocessAllocationOptions,
|
||||
} from './orderAllocationService';
|
||||
import { withAllocationSlot } from './allocationConcurrency';
|
||||
import {
|
||||
@@ -34,6 +35,12 @@ import { upsertCustomerQuoteItemCosts } from './quoteSheetService';
|
||||
import { getTenantDbStore } from './tenantDbContext';
|
||||
import { loadWeightUnitFactors, sumWeightInJin } from './unitConversionService';
|
||||
import { writeAuditLog } from './auditService';
|
||||
import {
|
||||
assertMainSystemPriceQtyReviewed,
|
||||
isEnabled as isPriceQtyRequestEnabled,
|
||||
isMainSystemAllocatedLines,
|
||||
type PriceQtyChange,
|
||||
} from './mainSystemPriceQtyRequest';
|
||||
import {
|
||||
buildOrderItemsEditAuditPayload,
|
||||
type ExistingOrderItemForAudit,
|
||||
@@ -677,6 +684,45 @@ async function syncPurchaserLinkedPurchaseSnapshots(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 比对「已存在的订单行」的价格/数量是否被本次改明细改动(供主系统行的改价改量守卫使用)。
|
||||
* 只比较已存在的行(新增行不算改价改量);已退货行跳过。
|
||||
*/
|
||||
function collectMainSystemPriceQtyChanges(
|
||||
existingMap: Map<
|
||||
string,
|
||||
{
|
||||
id: string;
|
||||
item_name?: string | null;
|
||||
price?: number | null;
|
||||
quantity?: number | null;
|
||||
is_returned?: boolean | null;
|
||||
}
|
||||
>,
|
||||
incoming: OrderManageItemInput[]
|
||||
): PriceQtyChange[] {
|
||||
const EPS = 1e-6;
|
||||
const changes: PriceQtyChange[] = [];
|
||||
for (const row of incoming) {
|
||||
const id = trimText(row.id);
|
||||
if (!id || isTempId(id)) continue;
|
||||
const existing = existingMap.get(id);
|
||||
if (!existing || existing.is_returned) continue;
|
||||
const name = trimText(existing.item_name) || trimText(row.item_name) || id;
|
||||
const oldPrice = Number(existing.price) || 0;
|
||||
const newPrice = Number(row.price) || 0;
|
||||
if (Math.abs(oldPrice - newPrice) > EPS) {
|
||||
changes.push({ itemId: id, itemName: name, field: 'price', from: oldPrice, to: newPrice });
|
||||
}
|
||||
const oldQty = Number(existing.quantity) || 0;
|
||||
const newQty = Number(row.quantity) || 0;
|
||||
if (Math.abs(oldQty - newQty) > EPS) {
|
||||
changes.push({ itemId: id, itemName: name, field: 'quantity', from: oldQty, to: newQty });
|
||||
}
|
||||
}
|
||||
return changes;
|
||||
}
|
||||
|
||||
export async function syncOrderManageItems(params: {
|
||||
orderCode: string;
|
||||
items: OrderManageItemInput[];
|
||||
@@ -697,6 +743,18 @@ export async function syncOrderManageItems(params: {
|
||||
purchaserDirectAllocation?: { purchaserCode: string };
|
||||
/** 小程序采购员加单可在保存事务内新建/复用商品档案 */
|
||||
provisionPurchaserOrderSkus?: boolean;
|
||||
/**
|
||||
* 放行订单内的零价明细(透传给分配)。默认 false(硬拦)。
|
||||
* 追加行专用:主系统分配过来的备货任务,其成本价=我们的销售价,那边没定价时就是 0;
|
||||
* 这类订单再追加新分配的行时,不能被已有零价行挡住(用户 2026-10-08 明确允许零价)。
|
||||
*/
|
||||
allowUnpriced?: boolean;
|
||||
/**
|
||||
* 内部路径专用:本次改价/改量是「跨系统改价改量申请」的**已生效/已审核**落地
|
||||
* (`mainSystemPriceQtyRequest.applyFinalPriceQtyToOurOrderItem`),跳过"必须走申请"的守卫。
|
||||
* ⚠️ 除该申请落地外不得传 true —— 传了就等于绕过主系统审核改它的成本价。
|
||||
*/
|
||||
mainSystemPriceQtyApproved?: boolean;
|
||||
operatorId?: string | null;
|
||||
operatorRoles?: string | null;
|
||||
/** Web 详情:与明细同一 PATCH 写订单头,避免先走 /api/data */
|
||||
@@ -731,6 +789,11 @@ export async function syncOrderManageItems(params: {
|
||||
throw Object.assign(new Error('订单至少保留一项商品'), { status: 400, code: 'invalid_request' });
|
||||
}
|
||||
|
||||
/** 透传给分配:放行订单内既有零价行(默认不放行,保持原硬拦口径) */
|
||||
const unpricedOpt: ReprocessAllocationOptions = params.allowUnpriced === true
|
||||
? { allowUnpriced: true }
|
||||
: {};
|
||||
|
||||
const orderResult = await pool.query(
|
||||
`SELECT order_code, order_status, customer_code, branch_code, created_at
|
||||
FROM orders WHERE order_code = $1 LIMIT 1`,
|
||||
@@ -818,7 +881,7 @@ export async function syncOrderManageItems(params: {
|
||||
}
|
||||
const existingResult = await client.query(
|
||||
`SELECT id, sku_code, item_name, supplier_code, is_extra_dish, quantity, price, amount, unit_cost,
|
||||
unit, remark,
|
||||
unit, remark, main_order_code,
|
||||
COALESCE(is_returned, false) AS is_returned, return_code
|
||||
FROM order_items WHERE order_code = $1`,
|
||||
[orderCode]
|
||||
@@ -839,6 +902,8 @@ export async function syncOrderManageItems(params: {
|
||||
unit_cost?: number | null;
|
||||
unit?: string | null;
|
||||
remark?: string | null;
|
||||
/** 主系统订单号(迁移 20261015 的行级来源标记;可能为 NULL) */
|
||||
main_order_code?: string | null;
|
||||
}])
|
||||
);
|
||||
const existingExtraDishIds = new Set(
|
||||
@@ -877,6 +942,59 @@ export async function syncOrderManageItems(params: {
|
||||
if (id && !isTempId(id)) keptIds.add(id);
|
||||
}
|
||||
|
||||
// 主系统分配过来的订单:**商品不能删**(开发者 2026-10-10 口径)。
|
||||
// 它的每一行都对着主系统一条备货行(退货红冲/发车回写靠这条对照定位);
|
||||
// 供不了要用「缺货」按钮报主系统转自采,而不是把行删掉。
|
||||
// 注意:第三方退货跟随走的是 `removeOrderItemForMainSystemReturn`(独立入口),不受本守卫影响。
|
||||
const removedIds = [...existingMap.entries()]
|
||||
.filter(([id, row]) => !keptIds.has(id) && !row.is_returned)
|
||||
.map(([id]) => id);
|
||||
if (removedIds.length) {
|
||||
const mainSystemOrder = await client.query(
|
||||
`SELECT 1 FROM public.main_system_order_imports
|
||||
WHERE branch_code = $1 AND our_order_code = $2
|
||||
LIMIT 1`,
|
||||
[order.branch_code || null, orderCode]
|
||||
);
|
||||
if (mainSystemOrder.rowCount) {
|
||||
const names = removedIds
|
||||
.map((id) => trimText(existingMap.get(id)?.item_name) || id)
|
||||
.slice(0, 5);
|
||||
throw Object.assign(
|
||||
new Error(`主系统分配过来的商品不能删除(${names.join('、')});供不了请用「缺货」`),
|
||||
{ status: 409, code: 'main_system_item_locked' }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 主系统分配过来的订单:**改价/改量要走申请**(开发者 2026-10-11 口径)。
|
||||
// 为什么拦在服务层:改明细有 5 个入口(Web / 小程序 ×3 / MCP),只在界面分流会被绕过;
|
||||
// 免审项(补价、改低、减量)在申请入口提交后立即生效,涨价/加量等主系统管理员审核。
|
||||
// 开关关闭时(默认)本守卫直接放行 ⇒ 与改造前逐字节一致。
|
||||
// 已审核/免审的落地路径传 `params.mainSystemPriceQtyApproved = true` 放行。
|
||||
if (!params.mainSystemPriceQtyApproved && isPriceQtyRequestEnabled()) {
|
||||
const changes = collectMainSystemPriceQtyChanges(existingMap, incoming);
|
||||
if (changes.length) {
|
||||
// ⚠️ 必须按**行**判:主系统单是按配送日合并的一张单,上面允许加本系统自建行/加菜行,
|
||||
// 那些行在主系统没有备货行(提交申请必然失败)⇒ 按整单判会把它们的正常改价堵死。
|
||||
const { guarded } = await isMainSystemAllocatedLines({
|
||||
branchCode: order.branch_code || '',
|
||||
ourOrderCode: orderCode,
|
||||
candidates: changes.map((change) => ({
|
||||
itemId: change.itemId,
|
||||
itemName: change.itemName,
|
||||
skuCode: existingMap.get(change.itemId)?.sku_code ?? null,
|
||||
mainOrderCode: existingMap.get(change.itemId)?.main_order_code ?? null,
|
||||
})),
|
||||
query: (sql, values) => client.query(sql, values as unknown[]),
|
||||
});
|
||||
assertMainSystemPriceQtyReviewed({
|
||||
isMainSystemOrder: true,
|
||||
changes: changes.filter((change) => guarded.has(change.itemId)),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for (const [id, row] of existingMap) {
|
||||
if (!keptIds.has(id)) {
|
||||
if (row.is_returned) continue;
|
||||
@@ -1530,6 +1648,7 @@ export async function syncOrderManageItems(params: {
|
||||
autoAllocateItemIds,
|
||||
forceSelfPurchaseItemIds,
|
||||
supplierSwitchItemIds,
|
||||
...unpricedOpt,
|
||||
...(orderStatus === 50
|
||||
? {
|
||||
onlyItemIds: newlyInsertedNonExtraIds,
|
||||
@@ -1541,8 +1660,9 @@ export async function syncOrderManageItems(params: {
|
||||
? {
|
||||
onlyItemIds: newlyInsertedNonExtraIds,
|
||||
skipPerOrderAutoBidGate: true,
|
||||
...unpricedOpt,
|
||||
}
|
||||
: undefined
|
||||
: (Object.keys(unpricedOpt).length ? unpricedOpt : undefined)
|
||||
);
|
||||
const softAllocationWarnings = (allocation.errors || []).filter((msg) =>
|
||||
/未配置(?:主)?采购员|待人工处理/.test(String(msg || ''))
|
||||
@@ -1705,7 +1825,7 @@ export async function syncOrderManageItems(params: {
|
||||
order.customer_code,
|
||||
order.branch_code,
|
||||
undefined,
|
||||
skipOpts
|
||||
{ ...skipOpts, ...unpricedOpt }
|
||||
);
|
||||
if (skipOpts.excludeSkuCodes?.length) {
|
||||
allocation.deferredForBid = true;
|
||||
@@ -1717,7 +1837,7 @@ export async function syncOrderManageItems(params: {
|
||||
order.customer_code,
|
||||
order.branch_code,
|
||||
undefined,
|
||||
{ skipPerOrderAutoBidGate: true, excludeSkuCodes }
|
||||
{ skipPerOrderAutoBidGate: true, excludeSkuCodes, ...unpricedOpt }
|
||||
);
|
||||
partial.deferredForBid = true;
|
||||
partial.deferredBidSkuCodes = excludeSkuCodes;
|
||||
@@ -1730,7 +1850,7 @@ export async function syncOrderManageItems(params: {
|
||||
order.customer_code,
|
||||
order.branch_code,
|
||||
undefined,
|
||||
{ skipPerOrderAutoBidGate: true, excludeSkuCodes }
|
||||
{ skipPerOrderAutoBidGate: true, excludeSkuCodes, ...unpricedOpt }
|
||||
);
|
||||
partial.deferredForBid = true;
|
||||
partial.deferredBidSkuCodes = excludeSkuCodes;
|
||||
@@ -1753,7 +1873,7 @@ export async function syncOrderManageItems(params: {
|
||||
order.customer_code,
|
||||
order.branch_code,
|
||||
undefined,
|
||||
skipOpts
|
||||
{ ...skipOpts, ...unpricedOpt }
|
||||
);
|
||||
if (skipOpts.excludeSkuCodes?.length) {
|
||||
allocation.deferredForBid = true;
|
||||
@@ -1815,6 +1935,92 @@ export async function syncOrderManageItems(params: {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 第三方订单(主系统分配)**退货跟随**专用入口(2026-10-08)。
|
||||
*
|
||||
* 走的是与「订单改明细删行」**完全相同**的删行/红冲路径(同一个 removeOrReturnOrderItem +
|
||||
* 同一个 deleteOrderItemWithDependencies),不新造任何红冲语义:
|
||||
* · 未采购、未备货完成 ⇒ 取消履约(删行 + 清孤儿备货/待采)
|
||||
* · 已采购 / 已备货完成 / 已验收入库 ⇒ OIR_ 退货单 + 销售/成本红冲 + 应付冲回 + 结算重算
|
||||
*
|
||||
* 与人工改单的差别只有两点,都是刻意的:
|
||||
* 1. 不受 `canEditOrderItemsForStatus` 的权限闸门约束(这是主系统发起的被动跟随,不是人改单);
|
||||
* **状态闸门由调用方负责**(设计文档 §3.3:已发车 ≥60 必须挂起、不得自动红冲)。
|
||||
* 2. 只处理**这一行**,不动同单其他明细。
|
||||
* 见 docs/design/20261008-第三方订单退货跟随与发车回写方案.md §3.3。
|
||||
*/
|
||||
export async function removeOrderItemForMainSystemReturn(params: {
|
||||
orderCode: string;
|
||||
branchCode?: string | null;
|
||||
itemId: string;
|
||||
/**
|
||||
* 在同一事务内、红冲/删行**之前**执行(第三方退货跟随的库存抵扣补丁用)。
|
||||
* 设计文档 §3.6 要求补丁与红冲同事务:否则红冲失败时会留下
|
||||
* 「成本已作废、库存预留已释放,但销售行还在」的不一致状态(对抗式复查 #5)。
|
||||
*/
|
||||
beforeRemove?: (client: PoolClient) => Promise<void>;
|
||||
}): Promise<'deleted' | 'returned' | 'already_returned'> {
|
||||
const orderCode = trimText(params.orderCode);
|
||||
const itemId = trimText(params.itemId);
|
||||
if (!orderCode || !itemId) {
|
||||
throw Object.assign(new Error('缺少订单号或明细 id'), { status: 400, code: 'invalid_request' });
|
||||
}
|
||||
|
||||
// 上下文要求:必须在**租户上下文**里调用(`runWithTenantDbContext(branchCode, …)`)——
|
||||
// 那时 `pool.connect()` 拿到的是带租户 search_path + app.branch_code 的连接(会话级或新借),
|
||||
// 未加限定名的 order_items / cost_details 才找得到。没有租户上下文时不要调用。
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const itemResult = await client.query(
|
||||
`SELECT id, sku_code, item_name, supplier_code, is_extra_dish, quantity, price, amount, unit_cost,
|
||||
COALESCE(is_returned, false) AS is_returned, return_code
|
||||
FROM order_items
|
||||
WHERE id = $1::uuid AND order_code = $2
|
||||
LIMIT 1`,
|
||||
[itemId, orderCode]
|
||||
);
|
||||
if (!itemResult.rowCount) {
|
||||
await client.query('ROLLBACK');
|
||||
throw Object.assign(new Error('订单明细不存在或不属于该订单'), { status: 404, code: 'not_found' });
|
||||
}
|
||||
const row = itemResult.rows[0];
|
||||
if (row.is_returned) {
|
||||
await client.query('ROLLBACK');
|
||||
return 'already_returned';
|
||||
}
|
||||
await assertNoPendingManualAfterSaleForOrderItem(client, itemId);
|
||||
if (params.beforeRemove) await params.beforeRemove(client);
|
||||
const outcome = await removeOrReturnOrderItem(client, {
|
||||
orderCode,
|
||||
branchCode: params.branchCode ?? null,
|
||||
item: {
|
||||
id: String(row.id),
|
||||
sku_code: row.sku_code,
|
||||
item_name: row.item_name,
|
||||
supplier_code: row.supplier_code,
|
||||
is_extra_dish: row.is_extra_dish,
|
||||
quantity: row.quantity,
|
||||
price: row.price,
|
||||
amount: row.amount,
|
||||
unit_cost: row.unit_cost,
|
||||
is_returned: row.is_returned,
|
||||
return_code: row.return_code,
|
||||
},
|
||||
hardDelete: async (target) => {
|
||||
await deleteOrderItemWithDependencies(client, orderCode, target, {});
|
||||
},
|
||||
});
|
||||
await client.query('COMMIT');
|
||||
return outcome;
|
||||
} catch (error) {
|
||||
await client.query('ROLLBACK').catch(() => undefined);
|
||||
throw error;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
/** 售后处理确认:走与订单删除相同的硬删/红冲,但不新建 OIR_/取消履约单。 */
|
||||
export async function applyAfterSaleHandleOrderItem(
|
||||
client: PoolClient,
|
||||
@@ -1994,3 +2200,114 @@ export async function updateOrderDeliveryDate(params: {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
export type OrderDeliveryAddressPatchResult = {
|
||||
order_code: string;
|
||||
delivery_address: string | null;
|
||||
previous_delivery_address: string | null;
|
||||
changed: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* 单独改「收货地址」(表头字段,**不带明细**)。
|
||||
*
|
||||
* 为什么需要它(2026-10-11 开发者提出):
|
||||
* 详情页原来只有一个可编辑的地址输入框,它随 `canEditOrderForStatus` 一起失效
|
||||
* ⇒ 订单一到 **40/45/50(待配送)** 地址就再也改不了,而"改地址"恰恰是发车前最常见的动作。
|
||||
* 明细保存(`PATCH /orders/:code/items`)在 40+ 被明细锁挡住,所以这里给一条只写表头的通道:
|
||||
* **不碰明细、不动状态链**,只 `UPDATE orders.delivery_address`。
|
||||
*
|
||||
* 门槛:订单存在、未进垃圾桶、`order_status < 90`(已结案不再改地址,避免与结算单/配送单不一致)。
|
||||
* 留痕:`operation_logs` 写 `order_delivery_address_edit`(含改前/改后),与配送日修改同口径。
|
||||
*/
|
||||
export async function updateOrderDeliveryAddress(params: {
|
||||
orderCode: string;
|
||||
deliveryAddress: unknown;
|
||||
operatorId?: string | null;
|
||||
operatorRoles?: string | null;
|
||||
}): Promise<OrderDeliveryAddressPatchResult> {
|
||||
const orderCode = String(params.orderCode || '').trim();
|
||||
if (!orderCode) {
|
||||
throw Object.assign(new Error('缺少订单号'), { status: 400, code: 'invalid_request' });
|
||||
}
|
||||
const nextAddress =
|
||||
params.deliveryAddress === null || params.deliveryAddress === undefined
|
||||
? ''
|
||||
: String(params.deliveryAddress).trim();
|
||||
if (nextAddress.length > 500) {
|
||||
throw Object.assign(new Error('收货地址过长(最多 500 字)'), {
|
||||
status: 400,
|
||||
code: 'invalid_request',
|
||||
});
|
||||
}
|
||||
|
||||
const client = await connectExclusiveTenantClient();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const found = await client.query(
|
||||
`SELECT order_code, order_status, delivery_address, deleted_at, branch_code
|
||||
FROM orders WHERE order_code = $1 LIMIT 1`,
|
||||
[orderCode]
|
||||
);
|
||||
const order = found.rows[0];
|
||||
if (!order) {
|
||||
throw Object.assign(new Error('订单不存在'), { status: 404, code: 'not_found' });
|
||||
}
|
||||
if (order.deleted_at) {
|
||||
throw Object.assign(new Error('订单在垃圾桶中,不可修改收货地址'), {
|
||||
status: 409,
|
||||
code: 'order_trashed',
|
||||
});
|
||||
}
|
||||
const status = Number(order.order_status) || 0;
|
||||
if (status >= 90) {
|
||||
throw Object.assign(new Error('订单已结案,不可修改收货地址'), {
|
||||
status: 400,
|
||||
code: 'invalid_status',
|
||||
});
|
||||
}
|
||||
|
||||
const previous = order.delivery_address ? String(order.delivery_address) : null;
|
||||
let changed = false;
|
||||
if ((previous || '') !== nextAddress) {
|
||||
await client.query(`UPDATE orders SET delivery_address = $1, updated_at = NOW() WHERE order_code = $2`, [
|
||||
nextAddress || null,
|
||||
orderCode,
|
||||
]);
|
||||
changed = true;
|
||||
}
|
||||
await client.query('COMMIT');
|
||||
|
||||
if (changed) {
|
||||
await writeAuditLog({
|
||||
operatorId: params.operatorId || null,
|
||||
operatorRole: params.operatorRoles || null,
|
||||
operationType: 'order_delivery_address_edit',
|
||||
targetTable: 'orders',
|
||||
targetId: orderCode,
|
||||
oldValue: { order_code: orderCode, delivery_address: previous },
|
||||
newValue: {
|
||||
order_code: orderCode,
|
||||
delivery_address: nextAddress || null,
|
||||
order_status: status,
|
||||
via: 'order_detail_header',
|
||||
},
|
||||
branchCode: order.branch_code || null,
|
||||
actionCategory: 'order',
|
||||
}).catch(() => undefined);
|
||||
}
|
||||
|
||||
return {
|
||||
order_code: orderCode,
|
||||
delivery_address: nextAddress || null,
|
||||
previous_delivery_address: previous,
|
||||
changed,
|
||||
};
|
||||
} catch (error) {
|
||||
await client.query('ROLLBACK').catch(() => undefined);
|
||||
throw error;
|
||||
} finally {
|
||||
await resetExclusiveTenantClient(client).catch(() => undefined);
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -125,6 +125,8 @@ export interface OrderManagementListRow {
|
||||
customer_delivery_time: string | null;
|
||||
delivery_address: string | null;
|
||||
cycle_code: string | null;
|
||||
/** 主系统分配过来的订单(2026-10-10):界面隐藏「删除」、改用「缺货」 */
|
||||
is_main_system_order: boolean;
|
||||
inspection_state: 'none' | 'pending' | 'passed' | 'failed';
|
||||
status_hint: string | null;
|
||||
/** 未化解验收不合格商品名(与 inspection_state=failed 同口径) */
|
||||
@@ -561,7 +563,12 @@ export async function listOrdersForManagement(
|
||||
),
|
||||
NULLIF(TRIM(c.address), '')
|
||||
) AS delivery_address,
|
||||
o.cycle_code
|
||||
o.cycle_code,
|
||||
-- 主系统分配过来的订单(2026-10-10):界面据此隐藏「删除」,改用「缺货」
|
||||
EXISTS (
|
||||
SELECT 1 FROM public.main_system_order_imports msi
|
||||
WHERE msi.branch_code = o.branch_code AND msi.our_order_code = o.order_code
|
||||
) AS is_main_system_order
|
||||
FROM orders o
|
||||
LEFT JOIN customers c ON c.customer_code = o.customer_code
|
||||
LEFT JOIN branches b ON b.branch_code = o.branch_code
|
||||
@@ -594,6 +601,29 @@ export async function listOrdersForManagement(
|
||||
})
|
||||
);
|
||||
|
||||
/**
|
||||
* 2026-10-11 方案 A1:主系统「免入库」单在 50 时展示为「待取货」(**不改状态链**)。
|
||||
*
|
||||
* 判定 = 该单在**行级台账**里所有行 `skipInbound=true`(`bool_and`)。
|
||||
* ⚠️ 用 `bool_and` 而非 `bool_or`:混合单(部分免入库/部分送仓)走发车流程,不得标成待取货。
|
||||
* ⚠️ **自有单天然 false**:它们不在 `main_system_order_import_items` 里 ⇒ 永远显示「待配送」。
|
||||
*/
|
||||
const skipInboundMap = new Map<string, boolean>();
|
||||
const orderCodesForSkip = listResult.rows
|
||||
.map((r) => String((r as { order_code?: string }).order_code || ''))
|
||||
.filter(Boolean);
|
||||
if (orderCodesForSkip.length) {
|
||||
const skipRes = await pool.query<{ our_order_code: string; all_skip: boolean }>(
|
||||
`SELECT our_order_code,
|
||||
bool_and(COALESCE(payload->>'skipInbound', 'false') = 'true') AS all_skip
|
||||
FROM public.main_system_order_import_items
|
||||
WHERE branch_code = $1 AND our_order_code = ANY($2::text[])
|
||||
GROUP BY our_order_code`,
|
||||
[branchCode, orderCodesForSkip]
|
||||
);
|
||||
for (const r of skipRes.rows) skipInboundMap.set(String(r.our_order_code), r.all_skip === true);
|
||||
}
|
||||
|
||||
const rows: OrderManagementListRow[] = listResult.rows.map((row) => {
|
||||
const orderCode = String(row.order_code);
|
||||
const storedStatus = Number(row.order_status) || 20;
|
||||
@@ -631,6 +661,9 @@ export async function listOrdersForManagement(
|
||||
customer_delivery_time: row.customer_delivery_time ? String(row.customer_delivery_time) : null,
|
||||
delivery_address: row.delivery_address ? String(row.delivery_address) : null,
|
||||
cycle_code: row.cycle_code ? String(row.cycle_code) : null,
|
||||
is_main_system_order: row.is_main_system_order === true,
|
||||
// 主系统全免入库单 ⇒ 前端在 50 展示「待取货」(自建单恒为 false)
|
||||
is_skip_inbound: skipInboundMap.get(orderCode) === true,
|
||||
inspection_state: inspectionState,
|
||||
status_hint:
|
||||
buildProgressStatusHint(
|
||||
@@ -638,7 +671,9 @@ export async function listOrdersForManagement(
|
||||
inspectionState,
|
||||
facts,
|
||||
fulfillment,
|
||||
pickingEnabled
|
||||
pickingEnabled,
|
||||
// 免入库单副文案同口径「待主系统骑手上门取货」(见 orderStatusDisplayService)
|
||||
skipInboundMap.get(orderCode) === true
|
||||
) ||
|
||||
buildStatusHint(storedStatus, inspectionState, fulfillment, pickingEnabled),
|
||||
inspection_fail_items: failItemsMap.get(orderCode) || [],
|
||||
|
||||
@@ -257,7 +257,12 @@ export function buildProgressStatusHint(
|
||||
inspectionState: OrderInspectionState,
|
||||
facts: OrderProgressFacts,
|
||||
fulfillment?: { prepDone: number; prepTotal: number; purchaseDone: number; purchaseTotal: number },
|
||||
pickingEnabled?: boolean
|
||||
pickingEnabled?: boolean,
|
||||
/**
|
||||
* 主系统**全免入库**单(2026-10-11 开发者定稿):我方不派车、50 就是"等主系统骑手取货",
|
||||
* 副文案必须与徽标「待取货」同口径,**不得**再写「待配送员开始配送」(张冠李戴)。
|
||||
*/
|
||||
skipInbound?: boolean
|
||||
): string | null {
|
||||
if (displayStatus === 20 && facts.itemCount > 0 && !facts.allocationFulfilled) {
|
||||
return '尚有明细未分配供应商/采购';
|
||||
@@ -287,7 +292,10 @@ export function buildProgressStatusHint(
|
||||
if (facts.unfinishedPicks > 0) return `分拣进行中,剩 ${facts.unfinishedPicks}`;
|
||||
return pickingEnabled === false ? null : '待分拣完成';
|
||||
}
|
||||
if (displayStatus === 50) return '待配送员开始配送';
|
||||
if (displayStatus === 50) {
|
||||
// 免入库:我方不派车,货由**主系统骑手上门取走**(取走后靠 picked_up 收口 90)
|
||||
return skipInbound ? '待主系统骑手上门取货' : '待配送员开始配送';
|
||||
}
|
||||
if (displayStatus === 60) {
|
||||
if (facts.deliveryEnded || facts.customerSigned) {
|
||||
return '已签收/已结束配送,待结案归档';
|
||||
|
||||
@@ -20,6 +20,11 @@ import { backfillMissingPrepPurchaseCosts } from './missingPurchaseCostBackfill'
|
||||
import { supplierSkipInboundExistsSql } from './supplierSkipInbound';
|
||||
import { isOrderOnlyDirectDelivery, skuDirectDeliveryAppliesSql } from './skuDirectDelivery';
|
||||
import { recordPriceInvertOnOrderComplete } from './priceInvertEventService';
|
||||
import {
|
||||
enqueueMainSystemWritebackForDeliveredOrder,
|
||||
enqueueMainSystemWritebackForReadyOrder,
|
||||
} from './mainSystemWriteback';
|
||||
import { isOrderFullySkipInbound } from './mainSystemPrepLedger';
|
||||
|
||||
type Db = Pick<PoolClient, 'query'>;
|
||||
|
||||
@@ -164,6 +169,10 @@ export async function tryAdvanceOrderToDelivery(orderCode: string): Promise<{ ad
|
||||
return { advanced: false, message: '订单状态已变更' };
|
||||
}
|
||||
await ensureDeliveryTaskForOrder(orderCode, branchCode);
|
||||
// 2026-10-11 定稿(开发者):**不论是送仓单还是免入库单,子系统到了「待配送」就该让主系统的商品
|
||||
// 显示"备货完成"** ⇒ 本路径对所有单回写 `status=30`(此前只对免入库早回写,送仓要等发车)。
|
||||
// 与「分拣完成」路径同一个函数、同一纪律:写在事务提交后、非阻塞、失败只记账、对账兜底。
|
||||
enqueueMainSystemWritebackForReadyOrder({ branchCode, orderCode });
|
||||
return { advanced: true, message: '分拣环节未启用,订单进入待配送' };
|
||||
}
|
||||
|
||||
@@ -275,6 +284,26 @@ export async function ensureDeliveryTaskForOrder(
|
||||
return '';
|
||||
}
|
||||
|
||||
// 主系统「免入库」订单:货由**主系统配送员上门取走**,我方不派车 ⇒ 不建配送任务。
|
||||
// 与上面 `isOrderOnlyDirectDelivery` 同一个卡点(所有调用方的最终兜底):
|
||||
// 分拣收尾、验收推进、备货齐套、处理单、配送列表补建等 8+ 个调用点都被这一处覆盖。
|
||||
// 无台账行 = 原生订单 ⇒ false,原生流程零影响。见设计文档 20261010 §3.4 / §9.6。
|
||||
//
|
||||
// ⚠️ **判定只看"是否整单全免入库",与 `MAIN_SYSTEM_SKIP_INBOUND_AWAIT_PICKUP` 解耦**(2026-10-11):
|
||||
// 那个开关的语义是"停 50 等主系统发车才收口",跟"要不要派我方车"无关;
|
||||
// 挂在一起时,按文档 §3.4 的回滚指引写 `0` 会把免入库单的配送任务放回来(旧行为就是被派单)。
|
||||
// 混合单(部分行免入库)不在排除之列 —— 送仓部分仍要我方发车,见 `isOrderFullySkipInbound`。
|
||||
const orderBranch = String(orderLive.rows[0].branch_code || '').trim();
|
||||
if (
|
||||
orderBranch &&
|
||||
// ⚠️ 必须复用当前事务的 client(`client`):本函数此刻已持有连接,
|
||||
// 再去 pool 取第二条会在池满时自锁。
|
||||
(await isOrderFullySkipInbound({ branchCode: orderBranch, ourOrderCode: code, db: client }))
|
||||
) {
|
||||
if (manageTransaction) await client.query('COMMIT');
|
||||
return '';
|
||||
}
|
||||
|
||||
const existing = await client.query(
|
||||
`SELECT task_code, person_code FROM delivery_tasks WHERE order_code = $1 LIMIT 1`,
|
||||
[code]
|
||||
@@ -411,8 +440,12 @@ export async function tryAdvanceOrderToDelivering(
|
||||
options?: AdvanceDeliveringOptions
|
||||
): Promise<{ advanced: boolean; message: string }> {
|
||||
await assertOrderActiveForFulfillment(orderCode);
|
||||
const orderResult = await pool.query(`SELECT order_status FROM orders WHERE order_code = $1`, [orderCode]);
|
||||
const orderResult = await pool.query(
|
||||
`SELECT order_status, branch_code FROM orders WHERE order_code = $1`,
|
||||
[orderCode]
|
||||
);
|
||||
const status = Number(orderResult.rows[0]?.order_status);
|
||||
const branchCodeForWriteback = (orderResult.rows[0]?.branch_code as string | null) ?? null;
|
||||
if (status >= 60) {
|
||||
return { advanced: true, message: '订单已在配送中或已完成' };
|
||||
}
|
||||
@@ -421,7 +454,7 @@ export async function tryAdvanceOrderToDelivering(
|
||||
}
|
||||
|
||||
try {
|
||||
return await withOrderLock(orderCode, 50, async (client) => {
|
||||
const advanceResult = await withOrderLock(orderCode, 50, async (client) => {
|
||||
const taskCode = options?.taskCode ? String(options.taskCode).trim() : '';
|
||||
const personCode = options?.personCode ? String(options.personCode).trim() : '';
|
||||
|
||||
@@ -523,6 +556,16 @@ export async function tryAdvanceOrderToDelivering(
|
||||
}
|
||||
return { advanced: true, message: '配送已开始' };
|
||||
});
|
||||
// 发车成功(事务已提交)→ 非阻塞回写主系统「备货完成」。
|
||||
// 2026-10-08 设计文档 §3.5:这是主系统"已发车不能点击退货"拦截的依据,也是它进入待验入库的前提。
|
||||
// 刻意不 await、不抛错:**回写失败绝不影响发车结果**(失败由台账记账 + 定时兜底重试)。
|
||||
if (advanceResult.advanced) {
|
||||
enqueueMainSystemWritebackForDeliveredOrder({
|
||||
branchCode: branchCodeForWriteback,
|
||||
orderCode,
|
||||
});
|
||||
}
|
||||
return advanceResult;
|
||||
} catch (error: any) {
|
||||
if (error?.soft) {
|
||||
return { advanced: false, message: error?.message || '无法开始配送' };
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { PoolClient } from 'pg';
|
||||
import { pool } from '../db';
|
||||
import { completeOrderWithoutDriverDelivery } from './orderWorkflowFulfillmentService';
|
||||
import { enqueueMainSystemWritebackForReadyOrder } from './mainSystemWriteback';
|
||||
import { config } from '../config';
|
||||
import type { TenantContext } from './tenantScope';
|
||||
import { ensureSkuForPickingOutbound } from './skuProvisioningService';
|
||||
import { chinaDeliveryDateBetweenSql, onOrAfterChinaDeliveryDateSql } from '../utils/chinaDate';
|
||||
@@ -94,19 +97,66 @@ function newPickCode() {
|
||||
* 并不保证订单仍在 45 —— 订单可能已被「拒收退回(40→30)」或「仓内漏分拣打回(50→45)」改动。
|
||||
* 缺这个谓词会靠调用时机兜底,一旦订单在 40/30 被扫到就会跳过验收环节直接进待配送。
|
||||
*/
|
||||
/**
|
||||
* 分拣出库收尾推进。
|
||||
*
|
||||
* 返回值 `skipInboundAwaitingPickup=true` 表示:这是**主系统免入库**订单,已停在 50 待配送、
|
||||
* **等主系统确认发车**(`preparations.picked_up` 事件)才收口 —— 调用方必须在**事务提交后**
|
||||
* 触发回写(HTTP 永不在事务内),见设计文档 20261010 §3.4。
|
||||
*/
|
||||
async function maybeAdvanceOrderAfterPickingOutbound(
|
||||
client: PoolClient,
|
||||
orderCode: string
|
||||
): Promise<void> {
|
||||
): Promise<{ skipInboundAwaitingPickup: boolean }> {
|
||||
await consumeReservationsForOrder(client, orderCode);
|
||||
const unfinishedPicks = await countUnfinishedPickingTasks(orderCode, client);
|
||||
if (unfinishedPicks > 0) return;
|
||||
if (unfinishedPicks > 0) return { skipInboundAwaitingPickup: false };
|
||||
const missingWarehouse = await countWarehouseItemsMissingPicking(orderCode, client);
|
||||
if (missingWarehouse > 0) return;
|
||||
if (missingWarehouse > 0) return { skipInboundAwaitingPickup: false };
|
||||
|
||||
// 主系统「免入库」订单:货由**主系统配送员直接来取**,我们只负责分拣。
|
||||
// 判定读公开台账(无台账行 = 原生订单 ⇒ false,原生流程逐字节不变)。
|
||||
// 见 docs/design/20261009-供应商侧库存抵扣与免入库推进方案.md §3.2
|
||||
try {
|
||||
const branchResult = await client.query<{ branch_code: string | null }>(
|
||||
`SELECT branch_code FROM orders WHERE order_code = $1 LIMIT 1`,
|
||||
[orderCode]
|
||||
);
|
||||
const branchCode = String(branchResult.rows[0]?.branch_code || '');
|
||||
const { isOrderFullySkipInbound } = await import('./mainSystemPrepLedger');
|
||||
// ⚠️ 传 `client` 复用当前事务的连接:本函数此刻已持有连接,
|
||||
// 再去 pool 取第二条会在池满时自锁。
|
||||
if (await isOrderFullySkipInbound({ branchCode, ourOrderCode: orderCode, db: client })) {
|
||||
// 先走既有边 45→50(结案入口只接受来源状态 30 或 50,见 F9),全程不新增状态边。
|
||||
await client.query(
|
||||
`UPDATE orders SET order_status = 50 WHERE order_code = $1 AND order_status = 45`,
|
||||
[orderCode]
|
||||
);
|
||||
if (config.mainSystemIntegration.skipInboundAwaitPickup) {
|
||||
// 【2026-10-10 新口径】不再分拣完毕即结案:**停在 50 待配送,等主系统确认发车**
|
||||
// (开发者原话:「分拣完成后等着主系统的分拣员来…点击了确认发车后,子系统的订单就标记为已完成」)。
|
||||
// 不建配送任务(ensureDeliveryTaskForOrder 的免入库守卫已兜住),
|
||||
// 对账也不会把它推到 60(tryAdvanceOrderToDelivering 无 options 时要求配送员已点开始,F8)。
|
||||
// 回写 `status=30` 由调用方在**事务提交后**触发 —— 主系统必须先收到它才会推进到可发车。
|
||||
return { skipInboundAwaitingPickup: true };
|
||||
}
|
||||
// 旧口径(默认关):分拣完毕即结案 90,跳过 50/60 配送环节
|
||||
await completeOrderWithoutDriverDelivery(orderCode, client);
|
||||
return { skipInboundAwaitingPickup: false };
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
// 判定失败不能把分拣流程带崩:退回原有 45→50 行为
|
||||
console.error(
|
||||
`[picking] 免入库判定失败,按普通订单推进 ${orderCode}:`,
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
}
|
||||
|
||||
await client.query(
|
||||
`UPDATE orders SET order_status = 50 WHERE order_code = $1 AND order_status = 45`,
|
||||
[orderCode]
|
||||
);
|
||||
return { skipInboundAwaitingPickup: false };
|
||||
}
|
||||
|
||||
function newContainerCode() {
|
||||
@@ -1244,17 +1294,33 @@ export async function completePickingOutbound(input: {
|
||||
relatedOrderCodes.push(String(task.order_code));
|
||||
}
|
||||
|
||||
const awaitingPickup = new Set<string>();
|
||||
for (const orderCode of relatedOrderCodes) {
|
||||
await maybeAdvanceOrderAfterPickingOutbound(client, orderCode);
|
||||
const advance = await maybeAdvanceOrderAfterPickingOutbound(client, orderCode);
|
||||
if (advance.skipInboundAwaitingPickup) awaitingPickup.add(orderCode);
|
||||
}
|
||||
|
||||
await client.query('COMMIT');
|
||||
|
||||
// 主系统免入库:我方货备齐 ⇒ **事务提交后**非阻塞回写 status=30。
|
||||
// 主系统必须先收到它才会推进到可发车;否则配送员不上门、picked_up 永不触发(死锁)。
|
||||
// HTTP 永不在事务内 —— 这里已在 COMMIT 之后。见设计文档 20261010 §3.4。
|
||||
for (const orderCode of awaitingPickup) {
|
||||
enqueueMainSystemWritebackForReadyOrder({
|
||||
branchCode: task.branch_code || null,
|
||||
orderCode,
|
||||
});
|
||||
}
|
||||
|
||||
for (const orderCode of relatedOrderCodes) {
|
||||
await tryAdvanceOrderToDelivery(orderCode);
|
||||
const unfinishedAfter = await countUnfinishedPickingTasks(orderCode);
|
||||
const missingWarehouse = await countWarehouseItemsMissingPicking(orderCode);
|
||||
if (unfinishedAfter === 0 && missingWarehouse === 0) {
|
||||
// 已结案(含"主系统免入库:分拣完毕即完成"与"商品直送齐套")不需要配送任务,
|
||||
// 否则会给 90 的订单留下永远用不上的孤儿任务。
|
||||
const st = await pool.query(`SELECT order_status FROM orders WHERE order_code = $1`, [orderCode]);
|
||||
if (Number(st.rows[0]?.order_status) >= 90) continue;
|
||||
await ensureDeliveryTaskForOrder(orderCode, task.branch_code || null);
|
||||
}
|
||||
}
|
||||
@@ -1343,6 +1409,8 @@ export async function outboundPickingByContainer(input: {
|
||||
const client = await pool.connect();
|
||||
let taskCompleted = false;
|
||||
let relatedOrderCodes: string[] = [];
|
||||
/** 主系统免入库、已停在 50 等主系统取货的订单:事务提交后要回写 status=30(HTTP 不进事务) */
|
||||
const awaitingPickupOrders = new Set<string>();
|
||||
let taskBranchCode: string | null = null;
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
@@ -1501,12 +1569,22 @@ export async function outboundPickingByContainer(input: {
|
||||
}
|
||||
|
||||
for (const orderCode of relatedOrderCodes) {
|
||||
await maybeAdvanceOrderAfterPickingOutbound(client, orderCode);
|
||||
const advance = await maybeAdvanceOrderAfterPickingOutbound(client, orderCode);
|
||||
if (advance.skipInboundAwaitingPickup) awaitingPickupOrders.add(orderCode);
|
||||
}
|
||||
}
|
||||
|
||||
await client.query('COMMIT');
|
||||
|
||||
// 主系统免入库:我方货备齐 ⇒ **事务提交后**非阻塞回写 status=30(HTTP 永不在事务内)。
|
||||
// 见设计文档 20261010 §3.4。
|
||||
for (const orderCode of awaitingPickupOrders) {
|
||||
enqueueMainSystemWritebackForReadyOrder({
|
||||
branchCode: taskBranchCode || task.branch_code || null,
|
||||
orderCode,
|
||||
});
|
||||
}
|
||||
|
||||
await logPickingScan({
|
||||
pickCode: String(task.pick_code),
|
||||
pickItemId: String(item.id),
|
||||
@@ -2091,9 +2169,18 @@ export type PickingAssignee = {
|
||||
username: string | null;
|
||||
branch_code: string | null;
|
||||
display_name: string;
|
||||
/**
|
||||
* 该用户的角色码(`picker` / `warehouse` / `delivery` …)。
|
||||
*
|
||||
* 为什么给前端(开发者 2026-10-11):分拣池**按设计**包含"勾了分拣出库的配送员"
|
||||
* (见迁移 `20260725_picking_manage_permission.sql`:`picking_manage` 本就授给 delivery),
|
||||
* 只列"分拣员"会让本地(无任何 picker 账号)下拉变空。故**范围不变、界面标出角色**:
|
||||
* 「张三(配送人员)」,避免被误认成专责分拣员。
|
||||
*/
|
||||
roles: string[];
|
||||
};
|
||||
|
||||
/** 可供 Web 分配/改派的分拣作业人员(开通分拣出库的仓内角色) */
|
||||
/** 可供 Web 分配/改派的分拣作业人员(**仓内作业角色**:picker 分拣员 / warehouse 仓管;配送员不在其列) */
|
||||
export async function listPickingAssignees(ctx: TenantContext | null): Promise<PickingAssignee[]> {
|
||||
const params: unknown[] = [];
|
||||
let branchFilter = '';
|
||||
@@ -2103,13 +2190,17 @@ export async function listPickingAssignees(ctx: TenantContext | null): Promise<P
|
||||
}
|
||||
const result = await pool.query(
|
||||
`SELECT p.id, p.full_name, p.username, p.branch_code,
|
||||
COALESCE(NULLIF(TRIM(p.full_name), ''), NULLIF(TRIM(p.username), ''), p.id::text) AS sort_name
|
||||
COALESCE(NULLIF(TRIM(p.full_name), ''), NULLIF(TRIM(p.username), ''), p.id::text) AS sort_name,
|
||||
string_agg(DISTINCT ur.role::text, ',' ORDER BY ur.role::text) AS roles
|
||||
FROM profiles p
|
||||
JOIN user_roles ur ON ur.user_id = p.id
|
||||
JOIN role_permissions rp ON rp.role::text = ur.role::text
|
||||
JOIN permissions perm ON perm.id = rp.permission_id AND perm.permission_code = 'picking_manage'
|
||||
WHERE COALESCE(p.status, 1) = 1
|
||||
AND ur.role::text = ANY(ARRAY['picker', 'warehouse', 'delivery']::text[])
|
||||
-- 2026-10-11 开发者定稿:**按权限/角色区分** —— 配送员不得作为分拣员被分配
|
||||
-- (历史迁移 20260725 曾把 picking_manage 授给 delivery,导致配送员混进分拣池;
|
||||
-- 现按"仓内作业角色"收口:分拣员 picker + 仓管 warehouse)
|
||||
AND ur.role::text = ANY(ARRAY['picker', 'warehouse']::text[])
|
||||
${branchFilter}
|
||||
GROUP BY p.id, p.full_name, p.username, p.branch_code
|
||||
ORDER BY sort_name ASC`,
|
||||
@@ -2124,6 +2215,10 @@ export async function listPickingAssignees(ctx: TenantContext | null): Promise<P
|
||||
username: row.username ? String(row.username) : null,
|
||||
branch_code: row.branch_code ? String(row.branch_code) : null,
|
||||
display_name: display,
|
||||
roles: String(row.roles || '')
|
||||
.split(',')
|
||||
.map((role) => role.trim())
|
||||
.filter(Boolean),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
ensureProcessingTaskForInspection,
|
||||
syncProcessingTasksForOrder,
|
||||
} from './processingTaskService';
|
||||
import { enqueueSkipInboundWritebackIfReady } from './mainSystemWriteback';
|
||||
import {
|
||||
isOrderItemFulfillmentValid,
|
||||
listUncoveredOrderItems,
|
||||
@@ -675,11 +676,19 @@ export async function tryAdvanceOrderToInspection(
|
||||
AND NOT ${supplierSkipInboundExistsSql('oi.supplier_code')}
|
||||
AND NOT ${skuDirectDeliveryAppliesSql('oi.sku_code', 'oi.order_code')}
|
||||
) AS need_inbound_count,
|
||||
-- 非商品直送的行数:这些行的货**必须经我们仓库出库**(含"库存抵扣"的行——它们没有缺口,
|
||||
-- 但货在我们仓里,仍需分拣出库+配送)。见 docs/design/20261009-供应商侧库存抵扣与免入库推进方案.md
|
||||
(SELECT COUNT(*)::int
|
||||
FROM order_items oi
|
||||
WHERE oi.order_code = $1
|
||||
AND NOT ${skuDirectDeliveryAppliesSql('oi.sku_code', 'oi.order_code')}
|
||||
) AS non_direct_count,
|
||||
(SELECT COUNT(*)::int FROM inspections WHERE order_code = $1) AS inspection_count`,
|
||||
[orderCode]
|
||||
);
|
||||
const itemCount = Number(coverage.rows[0]?.item_count || 0);
|
||||
const needInboundCount = Number(coverage.rows[0]?.need_inbound_count || 0);
|
||||
const nonDirectCount = Number(coverage.rows[0]?.non_direct_count || 0);
|
||||
const inspectionCount = Number(coverage.rows[0]?.inspection_count || 0);
|
||||
if (itemCount > 0 && needInboundCount === 0) {
|
||||
const driverNeeded = await db.query(
|
||||
@@ -692,23 +701,42 @@ export async function tryAdvanceOrderToInspection(
|
||||
AND NOT ${skuDirectDeliveryAppliesSql('oi.sku_code', 'oi.order_code')}`,
|
||||
[orderCode]
|
||||
);
|
||||
if (Number(driverNeeded.rows[0]?.cnt || 0) === 0) {
|
||||
// 只有**全部行都是商品直送**(货根本不经过我们)才允许直接结案。
|
||||
// 关键修正(2026-10-09):此前只看"没有缺口",于是"库存全额抵扣"的订单(无缺口、但货在我们仓里、
|
||||
// 仍需出库与配送)也被判成"直送齐套"直接结案 ⇒ 定时对账 15 分钟内把这类单结案 90、货从未出库。
|
||||
// 现在非直送行 > 0 时**不越级**,落到函数尾部的 30→40,再由既有 40→45/50 推进。
|
||||
if (nonDirectCount === 0 && Number(driverNeeded.rows[0]?.cnt || 0) === 0) {
|
||||
await completeOrderWithoutDriverDelivery(orderCode, client);
|
||||
return { advanced: true, message: '商品直送已齐套,订单已完成配送', newStatus: 90 };
|
||||
}
|
||||
const toDelivery = await db.query(
|
||||
// 既不是全直送、也没有"免入库且有缺口"的行 ⇒ 属于"库存抵扣/已入库"这类:
|
||||
// **不在此处越级**,也不原地返回(原地返回会让订单卡在 30),而是落到函数尾部的 30→40,
|
||||
// 再由既有 40→45/50 继续推进(分拣环节因此不会被跳过)。
|
||||
if (Number(driverNeeded.rows[0]?.cnt || 0) > 0) {
|
||||
const toDelivery = await db.query(
|
||||
`UPDATE orders SET order_status = 50 WHERE order_code = $1 AND order_status = 30 RETURNING order_code`,
|
||||
[orderCode]
|
||||
);
|
||||
if (!toDelivery.rowCount) {
|
||||
return {
|
||||
advanced: bumpedFromAllocation,
|
||||
message: bumpedFromAllocation ? '分配已纠正为待备货' : '订单状态已变更,未重复推进',
|
||||
newStatus: bumpedFromAllocation ? 30 : undefined,
|
||||
};
|
||||
if (!toDelivery.rowCount) {
|
||||
return {
|
||||
advanced: bumpedFromAllocation,
|
||||
message: bumpedFromAllocation ? '分配已纠正为待备货' : '订单状态已变更,未重复推进',
|
||||
newStatus: bumpedFromAllocation ? 30 : undefined,
|
||||
};
|
||||
}
|
||||
await ensureDeliveryTaskForOrder(orderCode, order.branch_code || null, client);
|
||||
// 主系统免入库:货备齐即回写 status=30(主系统靠它才推进到可发车)。
|
||||
// ⚠️ **只在没有外层事务时触发**(`!client` ⇒ db 是 pool,上面那条 UPDATE 已自动提交);
|
||||
// 传了 client 说明我们在调用方事务里,此刻回写会早于提交 —— 交给 15 分钟对账兜底。
|
||||
if (!client) {
|
||||
await enqueueSkipInboundWritebackIfReady({
|
||||
branchCode: order.branch_code || null,
|
||||
orderCode,
|
||||
});
|
||||
}
|
||||
return { advanced: true, message: '直送免入库已齐套,订单进入待配送', newStatus: 50 };
|
||||
}
|
||||
await ensureDeliveryTaskForOrder(orderCode, order.branch_code || null, client);
|
||||
return { advanced: true, message: '直送免入库已齐套,订单进入待配送', newStatus: 50 };
|
||||
// 落到尾部:30→40(库存抵扣等无需入库的行走这条,随后由 40→45/50 推进)
|
||||
}
|
||||
// 全量库存抵扣:无需新验收任务也可推进
|
||||
if (itemCount > 0 && needInboundCount > 0 && inspectionCount === 0 && created === 0) {
|
||||
|
||||
@@ -10,6 +10,7 @@ import { createPickingTask, repairMissingWarehousePickingForOrder } from './pick
|
||||
import { isPickingWorkflowEnabled } from './pickingConfigService';
|
||||
import { isProcessingWorkflowEnabled } from './processingWorkflowConfigService';
|
||||
import { ensureDeliveryTaskForOrder } from './orderWorkflowFulfillmentService';
|
||||
import { enqueueSkipInboundWritebackIfReady } from './mainSystemWriteback';
|
||||
import { ensureCustomerStatementAfterOrderComplete, ensureSupplierStatementsForOrder } from './financeReconciliationService';
|
||||
import { postProcessingLaborCost } from './operationCostPostingService';
|
||||
import { finalizeInspectionPhotosToResultFolder } from './storageUploadService';
|
||||
@@ -612,6 +613,10 @@ export async function maybeAdvanceOrderAfterFulfillment(
|
||||
if (statusAdvanced) {
|
||||
await ensureDeliveryTaskForOrder(orderCode, order.branch_code || null);
|
||||
await triggerSettlementAfterInbound(orderCode);
|
||||
await enqueueSkipInboundWritebackIfReady({
|
||||
branchCode: order.branch_code || null,
|
||||
orderCode,
|
||||
});
|
||||
}
|
||||
return {
|
||||
advanced: statusAdvanced,
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
import type { PoolClient } from 'pg';
|
||||
import { pool } from '../db';
|
||||
import { submitPriceQtyRequest } from './mainSystemPriceQtyRequest';
|
||||
import { assertPurchaseOrderInBranch } from './purchaserBranchScope';
|
||||
import { writeAuditLog } from './auditService';
|
||||
import { upsertCustomerStatementForOrder } from './financeReconciliationService';
|
||||
import {
|
||||
assertMainSystemPriceQtyReviewed,
|
||||
isEnabled as isPriceQtyRequestEnabled,
|
||||
} from './mainSystemPriceQtyRequest';
|
||||
|
||||
export type UpdatePurchaseLinkedSalePriceInput = {
|
||||
purchaseCode: string;
|
||||
@@ -88,6 +93,11 @@ export async function writeOrderItemSalePrice(
|
||||
operatorName?: string | null;
|
||||
/** 追加进审计 newValue 的来源信息(如 purchase_code / prep_id) */
|
||||
auditExtra: Record<string, unknown>;
|
||||
/**
|
||||
* 内部路径专用:本次改价是「跨系统改价改量申请」的已生效/已审核落地,跳过申请守卫。
|
||||
* ⚠️ 除申请落地外不得传 true。
|
||||
*/
|
||||
priceQtyApproved?: boolean;
|
||||
}
|
||||
): Promise<{
|
||||
lineAmount: number;
|
||||
@@ -95,7 +105,7 @@ export async function writeOrderItemSalePrice(
|
||||
statementSync?: UpdatePurchaseLinkedSalePriceResult['statement_sync'];
|
||||
}> {
|
||||
const before = await client.query(
|
||||
`SELECT price, locked_price, amount, quantity
|
||||
`SELECT price, locked_price, amount, quantity, item_name
|
||||
FROM order_items
|
||||
WHERE id = $1::uuid AND order_code = $2
|
||||
LIMIT 1`,
|
||||
@@ -105,6 +115,65 @@ export async function writeOrderItemSalePrice(
|
||||
throw Object.assign(new Error('关联订单明细不存在'), { status: 404, code: 'not_found' });
|
||||
}
|
||||
|
||||
// 跨系统改价审核守卫(2026-10-11):主系统分配过来的订单行,销售价(= 主系统成本价)的改动
|
||||
// 必须走申请入口。这里是最容易被绕过的写点(裸 UPDATE,不经改明细服务)。
|
||||
// 开关关闭(默认)时直接放行 ⇒ 与改造前逐字节一致。
|
||||
if (!input.priceQtyApproved && isPriceQtyRequestEnabled()) {
|
||||
const oldPrice = Number(before.rows[0].price) || 0;
|
||||
if (Math.abs(oldPrice - input.salePrice) > 1e-6) {
|
||||
const mainSystemOrder = await client.query(
|
||||
`SELECT 1 FROM public.main_system_order_imports
|
||||
WHERE branch_code = $1 AND our_order_code = $2
|
||||
LIMIT 1`,
|
||||
[input.branchCode, input.orderCode]
|
||||
);
|
||||
if (mainSystemOrder.rowCount) {
|
||||
/**
|
||||
* 2026-10-11 开发者定稿:**统一分流**(原来这里是直接抛错,导致"自采列表改价改不动"——
|
||||
* 自采列表没有申请分流入口,撞上守卫就只表现为"保存无效/失败")。
|
||||
*
|
||||
* 现在:
|
||||
* · **免审**(补价 0→正常价 / 改低 / 减量)⇒ 主系统当场生效、我方同步落地 ⇒
|
||||
* **继续走下面的原写入**(值已一致,等同幂等,调用方拿到的金额/合计仍正确);
|
||||
* · **需审核**(涨价 / 加量)⇒ 提交申请、**本地价格不变**,抛一条**说明性**业务错误,
|
||||
* 让界面明确显示"已提交,等待主系统审核",不再静默;
|
||||
* · 提交失败/未就绪 ⇒ 同样明确报错。
|
||||
*/
|
||||
const outcome = await submitPriceQtyRequest({
|
||||
branchCode: input.branchCode,
|
||||
ourOrderCode: input.orderCode,
|
||||
ourOrderItemId: input.orderItemId,
|
||||
proposedPrice: input.salePrice,
|
||||
unit: before.rows[0].unit != null ? String(before.rows[0].unit) : null,
|
||||
reason: '自购/自采列表改销售价(自动转改价申请)',
|
||||
actor: {
|
||||
userId: input.operatorId ?? null,
|
||||
roles: input.operatorName ?? null,
|
||||
requestedBy: input.operatorName ?? null,
|
||||
},
|
||||
}).catch((e: unknown) => ({ kind: 'failed', reason: (e as Error)?.message || String(e), retryable: true } as const));
|
||||
|
||||
if (outcome.kind !== 'ok') {
|
||||
throw Object.assign(
|
||||
new Error(
|
||||
`改价申请提交失败,本次未改动价格:${
|
||||
'reason' in outcome && outcome.reason ? outcome.reason : outcome.kind
|
||||
}`
|
||||
),
|
||||
{ status: 409, code: 'price_request_failed' }
|
||||
);
|
||||
}
|
||||
if (outcome.status !== 'applied') {
|
||||
throw Object.assign(
|
||||
new Error('已提交改价申请,等待主系统审核(本地价格暂不变动)'),
|
||||
{ status: 409, code: 'main_system_review_pending' }
|
||||
);
|
||||
}
|
||||
// 免审已生效 ⇒ 落到下面的原写入(同值幂等),保持调用方返回结构不变
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const quantity = Number(before.rows[0].quantity) || input.quantityFallback || 0;
|
||||
const lineAmount = Math.round(quantity * input.salePrice * 100) / 100;
|
||||
|
||||
|
||||
@@ -32,6 +32,8 @@ import {
|
||||
} from './platformBranch';
|
||||
import { runWithTenantDbContext } from './tenantDbContext';
|
||||
import { withDistributedLock } from './distributedLock';
|
||||
import { importMainSystemOrdersForAllSupplierBranches } from './mainSystemOrderImport';
|
||||
import { mapWithConcurrency, resolveConcurrency } from '../utils/concurrency';
|
||||
|
||||
let timer: ReturnType<typeof setInterval> | null = null;
|
||||
let bidOpenTimer: ReturnType<typeof setInterval> | null = null;
|
||||
@@ -414,8 +416,105 @@ const SCHEDULER_LOCK_TTL_SEC = 14 * 60;
|
||||
const BID_OPEN_LOCK_KEY = 'bid-queued-open-tick';
|
||||
const BID_OPEN_LOCK_TTL_SEC = 50;
|
||||
|
||||
/** 主系统分配任务:定时对账(兜底)。webhook 是实时通道,这里防漏推/宕机缺口。幂等。 */
|
||||
let lastMainSystemImportAt = 0;
|
||||
|
||||
async function runMainSystemImportReconcile() {
|
||||
// try 从函数第一行开始:本函数由 `void` 调用,任何逃逸的 rejection 都会变成
|
||||
// 未处理拒绝(本项目 no process.on('unhandledRejection'))→ 可能直接结束进程。
|
||||
try {
|
||||
const { config } = await import('../config');
|
||||
if (!config.mainSystemIntegration.autoImportEnabled) return;
|
||||
if (Date.now() - lastMainSystemImportAt < 10 * 60 * 1000) return; // 最多 10 分钟一次
|
||||
lastMainSystemImportAt = Date.now();
|
||||
const r = await importMainSystemOrdersForAllSupplierBranches();
|
||||
if (r.created || r.appended || r.failed) {
|
||||
console.log(
|
||||
`[scheduler] 主系统分配对账:${r.branches} 个分公司,新建 ${r.created} / 补行 ${r.appended} / 跳过 ${r.skipped} / 失败 ${r.failed}`
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[scheduler] 主系统分配对账失败:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 跨系统改价/改量申请对账(兜底):webhook 漏推时按主系统 `view=price_amend` 补齐状态。
|
||||
* 开关关闭时函数内部直接返回(与改造前一致,不做任何主系统调用)。
|
||||
*/
|
||||
let lastPriceQtyReconcileAt = 0;
|
||||
|
||||
async function runPriceQtyRequestReconcile() {
|
||||
try {
|
||||
const { isEnabled, reconcileMainSystemPriceQtyRequests } = await import('./mainSystemPriceQtyRequest');
|
||||
if (!isEnabled()) return;
|
||||
if (Date.now() - lastPriceQtyReconcileAt < 10 * 60 * 1000) return;
|
||||
lastPriceQtyReconcileAt = Date.now();
|
||||
const branches = await listActiveBranchCodes();
|
||||
const perTenant = await mapWithConcurrency(
|
||||
branches,
|
||||
resolveConcurrency(process.env.SCHEDULER_TENANT_CONCURRENCY, 4, 8, process.env.PG_POOL_MAX || 30),
|
||||
async (branchCode) => {
|
||||
try {
|
||||
return await reconcileMainSystemPriceQtyRequests({ branchCode });
|
||||
} catch (error: any) {
|
||||
console.error(`[scheduler] 改价/改量申请对账失败(${branchCode}):`, error?.message || error);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
);
|
||||
let checked = 0;
|
||||
let closed = 0;
|
||||
let failed = 0;
|
||||
for (const r of perTenant) {
|
||||
if (!r) continue;
|
||||
checked += r.checked;
|
||||
closed += r.closed;
|
||||
failed += r.failed;
|
||||
}
|
||||
if (closed || failed) {
|
||||
console.log(`[scheduler] 跨系统改价/改量对账:待审 ${checked},补齐 ${closed},落地失败 ${failed}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[scheduler] 跨系统改价/改量对账失败:', error);
|
||||
}
|
||||
}
|
||||
|
||||
async function runQueuedBidOpenTick() {
|
||||
try {
|
||||
const branches = await listActiveBranchCodes();
|
||||
// 2026-10-08 规模改造 §7:本 tick 每 60 秒一次,原来是「逐分公司串行」,
|
||||
// 500 个分公司时空库也要 0.6 s+、有数据后更久。改为有界并发(默认 4,上限 8),
|
||||
// `SCHEDULER_TENANT_CONCURRENCY=1` 即退回串行。
|
||||
// 单个分公司异常改为「记录后继续」(原来会中断当轮剩余分公司,两者都在下一轮重试)。
|
||||
const perTenant = await mapWithConcurrency(
|
||||
branches,
|
||||
resolveConcurrency(process.env.SCHEDULER_TENANT_CONCURRENCY, 4, 8, process.env.PG_POOL_MAX || 30),
|
||||
async (branchCode) => {
|
||||
try {
|
||||
return await runWithTenantDbContext(branchCode, async () => {
|
||||
const result = await openDueQueuedPerOrderBids(branchCode);
|
||||
const empty = await releaseDueEmptyBidRounds(branchCode);
|
||||
const quoted = await awardDueQuotedBidRounds(branchCode);
|
||||
const holds = await releaseDueAllocationHolds(branchCode);
|
||||
const stuck = await retryStuckAwardedAllocations(branchCode);
|
||||
return {
|
||||
opened: result.opened,
|
||||
cancelled: result.cancelled,
|
||||
emptyClosed: empty.closed,
|
||||
emptyAllocated: empty.allocated,
|
||||
quotedAwarded: quoted.awarded,
|
||||
holdReleased: holds.released,
|
||||
stuckRetried: stuck.retried,
|
||||
stuckAdvanced: stuck.advanced
|
||||
};
|
||||
});
|
||||
} catch (error: any) {
|
||||
console.error(`[scheduler] 排队竞价开标失败(${branchCode}):`, error?.message || error);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
);
|
||||
let opened = 0;
|
||||
let cancelled = 0;
|
||||
let emptyClosed = 0;
|
||||
@@ -424,21 +523,17 @@ async function runQueuedBidOpenTick() {
|
||||
let holdReleased = 0;
|
||||
let stuckRetried = 0;
|
||||
let stuckAdvanced = 0;
|
||||
await forEachActiveTenant(async (branchCode) => {
|
||||
const result = await openDueQueuedPerOrderBids(branchCode);
|
||||
opened += result.opened;
|
||||
cancelled += result.cancelled;
|
||||
const empty = await releaseDueEmptyBidRounds(branchCode);
|
||||
emptyClosed += empty.closed;
|
||||
emptyAllocated += empty.allocated;
|
||||
const quoted = await awardDueQuotedBidRounds(branchCode);
|
||||
quotedAwarded += quoted.awarded;
|
||||
const holds = await releaseDueAllocationHolds(branchCode);
|
||||
holdReleased += holds.released;
|
||||
const stuck = await retryStuckAwardedAllocations(branchCode);
|
||||
stuckRetried += stuck.retried;
|
||||
stuckAdvanced += stuck.advanced;
|
||||
});
|
||||
for (const r of perTenant) {
|
||||
if (!r) continue;
|
||||
opened += r.opened;
|
||||
cancelled += r.cancelled;
|
||||
emptyClosed += r.emptyClosed;
|
||||
emptyAllocated += r.emptyAllocated;
|
||||
quotedAwarded += r.quotedAwarded;
|
||||
holdReleased += r.holdReleased;
|
||||
stuckRetried += r.stuckRetried;
|
||||
stuckAdvanced += r.stuckAdvanced;
|
||||
}
|
||||
if (opened || cancelled) {
|
||||
console.log(`[scheduler] 排队竞价开标 ${opened},取消无效草稿 ${cancelled}`);
|
||||
}
|
||||
@@ -479,6 +574,10 @@ export function startScheduledJobs() {
|
||||
void withDistributedLock(SCHEDULER_LOCK_KEY, SCHEDULER_LOCK_TTL_SEC, async () => {
|
||||
await runScheduledJobsTick(true);
|
||||
});
|
||||
// 主系统分配对账:跟随 tick(内部再限流到最多 10 分钟一次)
|
||||
void runMainSystemImportReconcile();
|
||||
// 跨系统改价/改量申请对账(webhook 漏推自愈):跟随 tick,内部限流到 10 分钟一次
|
||||
void runPriceQtyRequestReconcile();
|
||||
}, 15 * 60 * 1000);
|
||||
void withDistributedLock(BID_OPEN_LOCK_KEY, BID_OPEN_LOCK_TTL_SEC, () => runQueuedBidOpenTick());
|
||||
bidOpenTimer = setInterval(() => {
|
||||
|
||||
@@ -1000,6 +1000,41 @@ export async function createSelfPurchaseStockInbound(
|
||||
]
|
||||
);
|
||||
|
||||
/**
|
||||
* §8.7(开发者 2026-10-11 定稿):**自采入库的实收要回写到订单侧**。
|
||||
*
|
||||
* 背景(实测):订单 `…SUP37831443_0002` 的「八角」自采入库录了 0.6,但订单详情仍显示 0.5 ——
|
||||
* 因为详情页的「实收数量」读的是 `inspections.actual_qty`(其次 `picking_items.loaded_qty`),
|
||||
* 而自采入库写的是**第三张表** `self_purchase_stock_inbounds`,两者没有关联。
|
||||
*
|
||||
* 口径:经 `inspection_id → inspections.order_item_id` **唯一定位**订单行后,把该验收记录的
|
||||
* `actual_qty` 更新为本次入库数量;**定位不到就跳过并记日志**(独立入库/称台入库无订单行,不猜)。
|
||||
* 核货实配 `picking_items.loaded_qty` 仍由分拣核货在自己阶段写,两者互不覆盖。
|
||||
*/
|
||||
let actualQtyWrittenBack = false;
|
||||
if (inspectionId) {
|
||||
try {
|
||||
const linked = await client.query<{ order_item_id: string | null }>(
|
||||
`SELECT order_item_id FROM inspections WHERE id = $1::uuid LIMIT 1`,
|
||||
[inspectionId]
|
||||
);
|
||||
const orderItemId = linked.rows[0]?.order_item_id ? String(linked.rows[0].order_item_id) : null;
|
||||
if (orderItemId) {
|
||||
await client.query(`UPDATE inspections SET actual_qty = $2 WHERE id = $1::uuid`, [inspectionId, qty]);
|
||||
actualQtyWrittenBack = true;
|
||||
} else {
|
||||
console.warn(
|
||||
`[self-purchase-inbound] 验收单 ${inspectionId} 未关联订单行(独立/称台入库),本次不回写订单实收`
|
||||
);
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
// 回写失败不阻断入库(入库是主责;实收可在对账/人工修正)
|
||||
console.warn(
|
||||
`[self-purchase-inbound] 订单实收回写失败(不影响入库):${(error as Error)?.message || error}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (owns) await client.query('COMMIT');
|
||||
|
||||
const createdId = String(inserted.rows[0]?.id || '');
|
||||
|
||||
@@ -11,6 +11,7 @@ import { writeAuditLog } from './auditService';
|
||||
import { upsertInventoryHoldingCost } from './inventorySurplusCostService';
|
||||
import { resolveStockMode } from './stockModeService';
|
||||
import { createIndependentInboundInspection } from './independentInboundService';
|
||||
import { assertBranchAllowsProductCatalog } from './platformBranch';
|
||||
|
||||
type Db = Pick<PoolClient, 'query'>;
|
||||
|
||||
@@ -60,6 +61,103 @@ export interface StockInboundInput {
|
||||
unit?: string | null;
|
||||
/** 再完成独立入库时复用 SPI 批次号 */
|
||||
batchNo?: string | null;
|
||||
/** 可选:拍照入库时人工改过的商品档案字段(见 docs/design/20261012-……档案回写.md) */
|
||||
archive?: ArchiveWritebackInput | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 拍照入库的人工修正值:**只回写调用方显式传进来的字段**。
|
||||
* 未传的字段一律不动 —— 「人工值优先直接覆盖」的操作定义就是「只认人工编辑过的字段」,
|
||||
* 避免未经人工确认的 AI 识别值污染商品档案。
|
||||
*
|
||||
* `manufacturer`(厂家,前端语义)映射到库里的 `skus.origin` 列(复用现有列,未新增 manufacturer 列)。
|
||||
*/
|
||||
export interface ArchiveWritebackInput {
|
||||
spec?: string | null;
|
||||
brand?: string | null;
|
||||
manufacturer?: string | null;
|
||||
}
|
||||
|
||||
/** skus.spec / brand / origin 三列均为 VARCHAR(100),先截断再落库,避免 22001 打断入库事务 */
|
||||
const ARCHIVE_FIELD_MAX = 100;
|
||||
|
||||
/** 客户端上报值的长度上限;落库时还会按列宽再截断一次 */
|
||||
const ARCHIVE_INPUT_MAX = 200;
|
||||
|
||||
const ARCHIVE_FIELDS = ['spec', 'brand', 'manufacturer'] as const;
|
||||
|
||||
/**
|
||||
* 归一化移动端上报的 `archive`:**逐个字段判在不在**,不在的字段保持 `undefined`(服务端就不写它)。
|
||||
* 返回 `null` = 本次不产生任何档案回写。
|
||||
*
|
||||
* 与 `applyArchiveWriteback` 放在一起:二者是「校验入参 → 落库写入」的一对,
|
||||
* 分开会让「哪些字段算人工值」的判据在两层各写一份。
|
||||
*/
|
||||
export function normalizeArchive(raw: unknown): ArchiveWritebackInput | null {
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
|
||||
const source = raw as Record<string, unknown>;
|
||||
const archive: ArchiveWritebackInput = {};
|
||||
let any = false;
|
||||
for (const field of ARCHIVE_FIELDS) {
|
||||
if (!Object.prototype.hasOwnProperty.call(source, field)) continue;
|
||||
const value = source[field];
|
||||
if (value == null) continue;
|
||||
archive[field] = String(value).slice(0, ARCHIVE_INPUT_MAX);
|
||||
any = true;
|
||||
}
|
||||
return any ? archive : null;
|
||||
}
|
||||
|
||||
function hasAnyArchiveField(archive?: ArchiveWritebackInput | null): boolean {
|
||||
if (!archive) return false;
|
||||
return (
|
||||
archive.spec != null || archive.brand != null || archive.manufacturer != null
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 把人工确认过的规格 / 品牌 / 厂家写回商品档案。
|
||||
*
|
||||
* · 规格、品牌 → `product_catalog`,由触发器 `sync_product_catalog_to_legacy()` 同步到 `skus`;
|
||||
* · 厂家 → **显式写 `skus.origin`**,因为该触发器不复制 `origin`;
|
||||
* · 与入库同事务:入库失败则回写一并回滚,不会出现「档案改了但货没入库」;
|
||||
* · 取值先 TRIM(与既有 `trimText` 口径一致),空串会被**当成一次真实的清空**写入。
|
||||
*/
|
||||
export async function applyArchiveWriteback(
|
||||
db: Db,
|
||||
input: { skuCode: string; branchCode?: string | null; archive?: ArchiveWritebackInput | null }
|
||||
): Promise<void> {
|
||||
if (!hasAnyArchiveField(input.archive)) return;
|
||||
const skuCode = trimText(input.skuCode);
|
||||
if (!skuCode) return;
|
||||
assertBranchAllowsProductCatalog(trimText(input.branchCode) || null);
|
||||
const archive = input.archive!;
|
||||
|
||||
const hasCatalogField = archive.spec != null || archive.brand != null;
|
||||
if (hasCatalogField) {
|
||||
await db.query(
|
||||
`UPDATE product_catalog
|
||||
SET spec = CASE WHEN $1::boolean THEN LEFT(TRIM($2), ${ARCHIVE_FIELD_MAX}) ELSE spec END,
|
||||
brand = CASE WHEN $3::boolean THEN LEFT(TRIM($4), ${ARCHIVE_FIELD_MAX}) ELSE brand END,
|
||||
updated_at = NOW()
|
||||
WHERE item_type = 'product' AND code = $5`,
|
||||
[
|
||||
archive.spec != null,
|
||||
archive.spec == null ? null : String(archive.spec),
|
||||
archive.brand != null,
|
||||
archive.brand == null ? null : String(archive.brand),
|
||||
skuCode,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
// 触发器不复制 origin ⇒ 厂家必须显式写 skus
|
||||
if (archive.manufacturer != null) {
|
||||
await db.query(
|
||||
`UPDATE skus SET origin = LEFT(TRIM($2), ${ARCHIVE_FIELD_MAX}) WHERE sku_code = $1`,
|
||||
[skuCode, String(archive.manufacturer)]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export interface StockInboundResult {
|
||||
@@ -128,6 +226,13 @@ export async function inboundFromWeigh(
|
||||
unit = inboundUnit;
|
||||
}
|
||||
|
||||
// 拍照入库:人工改过的规格/品牌/厂家回写商品档案(只写传进来的字段,与入库同事务)
|
||||
await applyArchiveWriteback(db, {
|
||||
skuCode,
|
||||
branchCode,
|
||||
archive: input.archive,
|
||||
});
|
||||
|
||||
const mode = await resolveStockMode({ skuCode, branchCode }, db);
|
||||
if (mode !== 'inventory') {
|
||||
throw Object.assign(new Error('过手商品不能独立入库,请先在商品管理改为「管库存」'), {
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
import { randomUUID } from 'crypto';
|
||||
import type { PoolClient } from 'pg';
|
||||
import { pool } from '../db';
|
||||
import { ensureTenantSchemaCloned, applyTenantSearchPath } from './tenantSchemaService';
|
||||
import { hashPassword } from '../utils/password';
|
||||
import type { MainSupplierProfile } from './mainSystemSupplierAuth';
|
||||
|
||||
/**
|
||||
* 惰性开通:主系统供应商 → 本系统「分公司 + 分公司管理员」。
|
||||
*
|
||||
* 触发时机:某个手机号在本系统**查不到账号**,但通过了主系统的供应商凭据校验。
|
||||
* 一次事务内完成(与 `POST /api/auth/admin/branches` 的开通步骤一致):
|
||||
* 1. branches (branch_code = 主系统 supplier_code)
|
||||
* 2. 租户 schema (ensureTenantSchemaCloned,分公司级数据隔离靠它)
|
||||
* 3. system_configs 分公司级初始化
|
||||
* 4. auth.users (登录名 = 手机号,密码写**随机不可用**值)
|
||||
* 5. profiles (account_source='main_supplier',绑定分公司)
|
||||
* 6. user_roles (role='admin')
|
||||
*
|
||||
* 幂等:以**手机号**为准——已存在且来源为 main_supplier 直接复用;
|
||||
* 若该手机号已被本系统内部账号占用,则拒绝(绝不抢占内部账号)。
|
||||
* 密码:本地写入随机哈希(本地永远校验不过),登录一律回主系统校验 ⇒ 主系统改密/停用即时生效。
|
||||
*/
|
||||
|
||||
/** 与 admin/branches 保持一致的分公司级默认配置 */
|
||||
const BRANCH_LLM_CONFIG_JSON =
|
||||
'{"enabled": false, "provider": "ark", "apiKeys": "", "model": "doubao-seed-2-0-lite-260428", "imageModel": "doubao-seedream-4-0-250828", "imageSize": "512x512", "baseUrl": "https://ark.cn-beijing.volces.com/api/v3"}';
|
||||
|
||||
export type SupplierBranchProvisionResult = {
|
||||
userId: string;
|
||||
branchCode: string;
|
||||
/** 本次是否新建(false = 复用既有开通结果) */
|
||||
created: boolean;
|
||||
};
|
||||
|
||||
function err(code: string, message: string) {
|
||||
return Object.assign(new Error(message), { code });
|
||||
}
|
||||
|
||||
export async function ensureMainSupplierBranchAndAdmin(
|
||||
profile: MainSupplierProfile
|
||||
): Promise<SupplierBranchProvisionResult> {
|
||||
const branchCode = String(profile.supplierCode || '').trim().toUpperCase();
|
||||
const username = String(profile.phone || '').trim();
|
||||
if (!branchCode || !username) {
|
||||
throw err('invalid_supplier_profile', '主系统返回的供应商档案不完整(缺 supplier_code 或手机号)');
|
||||
}
|
||||
|
||||
// ① 幂等:手机号已开通 ⇒ 直接复用
|
||||
const existingAccount = await pool.query<{ id: string; branch_code: string | null; account_source: string }>(
|
||||
`SELECT id, branch_code, account_source FROM profiles WHERE lower(username) = lower($1) LIMIT 1`,
|
||||
[username]
|
||||
);
|
||||
if (existingAccount.rowCount) {
|
||||
const row = existingAccount.rows[0];
|
||||
if (row.account_source !== 'main_supplier') {
|
||||
throw err('login_name_taken', '该手机号已被本系统内部账号占用,无法作为供应商管理员开通');
|
||||
}
|
||||
return { userId: row.id, branchCode: row.branch_code || branchCode, created: false };
|
||||
}
|
||||
|
||||
const userId = randomUUID();
|
||||
const email = `${username}@meoo.local`;
|
||||
const fullName = profile.contactName || `${profile.companyName}管理员`;
|
||||
// 本地密码:随机值,本地校验永远不通过(登录一律回主系统)
|
||||
const passwordHash = await hashPassword(randomUUID() + randomUUID());
|
||||
|
||||
const client: PoolClient = await pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
|
||||
// ② 分公司主档:已存在(可能是超管手工建的同码分公司)则复用,不覆盖其资料
|
||||
const branchExists = await client.query('SELECT 1 FROM branches WHERE branch_code = $1', [branchCode]);
|
||||
if (!branchExists.rowCount) {
|
||||
await client.query(
|
||||
`INSERT INTO branches (branch_code, branch_name, contact_name, contact_phone, address, status)
|
||||
VALUES ($1, $2, $3, $4, $5, 1)`,
|
||||
[branchCode, profile.companyName, profile.contactName || null, username, null]
|
||||
);
|
||||
} else {
|
||||
console.warn(`[supplier-provision] 分公司 ${branchCode} 已存在,复用之(不覆盖既有资料)`);
|
||||
}
|
||||
|
||||
// ③ 租户 schema(幂等)+ 分公司级配置
|
||||
const schemaName = await ensureTenantSchemaCloned(branchCode, 'active', client);
|
||||
await applyTenantSearchPath(client, schemaName);
|
||||
await client.query(
|
||||
`INSERT INTO system_configs (config_key, config_value, config_group, description, branch_code)
|
||||
VALUES ('branch_llm_config', $1::jsonb, 'ai', '分公司大模型配置', $2)
|
||||
ON CONFLICT ((COALESCE(branch_code, '__GLOBAL__')), config_key) DO NOTHING`,
|
||||
[BRANCH_LLM_CONFIG_JSON, branchCode]
|
||||
);
|
||||
|
||||
// ④ 账号与角色都落在 public
|
||||
await client.query(`SELECT set_config('search_path', 'public', true)`);
|
||||
|
||||
const emailTaken = await client.query('SELECT 1 FROM auth.users WHERE lower(email) = lower($1)', [email]);
|
||||
if (emailTaken.rowCount) {
|
||||
throw err('login_name_taken', '该手机号对应的登录账号已存在');
|
||||
}
|
||||
|
||||
await client.query(
|
||||
`INSERT INTO auth.users (
|
||||
instance_id, id, aud, role, email, encrypted_password, email_confirmed_at,
|
||||
raw_app_meta_data, raw_user_meta_data
|
||||
) VALUES (
|
||||
'00000000-0000-0000-0000-000000000000', $1, 'authenticated', 'authenticated', $2,
|
||||
$3, NOW(),
|
||||
'{"provider":"email","providers":["email"]}'::jsonb, $4::jsonb
|
||||
)`,
|
||||
[userId, email, passwordHash, JSON.stringify({ username, full_name: fullName })]
|
||||
);
|
||||
|
||||
// must_change_password = false:密码本来就是主系统那套,不要求再改一次
|
||||
//
|
||||
// ⚠️ 必须用 ON CONFLICT:auth.users 上有 AFTER INSERT 触发器 on_auth_user_created →
|
||||
// handle_new_user(),它会**先插一行 profiles**(id/username/full_name/avatar_url)。
|
||||
// 直接 INSERT 会撞 profiles_pkey(实测 23505)。这里改为 upsert,
|
||||
// 无论触发器在不在都能把分公司、来源、状态补齐。
|
||||
await client.query(
|
||||
`INSERT INTO profiles (id, username, full_name, phone, branch_code, status, must_change_password, account_source)
|
||||
VALUES ($1, $2, $3, $4, $5, 1, false, 'main_supplier')
|
||||
ON CONFLICT (id) DO UPDATE SET
|
||||
username = EXCLUDED.username,
|
||||
full_name = EXCLUDED.full_name,
|
||||
phone = EXCLUDED.phone,
|
||||
branch_code = EXCLUDED.branch_code,
|
||||
status = EXCLUDED.status,
|
||||
must_change_password = EXCLUDED.must_change_password,
|
||||
account_source = EXCLUDED.account_source`,
|
||||
[userId, username, fullName, username, branchCode]
|
||||
);
|
||||
|
||||
await client.query(`INSERT INTO user_roles (user_id, role) VALUES ($1, 'admin')`, [userId]);
|
||||
|
||||
await client.query('COMMIT');
|
||||
console.log(
|
||||
`[supplier-provision] 已开通分公司 ${branchCode}(${profile.companyName})管理员 ${username}`
|
||||
);
|
||||
return { userId, branchCode, created: true };
|
||||
} catch (error) {
|
||||
await client.query('ROLLBACK').catch(() => undefined);
|
||||
throw error;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
@@ -3,16 +3,54 @@ import { getTenantDbStore, runWithTenantDbContext } from './tenantDbContext';
|
||||
|
||||
const rawQuery = getRawPoolQuery();
|
||||
|
||||
/**
|
||||
* 优先租户:调用方显式传入 > 当前请求 ALS 里的租户。
|
||||
*
|
||||
* 背景(2026-10-08 规模改造):业务绑定表只在 `tenant_*`,历史上只能逐个 active schema 试。
|
||||
* 成本随「主系统供应商数」线性增长(实测 104 租户 63.5 ms,每租户 0.61 ms),
|
||||
* 而 `getDeliveryPersonCode` 之类在每个小程序请求上都要调一次。
|
||||
* 账号所属分公司其实一直写在 `public.profiles.branch_code`(登录判 need_branch 用的就是它),
|
||||
* 所以先查这一个租户即可;**查不到仍然回退原来的全租户扫描**,语义不变。
|
||||
*/
|
||||
export function resolvePreferredTenantBranch(explicitBranchCode?: string | null): string | null {
|
||||
const explicit = String(explicitBranchCode ?? '').trim();
|
||||
if (explicit) return explicit;
|
||||
const fromRequest = getTenantDbStore()?.branchCode;
|
||||
const normalized = String(fromRequest ?? '').trim();
|
||||
return normalized || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 候选租户顺序:优先租户(可空)排第一,其余保持原 `ORDER BY branch_code` 顺序。
|
||||
* **集合与原来完全相同**,只是把已知租户提前;优先租户不在 active 名单里时不改变顺序
|
||||
* ——否则会去查一个没有 schema 的分公司,`search_path` 落到 public 反而报「表不存在」。
|
||||
*/
|
||||
export function orderTenantBranches(
|
||||
tenants: Array<{ branch_code: string }>,
|
||||
preferredBranchCode?: string | null
|
||||
): string[] {
|
||||
const codes = tenants.map((t) => String(t.branch_code || '').trim()).filter(Boolean);
|
||||
const preferred = resolvePreferredTenantBranch(preferredBranchCode);
|
||||
if (!preferred || !codes.includes(preferred)) return codes;
|
||||
return [preferred, ...codes.filter((c) => c !== preferred)];
|
||||
}
|
||||
|
||||
export async function listActiveTenantBranches(): Promise<
|
||||
Array<{ branch_code: string; schema_name: string }>
|
||||
> {
|
||||
// 规模改造 §7:本函数被「每次跨租户查找」调用,500 个分公司下纯属重复打库。
|
||||
// 30 s TTL(TENANT_LIST_CACHE_TTL_MS=0 关闭);注册新租户时由
|
||||
// ensureTenantSchemaCloned 主动失效,无需等 TTL。
|
||||
const cached = activeTenantBranchesCache;
|
||||
if (cached && cached.expiresAt > Date.now()) return cached.value;
|
||||
|
||||
const result = await rawQuery(
|
||||
`SELECT branch_code, schema_name
|
||||
FROM public.tenant_schema_registry
|
||||
WHERE status = 'active'
|
||||
ORDER BY branch_code`
|
||||
);
|
||||
return (result.rows || [])
|
||||
const value = (result.rows || [])
|
||||
.map((r: { branch_code: string; schema_name: string }) => ({
|
||||
branch_code: String(r.branch_code || '').trim(),
|
||||
schema_name: String(r.schema_name || '').trim(),
|
||||
@@ -21,8 +59,37 @@ export async function listActiveTenantBranches(): Promise<
|
||||
(r: { branch_code: string; schema_name: string }) =>
|
||||
r.branch_code && /^tenant_[a-z0-9_-]{2,30}$/.test(r.schema_name)
|
||||
);
|
||||
if (activeTenantBranchesTtlMs > 0) {
|
||||
activeTenantBranchesCache = { value, expiresAt: Date.now() + activeTenantBranchesTtlMs };
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/** 新建/停用分公司后调用,避免最长 TTL 的可见性延迟。 */
|
||||
export function invalidateActiveTenantBranchesCache(): void {
|
||||
activeTenantBranchesCache = null;
|
||||
}
|
||||
|
||||
/** 仅测试用:清缓存并重读 TTL 环境变量。 */
|
||||
export function resetActiveTenantBranchesCacheForTest(): void {
|
||||
activeTenantBranchesCache = null;
|
||||
activeTenantBranchesTtlMs = readActiveTenantBranchesTtlMs();
|
||||
}
|
||||
|
||||
function readActiveTenantBranchesTtlMs(): number {
|
||||
const raw = process.env.TENANT_LIST_CACHE_TTL_MS;
|
||||
if (raw === undefined || raw === '') return 30_000;
|
||||
const value = Number(raw);
|
||||
if (!Number.isFinite(value) || value < 0) return 30_000;
|
||||
return Math.floor(value);
|
||||
}
|
||||
|
||||
let activeTenantBranchesTtlMs = readActiveTenantBranchesTtlMs();
|
||||
let activeTenantBranchesCache: {
|
||||
value: Array<{ branch_code: string; schema_name: string }>;
|
||||
expiresAt: number;
|
||||
} | null = null;
|
||||
|
||||
/**
|
||||
* 公开/无 ALS 读路径:先执行一次(通常命中 public 双轨),
|
||||
* 未命中再按 active tenant 进入 ALS 重试,返回首个命中结果。
|
||||
|
||||
@@ -71,6 +71,16 @@ export async function resolveActiveTenantSchema(
|
||||
return schema;
|
||||
}
|
||||
|
||||
/** 手工/运维改动租户登记后调用;传 branchCode 只清该分公司(含 60 s 的「无 schema」负缓存) */
|
||||
export function invalidateTenantSchemaResolveCache(branchCode?: string): void {
|
||||
const code = String(branchCode || '').trim();
|
||||
if (code) {
|
||||
schemaResolveCache.delete(code);
|
||||
return;
|
||||
}
|
||||
schemaResolveCache.clear();
|
||||
}
|
||||
|
||||
export async function ensureTenantSchemaCloned(
|
||||
branchCode: string,
|
||||
status: TenantSchemaStatus = 'pending',
|
||||
@@ -85,6 +95,11 @@ export async function ensureTenantSchemaCloned(
|
||||
`SELECT public.clone_tenant_schema($1, $2) AS clone_tenant_schema`,
|
||||
[code, status]
|
||||
);
|
||||
// 规模改造 §7:租户清单有 30 s 缓存、schema 解析有 60 s 缓存(含「无 schema」负缓存),
|
||||
// 这里一起主动失效,保证新建分公司**立刻**可用(否则首次登录后的请求可能仍按"无租户"落到 public)
|
||||
const { invalidateActiveTenantBranchesCache } = await import('./tenantSchemaFallback');
|
||||
invalidateActiveTenantBranchesCache();
|
||||
invalidateTenantSchemaResolveCache(code);
|
||||
return String(result.rows[0]?.clone_tenant_schema || tenantSchemaName(code));
|
||||
}
|
||||
|
||||
|
||||
@@ -190,12 +190,36 @@ async function loadTenantContextUncached(userId: string): Promise<TenantContext
|
||||
let supplierCode: string | null = null;
|
||||
let purchaserCode: string | null = null;
|
||||
if (!isInternalStaff) {
|
||||
// 业务绑定表在 tenant_*:无 ALS 时按 active schema 扫描;命中则带回分公司
|
||||
const { listActiveTenantBranches } = await import('./tenantSchemaFallback');
|
||||
// 业务绑定表在 tenant_*:原来只能按 active schema 逐个扫、取「首个任意命中」。
|
||||
// 规模改造 §4:`profiles.branch_code` 已知时先只查那一个租户(实测 104 租户 63.5 ms → 0.9 ms)。
|
||||
// 但**只有该租户命中这个账号「声明身份」对应的绑定时才算数**(邮箱后缀 = 建号角色);
|
||||
// 否则退回原来的「按 branch_code 顺序取首个任意命中」,结果与改造前完全一致
|
||||
// (覆盖:老账号无 branch_code、调岗后旧绑定残留等)。
|
||||
const { listActiveTenantBranches, resolvePreferredTenantBranch } = await import('./tenantSchemaFallback');
|
||||
const { runWithTenantDbContext } = await import('./tenantDbContext');
|
||||
const { declaredBindingKinds } = await import('../utils/accountBindingKinds');
|
||||
const tenants = await listActiveTenantBranches();
|
||||
for (const t of tenants) {
|
||||
const hit = await runWithTenantDbContext(t.branch_code, async () => {
|
||||
const emailResult = await rawQuery(`SELECT email FROM auth.users WHERE id = $1`, [userId]);
|
||||
const declared = declaredBindingKinds(String(emailResult.rows?.[0]?.email || ''));
|
||||
// 只有当 `profiles.branch_code` 确实是「registry=active 的租户」时才拿它当优先租户。
|
||||
// 否则绝不能查:`runWithTenantDbContext` 在 schema 解析为 null 时会以连接默认 search_path(public)执行,
|
||||
// 而 supplier_users/purchaser_users/delivery_person_users 只在 tenant_*(迁移 20260775 已把 public 副本挪走),
|
||||
// 结果是把「没有租户 = 找不到绑定」变成 42P01 抛错(每个请求 500,且 loadTenantContext 只缓存成功结果,不会自愈)。
|
||||
// 触发面:registry 回滚成 pending、分公司建了但克隆失败/没克隆、脚本直接插 branches。
|
||||
const preferredCandidate = resolvePreferredTenantBranch(branchCode);
|
||||
const preferred =
|
||||
preferredCandidate && tenants.some((t) => String(t.branch_code || '').trim() === preferredCandidate)
|
||||
? preferredCandidate
|
||||
: null;
|
||||
|
||||
const hitCache = new Map<
|
||||
string,
|
||||
{ supplierCode: string | null; purchaserCode: string | null; hasDelivery: boolean }
|
||||
>();
|
||||
const queryBindings = async (branchCodeToTry: string) => {
|
||||
const cached = hitCache.get(branchCodeToTry);
|
||||
if (cached) return cached;
|
||||
const hit = await runWithTenantDbContext(branchCodeToTry, async () => {
|
||||
const [supplierResult, purchaserResult, deliveryResult] = await Promise.all([
|
||||
pool.query(
|
||||
`SELECT supplier_code FROM supplier_users WHERE user_id = $1 AND status = 1 LIMIT 1`,
|
||||
@@ -216,14 +240,52 @@ async function loadTenantContextUncached(userId: string): Promise<TenantContext
|
||||
hasDelivery: Boolean(deliveryResult.rowCount),
|
||||
};
|
||||
});
|
||||
if (hit.supplierCode || hit.purchaserCode || hit.hasDelivery) {
|
||||
supplierCode = hit.supplierCode;
|
||||
purchaserCode = hit.purchaserCode;
|
||||
// 外部账号常无 profiles.branch_code:用绑定所在租户作为操作分公司
|
||||
if (!branchCode) {
|
||||
branchCode = t.branch_code;
|
||||
hitCache.set(branchCodeToTry, hit);
|
||||
return hit;
|
||||
};
|
||||
const satisfiesDeclared = (hit: {
|
||||
supplierCode: string | null;
|
||||
purchaserCode: string | null;
|
||||
hasDelivery: boolean;
|
||||
}) =>
|
||||
declared.length > 0
|
||||
? declared.every((kind) =>
|
||||
kind === 'purchaser' ? !!hit.purchaserCode : kind === 'supplier' ? !!hit.supplierCode : hit.hasDelivery
|
||||
)
|
||||
: Boolean(hit.supplierCode || hit.purchaserCode || hit.hasDelivery);
|
||||
|
||||
const applyHit = (
|
||||
hit: { supplierCode: string | null; purchaserCode: string | null; hasDelivery: boolean },
|
||||
branchCodeOfTenant: string
|
||||
) => {
|
||||
supplierCode = hit.supplierCode;
|
||||
purchaserCode = hit.purchaserCode;
|
||||
// 外部账号常无 profiles.branch_code:用绑定所在租户作为操作分公司
|
||||
if (!branchCode) {
|
||||
branchCode = branchCodeOfTenant;
|
||||
}
|
||||
};
|
||||
|
||||
let resolved = false;
|
||||
if (preferred) {
|
||||
const hit = await queryBindings(preferred);
|
||||
if (satisfiesDeclared(hit)) {
|
||||
applyHit(hit, preferred);
|
||||
resolved = true;
|
||||
} else if (hit.supplierCode || hit.purchaserCode || hit.hasDelivery) {
|
||||
console.warn(
|
||||
`[tenant-scope] 账号在 profiles.branch_code=${preferred} 内未命中声明绑定(${declared.join('/') || '任意'}),回退全租户扫描`
|
||||
);
|
||||
}
|
||||
}
|
||||
if (!resolved) {
|
||||
// 原顺序(branch_code 升序)、原语义(首个任意命中):结果与改造前一致
|
||||
for (const t of tenants) {
|
||||
const hit = await queryBindings(t.branch_code);
|
||||
if (hit.supplierCode || hit.purchaserCode || hit.hasDelivery) {
|
||||
applyHit(hit, t.branch_code);
|
||||
break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+106
-32
@@ -1,53 +1,117 @@
|
||||
import { Pool } from 'pg';
|
||||
|
||||
function resolveAdminDatabaseUrl(): string {
|
||||
if (process.env.ADMIN_DATABASE_URL) return process.env.ADMIN_DATABASE_URL;
|
||||
const appUrl = process.env.DATABASE_URL || '';
|
||||
try {
|
||||
if (appUrl) {
|
||||
const u = new URL(appUrl);
|
||||
const host = u.hostname || '127.0.0.1';
|
||||
const port = u.port || '5432';
|
||||
// 与应用库同主机端口;用户名默认 postgres(可用 ADMIN_DATABASE_URL 覆盖)
|
||||
return `postgresql://postgres@${host}:${port}/postgres`;
|
||||
}
|
||||
} catch {
|
||||
/* fall through */
|
||||
}
|
||||
return 'postgresql://postgres@127.0.0.1:5432/postgres';
|
||||
/**
|
||||
* 本地库初始化(供应商系统二次开发版)。
|
||||
*
|
||||
* 与主系统(AI 生鲜配送系统)的差异:
|
||||
* - 角色名 / 口令 / 库名全部从 DATABASE_URL 解析,不再硬编码 canteen / canteen123 / canteen_delivery;
|
||||
* - 显式拒绝把主系统库名(canteen_delivery)当成本系统目标库,避免误动主系统数据;
|
||||
* - 自动把 RLS 应用角色(canteen_app_rls,集群级共享)授权给应用角色,
|
||||
* 否则 RLS_REQUIRED=1 时 `SET LOCAL ROLE` 探测失败会导致服务拒绝启动。
|
||||
*
|
||||
* 解析放在函数内部,保证「import 本模块」不产生副作用(migrate.ts 会 import 它)。
|
||||
*/
|
||||
|
||||
/** 主系统(AI 生鲜配送系统)专用库名:本系统一律不许作为目标库 */
|
||||
const PROTECTED_DATABASE_NAMES = new Set(['canteen_delivery']);
|
||||
|
||||
/** RLS 非 owner 应用角色:由 migrations/20260736_rls_app_role.sql 创建,集群级共享 */
|
||||
const RLS_APP_ROLE = 'canteen_app_rls';
|
||||
|
||||
type AppTarget = {
|
||||
user: string;
|
||||
password: string;
|
||||
host: string;
|
||||
port: string;
|
||||
database: string;
|
||||
};
|
||||
|
||||
function quoteIdent(name: string): string {
|
||||
return `"${name.replace(/"/g, '""')}"`;
|
||||
}
|
||||
|
||||
const ADMIN_URL = resolveAdminDatabaseUrl();
|
||||
const APP_URL = process.env.DATABASE_URL || 'postgresql://canteen:canteen123@127.0.0.1:5432/canteen_delivery';
|
||||
function quoteLiteral(value: string): string {
|
||||
return `'${value.replace(/'/g, "''")}'`;
|
||||
}
|
||||
|
||||
function resolveAppTarget(): AppTarget {
|
||||
const appUrl = process.env.DATABASE_URL || '';
|
||||
if (!appUrl) {
|
||||
throw new Error('必须设置 DATABASE_URL(例如 postgresql://supplier:***@127.0.0.1:5432/supplier_delivery)');
|
||||
}
|
||||
const parsed = new URL(appUrl);
|
||||
const target: AppTarget = {
|
||||
user: decodeURIComponent(parsed.username),
|
||||
password: decodeURIComponent(parsed.password),
|
||||
host: parsed.hostname || '127.0.0.1',
|
||||
port: parsed.port || '5432',
|
||||
database: decodeURIComponent(parsed.pathname.replace(/^\//, '')),
|
||||
};
|
||||
if (!target.user || !target.database) {
|
||||
throw new Error(`DATABASE_URL 缺少角色名或库名:${appUrl}`);
|
||||
}
|
||||
if (PROTECTED_DATABASE_NAMES.has(target.database)) {
|
||||
throw new Error(
|
||||
`拒绝执行:目标库 ${target.database} 属于主系统(AI 生鲜配送系统)。` +
|
||||
'请把 DATABASE_URL 指向本系统的独立库(默认 supplier_delivery)。'
|
||||
);
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
function resolveAdminDatabaseUrl(target: AppTarget): string {
|
||||
if (process.env.ADMIN_DATABASE_URL) return process.env.ADMIN_DATABASE_URL;
|
||||
// 与应用库同主机端口;用户名默认 postgres(可用 ADMIN_DATABASE_URL 覆盖)
|
||||
return `postgresql://postgres@${target.host}:${target.port}/postgres`;
|
||||
}
|
||||
|
||||
async function setupDatabase() {
|
||||
const admin = new Pool({ connectionString: ADMIN_URL });
|
||||
const target = resolveAppTarget();
|
||||
const adminUrl = resolveAdminDatabaseUrl(target);
|
||||
const appUrl = process.env.DATABASE_URL as string;
|
||||
|
||||
const admin = new Pool({ connectionString: adminUrl });
|
||||
try {
|
||||
console.log('Setting up local PostgreSQL database...');
|
||||
console.log('Setting up local PostgreSQL database (supplier system)...');
|
||||
console.log(` target database: ${target.database}`);
|
||||
console.log(` target role: ${target.user}`);
|
||||
|
||||
const userExists = await admin.query(`SELECT 1 FROM pg_roles WHERE rolname = 'canteen'`);
|
||||
if (!userExists.rowCount) {
|
||||
await admin.query(`CREATE USER canteen WITH PASSWORD 'canteen123'`);
|
||||
console.log('Created user: canteen');
|
||||
// 1) 应用角色:存在则改口令,不存在则创建(非超级用户)
|
||||
const roleExists = await admin.query('SELECT 1 FROM pg_roles WHERE rolname = $1', [target.user]);
|
||||
if (!roleExists.rowCount) {
|
||||
await admin.query(`CREATE USER ${quoteIdent(target.user)} WITH PASSWORD ${quoteLiteral(target.password)}`);
|
||||
console.log(`Created user: ${target.user}`);
|
||||
} else {
|
||||
await admin.query(`ALTER USER canteen WITH PASSWORD 'canteen123'`);
|
||||
console.log('Updated password for user: canteen');
|
||||
await admin.query(`ALTER USER ${quoteIdent(target.user)} WITH PASSWORD ${quoteLiteral(target.password)}`);
|
||||
console.log(`Updated password for user: ${target.user}`);
|
||||
}
|
||||
|
||||
const dbExists = await admin.query(`SELECT 1 FROM pg_database WHERE datname = 'canteen_delivery'`);
|
||||
// 2) RLS 应用角色(与迁移 20260736 一致;集群级共享,主系统可能已创建)
|
||||
const rlsExists = await admin.query('SELECT 1 FROM pg_roles WHERE rolname = $1', [RLS_APP_ROLE]);
|
||||
if (!rlsExists.rowCount) {
|
||||
await admin.query(`CREATE ROLE ${quoteIdent(RLS_APP_ROLE)} NOLOGIN`);
|
||||
console.log(`Created RLS role: ${RLS_APP_ROLE}`);
|
||||
}
|
||||
// 非超级用户必须显式获得成员资格,才能在事务内 SET LOCAL ROLE
|
||||
await admin.query(`GRANT ${quoteIdent(RLS_APP_ROLE)} TO ${quoteIdent(target.user)}`);
|
||||
console.log(`Granted ${RLS_APP_ROLE} to ${target.user}`);
|
||||
|
||||
// 3) 应用库:不存在则创建,owner 指向应用角色
|
||||
const dbExists = await admin.query('SELECT 1 FROM pg_database WHERE datname = $1', [target.database]);
|
||||
if (!dbExists.rowCount) {
|
||||
await admin.query(`CREATE DATABASE canteen_delivery OWNER canteen`);
|
||||
console.log('Created database: canteen_delivery');
|
||||
await admin.query(`CREATE DATABASE ${quoteIdent(target.database)} OWNER ${quoteIdent(target.user)}`);
|
||||
console.log(`Created database: ${target.database}`);
|
||||
} else {
|
||||
console.log('Database already exists: canteen_delivery');
|
||||
console.log(`Database already exists: ${target.database}`);
|
||||
}
|
||||
|
||||
await admin.query(`GRANT ALL PRIVILEGES ON DATABASE canteen_delivery TO canteen`);
|
||||
await admin.query(
|
||||
`GRANT ALL PRIVILEGES ON DATABASE ${quoteIdent(target.database)} TO ${quoteIdent(target.user)}`
|
||||
);
|
||||
} finally {
|
||||
await admin.end();
|
||||
}
|
||||
|
||||
const app = new Pool({ connectionString: APP_URL });
|
||||
const app = new Pool({ connectionString: appUrl });
|
||||
try {
|
||||
await app.query('SELECT 1');
|
||||
console.log('Application database connection OK');
|
||||
@@ -67,4 +131,14 @@ if (require.main === module) {
|
||||
});
|
||||
}
|
||||
|
||||
/** 当前 DATABASE_URL 中的应用角色名(migrate.ts 收尾授权用,勿硬编码角色名) */
|
||||
export function resolveAppRoleName(): string {
|
||||
return resolveAppTarget().user;
|
||||
}
|
||||
|
||||
/** PostgreSQL 标识符安全加引号 */
|
||||
export function quotePgIdent(name: string): string {
|
||||
return quoteIdent(name);
|
||||
}
|
||||
|
||||
export { setupDatabase };
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* 账号「声明身份」→ 绑定类别(2026-10-08 规模改造 §4)。
|
||||
*
|
||||
* 移动端账号在建号时就按角色定了邮箱后缀(`userBindingService` / `supplierAccount`),
|
||||
* 后缀即该账号声明的绑定类别。用途:判断「在某个租户里找到的绑定」是否**足以代表**这个账号,
|
||||
* 从而决定能不能跳过跨租户全扫描(O(N) → O(1))。
|
||||
*
|
||||
* 无后缀(后台/内部账号)返回空数组,表示不做声明类别约束。
|
||||
*/
|
||||
export type BindingKind = 'purchaser' | 'supplier' | 'delivery';
|
||||
|
||||
export function declaredBindingKinds(email?: string | null): BindingKind[] {
|
||||
const value = String(email || '');
|
||||
if (value.endsWith('@purchaser.meoo.local')) return ['purchaser'];
|
||||
if (value.endsWith('@supplier.meoo.local')) return ['supplier'];
|
||||
if (value.endsWith('@delivery.meoo.local')) return ['delivery'];
|
||||
return [];
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* 有界并发映射(2026-10-08 规模改造 §6/§7 引入)。
|
||||
*
|
||||
* 背景:本系统按「主系统供应商数」放大成 N 个租户,多处循环是「逐租户串行」。
|
||||
* 500 个分公司时,一次 HTTP 型任务串行跑完要几十秒。这里提供最小可用的
|
||||
* 「保持结果顺序 + 固定并发度 + 单个失败不炸整轮」的工具。
|
||||
*
|
||||
* 约定:
|
||||
* - 返回数组与入参**同序同长**,第 i 项对应 items[i];
|
||||
* - 并发度最小 1(=1 即退回串行,用于回滚);
|
||||
* - `fn` 抛错时该项记 `undefined`,不会中断其余项。**调用方必须自己记日志/计数**
|
||||
* (可传 `onError`,避免失败只以 undefined 形式静默消失)。
|
||||
*/
|
||||
export async function mapWithConcurrency<T, R>(
|
||||
items: readonly T[],
|
||||
concurrency: number,
|
||||
fn: (item: T, index: number) => Promise<R>,
|
||||
onError?: (error: unknown, item: T, index: number) => void
|
||||
): Promise<Array<R | undefined>> {
|
||||
const results: Array<R | undefined> = new Array(items.length);
|
||||
const limit = Math.max(1, Math.min(Math.floor(concurrency) || 1, items.length || 1));
|
||||
let cursor = 0;
|
||||
const workers = new Array(limit).fill(null).map(async () => {
|
||||
for (;;) {
|
||||
const index = cursor;
|
||||
cursor += 1;
|
||||
if (index >= items.length) return;
|
||||
try {
|
||||
results[index] = await fn(items[index], index);
|
||||
} catch (error) {
|
||||
results[index] = undefined;
|
||||
if (onError) {
|
||||
try {
|
||||
onError(error, items[index], index);
|
||||
} catch {
|
||||
/* 回调自身出错不影响其它项 */
|
||||
}
|
||||
} else {
|
||||
console.error(
|
||||
`[concurrency] 第 ${index} 项失败(调用方未传 onError,请看调用点是否漏了日志):`,
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
await Promise.all(workers);
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读环境变量里的并发度;非法值退回 fallback,并受两个上限约束:
|
||||
* `cap`(业务上限)与 `poolMax / 5`(连接池预算)。
|
||||
*
|
||||
* 为什么要池预算(规模改造复查):每个并发租户上下文会**独占一条池连接直到任务结束**
|
||||
* (含回主系统的 HTTP 等待),`PG_POOL_MAX` 默认 30。若运维把池调小(如 10),
|
||||
* 仍按默认 6 并发就会把池占满、让正常请求排队到 10s 超时。这里按池大小自动收敛。
|
||||
*/
|
||||
export function resolveConcurrency(
|
||||
raw: string | number | undefined,
|
||||
fallback: number,
|
||||
cap = 10,
|
||||
poolMax?: number | string
|
||||
): number {
|
||||
const value = Number(raw);
|
||||
const base =
|
||||
!Number.isFinite(value) || value < 1 ? Math.max(1, Math.floor(fallback) || 1) : Math.floor(value);
|
||||
const pool = Number(poolMax);
|
||||
const poolBudget = Number.isFinite(pool) && pool > 0 ? Math.max(1, Math.floor(pool / 5)) : cap;
|
||||
return Math.max(1, Math.min(base, cap, poolBudget));
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
/**
|
||||
* 实收数量/单位「事实登记 + 事后同步」(2026-10-11 口径,设计文档
|
||||
* `docs/design/20261011-实收数量与单位的事后同步.md`)。
|
||||
*
|
||||
* 要钉住的四件事:
|
||||
* ① 事实登记节点 = `picking_check`(核货)+ `inbound`(送仓入库核查)—— 两者驳回都不回滚;
|
||||
* ② 请求要带 `applied_at`(对方实际值生效时刻)并落库;
|
||||
* ③ **同意才落我方值**,且**只改我方自己的数据**(不碰主系统);驳回不落值、只留痕;
|
||||
* ④ 分级:免入库→装车核货量;送仓未入库→验收实收;送仓已入库→既有库存调整服务;
|
||||
* 已结算/已结案→不直改历史;计划量与金额一起改。
|
||||
*/
|
||||
const inbox = readFileSync(
|
||||
path.join(__dirname, '../src/services/mainSystemActualQtyInbox.ts'),
|
||||
'utf8'
|
||||
);
|
||||
const apply = readFileSync(
|
||||
path.join(__dirname, '../src/services/mainSystemActualQtyApply.ts'),
|
||||
'utf8'
|
||||
);
|
||||
const migration = readFileSync(
|
||||
path.join(__dirname, '../../migrations/20261023_main_system_actual_qty_applied_at.sql'),
|
||||
'utf8'
|
||||
);
|
||||
|
||||
describe('事实登记:两个节点 + applied_at', () => {
|
||||
it('inbound 与 picking_check 都是事实登记节点(驳回不回滚)', () => {
|
||||
const idx = inbox.indexOf('const FACT_NODES');
|
||||
const line = inbox.slice(idx, idx + 400);
|
||||
expect(line).toMatch(/'picking_check'/);
|
||||
expect(line).toMatch(/'inbound'/);
|
||||
});
|
||||
|
||||
it('请求载荷映射并落库 applied_at(迁移也必须有这一列)', () => {
|
||||
expect(inbox).toMatch(/appliedAt:/);
|
||||
expect(inbox).toMatch(/applied_at/);
|
||||
expect(migration).toMatch(/ADD COLUMN IF NOT EXISTS applied_at TIMESTAMPTZ/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('同意才落值:只改我方、驳回零改动', () => {
|
||||
it('decide 只在 approved 且有关联单时调用落值;rejected 不调用', () => {
|
||||
const idx = inbox.indexOf('export async function decideActualQtyRequest');
|
||||
const body = inbox.slice(idx, idx + 6000);
|
||||
expect(body).toMatch(/if \(params\.decision === 'approved' && row\.our_order_code\)/);
|
||||
expect(body).toMatch(/applyActualQtySyncValue\(/);
|
||||
// 落值结论要写回台账(payload.apply),供审核页展示
|
||||
expect(body).toMatch(/jsonb_build_object\('status', \$8::text, 'note', \$9::text/);
|
||||
// 回执失败早退:不得先落值
|
||||
const sentIdx = body.indexOf('if (sent.kind !==');
|
||||
const applyIdx = body.indexOf('applyActualQtySyncValue(');
|
||||
expect(sentIdx).toBeGreaterThan(-1);
|
||||
expect(applyIdx).toBeGreaterThan(sentIdx);
|
||||
});
|
||||
|
||||
it('落值模块不外呼主系统(自己只能改自己的)', () => {
|
||||
expect(apply).not.toMatch(/postMainSystem|requestMainSystem|writeback/i);
|
||||
});
|
||||
});
|
||||
|
||||
describe('分级落点(开发者已批准)', () => {
|
||||
it('免入库 ⇒ 装车核货量(并在缺行时惰性补行,且在租户上下文内)', () => {
|
||||
expect(apply).toMatch(/ensureSkipInboundLoadingLines/);
|
||||
expect(apply).toMatch(/includeAllItems: true/);
|
||||
expect(apply).toMatch(/runWithTenantDbContext\(branchCode, \(\) =>\s*\n\s*ensureSkipInboundLoadingLines/);
|
||||
expect(apply).toMatch(/UPDATE picking_items SET loaded_qty/);
|
||||
});
|
||||
|
||||
it('送仓已入库 ⇒ 复用既有库存调整服务(不直改库存流水)', () => {
|
||||
expect(apply).toMatch(/adjustInboundInspectionQty\(/);
|
||||
expect(apply).toMatch(/inbound_batch_no IS NOT NULL/);
|
||||
});
|
||||
|
||||
it('已结算/已结案 ⇒ 不直改历史,只落"需财务调整"结论', () => {
|
||||
expect(apply).toMatch(/customer_statements/);
|
||||
expect(apply).toMatch(/skipped_settled/);
|
||||
const idx = apply.indexOf('if (Number(settled.rows[0]?.n || 0) > 0 || orderStatus >= 90)');
|
||||
expect(idx).toBeGreaterThan(-1);
|
||||
// 该分支之后才允许出现实收写入
|
||||
expect(apply.indexOf('UPDATE picking_items SET loaded_qty')).toBeGreaterThan(idx);
|
||||
});
|
||||
|
||||
it('计划量与金额一起改(账一致),且台账定位不到就不落值(不猜)', () => {
|
||||
expect(apply).toMatch(/UPDATE order_items SET quantity = \$2, amount = \$3, unit = \$4/);
|
||||
expect(apply).toMatch(/台账里找不到该备货行的对照/);
|
||||
});
|
||||
|
||||
it('改销售字段必须同步结算投影(2026-09-24 口径,防结算停在旧值)', () => {
|
||||
/**
|
||||
* 全局守卫见 `orderSaleChangeSyncsStatements.test.ts`:任何 `UPDATE order_items SET quantity/amount/price`
|
||||
* 的文件都必须调用 `syncStatementsForOrderSafe`。本函数在同步成功后改数量+金额 ⇒ 必须接同一步。
|
||||
*/
|
||||
expect(apply).toMatch(/syncStatementsForOrderSafe\(orderCode/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
/**
|
||||
* 「实收/单位申请」接收端(对方发起 → 我方审核)契约。
|
||||
* 主系统 Q8/Q9 已交付(提交 b8519fbb);我方按 §4.9/§4.10/§4.11 的口径实现。
|
||||
*/
|
||||
const inbox = readFileSync(new URL('../src/services/mainSystemActualQtyInbox.ts', import.meta.url), 'utf8');
|
||||
const route = readFileSync(new URL('../src/routes/mainSystemIntegration.ts', import.meta.url), 'utf8');
|
||||
const api = readFileSync(new URL('../src/services/mainSystem/api/preparations.ts', import.meta.url), 'utf8');
|
||||
const cfg = readFileSync(new URL('../src/services/mainSystem/config.ts', import.meta.url), 'utf8');
|
||||
|
||||
describe('实收申请接收端', () => {
|
||||
it('事件已接线且幂等键用对方 request_id', () => {
|
||||
expect(route).toContain("preparations.actual_qty_request");
|
||||
expect(route).toContain('recordActualQtyRequest');
|
||||
expect(inbox).toContain('WHERE branch_code = $1 AND request_id = $2');
|
||||
expect(inbox).toContain('ON CONFLICT (branch_code, request_id) DO NOTHING');
|
||||
});
|
||||
|
||||
it('事实登记节点 = 核货 + 入库(驳回不回滚),>=60/>=90 = 先审后改', () => {
|
||||
// 2026-10-11 口径变更:入库核查(inbound)也是事实登记(对方先改自己的实际值再发请求)
|
||||
expect(inbox).toMatch(/const FACT_NODES = new Set\(\['picking_check', 'inbound'\]\)/);
|
||||
expect(inbox).toContain('fact_registered');
|
||||
// 驳回:不回传 final_value,且文案明确"对方不回滚、我方只留痕"
|
||||
expect(inbox).toContain("params.decision === 'approved'");
|
||||
expect(inbox).toContain('事实登记,不回滚');
|
||||
// 通过:以 final_value ?? proposed_value 为准
|
||||
expect(inbox).toContain('params.finalValue ?? num(row.proposed_value)');
|
||||
});
|
||||
|
||||
it('决策回传打到主系统的 actual-qty-decision(路径只在 endpoints/config 定义)', () => {
|
||||
expect(api).toContain('export async function postMainSystemActualQtyDecision');
|
||||
expect(api).toContain("mainSystemPath('actualQtyDecision')");
|
||||
expect(cfg).toContain("actualQtyDecision: '/api/supplier/preparations/actual-qty-decision'");
|
||||
expect(api).toContain('request_id: params.requestId');
|
||||
expect(api).toContain('decision: params.decision');
|
||||
});
|
||||
|
||||
it('request_id 必须 UUID(非 UUID 直接忽略,不入待审队列)', () => {
|
||||
expect(inbox).toContain('const UUID_RE =');
|
||||
expect(inbox).toContain('request_id 非 UUID,已忽略');
|
||||
const start = inbox.indexOf('export async function recordActualQtyRequest');
|
||||
const fn = inbox.slice(start, start + 1200);
|
||||
expect(fn).toContain('if (!UUID_RE.test(mapped.requestId))');
|
||||
});
|
||||
|
||||
it('回传失败不落本地结论(避免两边不一致)', () => {
|
||||
expect(inbox).toContain("if (sent.kind !== 'ok')");
|
||||
expect(inbox).toContain('回传主系统失败,未改本地结论');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
/**
|
||||
* 实收数量口径(开发者 2026-10-11 定稿):
|
||||
*
|
||||
* ① **改价(我方销售价 = 主系统成本价)必须双方同意才生效** —— 不在本文件范围(见 mainSystemPriceQtyRequest 测试);
|
||||
* ② **实收数量不审核,两边各自记录、允许不一样**(损耗等原因,大概率不同);
|
||||
* ③ 只有**两个节点**会互相发消息:骑手取货(免入库)与送仓入库;
|
||||
* ④ 主系统发来的实收量**只能作为参照事实留痕**,**禁止**反过来改我方的分拣/配送实收 ——
|
||||
* 否则"主系统入库 ⇒ 我方核货实配被改",损耗差异会被抹平,账就假了。
|
||||
*
|
||||
* 本文件把 ③④ 两条钉成契约(②是业务口径,写在设计文档里)。
|
||||
*/
|
||||
const fulfillment = readFileSync(
|
||||
new URL('../src/services/mainSystemFulfillmentEvents.ts', import.meta.url),
|
||||
'utf8'
|
||||
);
|
||||
const ledger = readFileSync(new URL('../src/services/mainSystemPrepLedger.ts', import.meta.url), 'utf8');
|
||||
const prepApi = readFileSync(new URL('../src/services/mainSystem/api/preparations.ts', import.meta.url), 'utf8');
|
||||
|
||||
describe('实收数量:主系统 → 我方 = 只留痕,不改我方数值', () => {
|
||||
it('主系统实收只写台账参照字段(recordPrepActualQty),事件处理里不碰我方业务字段', () => {
|
||||
const start = fulfillment.indexOf('async function recordActualQtyFacts');
|
||||
const fn = fulfillment.slice(start, start + 1400);
|
||||
expect(fn).toContain('recordPrepActualQty');
|
||||
// 不得顺手改分拣/订单/发车数据
|
||||
for (const forbidden of [
|
||||
'picking_items',
|
||||
'UPDATE order_items',
|
||||
'loaded_qty',
|
||||
'delivery_tasks',
|
||||
'order_items SET quantity',
|
||||
]) {
|
||||
expect(fn, `recordActualQtyFacts 不该出现 ${forbidden}`).not.toContain(forbidden);
|
||||
}
|
||||
});
|
||||
|
||||
it('台账侧只更新 last_actual_qty / qty_diff 一族列', () => {
|
||||
const start = ledger.indexOf('export async function recordPrepActualQty');
|
||||
const fn = ledger.slice(start, start + 2600);
|
||||
expect(fn).toContain('last_actual_qty = $3');
|
||||
expect(fn).toContain('last_qty_diff');
|
||||
expect(fn).not.toContain('picking_items');
|
||||
expect(fn).not.toContain('UPDATE order_items');
|
||||
expect(fn).not.toContain('loaded_qty');
|
||||
});
|
||||
|
||||
it('只认这两个节点事件(其他阶段不得新增数量同步事件)', () => {
|
||||
expect(fulfillment).toContain("'preparations.picked_up' | 'preparations.inbound_completed'");
|
||||
expect(fulfillment).toContain('PREP_PICKED_UP_EVENT');
|
||||
expect(fulfillment).toContain('PREP_INBOUND_COMPLETED_EVENT');
|
||||
});
|
||||
});
|
||||
|
||||
describe('实收数量:我方 → 主系统 = 随发车回写(已有通道)', () => {
|
||||
it('回写载荷带我方实供量 prepare_qty(价格另有审核门禁,不在此列)', () => {
|
||||
expect(prepApi).toContain('prepare_qty: params.prepareQty');
|
||||
expect(prepApi).toContain('purchase_price: params.purchasePrice');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
/**
|
||||
* 主系统「核货完毕」事实镜像(2026-10-11,设计文档 `20261011-免入库核货完毕标记.md`)。
|
||||
*
|
||||
* 钉住四件事:
|
||||
* ① 事实只来自**拉取**(事件通道对"等量核货"静默)——lookup 是唯一可靠通道;
|
||||
* ② 落库只覆盖 payload 的 5 个事实键,**不得**顺手改其它键(台账 payload 是共享快照);
|
||||
* ③ 判定口径是 `actualQty != null` 且**仅免入库行**(送仓行已有"入库完成"标签);
|
||||
* ④ GET 路由**不调外部**(主系统抖动不得拖垮详情),刷新是独立 POST 且失败不 500。
|
||||
*/
|
||||
const service = readFileSync(
|
||||
path.join(__dirname, '../src/services/mainSystemActualFacts.ts'),
|
||||
'utf8'
|
||||
);
|
||||
const routes = readFileSync(
|
||||
path.join(__dirname, '../src/modules/workflow/routes/orderRoutes.ts'),
|
||||
'utf8'
|
||||
);
|
||||
const importLoop = readFileSync(path.join(__dirname, '../src/services/mainSystemOrderImport.ts'), 'utf8');
|
||||
|
||||
describe('核货事实:通道与落库', () => {
|
||||
it('用 lookup 拉(不受 active/archived 视图影响),不靠事件', () => {
|
||||
expect(service).toMatch(/lookupMainSystemPreparationStates/);
|
||||
// 代码里**不得**出现事件订阅/收件箱依赖(`actual_qty_request` 只允许出现在解释性注释里)
|
||||
const codeOnly = service
|
||||
.split('\n')
|
||||
.filter((line) => !line.trim().startsWith('*') && !line.trim().startsWith('//') && !line.trim().startsWith('/*'))
|
||||
.join('\n');
|
||||
expect(codeOnly).not.toMatch(/actual_qty_request/);
|
||||
});
|
||||
|
||||
it('只覆盖 payload 的 5 个事实键(payload || jsonb_build_object)', () => {
|
||||
expect(service).toMatch(/payload \|\| jsonb_build_object/);
|
||||
for (const key of ['actualQty', 'actualQtyAt', 'qtyDiff', 'isInbounded', 'inboundAt']) {
|
||||
expect(service, `缺少事实键 ${key}`).toContain(`'${key}'`);
|
||||
}
|
||||
// 不得整包替换 payload(那是导入的职责,会把 skipInbound 等事实抹掉)
|
||||
expect(service).not.toMatch(/SET payload = \$/);
|
||||
});
|
||||
|
||||
it('判定用 actualQty != null(不用 actualQtyAt:免入库行实测恒为 null)', () => {
|
||||
expect(service).toMatch(/checked: actualQty !== null/);
|
||||
expect(service).toMatch(/不用 `actualQtyAt`/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('核货事实:路由与兜底', () => {
|
||||
it('GET 路由只读库,POST 路由才拉取,两者都要权限', () => {
|
||||
const getIdx = routes.indexOf("'/orders/:orderCode/main-system-prep-facts'");
|
||||
const postIdx = routes.indexOf("'/orders/:orderCode/main-system-prep-facts/refresh'");
|
||||
expect(getIdx).toBeGreaterThan(-1);
|
||||
expect(postIdx).toBeGreaterThan(-1);
|
||||
const getBlock = routes.slice(getIdx, getIdx + 900);
|
||||
const postBlock = routes.slice(postIdx, postIdx + 1100);
|
||||
expect(getBlock).toMatch(/listOrderActualFacts/);
|
||||
expect(getBlock).not.toMatch(/refreshOrderActualFacts/);
|
||||
expect(postBlock).toMatch(/refreshOrderActualFacts/);
|
||||
expect(getBlock).toMatch(/requireWorkflowPermission/);
|
||||
expect(postBlock).toMatch(/requireWorkflowPermission/);
|
||||
});
|
||||
|
||||
it('刷新失败不抛(详情必须照常展示库内已有事实)', () => {
|
||||
const idx = service.indexOf('export async function refreshOrderActualFacts');
|
||||
const fn = service.slice(idx, idx + 900);
|
||||
expect(fn).toMatch(/catch \(error: unknown\)/);
|
||||
expect(fn).toMatch(/refreshed = false|reason =/);
|
||||
});
|
||||
|
||||
it('定时对账里挂了在飞单兜底(等量核货没人打开详情也能补上)', () => {
|
||||
expect(importLoop).toMatch(/refreshInFlightActualFactsForBranch/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,370 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||||
|
||||
/**
|
||||
* 主系统「同一订单后来追加分配」的行级增量导入(2026-10-10 用户报障)。
|
||||
*
|
||||
* 缺陷现场:主系统把某个商品**重新指派**给同一个供应商(同一张主系统订单多出一行),
|
||||
* 子系统里看不到 —— 因为导入是**整单幂等**(`imported.has(orderCode)` 就整单跳过),
|
||||
* 后来追加的行被静默丢掉。
|
||||
*
|
||||
* 这里钉住五件事:
|
||||
* ① 已导入订单 + 台账里没有的新行 ⇒ 走**改明细**追加(不是再建一张单);
|
||||
* ② 追加时既有行必须原样回传(尤其 `cost_price`=unit_cost,漏传会把既有行成本清成 0),
|
||||
* 且 `allowUnpriced: true`(主系统没定价 ⇒ 售价 0 是正常口径,不能被既有零价行挡住);
|
||||
* ③ 订单已进履约(≥40)⇒ **不自动改单**,新行挂 `suspended` 交人工;
|
||||
* ④ 没有新行 ⇒ 不调任何写路径(重复对账幂等,绝不重复追加);
|
||||
* (2026-10-10 起合并键是**(分公司, 配送日)**:日级占坑抢不到、且该日已有单号 ⇒ 走本文件的追加路径)
|
||||
* ⑤ 行级台账 INSERT 的占位符编号必须与参数个数一致
|
||||
* (修复前是 `$13` 却只传 12 个参数 → 线上**每一次**台账写入都抛
|
||||
* `bind message supplies 12 parameters, but prepared statement "" requires 13`,
|
||||
* 而调用点 catch 成"不影响建单",于是行级台账从来没写进去过)。
|
||||
*/
|
||||
|
||||
const query = vi.hoisted(() => vi.fn());
|
||||
const syncItems = vi.hoisted(() => vi.fn());
|
||||
const enrich = vi.hoisted(() => vi.fn());
|
||||
const withTenant = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock('../src/db', () => ({
|
||||
pool: { query: (...args: unknown[]) => query(...args), connect: vi.fn() },
|
||||
getRawPoolQuery: () => query,
|
||||
}));
|
||||
vi.mock('../src/services/orderManageItemsService', () => ({
|
||||
syncOrderManageItems: (...args: unknown[]) => syncItems(...args),
|
||||
}));
|
||||
vi.mock('../src/services/customerOrderSubmitService', () => ({
|
||||
submitMobileCustomerOrder: vi.fn(),
|
||||
}));
|
||||
vi.mock('../src/services/customerOrderEnrichService', () => ({
|
||||
enrichCustomerOrderItems: (...args: unknown[]) => enrich(...args),
|
||||
}));
|
||||
vi.mock('../src/services/tenantSchemaService', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../src/services/tenantSchemaService')>();
|
||||
return {
|
||||
...actual,
|
||||
runWithTenantDataAccess: (...args: unknown[]) => withTenant(...args),
|
||||
resolveActiveTenantSchema: async () => 'tenant_br001',
|
||||
};
|
||||
});
|
||||
|
||||
import { importMainSystemGroups } from '../src/services/mainSystemOrderImport';
|
||||
import { recordImportedPrepItems } from '../src/services/mainSystemPrepLedger';
|
||||
import type { MainOrderGroup } from '../src/services/mainSystemPreparations';
|
||||
|
||||
const OUR_ORDER = 'ORD_API_20261010_SUP001_0001';
|
||||
const MAIN_ORDER = 'ORD_WEB_20261010_BR002_0007';
|
||||
const EXISTING_PREP_ID = '11111111-1111-4111-8111-111111111111';
|
||||
const NEW_PREP_ID = '22222222-2222-4222-8222-222222222222';
|
||||
const NEW_ITEM_ID = '33333333-3333-4333-8333-333333333333';
|
||||
|
||||
function prepRow(over: Record<string, unknown>) {
|
||||
return {
|
||||
orderCode: MAIN_ORDER,
|
||||
skuCode: null,
|
||||
displayName: null,
|
||||
prepareQty: 1,
|
||||
unit: '斤',
|
||||
orderQty: null,
|
||||
orderUnit: null,
|
||||
purchasePrice: 0,
|
||||
suggestedPrice: null,
|
||||
prepareStatus: 10,
|
||||
deliveryDate: '2026-10-10',
|
||||
taskDay: '2026-10-10',
|
||||
isStockout: false,
|
||||
processingMethod: null,
|
||||
returnCode: null,
|
||||
returnReason: null,
|
||||
requiresQualityReport: false,
|
||||
orderItemRemark: null,
|
||||
skipInbound: false,
|
||||
isDirectDelivery: false,
|
||||
...over,
|
||||
} as never;
|
||||
}
|
||||
|
||||
/** 既有行(桔皮,售价 0 —— 正是"零价行不能挡住追加"的现场)+主系统新分配的行(花生) */
|
||||
const GROUP: MainOrderGroup = {
|
||||
orderCode: MAIN_ORDER,
|
||||
deliveryDate: '2026-10-10',
|
||||
taskDay: '2026-10-10',
|
||||
rows: [
|
||||
prepRow({ id: EXISTING_PREP_ID, itemName: '桔皮', prepareQty: 0.5, unit: '斤', purchasePrice: 0 }),
|
||||
prepRow({ id: NEW_PREP_ID, itemName: '花生', prepareQty: 2, unit: '包', purchasePrice: 6 }),
|
||||
],
|
||||
};
|
||||
|
||||
const LEDGER_ROW = {
|
||||
id: 'led-1',
|
||||
branch_code: 'SUP001',
|
||||
main_order_code: MAIN_ORDER,
|
||||
prep_id: EXISTING_PREP_ID,
|
||||
our_order_code: OUR_ORDER,
|
||||
our_order_item_id: 'existing-item-1',
|
||||
main_supplier_code: 'SUP001',
|
||||
main_sku_code: null,
|
||||
item_name: '桔皮',
|
||||
last_prepare_qty: '0.5',
|
||||
last_prepare_status: 10,
|
||||
last_return_code: null,
|
||||
disposition: 'imported',
|
||||
disposition_reason: null,
|
||||
writeback_status: null,
|
||||
last_seen_active_at: null,
|
||||
payload: null,
|
||||
};
|
||||
|
||||
/** 追加前读到的订单头/明细,与追加后台账重读的明细 */
|
||||
const EXISTING_ITEM_ROW = {
|
||||
id: 'existing-item-1',
|
||||
item_name: '桔皮',
|
||||
sku_code: 'SKU_EXISTING',
|
||||
quantity: '10.00',
|
||||
unit: '斤',
|
||||
price: '0.00',
|
||||
amount: '0.00',
|
||||
cost_price: '3.5000',
|
||||
supplier_code: 'INTERNAL',
|
||||
processing_method: '原材料',
|
||||
processing_owner: null,
|
||||
category_code: 'CAT_1',
|
||||
category_name: '蔬菜',
|
||||
sort_order: 1,
|
||||
remark: null,
|
||||
is_extra_dish: false,
|
||||
quality_report_id: null,
|
||||
};
|
||||
|
||||
function sqlOf(call: unknown[]): string {
|
||||
return String(call[0] || '');
|
||||
}
|
||||
|
||||
/** 租户连接:按 SQL 内容分派(追加路径只读这几处) */
|
||||
function tenantClient(orderStatus: number) {
|
||||
return {
|
||||
query: async (...args: unknown[]) => {
|
||||
const sql = sqlOf(args);
|
||||
if (sql.includes('SELECT order_status FROM orders')) {
|
||||
return { rowCount: 1, rows: [{ order_status: orderStatus }] };
|
||||
}
|
||||
if (sql.includes('SELECT id, item_name, sku_code, quantity, unit, price, amount,')) {
|
||||
return { rowCount: 1, rows: [EXISTING_ITEM_ROW] };
|
||||
}
|
||||
if (sql.includes('SELECT id::text AS id, item_name')) {
|
||||
return {
|
||||
rowCount: 2,
|
||||
rows: [
|
||||
{ id: 'existing-item-1', item_name: '桔皮' },
|
||||
{ id: NEW_ITEM_ID, item_name: '花生' },
|
||||
],
|
||||
};
|
||||
}
|
||||
return { rowCount: 0, rows: [] };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('已导入订单的新分配行 → 行级增量追加', () => {
|
||||
beforeEach(() => {
|
||||
query.mockReset();
|
||||
syncItems.mockReset();
|
||||
enrich.mockReset();
|
||||
withTenant.mockReset();
|
||||
enrich.mockImplementation(async (_c: string, items: unknown[]) => items);
|
||||
syncItems.mockResolvedValue({ total_amount: 12, total_weight: 10, items: [] });
|
||||
withTenant.mockImplementation(async (_b: string, fn: (c: unknown) => Promise<unknown>) =>
|
||||
fn(tenantClient(30))
|
||||
);
|
||||
query.mockImplementation(async (...args: unknown[]) => {
|
||||
const sql = sqlOf(args);
|
||||
// 日级占坑:抢不到(该配送日已建过单)⇒ 读回已有单号 → 走行级增量追加
|
||||
if (sql.includes('INSERT INTO public.main_system_daily_order_imports')) {
|
||||
return { rowCount: 0, rows: [] };
|
||||
}
|
||||
if (sql.includes('SELECT our_order_code FROM public.main_system_daily_order_imports')) {
|
||||
return { rowCount: 1, rows: [{ our_order_code: OUR_ORDER }] };
|
||||
}
|
||||
if (sql.includes('FROM public.main_system_order_imports')) {
|
||||
return { rowCount: 1, rows: [{ main_order_code: MAIN_ORDER, our_order_code: OUR_ORDER }] };
|
||||
}
|
||||
if (sql.includes('FROM public.main_system_order_import_items')) {
|
||||
return { rowCount: 1, rows: [LEDGER_ROW] };
|
||||
}
|
||||
// 台账 INSERT:模拟 pg 对占位符个数的校验(多一个 $n 少一个参数会抛)
|
||||
if (sql.includes('INSERT INTO public.main_system_order_import_items')) {
|
||||
const params = (args[1] as unknown[]) || [];
|
||||
const referenced = [...sql.matchAll(/\$(\d+)/g)].map((m) => Number(m[1]));
|
||||
const max = referenced.length ? Math.max(...referenced) : 0;
|
||||
if (max > params.length) {
|
||||
throw new Error(
|
||||
`bind message supplies ${params.length} parameters, but prepared statement "" requires ${max}`
|
||||
);
|
||||
}
|
||||
return { rowCount: 1, rows: [] };
|
||||
}
|
||||
// 其余(含租户 schema 注册表探测):rowCount 0 ⇒ 不借会话连接,直接进租户上下文
|
||||
return { rowCount: 0, rows: [] };
|
||||
});
|
||||
});
|
||||
|
||||
it('新行走改明细追加:既有行原样回传 + 新行带 create_product + 放行零价', async () => {
|
||||
const outcome = await importMainSystemGroups({
|
||||
supplierCode: 'SUP001',
|
||||
branchCode: 'SUP001',
|
||||
userId: null,
|
||||
groups: [GROUP],
|
||||
});
|
||||
|
||||
expect(outcome.appended).toBe(1);
|
||||
expect(outcome.created).toBe(0);
|
||||
expect(syncItems).toHaveBeenCalledTimes(1);
|
||||
|
||||
const params = syncItems.mock.calls[0][0] as {
|
||||
orderCode: string;
|
||||
items: Array<Record<string, unknown>>;
|
||||
allowUnpriced?: boolean;
|
||||
provisionPurchaserOrderSkus?: boolean;
|
||||
};
|
||||
expect(params.orderCode).toBe(OUR_ORDER);
|
||||
expect(params.allowUnpriced).toBe(true);
|
||||
expect(params.provisionPurchaserOrderSkus).toBe(true);
|
||||
|
||||
const existing = params.items.find((it) => it.id === 'existing-item-1')!;
|
||||
// 既有行必须原样回传:unit_cost 由 cost_price 推导,漏传会把它清成 0
|
||||
expect(existing.cost_price).toBe('3.5000');
|
||||
expect(existing.quantity).toBe('10.00');
|
||||
expect(existing.supplier_code).toBe('INTERNAL');
|
||||
|
||||
const appended = params.items.find((it) => it.item_name === '花生')!;
|
||||
expect(appended).toBeTruthy();
|
||||
expect(Number(appended.price)).toBe(6);
|
||||
expect(appended.create_product).toBe(true);
|
||||
// 归不上类也要有分类(否则录单链路会以"商品未选择分类"400)
|
||||
expect(String(appended.category_code || '')).not.toBe('');
|
||||
});
|
||||
|
||||
it('追加成功后把新行的行级对照写进台账(含 our_order_item_id)', async () => {
|
||||
await importMainSystemGroups({ supplierCode: 'SUP001', branchCode: 'SUP001', userId: null, groups: [GROUP] });
|
||||
|
||||
const inserts = query.mock.calls.filter(
|
||||
(c) =>
|
||||
sqlOf(c).includes('INSERT INTO public.main_system_order_import_items') &&
|
||||
String(sqlOf(c)).includes('disposition')
|
||||
);
|
||||
expect(inserts.length).toBeGreaterThan(0);
|
||||
// 花生那行的对照必须指向新追加的订单行(整单行全量写入,逐行找它)
|
||||
const peanut = inserts.map((c) => c[1] as unknown[]).find((params) => params[2] === NEW_PREP_ID);
|
||||
expect(peanut).toBeTruthy();
|
||||
expect(peanut![4]).toBe(NEW_ITEM_ID);
|
||||
expect(peanut![11]).toBe('imported');
|
||||
// 桔皮那行顺带把此前为空的对照补上
|
||||
const orange = inserts.map((c) => c[1] as unknown[]).find((params) => params[2] === EXISTING_PREP_ID);
|
||||
expect(orange![4]).toBe('existing-item-1');
|
||||
});
|
||||
|
||||
it('订单已进履约(≥40)→ 不改单,新行挂待处理', async () => {
|
||||
withTenant.mockImplementation(async (_b: string, fn: (c: unknown) => Promise<unknown>) =>
|
||||
fn(tenantClient(45))
|
||||
);
|
||||
|
||||
const outcome = await importMainSystemGroups({
|
||||
supplierCode: 'SUP001',
|
||||
branchCode: 'SUP001',
|
||||
userId: null,
|
||||
groups: [GROUP],
|
||||
});
|
||||
|
||||
expect(syncItems).not.toHaveBeenCalled();
|
||||
expect(outcome.skipped).toBe(1);
|
||||
expect(String(outcome.results[0].message)).toContain('履约');
|
||||
|
||||
const suspend = query.mock.calls.find((c) => sqlOf(c).includes('SET disposition = $3'));
|
||||
expect(suspend).toBeTruthy();
|
||||
expect((suspend![1] as unknown[])[2]).toBe('suspended');
|
||||
});
|
||||
|
||||
it('台账里已有这两行 → 没有新行,不调用任何写路径(重复对账幂等)', async () => {
|
||||
query.mockImplementation(async (...args: unknown[]) => {
|
||||
const sql = sqlOf(args);
|
||||
if (sql.includes('INSERT INTO public.main_system_daily_order_imports')) {
|
||||
return { rowCount: 0, rows: [] };
|
||||
}
|
||||
if (sql.includes('SELECT our_order_code FROM public.main_system_daily_order_imports')) {
|
||||
return { rowCount: 1, rows: [{ our_order_code: OUR_ORDER }] };
|
||||
}
|
||||
if (sql.includes('FROM public.main_system_order_imports')) {
|
||||
return { rowCount: 1, rows: [{ main_order_code: MAIN_ORDER, our_order_code: OUR_ORDER }] };
|
||||
}
|
||||
if (sql.includes('FROM public.main_system_order_import_items')) {
|
||||
return {
|
||||
rowCount: 2,
|
||||
rows: [
|
||||
LEDGER_ROW,
|
||||
{ ...LEDGER_ROW, id: 'led-2', prep_id: NEW_PREP_ID, item_name: '花生', our_order_item_id: 'item-2' },
|
||||
],
|
||||
};
|
||||
}
|
||||
return { rowCount: 0, rows: [] };
|
||||
});
|
||||
|
||||
const outcome = await importMainSystemGroups({
|
||||
supplierCode: 'SUP001',
|
||||
branchCode: 'SUP001',
|
||||
userId: null,
|
||||
groups: [GROUP],
|
||||
});
|
||||
|
||||
expect(syncItems).not.toHaveBeenCalled();
|
||||
expect(outcome.appended).toBe(0);
|
||||
expect(outcome.skipped).toBe(1);
|
||||
expect(String(outcome.results[0].message)).toContain('没有新分配的行');
|
||||
});
|
||||
|
||||
it('行级台账写入:列清单与占位符必须逐位对应(修复前 disposition→$13 与 payload→$12 是错位的)', async () => {
|
||||
// 缺货行不建明细,但同样要落台账(处置 skipped_stockout),且不得占用名字匹配位
|
||||
await recordImportedPrepItems({
|
||||
branchCode: 'SUP001',
|
||||
mainOrderCode: MAIN_ORDER,
|
||||
supplierCode: 'SUP001',
|
||||
ourOrderCode: OUR_ORDER,
|
||||
prepRows: [
|
||||
{ id: NEW_PREP_ID, itemName: '花生', prepareQty: 2, prepareStatus: 10, isStockout: true },
|
||||
],
|
||||
ourItems: [{ id: NEW_ITEM_ID, item_name: '花生' }],
|
||||
});
|
||||
|
||||
const insert = query.mock.calls.find((c) =>
|
||||
sqlOf(c).includes('INSERT INTO public.main_system_order_import_items')
|
||||
)!;
|
||||
const sql = sqlOf(insert);
|
||||
const params = (insert[1] as unknown[]) || [];
|
||||
|
||||
// ① 占位符编号不得超出参数个数($13 配 12 个参数 ⇒ Postgres 直接报
|
||||
// `bind message supplies 12 parameters … requires 13`,而调用点只当"不影响建单"吞掉)
|
||||
const referenced = [...sql.matchAll(/\$(\d+)/g)].map((m) => Number(m[1]));
|
||||
expect(Math.max(...referenced)).toBeLessThanOrEqual(params.length);
|
||||
|
||||
// ② 更强的判据:列清单里 `disposition` 同位的占位符,取到的参数必须真是一个处置值。
|
||||
// 修复前 SQL 是 `… last_return_code, disposition, payload … VALUES (…,$11,$13,$12::jsonb)`
|
||||
// ⇒ 同位的 $13 取到的是 JSON 快照对象(写进 varchar(20) 必然失败/错位)。
|
||||
const colStart = sql.indexOf('(');
|
||||
const cols = sql.slice(colStart + 1, sql.indexOf(')', colStart)).split(',').map((c) => c.trim());
|
||||
const valStart = sql.indexOf('VALUES (') + 'VALUES ('.length;
|
||||
const values = sql
|
||||
.slice(valStart, sql.indexOf(')', valStart))
|
||||
.split(',')
|
||||
.map((v) => v.trim());
|
||||
const dispositionAt = cols.indexOf('disposition');
|
||||
expect(dispositionAt).toBeGreaterThan(-1);
|
||||
const payloadAt = cols.indexOf('payload');
|
||||
const paramOf = (position: number) => params[Number(values[position].replace(/[^0-9]/g, '')) - 1];
|
||||
|
||||
expect(['imported', 'skipped_stockout']).toContain(paramOf(dispositionAt));
|
||||
expect(typeof paramOf(payloadAt)).toBe('string');
|
||||
expect(() => JSON.parse(String(paramOf(payloadAt)))).not.toThrow();
|
||||
|
||||
// ③ 缺货行:处置写 skipped_stockout,且**不给订单行对照**(本系统没建这行)
|
||||
expect(paramOf(dispositionAt)).toBe('skipped_stockout');
|
||||
expect(paramOf(cols.indexOf('our_order_item_id'))).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
/**
|
||||
* 客户口径(开发者 2026-10-11 定稿):**主系统的分公司名字就是客户名字**。
|
||||
* · 一个主系统下单分公司 = 我方一个客户;客户编码 `MAIN_<分公司编码>`;客户名 = 分公司名;
|
||||
* · 分公司名在主系统为空 ⇒ 「主系统分公司 <编码>」兜底(开发者批准);
|
||||
* · 名字**没被占用就不加编号**(占用才 `-2`/`-3`);
|
||||
* · 拿不到分公司编码(webhook 剥字段)⇒ 退回原占位客户,行为与本改动前一致;
|
||||
* · 存量订单按台账/主系统单号里的 `_BRxxx_` 段改挂(开发者决策 ③「需要」)。
|
||||
*/
|
||||
const importSrc = readFileSync(
|
||||
new URL('../src/services/mainSystemOrderImport.ts', import.meta.url),
|
||||
'utf8'
|
||||
);
|
||||
const ledgerSrc = readFileSync(new URL('../src/services/mainSystemPrepLedger.ts', import.meta.url), 'utf8');
|
||||
const script = readFileSync(
|
||||
new URL('../scripts/reattribute-main-system-branch-customers.ts', import.meta.url),
|
||||
'utf8'
|
||||
);
|
||||
|
||||
describe('客户 = 主系统分公司,客户名 = 分公司名', () => {
|
||||
it('客户编码用 MAIN_<分公司编码>,名字用分公司名,空名走兜底', () => {
|
||||
expect(importSrc).toContain('`${IMPORT_CUSTOMER_PREFIX}${mainBranchCode}`');
|
||||
expect(importSrc).toContain('function fallbackBranchName(mainBranchCode: string)');
|
||||
expect(importSrc).toContain('主系统分公司 ${mainBranchCode}');
|
||||
expect(importSrc).toMatch(/mainBranchName \|\| fallbackBranchName\(mainBranchCode\)/);
|
||||
});
|
||||
|
||||
it('名字只在被别的客户占用时才加编号', () => {
|
||||
const start = importSrc.indexOf('async function dedupeCustomerName');
|
||||
const fn = importSrc.slice(start, start + 1200);
|
||||
expect(fn).toContain('WHERE company_name = $1 AND customer_code <> $2');
|
||||
expect(fn).toContain('if (!taken.rowCount) return baseName;');
|
||||
expect(fn).toContain('${baseName}-${i}');
|
||||
});
|
||||
|
||||
it('拿不到分公司编码时退回占位客户(webhook 剥字段的历史兼容)', () => {
|
||||
expect(importSrc).toContain('fallbackPlaceholderName');
|
||||
expect(importSrc).toMatch(/hasMainBranch\s*\?\s*`\$\{IMPORT_CUSTOMER_PREFIX\}\$\{mainBranchCode\}`/);
|
||||
});
|
||||
|
||||
it('归属取当日行里出现最多的分公司(真混合时告警,不静默丢)', () => {
|
||||
const start = importSrc.indexOf('function pickDayMainBranch');
|
||||
const fn = importSrc.slice(start, start + 1400);
|
||||
expect(fn).toContain('counter');
|
||||
expect(fn).toContain('多个下单分公司');
|
||||
expect(importSrc).toContain('pickDayMainBranch(pending.flatMap((entry) => entry.rows))');
|
||||
});
|
||||
|
||||
it('台账落 main_branch_code / main_branch_name(非空才覆盖)', () => {
|
||||
expect(ledgerSrc).toContain('main_branch_code, main_branch_name');
|
||||
expect(ledgerSrc).toContain(
|
||||
'main_branch_code = COALESCE(EXCLUDED.main_branch_code, public.main_system_order_import_items.main_branch_code)'
|
||||
);
|
||||
expect(ledgerSrc).toContain('row.branchCode ? String(row.branchCode).trim().toUpperCase() : null');
|
||||
});
|
||||
});
|
||||
|
||||
describe('存量归属改挂(决策 ③)', () => {
|
||||
it('导出可复用函数 + 一次性脚本,归属依据逐级回退且不瞎猜', () => {
|
||||
expect(importSrc).toContain('export async function reattributeMainSystemOrdersToBranchCustomers');
|
||||
expect(importSrc).toContain('BR[0-9A-Z]+');
|
||||
const start = importSrc.indexOf('export async function reattributeMainSystemOrdersToBranchCustomers');
|
||||
const fn = importSrc.slice(start, start + 3800);
|
||||
expect(fn).toContain('if (!mainBranchCode) continue;');
|
||||
expect(fn).toContain('customer_code IS DISTINCT FROM $2');
|
||||
expect(fn).toContain('SET status = 40');
|
||||
expect(fn).toContain('SELECT count(*)::text AS count FROM orders WHERE customer_code = $1');
|
||||
expect(script).toContain('reattributeMainSystemOrdersToBranchCustomers');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,91 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
/**
|
||||
* 主系统对接模块的**两条契约**(开发者 2026-10-11 要求):
|
||||
* ① **域名单一来源**:所有端点 URL 都由 `MAIN_SYSTEM_BASE_URL` 派生,
|
||||
* 换域名/换路径只改 env(或 `MAIN_SYSTEM_*_PATH`),业务代码里没有第二份地址;
|
||||
* ② **默认关**:未设 `MAIN_SYSTEM_PRICE_QTY_ENABLED=1` 时,跨系统改价/改量整条链路关闭
|
||||
* ⇒ 正常下单/改明细路径零影响(与改造前逐字节一致)。
|
||||
*/
|
||||
|
||||
const saved = {
|
||||
baseUrl: process.env.MAIN_SYSTEM_BASE_URL,
|
||||
priceQty: process.env.MAIN_SYSTEM_PRICE_QTY_ENABLED,
|
||||
requestPath: process.env.MAIN_SYSTEM_PRICE_QTY_REQUEST_PATH,
|
||||
};
|
||||
|
||||
function restoreEnv() {
|
||||
for (const [key, value] of Object.entries({
|
||||
MAIN_SYSTEM_BASE_URL: saved.baseUrl,
|
||||
MAIN_SYSTEM_PRICE_QTY_ENABLED: saved.priceQty,
|
||||
MAIN_SYSTEM_PRICE_QTY_REQUEST_PATH: saved.requestPath,
|
||||
})) {
|
||||
if (value === undefined) delete process.env[key];
|
||||
else process.env[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
restoreEnv();
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
describe('主系统域名 / 端点:单一来源', () => {
|
||||
it('改 MAIN_SYSTEM_BASE_URL 即改所有端点(含尾斜杠归一)', async () => {
|
||||
process.env.MAIN_SYSTEM_BASE_URL = 'https://main.example.com/erp/';
|
||||
vi.resetModules();
|
||||
const { buildMainSystemUrl } = await import('../src/services/mainSystem/endpoints');
|
||||
expect(buildMainSystemUrl('preparations')).toBe('https://main.example.com/erp/api/supplier/preparations');
|
||||
expect(buildMainSystemUrl('preparationsStatus')).toBe(
|
||||
'https://main.example.com/erp/api/supplier/preparations/status'
|
||||
);
|
||||
expect(buildMainSystemUrl('priceQtyRequest')).toBe(
|
||||
'https://main.example.com/erp/api/supplier/preparations/price-qty-request'
|
||||
);
|
||||
expect(buildMainSystemUrl('preparations', { view: 'price_amend' })).toBe(
|
||||
'https://main.example.com/erp/api/supplier/preparations?view=price_amend'
|
||||
);
|
||||
});
|
||||
|
||||
it('端点路径可被 env 覆盖(主系统改路径时不用改代码)', async () => {
|
||||
process.env.MAIN_SYSTEM_BASE_URL = 'http://127.0.0.1:3001';
|
||||
process.env.MAIN_SYSTEM_PRICE_QTY_REQUEST_PATH = '/api/supplier/v2/price-qty-request';
|
||||
vi.resetModules();
|
||||
const { buildMainSystemUrl } = await import('../src/services/mainSystem/endpoints');
|
||||
expect(buildMainSystemUrl('priceQtyRequest')).toBe(
|
||||
'http://127.0.0.1:3001/api/supplier/v2/price-qty-request'
|
||||
);
|
||||
});
|
||||
|
||||
it('域名为空时抛错而不是拼出奇怪地址', async () => {
|
||||
// 注意:`src/config.ts` 在 import 时会 `loadEnv()` 回读 `server/.env`(且不覆盖已存在的 env),
|
||||
// 所以这里用**空串**表达"未配置",而不是 delete(delete 会被回读补回来)。
|
||||
process.env.MAIN_SYSTEM_BASE_URL = '';
|
||||
vi.resetModules();
|
||||
const { buildMainSystemUrl } = await import('../src/services/mainSystem/endpoints');
|
||||
expect(() => buildMainSystemUrl('preparations')).toThrow(/MAIN_SYSTEM_BASE_URL/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('跨系统改价/改量:开关判定(`=1` 才开,其余一律关)', () => {
|
||||
// ⚠️ 不能用 delete 表达"未配置":`src/config.ts` 在 import 时会 `loadEnv()` 回读 `server/.env`
|
||||
// (且不覆盖已存在的 env)⇒ delete 会被回读补回来。用**空串/其它值**表达"关",
|
||||
// 这样本地 `.env` 里联调把开关置 1 时,本用例仍然稳定。
|
||||
it('空串 / 0 / true 都当关;只有 =1 才算开', async () => {
|
||||
for (const value of ['', '0', 'true', 'yes']) {
|
||||
process.env.MAIN_SYSTEM_PRICE_QTY_ENABLED = value;
|
||||
vi.resetModules();
|
||||
const config = await import('../src/services/mainSystem/config');
|
||||
expect(config.isPriceQtyRequestEnabled(), `值 "${value}" 应为关`).toBe(false);
|
||||
}
|
||||
|
||||
process.env.MAIN_SYSTEM_PRICE_QTY_ENABLED = '1';
|
||||
vi.resetModules();
|
||||
const on = await import('../src/services/mainSystem/config');
|
||||
expect(on.isPriceQtyRequestEnabled()).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,517 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||||
|
||||
/**
|
||||
* 主系统分配单的三条新口径(开发者 2026-10-10):
|
||||
* ① 按**配送日**合并:同一配送日的多张主系统单 ⇒ 一张本系统订单;
|
||||
* ② 明细备注带**主系统单号**(主系统暂不回传客户,先用单号区分);
|
||||
* ③ 「缺货」= 报主系统 `status=40`(转自采)⇒ 成功后才收口我方(明细标缺货 + 未完成采购作废),
|
||||
* 主系统不可用时**一律不动本地**(否则会出现"我方已剔除、主系统还在等我们供货")。
|
||||
*/
|
||||
|
||||
const query = vi.hoisted(() => vi.fn());
|
||||
const submit = vi.hoisted(() => vi.fn());
|
||||
const enrich = vi.hoisted(() => vi.fn());
|
||||
const withTenant = vi.hoisted(() => vi.fn());
|
||||
const writeback = vi.hoisted(() => vi.fn());
|
||||
const lookup = vi.hoisted(() => vi.fn());
|
||||
const removeItem = vi.hoisted(() => vi.fn());
|
||||
const hasInbound = vi.hoisted(() => vi.fn());
|
||||
const hasPrepDone = vi.hoisted(() => vi.fn());
|
||||
const hasPurchaseDone = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock('../src/db', () => ({
|
||||
pool: { query: (...args: unknown[]) => query(...args), connect: vi.fn() },
|
||||
getRawPoolQuery: () => query,
|
||||
}));
|
||||
vi.mock('../src/services/customerOrderSubmitService', () => ({
|
||||
submitMobileCustomerOrder: (...args: unknown[]) => submit(...args),
|
||||
}));
|
||||
vi.mock('../src/services/customerOrderEnrichService', () => ({
|
||||
enrichCustomerOrderItems: (...args: unknown[]) => enrich(...args),
|
||||
}));
|
||||
vi.mock('../src/services/tenantSchemaService', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../src/services/tenantSchemaService')>();
|
||||
return {
|
||||
...actual,
|
||||
runWithTenantDataAccess: (...args: unknown[]) => withTenant(...args),
|
||||
resolveActiveTenantSchema: async () => 'tenant_br001',
|
||||
};
|
||||
});
|
||||
vi.mock('../src/services/orderManageItemsService', () => ({
|
||||
removeOrderItemForMainSystemReturn: (...args: unknown[]) => removeItem(...args),
|
||||
}));
|
||||
vi.mock('../src/services/orderItemReturnService', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../src/services/orderItemReturnService')>();
|
||||
return {
|
||||
...actual,
|
||||
orderItemHasInspectionInbound: (...args: unknown[]) => hasInbound(...args),
|
||||
orderItemHasCompletedPreparation: (...args: unknown[]) => hasPrepDone(...args),
|
||||
orderItemHasCompletedPurchase: (...args: unknown[]) => hasPurchaseDone(...args),
|
||||
};
|
||||
});
|
||||
vi.mock('../src/services/mainSystemPreparations', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../src/services/mainSystemPreparations')>();
|
||||
return {
|
||||
...actual,
|
||||
writebackMainSystemPreparationStatus: (...args: unknown[]) => writeback(...args),
|
||||
lookupMainSystemPreparationStates: (...args: unknown[]) => lookup(...args),
|
||||
};
|
||||
});
|
||||
|
||||
import { bucketGroupsByDeliveryDate, isPreparationNoLongerOurs } from '../src/services/mainSystemOrderImport';
|
||||
import { reportMainSystemStockout } from '../src/services/mainSystemStockout';
|
||||
import type { MainOrderGroup } from '../src/services/mainSystemPreparations';
|
||||
|
||||
function row(over: Record<string, unknown>) {
|
||||
return {
|
||||
orderCode: 'MO-1',
|
||||
skuCode: null,
|
||||
displayName: null,
|
||||
prepareQty: 1,
|
||||
unit: '斤',
|
||||
orderQty: null,
|
||||
orderUnit: null,
|
||||
purchasePrice: 0,
|
||||
suggestedPrice: null,
|
||||
prepareStatus: 10,
|
||||
deliveryDate: '2026-10-09',
|
||||
taskDay: '2026-10-09',
|
||||
isStockout: false,
|
||||
processingMethod: null,
|
||||
returnCode: null,
|
||||
returnReason: null,
|
||||
requiresQualityReport: false,
|
||||
orderItemRemark: null,
|
||||
skipInbound: false,
|
||||
isDirectDelivery: false,
|
||||
...over,
|
||||
} as never;
|
||||
}
|
||||
|
||||
function group(orderCode: string, deliveryDate: string | null, names: string[]): MainOrderGroup {
|
||||
return {
|
||||
orderCode,
|
||||
deliveryDate,
|
||||
taskDay: deliveryDate,
|
||||
rows: names.map((itemName, index) =>
|
||||
row({ id: `${orderCode}-${index}`, orderCode, itemName, deliveryDate, prepareQty: index + 1 })
|
||||
),
|
||||
} as MainOrderGroup;
|
||||
}
|
||||
|
||||
function sqlOf(call: unknown[]): string {
|
||||
return String(call[0] || '');
|
||||
}
|
||||
|
||||
describe('按配送日合并', () => {
|
||||
it('同一配送日的多张主系统单归到一个桶,跨配送日分开', () => {
|
||||
const buckets = bucketGroupsByDeliveryDate([
|
||||
group('MO-A', '2026-10-09', ['土豆']),
|
||||
group('MO-B', '2026-10-09', ['白菜', '黄瓜']),
|
||||
group('MO-C', '2026-10-10', ['番茄']),
|
||||
]);
|
||||
expect(buckets.map((b) => b.deliveryDate)).toEqual(['2026-10-09', '2026-10-10']);
|
||||
expect(buckets[0].groups.map((g) => g.orderCode)).toEqual(['MO-A', 'MO-B']);
|
||||
expect(buckets[1].groups.map((g) => g.orderCode)).toEqual(['MO-C']);
|
||||
});
|
||||
|
||||
it('配送日缺失时用哨兵日兜底(不丢行)', () => {
|
||||
const buckets = bucketGroupsByDeliveryDate([group('MO-D', null, ['土豆'])]);
|
||||
expect(buckets).toHaveLength(1);
|
||||
expect(buckets[0].deliveryDate).toBe('1970-01-01');
|
||||
});
|
||||
});
|
||||
|
||||
describe('建日单:一次建单承接该配送日全部主系统单', () => {
|
||||
/** 租户连接上跑过的 (SQL, 参数),用于断言"来源主系统单号落列" */
|
||||
let tenantCalls: Array<{ sql: string; params: unknown[] }> = [];
|
||||
|
||||
beforeEach(() => {
|
||||
query.mockReset();
|
||||
submit.mockReset();
|
||||
enrich.mockReset();
|
||||
withTenant.mockReset();
|
||||
tenantCalls = [];
|
||||
enrich.mockImplementation(async (_c: string, items: unknown[]) => items);
|
||||
submit.mockResolvedValue({ order_code: 'ORD_API_DAY_1', zero_price_count: 0, new_products_created: 0 });
|
||||
withTenant.mockImplementation(async (_b: string, fn: (c: unknown) => Promise<unknown>) =>
|
||||
fn({
|
||||
query: async (...args: unknown[]) => {
|
||||
tenantCalls.push({ sql: String(args[0] || ''), params: (args[1] as unknown[]) || [] });
|
||||
return { rowCount: 0, rows: [] };
|
||||
},
|
||||
})
|
||||
);
|
||||
query.mockImplementation(async (...args: unknown[]) => {
|
||||
const sql = sqlOf(args);
|
||||
if (sql.includes('INSERT INTO public.main_system_daily_order_imports')) {
|
||||
return { rowCount: 1, rows: [{ id: 'day-claim-1' }] };
|
||||
}
|
||||
if (sql.includes('SELECT id::text AS id, item_name')) {
|
||||
return { rowCount: 2, rows: [{ id: 'i1', item_name: '土豆' }, { id: 'i2', item_name: '白菜' }] };
|
||||
}
|
||||
return { rowCount: 0, rows: [] };
|
||||
});
|
||||
});
|
||||
|
||||
it('只建一张单;来源主系统单号落到 main_order_code,**不写备注**', async () => {
|
||||
const { importMainSystemGroups } = await import('../src/services/mainSystemOrderImport');
|
||||
const outcome = await importMainSystemGroups({
|
||||
supplierCode: 'SUP001',
|
||||
branchCode: 'SUP001',
|
||||
userId: null,
|
||||
groups: [group('MO-A', '2026-10-09', ['土豆']), group('MO-B', '2026-10-09', ['白菜'])],
|
||||
});
|
||||
|
||||
expect(submit).toHaveBeenCalledTimes(1);
|
||||
const items = (submit.mock.calls[0][0] as { items: Array<Record<string, unknown>> }).items;
|
||||
expect(items).toHaveLength(2);
|
||||
// 备注是业务字段:不得被来源单号占用(开发者 2026-10-10 明确)
|
||||
expect(items[0].remark ?? null).toBeNull();
|
||||
expect(items[1].remark ?? null).toBeNull();
|
||||
|
||||
// 来源单号落在 order_items.main_order_code(详情表按它做一级分组)
|
||||
const stamps = tenantCalls.filter((c) => c.sql.includes('SET main_order_code'));
|
||||
expect(stamps).toHaveLength(2);
|
||||
const byOrder = new Map(stamps.map((c) => [String(c.params[2]), c.params[1] as string[]]));
|
||||
expect(byOrder.get('MO-A')).toEqual(['i1']);
|
||||
expect(byOrder.get('MO-B')).toEqual(['i2']);
|
||||
|
||||
// 两个主系统订单各出一条 created 结果,指向同一张日单
|
||||
expect(outcome.results).toHaveLength(2);
|
||||
expect(new Set(outcome.results.map((r) => r.ourOrderCode))).toEqual(new Set(['ORD_API_DAY_1']));
|
||||
expect(outcome.created).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('报缺货:先主系统、后本地', () => {
|
||||
const ORDER = 'ORD_API_DAY_1';
|
||||
const ITEM = '11111111-1111-4111-8111-111111111111';
|
||||
const PREP = '22222222-2222-4222-8222-222222222222';
|
||||
/** 租户连接上真正跑过的 SQL(本地收口走 runWithTenantDataAccess,不在 pool 上) */
|
||||
let tenantSql: string[] = [];
|
||||
/** 同上,保留参数(断言作废备注等) */
|
||||
let tenantCalls: Array<{ sql: string; params: unknown[] }> = [];
|
||||
|
||||
beforeEach(() => {
|
||||
tenantSql = [];
|
||||
tenantCalls = [];
|
||||
query.mockReset();
|
||||
withTenant.mockReset();
|
||||
writeback.mockReset();
|
||||
lookup.mockReset();
|
||||
removeItem.mockReset();
|
||||
hasInbound.mockReset();
|
||||
hasPrepDone.mockReset();
|
||||
hasPurchaseDone.mockReset();
|
||||
removeItem.mockResolvedValue('deleted');
|
||||
hasInbound.mockResolvedValue(false);
|
||||
hasPrepDone.mockResolvedValue(false);
|
||||
hasPurchaseDone.mockResolvedValue(false);
|
||||
withTenant.mockImplementation(async (_b: string, fn: (c: unknown) => Promise<unknown>) =>
|
||||
fn({
|
||||
query: async (...args: unknown[]) => {
|
||||
const sql = sqlOf(args);
|
||||
tenantSql.push(sql);
|
||||
tenantCalls.push({ sql, params: (args[1] as unknown[]) || [] });
|
||||
if (sql.includes('BEGIN') || sql.includes('COMMIT') || sql.includes('ROLLBACK')) {
|
||||
return { rowCount: 0, rows: [] };
|
||||
}
|
||||
if (sql.includes('FROM order_items') && sql.includes('COALESCE(is_returned, false) AS is_returned')) {
|
||||
// 报缺货前的状态查询 / 剔除前的行查询(两个都读 is_returned)
|
||||
return {
|
||||
rowCount: 1,
|
||||
rows: [
|
||||
{
|
||||
id: ITEM,
|
||||
item_name: '土豆',
|
||||
sku_code: 'SKU1',
|
||||
is_returned: false,
|
||||
is_stockout: false,
|
||||
stockout_reported_at: null,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
// 订单头重算:读剩余明细(这里给一行)后 UPDATE orders
|
||||
if (sql.includes('SELECT quantity, unit, amount')) {
|
||||
return { rowCount: 1, rows: [{ quantity: '1', unit: '斤', amount: '10.00' }] };
|
||||
}
|
||||
if (sql.includes('UPDATE orders SET total_amount')) return { rowCount: 1, rows: [] };
|
||||
return { rowCount: 0, rows: [] };
|
||||
},
|
||||
})
|
||||
);
|
||||
query.mockImplementation(async (...args: unknown[]) => {
|
||||
const sql = sqlOf(args);
|
||||
// 主系统订单台账存在 ⇒ 是主系统分配单
|
||||
if (sql.includes('FROM public.main_system_order_imports')) return { rowCount: 1, rows: [] };
|
||||
// 行级台账:这一行有对照
|
||||
if (sql.includes('our_order_item_id = $2::uuid')) {
|
||||
return {
|
||||
rowCount: 1,
|
||||
rows: [
|
||||
{
|
||||
id: 'l1',
|
||||
branch_code: 'SUP001',
|
||||
main_order_code: 'MO-A',
|
||||
prep_id: PREP,
|
||||
our_order_code: ORDER,
|
||||
our_order_item_id: ITEM,
|
||||
main_supplier_code: 'SUP001',
|
||||
main_sku_code: 'SKU1',
|
||||
item_name: '土豆',
|
||||
last_prepare_qty: 1,
|
||||
last_prepare_status: 10,
|
||||
last_return_code: null,
|
||||
disposition: 'imported',
|
||||
disposition_reason: null,
|
||||
writeback_status: null,
|
||||
last_seen_active_at: null,
|
||||
payload: null,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
return { rowCount: 0, rows: [] };
|
||||
});
|
||||
writeback.mockResolvedValue({ kind: 'ok', updated: 1, skipped: [], needsCustomerPrice: false });
|
||||
});
|
||||
|
||||
it('主系统确认后:报 status=40,并把这一行从本地清掉(订单行 + 自采/备货)', async () => {
|
||||
const outcome = await reportMainSystemStockout({
|
||||
branchCode: 'SUP001',
|
||||
orderCode: ORDER,
|
||||
itemId: ITEM,
|
||||
reason: '产地断货',
|
||||
});
|
||||
|
||||
expect(outcome.kind).toBe('ok');
|
||||
expect(writeback).toHaveBeenCalledTimes(1);
|
||||
const params = writeback.mock.calls[0][0] as Record<string, unknown>;
|
||||
expect(params.status).toBe(40);
|
||||
expect(params.stockoutReason).toBe('产地断货');
|
||||
expect(params.preparationId).toBe(PREP);
|
||||
|
||||
// 先按既有"取消履约"判据确认还能硬删,再调删除原语(它连待处理采购/备货一起清)
|
||||
expect(hasInbound).toHaveBeenCalledTimes(1);
|
||||
expect(hasPrepDone).toHaveBeenCalledTimes(1);
|
||||
expect(hasPurchaseDone).toHaveBeenCalledTimes(1);
|
||||
expect(removeItem).toHaveBeenCalledTimes(1);
|
||||
expect((removeItem.mock.calls[0][0] as Record<string, unknown>).itemId).toBe(ITEM);
|
||||
|
||||
const all = tenantSql.join('\n');
|
||||
// 行被删掉了 ⇒ 不再写 is_stockout 标签;也不再需要作废采购(行整体清掉)
|
||||
expect(all).not.toContain('SET is_stockout = true');
|
||||
expect(all).not.toContain('UPDATE purchase_orders');
|
||||
// ⚠️ 转的是**主系统自采**:本地绝不允许新建任何采购单
|
||||
expect(all).not.toContain('INSERT INTO purchase_orders');
|
||||
// 删行后订单头金额必须跟着走
|
||||
expect(all).toContain('UPDATE orders SET total_amount');
|
||||
|
||||
// 台账处置:本系统已无此行 ⇒ 清对照 + skipped_stockout
|
||||
// (清对照是为了"主系统又分配回来"时能重新建行;skipped_stockout 让退货跟随不再处理它)
|
||||
const disposition = query.mock.calls.find((c) => sqlOf(c).includes("disposition = 'skipped_stockout'"));
|
||||
expect(disposition).toBeTruthy();
|
||||
expect(sqlOf(disposition!)).toContain('our_order_item_id = NULL');
|
||||
expect(removeItem).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('已有货物事实(已入库/备货完成/采购完成)→ 拒绝缺货,不动本地', async () => {
|
||||
hasInbound.mockResolvedValue(true);
|
||||
const outcome = await reportMainSystemStockout({
|
||||
branchCode: 'SUP001',
|
||||
orderCode: ORDER,
|
||||
itemId: ITEM,
|
||||
});
|
||||
expect(outcome.kind).toBe('invalid_state');
|
||||
expect(removeItem).not.toHaveBeenCalled();
|
||||
const all = tenantSql.join('\n');
|
||||
expect(all).not.toContain('UPDATE orders SET total_amount');
|
||||
});
|
||||
|
||||
it('主系统不可用 → 本地一动不动(不得先剔除再报)', async () => {
|
||||
writeback.mockResolvedValue({ kind: 'unavailable', reason: 'timeout' });
|
||||
lookup.mockResolvedValue({ kind: 'unavailable', reason: 'timeout' });
|
||||
|
||||
const outcome = await reportMainSystemStockout({ branchCode: 'SUP001', orderCode: ORDER, itemId: ITEM });
|
||||
expect(outcome.kind).toBe('unavailable');
|
||||
|
||||
const localWrites = tenantSql.filter(
|
||||
(sql) => sql.includes('SET is_stockout = true') || sql.includes('UPDATE purchase_orders')
|
||||
);
|
||||
expect(localWrites).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('主系统侧已经是 40(缺货)→ 视为已达成,仍收口本地', async () => {
|
||||
writeback.mockResolvedValue({ kind: 'unavailable', reason: 'conflict 该备货已流转自采,不可修改' });
|
||||
lookup.mockResolvedValue({
|
||||
kind: 'ok',
|
||||
results: [{ id: PREP, found: true, prepareStatus: 40 }],
|
||||
});
|
||||
|
||||
const outcome = await reportMainSystemStockout({ branchCode: 'SUP001', orderCode: ORDER, itemId: ITEM });
|
||||
expect(outcome.kind).toBe('ok');
|
||||
expect((outcome as { alreadyReported: boolean }).alreadyReported).toBe(true);
|
||||
});
|
||||
|
||||
it('非主系统订单 → 拒绝,且不发 HTTP', async () => {
|
||||
query.mockImplementation(async (...args: unknown[]) => {
|
||||
const sql = sqlOf(args);
|
||||
if (sql.includes('FROM public.main_system_order_imports')) return { rowCount: 0, rows: [] };
|
||||
return { rowCount: 0, rows: [] };
|
||||
});
|
||||
|
||||
const outcome = await reportMainSystemStockout({ branchCode: 'SUP001', orderCode: 'ORD_NATIVE', itemId: ITEM });
|
||||
expect(outcome.kind).toBe('not_main_system_item');
|
||||
expect(writeback).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('缺货跟随判据:主系统"已经不属于我们了"(2026-10-10)', () => {
|
||||
const ours = 'SUP37831443';
|
||||
const state = (over: Partial<{ found: boolean; prepareStatus: number | null; reassigned: boolean; currentSupplierCode: string | null }>) => ({
|
||||
found: true,
|
||||
prepareStatus: 10,
|
||||
reassigned: false,
|
||||
currentSupplierCode: ours,
|
||||
...over,
|
||||
});
|
||||
|
||||
it('转自采(prepare_status=40)⇒ 是"不再属于我们"', () => {
|
||||
expect(
|
||||
isPreparationNoLongerOurs({
|
||||
state: state({ prepareStatus: 40, reassigned: true, currentSupplierCode: 'INTERNAL' }),
|
||||
ourBranchCode: ours,
|
||||
})
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('改派给了别人 ⇒ 也是"不再属于我们"', () => {
|
||||
expect(
|
||||
isPreparationNoLongerOurs({
|
||||
state: state({ prepareStatus: 10, reassigned: true, currentSupplierCode: 'SUP_OTHER' }),
|
||||
ourBranchCode: ours,
|
||||
})
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('还在我们名下(准备中/已完成)⇒ 不动', () => {
|
||||
for (const status of [10, 20, 30]) {
|
||||
expect(
|
||||
isPreparationNoLongerOurs({ state: state({ prepareStatus: status }), ourBranchCode: ours })
|
||||
).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it('查不到该行(found=false)⇒ 不认(退货/取消留给开关控制的退货跟随判)', () => {
|
||||
expect(
|
||||
isPreparationNoLongerOurs({
|
||||
state: state({ found: false, prepareStatus: null, reassigned: false, currentSupplierCode: null }),
|
||||
ourBranchCode: ours,
|
||||
})
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('reassigned 但当前供应商仍是我们(脏数据)⇒ 不认', () => {
|
||||
expect(
|
||||
isPreparationNoLongerOurs({
|
||||
state: state({ reassigned: true, currentSupplierCode: ours }),
|
||||
ourBranchCode: ours,
|
||||
})
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('占位客户状态自愈(2026-10-10 白屏事故)', () => {
|
||||
/** 客户状态域只认 10/20/30/40/50;写 1 会让前端客户管理页读 statusMap[1].bgColor 抛错、整页白屏 */
|
||||
let calls: Array<{ sql: string; params: unknown[] }> = [];
|
||||
let customerStatus: number | null = null;
|
||||
let customerSource: string | null = null;
|
||||
|
||||
beforeEach(() => {
|
||||
calls = [];
|
||||
customerStatus = null;
|
||||
customerSource = null;
|
||||
query.mockReset();
|
||||
submit.mockReset();
|
||||
enrich.mockReset();
|
||||
withTenant.mockReset();
|
||||
enrich.mockImplementation(async (_c: string, items: unknown[]) => items);
|
||||
submit.mockResolvedValue({ order_code: 'ORD_API_DAY_1', zero_price_count: 0, new_products_created: 0 });
|
||||
withTenant.mockImplementation(async (_b: string, fn: (c: unknown) => Promise<unknown>) =>
|
||||
fn({
|
||||
query: async (...args: unknown[]) => {
|
||||
const sql = String(args[0] || '');
|
||||
calls.push({ sql, params: (args[1] as unknown[]) || [] });
|
||||
if (sql.includes('FROM customers') && sql.includes('WHERE customer_code = $1')) {
|
||||
// 2026-10-11:客户口径升级为「一个主系统下单分公司一个客户」,
|
||||
// 自愈查询多了 company_name(用于把客户名对齐成分公司名)⇒ 桩同步补该列。
|
||||
return customerStatus == null
|
||||
? { rowCount: 0, rows: [] }
|
||||
: {
|
||||
rowCount: 1,
|
||||
rows: [{ status: customerStatus, source: customerSource, company_name: '主系统订单(SUP001)' }],
|
||||
};
|
||||
}
|
||||
return { rowCount: 0, rows: [] };
|
||||
},
|
||||
})
|
||||
);
|
||||
query.mockImplementation(async (...args: unknown[]) => {
|
||||
const sql = sqlOf(args);
|
||||
if (sql.includes('INSERT INTO public.main_system_daily_order_imports')) {
|
||||
return { rowCount: 1, rows: [{ id: 'day-claim-1' }] };
|
||||
}
|
||||
if (sql.includes('SELECT id::text AS id, item_name')) {
|
||||
return { rowCount: 1, rows: [{ id: 'i1', item_name: '土豆' }] };
|
||||
}
|
||||
if (sql.includes('INSERT INTO public.main_system_order_import_items')) return { rowCount: 1, rows: [] };
|
||||
return { rowCount: 0, rows: [] };
|
||||
});
|
||||
});
|
||||
|
||||
it('新建占位客户用 status=10(不是 1)', async () => {
|
||||
const { importMainSystemGroups } = await import('../src/services/mainSystemOrderImport');
|
||||
await importMainSystemGroups({
|
||||
supplierCode: 'SUP001',
|
||||
branchCode: 'SUP001',
|
||||
userId: null,
|
||||
groups: [group('MO-A', '2026-10-09', ['土豆'])],
|
||||
});
|
||||
const insert = calls.find((c) => c.sql.includes('INSERT INTO customers'));
|
||||
expect(insert).toBeTruthy();
|
||||
expect(insert!.params[3]).toBe(10);
|
||||
// 来源标记(只作区分,不用于隐藏:主系统就是子系统的客户)
|
||||
expect(insert!.params[4]).toBe('main_system');
|
||||
});
|
||||
|
||||
it('已存在的占位客户状态不在域内 ⇒ 自愈为 10(即使本轮没有新行)', async () => {
|
||||
customerStatus = 1;
|
||||
const { importMainSystemGroups } = await import('../src/services/mainSystemOrderImport');
|
||||
await importMainSystemGroups({
|
||||
supplierCode: 'SUP001',
|
||||
branchCode: 'SUP001',
|
||||
userId: null,
|
||||
groups: [group('MO-A', '2026-10-09', ['土豆'])],
|
||||
});
|
||||
const heal = calls.find((c) => c.sql.includes('UPDATE customers SET status'));
|
||||
expect(heal).toBeTruthy();
|
||||
// 同一轮把 status 与 source 一起补上
|
||||
expect(heal!.params[0]).toBe('MAIN_SUP001');
|
||||
expect(heal!.params).toContain(10);
|
||||
});
|
||||
|
||||
it('状态已在域内且来源已标记 ⇒ 不发多余 UPDATE', async () => {
|
||||
customerStatus = 10;
|
||||
customerSource = 'main_system';
|
||||
const { importMainSystemGroups } = await import('../src/services/mainSystemOrderImport');
|
||||
await importMainSystemGroups({
|
||||
supplierCode: 'SUP001',
|
||||
branchCode: 'SUP001',
|
||||
userId: null,
|
||||
groups: [group('MO-A', '2026-10-09', ['土豆'])],
|
||||
});
|
||||
expect(calls.find((c) => c.sql.includes('UPDATE customers SET status'))).toBeFalsy();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,417 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import path from 'path';
|
||||
|
||||
/**
|
||||
* 主系统履约事件接收端(2026-10-10,设计文档
|
||||
* `docs/design/20261010-第三方订单履约事件接收端与免入库回写时机.md`)的行为回归。
|
||||
*
|
||||
* 覆盖:幂等占坑、两条链路的收口入口与前置、乱序不越级、无台账忽略、
|
||||
* 业务闸门(零价)不绕过、实收量事实落账、以及"零反向写回"的源码合同。
|
||||
*/
|
||||
|
||||
const query = vi.hoisted(() => vi.fn());
|
||||
const runWithTenantDbContext = vi.hoisted(() => vi.fn());
|
||||
const completeOrderWithoutDriverDelivery = vi.hoisted(() => vi.fn());
|
||||
const finalizeOrderFulfillment = vi.hoisted(() => vi.fn());
|
||||
const lookupMainSystemPreparationStates = vi.hoisted(() => vi.fn());
|
||||
const recordPrepActualQty = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock('../src/db', () => ({
|
||||
pool: { query: (...a: unknown[]) => query(...a), connect: vi.fn() },
|
||||
getRawPoolQuery: () => query,
|
||||
}));
|
||||
|
||||
vi.mock('../src/config', () => ({
|
||||
config: {
|
||||
mainSystemIntegration: {
|
||||
fulfillmentEventsEnabled: true,
|
||||
skipInboundAwaitPickup: true,
|
||||
clientId: 'x',
|
||||
clientSecret: 'y',
|
||||
preparationsPath: '/api/supplier/preparations',
|
||||
statusPath: '/api/supplier/preparations/status',
|
||||
oauthPath: '/api/supplier/oauth/token',
|
||||
},
|
||||
mainSystem: { baseUrl: 'http://stub', timeoutMs: 1000 },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../src/services/tenantDbContext', () => ({
|
||||
runWithTenantDbContext: (...a: unknown[]) => runWithTenantDbContext(...a),
|
||||
}));
|
||||
|
||||
vi.mock('../src/services/orderWorkflowFulfillmentService', () => ({
|
||||
completeOrderWithoutDriverDelivery: (...a: unknown[]) => completeOrderWithoutDriverDelivery(...a),
|
||||
finalizeOrderFulfillment: (...a: unknown[]) => finalizeOrderFulfillment(...a),
|
||||
}));
|
||||
|
||||
vi.mock('../src/services/mainSystemPreparations', () => ({
|
||||
lookupMainSystemPreparationStates: (...a: unknown[]) => lookupMainSystemPreparationStates(...a),
|
||||
}));
|
||||
|
||||
vi.mock('../src/services/mainSystemPrepLedger', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../src/services/mainSystemPrepLedger')>();
|
||||
return { ...actual, recordPrepActualQty: (...a: unknown[]) => recordPrepActualQty(...a) };
|
||||
});
|
||||
|
||||
const {
|
||||
handleFulfillmentEvent,
|
||||
isFulfillmentEvent,
|
||||
concludeByFulfillmentEvent,
|
||||
PREP_PICKED_UP_EVENT,
|
||||
PREP_INBOUND_COMPLETED_EVENT,
|
||||
} = await import('../src/services/mainSystemFulfillmentEvents');
|
||||
|
||||
type QueryResult = { rows: unknown[]; rowCount: number };
|
||||
|
||||
/** 按 SQL 特征分派:台账订单号 / 我方订单状态 / 事件幂等占坑 / 事件更新 */
|
||||
function mockDb(options: {
|
||||
ourOrderCode?: string | null;
|
||||
orderStatus?: number | null;
|
||||
insertWins?: boolean;
|
||||
}) {
|
||||
const { ourOrderCode = 'ORD_API_1', orderStatus = 50, insertWins = true } = options;
|
||||
query.mockImplementation(async (sql: string) => {
|
||||
const text = String(sql);
|
||||
if (text.includes('FROM public.main_system_order_imports')) {
|
||||
return { rows: ourOrderCode ? [{ our_order_code: ourOrderCode }] : [], rowCount: ourOrderCode ? 1 : 0 } as QueryResult;
|
||||
}
|
||||
if (text.includes('SELECT order_status FROM orders')) {
|
||||
return { rows: orderStatus === null ? [] : [{ order_status: orderStatus }], rowCount: orderStatus === null ? 0 : 1 } as QueryResult;
|
||||
}
|
||||
if (text.includes('INSERT INTO public.main_system_fulfillment_events')) {
|
||||
return { rows: insertWins ? [{ id: 'evt-1' }] : [], rowCount: insertWins ? 1 : 0 } as QueryResult;
|
||||
}
|
||||
return { rows: [], rowCount: 1 } as QueryResult;
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
query.mockReset();
|
||||
runWithTenantDbContext.mockReset().mockImplementation(async (_b: string, fn: () => unknown) => fn());
|
||||
completeOrderWithoutDriverDelivery.mockReset().mockResolvedValue(true);
|
||||
finalizeOrderFulfillment.mockReset().mockResolvedValue(true);
|
||||
lookupMainSystemPreparationStates.mockReset();
|
||||
recordPrepActualQty.mockReset().mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
describe('事件名识别', () => {
|
||||
it('只认两个履约事件', () => {
|
||||
expect(isFulfillmentEvent('preparations.picked_up')).toBe(true);
|
||||
expect(isFulfillmentEvent('preparations.inbound_completed')).toBe(true);
|
||||
expect(isFulfillmentEvent('preparations.allocated')).toBe(false);
|
||||
expect(isFulfillmentEvent('')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('幂等:主系统侧不做持久去重,必须由我方兜住', () => {
|
||||
it('重复投递 ⇒ duplicate=true,且不重复收口', async () => {
|
||||
mockDb({ insertWins: false });
|
||||
const result = await handleFulfillmentEvent({
|
||||
branchCode: 'SUP1',
|
||||
event: PREP_PICKED_UP_EVENT,
|
||||
mainOrderCode: 'ORD_WEB_1',
|
||||
});
|
||||
expect(result.duplicate).toBe(true);
|
||||
expect(completeOrderWithoutDriverDelivery).not.toHaveBeenCalled();
|
||||
expect(finalizeOrderFulfillment).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('首次投递 ⇒ 占坑成功并收口', async () => {
|
||||
mockDb({ insertWins: true, orderStatus: 50 });
|
||||
const result = await handleFulfillmentEvent({
|
||||
branchCode: 'SUP1',
|
||||
event: PREP_PICKED_UP_EVENT,
|
||||
mainOrderCode: 'ORD_WEB_1',
|
||||
});
|
||||
expect(result.duplicate).toBe(false);
|
||||
expect(result.outcome.status).toBe('done');
|
||||
expect(completeOrderWithoutDriverDelivery).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('C1 picked_up(免入库):停在 50 ⇒ 收口', () => {
|
||||
it('订单在 50 ⇒ 走 completeOrderWithoutDriverDelivery(接受 30/50)', async () => {
|
||||
mockDb({ orderStatus: 50 });
|
||||
const outcome = await concludeByFulfillmentEvent({
|
||||
branchCode: 'SUP1',
|
||||
event: PREP_PICKED_UP_EVENT,
|
||||
ourOrderCode: 'ORD_API_1',
|
||||
});
|
||||
expect(outcome.status).toBe('done');
|
||||
expect(completeOrderWithoutDriverDelivery).toHaveBeenCalledWith('ORD_API_1');
|
||||
expect(finalizeOrderFulfillment).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('订单还在 45 ⇒ suspended,**不越级改状态**', async () => {
|
||||
mockDb({ orderStatus: 45 });
|
||||
const outcome = await concludeByFulfillmentEvent({
|
||||
branchCode: 'SUP1',
|
||||
event: PREP_PICKED_UP_EVENT,
|
||||
ourOrderCode: 'ORD_API_1',
|
||||
});
|
||||
expect(outcome.status).toBe('suspended');
|
||||
expect(completeOrderWithoutDriverDelivery).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('C2 inbound_completed(送仓):已发车到 60 ⇒ 收口', () => {
|
||||
it('订单在 60 ⇒ 走 finalizeOrderFulfillment(接受 60)', async () => {
|
||||
mockDb({ orderStatus: 60 });
|
||||
const outcome = await concludeByFulfillmentEvent({
|
||||
branchCode: 'SUP1',
|
||||
event: PREP_INBOUND_COMPLETED_EVENT,
|
||||
ourOrderCode: 'ORD_API_1',
|
||||
});
|
||||
expect(outcome.status).toBe('done');
|
||||
expect(finalizeOrderFulfillment).toHaveBeenCalledWith('ORD_API_1');
|
||||
expect(completeOrderWithoutDriverDelivery).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('订单还在 50(我方尚未发车)⇒ suspended', async () => {
|
||||
mockDb({ orderStatus: 50 });
|
||||
const outcome = await concludeByFulfillmentEvent({
|
||||
branchCode: 'SUP1',
|
||||
event: PREP_INBOUND_COMPLETED_EVENT,
|
||||
ourOrderCode: 'ORD_API_1',
|
||||
});
|
||||
expect(outcome.status).toBe('suspended');
|
||||
expect(finalizeOrderFulfillment).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('边界', () => {
|
||||
it('订单已 90 ⇒ done(幂等命中),不重复结案', async () => {
|
||||
mockDb({ orderStatus: 90 });
|
||||
const outcome = await concludeByFulfillmentEvent({
|
||||
branchCode: 'SUP1',
|
||||
event: PREP_PICKED_UP_EVENT,
|
||||
ourOrderCode: 'ORD_API_1',
|
||||
});
|
||||
expect(outcome.status).toBe('done');
|
||||
expect(completeOrderWithoutDriverDelivery).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('我方订单不存在 ⇒ ignored', async () => {
|
||||
mockDb({ orderStatus: null });
|
||||
const outcome = await concludeByFulfillmentEvent({
|
||||
branchCode: 'SUP1',
|
||||
event: PREP_PICKED_UP_EVENT,
|
||||
ourOrderCode: 'ORD_API_MISSING',
|
||||
});
|
||||
expect(outcome.status).toBe('ignored');
|
||||
});
|
||||
|
||||
it('台账无该主系统订单 ⇒ ignored(不是我们的单)', async () => {
|
||||
mockDb({ ourOrderCode: null });
|
||||
const result = await handleFulfillmentEvent({
|
||||
branchCode: 'SUP1',
|
||||
event: PREP_PICKED_UP_EVENT,
|
||||
mainOrderCode: 'ORD_WEB_OTHER',
|
||||
});
|
||||
expect(result.outcome.status).toBe('ignored');
|
||||
expect(completeOrderWithoutDriverDelivery).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('零价闸门拦下 ⇒ suspended 且原因写明,**不绕过财务口径**', async () => {
|
||||
mockDb({ orderStatus: 50 });
|
||||
completeOrderWithoutDriverDelivery.mockRejectedValueOnce(
|
||||
Object.assign(new Error('订单有 1 条明细售价为 0,请先补价后再签收'), { code: 'zero_price_blocked' })
|
||||
);
|
||||
const result = await handleFulfillmentEvent({
|
||||
branchCode: 'SUP1',
|
||||
event: PREP_PICKED_UP_EVENT,
|
||||
mainOrderCode: 'ORD_WEB_1',
|
||||
});
|
||||
expect(result.outcome.status).toBe('suspended');
|
||||
expect(String(result.outcome.reason)).toContain('zero_price_blocked');
|
||||
});
|
||||
});
|
||||
|
||||
describe('实收量事实落账(铁律二:实收 ≠ 申报是常态)', () => {
|
||||
it('带 actualQty 的行落台账;actualQty=null 的行不落(不得用申报量冒充)', async () => {
|
||||
mockDb({ orderStatus: 50 });
|
||||
await handleFulfillmentEvent({
|
||||
branchCode: 'SUP1',
|
||||
event: PREP_PICKED_UP_EVENT,
|
||||
mainOrderCode: 'ORD_WEB_1',
|
||||
rows: [
|
||||
{
|
||||
id: 'prep-1', orderCode: 'ORD_WEB_1', skuCode: 'S1', itemName: '西红柿', displayName: null,
|
||||
prepareQty: 10, unit: '斤', orderQty: null, orderUnit: null, purchasePrice: 3.5,
|
||||
suggestedPrice: null, prepareStatus: 30, deliveryDate: null, taskDay: null,
|
||||
isStockout: false, processingMethod: null, returnCode: null, returnReason: null,
|
||||
requiresQualityReport: false, orderItemRemark: null, skipInbound: true, isDirectDelivery: false,
|
||||
actualQty: 9.5, actualQtyAt: '2026-10-10T05:10:00.000Z', qtyDiff: -0.5,
|
||||
isInbounded: false, inboundAt: null, orderDepartedAt: null,
|
||||
},
|
||||
{
|
||||
id: 'prep-2', orderCode: 'ORD_WEB_1', skuCode: 'S2', itemName: '土豆', displayName: null,
|
||||
prepareQty: 5, unit: '斤', orderQty: null, orderUnit: null, purchasePrice: 2,
|
||||
suggestedPrice: null, prepareStatus: 30, deliveryDate: null, taskDay: null,
|
||||
isStockout: false, processingMethod: null, returnCode: null, returnReason: null,
|
||||
requiresQualityReport: false, orderItemRemark: null, skipInbound: true, isDirectDelivery: false,
|
||||
actualQty: null, actualQtyAt: null, qtyDiff: null,
|
||||
isInbounded: false, inboundAt: null, orderDepartedAt: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(recordPrepActualQty).toHaveBeenCalledTimes(1);
|
||||
expect(recordPrepActualQty.mock.calls[0][0]).toMatchObject({
|
||||
branchCode: 'SUP1', prepId: 'prep-1', actualQty: 9.5, qtyDiff: -0.5,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('R3 履约字段:三处映射必须同改(防 2026-10-09「只改一处丢字段」重演)', () => {
|
||||
// 2026-10-11:主系统备货接口按"模块化 + 接口封装"拆到 ./mainSystem/api/preparations.ts
|
||||
// (mainSystemPreparations.ts 变成兼容门面),所以三处映射的锚点跟着实现文件走。
|
||||
const prepSrc = readFileSync(path.join(__dirname, '../src/services/mainSystem/api/preparations.ts'), 'utf8');
|
||||
const facadeSrc = readFileSync(path.join(__dirname, '../src/services/mainSystemPreparations.ts'), 'utf8');
|
||||
const routeSrc = readFileSync(path.join(__dirname, '../src/routes/mainSystemIntegration.ts'), 'utf8');
|
||||
const R3_KEYS = ['actual_qty', 'actual_qty_at', 'qty_diff', 'is_inbounded', 'inbound_at', 'order_departed_at'];
|
||||
|
||||
it('① 拉取(mapRow)与 ② lookup 两处都在 mainSystem/api/preparations.ts,且都映射 R3 字段', () => {
|
||||
for (const key of R3_KEYS) {
|
||||
const hits = [...prepSrc.matchAll(new RegExp(`raw\\?\\.${key}\\b`, 'g'))].length;
|
||||
// 同一文件里两处映射(拉取 + lookup)⇒ 每个字段至少出现 2 次
|
||||
expect(hits, `字段 ${key} 在 mainSystem/api/preparations.ts 只映射了 ${hits} 处(应为 ≥2)`).toBeGreaterThanOrEqual(2);
|
||||
}
|
||||
});
|
||||
|
||||
it('①′ 兼容门面仍从实现文件再导出(业务模块与测试都 import 门面路径,不得断)', () => {
|
||||
expect(facadeSrc).toMatch(/from '\.\/mainSystem\/api\/preparations'/);
|
||||
expect(facadeSrc).toMatch(/MainPreparationRow/);
|
||||
});
|
||||
|
||||
it('③ webhook 载荷(mapWebhookRow)同样映射 R3 字段', () => {
|
||||
for (const key of R3_KEYS) {
|
||||
expect(routeSrc, `webhook 映射缺字段 ${key}`).toMatch(new RegExp(`raw\\?\\.${key}\\b`));
|
||||
}
|
||||
});
|
||||
|
||||
it('类型定义含 R3 字段(漏加字段会编译失败,这里再钉一道)', () => {
|
||||
for (const field of ['actualQty', 'actualQtyAt', 'qtyDiff', 'isInbounded', 'inboundAt', 'orderDepartedAt']) {
|
||||
expect(prepSrc).toMatch(new RegExp(`${field}:`));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('拉取兜底:性能纪律(不逐单打主系统)', () => {
|
||||
it('N 张在途订单也只打 **1 次** lookup(内部按 500 分片),不是 N 次', async () => {
|
||||
// 两张主系统订单 → 两张我方订单,都在 60(已发车送仓)
|
||||
query.mockImplementation(async (sql: string) => {
|
||||
const text = String(sql);
|
||||
if (text.includes('FROM public.main_system_order_imports')) {
|
||||
return {
|
||||
rows: [
|
||||
{ main_order_code: 'ORD_WEB_A', our_order_code: 'ORD_API_A' },
|
||||
{ main_order_code: 'ORD_WEB_B', our_order_code: 'ORD_API_B' },
|
||||
],
|
||||
rowCount: 2,
|
||||
} as QueryResult;
|
||||
}
|
||||
if (text.includes('SELECT order_code, order_status FROM orders')) {
|
||||
return {
|
||||
rows: [
|
||||
{ order_code: 'ORD_API_A', order_status: 60 },
|
||||
{ order_code: 'ORD_API_B', order_status: 60 },
|
||||
],
|
||||
rowCount: 2,
|
||||
} as QueryResult;
|
||||
}
|
||||
// 单张订单状态(concludeByFulfillmentEvent 用的那一条)
|
||||
if (text.includes('SELECT order_status FROM orders')) {
|
||||
return { rows: [{ order_status: 60 }], rowCount: 1 } as QueryResult;
|
||||
}
|
||||
if (text.includes('main_sku_code')) {
|
||||
return {
|
||||
rows: [
|
||||
{ main_order_code: 'ORD_WEB_A', main_sku_code: 'S1' },
|
||||
{ main_order_code: 'ORD_WEB_B', main_sku_code: 'S2' },
|
||||
],
|
||||
rowCount: 2,
|
||||
} as QueryResult;
|
||||
}
|
||||
if (text.includes('INSERT INTO public.main_system_fulfillment_events')) {
|
||||
return { rows: [{ id: 'e' }], rowCount: 1 } as QueryResult;
|
||||
}
|
||||
return { rows: [], rowCount: 1 } as QueryResult;
|
||||
});
|
||||
lookupMainSystemPreparationStates.mockResolvedValue({
|
||||
kind: 'ok',
|
||||
results: [
|
||||
{ orderCode: 'ORD_WEB_A', skuCode: 'S1', isInbounded: true, orderItemPresent: true, orderDepartedAt: null },
|
||||
{ orderCode: 'ORD_WEB_B', skuCode: 'S2', isInbounded: true, orderItemPresent: true, orderDepartedAt: null },
|
||||
],
|
||||
});
|
||||
|
||||
const { reconcileFulfillmentFromPull } = await import('../src/services/mainSystemFulfillmentEvents');
|
||||
const result = await reconcileFulfillmentFromPull('SUP1');
|
||||
|
||||
// 关键断言:无论多少张单,lookup 只调一次
|
||||
expect(lookupMainSystemPreparationStates).toHaveBeenCalledTimes(1);
|
||||
const [, items] = lookupMainSystemPreparationStates.mock.calls[0] as [string, unknown[]];
|
||||
expect(items).toHaveLength(2); // 两张单的行合并进同一次请求
|
||||
expect(result.closed).toBe(2);
|
||||
});
|
||||
|
||||
it('主系统问不到(lookup 失败)⇒ 一律不判定,不误收口', async () => {
|
||||
query.mockImplementation(async (sql: string) => {
|
||||
const text = String(sql);
|
||||
if (text.includes('FROM public.main_system_order_imports')) {
|
||||
return { rows: [{ main_order_code: 'ORD_WEB_A', our_order_code: 'ORD_API_A' }], rowCount: 1 } as QueryResult;
|
||||
}
|
||||
if (text.includes('SELECT order_code, order_status FROM orders')) {
|
||||
return { rows: [{ order_code: 'ORD_API_A', order_status: 60 }], rowCount: 1 } as QueryResult;
|
||||
}
|
||||
if (text.includes('main_sku_code')) {
|
||||
return { rows: [{ main_order_code: 'ORD_WEB_A', main_sku_code: 'S1' }], rowCount: 1 } as QueryResult;
|
||||
}
|
||||
return { rows: [], rowCount: 0 } as QueryResult;
|
||||
});
|
||||
lookupMainSystemPreparationStates.mockResolvedValue({ kind: 'unavailable', reason: '超时' });
|
||||
|
||||
const { reconcileFulfillmentFromPull } = await import('../src/services/mainSystemFulfillmentEvents');
|
||||
const result = await reconcileFulfillmentFromPull('SUP1');
|
||||
expect(result.closed).toBe(0);
|
||||
expect(finalizeOrderFulfillment).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('零反向写回(铁律一)的源码合同', () => {
|
||||
const src = readFileSync(
|
||||
path.join(__dirname, '../src/services/mainSystemFulfillmentEvents.ts'),
|
||||
'utf8'
|
||||
);
|
||||
const configSrc = readFileSync(path.join(__dirname, '../src/config.ts'), 'utf8');
|
||||
|
||||
it('接收端不 import 任何"写主系统"的模块(回写状态 / 改价)', () => {
|
||||
// 不得调用主系统的任何写接口
|
||||
expect(src).not.toMatch(/writebackMainSystemPreparationStatus/);
|
||||
expect(src).not.toMatch(/amend-price|amendPrice|prepAmendRequest/);
|
||||
// 也不得触碰库存/成本(本批不做自动补库存,见设计文档 §6 D2)
|
||||
expect(src).not.toMatch(/inventory_logs|inventoryAdjustService|cost_details/);
|
||||
});
|
||||
|
||||
it('收口只走既有结案入口,不新造状态边', () => {
|
||||
expect(src).toMatch(/completeOrderWithoutDriverDelivery/);
|
||||
expect(src).toMatch(/finalizeOrderFulfillment/);
|
||||
// 不得直接写 order_status(状态推进一律走既有函数)
|
||||
expect(src).not.toMatch(/UPDATE\s+orders\s+SET\s+order_status/i);
|
||||
});
|
||||
|
||||
it('两个开关 2026-10-11 定稿均改为默认开(`!== .0.` 才关)', () => {
|
||||
// 成对:接收端负责收口 90,skipInbound 负责停在 50 等骑手取货;只翻一个就卡单
|
||||
expect(configSrc).toMatch(
|
||||
/fulfillmentEventsEnabled:\s*process\.env\.MAIN_SYSTEM_FULFILLMENT_EVENTS !== '0'/
|
||||
);
|
||||
// 默认开:`!== '0'` 才关(与 MAIN_SYSTEM_WRITEBACK 同风格);写成 0 即回退旧行为
|
||||
expect(configSrc).toMatch(
|
||||
/skipInboundAwaitPickup:\s*process\.env\.MAIN_SYSTEM_SKIP_INBOUND_AWAIT_PICKUP !== '0'/
|
||||
);
|
||||
// 两者是**一对**:配置注释必须写明"接收端关着则停在 50 收不了口",防止后人只翻一个开关
|
||||
expect(configSrc).toMatch(/永远收不了口/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,163 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||||
|
||||
/**
|
||||
* 主系统订单导入的「占坑式幂等」回归。
|
||||
*
|
||||
* 历史(2026-10-08 对抗式复查修复):原先幂等是「先查台账 → 再建单 → 最后写台账」,跨两个独立事务;
|
||||
* 定时对账与 webhook 同时导入时双方都判定"没导过" → **各建一张单**。
|
||||
*
|
||||
* 2026-10-10 起合并键改为**(分公司, 配送日)**(开发者口径:一天一张单),占坑也随之升到日级:
|
||||
* ① 占不到坑且**没有单号**(另一次导入正在建单)→ 直接 skipped,**绝不建单**;
|
||||
* ② 占到坑 → 建单后把单号回填到**日级**占坑行,并把每个主系统订单写进整单台账指向这张日单;
|
||||
* ③ 建单抛错 → 释放日级坑位(DELETE 未回填的行),否则该配送日会被永久挡住;
|
||||
* ④ 台账 SQL 必须带 `public.` 限定(租户 search_path 下不加限定会落到 tenant_* 去)。
|
||||
*/
|
||||
|
||||
const query = vi.hoisted(() => vi.fn());
|
||||
const submit = vi.hoisted(() => vi.fn());
|
||||
const enrich = vi.hoisted(() => vi.fn());
|
||||
const withTenant = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock('../src/db', () => ({
|
||||
pool: { query: (...args: unknown[]) => query(...args), connect: vi.fn() },
|
||||
getRawPoolQuery: () => query,
|
||||
}));
|
||||
vi.mock('../src/services/customerOrderSubmitService', () => ({
|
||||
submitMobileCustomerOrder: (...args: unknown[]) => submit(...args),
|
||||
}));
|
||||
vi.mock('../src/services/customerOrderEnrichService', () => ({
|
||||
enrichCustomerOrderItems: (...args: unknown[]) => enrich(...args),
|
||||
}));
|
||||
vi.mock('../src/services/tenantSchemaService', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../src/services/tenantSchemaService')>();
|
||||
return {
|
||||
...actual,
|
||||
runWithTenantDataAccess: (...args: unknown[]) => withTenant(...args),
|
||||
resolveActiveTenantSchema: async () => 'tenant_br001',
|
||||
};
|
||||
});
|
||||
|
||||
import { importMainSystemGroups } from '../src/services/mainSystemOrderImport';
|
||||
import type { MainOrderGroup } from '../src/services/mainSystemPreparations';
|
||||
|
||||
const GROUP: MainOrderGroup = {
|
||||
orderCode: 'MO-TEST-1',
|
||||
deliveryDate: '2026-10-09',
|
||||
taskDay: '2026-10-09',
|
||||
rows: [
|
||||
{
|
||||
id: 'r1',
|
||||
orderCode: 'MO-TEST-1',
|
||||
itemName: '土豆',
|
||||
prepareQty: 10,
|
||||
unit: '斤',
|
||||
purchasePrice: 2.5,
|
||||
suggestedPrice: null,
|
||||
processingMethod: null,
|
||||
processingOwner: 'supplier',
|
||||
isStockout: false,
|
||||
} as never,
|
||||
],
|
||||
};
|
||||
|
||||
function sqlOf(call: unknown[]): string {
|
||||
return String(call[0] || '');
|
||||
}
|
||||
|
||||
describe('importMainSystemGroups 占坑式幂等', () => {
|
||||
beforeEach(() => {
|
||||
query.mockReset();
|
||||
submit.mockReset();
|
||||
enrich.mockReset();
|
||||
withTenant.mockReset();
|
||||
withTenant.mockImplementation(async (_b: string, fn: (c: unknown) => Promise<unknown>) =>
|
||||
fn({ query: async () => ({ rowCount: 1, rows: [] }) })
|
||||
);
|
||||
enrich.mockImplementation(async (_c: string, items: unknown[]) => items);
|
||||
submit.mockResolvedValue({ order_code: 'ORD_API_X1', zero_price_count: 0, new_products_created: 0 });
|
||||
query.mockImplementation(async (...args: unknown[]) => {
|
||||
const sql = sqlOf(args);
|
||||
if (sql.includes('INSERT INTO public.main_system_daily_order_imports')) {
|
||||
return { rowCount: 1, rows: [{ id: 'claim-1' }] };
|
||||
}
|
||||
return { rowCount: 0, rows: [] };
|
||||
});
|
||||
});
|
||||
|
||||
it('占不到坑且该配送日还没有单号(正在建单)→ skipped,且不建单', async () => {
|
||||
query.mockImplementation(async (...args: unknown[]) => {
|
||||
const sql = sqlOf(args);
|
||||
// 日级占坑 INSERT 返回 0 行(没抢到),随后 SELECT 读到的 our_order_code 为空
|
||||
if (sql.includes('INSERT INTO public.main_system_daily_order_imports')) return { rowCount: 0, rows: [] };
|
||||
if (sql.includes('SELECT our_order_code FROM public.main_system_daily_order_imports')) {
|
||||
return { rowCount: 1, rows: [{ our_order_code: null }] };
|
||||
}
|
||||
return { rowCount: 0, rows: [] };
|
||||
});
|
||||
|
||||
const outcome = await importMainSystemGroups({
|
||||
supplierCode: 'SUP001',
|
||||
branchCode: 'BR001',
|
||||
userId: null,
|
||||
groups: [GROUP],
|
||||
});
|
||||
expect(submit).not.toHaveBeenCalled();
|
||||
expect(outcome.skipped).toBe(1);
|
||||
expect(outcome.created).toBe(0);
|
||||
expect(outcome.results[0].message).toContain('正在导入');
|
||||
});
|
||||
|
||||
it('占到坑 → 建单后把单号回填到日级占坑行,并把主系统订单写进整单台账', async () => {
|
||||
await importMainSystemGroups({ supplierCode: 'SUP001', branchCode: 'BR001', userId: null, groups: [GROUP] });
|
||||
|
||||
expect(submit).toHaveBeenCalledTimes(1);
|
||||
const claimCall = query.mock.calls.find((c) =>
|
||||
sqlOf(c).includes('INSERT INTO public.main_system_daily_order_imports')
|
||||
);
|
||||
expect(claimCall).toBeTruthy();
|
||||
expect(sqlOf(claimCall!)).toContain('ON CONFLICT (branch_code, delivery_date) DO UPDATE');
|
||||
expect(sqlOf(claimCall!)).toContain("INTERVAL '10 minutes'");
|
||||
|
||||
const refill = query.mock.calls.find((c) =>
|
||||
sqlOf(c).includes('UPDATE public.main_system_daily_order_imports')
|
||||
);
|
||||
expect(refill).toBeTruthy();
|
||||
expect(refill![1]![0]).toBe('ORD_API_X1');
|
||||
expect(refill![1]![1]).toBe('claim-1');
|
||||
|
||||
// 整单台账仍逐主系统订单一行,指向同一张日单
|
||||
const ledgerCall = query.mock.calls.find((c) =>
|
||||
sqlOf(c).includes('INSERT INTO public.main_system_order_imports')
|
||||
);
|
||||
expect(ledgerCall).toBeTruthy();
|
||||
expect(sqlOf(ledgerCall!)).toContain('ON CONFLICT (branch_code, main_order_code) DO UPDATE');
|
||||
expect((ledgerCall![1] as unknown[])[3]).toBe('ORD_API_X1');
|
||||
});
|
||||
|
||||
it('建单抛错 → 释放坑位(DELETE 未回填的行)', async () => {
|
||||
submit.mockRejectedValue(new Error('submit boom'));
|
||||
const outcome = await importMainSystemGroups({
|
||||
supplierCode: 'SUP001',
|
||||
branchCode: 'BR001',
|
||||
userId: null,
|
||||
groups: [GROUP],
|
||||
});
|
||||
|
||||
const deleteCall = query.mock.calls.find((c) =>
|
||||
sqlOf(c).includes('DELETE FROM public.main_system_daily_order_imports')
|
||||
);
|
||||
expect(deleteCall).toBeTruthy();
|
||||
expect(deleteCall![1]).toEqual(['claim-1']);
|
||||
expect(outcome.failed).toBe(1);
|
||||
});
|
||||
|
||||
it('台账读写 SQL 一律带 public. 限定', async () => {
|
||||
await importMainSystemGroups({ supplierCode: 'SUP001', branchCode: 'BR001', userId: null, groups: [GROUP] });
|
||||
const ledgerCalls = query.mock.calls.filter((c) => sqlOf(c).includes('main_system_order_imports'));
|
||||
expect(ledgerCalls.length).toBeGreaterThan(0);
|
||||
for (const call of ledgerCalls) {
|
||||
expect(/main_system_order_imports/.test(sqlOf(call))).toBe(true);
|
||||
expect(sqlOf(call)).not.toMatch(/(FROM|INTO|UPDATE)\s+main_system_order_imports/);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
/**
|
||||
* 导入守卫(2026-10-11 真实事故后补):
|
||||
* 事故现象:某分公司(SUP35143228)换库后**对接 Token 换不到**(主系统回
|
||||
* `forbidden: 未授权访问该供应商`),拉单返回 `unavailable`,导入把它当"本轮 0 行"静默跳过
|
||||
* ⇒ 该分公司永远收不到单、却全程无告警(`failed: 0`、无认领记录、无台账行)。
|
||||
* 用户表现为「登录后看不到任何订单」。
|
||||
*
|
||||
* 本文件钉两条:① 拉不到必须计入 failed + 带分公司编码的告警;② 归属断言(不得张冠李戴)。
|
||||
*/
|
||||
const src = readFileSync(new URL('../src/services/mainSystemOrderImport.ts', import.meta.url), 'utf8');
|
||||
const fanout = src.slice(src.indexOf('export async function importMainSystemOrdersForAllSupplierBranches'));
|
||||
|
||||
describe('拉取失败不得静默跳过', () => {
|
||||
it('unavailable ⇒ 计入 failed 并打带分公司编码的错误日志', () => {
|
||||
expect(fanout).toContain("(preloadedActive as { kind?: string }).kind === 'unavailable'");
|
||||
expect(fanout).toContain('拉取失败,本分公司本轮未导入');
|
||||
expect(fanout).toContain('failed: 1');
|
||||
// 必须在调用 importMainSystemOrders **之前**拦下(否则会被当成 0 行继续走)
|
||||
expect(fanout.indexOf("kind === 'unavailable'")).toBeLessThan(
|
||||
fanout.indexOf('const outcome = await importMainSystemOrders(')
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('归属断言:绝不能张冠李戴', () => {
|
||||
it('本轮写入的台账行 main_supplier_code 必须等于本分公司', () => {
|
||||
expect(fanout).toContain('归属断言');
|
||||
expect(fanout).toContain('COALESCE(main_supplier_code, $1) <> $1');
|
||||
expect(fanout).toContain('属于**其它供应商**');
|
||||
// 断言失败要计入 failed(宁可报警,不可静默错建)
|
||||
expect(fanout).toContain('failed: bad');
|
||||
});
|
||||
|
||||
it('断言自身异常不阻断导入(只告警)', () => {
|
||||
expect(fanout).toContain('归属断言执行失败(不阻断导入)');
|
||||
});
|
||||
});
|
||||
|
||||
describe('客户归属兜底:不得挂在禁用客户上(2026-10-11 报障)', () => {
|
||||
it('行里缺 branch_code 时,从主系统单号解析分公司(orderCode 兜底)', () => {
|
||||
const start = src.indexOf('function pickDayMainBranch');
|
||||
const fn = src.slice(start, start + 2600);
|
||||
expect(fn).toContain('orderCode');
|
||||
expect(fn).toContain('if (!counter.size) {');
|
||||
expect(fn).toContain('match(/_(BR[0-9A-Z]+)_/i)');
|
||||
});
|
||||
|
||||
it('占位客户被停用(status=40)后,一旦用回它必须自愈启用', () => {
|
||||
const start = src.indexOf('async function ensureImportCustomer');
|
||||
const fn = src.slice(start, start + 4200);
|
||||
expect(fn).toContain('Number(current?.status) === 40');
|
||||
expect(fn).toContain('禁用客户');
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,143 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mapPrepRowsToOurItems } from '../src/services/mainSystemPrepLedger';
|
||||
import { voidInventoryCoverCostForItem } from '../src/services/mainSystemReturnFollow';
|
||||
|
||||
/**
|
||||
* 第三方订单退货跟随(2026-10-08,设计文档 20261008 §3.1/§3.4)的纯逻辑回归:
|
||||
* ① 备货行 ↔ 本系统订单行的对照必须**按名字 + 出现次序**确定,不允许随机/时间兜底;
|
||||
* ② 库存抵扣成本行的作废必须按 `order_code + sku_code` 打(因为那类成本行没有 order_item_id),
|
||||
* 且必须带 `cost_source='inventory_cover'` 以免误伤正常采购成本。
|
||||
*/
|
||||
|
||||
describe('mapPrepRowsToOurItems(行级对照)', () => {
|
||||
it('同名多行按各自出现次序配对(可复现,不用时间兜底)', () => {
|
||||
const prep = [
|
||||
{ id: 'p1', itemName: '土豆' },
|
||||
{ id: 'p2', itemName: '白菜' },
|
||||
{ id: 'p3', itemName: '土豆' },
|
||||
];
|
||||
const ours = [
|
||||
{ id: 'i1', item_name: '土豆' },
|
||||
{ id: 'i2', item_name: '白菜' },
|
||||
{ id: 'i3', item_name: '土豆' },
|
||||
];
|
||||
const map = mapPrepRowsToOurItems(prep, ours);
|
||||
expect(map.get('p1')).toBe('i1');
|
||||
expect(map.get('p2')).toBe('i2');
|
||||
expect(map.get('p3')).toBe('i3');
|
||||
expect(map.size).toBe(3);
|
||||
});
|
||||
|
||||
it('对不上的行留空(宁可挂待处理,不猜)', () => {
|
||||
const map = mapPrepRowsToOurItems(
|
||||
[{ id: 'p1', itemName: '土豆' }, { id: 'p2', itemName: '没这个品' }],
|
||||
[{ id: 'i1', item_name: '土豆' }]
|
||||
);
|
||||
expect(map.get('p1')).toBe('i1');
|
||||
expect(map.has('p2')).toBe(false);
|
||||
});
|
||||
|
||||
it('名称两边的空白差异不影响配对', () => {
|
||||
const map = mapPrepRowsToOurItems(
|
||||
[{ id: 'p1', itemName: ' 土豆 ' }],
|
||||
[{ id: 'i1', item_name: '土豆' }]
|
||||
);
|
||||
expect(map.get('p1')).toBe('i1');
|
||||
});
|
||||
|
||||
it('我方多出来的行不会被误配', () => {
|
||||
const map = mapPrepRowsToOurItems(
|
||||
[{ id: 'p1', itemName: '土豆' }],
|
||||
[{ id: 'i1', item_name: '土豆' }, { id: 'i2', item_name: '土豆' }]
|
||||
);
|
||||
expect([...map.values()]).toEqual(['i1']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('voidInventoryCoverCostForItem(库存抵扣补丁)', () => {
|
||||
it('按 order_code + sku_code + cost_source=inventory_cover 作废,且幂等写法(amount=0 再跑无副作用)', async () => {
|
||||
const calls: Array<{ text: string; params?: unknown[] }> = [];
|
||||
const db = {
|
||||
query: async (text: string, params?: unknown[]) => {
|
||||
calls.push({ text, params });
|
||||
return { rowCount: 1 };
|
||||
},
|
||||
};
|
||||
await voidInventoryCoverCostForItem(db, {
|
||||
orderCode: 'ORD_API_X',
|
||||
skuCode: 'SKU1',
|
||||
remark: '测试',
|
||||
});
|
||||
expect(calls).toHaveLength(1);
|
||||
const sql = calls[0].text.replace(/\s+/g, ' ');
|
||||
expect(sql).toContain('UPDATE cost_details');
|
||||
expect(sql).toContain('amount = 0');
|
||||
expect(sql).toContain('allocated_amount = 0');
|
||||
expect(sql).toContain("status = 20");
|
||||
expect(sql).toContain('order_code = $1 AND sku_code = $2');
|
||||
expect(sql).toContain("cost_source = 'inventory_cover'");
|
||||
// 绝不能用 order_item_id 作匹配(那类成本行 order_item_id 为空,这正是本次要补的缺口)
|
||||
expect(sql).not.toContain('order_item_id');
|
||||
expect(calls[0].params).toEqual(['ORD_API_X', 'SKU1', '测试']);
|
||||
});
|
||||
|
||||
it('没有 sku 时不动账(避免按 order 全表误伤)', async () => {
|
||||
let called = 0;
|
||||
const db = { query: async () => { called += 1; return { rowCount: 0 }; } };
|
||||
await voidInventoryCoverCostForItem(db, { orderCode: 'ORD_API_X', skuCode: '', remark: 'x' });
|
||||
await voidInventoryCoverCostForItem(db, { orderCode: 'ORD_API_X', skuCode: null, remark: 'x' });
|
||||
expect(called).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* A2(2026-10-09 主系统增量改造后):退货判定改由 `POST /preparations/lookup` 权威回答。
|
||||
* 这里钉住四态判定与三条安全底线:问不到不判定、备货行还在就不动、缺 sku 仍走归档兜底。
|
||||
*/
|
||||
describe('judgeByLookup:四态判定', () => {
|
||||
const base = {
|
||||
orderCode: 'O1', skuCode: 'S1', id: 'p1', prepareStatus: null as number | null, prepareTime: null,
|
||||
prepareQty: null, purchasePrice: null, unit: null, orderStatus: null, orderDeleted: false,
|
||||
orderItemPresent: true, isReturned: false, returnCode: null as string | null,
|
||||
currentSupplierCode: 'SUP1', reassigned: false,
|
||||
};
|
||||
|
||||
it('主系统侧仍在办理(found=true, status<30)→ inconsistent(不处置,交人工)', async () => {
|
||||
const { judgeByLookup } = await import('../src/services/mainSystemReturnFollow');
|
||||
expect(judgeByLookup({ ...base, found: true, prepareStatus: 10 })).toBe('inconsistent');
|
||||
});
|
||||
|
||||
it('主系统侧已完成(found=true, status>=30)→ completed(不是退货)', async () => {
|
||||
const { judgeByLookup } = await import('../src/services/mainSystemReturnFollow');
|
||||
expect(judgeByLookup({ ...base, found: true, prepareStatus: 30 })).toBe('completed');
|
||||
});
|
||||
|
||||
it('备货行没了但订单行仍在且未退货 → completed(正常完成)', async () => {
|
||||
const { judgeByLookup } = await import('../src/services/mainSystemReturnFollow');
|
||||
expect(judgeByLookup({ ...base, found: false })).toBe('completed');
|
||||
});
|
||||
|
||||
it('已退货红冲(is_returned / return_code)→ returned', async () => {
|
||||
const { judgeByLookup } = await import('../src/services/mainSystemReturnFollow');
|
||||
expect(judgeByLookup({ ...base, found: false, isReturned: true })).toBe('returned');
|
||||
expect(judgeByLookup({ ...base, found: false, returnCode: 'OIR_X' })).toBe('returned');
|
||||
});
|
||||
|
||||
it('已改供别家 → reassigned(单独计数,处置同退货类)', async () => {
|
||||
const { judgeByLookup } = await import('../src/services/mainSystemReturnFollow');
|
||||
expect(
|
||||
judgeByLookup({ ...base, found: false, currentSupplierCode: 'SUP_OTHER', reassigned: true })
|
||||
).toBe('reassigned');
|
||||
});
|
||||
|
||||
it('订单行已被删除 / 整单删除 → cancelled(取消履约)', async () => {
|
||||
const { judgeByLookup } = await import('../src/services/mainSystemReturnFollow');
|
||||
expect(judgeByLookup({ ...base, found: false, orderItemPresent: false })).toBe('cancelled');
|
||||
expect(judgeByLookup({ ...base, found: false, orderDeleted: true, orderItemPresent: false })).toBe('cancelled');
|
||||
});
|
||||
|
||||
it('该行没出现在 lookup 结果里 → unknown(**绝不**当退货)', async () => {
|
||||
const { judgeByLookup } = await import('../src/services/mainSystemReturnFollow');
|
||||
expect(judgeByLookup(undefined)).toBe('unknown');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,314 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||||
|
||||
/**
|
||||
* 发车回写(2026-10-08,设计文档 20261008 §3.5)的三条硬规则回归:
|
||||
* ① 我价 ≤ 0 → **跳过回写**(挂 skipped_zero_price),不因一行卡住整单;
|
||||
* ② 实供量 > 主系统备货量 → 必须带 `confirm_over_qty`;
|
||||
* ③ 主系统 4xx(明确拒绝)记 rejected 不重试;5xx/超时记 suspended 待重试;
|
||||
* ④ 未找到对应订单行的行不猜,记 suspended。
|
||||
*/
|
||||
|
||||
const query = vi.hoisted(() => vi.fn());
|
||||
const writebackHttp = vi.hoisted(() => vi.fn());
|
||||
const listPending = vi.hoisted(() => vi.fn());
|
||||
const markWriteback = vi.hoisted(() => vi.fn());
|
||||
const withTenant = vi.hoisted(() => vi.fn());
|
||||
const setOurOrderItemId = vi.hoisted(() => vi.fn());
|
||||
const priceQtyEnabled = vi.hoisted(() => ({ value: false }));
|
||||
const approvedFinal = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock('../src/db', () => ({
|
||||
pool: { query: (...a: unknown[]) => query(...a), connect: vi.fn() },
|
||||
getRawPoolQuery: () => query,
|
||||
}));
|
||||
vi.mock('../src/config', () => ({
|
||||
config: {
|
||||
mainSystemIntegration: {
|
||||
writebackEnabled: true,
|
||||
returnFollowEnabled: true,
|
||||
clientId: 'x',
|
||||
clientSecret: 'y',
|
||||
preparationsPath: '/api/supplier/preparations',
|
||||
statusPath: '/api/supplier/preparations/status',
|
||||
oauthPath: '/api/supplier/oauth/token',
|
||||
},
|
||||
mainSystem: { baseUrl: 'http://stub', timeoutMs: 1000 },
|
||||
},
|
||||
}));
|
||||
vi.mock('../src/services/mainSystemPreparations', () => ({
|
||||
writebackMainSystemPreparationStatus: (...a: unknown[]) => writebackHttp(...a),
|
||||
fetchMainSystemPreparations: vi.fn(),
|
||||
fetchMainSystemArchivedPreparations: vi.fn(),
|
||||
}));
|
||||
vi.mock('../src/services/mainSystemPrepLedger', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../src/services/mainSystemPrepLedger')>();
|
||||
return {
|
||||
...actual,
|
||||
listRowsPendingWriteback: (...a: unknown[]) => listPending(...a),
|
||||
markWriteback: (...a: unknown[]) => markWriteback(...a),
|
||||
setOurOrderItemId: (...a: unknown[]) => setOurOrderItemId(...a),
|
||||
};
|
||||
});
|
||||
vi.mock('../src/services/mainSystemPriceQtyRequest', () => ({
|
||||
isEnabled: () => priceQtyEnabled.value,
|
||||
getApprovedFinalValues: (...a: unknown[]) => approvedFinal(...a),
|
||||
}));
|
||||
vi.mock('../src/services/tenantDbContext', () => ({
|
||||
runWithTenantDbContext: (...a: unknown[]) => withTenant(...a),
|
||||
getTenantDbStore: () => undefined,
|
||||
}));
|
||||
|
||||
import { writebackDeliveredOrderToMainSystem } from '../src/services/mainSystemWriteback';
|
||||
|
||||
const ROW = {
|
||||
id: 'l1',
|
||||
branch_code: 'SUP1',
|
||||
main_order_code: 'MO1',
|
||||
prep_id: 'p1',
|
||||
our_order_code: 'ORD_API_1',
|
||||
our_order_item_id: 'i1',
|
||||
main_supplier_code: 'SUP1',
|
||||
main_sku_code: 'SKU1',
|
||||
item_name: '土豆',
|
||||
last_prepare_qty: 10,
|
||||
last_prepare_status: 10,
|
||||
last_return_code: null,
|
||||
disposition: 'imported' as const,
|
||||
disposition_reason: null,
|
||||
writeback_status: 'none',
|
||||
payload: null,
|
||||
};
|
||||
|
||||
function mockItem(overrides: Record<string, unknown> = {}) {
|
||||
const item = {
|
||||
id: 'i1',
|
||||
sku_code: 'SKU_LOCAL',
|
||||
item_name: '土豆',
|
||||
quantity: 10,
|
||||
unit: '斤',
|
||||
price: 3.5,
|
||||
...overrides,
|
||||
};
|
||||
withTenant.mockImplementation(async (_b: string, fn: (c: unknown) => Promise<unknown>) =>
|
||||
fn({ query: async () => ({ rowCount: 1, rows: [item] }) })
|
||||
);
|
||||
// 兼容直接 pool.query 读订单行的写法
|
||||
query.mockImplementation(async () => ({ rowCount: 1, rows: [item] }));
|
||||
}
|
||||
|
||||
describe('writebackDeliveredOrderToMainSystem', () => {
|
||||
beforeEach(() => {
|
||||
query.mockReset();
|
||||
writebackHttp.mockReset();
|
||||
listPending.mockReset();
|
||||
markWriteback.mockReset();
|
||||
withTenant.mockReset();
|
||||
listPending.mockResolvedValue([ROW]);
|
||||
markWriteback.mockResolvedValue(undefined);
|
||||
setOurOrderItemId.mockReset();
|
||||
setOurOrderItemId.mockResolvedValue(undefined);
|
||||
writebackHttp.mockResolvedValue({ kind: 'ok', updated: 1, skipped: [], needsCustomerPrice: false });
|
||||
priceQtyEnabled.value = false;
|
||||
approvedFinal.mockReset();
|
||||
approvedFinal.mockResolvedValue(null);
|
||||
mockItem();
|
||||
});
|
||||
|
||||
it('正常回写:数量/单价/单位按我方口径,带 prep_id', async () => {
|
||||
const out = await writebackDeliveredOrderToMainSystem('SUP1', 'ORD_API_1');
|
||||
expect(out.done).toBe(1);
|
||||
expect(writebackHttp).toHaveBeenCalledTimes(1);
|
||||
const arg = writebackHttp.mock.calls[0][0] as Record<string, unknown>;
|
||||
expect(arg).toMatchObject({
|
||||
supplierCode: 'SUP1',
|
||||
preparationId: 'p1',
|
||||
status: 30,
|
||||
prepareQty: 10,
|
||||
purchasePrice: 3.5,
|
||||
unit: '斤',
|
||||
});
|
||||
expect(arg.confirmOverQty).toBe(false);
|
||||
expect(markWriteback).toHaveBeenCalledWith(expect.objectContaining({ status: 'done' }));
|
||||
});
|
||||
|
||||
it('我价 0 → 跳过回写、不发 HTTP、挂 skipped_zero_price', async () => {
|
||||
mockItem({ price: 0 });
|
||||
const out = await writebackDeliveredOrderToMainSystem('SUP1', 'ORD_API_1');
|
||||
expect(writebackHttp).not.toHaveBeenCalled();
|
||||
expect(out.skippedZeroPrice).toBe(1);
|
||||
expect(out.done).toBe(0);
|
||||
expect(markWriteback).toHaveBeenCalledWith(expect.objectContaining({ status: 'skipped_zero_price' }));
|
||||
});
|
||||
|
||||
it('实供量 > 主系统备货量 → 带 confirm_over_qty', async () => {
|
||||
mockItem({ quantity: 12 });
|
||||
await writebackDeliveredOrderToMainSystem('SUP1', 'ORD_API_1');
|
||||
expect((writebackHttp.mock.calls[0][0] as Record<string, unknown>).confirmOverQty).toBe(true);
|
||||
});
|
||||
|
||||
it('C5:改价审核开关关闭(默认)⇒ 回写照旧携带价格', async () => {
|
||||
priceQtyEnabled.value = false;
|
||||
await writebackDeliveredOrderToMainSystem('SUP1', 'ORD_API_1');
|
||||
const arg = writebackHttp.mock.calls[0][0] as Record<string, unknown>;
|
||||
expect(arg.purchasePrice).toBe(3.5);
|
||||
expect(approvedFinal).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('C5:开关打开 + 价格未经审核 ⇒ **不回写价格**(堵住静默通道)', async () => {
|
||||
priceQtyEnabled.value = true;
|
||||
approvedFinal.mockResolvedValue(null);
|
||||
const out = await writebackDeliveredOrderToMainSystem('SUP1', 'ORD_API_1');
|
||||
const arg = writebackHttp.mock.calls[0][0] as Record<string, unknown>;
|
||||
expect(arg.purchasePrice).toBeUndefined();
|
||||
// 数量仍按实供量回写(备货完成这件事不受影响)
|
||||
expect(arg.prepareQty).toBe(10);
|
||||
expect(out.done).toBe(1);
|
||||
expect(markWriteback).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ status: 'done', reason: expect.stringContaining('未经改价审核流程确认') })
|
||||
);
|
||||
});
|
||||
|
||||
it('C5:开关打开 + 已有审核通过的同一价格 ⇒ 照常回写价格', async () => {
|
||||
priceQtyEnabled.value = true;
|
||||
approvedFinal.mockResolvedValue({ requestId: 'MS-REQ-1', finalPrice: 3.5, finalQty: 10, status: 'approved' });
|
||||
await writebackDeliveredOrderToMainSystem('SUP1', 'ORD_API_1');
|
||||
const arg = writebackHttp.mock.calls[0][0] as Record<string, unknown>;
|
||||
expect(arg.purchasePrice).toBe(3.5);
|
||||
});
|
||||
|
||||
it('C5:开关打开 + 已审核价与本地价不一致 ⇒ 不回写价格(主系统以自己为准)', async () => {
|
||||
priceQtyEnabled.value = true;
|
||||
approvedFinal.mockResolvedValue({ requestId: 'MS-REQ-1', finalPrice: 4.2, finalQty: 10, status: 'approved' });
|
||||
await writebackDeliveredOrderToMainSystem('SUP1', 'ORD_API_1');
|
||||
const arg = writebackHttp.mock.calls[0][0] as Record<string, unknown>;
|
||||
expect(arg.purchasePrice).toBeUndefined();
|
||||
});
|
||||
|
||||
it('主系统 4xx 明确拒绝 → rejected(不再重试)', async () => {
|
||||
writebackHttp.mockResolvedValue({ kind: 'rejected', reason: '价格须大于 0' });
|
||||
const out = await writebackDeliveredOrderToMainSystem('SUP1', 'ORD_API_1');
|
||||
expect(out.rejected).toBe(1);
|
||||
expect(markWriteback).toHaveBeenCalledWith(expect.objectContaining({ status: 'rejected' }));
|
||||
});
|
||||
|
||||
it('主系统 5xx/超时 → suspended(下轮重试)', async () => {
|
||||
writebackHttp.mockResolvedValue({ kind: 'unavailable', reason: 'HTTP 502' });
|
||||
const out = await writebackDeliveredOrderToMainSystem('SUP1', 'ORD_API_1');
|
||||
expect(out.unavailable).toBe(1);
|
||||
expect(markWriteback).toHaveBeenCalledWith(expect.objectContaining({ status: 'suspended' }));
|
||||
});
|
||||
|
||||
it('缺对照但能按商品名对上 → 惰性对照后照常回写(历史行自愈)', async () => {
|
||||
listPending.mockResolvedValue([{ ...ROW, our_order_item_id: null }]);
|
||||
const out = await writebackDeliveredOrderToMainSystem('SUP1', 'ORD_API_1');
|
||||
// 惰性对照在租户上下文里按「同单 + 同商品名」找回订单行,并回写台账
|
||||
expect(setOurOrderItemId).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ branchCode: 'SUP1', prepId: 'p1', ourOrderItemId: 'i1' })
|
||||
);
|
||||
expect(writebackHttp).toHaveBeenCalledTimes(1);
|
||||
expect(out.done).toBe(1);
|
||||
});
|
||||
|
||||
it('缺对照且名字也对不上 → 挂 suspended,不发 HTTP(不猜)', async () => {
|
||||
listPending.mockResolvedValue([{ ...ROW, our_order_item_id: null, item_name: '对不上的品' }]);
|
||||
const out = await writebackDeliveredOrderToMainSystem('SUP1', 'ORD_API_1');
|
||||
expect(writebackHttp).not.toHaveBeenCalled();
|
||||
expect(markWriteback).toHaveBeenCalledWith(expect.objectContaining({ status: 'suspended' }));
|
||||
expect(out.attempted).toBe(0);
|
||||
});
|
||||
|
||||
it('无待回写行时不发任何 HTTP', async () => {
|
||||
listPending.mockResolvedValue([]);
|
||||
const out = await writebackDeliveredOrderToMainSystem('SUP1', 'ORD_API_1');
|
||||
expect(writebackHttp).not.toHaveBeenCalled();
|
||||
expect(out.attempted).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('A3:按主系统回传的 updated / skipped 记账(2026-10-09 增量)', () => {
|
||||
beforeEach(() => {
|
||||
query.mockReset();
|
||||
writebackHttp.mockReset();
|
||||
listPending.mockReset();
|
||||
markWriteback.mockReset();
|
||||
withTenant.mockReset();
|
||||
listPending.mockResolvedValue([ROW]);
|
||||
markWriteback.mockResolvedValue(undefined);
|
||||
mockItem();
|
||||
});
|
||||
|
||||
it('updated=0 且 reason=already_completed → 记 done(幂等命中,等价成功)', async () => {
|
||||
writebackHttp.mockResolvedValue({
|
||||
kind: 'ok',
|
||||
updated: 0,
|
||||
skipped: [{ id: 'p1', skuCode: null, reason: 'already_completed', message: '该行已备货完成' }],
|
||||
needsCustomerPrice: false,
|
||||
});
|
||||
const out = await writebackDeliveredOrderToMainSystem('SUP1', 'ORD_API_1');
|
||||
expect(out.alreadyDone).toBe(1);
|
||||
expect(out.done).toBe(0);
|
||||
expect(markWriteback).toHaveBeenCalledWith(expect.objectContaining({ status: 'done' }));
|
||||
});
|
||||
|
||||
it('updated=0 且 reason=transferred_to_purchase → 记 rejected(重试无用,不再重试)', async () => {
|
||||
writebackHttp.mockResolvedValue({
|
||||
kind: 'ok',
|
||||
updated: 0,
|
||||
skipped: [{ id: 'p1', skuCode: null, reason: 'transferred_to_purchase', message: '已流转自采' }],
|
||||
needsCustomerPrice: false,
|
||||
});
|
||||
const out = await writebackDeliveredOrderToMainSystem('SUP1', 'ORD_API_1');
|
||||
expect(out.rejected).toBe(1);
|
||||
expect(markWriteback).toHaveBeenCalledWith(expect.objectContaining({ status: 'rejected' }));
|
||||
});
|
||||
|
||||
it('updated=0 且 reason=row_not_updated → 记 suspended(下轮兜底重试)', async () => {
|
||||
writebackHttp.mockResolvedValue({
|
||||
kind: 'ok',
|
||||
updated: 0,
|
||||
skipped: [{ id: 'p1', skuCode: null, reason: 'row_not_updated', message: '并发修改' }],
|
||||
needsCustomerPrice: false,
|
||||
});
|
||||
const out = await writebackDeliveredOrderToMainSystem('SUP1', 'ORD_API_1');
|
||||
expect(out.unavailable).toBe(1);
|
||||
expect(markWriteback).toHaveBeenCalledWith(expect.objectContaining({ status: 'suspended' }));
|
||||
});
|
||||
|
||||
it('updated=0 且没有任何 skipped 记录 → 绝不记 done(挂 suspended 交下轮)', async () => {
|
||||
writebackHttp.mockResolvedValue({ kind: 'ok', updated: 0, skipped: [], needsCustomerPrice: false });
|
||||
const out = await writebackDeliveredOrderToMainSystem('SUP1', 'ORD_API_1');
|
||||
expect(out.done).toBe(0);
|
||||
expect(out.unavailable).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('A3b:409 的两种含义(真实主系统实测得出)', () => {
|
||||
beforeEach(() => {
|
||||
query.mockReset();
|
||||
writebackHttp.mockReset();
|
||||
listPending.mockReset();
|
||||
markWriteback.mockReset();
|
||||
withTenant.mockReset();
|
||||
listPending.mockResolvedValue([ROW]);
|
||||
markWriteback.mockResolvedValue(undefined);
|
||||
mockItem();
|
||||
});
|
||||
|
||||
it('409「备货已确认锁定」→ already_done(结果已达成,记 done)', async () => {
|
||||
writebackHttp.mockResolvedValue({
|
||||
kind: 'already_done',
|
||||
reason: 'conflict 备货已确认锁定,不可修改(缺货标记除外)',
|
||||
});
|
||||
const out = await writebackDeliveredOrderToMainSystem('SUP1', 'ORD_API_1');
|
||||
expect(out.alreadyDone).toBe(1);
|
||||
expect(out.rejected).toBe(0);
|
||||
expect(markWriteback).toHaveBeenCalledWith(expect.objectContaining({ status: 'done' }));
|
||||
});
|
||||
|
||||
it('409「已流转自采」→ rejected(真的没写进去)', async () => {
|
||||
writebackHttp.mockResolvedValue({ kind: 'rejected', reason: 'conflict 该备货已流转自采,不可修改' });
|
||||
const out = await writebackDeliveredOrderToMainSystem('SUP1', 'ORD_API_1');
|
||||
expect(out.rejected).toBe(1);
|
||||
expect(out.alreadyDone).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
/**
|
||||
* 「未启用分拣」进入待配送(50)时的**备齐回写**(2026-10-11 修复;同日改为对所有单生效)。
|
||||
*
|
||||
* 缺口:`tryAdvanceOrderToDelivery` 有两条进入 50 的路径 ——「分拣已完成」与「未启用分拣」。
|
||||
* 前者由分拣服务在完成后调用 `enqueueMainSystemWritebackForReadyOrder`;后者**此前没有回写**
|
||||
* ⇒ 主系统「免入库」单(我方不过配送、永远不经过 50→60)只能等 15 分钟对账兜底,
|
||||
* 而主系统要 `prepare_status >= 30` 才派配送员上门 ⇒ 这段时间是实打实的空等。
|
||||
*
|
||||
* 修法:在「未启用分拣」分支补 `enqueueMainSystemWritebackForReadyOrder({ branchCode, orderCode })`
|
||||
* (非阻塞回写;判定/失败只记账、交对账兜底,绝不把推进流程带崩)。
|
||||
*
|
||||
* ⚠️ 2026-10-11 复核补记:这里**最初把两个位置参数写反了**(`(orderCode, branchCode)`),
|
||||
* 而签名是 `(branchCode, orderCode)` ⇒ 台账按"单号当分公司"查 ⇒ 0 行、静默不回写。
|
||||
* 因此三个回写触发函数统一改为**对象参数**,本用例与 `skipInboundWritebackTiming` 一起把写法钉死。
|
||||
*/
|
||||
const fulfillment = readFileSync(
|
||||
new URL('../src/services/orderWorkflowFulfillmentService.ts', import.meta.url),
|
||||
'utf8'
|
||||
);
|
||||
const writeback = readFileSync(new URL('../src/services/mainSystemWriteback.ts', import.meta.url), 'utf8');
|
||||
|
||||
describe('未启用分拣 ⇒ 进入待配送时必须备齐回写', () => {
|
||||
it('「未启用分拣」分支对所有单调用备齐回写(且在 UPDATE 之后)', () => {
|
||||
const start = fulfillment.indexOf('export async function tryAdvanceOrderToDelivery');
|
||||
const fn = fulfillment.slice(start, start + 2400);
|
||||
const disabledBranch = fn.slice(fn.indexOf('if (!pickingEnabled)'), fn.indexOf('if (status < 45)'));
|
||||
// ⚠️ 先剥注释再断言:否则"把调用注释掉"这种回退也能骗过测试(反向对照实测踩过)
|
||||
const codeOnly = disabledBranch
|
||||
.split('\n')
|
||||
.filter((line) => !line.trim().startsWith('//'))
|
||||
.join('\n');
|
||||
// 必须是**对象参数**且键名齐全:位置参数版本曾把 branch/order 传反(静默 0 行不回写)
|
||||
expect(codeOnly).toContain(
|
||||
'enqueueMainSystemWritebackForReadyOrder({ branchCode, orderCode })'
|
||||
);
|
||||
// 2026-10-11 开发者定稿:不再限免入库 —— 送仓单到待配送也要回写
|
||||
expect(codeOnly).not.toContain('enqueueSkipInboundWritebackIfReady');
|
||||
// 回写必须在 UPDATE(50) 之后(HTTP 不得在事务内)
|
||||
expect(codeOnly.indexOf('order_status = 50')).toBeLessThan(
|
||||
codeOnly.indexOf('enqueueMainSystemWritebackForReadyOrder')
|
||||
);
|
||||
});
|
||||
|
||||
it('对账兜底同样放开到"所有单 status>=50"(不再要求免入库)', () => {
|
||||
const start = writeback.indexOf('export async function retryPendingWritebacksForBranch');
|
||||
const fn = writeback.slice(start, start + 1800);
|
||||
expect(fn).toContain('if (orderStatus < 50) continue;');
|
||||
expect(fn).not.toContain('skipInbound && orderStatus >= 50');
|
||||
});
|
||||
|
||||
it('回写总开关默认开(显式 =0 才关)', () => {
|
||||
const cfg = readFileSync(new URL('../src/config.ts', import.meta.url), 'utf8');
|
||||
expect(cfg).toContain("writebackEnabled: process.env.MAIN_SYSTEM_WRITEBACK !== '0'");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,96 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
/**
|
||||
* 「收货地址」两条链路(2026-10-11 开发者提出):
|
||||
* ① 主系统分公司的**仓库地址**要自动带进我方订单(P1-10 的 `branch_address`,此前一直没消费);
|
||||
* ② 明细锁(40+)后也要能**单独改地址** —— 只写表头,不碰明细、不动状态链。
|
||||
*
|
||||
* 本文件按仓库既有做法做**源级契约**钉住(真正的行为验证走本地真库 smoke,见 docs 变更记录)。
|
||||
*/
|
||||
const orderRoutes = readFileSync(
|
||||
new URL('../src/modules/workflow/routes/orderRoutes.ts', import.meta.url),
|
||||
'utf8'
|
||||
);
|
||||
const manageService = readFileSync(
|
||||
new URL('../src/services/orderManageItemsService.ts', import.meta.url),
|
||||
'utf8'
|
||||
);
|
||||
const importService = readFileSync(
|
||||
new URL('../src/services/mainSystemOrderImport.ts', import.meta.url),
|
||||
'utf8'
|
||||
);
|
||||
const prepApi = readFileSync(
|
||||
new URL('../src/services/mainSystem/api/preparations.ts', import.meta.url),
|
||||
'utf8'
|
||||
);
|
||||
const webhookRoutes = readFileSync(
|
||||
new URL('../src/routes/mainSystemIntegration.ts', import.meta.url),
|
||||
'utf8'
|
||||
);
|
||||
|
||||
describe('单独改收货地址:路由与门槛', () => {
|
||||
it('路由存在且与配送日路由分离(不是管理员专用)', () => {
|
||||
expect(orderRoutes).toContain("router.patch('/orders/:orderCode/delivery-address'");
|
||||
const start = orderRoutes.indexOf("router.patch('/orders/:orderCode/delivery-address'");
|
||||
const route = orderRoutes.slice(start, orderRoutes.indexOf('\nrouter.', start + 10));
|
||||
// 权限:能编辑订单的人都能改地址;不得出现"仅管理员"的 403 分支
|
||||
for (const code of ['order_edit', 'order_entry', 'order_manage', 'allocation_manage']) {
|
||||
expect(route).toContain(`'${code}'`);
|
||||
}
|
||||
expect(route).not.toContain('仅管理员');
|
||||
expect(route).toContain('assertOrderCodeAccess');
|
||||
expect(route).toContain('updateOrderDeliveryAddress');
|
||||
});
|
||||
|
||||
it('服务只写表头:不动明细、不推进状态链', () => {
|
||||
const start = manageService.indexOf('export async function updateOrderDeliveryAddress');
|
||||
const fn = manageService.slice(start, start + 4200);
|
||||
expect(fn).toContain('export async function updateOrderDeliveryAddress');
|
||||
expect(fn).toContain('UPDATE orders SET delivery_address = $1');
|
||||
// 明细与状态链:这段代码里一个字都不许出现
|
||||
expect(fn).not.toContain('order_items');
|
||||
expect(fn).not.toContain('UPDATE orders SET order_status');
|
||||
expect(fn).not.toContain('advanceOrderWorkflow');
|
||||
});
|
||||
|
||||
it('终态与垃圾桶分别拒:>=90 与 order_trashed', () => {
|
||||
const start = manageService.indexOf('export async function updateOrderDeliveryAddress');
|
||||
const fn = manageService.slice(start, start + 4200);
|
||||
expect(fn).toContain('status >= 90');
|
||||
expect(fn).toContain("code: 'invalid_status'");
|
||||
expect(fn).toContain("code: 'order_trashed'");
|
||||
expect(fn).toContain('order_delivery_address_edit');
|
||||
});
|
||||
});
|
||||
|
||||
describe('主系统仓库地址(P1-10):带进我方订单', () => {
|
||||
it('备货行模型与映射都读 branch_name / branch_address(拉取与 webhook 同口径)', () => {
|
||||
expect(prepApi).toContain('branchName: string | null;');
|
||||
expect(prepApi).toContain('branchAddress: string | null;');
|
||||
expect(prepApi).toContain('branchName: raw?.branch_name');
|
||||
expect(prepApi).toContain('branchAddress:');
|
||||
expect(prepApi).toContain('raw?.branch_address');
|
||||
expect(webhookRoutes).toContain('raw?.branch_address');
|
||||
});
|
||||
|
||||
it('导入建单时仓库地址优先:mainBranchAddress 进 resolveImportDeliveryAddress 且排在最前', () => {
|
||||
expect(importService).toContain('mainBranchAddress');
|
||||
const start = importService.indexOf('async function resolveImportDeliveryAddress');
|
||||
const fn = importService.slice(start, start + 2200);
|
||||
// 主系统地址命中即返回(在客户档案/上次填写之前)
|
||||
const mainHit = fn.indexOf('if (mainBranchAddress)');
|
||||
const customerHit = fn.indexOf('FROM customers c');
|
||||
expect(mainHit).toBeGreaterThan(0);
|
||||
expect(customerHit).toBeGreaterThan(mainHit);
|
||||
// 建单调用点确实把当日首行的分公司地址传了进去
|
||||
expect(importService).toContain('mainBranchAddress:');
|
||||
expect(importService).toMatch(/allRows\.find\(\(row\) => row\.branchAddress\)/);
|
||||
});
|
||||
|
||||
it('只补空的客户档案地址,不覆盖人工维护过的地址', () => {
|
||||
const start = importService.indexOf('async function resolveImportDeliveryAddress');
|
||||
const fn = importService.slice(start, start + 2200);
|
||||
expect(fn).toContain("NULLIF(TRIM(COALESCE(address, '')), '') IS NULL");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,122 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { mapOrderPrepRowsToOurItems } from '../src/services/mainSystemPrepLedger';
|
||||
|
||||
/**
|
||||
* 整单(跨主系统单)一对一对照(2026-10-11 修复)。
|
||||
*
|
||||
* 实测缺陷:一张我方订单由多张主系统单合并而来,同名商品会在多张单里各出现一次
|
||||
* (`…_0006` 肉片 3.5 斤 / `…_0007` 肉片 6 斤)。旧实现**按单各算一次** ⇒ 两张单都认领同一条订单行,
|
||||
* 后一张单的行永远配不上 ⇒ 详情掉进「本系统录单」、台账两条备货行指向同一订单行、回写把 3.5 写成 6。
|
||||
*/
|
||||
const ourItems = [
|
||||
{ id: 'item-meat-6', item_name: '肉片', quantity: 6 },
|
||||
{ id: 'item-meat-35', item_name: '肉片', quantity: 3.5 },
|
||||
{ id: 'item-pork', item_name: '五花肉', quantity: 20 },
|
||||
];
|
||||
|
||||
describe('整单对照:一对一、不重复认领', () => {
|
||||
it('同名商品跨两张主系统单 ⇒ 按数量配对到各自的订单行(实测用例)', () => {
|
||||
const mapping = mapOrderPrepRowsToOurItems(
|
||||
[
|
||||
{ orderCode: 'ORD_WEB_..._0006', rows: [{ id: 'prep-35', itemName: '肉片', prepareQty: 3.5 }] },
|
||||
{ orderCode: 'ORD_WEB_..._0007', rows: [{ id: 'prep-6', itemName: '肉片', prepareQty: 6 }] },
|
||||
],
|
||||
ourItems
|
||||
);
|
||||
expect(mapping.get('prep-35')).toBe('item-meat-35');
|
||||
expect(mapping.get('prep-6')).toBe('item-meat-6');
|
||||
expect(new Set(mapping.values()).size).toBe(2); // 一对一:不得复用同一条订单行
|
||||
});
|
||||
|
||||
it('数量缺失时退回出现次序,仍是一对一', () => {
|
||||
const mapping = mapOrderPrepRowsToOurItems(
|
||||
[
|
||||
{ orderCode: 'A', rows: [{ id: 'p1', itemName: '肉片', prepareQty: null }] },
|
||||
{ orderCode: 'B', rows: [{ id: 'p2', itemName: '肉片', prepareQty: null }] },
|
||||
],
|
||||
ourItems
|
||||
);
|
||||
expect(mapping.get('p1')).toBe('item-meat-6');
|
||||
expect(mapping.get('p2')).toBe('item-meat-35');
|
||||
});
|
||||
|
||||
it('缺货行不占位;同名行按剩余候选依次配;用完即留空(绝不复用)', () => {
|
||||
const mapping = mapOrderPrepRowsToOurItems(
|
||||
[
|
||||
{
|
||||
orderCode: 'A',
|
||||
rows: [
|
||||
{ id: 'stockout', itemName: '肉片', prepareQty: 6, isStockout: true },
|
||||
{ id: 'real', itemName: '肉片', prepareQty: 6 },
|
||||
{ id: 'second', itemName: '肉片', prepareQty: 9 },
|
||||
{ id: 'third', itemName: '肉片', prepareQty: 12 },
|
||||
{ id: 'unknown', itemName: '不存在的商品', prepareQty: 1 },
|
||||
],
|
||||
},
|
||||
],
|
||||
ourItems
|
||||
);
|
||||
expect(mapping.has('stockout')).toBe(false); // 缺货行不占匹配位
|
||||
expect(mapping.get('real')).toBe('item-meat-6'); // 数量吻合优先
|
||||
expect(mapping.get('second')).toBe('item-meat-35'); // 剩哪条配哪条(旧口径"出现次序")
|
||||
expect(mapping.has('third')).toBe(false); // 我方同名行已用完 ⇒ 留空,不猜
|
||||
expect(mapping.has('unknown')).toBe(false);
|
||||
expect(new Set(mapping.values()).size).toBe(mapping.size); // 全局一对一
|
||||
});
|
||||
|
||||
it('不同商品各走各的桶', () => {
|
||||
const mapping = mapOrderPrepRowsToOurItems(
|
||||
[
|
||||
{
|
||||
orderCode: 'A',
|
||||
rows: [
|
||||
{ id: 'p-meat', itemName: '肉片', prepareQty: 3.5 },
|
||||
{ id: 'p-pork', itemName: '五花肉', prepareQty: 20 },
|
||||
],
|
||||
},
|
||||
],
|
||||
ourItems
|
||||
);
|
||||
expect(mapping.get('p-meat')).toBe('item-meat-35');
|
||||
expect(mapping.get('p-pork')).toBe('item-pork');
|
||||
});
|
||||
});
|
||||
|
||||
describe('导入链路必须整单算一次对照(防回退)', () => {
|
||||
const importSrc = readFileSync(
|
||||
path.join(__dirname, '../src/services/mainSystemOrderImport.ts'),
|
||||
'utf8'
|
||||
);
|
||||
const ledgerSrc = readFileSync(
|
||||
path.join(__dirname, '../src/services/mainSystemPrepLedger.ts'),
|
||||
'utf8'
|
||||
);
|
||||
|
||||
it('persistRows 算一次整单对照,同时喂给台账与来源单号落列', () => {
|
||||
const idx = importSrc.indexOf('const persistRows');
|
||||
const body = importSrc.slice(idx, idx + 3000);
|
||||
expect(body).toMatch(/mapOrderPrepRowsToOurItems\(/);
|
||||
expect(body).toMatch(/mapping: orderMapping/);
|
||||
expect(body).toMatch(/stampMainOrderCodes\(\{[^}]*mapping: orderMapping/s);
|
||||
// 台账写入必须用同一份对照(不得再按单各算一次)
|
||||
expect(body).not.toMatch(/recordImportedPrepItems\(\{[\s\S]{0,400}?mapPrepRowsToOurItems\(/);
|
||||
});
|
||||
|
||||
it('台账写入优先用外部传入的对照', () => {
|
||||
const idx = ledgerSrc.indexOf('export async function recordImportedPrepItems');
|
||||
const body = ledgerSrc.slice(idx, idx + 1200);
|
||||
expect(body).toMatch(/params\.mapping \?\?/);
|
||||
});
|
||||
|
||||
it('存量错值有纠正入口,且纠正规则保守(只动 NULL / 重复认领)', () => {
|
||||
const idx = ledgerSrc.indexOf('export async function healOrderPrepMapping');
|
||||
expect(idx).toBeGreaterThan(-1);
|
||||
const body = ledgerSrc.slice(idx, idx + 4000);
|
||||
expect(body).toMatch(/duplicated\.has\(stored\)/);
|
||||
expect(body).toMatch(/if \(!shouldBe\) continue;/);
|
||||
// 必须挂进导入链路,否则错值不会自愈
|
||||
expect(importSrc).toMatch(/healOrderPrepMapping\(/);
|
||||
});
|
||||
});
|
||||
@@ -105,3 +105,25 @@ describe('order list allocation hint', () => {
|
||||
expect(pickDisplayOrderStatus(30, 20, facts, 'none')).toBe(30);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 主系统「免入库」单在 50 的**副文案**口径(2026-10-11 开发者定稿):
|
||||
* 我方不派车、货由主系统骑手上门取走 ⇒ 副文案必须与徽标「待取货」同口径,
|
||||
* 不得再写「待配送员开始配送」(张冠李戴)。
|
||||
*/
|
||||
describe('免入库单 50 副文案', () => {
|
||||
const facts = baseFacts({ allocationFulfilled: true });
|
||||
|
||||
it('免入库:待主系统骑手上门取货', () => {
|
||||
expect(buildProgressStatusHint(50, 'passed', facts, undefined, true, true)).toBe(
|
||||
'待主系统骑手上门取货'
|
||||
);
|
||||
});
|
||||
|
||||
it('送仓/自建单:仍是待配送员开始配送(skipInbound 缺省或 false 不得改口径)', () => {
|
||||
expect(buildProgressStatusHint(50, 'passed', facts, undefined, true)).toBe('待配送员开始配送');
|
||||
expect(buildProgressStatusHint(50, 'passed', facts, undefined, true, false)).toBe(
|
||||
'待配送员开始配送'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
/**
|
||||
* 分拣员下拉:**范围不变,标出角色**(开发者 2026-10-11 报障后选定的口径)。
|
||||
*
|
||||
* 报障原文:「本地的分拣存在bug 不存在分拣员时 怎么将配送员当成了分拣员处理可以选择了」。
|
||||
* 排查结论(实测):**不是回退**,而是迁移 `20260725_picking_manage_permission.sql` 一开始就把
|
||||
* `picking_manage` 授给了 `delivery` 角色(配送员兼分拣),所以"勾了分拣出库的配送员"本就在分拣池里;
|
||||
* 本地又**没有任何 picker 账号**,于是下拉里只有配送员。
|
||||
*
|
||||
* 采纳口径:**保留配送员可被分配**(否则本地下拉会空、无法分配),但在下拉里标出角色,
|
||||
* 避免被误认成专责分拣员。角色名复用既有 i18n(`layout.role.*`),**不新增小字**。
|
||||
*/
|
||||
const pickingService = readFileSync(
|
||||
new URL('../src/services/pickingService.ts', import.meta.url),
|
||||
'utf8'
|
||||
);
|
||||
const pickingPage = readFileSync(
|
||||
new URL('../../src/pages/picking/PickingManagement.tsx', import.meta.url),
|
||||
'utf8'
|
||||
);
|
||||
const pickingTypes = readFileSync(new URL('../../src/utils/picking.ts', import.meta.url), 'utf8');
|
||||
|
||||
describe('分拣池:角色随行返回(供界面标注)', () => {
|
||||
it('取人 SQL:白名单**只含仓内作业角色**(配送员不得被当分拣员分配)', () => {
|
||||
const start = pickingService.indexOf('export async function listPickingAssignees');
|
||||
const fn = pickingService.slice(start, start + 1800);
|
||||
expect(fn).toContain("ARRAY['picker', 'warehouse']::text[]");
|
||||
expect(fn).not.toContain("'delivery'");
|
||||
expect(fn).toContain("perm.permission_code = 'picking_manage'");
|
||||
});
|
||||
|
||||
it('返回值带 roles(一次聚合,不额外查库)', () => {
|
||||
const start = pickingService.indexOf('export async function listPickingAssignees');
|
||||
const fn = pickingService.slice(start, start + 2600);
|
||||
expect(fn).toContain("string_agg(DISTINCT ur.role::text, ',' ORDER BY ur.role::text) AS roles");
|
||||
expect(fn).toContain("String(row.roles || '')");
|
||||
expect(pickingService).toContain('roles: string[];');
|
||||
});
|
||||
});
|
||||
|
||||
describe('分拣员下拉:标注角色', () => {
|
||||
it('统一走 assigneeLabel,且角色名用既有 i18n key', () => {
|
||||
expect(pickingPage).toContain('function assigneeLabel(');
|
||||
expect(pickingPage).toContain('buildRoleLabelResolver');
|
||||
// 「layout.role.* 只在统一解析器里拼接」由 src/utils/roleLabel.test.ts 全局钉住;
|
||||
// 这里只确认本页确实走了那个解析器,没有自己拼 key。
|
||||
expect(pickingPage).toContain('roleLabel(role)');
|
||||
const uses = pickingPage.split('assigneeLabel(user, roleLabel)').length - 1;
|
||||
expect(uses).toBe(3);
|
||||
expect(pickingPage).not.toMatch(/<option key=\{user\.id\} value=\{user\.id\}>\s*\{user\.display_name\}/);
|
||||
});
|
||||
|
||||
it('前端类型声明 roles 可选(后端老版本仍兼容)', () => {
|
||||
expect(pickingTypes).toContain('roles?: string[];');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
/**
|
||||
* 自采列表改销售价:**统一分流**(开发者 2026-10-11 定稿)。
|
||||
*
|
||||
* 事故:自采列表保存销售价 → 命中"主系统分配行改价必须走审核"守卫 → 直接抛错 →
|
||||
* 界面表现为"改不动/保存无效"。修法:守卫不再直接抛,改为**提交改价申请**:
|
||||
* · 免审(补价 0→正常价 / 改低 / 减量)⇒ 主系统当场生效、我方同步落地 ⇒ 继续原写入(同值幂等);
|
||||
* · 需审(涨价 / 加量)⇒ 提交后**本地不变**,抛说明性错误(界面提示"已提交待审")。
|
||||
*/
|
||||
const src = readFileSync(new URL('../src/services/purchaseLinkedSalePriceService.ts', import.meta.url), 'utf8');
|
||||
const guard = src.slice(src.indexOf('跨系统改价审核守卫'), src.indexOf('const quantity = Number(before.rows[0].quantity)'));
|
||||
|
||||
describe('销售价写入:主系统分配行的统一分流', () => {
|
||||
it('命中守卫时提交改价申请(不再直接 assert 抛错)', () => {
|
||||
expect(src).toContain("import { submitPriceQtyRequest } from './mainSystemPriceQtyRequest'");
|
||||
expect(guard).toContain('await submitPriceQtyRequest(');
|
||||
expect(guard).not.toContain('assertMainSystemPriceQtyReviewed(');
|
||||
});
|
||||
|
||||
it('三种结果都有明确处置:提交失败 / 待审 / 免审放行', () => {
|
||||
expect(guard).toContain("if (outcome.kind !== 'ok')");
|
||||
expect(guard).toContain('改价申请提交失败,本次未改动价格');
|
||||
expect(guard).toContain("if (outcome.status !== 'applied')");
|
||||
expect(guard).toContain('已提交改价申请,等待主系统审核(本地价格暂不变动)');
|
||||
// 免审 ⇒ 继续走原写入(注释即口径)
|
||||
expect(guard).toContain('免审已生效 ⇒ 落到下面的原写入');
|
||||
});
|
||||
|
||||
it('我方自建行不受影响(守卫只在"主系统订单"命中时才分流)', () => {
|
||||
expect(guard).toContain('FROM public.main_system_order_imports');
|
||||
expect(guard).toContain('if (mainSystemOrder.rowCount) {');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
/**
|
||||
* §8.7 自采入库实收回写订单(开发者 2026-10-11 定稿)。
|
||||
*
|
||||
* 事故:订单 `…SUP37831443_0002` 的「八角」自采入库录 0.6,订单详情仍显示 0.5(= 计划量)。
|
||||
* 根因:详情页「实收数量」读 `inspections.actual_qty`(其次 `picking_items.loaded_qty`),
|
||||
* 而自采入库写的是第三张表 `self_purchase_stock_inbounds`,两者无关联。
|
||||
* 口径:入库成功后经 `inspection_id → inspections.order_item_id` **唯一定位**订单行,
|
||||
* 把该验收记录的 `actual_qty` 更新为入库数量;定位不到 ⇒ 跳过并记日志(不猜)。
|
||||
*/
|
||||
const src = readFileSync(
|
||||
new URL('../src/services/selfPurchaseStockInboundService.ts', import.meta.url),
|
||||
'utf8'
|
||||
);
|
||||
const fn = src.slice(
|
||||
src.indexOf('export async function createSelfPurchaseStockInbound'),
|
||||
src.indexOf('void writeAuditLog', src.indexOf('export async function createSelfPurchaseStockInbound'))
|
||||
);
|
||||
|
||||
describe('自采入库 → 订单实收回写', () => {
|
||||
it('经 inspection_id 唯一定位订单行后回写 inspections.actual_qty', () => {
|
||||
expect(fn).toContain('SELECT order_item_id FROM inspections WHERE id = $1::uuid');
|
||||
expect(fn).toContain('UPDATE inspections SET actual_qty = $2 WHERE id = $1::uuid');
|
||||
expect(fn).toContain('actualQtyWrittenBack = true');
|
||||
});
|
||||
|
||||
it('回写必须晚于入库 INSERT、且在同一次 COMMIT 之前(同一事务)', () => {
|
||||
const insertIdx = fn.indexOf('INSERT INTO self_purchase_stock_inbounds');
|
||||
const wbIdx = fn.indexOf('UPDATE inspections SET actual_qty');
|
||||
// 取**回写之后**的那次 COMMIT(函数里前面还有别的提交点)
|
||||
const commitIdx = fn.indexOf("if (owns) await client.query('COMMIT')", wbIdx);
|
||||
expect(insertIdx).toBeGreaterThan(-1);
|
||||
expect(wbIdx).toBeGreaterThan(insertIdx);
|
||||
expect(commitIdx).toBeGreaterThan(wbIdx);
|
||||
});
|
||||
|
||||
it('定位不到订单行 ⇒ 跳过 + 记日志(独立/称台入库不回写)', () => {
|
||||
expect(fn).toContain('未关联订单行(独立/称台入库),本次不回写订单实收');
|
||||
});
|
||||
|
||||
it('回写失败不阻断入库', () => {
|
||||
expect(fn).toContain('订单实收回写失败(不影响入库)');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,207 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
/**
|
||||
* S4:免入库回写时机 + 分支覆盖(2026-10-10,设计文档
|
||||
* `docs/design/20261010-第三方订单履约事件接收端与免入库回写时机.md` §3.4)。
|
||||
*
|
||||
* 要钉住的四件事(任何一条被改回去都会让链路重新死锁):
|
||||
* ① 免入库订单在**未启用分拣**时也有分支(原实现只有分拣那条路,见 F5);
|
||||
* ② 新口径下分拣完毕**停在 50 等主系统确认发车**,不是直接结案 90;
|
||||
* ③ 回写 `status=30` 必须在**事务提交后**触发(HTTP 永不在事务内);
|
||||
* ④ 配送任务的公共入口对免入库订单**不建任务**(一个卡点覆盖 8+ 调用方)。
|
||||
*/
|
||||
|
||||
const picking = readFileSync(path.join(__dirname, '../src/services/pickingService.ts'), 'utf8');
|
||||
const workflow = readFileSync(
|
||||
path.join(__dirname, '../src/services/orderWorkflowFulfillmentService.ts'),
|
||||
'utf8'
|
||||
);
|
||||
const writeback = readFileSync(path.join(__dirname, '../src/services/mainSystemWriteback.ts'), 'utf8');
|
||||
|
||||
describe('① 分拣分支:新旧两种口径都在,且由开关切换', () => {
|
||||
it('新口径:停在 50 等主系统确认发车(不结案)', () => {
|
||||
expect(picking).toMatch(/skipInboundAwaitPickup/);
|
||||
expect(picking).toMatch(/skipInboundAwaitingPickup:\s*true/);
|
||||
// 必须明确写出"停在 50"的语义,而不是拿别的东西冒充
|
||||
expect(picking).toMatch(/等主系统确认发车|等主系统取货/);
|
||||
});
|
||||
|
||||
it('旧口径保留:开关关闭时仍"分拣完毕即结案 90"', () => {
|
||||
expect(picking).toMatch(/completeOrderWithoutDriverDelivery\(orderCode, client\)/);
|
||||
});
|
||||
|
||||
it('两条口径都先走既有边 45→50(结案入口只接受 30/50)', () => {
|
||||
expect(picking).toMatch(
|
||||
/UPDATE orders SET order_status = 50 WHERE order_code = \$1 AND order_status = 45/
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('② 回写在事务提交后触发(HTTP 永不在事务内)', () => {
|
||||
it('enqueueMainSystemWritebackForReadyOrder 的**调用**出现在 COMMIT 之后', () => {
|
||||
// 先剥掉 import 行:否则 indexOf 命中的是 import 语句,而不是真正的调用点
|
||||
const body = picking
|
||||
.split('\n')
|
||||
.filter((line) => !/^\s*import\b/.test(line))
|
||||
.join('\n');
|
||||
const commitIdx = body.indexOf("await client.query('COMMIT')");
|
||||
const enqueueIdx = body.indexOf('enqueueMainSystemWritebackForReadyOrder({');
|
||||
expect(commitIdx).toBeGreaterThan(-1);
|
||||
expect(enqueueIdx).toBeGreaterThan(-1);
|
||||
expect(enqueueIdx).toBeGreaterThan(commitIdx);
|
||||
});
|
||||
|
||||
it('三个回写触发函数只接受对象参数(防 branch/order 位置传反)', () => {
|
||||
/**
|
||||
* 2026-10-11 复核抓到的**真实缺陷**:
|
||||
* `orderWorkflowFulfillmentService.tryAdvanceOrderToDelivery` 里写成了
|
||||
* `enqueueMainSystemWritebackForReadyOrder(orderCode, branchCode)` —— 与签名 `(branchCode, orderCode)`
|
||||
* 正好相反 ⇒ 台账按 (单号当分公司, 分公司当单号) 查 ⇒ **0 行、静默不回写**(不抛错、不写日志)。
|
||||
* 两个参数同为 `string`,TS 结构上拦不住 ⇒ 统一改**对象参数**,并用本用例钉死。
|
||||
*/
|
||||
expect(writeback).toMatch(
|
||||
/export function enqueueMainSystemWritebackForReadyOrder\(params: \{\s*branchCode: string \| null;\s*orderCode: string;\s*\}\)/
|
||||
);
|
||||
expect(writeback).toMatch(
|
||||
/export function enqueueMainSystemWritebackForDeliveredOrder\(params: \{\s*branchCode: string \| null;\s*orderCode: string;\s*\}\)/
|
||||
);
|
||||
expect(writeback).toMatch(/export async function enqueueSkipInboundWritebackIfReady\(\s*params: \{/);
|
||||
|
||||
const others = [
|
||||
['orderWorkflowFulfillmentService', workflow],
|
||||
['pickingService', picking],
|
||||
['mainSystemWriteback', writeback],
|
||||
[
|
||||
'processingTaskService',
|
||||
readFileSync(path.join(__dirname, '../src/services/processingTaskService.ts'), 'utf8'),
|
||||
],
|
||||
[
|
||||
'preparationFulfillmentService',
|
||||
readFileSync(path.join(__dirname, '../src/services/preparationFulfillmentService.ts'), 'utf8'),
|
||||
],
|
||||
] as const;
|
||||
for (const [name, src] of others) {
|
||||
const args = [
|
||||
...src.matchAll(/enqueueMainSystemWritebackFor(?:Ready|Delivered)Order\(([^)]*)/g),
|
||||
...src.matchAll(/enqueueSkipInboundWritebackIfReady\(([^)]*)/g),
|
||||
].map((m) => m[1].trim());
|
||||
for (const arg of args) {
|
||||
// 定义处写作 `params: {`,调用处必须是 `{ ... }` 对象实参
|
||||
if (arg.startsWith('params:')) continue;
|
||||
expect(arg.startsWith('{'), `${name}: 回写触发必须用对象实参,禁止位置参数`).toBe(true);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('回写触发点是"货备齐",不是 50→60(免入库不走发车)', () => {
|
||||
expect(writeback).toMatch(/export function enqueueMainSystemWritebackForReadyOrder/);
|
||||
// 两处触发共存:发车(送仓)与备齐(免入库)
|
||||
expect(writeback).toMatch(/export function enqueueMainSystemWritebackForDeliveredOrder/);
|
||||
});
|
||||
|
||||
it('兜底重试对"已到待配送(50)"放行(2026-10-11 起对**所有单**,不再限免入库)', () => {
|
||||
const retryIdx = writeback.indexOf('export async function retryPendingWritebacksForBranch');
|
||||
expect(retryIdx).toBeGreaterThan(-1);
|
||||
const fn = writeback.slice(retryIdx, retryIdx + 1800);
|
||||
// 开发者 2026-10-11 定稿:不论送仓还是免入库,到 50 就该回写 status=30
|
||||
expect(fn).toContain('if (orderStatus < 50) continue;');
|
||||
// 老的"仅免入库放行 50"判据已废弃
|
||||
expect(fn).not.toMatch(/skipInbound\s*&&\s*orderStatus\s*>=\s*50/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('②b 覆盖**所有**把免入库单推到 50 的路径(不能只修一半)', () => {
|
||||
const processing = readFileSync(
|
||||
path.join(__dirname, '../src/services/processingTaskService.ts'),
|
||||
'utf8'
|
||||
);
|
||||
const prepFulfillment = readFileSync(
|
||||
path.join(__dirname, '../src/services/preparationFulfillmentService.ts'),
|
||||
'utf8'
|
||||
);
|
||||
|
||||
it('未启用分拣的 40→50(processingTaskService)挂了回写 —— 这是供应商分公司的**实际默认路径**', () => {
|
||||
// 实测:SUP37831443 / SUP92185841 分拣=关、库存抵扣=开 ⇒ 免入库单走的就是这一条
|
||||
const idx = processing.indexOf('if (!pickingEnabled)');
|
||||
expect(idx).toBeGreaterThan(-1);
|
||||
const branch = processing.slice(idx, idx + 1200);
|
||||
expect(branch).toMatch(/order_status = 50/);
|
||||
expect(branch, '未启用分拣分支缺回写触发').toMatch(/enqueueSkipInboundWritebackIfReady/);
|
||||
});
|
||||
|
||||
it('免入库+有缺口的 30→50(preparationFulfillmentService)挂了回写', () => {
|
||||
const idx = prepFulfillment.indexOf('直送免入库已齐套');
|
||||
expect(idx).toBeGreaterThan(-1);
|
||||
const around = prepFulfillment.slice(Math.max(0, idx - 900), idx);
|
||||
expect(around).toMatch(/enqueueSkipInboundWritebackIfReady/);
|
||||
// 且必须只在无外层事务时触发(HTTP 不能早于提交)
|
||||
expect(around).toMatch(/if \(!client\)/);
|
||||
});
|
||||
|
||||
it('分拣路径(pickingService)仍挂回写,且在 COMMIT 之后', () => {
|
||||
const body = picking
|
||||
.split('\n')
|
||||
.filter((line) => !/^\s*import\b/.test(line))
|
||||
.join('\n');
|
||||
expect(body.indexOf('enqueueMainSystemWritebackForReadyOrder({')).toBeGreaterThan(
|
||||
body.indexOf("await client.query('COMMIT')")
|
||||
);
|
||||
});
|
||||
|
||||
it('漏掉的路径仍有对账兜底:任何单到 50 都允许回写', () => {
|
||||
const retryIdx = writeback.indexOf('export async function retryPendingWritebacksForBranch');
|
||||
expect(writeback.slice(retryIdx, retryIdx + 1800)).toContain('if (orderStatus < 50) continue;');
|
||||
});
|
||||
});
|
||||
|
||||
describe('③ 配送任务:整单免入库不建任务(公共入口一处兜住)', () => {
|
||||
it('守卫在 ensureDeliveryTaskForOrder 内,且**不依赖**任何配置开关', () => {
|
||||
const fnIdx = workflow.indexOf('export async function ensureDeliveryTaskForOrder');
|
||||
expect(fnIdx).toBeGreaterThan(-1);
|
||||
const body = workflow.slice(fnIdx, fnIdx + 3000);
|
||||
expect(body).toMatch(/isOrderFullySkipInbound/);
|
||||
// 与"全单直送"同一卡点(同一位置兜住所有调用方)
|
||||
expect(body).toMatch(/isOrderOnlyDirectDelivery/);
|
||||
// ⚠️ 2026-10-11:守卫与 `MAIN_SYSTEM_SKIP_INBOUND_AWAIT_PICKUP` **解耦** ——
|
||||
// 那个开关只管"停 50 等主系统发车才收口",按回滚指引写 0 不得把配送任务放回来。
|
||||
expect(body).not.toMatch(/skipInboundAwaitPickup/);
|
||||
});
|
||||
|
||||
it('判定是 bool_and(整单全免入库),混合单必须按送仓处理', () => {
|
||||
const ledger = readFileSync(path.join(__dirname, '../src/services/mainSystemPrepLedger.ts'), 'utf8');
|
||||
const idx = ledger.indexOf('export async function isOrderFullySkipInbound');
|
||||
expect(idx).toBeGreaterThan(-1);
|
||||
const body = ledger.slice(idx, idx + 1600);
|
||||
expect(body).toMatch(/bool_and\(COALESCE\(payload->>'skipInbound', 'false'\) = 'true'\)/);
|
||||
// 退回 bool_or 会把混合单误判成免入库 ⇒ 送仓部分没有配送任务
|
||||
expect(body).not.toMatch(/bool_or/);
|
||||
});
|
||||
|
||||
it('唯一绕过公共卡点的创建点(客户绑定配送员回填)也必须排除整单免入库', () => {
|
||||
const binding = readFileSync(
|
||||
path.join(__dirname, '../src/services/customerDeliveryBindingService.ts'),
|
||||
'utf8'
|
||||
);
|
||||
const idx = binding.indexOf('INSERT INTO delivery_tasks');
|
||||
expect(idx).toBeGreaterThan(-1);
|
||||
const stmt = binding.slice(idx, idx + 2000);
|
||||
// 复用台账里那份同语义 SQL,禁止在业务代码里另写一套免入库判据
|
||||
expect(stmt).toMatch(/fullySkipInboundOrderExistsSql/);
|
||||
expect(stmt).toMatch(/NOT EXISTS/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('④ 不新增状态边、不碰财务口径', () => {
|
||||
it('pickingService 未出现裸写 order_status 的新目标值', () => {
|
||||
// 只允许 50(既有边 45→50);不得出现 60/90 的裸写
|
||||
const bare = [...picking.matchAll(/UPDATE orders SET order_status = (\d+)/g)].map((m) => m[1]);
|
||||
expect(bare.every((v) => v === '50')).toBe(true);
|
||||
});
|
||||
|
||||
it('接收端与分拣改动都不触碰库存/成本表', () => {
|
||||
expect(picking).not.toMatch(/INSERT INTO inventory_logs|UPDATE inventory_logs/);
|
||||
expect(writeback).not.toMatch(/INSERT INTO inventory_logs|UPDATE inventory_logs/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { ORDER_STATUS_ALLOWED, ORDER_STATUS_NEXT } from '../src/modules/kernel/orderStatus';
|
||||
|
||||
/**
|
||||
* 冻结面改造的**源码合同**(2026-10-09,设计文档 20261009-供应商侧库存抵扣与免入库推进方案.md):
|
||||
* B1 修复:库存全额抵扣的订单不得被判成"直送齐套"直接结案 90(货还在我们仓里,必须出库配送);
|
||||
* B2 新增:主系统「免入库」订单在分拣完毕即结案,跳过配送且不建配送任务;
|
||||
* 两条都**不得新增状态边** —— 状态链常量逐项钉死。
|
||||
*/
|
||||
|
||||
const read = (p: string) => readFileSync(path.join(__dirname, '..', p), 'utf8');
|
||||
|
||||
describe('状态链未被本次改造触碰', () => {
|
||||
it('主链与允许边逐项一致(无新增边)', () => {
|
||||
expect(ORDER_STATUS_NEXT).toEqual({ 20: 30, 30: 40, 40: 45, 45: 50, 50: 60, 60: 90 });
|
||||
expect(ORDER_STATUS_ALLOWED).toEqual({ 20: [30], 30: [40], 40: [45, 30], 45: [50], 50: [60], 60: [90] });
|
||||
});
|
||||
});
|
||||
|
||||
describe('B1:齐套结案分支必须以「全部行商品直送」为前提', () => {
|
||||
const src = read('src/services/preparationFulfillmentService.ts');
|
||||
|
||||
it('结案分支同时要求 nonDirectCount === 0(防止库存抵扣行被误结案)', () => {
|
||||
expect(src).toMatch(/nonDirectCount === 0 && Number\(driverNeeded\.rows\[0\]\?\.cnt \|\| 0\) === 0/);
|
||||
});
|
||||
|
||||
it('coverage 查询里有 non_direct_count(非直送行数,不加缺口条件)', () => {
|
||||
expect(src).toMatch(/AS non_direct_count/);
|
||||
expect(src).toMatch(/const nonDirectCount = Number\(coverage\.rows\[0\]\?\.non_direct_count \|\| 0\)/);
|
||||
});
|
||||
|
||||
it('非直送行 > 0 且无免入库缺口行时**落到尾部 30→40**,不得原地返回卡单', () => {
|
||||
// 分支体内只有"免入库有缺口 → 50"这一条早退;库存抵扣行走尾部
|
||||
expect(src).toMatch(/if \(Number\(driverNeeded\.rows\[0\]\?\.cnt \|\| 0\) > 0\) \{/);
|
||||
expect(src).toMatch(/UPDATE orders SET order_status = 40 WHERE order_code = \$1 AND order_status = 30/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('B2:主系统免入库 → 分拣完毕即结案、跳过配送', () => {
|
||||
const src = read('src/services/pickingService.ts');
|
||||
|
||||
it('分拣收尾里按台账判定免入库并直接结案', () => {
|
||||
expect(src).toMatch(/isOrderFullySkipInbound/);
|
||||
expect(src).toMatch(/completeOrderWithoutDriverDelivery\(orderCode, client\)/);
|
||||
});
|
||||
|
||||
it('结案前先走既有边 45→50(结案入口只接受 30/50)', () => {
|
||||
expect(src).toMatch(/UPDATE orders SET order_status = 50 WHERE order_code = \$1 AND order_status = 45/);
|
||||
});
|
||||
|
||||
it('已结案订单不再建配送任务(避免 90 的孤儿任务)', () => {
|
||||
expect(src).toMatch(/const st = await pool\.query\(`SELECT order_status FROM orders WHERE order_code = \$1`/);
|
||||
expect(src).toMatch(/if \(Number\(st\.rows\[0\]\?\.order_status\) >= 90\) continue;/);
|
||||
});
|
||||
|
||||
it('判定失败时退回原有 45→50 行为(不因判定异常带崩分拣)', () => {
|
||||
expect(src).toMatch(/免入库判定失败,按普通订单推进/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('台账判定:原生订单必须是 false', () => {
|
||||
const src = read('src/services/mainSystemPrepLedger.ts');
|
||||
|
||||
it('无台账行 / 空 branch / 空单号 一律 false', () => {
|
||||
expect(src).toMatch(/if \(!branch \|\| !orderCode\) return false;/);
|
||||
// ⚠️ 2026-10-11 口径修正:由 `bool_or`(任一行)改为 `bool_and`(**整单全免入库**)——
|
||||
// 混合单(部分行免入库)仍要我方发车送仓,不得当成免入库单(不派车 / 停 50 不收口)。
|
||||
expect(src).toMatch(/bool_and\(COALESCE\(payload->>'skipInbound', 'false'\) = 'true'\)/);
|
||||
expect(src).toMatch(/return result\.rows\[0\]\?\.skip === true;/);
|
||||
});
|
||||
});
|
||||
@@ -9,7 +9,10 @@ import type {
|
||||
SupplierOption,
|
||||
CatalogSkuOption,
|
||||
} from '../../pages/orders/orderManagement/orderManagementHelpers';
|
||||
import { planDisplayQty } from '../../pages/orders/orderManagement/orderManagementHelpers';
|
||||
import {
|
||||
planDisplayQty,
|
||||
type OrderDetailItemGroup,
|
||||
} from '../../pages/orders/orderManagement/orderManagementHelpers';
|
||||
import { SkuNameSelector } from './SkuNameSelector';
|
||||
import { orderManageProcessingMethodSelectOptions } from '../../utils/processingMethods';
|
||||
import {
|
||||
@@ -60,6 +63,11 @@ function FulfillmentStageBadges({
|
||||
if (orderStatus == null || orderStatus < 30) return null;
|
||||
const tags: string[] = [];
|
||||
if (item.prep_ready) tags.push(t('orders.detail.stagePrep'));
|
||||
/**
|
||||
* 主系统「免入库」行已核货(主系统配送员核货实配已产生)—— 事实镜像,只读展示(2026-10-11)。
|
||||
* 悬停显示核货实配量,便于对账;不显示数量的原因是与"备货完成/入库完成"标签保持同一视觉规格。
|
||||
*/
|
||||
if (item.checked_done) tags.push(t('orders.detail.stageChecked'));
|
||||
if (item.inbound_done) tags.push(t('orders.detail.stageInbound'));
|
||||
if (item.pick_done) tags.push(t('orders.detail.stagePick'));
|
||||
if (!tags.length) return null;
|
||||
@@ -69,6 +77,11 @@ function FulfillmentStageBadges({
|
||||
<span
|
||||
key={label}
|
||||
className="text-[10px] font-medium text-emerald-800 bg-emerald-50 dark:text-emerald-200 dark:bg-emerald-900/40 px-1 py-0.5 rounded"
|
||||
title={
|
||||
label === t('orders.detail.stageChecked') && item.checked_qty != null
|
||||
? `${t('orders.detail.stageChecked')}:${item.checked_qty}${item.unit || ''}`
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
@@ -189,13 +202,28 @@ export interface OrderDetailDeliveryNotePanelProps {
|
||||
deliveryAddress: string;
|
||||
orderRemark: string;
|
||||
canEditHeader: boolean;
|
||||
/**
|
||||
* 单独改收货地址的入口(2026-10-11):明细锁(40+)后表头不再可编辑,
|
||||
* 但改地址是发车前常见动作 ⇒ 由页面给一条只写表头的通道。
|
||||
*/
|
||||
canEditAddress?: boolean;
|
||||
addressEditing?: boolean;
|
||||
addressDraft?: string;
|
||||
addressSaving?: boolean;
|
||||
onAddressDraftChange?: (value: string) => void;
|
||||
onAddressEdit?: () => void;
|
||||
onAddressCancel?: () => void;
|
||||
onAddressSave?: () => void;
|
||||
canEditItems: boolean;
|
||||
canEditPrice: boolean;
|
||||
/** 订单状态,用于判断计划列是否只读(履约中 40/45/50/60 只读) */
|
||||
orderStatus?: number;
|
||||
loading: boolean;
|
||||
items: OrderItem[];
|
||||
groupedItems: Array<{ category: string; items: OrderItem[] }>;
|
||||
groupedItems: OrderDetailItemGroup[];
|
||||
/** 「按订单分组」开关(一级=主系统订单 / 二级=分类),默认开启 */
|
||||
groupByMainOrder?: boolean;
|
||||
onToggleGroupByMainOrder?: () => void;
|
||||
categorySummary: Array<{ name: string; count: number }>;
|
||||
categoryFilter: string | null;
|
||||
categoryOptions: Array<{ value: string; label: string }>;
|
||||
@@ -211,6 +239,14 @@ export interface OrderDetailDeliveryNotePanelProps {
|
||||
onUpdateCategory: (id: string, categoryCode: string) => void;
|
||||
onAddItem: () => void;
|
||||
onRemoveItem: (item: OrderItem) => void;
|
||||
/**
|
||||
* 主系统分配过来的订单(2026-10-10):商品不能删,取而代之的是「缺货」
|
||||
* (报主系统 status=40 转自采 + 我方该行剔除待备货)。
|
||||
*/
|
||||
isMainSystemOrder?: boolean;
|
||||
onReportStockout?: (item: OrderItem) => void;
|
||||
/** 正在上报缺货的明细 id(在途锁:防重复点击) */
|
||||
stockoutPendingItemId?: string | null;
|
||||
onCreateSupplier: (itemId: string) => void;
|
||||
catalogSkus?: CatalogSkuOption[];
|
||||
onSelectSku?: (itemId: string, skuCode: string, sku?: CatalogSkuOption) => void;
|
||||
@@ -233,12 +269,22 @@ export const OrderDetailDeliveryNotePanel: React.FC<OrderDetailDeliveryNotePanel
|
||||
deliveryAddress,
|
||||
orderRemark,
|
||||
canEditHeader,
|
||||
canEditAddress,
|
||||
addressEditing,
|
||||
addressDraft,
|
||||
addressSaving,
|
||||
onAddressDraftChange,
|
||||
onAddressEdit,
|
||||
onAddressCancel,
|
||||
onAddressSave,
|
||||
canEditItems,
|
||||
canEditPrice,
|
||||
orderStatus,
|
||||
loading,
|
||||
items,
|
||||
groupedItems,
|
||||
groupByMainOrder = false,
|
||||
onToggleGroupByMainOrder,
|
||||
categorySummary,
|
||||
categoryFilter,
|
||||
categoryOptions,
|
||||
@@ -249,6 +295,9 @@ export const OrderDetailDeliveryNotePanel: React.FC<OrderDetailDeliveryNotePanel
|
||||
onUpdateCategory,
|
||||
onAddItem,
|
||||
onRemoveItem,
|
||||
isMainSystemOrder = false,
|
||||
onReportStockout,
|
||||
stockoutPendingItemId = null,
|
||||
onCreateSupplier,
|
||||
catalogSkus = [],
|
||||
onSelectSku,
|
||||
@@ -356,8 +405,45 @@ export const OrderDetailDeliveryNotePanel: React.FC<OrderDetailDeliveryNotePanel
|
||||
onChange={(e) => onHeaderChange({ delivery_address: e.target.value })}
|
||||
className="app-input flex-1 min-w-0 px-2 py-1 border rounded text-sm"
|
||||
/>
|
||||
) : addressEditing ? (
|
||||
<span className="flex flex-1 min-w-0 items-center gap-1">
|
||||
<input
|
||||
type="text"
|
||||
autoFocus
|
||||
value={addressDraft ?? ''}
|
||||
onChange={(e) => onAddressDraftChange?.(e.target.value)}
|
||||
className="app-input flex-1 min-w-0 px-2 py-1 border rounded text-sm"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
disabled={addressSaving}
|
||||
onClick={() => onAddressSave?.()}
|
||||
className="app-button-primary px-2 py-1 rounded text-xs disabled:opacity-60"
|
||||
>
|
||||
{t('common.save')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={addressSaving}
|
||||
onClick={() => onAddressCancel?.()}
|
||||
className="app-button-secondary app-border px-2 py-1 border rounded text-xs disabled:opacity-60"
|
||||
>
|
||||
{t('common.cancel')}
|
||||
</button>
|
||||
</span>
|
||||
) : (
|
||||
<span className="truncate">{deliveryAddress || '-'}</span>
|
||||
<span className="flex flex-1 min-w-0 items-center gap-2">
|
||||
<span className="truncate">{deliveryAddress || '-'}</span>
|
||||
{canEditAddress ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onAddressEdit?.()}
|
||||
className="app-button-secondary app-border shrink-0 px-2 py-0.5 border rounded text-xs"
|
||||
>
|
||||
{t('common.edit')}
|
||||
</button>
|
||||
) : null}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
@@ -424,7 +510,23 @@ export const OrderDetailDeliveryNotePanel: React.FC<OrderDetailDeliveryNotePanel
|
||||
<div className="min-w-0" />
|
||||
)}
|
||||
|
||||
{canEditItems ? (
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
{onToggleGroupByMainOrder ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onToggleGroupByMainOrder}
|
||||
aria-pressed={groupByMainOrder}
|
||||
title={t('orders.detail.groupByOrderHint')}
|
||||
className={`inline-flex items-center gap-1 px-2.5 py-1.5 text-xs font-medium border rounded-lg transition-colors ${
|
||||
groupByMainOrder
|
||||
? 'text-indigo-700 bg-indigo-50 border-indigo-200 hover:bg-indigo-100'
|
||||
: 'app-button-secondary app-border'
|
||||
}`}
|
||||
>
|
||||
{t('orders.detail.groupByOrder')}
|
||||
</button>
|
||||
) : null}
|
||||
{canEditItems ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onAddItem}
|
||||
@@ -433,7 +535,8 @@ export const OrderDetailDeliveryNotePanel: React.FC<OrderDetailDeliveryNotePanel
|
||||
<Plus className="w-3.5 h-3.5" />
|
||||
{t('orders.detail.add')}
|
||||
</button>
|
||||
) : null}
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="overflow-x-auto border border-slate-700 dark:border-slate-500">
|
||||
@@ -481,7 +584,20 @@ export const OrderDetailDeliveryNotePanel: React.FC<OrderDetailDeliveryNotePanel
|
||||
0
|
||||
);
|
||||
return (
|
||||
<React.Fragment key={`dn-group-${group.category}`}>
|
||||
<React.Fragment key={`dn-group-${group.mainOrderCode || ''}-${group.category}`}>
|
||||
{group.startsMainOrder ? (
|
||||
/* 一级分组表头:来源主系统订单(开发者 2026-10-10:一级=订单、二级=分类) */
|
||||
<tr className="bg-indigo-50/80 dark:bg-indigo-950/40 font-semibold">
|
||||
<td
|
||||
colSpan={colCount}
|
||||
className="border border-slate-700 dark:border-slate-500 px-2 py-1.5"
|
||||
>
|
||||
{group.mainOrderCode
|
||||
? t('orders.detail.mainOrderGroup', { code: group.mainOrderCode })
|
||||
: t('orders.detail.localOrderGroup')}
|
||||
</td>
|
||||
</tr>
|
||||
) : null}
|
||||
{group.items.map((item) => {
|
||||
seq += 1;
|
||||
const displayName = withItemFlagsLabel(
|
||||
@@ -824,27 +940,54 @@ export const OrderDetailDeliveryNotePanel: React.FC<OrderDetailDeliveryNotePanel
|
||||
/>
|
||||
</td>
|
||||
<td className="border border-slate-700 dark:border-slate-500 px-1 py-1 text-center w-14">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onRemoveItem(item)}
|
||||
disabled={
|
||||
item.is_returned ||
|
||||
((!item.inbound_done && item.can_hard_delete !== false) &&
|
||||
editItemsCount <= 1)
|
||||
}
|
||||
title={
|
||||
item.is_returned
|
||||
? t('orders.detail.hintReturned')
|
||||
: item.inbound_done || item.can_hard_delete === false
|
||||
? t('orders.detail.hintRefund')
|
||||
: editItemsCount <= 1
|
||||
? t('orders.detail.hintKeepOne')
|
||||
: t('orders.detail.hintDelete')
|
||||
}
|
||||
className="inline-flex p-1.5 text-red-600 hover:bg-red-50 rounded disabled:opacity-40"
|
||||
>
|
||||
<Trash2 className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
{isMainSystemOrder ? (
|
||||
/* 主系统分配过来的商品**不能删**,只能报「缺货」(2026-10-10)。
|
||||
报成功后该行会被**从本地清掉**(订单行/自采单/备货单一起),
|
||||
所以这里不需要"已缺货"标签;历史遗留的 is_stockout 行也照常给按钮,
|
||||
点一下即可完成清理(服务端对已报过的行只补做本地清理、不重复发 HTTP)。 */
|
||||
item.is_returned ? (
|
||||
<span
|
||||
className="inline-flex px-1 py-0.5 text-[11px] text-slate-500 whitespace-nowrap"
|
||||
title={t('orders.detail.hintReturned')}
|
||||
>
|
||||
{t('orders.detail.returnedTag')}
|
||||
</span>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onReportStockout?.(item)}
|
||||
disabled={
|
||||
!onReportStockout || stockoutPendingItemId === String(item.id)
|
||||
}
|
||||
title={t('orders.detail.hintStockout')}
|
||||
className="inline-flex px-1.5 py-1 text-xs font-medium text-amber-700 hover:bg-amber-50 rounded disabled:opacity-40 whitespace-nowrap"
|
||||
>
|
||||
{t('orders.detail.stockout')}
|
||||
</button>
|
||||
)
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onRemoveItem(item)}
|
||||
disabled={
|
||||
item.is_returned ||
|
||||
((!item.inbound_done && item.can_hard_delete !== false) &&
|
||||
editItemsCount <= 1)
|
||||
}
|
||||
title={
|
||||
item.is_returned
|
||||
? t('orders.detail.hintReturned')
|
||||
: item.inbound_done || item.can_hard_delete === false
|
||||
? t('orders.detail.hintRefund')
|
||||
: editItemsCount <= 1
|
||||
? t('orders.detail.hintKeepOne')
|
||||
: t('orders.detail.hintDelete')
|
||||
}
|
||||
className="inline-flex p-1.5 text-red-600 hover:bg-red-50 rounded disabled:opacity-40"
|
||||
>
|
||||
<Trash2 className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
)}
|
||||
</td>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
@@ -19,6 +19,15 @@ export const MENU_CATALOG: MenuCatalogEntry[] = [
|
||||
{ menuKey: 'customer-order', path: '/customer-order', defaultLabel: '订单录入', icon: 'ShoppingCart', permission: 'order_entry' },
|
||||
{ menuKey: 'orders-list', path: '/orders', defaultLabel: '订单管理', icon: 'ChevronRight', permission: ['order_manage', 'order_view'], secondary: true },
|
||||
{ menuKey: 'orders-bids', path: '/orders/bids', defaultLabel: '竞价管理', icon: 'ChevronRight', permission: 'bid_manage', secondary: true },
|
||||
{
|
||||
menuKey: 'orders-price-qty',
|
||||
path: '/orders/price-qty-requests',
|
||||
defaultLabel: '跨系统改价/改量申请',
|
||||
icon: 'ChevronRight',
|
||||
permission: ['order_manage', 'order_edit'],
|
||||
accessMatch: 'any',
|
||||
secondary: true,
|
||||
},
|
||||
{ menuKey: 'customers-list', path: '/customers', defaultLabel: '客户列表', icon: 'ChevronRight', permission: 'customer_manage', secondary: true },
|
||||
{ menuKey: 'customers-quote-versions', path: '/customers/quote-versions', defaultLabel: '报价管理', icon: 'ChevronRight', permission: 'customer_manage', secondary: true },
|
||||
{ menuKey: 'products-categories', path: '/products/categories', defaultLabel: '分类管理', icon: 'ChevronRight', permission: ['category_manage', 'product_manage'], secondary: true },
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user