开发者截图报障:主系统把两行都删了,我方订单变成「0 明细却仍挂 ¥112.10」,且没有任何售后单。
根因三条(都已在真库定位到代码行):
① **分支判错(无售后单的直接原因)**:红冲路径的建单函数只要求 `returnCode+itemId`(本可建单),
但这次走了「取消履约(删行)」—— 该分支建单要求「有供应商应付留痕」,而库存抵扣/自货行
`supplier_code` 为空 ⇒ `recordCancelledItemReturn` 直接返回 null ⇒ **不建单**。
判据错在:三项履约事实(验收入库/备货完成/采购完成)**没把"库存抵扣覆盖"算进去**
(设计 §3.2 明确「已入库 / 已在库(**含库存抵扣**)⇒ 退货红冲」)。
修法:新增 `orderItemHasStockCover()`(按 `order_items.stock_cover_qty`),
让覆盖行走红冲 ⇒ 红冲销售/成本 + 重建结算 + **建 OIR_ 售后单**。
同步把 2026-09-24 那条旧源码契约测试更新到新口径(附设计出处),并保留"未覆盖⇒删行"行为。
② **结算壳清不掉**:明细全删后客户结算单仍挂 130.04/2 行。`upsertCustomerStatementForOrder`
默认按 **`inbound`(验收入库)**推导结算日,而自货/库存抵扣单**没有验收单** ⇒ 主查询查不到行 ⇒
提前 `return 'empty'` ⇒ 既有"清空壳"分支(status=10 且 paid=0)**永远够不到**。
修法:在 `recalculateStatementsAffectedByOrder` 里按"订单还剩多少有效明细"直接判定并清壳
(与结算日口径无关),清完再走常规重算。
③ **订单头金额不重算**:`mainSystemStockout.recalcOrderHeaderTotals` 的注释本就写着
"退货跟随/售后取消履约都**不**重算订单头" —— 缺货路径补了,退货路径漏了。
修法:退货跟随处置后调用同一助手(同一口径:金额=未退货行 amount 之和、重量折算到斤)。
真库收敛(走的都是产品函数,不是 SQL 补数):该单
订单总额 112.10 → **0.00**、重量 29.50 → **0.00**、客户结算单 130.04/10 → **已清(明细 0 行)**;
此前苹果行已按跟随处置(删行 + 抵扣成本作废 + 台账 cancelled)。
测试:mainSystemReturnFollow 19→22 条(账务收口三守卫);deleteItemPrepCompletedRedFlush 按新口径更新。
门禁 8 通过 / check-ai-cost 仍红(基线)/ verify-facts 未执行;tsc 前后端 0;
server 360 通过 / 25 失败文件(相对基线**零新增**);root 738 通过 / 2 失败。
⚠️ 待裁决(未擅自做):
1. **本单漏掉的那张售后单**是否补建(该行已被删,补建属一次性数据动作);
2. 明细清空的 90 单**是否要收口**(现行设计:已完成单不删、只留痕;现状态为"保留历史 + 金额归零")。
254 lines
12 KiB
TypeScript
254 lines
12 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 真库事故)', () => {
|
||
it('只有 returned 可越闸;其余(含问不到)一律维持挂人工', () => {
|
||
expect(canDisposeWithoutWatermark('returned')).toBe(true);
|
||
for (const v of ['completed', 'cancelled', 'reassigned', 'order_deleted', '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)');
|
||
});
|
||
});
|
||
|
||
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)'));
|
||
});
|
||
});
|