import { beforeEach, describe, expect, it, vi } from 'vitest'; /** * **BIZ-16:订单头金额对账(一次性重算)**(2026-10-19 T10a)。 * * 缺陷:`orders.total_amount` 是冗余汇总,行被删/退货红冲后历史上有入口不重算 ⇒ 存量"头与明细不一致" * (审计样本 `ORD_API_20261018_BR002_0001`:头 253.00 / 未退货明细 249.00,差 ¥4)。 * * 口径(**不扩大财务口径**):沿用 `recalcOrderHeaderTotals` 的同一条算法 * (金额 = 未退货行 `amount` 之和;重量 = `sumWeightInJin`),本服务只补"一次性找到并写回"这一步。 * * 这份测试**构造一份不一致的库**,断言 dry-run 只报告、apply 后一致、再跑幂等。 */ const H = vi.hoisted(() => ({ tenantDataAccess: vi.fn(), })); vi.mock('../src/services/tenantSchemaService', async (importOriginal) => { const actual = await importOriginal(); return { ...actual, runWithTenantDataAccess: (...args: unknown[]) => H.tenantDataAccess(...args), }; }); const { reconcileOrderHeaderTotals, findOrderHeaderMismatches, ORDER_HEADER_TOLERANCE, } = await import('../src/services/orderHeaderReconcileService'); const { recalcOrderHeaderTotals } = await import('../src/services/mainSystemStockout'); const BRANCH = 'BR002'; type ItemRow = { order_code: string; quantity: number; unit: string; amount: number; is_returned: boolean }; type OrderRow = { order_code: string; total_amount: number; total_weight: number; deleted_at: string | null }; /** 内存版"订单头 + 明细":SQL 语义按服务里的判据实现(含红冲排除、垃圾单排除、容差) */ function makeFakeTenant(seed: { orders: OrderRow[]; items: ItemRow[] }) { const state = { orders: seed.orders.map((row) => ({ ...row })), items: seed.items.map((row) => ({ ...row })), }; const calls: Array<{ sql: string; params: unknown[] }> = []; const itemSum = (orderCode: string) => Math.round( state.items .filter((item) => item.order_code === orderCode && !item.is_returned) .reduce((sum, item) => sum + (Number(item.amount) || 0), 0) * 100 ) / 100; const mismatched = () => state.orders .filter((order) => !order.deleted_at) .map((order) => ({ order, items: itemSum(order.order_code) })) .filter(({ order, items }) => Math.abs(Number(order.total_amount || 0) - items) > ORDER_HEADER_TOLERANCE) .sort((a, b) => String(a.order.order_code).localeCompare(String(b.order.order_code))); const query = async (sql: string, params: unknown[] = []) => { const text = String(sql); calls.push({ sql: text, params }); if (text.includes('SELECT COUNT(*)::int AS n')) { return { rowCount: 1, rows: [{ n: mismatched().length }] }; } // 不一致清单(ORDER BY order_code + LIMIT $2) if (text.includes('ABS(COALESCE(o.total_amount, 0) - COALESCE(s.item_amount, 0))') && text.includes('LIMIT $2')) { const limit = Number(params[1]) || 200; const rows = mismatched() .slice(0, limit) .map(({ order, items }) => ({ order_code: order.order_code, header_amount: Number(order.total_amount || 0), item_amount: items, })); return { rowCount: rows.length, rows }; } // 明细(既有口径:未退货行) if (text.includes('SELECT quantity, unit, amount') && text.includes('FROM order_items')) { const orderCode = String(params[0]); const rows = state.items .filter((item) => item.order_code === orderCode && !item.is_returned) .map(({ quantity, unit, amount }) => ({ quantity, unit, amount })); return { rowCount: rows.length, rows }; } // 重量换算表缺失 ⇒ 回退内置系数 if (text.includes('FROM unit_conversions')) return { rowCount: 0, rows: [] }; // 写回订单头 if (text.includes('UPDATE orders SET total_amount')) { const orderCode = String(params[0]); const order = state.orders.find((row) => row.order_code === orderCode); if (order) { order.total_amount = Number(params[1]) || 0; order.total_weight = Number(params[2]) || 0; } return { rowCount: order ? 1 : 0, rows: [] }; } return { rowCount: 0, rows: [] }; }; H.tenantDataAccess.mockImplementation( async (_branch: string, fn: (client: unknown) => Promise) => fn({ query }) ); return { state, calls, query }; } const stdSeed = () => ({ orders: [ // 审计同款:头 253,未退货明细 100 + 149 = 249,差 ¥4 { order_code: 'ORD_API_20261018_BR002_0001', total_amount: 253.0, total_weight: 9.9, deleted_at: null }, // 已一致(对照,不得被改) { order_code: 'ORD_CONSISTENT_0001', total_amount: 100.0, total_weight: 2, deleted_at: null }, // 已进垃圾桶(排除) { order_code: 'ORD_TRASH_0001', total_amount: 999.0, total_weight: 0, deleted_at: new Date().toISOString() }, ] as OrderRow[], items: [ { order_code: 'ORD_API_20261018_BR002_0001', quantity: 2, unit: '斤', amount: 100.0, is_returned: false }, { order_code: 'ORD_API_20261018_BR002_0001', quantity: 3, unit: '斤', amount: 149.0, is_returned: false }, // 红冲/退货行:按既有口径**排除**(不能把 ¥50 再加回头里) { order_code: 'ORD_API_20261018_BR002_0001', quantity: 1, unit: '斤', amount: 50.0, is_returned: true }, { order_code: 'ORD_CONSISTENT_0001', quantity: 2, unit: '斤', amount: 100.0, is_returned: false }, { order_code: 'ORD_TRASH_0001', quantity: 1, unit: '斤', amount: 999.0, is_returned: false }, ] as ItemRow[], }); beforeEach(() => { H.tenantDataAccess.mockReset(); }); describe('BIZ-16 订单头金额对账(一次性重算)', () => { it('dry-run:只报告不一致(头 253 vs 明细 249,diff ¥4),一行都不改', async () => { const fake = makeFakeTenant(stdSeed()); const result = await findOrderHeaderMismatches({ branchCode: BRANCH }); expect(result.apply).toBe(false); expect(result.mismatchCount).toBe(1); expect(result.mismatches[0]).toMatchObject({ orderCode: 'ORD_API_20261018_BR002_0001', headerAmount: 253, itemAmount: 249, diff: 4, }); expect(fake.state.orders.find((o) => o.order_code === 'ORD_API_20261018_BR002_0001')?.total_amount).toBe(253); expect(fake.calls.some((call) => call.sql.includes('UPDATE orders SET total_amount'))).toBe(false); }); it('apply:按既有口径写回(金额 249、重量 5 斤;红冲行排除),再跑即一致(幂等)', async () => { const fake = makeFakeTenant(stdSeed()); const result = await reconcileOrderHeaderTotals({ branchCode: BRANCH, apply: true }); expect(result.mismatchCount).toBe(1); expect(result.fixed).toEqual([ { orderCode: 'ORD_API_20261018_BR002_0001', beforeAmount: 253, afterAmount: 249, afterWeight: 5, }, ]); expect(result.remaining, 'apply 后必须不再有头/明细不一致').toBe(0); const order = fake.state.orders.find((o) => o.order_code === 'ORD_API_20261018_BR002_0001'); expect(order?.total_amount).toBe(249); expect(order?.total_weight).toBe(5); // 对照订单未被误改 expect(fake.state.orders.find((o) => o.order_code === 'ORD_CONSISTENT_0001')?.total_amount).toBe(100); // 幂等:第二次没有任何可修的 const second = await reconcileOrderHeaderTotals({ branchCode: BRANCH, apply: true }); expect(second.mismatchCount).toBe(0); expect(second.fixed).toEqual([]); expect(second.remaining).toBe(0); }); it('分页:limit 生效,remaining 给出全量不一致数(不受 limit 影响)', async () => { const seed = stdSeed(); seed.orders.push( { order_code: 'ORD_BAD_0002', total_amount: 10.5, total_weight: 0, deleted_at: null }, { order_code: 'ORD_BAD_0003', total_amount: 20.5, total_weight: 0, deleted_at: null } ); seed.items.push( { order_code: 'ORD_BAD_0002', quantity: 1, unit: '斤', amount: 10.0, is_returned: false }, { order_code: 'ORD_BAD_0003', quantity: 1, unit: '斤', amount: 20.0, is_returned: false } ); makeFakeTenant(seed); const dry = await findOrderHeaderMismatches({ branchCode: BRANCH, limit: 2 }); expect(dry.mismatchCount, 'limit=2 ⇒ 只返回前 2 条').toBe(2); expect(dry.remaining, 'remaining 必须是全量(3 条)').toBe(3); const applied = await reconcileOrderHeaderTotals({ branchCode: BRANCH, apply: true, limit: 2 }); expect(applied.fixed).toHaveLength(2); expect(applied.remaining, '只修了 2 条 ⇒ 还剩 1 条').toBe(1); }); it('退款/红冲后 header 过期:按未退货行重算(不是把红冲金额加回去)', async () => { makeFakeTenant({ // 红冲前头 = 400(300 有效 + 100 红冲),红冲后头没跟着重算 ⇒ 过期 100 orders: [{ order_code: 'ORD_RED_0001', total_amount: 400.0, total_weight: 4, deleted_at: null }], items: [ { order_code: 'ORD_RED_0001', quantity: 3, unit: '斤', amount: 300.0, is_returned: false }, { order_code: 'ORD_RED_0001', quantity: 1, unit: '斤', amount: 100.0, is_returned: true }, ], }); const result = await reconcileOrderHeaderTotals({ branchCode: BRANCH, apply: true }); expect(result.fixed[0]).toMatchObject({ afterAmount: 300, afterWeight: 3 }); expect(result.remaining).toBe(0); }); it('缺少分公司 ⇒ 400 branch_required(不扫描全库)', async () => { makeFakeTenant(stdSeed()); await expect(reconcileOrderHeaderTotals({ branchCode: ' ' })).rejects.toMatchObject({ status: 400, code: 'branch_required', }); expect(H.tenantDataAccess).not.toHaveBeenCalled(); }); it('既有入口 recalcOrderHeaderTotals 仍走同一条口径(重构未改行为)', async () => { const fake = makeFakeTenant(stdSeed()); await recalcOrderHeaderTotals({ branchCode: BRANCH, orderCode: 'ORD_API_20261018_BR002_0001' }); expect(fake.state.orders.find((o) => o.order_code === 'ORD_API_20261018_BR002_0001')).toMatchObject({ total_amount: 249, total_weight: 5, }); }); });