import { readFileSync } from 'node:fs'; import path from 'node:path'; import { describe, expect, it, vi } from 'vitest'; import { attachOrderRebateSnapshots, summarizeCustomerRebate } from '../src/services/customerRebateService'; /** * 过账扣点两条修复的回归钉子(2026-10-08): * * ① **历史订单不得被重刷**:一行只在「它被创建的那一刻」快照一次。 * 客户改比例 / 关开关后再保存一次历史单的明细,已有行必须原样不动 —— 否则历史成本被追溯改写。 * 修法:`attachOrderRebateSnapshots` 支持 `rowIds`(本次新建的行),改单路径只传新行 id; * 传空数组 = 本次没有新建行 → 一条 UPDATE 都不许发。 * * ② **入库日口径**:财务概览有「入库日」维度,扣点必须与销售额/成本落在同一窗口, * 否则净利会随维度切换少扣一笔。修法:`summarizeCustomerRebate` 支持 `inbound`, * 用与 marginQueryService 逐字相同的表达式 + LATERAL JOIN。 */ const ALL_ROWS = [ { id: 'aaaaaaaa-0000-0000-0000-000000000001', category_code: 'C1' }, { id: 'aaaaaaaa-0000-0000-0000-000000000002', category_code: 'C1' }, { id: 'aaaaaaaa-0000-0000-0000-000000000003', category_code: 'C2' }, ]; /** 只认本服务真正会发的 SQL;其它一律抛错,避免"以为测到了其实没测" */ function fakeDb(options: { mode: string | null; ratio?: number | null; categoryRatios?: Record; }) { const updates: Array<{ sql: string; params: unknown[] }> = []; const selects: Array<{ sql: string; params: unknown[] }> = []; const db = { query: vi.fn(async (sql: string, params: unknown[] = []) => { const text = String(sql); if (/FROM customers WHERE customer_code/.test(text)) { return { rows: [ { rebate_mode: options.mode, rebate_ratio: options.ratio ?? null, rebate_category_ratios: options.categoryRatios ?? {}, }, ], rowCount: 1, }; } if (/SELECT id::text AS id, category_code FROM order_items/.test(text)) { selects.push({ sql: text, params }); const scoped = params[1] as string[] | null; const rows = scoped == null ? ALL_ROWS : ALL_ROWS.filter((r) => scoped.includes(r.id)); return { rows, rowCount: rows.length }; } if (/UPDATE order_items SET rebate_ratio/.test(text)) { updates.push({ sql: text, params }); return { rows: [], rowCount: 1 }; } throw new Error('unexpected sql: ' + text); }), } as never; return { db, updates, selects }; } describe('过账扣点 · 快照只作用于新建行(历史不得重刷)', () => { it('传空 rowIds(本次没有新建行):一条 UPDATE 都不发', async () => { const { db, updates, selects } = fakeDb({ mode: 'order', ratio: 0.05 }); const res = await attachOrderRebateSnapshots({ orderCode: 'ORD_1', customerCode: 'CUS_1', rowIds: [], db, }); expect(res.updated).toBe(0); expect(updates).toHaveLength(0); expect(selects).toHaveLength(0); // 连查行都不查 }); it('传具体 rowIds:只写这些行,历史行一个不碰', async () => { const { db, updates } = fakeDb({ mode: 'order', ratio: 0.05 }); const res = await attachOrderRebateSnapshots({ orderCode: 'ORD_1', customerCode: 'CUS_1', rowIds: [ALL_ROWS[0].id], db, }); expect(res.updated).toBe(1); expect(updates).toHaveLength(1); expect(updates[0].params[0]).toBe(ALL_ROWS[0].id); expect(updates[0].params[1]).toBe(0.05); }); it('不传 rowIds(仅下单:整单都是新建行):全部行都写', async () => { const { db, updates, selects } = fakeDb({ mode: 'order', ratio: 0.08 }); const res = await attachOrderRebateSnapshots({ orderCode: 'ORD_1', customerCode: 'CUS_1', db }); expect(res.updated).toBe(3); expect(updates).toHaveLength(3); // scoped 传 null ⇒ SQL 里走 `$2::uuid[] IS NULL` 分支 expect(selects[0].params[1]).toBeNull(); }); it('客户关闭 + 只给新行:新行写 NULL,历史行不动(不再整单清空)', async () => { const { db, updates } = fakeDb({ mode: null }); const res = await attachOrderRebateSnapshots({ orderCode: 'ORD_1', customerCode: 'CUS_1', rowIds: [ALL_ROWS[2].id], db, }); expect(res.updated).toBe(1); expect(updates).toHaveLength(1); expect(updates[0].params[1]).toBeNull(); }); }); describe('过账扣点 · 改单/下单两处接线', () => { const itemSvc = readFileSync( path.join(__dirname, '../src/services/orderManageItemsService.ts'), 'utf8' ); const submitSvc = readFileSync( path.join(__dirname, '../src/services/customerOrderSubmitService.ts'), 'utf8' ); it('改单路径:收集本次新建的全部行(含加菜)并把 rowIds 传下去', () => { expect(itemSvc).toContain('const newlyInsertedItemIds: string[] = [];'); expect(itemSvc).toContain('newlyInsertedItemIds.push(newId);'); expect(itemSvc).toMatch(/rowIds:\s*newlyInsertedItemIds/); }); it('下单路径:整单新建,故意不传 rowIds(注释写明了原因)', () => { expect(submitSvc).toContain('这里**故意不传 rowIds**'); expect(submitSvc).not.toMatch(/rowIds:\s*newlyInserted/); }); }); describe('过账扣点 · 入库日口径', () => { it('dateField=inbound:走与财务概览同一表达式(含入库日 LATERAL JOIN)', async () => { const sqls: string[] = []; const db = { query: vi.fn(async (sql: string) => { sqls.push(String(sql)); // shanghaiDateOf 不会走(传的是 YYYY-MM-DD),聚合返回空 return { rows: [], rowCount: 0 }; }), } as never; const res = await summarizeCustomerRebate({ from: '2026-10-01', to: '2026-10-31', dateField: 'inbound', db, }); expect(res.date_field).toBe('inbound'); const agg = sqls.find((s) => /FROM order_items oi/.test(s)) || ''; expect(agg).toContain("COALESCE(ib.first_inbound_at, o.updated_at) AT TIME ZONE 'Asia/Shanghai'"); expect(agg).toContain('LEFT JOIN LATERAL'); expect(agg).toContain('inbound_batch_no'); }); it('未知口径仍然抛 400(不静默算 0)', async () => { const db = { query: vi.fn(async () => ({ rows: [], rowCount: 0 })) } as never; await expect( summarizeCustomerRebate({ from: '2026-10-01', to: '2026-10-31', dateField: 'nope' as never, db }) ).rejects.toMatchObject({ status: 400 }); }); });