开发者:「之前快速更新导致供应商系统存在一些单子,主系统这些单子的商品要么被删除、
要么订单都不在配送系统里了,但我们这边还留着被污染的数据没有整理」。裁决:删行+空单进垃圾桶、
退货行残留抵扣归零清计划、同时补防复发代码(本地库,线上未部署供应商系统)。
根因(判据顺序,真接口实测确认):
- judgeByLookup 里 `if (item.found)` 先返回 inconsistent(挂人工),把同一个 lookup 响应里的
`order_deleted: true`(整单已删)吃掉 ⇒ 第 587 行的 orderDeleted 分支永远走不到
- 且 canDisposeWithoutWatermark 只放行 returned、已挂起行闸门也只放行 returned
⇒ 存量 6 行挂起后**永远出不来**
- 实测:垃圾桶主单 ORD_WEB_20261010_BR002_0001/_0002 的 lookup 返回
found=true/prepare_status=10/order_status=50/**order_deleted=true**;活单 order_deleted=false
修复(三处,缺一处挂起行仍出不来;保守边界不变):
1) 判据顺序改为 退货事实 → 整单删除 → 备货行状态(isReturned 仍最优先)
2) canDisposeWithoutWatermark 追加 order_deleted(与 returned 同级:都是主系统权威事实)
3) 已挂起行(suspended)重新纳入处置:order_deleted 同样放行
4) 另加:已退货行残留抵扣兜底清扫 sweepReturnedItemsWithCoverResidue(归零+释放预留+
清批次计划/我方指定),挂 15 分钟 tick(runReturnedCoverResidueSweep)
存量整理(走既有服务,零裸 SQL、非一次性脚本):
- followMainSystemPrepChanges('BR003') 一轮:6 行 suspended→cancelled、6 行明细删净
(未采购/未入库 ⇒ 逐行取消)→ 自动触发 [mirror-closure] 空镜像单收口进垃圾桶(软删可恢复)
- 退货行残留抵扣清扫:ORD_API_20261012_BR003_0002 抄手皮 cover=3、龙口粉丝 cover=5 ⇒ 0
- 最后 1 条挂起台账(主系统整单已删 + 我方单已收口进垃圾桶)置 cancelled 终态留痕
- 整理后复查:A 类(整单没了)= 0、台账挂起 = 0;
台账分布 imported 8 / cancelled 8 / completed 4 / skipped_stockout 2 / returned 2
交付物:
- 只读审计脚本 server/scripts/audit-mirror-pollution.mjs(可反复跑,输出分类+逐单+挂起清单)
- 盘点与执行记录 docs/audit/20261013-主系统删单存量污染盘点.md(判据/清单/根因/前后对照/遗留观察)
- 设计文档 20261008-第三方订单退货跟随与发车回写方案.md 追加「附录 A」记录本次判据修正
测试:mainSystemReturnFollow.test.ts 新增 3 组用例(判据顺序、越闸、退货优先)、
新增 returnedCoverResidueSweep.test.ts 4 例;相关 10 个测试文件 123 例全绿。
遗留观察(未处理,待开发者决定):2 张 D 类单(主系统已 50 / 我方仍 30、无抵扣无备货单)
属早期遗留的"没跟上",不是删单污染。
301 lines
15 KiB
TypeScript
301 lines
15 KiB
TypeScript
import { readFileSync } from 'node:fs';
|
||
import { describe, expect, it } from 'vitest';
|
||
import { mapPrepRowsToOurItems } from '../src/services/mainSystemPrepLedger';
|
||
import {
|
||
canDisposeWithoutWatermark,
|
||
judgeByLookup,
|
||
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;主系统**整单删除** → order_deleted(2026-10-12 拆分)', async () => {
|
||
const { judgeByLookup } = await import('../src/services/mainSystemReturnFollow');
|
||
// 只是该商品行没了(行级)⇒ cancelled(未入库删行 / 已入库退货)
|
||
expect(judgeByLookup({ ...base, found: false, orderItemPresent: false })).toBe('cancelled');
|
||
// 主系统**整单已删**(订单级)⇒ order_deleted(再按"是否已完成"决定动不动)
|
||
expect(judgeByLookup({ ...base, found: false, orderDeleted: true, orderItemPresent: false })).toBe(
|
||
'order_deleted'
|
||
);
|
||
});
|
||
|
||
it('源码钉住:仅"整单删除 + 已完成(90)"才不动;旧的 ≥60 挂起已下线', async () => {
|
||
const { readFileSync } = await import('node:fs');
|
||
const src = readFileSync(
|
||
new URL('../src/services/mainSystemReturnFollow.ts', import.meta.url),
|
||
'utf8'
|
||
);
|
||
// 闸门:只保护"整单删除 + ≥90"
|
||
expect(src).toContain("verdict === 'order_deleted' && facts.orderStatus >= 90");
|
||
// 旧口径"≥60 一律挂起"不得残留
|
||
expect(src).not.toContain('facts.orderStatus >= 60');
|
||
// 整单删除要留订单级操作日志
|
||
expect(src).toContain('main_system_order_deleted_follow');
|
||
});
|
||
|
||
it('该行没出现在 lookup 结果里 → unknown(**绝不**当退货)', async () => {
|
||
const { judgeByLookup } = await import('../src/services/mainSystemReturnFollow');
|
||
expect(judgeByLookup(undefined)).toBe('unknown');
|
||
});
|
||
});
|
||
|
||
describe('无水位历史行:只有「主系统给的明确事实」能越过闸门(2026-10-12 / 2026-10-13)', () => {
|
||
it('returned 与 order_deleted 可越闸;其余(含问不到)一律维持挂人工', () => {
|
||
expect(canDisposeWithoutWatermark('returned')).toBe(true);
|
||
// 2026-10-13 追加:整单已删也是主系统的订单级权威事实(真库事故:6 行因它被挡而永久挂起)
|
||
expect(canDisposeWithoutWatermark('order_deleted')).toBe(true);
|
||
for (const v of ['completed', 'cancelled', 'reassigned', 'in_flight', 'inconsistent', 'unknown', null, undefined] as const) {
|
||
expect(canDisposeWithoutWatermark(v as never), `不应放行:${String(v)}`).toBe(false);
|
||
}
|
||
});
|
||
|
||
it('处置判定(lookup)必须排在"历史行挂起"之前(否则明确退货也永远问不到)', () => {
|
||
const src = readFileSync(new URL('../src/services/mainSystemReturnFollow.ts', import.meta.url), 'utf8');
|
||
const loopIdx = src.indexOf('for (const row of missing) {');
|
||
expect(loopIdx).toBeGreaterThan(-1);
|
||
const body = src.slice(loopIdx, loopIdx + 3000);
|
||
const lookupIdx = body.indexOf('judgeByLookup(lookupMap.get(');
|
||
const suspendIdx = body.indexOf('本系统启用退货跟随前该行就已不在 active');
|
||
expect(lookupIdx).toBeGreaterThan(-1);
|
||
expect(suspendIdx).toBeGreaterThan(-1);
|
||
// lookup 必须在挂起之前(旧写法是先挂起、continue,永远走不到 lookup)
|
||
expect(lookupIdx).toBeLessThan(suspendIdx);
|
||
expect(body).toContain('canDisposeWithoutWatermark(verdict)');
|
||
});
|
||
|
||
/**
|
||
* 2026-10-13 真库事故:挂起闸门只放行 `returned` ⇒ 已挂起的 6 行**永远出不来**
|
||
* (哪怕 lookup 每次都回答"整单已删")。现在 `order_deleted` 与 `returned` 同级放行。
|
||
*/
|
||
it('已挂起行:order_deleted 也要能重新进入处置(否则永远出不来)', () => {
|
||
const src = readFileSync(new URL('../src/services/mainSystemReturnFollow.ts', import.meta.url), 'utf8');
|
||
expect(src).toContain("verdict !== 'returned' && verdict !== 'order_deleted'");
|
||
});
|
||
});
|
||
|
||
/**
|
||
* 整单删除必须排在"备货行还在"之前(2026-10-13 真库事故):
|
||
* 主系统整单进垃圾桶时,订单与其备货行**都还在**(实测垃圾桶主单仍有 3 行、prepare_status=10),
|
||
* 旧的 `if (item.found) → inconsistent` 会把 `order_deleted: true` 这个同一响应里的事实吃掉,
|
||
* 存量 6 行因此挂人工(本地真库 + 真接口实测)。
|
||
*/
|
||
describe('整单删除事实优先于「备货行还在」(2026-10-13 真库事故)', () => {
|
||
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 且 order_deleted=true ⇒ order_deleted(不再落 inconsistent)', () => {
|
||
expect(
|
||
judgeByLookup({ ...base, found: true, prepareStatus: 10, orderDeleted: true })
|
||
).toBe('order_deleted');
|
||
// 备货行"已完成"也一样:整单都没了 ⇒ 不能当正常完成
|
||
expect(
|
||
judgeByLookup({ ...base, found: true, prepareStatus: 30, orderDeleted: true })
|
||
).toBe('order_deleted');
|
||
});
|
||
|
||
it('退货事实仍然最优先(order_deleted 不能盖过 is_returned)', () => {
|
||
expect(
|
||
judgeByLookup({ ...base, found: true, prepareStatus: 30, isReturned: true, orderDeleted: true })
|
||
).toBe('returned');
|
||
});
|
||
|
||
it('活单对照不受影响(order_deleted=false)', () => {
|
||
expect(judgeByLookup({ ...base, found: true, prepareStatus: 10 })).toBe('inconsistent');
|
||
expect(judgeByLookup({ ...base, found: true, prepareStatus: 30 })).toBe('completed');
|
||
});
|
||
});
|
||
|
||
describe('退货事实优先于"备货行还在 ⇒ 已完成"(2026-10-12 真库事故)', () => {
|
||
it('备货行仍在(30) 但订单行已退货 ⇒ returned(必须红冲 + 建售后单)', async () => {
|
||
// 现场:lookup 同时给出 found=true/prepareStatus=30 与 isReturned=true/returnCode=OIR_…
|
||
expect(
|
||
judgeByLookup({
|
||
orderCode: 'ORD_WEB_20261012_BR002_0002',
|
||
skuCode: 'SKU78666376463',
|
||
id: 'prep-1',
|
||
found: true,
|
||
prepareStatus: 30,
|
||
isReturned: true,
|
||
returnCode: 'OIR_2BR0020002_586198bb',
|
||
} as never)
|
||
).toBe('returned');
|
||
});
|
||
|
||
it('只有 returnCode、没有 isReturned 时同样按退货处理', async () => {
|
||
expect(
|
||
judgeByLookup({ found: true, prepareStatus: 30, returnCode: 'OIR_X' } as never)
|
||
).toBe('returned');
|
||
});
|
||
|
||
it('备货行仍在且**未**退货 ⇒ 维持 completed(正常完成,不红冲)', async () => {
|
||
expect(
|
||
judgeByLookup({ found: true, prepareStatus: 30, isReturned: false, returnCode: null } as never)
|
||
).toBe('completed');
|
||
});
|
||
});
|
||
|
||
describe('退货跟随的账务收口(2026-10-12 开发者截图报障:0 行订单仍挂 ¥112.10、结算未清)', () => {
|
||
const followSrc = readFileSync(new URL('../src/services/mainSystemReturnFollow.ts', import.meta.url), 'utf8');
|
||
const returnSrc = readFileSync(new URL('../src/services/orderItemReturnService.ts', import.meta.url), 'utf8');
|
||
const financeSrc = readFileSync(new URL('../src/services/financeReconciliationService.ts', import.meta.url), 'utf8');
|
||
|
||
it('① 删除/红冲后必须重算订单头金额与重量(缺货路径早已这么做,退货路径曾漏)', () => {
|
||
expect(followSrc).toMatch(/recalcOrderHeaderTotals\(\{ branchCode, orderCode \}\)/);
|
||
// 复用缺货路径那个助手(同一口径),且它已导出
|
||
const stockout = readFileSync(new URL('../src/services/mainSystemStockout.ts', import.meta.url), 'utf8');
|
||
expect(stockout).toMatch(/export async function recalcOrderHeaderTotals/);
|
||
});
|
||
|
||
it('② 「库存抵扣覆盖」必须走退货红冲(否则不建售后单 + 留 0 行挂金额的订单)', () => {
|
||
// 覆盖探测存在
|
||
expect(returnSrc).toMatch(/async function orderItemHasStockCover\(/);
|
||
expect(returnSrc).toContain('COALESCE(stock_cover_qty, 0)::numeric AS cover');
|
||
// 且参与分支判定:取消履约(删行)只在**未覆盖**时走
|
||
const idx = returnSrc.indexOf('const covered = !inbound && !prepCompleted && !purchaseCompleted');
|
||
expect(idx).toBeGreaterThan(-1);
|
||
const after = returnSrc.slice(idx, idx + 300);
|
||
expect(after).toMatch(/if \(!inbound && !prepCompleted && !purchaseCompleted && !covered\)/);
|
||
});
|
||
|
||
it('③ 明细清空的订单:待确认客户结算单必须能清壳(不再被 inbound 推导挡在门外)', () => {
|
||
const fnIdx = financeSrc.indexOf('export async function recalculateStatementsAffectedByOrder');
|
||
expect(fnIdx).toBeGreaterThan(-1);
|
||
const body = financeSrc.slice(fnIdx, fnIdx + 3000);
|
||
expect(body).toMatch(/FROM order_items/);
|
||
expect(body).toMatch(/DELETE FROM statement_lines WHERE statement_no = \$1 AND statement_type = 'customer'/);
|
||
expect(body).toMatch(/DELETE FROM customer_statements WHERE statement_no = \$1 AND statement_status = 10/);
|
||
// 判定发生在 applyStatementRecalcs 之前(不依赖行内重建路径)
|
||
expect(body.indexOf('DELETE FROM customer_statements')).toBeLessThan(body.indexOf('applyStatementRecalcs(refs, db)'));
|
||
});
|
||
});
|