147 lines
7.2 KiB
TypeScript
147 lines
7.2 KiB
TypeScript
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||
import { readFileSync } from 'node:fs';
|
||
import path from 'node:path';
|
||
|
||
/**
|
||
* 已退货行**残留抵扣**的兜底清扫(2026-10-13 开发者批准口径:「归零并清计划/预留」)。
|
||
*
|
||
* 背景:主系统删单/删商品导致我方留下"已退货但还挂着 stock_cover_qty"的行
|
||
* (真库实况 `ORD_API_20261012_BR003_0002` 的抄手皮 cover=3、龙口粉丝 cover=5)。
|
||
* 退货路径只释放预留、**不归零抵扣** ⇒ 读侧(抵扣口径/批次明细/报告)仍把这行当"在抵扣"。
|
||
*
|
||
* 钉住:① 只动「已退货 + cover>0」的行;② 归零的同时必须释放预留(内部会清批次计划与
|
||
* 我方指定批次);③ 已挂进 15 分钟 tick;④(2026-10-14 补)**抵扣成本行也要作废** ——
|
||
* 旧清扫只归零 + 释放,成本行留着 ⇒ 真库`ORD_API_20261014_BR002_0002` 的腿子牛肉
|
||
* (主系统已删除该商品)仍挂着 ¥30.00;但同单同 SKU 有活行时**不得**整体作废(粒度只到 订单×SKU)。
|
||
*/
|
||
const query = vi.hoisted(() => vi.fn());
|
||
|
||
vi.mock('../src/db', () => ({
|
||
pool: { query: (...args: unknown[]) => query(...args) },
|
||
}));
|
||
vi.mock('../src/services/tenantDbContext', () => ({
|
||
runWithTenantDbContext: (_branch: string, fn: () => unknown) => fn(),
|
||
}));
|
||
|
||
import { sweepReturnedItemsWithCoverResidue } from '../src/services/inventoryStockCoverService';
|
||
|
||
const read = (relative: string) => readFileSync(path.join(__dirname, '..', relative), 'utf8');
|
||
const serviceSrc = read('src/services/inventoryStockCoverService.ts');
|
||
const schedulerSrc = read('src/services/scheduledJobs.ts');
|
||
|
||
/**
|
||
* 按 SQL 文本路由的假 db(清扫一轮会依次打:外层取数 → 归零 → 释放预留 → 是否有活行 → 作废成本行)。
|
||
* `costRowAffected` 模拟 `UPDATE cost_details` 的**实际影响行数**(`voided` 按它计,不按"试过就算")。
|
||
*/
|
||
function routedMock(opts: { liveSibling: boolean; costRowAffected?: number }) {
|
||
query.mockImplementation(async (sql: string) => {
|
||
const s = String(sql);
|
||
if (s.includes('COALESCE(oi.is_returned, false) = true')) {
|
||
return { rows: [{ id: 'item-1', order_code: 'ORD-1', sku_code: 'SKU-1' }], rowCount: 1 };
|
||
}
|
||
if (s.includes('SELECT 1 FROM order_items')) {
|
||
return opts.liveSibling ? { rows: [{}], rowCount: 1 } : { rows: [], rowCount: 0 };
|
||
}
|
||
if (s.includes("cost_source = 'inventory_cover'")) {
|
||
return { rows: [], rowCount: opts.costRowAffected ?? 1 };
|
||
}
|
||
return { rows: [], rowCount: 0 };
|
||
});
|
||
}
|
||
|
||
describe('退货行残留抵扣清扫', () => {
|
||
beforeEach(() => {
|
||
query.mockReset();
|
||
});
|
||
|
||
it('① 只动「已退货 + 抵扣>0」的行(SQL 条件可查)', async () => {
|
||
query.mockResolvedValue({ rows: [], rowCount: 0 });
|
||
await sweepReturnedItemsWithCoverResidue('BR003', 100);
|
||
const sql = String(query.mock.calls[0][0]);
|
||
expect(sql).toContain('COALESCE(oi.is_returned, false) = true');
|
||
expect(sql).toContain('COALESCE(oi.stock_cover_qty, 0) > 0.000001');
|
||
expect(sql).toContain('oi.return_code IS NULL OR oi.return_code NOT LIKE');
|
||
expect(sql.startsWith('SELECT')).toBe(true);
|
||
});
|
||
|
||
it('①b 主系统退回行(return_code 以 R 开头)不被清,退货行(OIR_)仍被清', async () => {
|
||
const allRows = [
|
||
{ id: 'r-row', order_code: 'ORD-1', sku_code: 'SKU-1', return_code: 'R1792492615025W7B2' },
|
||
{ id: 'oir-row', order_code: 'ORD-1', sku_code: 'SKU-1', return_code: 'OIR_1' },
|
||
{ id: 'null-row', order_code: 'ORD-1', sku_code: 'SKU-1', return_code: null },
|
||
];
|
||
query.mockImplementation(async (sql: string, params: unknown[] = []) => {
|
||
const text = String(sql);
|
||
if (text.includes('COALESCE(oi.is_returned, false) = true')) {
|
||
// 模拟 DB 的 WHERE:R 开头的退回行被排除,OIR/空码行保留
|
||
const selected = allRows.filter((r) => !(r.return_code && r.return_code.startsWith('R')));
|
||
return { rows: selected, rowCount: selected.length };
|
||
}
|
||
if (text.includes('SELECT 1 FROM order_items')) return { rows: [], rowCount: 0 };
|
||
if (text.includes("cost_source = 'inventory_cover'")) return { rows: [], rowCount: 1 };
|
||
return { rows: [], rowCount: 1 };
|
||
});
|
||
|
||
const res = await sweepReturnedItemsWithCoverResidue('BR003', 10);
|
||
expect(res.cleared).toBe(2);
|
||
const clearedIds = query.mock.calls
|
||
.filter((c) => String(c[0]).includes('UPDATE order_items SET stock_cover_qty'))
|
||
.map((c) => String((c[1] as unknown[])[0]));
|
||
expect(clearedIds).toContain('oir-row');
|
||
expect(clearedIds).toContain('null-row');
|
||
expect(clearedIds).not.toContain('r-row');
|
||
});
|
||
|
||
it('② 归零 + 释放预留(释放内部清 FIFO 批次计划与我方指定批次)', async () => {
|
||
query
|
||
.mockResolvedValueOnce({ rows: [{ id: 'item-1', order_code: 'ORD-1' }], rowCount: 1 })
|
||
.mockResolvedValue({ rows: [], rowCount: 1 });
|
||
const res = await sweepReturnedItemsWithCoverResidue('BR003', 10);
|
||
expect(res.cleared).toBe(1);
|
||
const sqls = query.mock.calls.map((c) => String(c[0]));
|
||
expect(sqls.some((s) => s.includes('UPDATE order_items SET stock_cover_qty = $2'))).toBe(true);
|
||
expect(sqls.some((s) => s.includes('UPDATE inventory_reservations'))).toBe(true);
|
||
});
|
||
|
||
it('③ 空扫不报错、返回 0', async () => {
|
||
query.mockResolvedValue({ rows: [], rowCount: 0 });
|
||
expect(await sweepReturnedItemsWithCoverResidue('BR003')).toEqual({ cleared: 0, voided: 0 });
|
||
expect(await sweepReturnedItemsWithCoverResidue('')).toEqual({ cleared: 0, voided: 0 });
|
||
});
|
||
|
||
it('⑤ 同单同 SKU 无活行 ⇒ 顺带作废抵扣成本行(2026-10-14 补)', async () => {
|
||
routedMock({ liveSibling: false, costRowAffected: 1 });
|
||
const res = await sweepReturnedItemsWithCoverResidue('BR003', 10);
|
||
expect(res.cleared).toBe(1);
|
||
expect(res.voided, '无活行且确有成本行时必须作废(腿子牛肉那 ¥30 就是这种残留)').toBe(1);
|
||
const sqls = query.mock.calls.map((c) => String(c[0]));
|
||
expect(
|
||
sqls.some((s) => s.includes('SET amount = 0') && s.includes("cost_source = 'inventory_cover'"))
|
||
).toBe(true);
|
||
});
|
||
|
||
it('⑤b 没匹配到成本行 ⇒ voided 记 0(不把"没匹配到"报成"已作废")', async () => {
|
||
routedMock({ liveSibling: false, costRowAffected: 0 });
|
||
const res = await sweepReturnedItemsWithCoverResidue('BR003', 10);
|
||
expect(res.cleared).toBe(1);
|
||
expect(res.voided).toBe(0);
|
||
});
|
||
|
||
it('⑥ 同单同 SKU 尚有活行 ⇒ 只归零/释放,不作废成本行(避免误伤活行成本)', async () => {
|
||
routedMock({ liveSibling: true });
|
||
const res = await sweepReturnedItemsWithCoverResidue('BR003', 10);
|
||
expect(res.cleared).toBe(1);
|
||
expect(res.voided).toBe(0);
|
||
const sqls = query.mock.calls.map((c) => String(c[0]));
|
||
expect(
|
||
sqls.some((s) => s.includes('SET amount = 0') && s.includes("cost_source = 'inventory_cover'"))
|
||
).toBe(false);
|
||
});
|
||
|
||
it('④ 已挂进 15 分钟 tick(防复发:不靠人工跑脚本)', () => {
|
||
expect(schedulerSrc).toContain('runReturnedCoverResidueSweep');
|
||
expect(schedulerSrc).toContain('sweepReturnedItemsWithCoverResidue');
|
||
expect(serviceSrc).toContain('sweepReturnedItemsWithCoverResidue');
|
||
});
|
||
});
|