fix(主系统同步单): 修「标着库存抵扣但抵扣为 0」的卡行 + 放开「同步行可删」(删单仍禁)
开发者 2026-10-17 报障:「订单管理,从配送系统同步过来的订单商品行可以删除,同步过来的商品无法处理」。 生产只读排查(BR005 / ORD_API_20261017_BR005_0001):香蕉 500 斤这一行 supplier_code='STOCK_COVER'、stock_cover_qty=0、履约行 inventory_cover_qty=0, 既没有采购单也没有备货单 ⇒ 既不走库存抵扣也不进采购/备货 ⇒ 验收/分拣拿不到货。 全生产扫一遍只有这 1 行(br005 1 行,其余租户 0 行)。 A)卡行修复 · 迁移 20261056:三条边界**同时**成立才把 supplier_code 改回 'UNASSIGNED' (① stock_cover_qty≤0 ② 履约行也没有手动抵扣量 ③ 未退货)——只纠正标记、不删行、 不误伤"真抵扣"和"手动选择抵扣商品"的行;遍历所有 tenant_* + tenant_template,幂等。 · 增量自愈:inventoryStockCoverService.normalizeStockCoverSupplierFlags(),在整单抵扣收尾 (补完 FIFO 批次计划之后)调用;失败只记日志、不影响本次抵扣结果。 B)同步行可删(口径变更,开发者 2026-10-17 授权,覆盖 2026-10-10 的"禁删") · 服务层不再对主系统单抛 409 main_system_item_locked; · 删除时**同一事务**把该行行级台账(main_system_order_import_items,按 our_order_item_id 反查) 置 disposition='cancelled' ⇒ needsAppendToOrder 不再追加、台账 upsert 的处置是粘性的 ⇒ 下一轮对账/主系统 webhook 追加不会把它塞回来; · markPrepDisposition 增加可选 client,保证处置与删除同事务提交(失败只记日志,巡检兜底); · 界面:主系统行也出现删除按钮(复用既有 title 文案,无新增文案); · **删单仍然禁止**(orderDeleteService.assertNotMainSystemOrder 未动),缺货按钮保留。 验证: · 本地真库(事务内造 3 行 + ROLLBACK):假标记行 STOCK_COVER/0 → UNASSIGNED; STOCK_COVER/500 与"履约行 manual cover 500"两行保持 STOCK_COVER(不误伤) · cd server && npx tsc --noEmit → 0 错;npm run typecheck(web)→ 0 错 · 新增用例:stockCoverSupplierFlagRepair 5 条、mainSystemItemDeletable 9 条,全过; 相关后端子集 35 文件 / 536 用例通过(independentInbound 有 1 条既有失败,与基线同) · 前端 order 相关 42 文件 / 245 用例全过 · 设计门禁:8 通过 / 1 已知红 check-ai-cost / verify-facts 因本地缺 tenant_br003 红(均基线)
This commit is contained in:
@@ -0,0 +1,94 @@
|
||||
# 主系统同步单:「标着库存抵扣但抵扣为 0」的卡行修复 + 允许删除同步行(2026-10-17)
|
||||
|
||||
- 日期:2026-10-17
|
||||
- 触发:开发者「订单管理,从配送系统同步过来的订单商品行可以删除,同步过来的商品无法处理现在」
|
||||
- 相关:`20261014-订单成本排除独立进货与库存成本分类.md`(`STOCK_COVER` 第三个取值)、
|
||||
`20261010-主系统订单按配送日合并与缺货流转.md`(主系统单禁删 → 缺货)
|
||||
|
||||
## 1. 真机事实(生产只读排查)
|
||||
|
||||
`BR005 / ORD_API_20261017_BR005_0001`(状态 20,4 行):
|
||||
|
||||
| 行 | supplier_code | stock_cover_qty | 履约抵扣 | 采购单 / 备货单 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| 红心火龙果 400 | `INTERNAL` | 0 | 0 | 自采(正常) |
|
||||
| 爱媛橙 500 | `STOCK_COVER` | 500 | 500 | —(全额抵扣) |
|
||||
| 爱媛橙 500 | `STOCK_COVER` | 500 | 500 | —(另一张主系统单,正常) |
|
||||
| **香蕉 500** | **`STOCK_COVER`** | **0** | **0** | **都没有** |
|
||||
|
||||
⇒ 香蕉这行**既不走库存抵扣、也不进采购/备货**,后续验收/分拣拿不到货 = 开发者说的「无法处理」。
|
||||
全生产扫一遍:**只有这 1 行**(`tenant_br005` 1 行;br001/002/003/004 各 0 行)。
|
||||
|
||||
## 2. A:卡行修复(先做)
|
||||
|
||||
### 2.1 根因
|
||||
|
||||
`STOCK_COVER` 这个标记**只能**由 `STOCK_COVER_SUPPLIER_SQL` ①(抵扣量 ≥ 行需求)写,
|
||||
抵扣归零时 ③ 会回退 `UNASSIGNED`。出现「标记在、抵扣 0」= 某个先后顺序把两步拆开了
|
||||
(分配先判"全额可抵",随后的抵扣应用却抵了 0),既有 8 处归零点都用了同一片段,因此不是单点漏写。
|
||||
|
||||
### 2.2 处置
|
||||
|
||||
- **存量**:迁移 `20261056_fix_stock_cover_supplier_flags.sql` —— 三条边界**同时成立**才把
|
||||
`supplier_code` 改成 `UNASSIGNED`(交回采购/备货):
|
||||
① `stock_cover_qty` ≤ 0;② 履约行也没有手动抵扣量(手动「选择抵扣商品」只写履约行);
|
||||
③ 未退货。**不删行、不改自采、不碰真抵扣行**;遍历所有 `tenant_*` + `tenant_template`,幂等。
|
||||
- **增量**:`inventoryStockCoverService.normalizeStockCoverSupplierFlags()`,在整单抵扣收尾
|
||||
(补完 FIFO 批次计划之后)调用;失败只记日志、不影响本次抵扣结果。
|
||||
- 效果:这类行回到 `UNASSIGNED` ⇒ 「待分配」⇒ 采购/备货/缺货都能接手。
|
||||
|
||||
## 3. B:允许删除主系统同步过来的商品行(后做)
|
||||
|
||||
### 3.1 口径变更(开发者 2026-10-17 授权,**覆盖** 2026-10-10 的「主系统单禁删」)
|
||||
|
||||
- 删**行**:允许(界面给出与自建行同样的「删除」入口与二次确认);
|
||||
- 删**单**:仍然禁止(`orderDeleteService.assertNotMainSystemOrder` 不动);
|
||||
- 「缺货」按钮保留:它是**报给主系统**的正规通道,删除只是本地不再要这一行。
|
||||
|
||||
### 3.2 防复发(关键)
|
||||
|
||||
删掉的行**不能**在下一轮对账/追加里被塞回来。落点用**既有**行级台账,不新建表:
|
||||
|
||||
- 删除时把该行对应的 `public.main_system_order_import_items`
|
||||
(按 `our_order_item_id` 反查)置 `disposition='cancelled'` + `disposition_reason='子系统删除明细'`;
|
||||
- `needsAppendToOrder()` 已经把 `cancelled` 列进 `APPEND_BLOCKED_DISPOSITIONS`
|
||||
⇒ 同日重复导入、主系统 webhook 追加都不会再加回来;
|
||||
- `recordImportedPrepItems` 的 upsert CASE 只在原值为 `pending`/`skipped_stockout` 时才覆盖处置
|
||||
⇒ `cancelled` 是**粘性**的,不会被下一轮"复活"。
|
||||
|
||||
### 3.3 边界
|
||||
|
||||
- 已验收入库的行仍走「退货」而不是硬删(既有 `deleteOrderItemWithDependencies` 的守卫不动);
|
||||
- 删除本身仍受订单状态闸门(可编辑状态)与「至少保留一行」限制;
|
||||
- 跨日重新分配(新配送日、新单)属于新业务事实,**不受**本次删除影响(会按新单重新出现)。
|
||||
|
||||
## 4. 验收清单
|
||||
|
||||
| # | 验收项 | 验证方式 |
|
||||
| --- | --- | --- |
|
||||
| R1 | 迁移 20261056 三条边界齐全、幂等、遍历所有租户、模板失败不阻断 | 单测(源码 + SQL 断言) |
|
||||
| R2 | 真库语义:假标记行被纠正;`cover=500` 行与「履约行有手动抵扣」的行**不被误伤** | 本地真库事务内实测(已跑,见 §6) |
|
||||
| R3 | 整单抵扣收尾调用自愈,且在补批次计划之后、失败只记日志 | 单测(源码钉住顺序) |
|
||||
| R4 | 主系统行可删:服务层不再抛 409,且删除时把台账行置 `cancelled` | 单测(源码 + 单测) |
|
||||
| R5 | `needsAppendToOrder` 对 `cancelled` 返回 false(不会复活) | 既有用例 + 新增断言 |
|
||||
| R6 | 界面:主系统行也有删除入口(icon + 既有 title 文案,无新增文案) | 契约测试 |
|
||||
| R7 | 删单仍被禁(未动 `assertNotMainSystemOrder`) | 源码断言 |
|
||||
| R8 | 既有库存抵扣/主系统导入回归不坏 | `npm --prefix server test` 与基线比对 |
|
||||
|
||||
## 5. 未做 / 已知风险
|
||||
|
||||
- **生产 `.env` 缺 `MAIN_SYSTEM_INTEGRATION_CLIENT_SECRET`(len=0)** ⇒ 出站全不可用
|
||||
(「缺货」上报、改价改量通知、对账拉取都会报"未配置")。这是**配置缺失**,不是代码问题;
|
||||
属部署动作,需开发者当轮下令才能补。
|
||||
- 不做「删除时同步告诉主系统」:主系统没有"供应商删行"的反向接口(缺货才是),
|
||||
本次仅是**本地不再需要该行**。
|
||||
- `STOCK_COVER + 0` 的**产生时机**未复现到单一提交(8 处归零点都用了同一片段);
|
||||
因此本次按「存量纠正 + 收尾自愈」兜住,而不是改某一条写路径。
|
||||
|
||||
## 6. 验证(2026-10-17 回填)
|
||||
|
||||
- R2 本地真库实测(事务内造 3 行 + ROLLBACK):假标记行 `STOCK_COVER/0` → `UNASSIGNED`;
|
||||
`STOCK_COVER/500` 与「履约行 manual cover 500」两行**保持 STOCK_COVER**;
|
||||
- R1/R3/R4/R5/R6/R7:`server/tests/stockCoverSupplierFlagRepair.test.ts` +
|
||||
`server/tests/mainSystemItemDeletable.test.ts` + 前端契约测试;
|
||||
- R8:全量后端套件与基线 `14d7afe` 比对(失败集合一致)。
|
||||
@@ -137,6 +137,8 @@ AI 提示词清理已停用条目(7 条归档不删、清单过滤 archived、
|
||||
|
||||
配套交互式全景图(15 模块 / **326** 功能点(2026-09-29 实测;原写 318 已更正),按实现状态着色,可搜索与逐条展开)源码见 [`tools/v3-flowmap/`](../../tools/v3-flowmap/)(`data.js` 为唯一数据源,`node gen-static.mjs` 生成静态页;`flowmap.html` 为生成物不入库)。
|
||||
|
||||
主系统同步单的**卡行与可删除**(2026-10-17 真机报障:香蕉 500 斤行 `supplier_code=STOCK_COVER` 但 `stock_cover_qty=0`、既无采购单也无备货单 ⇒ 「同步过来的商品无法处理」):存量由迁移 `20261056` 按「抵扣为 0 + 履约行也无手动抵扣 + 未退货」三条边界改回 `UNASSIGNED`(只纠正标记、不删行、不误伤真抵扣行),增量由整单抵扣收尾的 `normalizeStockCoverSupplierFlags()` 自愈;同轮按开发者裁决**放开「主系统同步行可删」**(删单仍禁),删除时把行级台账 `disposition` 置 `cancelled` 以免下一轮追加复活,见 [20261017-主系统同步行卡住与可删除.md](./20261017-主系统同步行卡住与可删除.md)。
|
||||
|
||||
主系统竞价**只报价、不定标**(开发者 2026-10-17 裁决:我方不做本地竞价管理,菜单已摘除)—— 主系统发标后按 `bid.opened` 推给我方,我方落**待报价镜像台账**(两张 `public` 表,幂等键 `(round_id, supplier_code)`),页面逐行填**单价**(一次性采购价、无税/运费、>0 且 ≤4 位小数)经我方后端转发 `POST /api/supplier/bids/:round_id/quotes`,中标结果只读展示、中标后仍走既有「分配 → 建单」链路;含「对方只重试 2 次 ⇒ 我方必须能拉 `GET /api/supplier/bids` 兜底」与全套错误码映射(`bid_not_open` / `quote_deadline_passed` / `supplier_category_mismatch` / `bid_disabled` / 401 刷新重试一次),见 [20261017-主系统竞价待报价与报价提交.md](./20261017-主系统竞价待报价与报价提交.md)。
|
||||
|
||||
---
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
-- 修复「标着库存抵扣、实际抵扣为 0」的假标记行(2026-10-17 真机报障)
|
||||
--
|
||||
-- 现象(生产 BR005 / ORD_API_20261017_BR005_0001):香蕉 500 斤这一行
|
||||
-- supplier_code = 'STOCK_COVER',但 stock_cover_qty = 0、履约行 inventory_cover_qty = 0,
|
||||
-- 且**既没有采购单也没有备货单** ⇒ 这一行既不走库存抵扣、也不进采购/备货 ⇒ 验收/分拣拿不到货,
|
||||
-- 界面表现为「同步过来的商品无法处理」。
|
||||
--
|
||||
-- 口径:`STOCK_COVER` 只能由「抵扣量 ≥ 行需求」写入(STOCK_COVER_SUPPLIER_SQL ①),
|
||||
-- 抵扣归零时应回退 `UNASSIGNED`(③)。出现"标记在、抵扣为 0"= 某个先后顺序把两步拆开了
|
||||
-- (分配先判"全额可抵"、随后的抵扣应用却抵了 0)。代码侧已在整单抵扣收尾自愈
|
||||
-- (`inventoryStockCoverService.normalizeStockCoverSupplierFlags`),本迁移负责**存量**。
|
||||
--
|
||||
-- 安全边界:三条同时成立才改 ——
|
||||
-- ① `stock_cover_qty` 为 0/空;
|
||||
-- ② 履约行也没有手动抵扣量(手动「选择抵扣商品」只写 `order_item_fulfillments.inventory_cover_qty`,
|
||||
-- 不写 `stock_cover_qty`,这类行是真抵扣,**不能**误伤);
|
||||
-- ③ 行未退货(退货行由退货清扫按另一套口径处理)。
|
||||
--
|
||||
-- 幂等:改完的行 supplier_code 已是 UNASSIGNED,重跑不会再命中。
|
||||
|
||||
DO $$
|
||||
DECLARE
|
||||
s text;
|
||||
v_branch text;
|
||||
fixed int;
|
||||
total int := 0;
|
||||
BEGIN
|
||||
FOR s IN
|
||||
SELECT nspname FROM pg_namespace
|
||||
WHERE nspname = 'tenant_template' OR nspname LIKE 'tenant\_b%'
|
||||
ORDER BY nspname
|
||||
LOOP
|
||||
IF to_regclass(format('%I.order_items', s)) IS NULL THEN
|
||||
RAISE NOTICE '跳过 %:没有 order_items 表', s;
|
||||
CONTINUE;
|
||||
END IF;
|
||||
|
||||
-- 租户表是 FORCE RLS:先在**本事务**设置该 schema 的租户上下文,否则 UPDATE 会被 WITH CHECK 拒掉
|
||||
v_branch := CASE
|
||||
WHEN s = 'tenant_template' THEN NULL
|
||||
ELSE upper(replace(substr(s, length('tenant_') + 1), '_', ''))
|
||||
END;
|
||||
PERFORM set_config('app.branch_code', COALESCE(v_branch, 'BR002'), true);
|
||||
|
||||
BEGIN
|
||||
EXECUTE format($f$
|
||||
UPDATE %1$I.order_items oi
|
||||
SET supplier_code = 'UNASSIGNED'
|
||||
WHERE UPPER(TRIM(COALESCE(oi.supplier_code, ''))) = 'STOCK_COVER'
|
||||
AND COALESCE(oi.stock_cover_qty, 0) <= 1e-9
|
||||
AND COALESCE(oi.is_returned, false) = false
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM %1$I.order_item_fulfillments f
|
||||
WHERE f.order_item_id = oi.id
|
||||
AND COALESCE(f.inventory_cover_qty, 0) > 1e-9
|
||||
)
|
||||
$f$, s);
|
||||
GET DIAGNOSTICS fixed = ROW_COUNT;
|
||||
total := total + fixed;
|
||||
IF fixed > 0 THEN
|
||||
RAISE NOTICE '%:纠正 % 行「标着库存抵扣但抵扣为 0」的假标记 → UNASSIGNED', s, fixed;
|
||||
END IF;
|
||||
EXCEPTION WHEN others THEN
|
||||
-- 模板 schema 可能被 RLS 挡住(与 20261054 哨兵客户同情形):只记日志,不阻断迁移
|
||||
RAISE NOTICE '%:未能纠正(%),该 schema 由代码自愈兜底', s, SQLERRM;
|
||||
END;
|
||||
END LOOP;
|
||||
|
||||
RAISE NOTICE '假标记行修复完成:共纠正 % 行', total;
|
||||
END $$;
|
||||
@@ -829,6 +829,48 @@ export async function applyStockCoverForOrderItem(
|
||||
* 按订单逐行落库存抵扣并写预留(竞价闸门 / 发标前共用)。
|
||||
* 开关关闭时各行 cover 为 0。
|
||||
*/
|
||||
/**
|
||||
* **自愈:清掉"标着库存抵扣、实际没抵到"的假标记**(2026-10-17 真库事故)。
|
||||
*
|
||||
* 真库现象(生产 `BR005 / ORD_API_20261017_BR005_0001`):香蕉 500 斤这一行
|
||||
* `supplier_code='STOCK_COVER'` 但 `stock_cover_qty=0`、履约行 `inventory_cover_qty=0`
|
||||
* ⇒ 该行**既不走库存抵扣、也不进采购/备货**(没有采购单、没有备货单)⇒ 后续验收/分拣拿不到货,
|
||||
* 界面表现为"同步过来的商品无法处理"。
|
||||
*
|
||||
* 口径:`STOCK_COVER` 这个标记**只能**由 `STOCK_COVER_SUPPLIER_SQL` ①(抵扣量 ≥ 行需求)写;
|
||||
* 抵扣量归零时 ③ 会把它回退成 `UNASSIGNED`。出现"标记在、抵扣为 0"说明某个先后顺序把两步拆开了
|
||||
* (分配先判"全额可抵"、随后的抵扣应用却抵了 0)⇒ 这里按**事实**纠正标记,把行交回采购/备货。
|
||||
*
|
||||
* 安全边界(三条同时成立才改):
|
||||
* · `coalesce(stock_cover_qty,0) <= 0`(本行确实没有抵扣量);
|
||||
* · 履约行也没有手动抵扣量(`order_item_fulfillments.inventory_cover_qty`,
|
||||
* 手动「选择抵扣商品」只写履约行、**不写** `stock_cover_qty`,不能误伤);
|
||||
* · 行未退货(退货行由退货清扫负责,口径不同)。
|
||||
*/
|
||||
export async function normalizeStockCoverSupplierFlags(db: Db, orderCode: string): Promise<number> {
|
||||
const code = String(orderCode || '').trim();
|
||||
if (!code) return 0;
|
||||
const result = await db.query(
|
||||
`UPDATE order_items oi
|
||||
SET supplier_code = 'UNASSIGNED'
|
||||
WHERE oi.order_code = $1
|
||||
AND UPPER(TRIM(COALESCE(oi.supplier_code, ''))) = '${STOCK_COVER_SUPPLIER_CODE}'
|
||||
AND COALESCE(oi.stock_cover_qty, 0) <= 1e-9
|
||||
AND COALESCE(oi.is_returned, false) = false
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM order_item_fulfillments f
|
||||
WHERE f.order_item_id = oi.id
|
||||
AND COALESCE(f.inventory_cover_qty, 0) > 1e-9
|
||||
)`,
|
||||
[code]
|
||||
);
|
||||
const fixed = Number((result as { rowCount?: number | null }).rowCount) || 0;
|
||||
if (fixed > 0) {
|
||||
console.warn(`[stock-cover] ${code}:纠正 ${fixed} 行"标着库存抵扣但抵扣为 0"的假标记 → UNASSIGNED`);
|
||||
}
|
||||
return fixed;
|
||||
}
|
||||
|
||||
export async function applyStockCoverForOrder(
|
||||
orderCode: string,
|
||||
branchCode?: string | null,
|
||||
@@ -893,6 +935,16 @@ export async function applyStockCoverForOrder(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 收尾自愈:把"标着 STOCK_COVER 但一行都没抵到"的行交回采购/备货。
|
||||
* 失败不影响本次抵扣结果(最多留一个假标记,下次抵扣/迁移再纠正)。
|
||||
*/
|
||||
try {
|
||||
await normalizeStockCoverSupplierFlags(db, code);
|
||||
} catch (err) {
|
||||
console.error('[stock-cover] 纠正库存抵扣标记失败(不影响抵扣):', err);
|
||||
}
|
||||
|
||||
return { itemCount: items.rowCount || 0, coveredQty, zeroReasons };
|
||||
}
|
||||
|
||||
|
||||
@@ -499,8 +499,10 @@ export async function markPrepDisposition(params: {
|
||||
prepId: string;
|
||||
disposition: PrepLedgerDisposition;
|
||||
reason?: string | null;
|
||||
/** 传入事务连接时与调用方同事务(删明细必须和处置一起提交) */
|
||||
client?: { query: (sql: string, values?: unknown[]) => Promise<unknown> };
|
||||
}): Promise<void> {
|
||||
await pool.query(
|
||||
await (params.client || 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`,
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
} from './orderAllocationService';
|
||||
import { withAllocationSlot } from './allocationConcurrency';
|
||||
import { deleteUnworkedPickingRowsForItems } from './pickingService';
|
||||
import { markPrepDisposition } from './mainSystemPrepLedger';
|
||||
import {
|
||||
countPreparationLinks,
|
||||
linkOrderItemToInventoryCover,
|
||||
@@ -1096,10 +1097,18 @@ export async function syncOrderManageItems(params: {
|
||||
if (id && !isTempId(id)) keptIds.add(id);
|
||||
}
|
||||
|
||||
// 主系统分配过来的订单:**商品不能删**(开发者 2026-10-10 口径)。
|
||||
// 它的每一行都对着主系统一条备货行(退货红冲/发车回写靠这条对照定位);
|
||||
// 供不了要用「缺货」按钮报主系统转自采,而不是把行删掉。
|
||||
// 注意:第三方退货跟随走的是 `removeOrderItemForMainSystemReturn`(独立入口),不受本守卫影响。
|
||||
/**
|
||||
* 主系统分配过来的订单:**允许删行**(开发者 2026-10-17 裁决,覆盖 2026-10-10 的"禁删")。
|
||||
*
|
||||
* 口径变化的原因:同步过来的行有时确实是废行(例如「标着库存抵扣但抵扣为 0」、或者主系统发错商品),
|
||||
* 只给「缺货」一条路会让人无路可走。**删单仍然禁止**(`orderDeleteService.assertNotMainSystemOrder` 不动),
|
||||
* 缺货按钮也保留(那是报给主系统的正规通道)。
|
||||
*
|
||||
* ⚠️ 防复发:删掉的行不能在下一轮对账/主系统 webhook 追加里被塞回来 —— 必须**同时**
|
||||
* 把它这一行的行级台账(`public.main_system_order_import_items`,按 `our_order_item_id` 反查)
|
||||
* 置 `disposition='cancelled'`;`needsAppendToOrder()` 已把 `cancelled` 列为不再追加,
|
||||
* 且台账 upsert 只在原值 `pending`/`skipped_stockout` 时才覆盖处置 ⇒ 该处置是粘性的。
|
||||
*/
|
||||
const removedIds = [...existingMap.entries()]
|
||||
.filter(([id, row]) => !keptIds.has(id) && !row.is_returned)
|
||||
.map(([id]) => id);
|
||||
@@ -1111,13 +1120,32 @@ export async function syncOrderManageItems(params: {
|
||||
[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' }
|
||||
);
|
||||
for (const removedId of removedIds) {
|
||||
try {
|
||||
const links = await client.query(
|
||||
`SELECT prep_id FROM public.main_system_order_import_items
|
||||
WHERE branch_code = $1 AND our_order_item_id = $2::uuid`,
|
||||
[order.branch_code || null, removedId]
|
||||
);
|
||||
for (const link of links.rows as Array<{ prep_id: string | null }>) {
|
||||
const prepId = String(link?.prep_id || '').trim();
|
||||
if (!prepId) continue;
|
||||
await markPrepDisposition({
|
||||
branchCode: order.branch_code || '',
|
||||
prepId,
|
||||
disposition: 'cancelled',
|
||||
reason: '子系统删除明细(操作员)',
|
||||
client,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
// 台账处置失败**不阻断**删除(否则又变回"删不掉");只记日志,由巡检兜底
|
||||
console.error(
|
||||
`[order_items_edit] 主系统行处置落账失败(继续删除)${orderCode} ${removedId}:`,
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { needsAppendToOrder } from '../src/services/mainSystemOrderImport';
|
||||
|
||||
/**
|
||||
* 主系统同步过来的商品行:**允许删除**(开发者 2026-10-17 裁决,覆盖 2026-10-10 的"禁删")。
|
||||
*
|
||||
* 三条必须同时成立,缺一条就会变成灾难:
|
||||
* ① 服务层不再对主系统单抛 409 `main_system_item_locked`(否则界面给了按钮也点不动);
|
||||
* ② 删除**同一事务**里把该行的主系统台账处置成 `cancelled`(否则下一轮对账/webhook 追加把它塞回来,
|
||||
* 用户会看到"删了又回来");
|
||||
* ③ **删单仍然禁止**(`orderDeleteService.assertNotMainSystemOrder` 不许动)——
|
||||
* 删行和删单是两件事,后者会扯断退货红冲/发车回写的对照。
|
||||
*/
|
||||
const itemsService = readFileSync(
|
||||
path.join(__dirname, '../src/services/orderManageItemsService.ts'),
|
||||
'utf8'
|
||||
);
|
||||
const deleteService = readFileSync(
|
||||
path.join(__dirname, '../src/services/orderDeleteService.ts'),
|
||||
'utf8'
|
||||
);
|
||||
const ledgerService = readFileSync(
|
||||
path.join(__dirname, '../src/services/mainSystemPrepLedger.ts'),
|
||||
'utf8'
|
||||
);
|
||||
const panel = readFileSync(
|
||||
path.join(__dirname, '../../src/components/order/OrderDetailDeliveryNotePanel.tsx'),
|
||||
'utf8'
|
||||
);
|
||||
|
||||
describe('① 服务层:主系统行不再被 409 拦住', () => {
|
||||
it('已经不再抛 main_system_item_locked', () => {
|
||||
expect(itemsService).not.toMatch(/main_system_item_locked/);
|
||||
expect(itemsService).not.toMatch(/主系统分配过来的商品不能删除/);
|
||||
});
|
||||
|
||||
it('删除时把该行台账置 cancelled(且与删除同事务:传 client)', () => {
|
||||
const idx = itemsService.indexOf('SELECT prep_id FROM public.main_system_order_import_items');
|
||||
expect(idx).toBeGreaterThan(-1);
|
||||
const block = itemsService.slice(idx, idx + 900);
|
||||
expect(block).toMatch(/disposition: 'cancelled'/);
|
||||
expect(block).toMatch(/reason: '子系统删除明细(操作员)'/);
|
||||
expect(block).toMatch(/client,/);
|
||||
});
|
||||
|
||||
it('markPrepDisposition 支持事务连接(否则处置会落在事务外、删了又复活)', () => {
|
||||
expect(ledgerService).toMatch(/client\?: \{ query:/);
|
||||
expect(ledgerService).toMatch(/params\.client \|\| pool/);
|
||||
});
|
||||
|
||||
it('台账处置失败不阻断删除(只记日志,巡检兜底)', () => {
|
||||
const idx = itemsService.indexOf('主系统行处置落账失败');
|
||||
expect(idx).toBeGreaterThan(-1);
|
||||
expect(itemsService.slice(Math.max(0, idx - 400), idx)).toMatch(/catch/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('② 防复发:cancelled 的行不会被追加回来', () => {
|
||||
it('needsAppendToOrder 对 cancelled 说"不用追加"', () => {
|
||||
expect(
|
||||
needsAppendToOrder({ id: 'prep-1' }, [
|
||||
{ prep_id: 'prep-1', our_order_item_id: null, disposition: 'cancelled' },
|
||||
])
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('与之对照:imported + 空链接仍然要补(既有修复不许被这次改动削弱)', () => {
|
||||
expect(
|
||||
needsAppendToOrder({ id: 'prep-1' }, [
|
||||
{ prep_id: 'prep-1', our_order_item_id: null, disposition: 'imported' },
|
||||
])
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('已配上订单行的行不会被重复追加', () => {
|
||||
expect(
|
||||
needsAppendToOrder({ id: 'prep-1' }, [
|
||||
{ prep_id: 'prep-1', our_order_item_id: 'item-1', disposition: 'imported' },
|
||||
])
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('③ 删单仍然禁止(口径没有被顺手放开)', () => {
|
||||
it('assertNotMainSystemOrder 仍在,并被 deleteOrder 两条路径调用', () => {
|
||||
expect(deleteService).toMatch(/async function assertNotMainSystemOrder/);
|
||||
const calls = deleteService.match(/assertNotMainSystemOrder\(client/g) || [];
|
||||
expect(calls.length).toBeGreaterThanOrEqual(2);
|
||||
expect(deleteService).toMatch(/main_system_order_locked/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('④ 界面:主系统行也有删除入口(无新增文案)', () => {
|
||||
it('isMainSystemOrder 分支里出现 onRemoveItem,且沿用既有 title 文案键', () => {
|
||||
const branchStart = panel.indexOf('{isMainSystemOrder ? (');
|
||||
expect(branchStart).toBeGreaterThan(-1);
|
||||
// 取主系统分支到非主系统分支之间的片段
|
||||
const branchEnd = panel.indexOf(') : (', branchStart);
|
||||
expect(branchEnd).toBeGreaterThan(branchStart);
|
||||
const block = panel.slice(branchStart, branchEnd);
|
||||
expect(block).toMatch(/onRemoveItem\(item\)/);
|
||||
expect(block).toMatch(/t\('orders\.detail\.hintDelete'\)/);
|
||||
expect(block).toMatch(/t\('orders\.detail\.hintKeepOne'\)/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
/**
|
||||
* 「标着库存抵扣、实际抵扣为 0」的假标记行(2026-10-17 生产真机事故)。
|
||||
*
|
||||
* 生产 `BR005 / ORD_API_20261017_BR005_0001`:香蕉 500 斤这一行
|
||||
* `supplier_code='STOCK_COVER'` 但 `stock_cover_qty=0`、履约行 `inventory_cover_qty=0`,
|
||||
* 既没有采购单也没有备货单 ⇒ 后续验收/分拣拿不到货,界面表现为"同步过来的商品无法处理"。
|
||||
*
|
||||
* 这个文件钉住修复的两条腿:
|
||||
* ① **存量**:迁移 `20261056` 按"三条边界同时成立"纠正(不误伤真抵扣行);
|
||||
* ② **增量**:整单抵扣收尾自愈(`normalizeStockCoverSupplierFlags`),否则下次还会出现。
|
||||
*/
|
||||
const service = readFileSync(
|
||||
path.join(__dirname, '../src/services/inventoryStockCoverService.ts'),
|
||||
'utf8'
|
||||
);
|
||||
const migration = readFileSync(
|
||||
path.join(__dirname, '../../migrations/20261056_fix_stock_cover_supplier_flags.sql'),
|
||||
'utf8'
|
||||
);
|
||||
|
||||
describe('存量修复:迁移 20261056 的判据', () => {
|
||||
it('三条安全边界齐全:抵扣为 0 / 履约行也无手动抵扣量 / 未退货', () => {
|
||||
expect(migration).toMatch(/UPPER\(TRIM\(COALESCE\(oi\.supplier_code, ''\)\)\) = 'STOCK_COVER'/);
|
||||
expect(migration).toMatch(/COALESCE\(oi\.stock_cover_qty, 0\) <= 1e-9/);
|
||||
expect(migration).toMatch(/NOT EXISTS \(/);
|
||||
expect(migration).toMatch(/COALESCE\(f\.inventory_cover_qty, 0\) > 1e-9/);
|
||||
expect(migration).toMatch(/COALESCE\(oi\.is_returned, false\) = false/);
|
||||
});
|
||||
|
||||
it('只改成本地可处理的 UNASSIGNED(交回采购/备货),不是删行、不是改成自采', () => {
|
||||
expect(migration).toMatch(/SET supplier_code = 'UNASSIGNED'/);
|
||||
expect(migration).not.toMatch(/DELETE FROM %1\$I\.order_items/);
|
||||
expect(migration).not.toMatch(/INTERNAL/);
|
||||
});
|
||||
|
||||
it('幂等 + 遍历所有租户 schema(含 tenant_template),且不因模板被 RLS 挡住而中断迁移', () => {
|
||||
expect(migration).toMatch(/tenant_template' OR nspname LIKE 'tenant\\_b%'/);
|
||||
expect(migration).toMatch(/EXCEPTION WHEN others THEN/);
|
||||
expect(migration).toMatch(/set_config\('app\.branch_code'/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('增量自愈:整单抵扣收尾纠正假标记', () => {
|
||||
it('导出 normalizeStockCoverSupplierFlags,且判据与迁移同口径', () => {
|
||||
const idx = service.indexOf('export async function normalizeStockCoverSupplierFlags');
|
||||
expect(idx).toBeGreaterThan(-1);
|
||||
const block = service.slice(idx, idx + 1600);
|
||||
expect(block).toMatch(/SET supplier_code = 'UNASSIGNED'/);
|
||||
expect(block).toMatch(/COALESCE\(oi\.stock_cover_qty, 0\) <= 1e-9/);
|
||||
expect(block).toMatch(/COALESCE\(f\.inventory_cover_qty, 0\) > 1e-9/);
|
||||
expect(block).toMatch(/COALESCE\(oi\.is_returned, false\) = false/);
|
||||
});
|
||||
|
||||
it('applyStockCoverForOrder 收尾一定调用它(且失败不影响本次抵扣结果)', () => {
|
||||
const applyIdx = service.indexOf('export async function applyStockCoverForOrder(');
|
||||
expect(applyIdx).toBeGreaterThan(-1);
|
||||
const tail = service.slice(applyIdx, applyIdx + 6000);
|
||||
const callIdx = tail.indexOf('normalizeStockCoverSupplierFlags(db, code)');
|
||||
expect(callIdx).toBeGreaterThan(-1);
|
||||
// 必须先补完批次计划、再自愈(顺序写反会把刚抵上的行误清)
|
||||
expect(tail.indexOf('planFifoBatchesForCoveredItems')).toBeLessThan(callIdx);
|
||||
// 自愈失败只记日志
|
||||
const around = tail.slice(Math.max(0, callIdx - 300), callIdx + 200);
|
||||
expect(around).toMatch(/catch/);
|
||||
expect(around).toMatch(/不影响抵扣/);
|
||||
});
|
||||
});
|
||||
@@ -1343,6 +1343,31 @@ export const OrderDetailDeliveryNotePanel: React.FC<OrderDetailDeliveryNotePanel
|
||||
{t('orders.detail.stockout')}
|
||||
</button>
|
||||
)}
|
||||
{/* 2026-10-17 开发者裁决:主系统同步过来的行**也允许删除**
|
||||
(废行/发错商品不再只有「缺货」一条路;删单仍禁止)。
|
||||
删除后服务层会把该行的主系统台账置 cancelled,下一轮不会复活。
|
||||
已入库的行仍走「退货」而不是硬删(与自建行同一条规则)。 */}
|
||||
<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>
|
||||
</div>
|
||||
) : (
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user