原改动人:雨天 <oncwnuHbbvAwYZMdPF78PsWNPadI@git.weixin.qq.com> 代为提交:Lead 会话(本 commit 内容与该会话工作区逐字节一致,未做任何修改), 目的是不让在研成果丢失、并让工作树回到干净可部署状态。 提交前由 Lead 实跑验证: - 前端 npx tsc --noEmit 0 错误;后端 server npx tsc --noEmit 0 错误 - 本批新增的 7 个测试 54/54 通过;Lead 侧契约测试(散客录单/文案/成本列)42/42 通过 - bash tools/design-consistency/run-all.sh --verify:通过 8 / 未通过 1(check-ai-cost,既有红)/ 未执行 1(verify-facts,本地库不可连)—— 与基线一致 新增能力(各含 docs/design 设计文): - 独立进货不得有配送任务:生成侧兜底 + 补建候选 + 查询侧三道防线(实测 5 张独立进货单里 4 张有僵尸 delivery_tasks) - 主系统追加行零价闸门尊重其已声明的 allowUnpriced(否则整批分配行静默丢失) - 库存抵扣为 0 的原因可见(不再静默,原因判定与抵扣量同源并落到日志与「库存抵扣」入口) - 退货/删单跟随改独立 2 分钟周期(MAIN_SYSTEM_RETURN_FOLLOW_SEC,置 0 退回旧行为) - 加工领料可用本单自己的预留(放行必须与本单预留消费成对,避免短送与同一批算两次) - 出库拍照预览、主系统实收 / SKU 映射 / 单位变更 inbox 等配套 同一批包含对已废弃旧方案的回滚(design doc 与 README 索引行一并移除): - 独立进货建客户档案(方案甲)→ 回到哨兵方案;随之删除 migrations/20261044_independent_inbound_customer.sql - 分类新建去重(同名复用已有) - 分拣标签纸张尺寸预设 / 分拣标签可选客户名与区域 未包含:src/pages/orders/OrderManagementPage.tsx(0 字节空文件,疑似误建,既未提交也未删除)
445 lines
18 KiB
TypeScript
445 lines
18 KiB
TypeScript
import { readFileSync } from 'node:fs';
|
||
import { describe, expect, it, vi } from 'vitest';
|
||
import {
|
||
generateOrderItemReturnCode,
|
||
generateOrderItemSwitchReturnCode,
|
||
resolveReturnStockAction,
|
||
markOrderItemReturned,
|
||
removeOrReturnOrderItem,
|
||
reversePurchaseInboundForSupplierSwitch,
|
||
} from '../src/services/orderItemReturnService';
|
||
|
||
describe('退货库存动作', () => {
|
||
it('未入库不减仓', () => {
|
||
expect(resolveReturnStockAction({ inbound: false, alreadyOut: false })).toBe('none');
|
||
});
|
||
|
||
it('已入库仍在仓则回冲入库', () => {
|
||
expect(resolveReturnStockAction({ inbound: true, alreadyOut: false })).toBe('reverse_in');
|
||
});
|
||
|
||
it('配送中/已出库不减仓库库存', () => {
|
||
expect(resolveReturnStockAction({ inbound: true, alreadyOut: true })).toBe('already_out');
|
||
});
|
||
|
||
it('台账被跳过(无可用回冲批次)时不得记成 reverse_in', () => {
|
||
// 过手履约 / 商品直送 / 供应商免入库 / 仓内加工成品:可能有验收记录与 inbound_batch_no,
|
||
// 但没有库存批次 → 回冲是空操作 → 留痕必须如实为 none
|
||
expect(
|
||
resolveReturnStockAction({ inbound: true, alreadyOut: false, reversible: false })
|
||
).toBe('none');
|
||
});
|
||
|
||
it('确有可回冲批次时仍记 reverse_in;省略 reversible 保持旧语义', () => {
|
||
expect(
|
||
resolveReturnStockAction({ inbound: true, alreadyOut: false, reversible: true })
|
||
).toBe('reverse_in');
|
||
expect(resolveReturnStockAction({ inbound: true, alreadyOut: false })).toBe('reverse_in');
|
||
// 已出库优先于可回冲性
|
||
expect(
|
||
resolveReturnStockAction({ inbound: true, alreadyOut: true, reversible: false })
|
||
).toBe('already_out');
|
||
});
|
||
});
|
||
|
||
describe('退货留痕准确性(台账被跳过的行)', () => {
|
||
const itemRow = {
|
||
id: 'item-1',
|
||
sku_code: 'SKU1',
|
||
item_name: '白菜',
|
||
quantity: 2,
|
||
price: 10,
|
||
amount: 20,
|
||
unit_cost: 6,
|
||
is_extra_dish: false,
|
||
is_returned: false,
|
||
return_code: null,
|
||
};
|
||
|
||
/**
|
||
* 是否真的写了「回冲入库」的库存日志。
|
||
* 注意:`'order_item_return'` 这个字面量在客户结算红冲(statement_lines)里也会出现,
|
||
* 所以必须限定在库存日志的写入上,否则断言会误判(原断言用的是
|
||
* `operation_type = 'order_item_return'`,而该串在任何 SQL 里都不存在 —— 等于没断言)。
|
||
*/
|
||
const wroteStockReturnLog = (list: Array<{ sql: string }>) =>
|
||
list.some(
|
||
(c) => c.sql.includes('INSERT INTO inventory_logs') && c.sql.includes("'order_item_return'")
|
||
);
|
||
|
||
function makeDb(withReversibleBatches: boolean) {
|
||
const calls: Array<{ sql: string; params?: unknown[] }> = [];
|
||
const db = {
|
||
query: vi.fn(async (sql: string, params?: unknown[]) => {
|
||
const s = String(sql);
|
||
calls.push({ sql: s, params });
|
||
// 可回冲批次查询(与 reverseInboundStock 同一口径)
|
||
if (s.includes('FROM inventory i')) {
|
||
return withReversibleBatches
|
||
? { rowCount: 1, rows: [{ batch_no: 'IN1', sku_code: 'SKU1', available_qty: 5 }] }
|
||
: { rowCount: 0, rows: [] };
|
||
}
|
||
if (s.includes('FROM order_items') && s.includes('return_code')) {
|
||
return { rowCount: 1, rows: [{ ...itemRow }] };
|
||
}
|
||
if (s.includes("operation_type = 'inspection_in'")) {
|
||
return { rowCount: 1, rows: [{}] }; // 有验收入库记录(过手也有批次号)
|
||
}
|
||
if (s.includes('picking_out')) {
|
||
return { rowCount: 0, rows: [] }; // 未出库
|
||
}
|
||
if (s.includes('FROM cost_details') || s.includes('UPDATE cost_details')) {
|
||
return { rowCount: 1, rows: [{ id: 'cd1', qty: 0 }] };
|
||
}
|
||
if (s.includes('FROM orders WHERE')) {
|
||
return { rowCount: 1, rows: [{ cycle_code: '202608', branch_code: 'BR1' }] };
|
||
}
|
||
if (s.includes('FROM after_sales')) {
|
||
if (s.includes('aftersale_type')) return { rowCount: 0, rows: [] };
|
||
return { rowCount: 1, rows: [{}] };
|
||
}
|
||
return { rowCount: 0, rows: [] };
|
||
}),
|
||
};
|
||
return { db, calls };
|
||
}
|
||
|
||
it('无可回冲批次 → 留痕记 none,且不写 order_item_return 库存日志', async () => {
|
||
const { db, calls } = makeDb(false);
|
||
const result = await markOrderItemReturned(db as any, {
|
||
orderCode: 'ORD1',
|
||
branchCode: 'BR1',
|
||
item: { id: 'item-1', sku_code: 'SKU1' },
|
||
});
|
||
|
||
expect(result.stock_action).toBe('none');
|
||
const insert = calls.find((c) => c.sql.includes('INSERT INTO order_item_returns'));
|
||
// 参数顺序:return_code, order_code, item_id, sku, qty, sale_amount, stock_action, branch_code
|
||
expect(insert?.params?.[6]).toBe('none');
|
||
expect(wroteStockReturnLog(calls)).toBe(false);
|
||
expect(calls.some((c) => c.sql.includes('UPDATE inventory'))).toBe(false);
|
||
// 退货单与财务红冲仍必须照做
|
||
expect(insert).toBeTruthy();
|
||
expect(calls.some((c) => c.sql.includes('UPDATE cost_details'))).toBe(true);
|
||
});
|
||
|
||
it('确有可回冲批次 → 记 reverse_in 并真扣库存', async () => {
|
||
const { db, calls } = makeDb(true);
|
||
const result = await markOrderItemReturned(db as any, {
|
||
orderCode: 'ORD1',
|
||
branchCode: 'BR1',
|
||
item: { id: 'item-1', sku_code: 'SKU1' },
|
||
});
|
||
|
||
expect(result.stock_action).toBe('reverse_in');
|
||
const insert = calls.find((c) => c.sql.includes('INSERT INTO order_item_returns'));
|
||
expect(insert?.params?.[6]).toBe('reverse_in');
|
||
expect(calls.some((c) => c.sql.includes('UPDATE inventory'))).toBe(true);
|
||
expect(wroteStockReturnLog(calls)).toBe(true);
|
||
});
|
||
});
|
||
|
||
describe('可回冲批次谓词必须共用(防止判定与回冲口径漂移)', () => {
|
||
const src = readFileSync(
|
||
new URL('../src/services/orderItemReturnService.ts', import.meta.url),
|
||
'utf8'
|
||
);
|
||
|
||
it('可回冲批次的 SQL 只允许存在一处', () => {
|
||
// 'FROM inventory i' 是「同订单同 SKU 且仍有可用库存的批次」这段谓词的指纹;
|
||
// 一旦被复制成第二份,判定与实际回冲就可能对不上(正是本次修复的假留痕成因)。
|
||
expect((src.match(/FROM inventory i\b/g) || []).length).toBe(1);
|
||
});
|
||
|
||
it('判定方与回冲方都必须走同一个 helper', () => {
|
||
const hasBody = src.slice(src.indexOf('async function hasReversibleInboundStock('));
|
||
expect(hasBody.slice(0, 500)).toContain('findReversibleInboundBatches(');
|
||
const reverseBody = src.slice(src.indexOf('async function reverseInboundStock('));
|
||
expect(reverseBody.slice(0, 1200)).toContain('findReversibleInboundBatches(');
|
||
});
|
||
});
|
||
|
||
describe('退货单号', () => {
|
||
it('生成稳定前缀 OIR_', () => {
|
||
const code = generateOrderItemReturnCode('ORD_WEB_20260821_HZ_0001', 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee');
|
||
expect(code.startsWith('OIR_')).toBe(true);
|
||
expect(code.length).toBeLessThanOrEqual(50);
|
||
expect(generateOrderItemSwitchReturnCode('ORD_WEB_20260821_HZ_0001', 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee').startsWith('OIS_')).toBe(true);
|
||
});
|
||
});
|
||
|
||
describe('入库后红冲与未入库不 409', () => {
|
||
const manageSource = readFileSync(
|
||
new URL('../src/services/orderManageItemsService.ts', import.meta.url),
|
||
'utf8'
|
||
);
|
||
const loadingSource = readFileSync(
|
||
new URL('../src/services/deliveryLoadingService.ts', import.meta.url),
|
||
'utf8'
|
||
);
|
||
|
||
it('删行按是否已入库分支,待验收未入库不再一律 409', () => {
|
||
expect(manageSource).toContain('removeOrReturnOrderItem');
|
||
expect(manageSource).toContain('orderItemHasInspectionInbound');
|
||
expect(manageSource).toContain('已验收入库,无法删除(请走退货)');
|
||
expect(manageSource).not.toContain('采购已进入待验收或已完成,无法修改或删除');
|
||
});
|
||
|
||
it('核货应配排除退货行', () => {
|
||
expect(loadingSource).toContain('COALESCE(oi.is_returned, false) = false');
|
||
expect(loadingSource).toContain("code: 'returned'");
|
||
});
|
||
|
||
it('已入库改履约方走转挂,退货仍走 markOrderItemReturned', () => {
|
||
expect(manageSource).toContain('reattributeInboundFulfillment');
|
||
expect(manageSource).not.toContain('reversePurchaseInboundForSupplierSwitch');
|
||
expect(manageSource).toContain('markOrderItemReturned');
|
||
expect(manageSource).not.toContain('inboundSupplierToSelfCorrections');
|
||
});
|
||
|
||
it('未入库改派只删该行分拣;改派 id 传入分配器', () => {
|
||
expect(manageSource).toContain('DELETE FROM picking_items WHERE order_item_id');
|
||
expect(manageSource).toContain('supplierSwitchItemIds');
|
||
expect(manageSource).toContain('from_supplier_code');
|
||
});
|
||
});
|
||
|
||
describe('markOrderItemReturned', () => {
|
||
it('已入库打标、开退货单、成本红冲;已出库不减仓', async () => {
|
||
const calls: string[] = [];
|
||
const db = {
|
||
query: vi.fn(async (sql: string) => {
|
||
const s = String(sql);
|
||
calls.push(s);
|
||
if (s.includes('FROM order_items') && s.includes('return_code')) {
|
||
return {
|
||
rowCount: 1,
|
||
rows: [
|
||
{
|
||
id: 'item-1',
|
||
sku_code: 'SKU1',
|
||
item_name: '白菜',
|
||
quantity: 2,
|
||
price: 10,
|
||
amount: 20,
|
||
unit_cost: 6,
|
||
is_extra_dish: false,
|
||
is_returned: false,
|
||
return_code: null,
|
||
},
|
||
],
|
||
};
|
||
}
|
||
if (s.includes("operation_type = 'inspection_in'")) {
|
||
return { rowCount: 1, rows: [{}] };
|
||
}
|
||
if (s.includes('picking_out')) {
|
||
return { rowCount: 1, rows: [{}] };
|
||
}
|
||
if (s.includes('FROM cost_details') || s.includes('UPDATE cost_details')) {
|
||
return { rowCount: 1, rows: [{ id: 'cd1', qty: 0 }] };
|
||
}
|
||
if (s.includes('FROM orders WHERE')) {
|
||
return { rowCount: 1, rows: [{ cycle_code: '202608', branch_code: 'BR1' }] };
|
||
}
|
||
if (s.includes('FROM after_sales')) {
|
||
if (s.includes('aftersale_type')) {
|
||
return { rowCount: 0, rows: [] };
|
||
}
|
||
return { rowCount: 1, rows: [{}] };
|
||
}
|
||
return { rowCount: 0, rows: [] };
|
||
}),
|
||
};
|
||
|
||
const result = await markOrderItemReturned(db as any, {
|
||
orderCode: 'ORD1',
|
||
branchCode: 'BR1',
|
||
item: { id: 'item-1', sku_code: 'SKU1' },
|
||
});
|
||
|
||
expect(result.already).toBe(false);
|
||
expect(result.stock_action).toBe('already_out');
|
||
expect(calls.some((s) => s.includes('is_returned = true'))).toBe(true);
|
||
expect(calls.some((s) => s.includes('INSERT INTO order_item_returns'))).toBe(true);
|
||
expect(calls.some((s) => s.includes('INSERT INTO after_sales'))).toBe(true);
|
||
// 已出库 → 不回冲库存(限定在库存日志上,见 wroteStockReturnLog 的说明)
|
||
expect(
|
||
calls.some(
|
||
(s) => s.includes('INSERT INTO inventory_logs') && s.includes("'order_item_return'")
|
||
)
|
||
).toBe(false);
|
||
expect(calls.some((s) => s.includes('UPDATE cost_details'))).toBe(true);
|
||
});
|
||
|
||
it('已退货幂等', async () => {
|
||
const db = {
|
||
query: vi.fn(async (sql: string) => {
|
||
if (String(sql).includes('FROM order_items')) {
|
||
return {
|
||
rowCount: 1,
|
||
rows: [{ id: 'item-1', is_returned: true, return_code: 'OIR_X', sku_code: 'SKU1' }],
|
||
};
|
||
}
|
||
return { rowCount: 0, rows: [] };
|
||
}),
|
||
};
|
||
const result = await markOrderItemReturned(db as any, {
|
||
orderCode: 'ORD1',
|
||
item: { id: 'item-1' },
|
||
});
|
||
expect(result.already).toBe(true);
|
||
expect(result.return_code).toBe('OIR_X');
|
||
expect(db.query.mock.calls.length).toBeGreaterThanOrEqual(2);
|
||
});
|
||
});
|
||
|
||
/**
|
||
* 红冲路径必须释放**活跃预留**(2026-10-12 对抗式复核)。
|
||
*
|
||
* 现场:`removeOrReturnOrderItem` 新增了 `covered`(库存抵扣 = 货已从我们库出)判据 ⇒
|
||
* 无验收/无备货/无采购的抵扣行也走红冲;但释放预留只写在主系统退货跟随的 `beforeRemove` 里,
|
||
* 且条件是 `inbound || prepCompleted || purchaseCompleted`(**不含 covered**)⇒
|
||
* 退货行预留仍停在 status=10。订单 ≥60 后 15 分钟,
|
||
* `cleanupStaleReservationsForCompletedOrders`(**不过滤退货行**)按预留量真扣库并落
|
||
* `delivery_loading_out` 流水 —— 货已退、成本已红冲,形成没有销售对应的静默损耗。
|
||
*/
|
||
describe('removeOrReturnOrderItem:红冲路径释放预留', () => {
|
||
const itemRow = {
|
||
id: 'item-1',
|
||
sku_code: 'SKU-COVERED',
|
||
item_name: '苹果',
|
||
quantity: 29.5,
|
||
price: 3.8,
|
||
amount: 112.1,
|
||
unit_cost: 2,
|
||
supplier_code: null,
|
||
is_extra_dish: false,
|
||
is_returned: false,
|
||
return_code: null,
|
||
};
|
||
|
||
function makeCoveredDb() {
|
||
const calls: Array<{ sql: string; params?: unknown[] }> = [];
|
||
const db = {
|
||
query: vi.fn(async (sql: string, params?: unknown[]) => {
|
||
const s = String(sql);
|
||
calls.push({ sql: s, params });
|
||
// 行存在且未退货(removeOrReturnOrderItem 的现状查询 + markOrderItemReturned 的读取共用)
|
||
if (s.includes('FROM order_items') && s.includes('return_code')) {
|
||
return { rowCount: 1, rows: [{ ...itemRow }] };
|
||
}
|
||
// 库存抵扣行的指纹:无验收 / 无备货 / 无采购,但有 stock_cover_qty
|
||
if (s.includes('COALESCE(stock_cover_qty, 0)::numeric AS cover')) {
|
||
return { rowCount: 1, rows: [{ cover: 29.5 }] };
|
||
}
|
||
if (s.includes('FROM inventory i')) return { rowCount: 0, rows: [] }; // 无可回冲批次
|
||
if (s.includes('FROM cost_details') || s.includes('UPDATE cost_details')) {
|
||
return { rowCount: 1, rows: [{ id: 'cd1', qty: 0 }] };
|
||
}
|
||
if (s.includes('FROM orders WHERE')) {
|
||
return { rowCount: 1, rows: [{ cycle_code: '202610', branch_code: 'BR1' }] };
|
||
}
|
||
if (s.includes('FROM after_sales')) {
|
||
if (s.includes('aftersale_type')) return { rowCount: 0, rows: [] };
|
||
return { rowCount: 1, rows: [{}] };
|
||
}
|
||
return { rowCount: 0, rows: [] };
|
||
}),
|
||
};
|
||
return { db, calls };
|
||
}
|
||
|
||
it('库存抵扣行(无验收/无备货/无采购)走红冲时释放 status=10 预留', async () => {
|
||
const { db, calls } = makeCoveredDb();
|
||
const outcome = await removeOrReturnOrderItem(db as any, {
|
||
orderCode: 'ORD1',
|
||
branchCode: 'BR1',
|
||
item: { ...itemRow },
|
||
hardDelete: async () => {
|
||
throw new Error('库存抵扣行不该走删行(会丢售后单与红冲)');
|
||
},
|
||
});
|
||
|
||
expect(outcome).toBe('returned');
|
||
expect(calls.some((c) => c.sql.includes('is_returned = true'))).toBe(true);
|
||
const release = calls.find(
|
||
(c) => c.sql.includes('UPDATE inventory_reservations') && c.sql.includes('status = 30')
|
||
);
|
||
expect(release, '红冲路径必须释放活跃预留,否则 15 分钟后会被真扣库').toBeTruthy();
|
||
expect(release?.params?.[0]).toBe('item-1');
|
||
});
|
||
});
|
||
|
||
describe('reversePurchaseInboundForSupplierSwitch', () => {
|
||
it('红冲采购不打退货标、不冲客户销售', async () => {
|
||
const calls: string[] = [];
|
||
const db = {
|
||
query: vi.fn(async (sql: string) => {
|
||
const s = String(sql);
|
||
calls.push(s);
|
||
if (s.includes('FROM order_items') && s.includes('id <>')) {
|
||
return { rowCount: 0, rows: [] };
|
||
}
|
||
if (s.includes('FROM order_items') && s.includes('is_returned')) {
|
||
return {
|
||
rowCount: 1,
|
||
rows: [
|
||
{
|
||
id: 'item-1',
|
||
sku_code: 'SKU1',
|
||
item_name: '白菜',
|
||
quantity: 2,
|
||
unit_cost: 6,
|
||
is_extra_dish: false,
|
||
is_returned: false,
|
||
},
|
||
],
|
||
};
|
||
}
|
||
if (s.includes('SELECT NULLIF(TRIM(inbound_batch_no)') && s.includes('FROM inspections')) {
|
||
return { rowCount: 1, rows: [{ inbound_batch_no: 'IN1' }] };
|
||
}
|
||
if (s.includes("operation_type = 'inspection_in'")) {
|
||
return { rowCount: 1, rows: [{}] };
|
||
}
|
||
if (s.includes('picking_out')) {
|
||
return { rowCount: 1, rows: [{}] };
|
||
}
|
||
if (s.includes('FROM cost_details') || s.includes('UPDATE cost_details')) {
|
||
return { rowCount: 1, rows: [{ id: 'cd1', amount: 12 }] };
|
||
}
|
||
if (s.includes('FROM order_item_fulfillments')) {
|
||
return { rowCount: 0, rows: [] };
|
||
}
|
||
if (s.includes('FROM purchase_orders')) {
|
||
return { rowCount: 0, rows: [] };
|
||
}
|
||
return { rowCount: 0, rows: [] };
|
||
}),
|
||
};
|
||
|
||
const result = await reversePurchaseInboundForSupplierSwitch(db as any, {
|
||
orderCode: 'ORD1',
|
||
itemId: 'item-1',
|
||
previousSupplierCode: 'SUP_A',
|
||
skuCode: 'SKU1',
|
||
quantity: 2,
|
||
unitCost: 6,
|
||
});
|
||
|
||
expect(result.skipped).toBe(false);
|
||
expect(result.stock_action).toBe('already_out');
|
||
expect(calls.some((s) => s.includes('is_returned = true'))).toBe(false);
|
||
expect(calls.some((s) => s.includes('INSERT INTO order_item_returns'))).toBe(true);
|
||
expect(calls.some((s) => s.includes('INSERT INTO after_sales'))).toBe(true);
|
||
expect(JSON.stringify(db.query.mock.calls).includes('改派红冲')).toBe(true);
|
||
const afterSaleInsert = db.query.mock.calls.find((c) =>
|
||
String(c[0]).includes('INSERT INTO after_sales')
|
||
);
|
||
expect(afterSaleInsert?.[1]).toEqual(expect.arrayContaining(['inbound_switch', 12]));
|
||
expect(calls.some((s) => s.includes('UPDATE inspections'))).toBe(true);
|
||
expect(JSON.stringify(db.query.mock.calls).includes('改派退供作废入库流水')).toBe(true);
|
||
});
|
||
});
|