import { beforeEach, describe, expect, it, vi } from 'vitest'; /** * `applyQuoteSheetUpdate` 抽取的**行为不变**守卫(2026-10-18 增量): * · `updateQuoteSheet` 仍是「自己开事务 → DELETE+INSERT 明细 → 刷版本 → COMMIT」, * 与原实现逐字一致(搬动代码不得改口径); * · **审批通过**走 `applyQuoteSheetUpdate(..., { client })`:在调用方事务内执行, * **不得**自己 BEGIN/COMMIT; * · 两条路径都**不碰审批字段**(`approval_status` / `approved_by` / `approved_at` / `status`), * 也不得把同分公司共享客户的其它生效单置 `status=3`(那是 `activateQuoteSheet` 的行为,本路径禁止调用它)。 */ const poolQuery = vi.hoisted(() => vi.fn()); const clientQuery = vi.hoisted(() => vi.fn()); const clientRelease = vi.hoisted(() => vi.fn()); vi.mock('../src/db', () => ({ pool: { query: (...args: unknown[]) => poolQuery(...args), connect: async () => ({ query: (...args: unknown[]) => clientQuery(...args), release: () => clientRelease(), }), }, getRawPoolQuery: () => poolQuery, })); vi.mock('../src/services/notificationService', () => ({ notifyRoleUsers: vi.fn() })); import { applyQuoteSheetUpdate, updateQuoteSheet } from '../src/services/quoteSheetService'; const SHEET = 'QS1'; const BRANCH = 'BR002'; type State = { events: string[]; sheet: Record; items: Array>; customers: string[]; }; function makeState(): State { return { events: [], sheet: { quote_sheet_code: SHEET, branch_code: BRANCH, title: '报价单 V1', version_no: 1, quote_cycle: 'month', status: 1, approval_status: 30, approved_by: 'u-approver', approved_at: '2026-10-17T00:00:00.000Z', effective_at: '2026-10-17T00:00:00.000Z', expires_at: new Date(Date.now() + 86400_000).toISOString(), auto_sale_price_by_cost: false, }, items: [ { quote_sheet_code: SHEET, sku_code: 'SKU1', unit: '斤', sale_price: '10.00', price: '10.00', cost_price: '5.00', sort_order: 0 }, ], customers: ['MAIN_BR002'], }; } function installDb(state: State): void { const handler = async (sql: string, params: unknown[] = [], fromClient: boolean) => { const text = String(sql); if (/^\s*(BEGIN|COMMIT|ROLLBACK)\s*;?\s*$/i.test(text)) { if (fromClient) state.events.push(text.trim().toUpperCase()); return { rows: [], rowCount: 0 }; } if (text.includes('UPDATE customer_quote_sheets') && text.includes('SET title = COALESCE')) { state.events.push('UPDATE_SHEET'); return { rows: [], rowCount: 1 }; } if (text.includes('DELETE FROM customer_quote_sheet_customers')) { state.events.push('DELETE_CUSTOMERS'); state.customers = []; return { rows: [], rowCount: 1 }; } if (text.includes('INSERT INTO customer_quote_sheet_customers')) { state.events.push('INSERT_CUSTOMER'); state.customers.push(String(params[1])); return { rows: [], rowCount: 1 }; } if (text.includes('DELETE FROM customer_quote_sheet_items')) { state.events.push('DELETE_ITEMS'); state.items = []; return { rows: [], rowCount: 1 }; } if (text.includes('INSERT INTO customer_quote_sheet_items')) { state.events.push('INSERT_ITEM'); state.items.push({ quote_sheet_code: String(params[0]), sku_code: String(params[1]), sku_name: params[2], unit: params[3], price: String(params[4]), cost_price: String(params[5]), sale_price: String(params[6]), markup_ratio: params[7], sort_order: params[8], }); return { rows: [], rowCount: 1 }; } if (text.includes('UPDATE customer_quote_versions') && text.includes('SET status = 0')) { state.events.push('VERSION_EXPIRE'); return { rows: [], rowCount: 0 }; } if (text.includes('INSERT INTO customer_quote_versions')) { state.events.push('VERSION_INSERT'); return { rows: [], rowCount: 1 }; } if (text.includes('SELECT COALESCE(MAX(version_no)')) { return { rows: [{ next_version: 2 }] }; } if (text.includes('FROM customer_quote_sheet_items') && text.includes('ORDER BY sort_order')) { return { rows: state.items, rowCount: state.items.length }; } if (text.includes('FROM customer_quote_sheet_items')) { return { rows: state.items, rowCount: state.items.length }; } if (text.includes('FROM customer_quote_sheet_customers') && text.includes('JOIN customers')) { return { rows: state.customers.map((customer_code) => ({ customer_code, company_name: '客户' })) }; } if (text.includes('FROM customer_quote_sheet_customers')) { return { rows: state.customers.map((customer_code) => ({ customer_code })), rowCount: state.customers.length }; } if (text.includes('FROM customers WHERE customer_code = ANY($1)')) { const codes = (params[0] as string[]) || []; return { rows: codes.map((customer_code) => ({ customer_code })), rowCount: codes.length }; } if (text.includes('FROM customer_quote_sheets')) { return { rows: [state.sheet], rowCount: 1 }; } return { rows: [], rowCount: 0 }; }; poolQuery.mockImplementation((sql: string, params?: unknown[]) => handler(sql, params || [], false)); clientQuery.mockImplementation((sql: string, params?: unknown[]) => handler(sql, params || [], true)); } const ITEMS = [ { sku_code: 'SKU1', unit: '斤', sale_price: 11, price: 11, cost_price: 5, sku_name: '草鱼' }, { sku_code: 'SKU2', unit: '袋', sale_price: 20, price: 20, cost_price: 9, sku_name: '鲤鱼' }, ]; function allSql(state: State): string[] { return [...state.events]; } beforeEach(() => { poolQuery.mockReset(); clientQuery.mockReset(); clientRelease.mockReset(); delete process.env.QUOTE_EDIT_APPROVAL; }); describe('updateQuoteSheet(行为不变)', () => { it('自己开事务:BEGIN → 改单头 → DELETE+INSERT 明细 → 刷版本 → COMMIT', async () => { const state = makeState(); installDb(state); const detail = await updateQuoteSheet({ quoteSheetCode: SHEET, items: ITEMS, ctx: { branchCode: BRANCH } as any, }); expect(detail?.quote_sheet_code).toBe(SHEET); const order = state.events.filter((event) => ['BEGIN', 'UPDATE_SHEET', 'DELETE_ITEMS', 'INSERT_ITEM', 'VERSION_EXPIRE', 'VERSION_INSERT', 'COMMIT'].includes(event) ); expect(order[0]).toBe('BEGIN'); expect(order[order.length - 1]).toBe('COMMIT'); expect(order).toContain('DELETE_ITEMS'); expect(order.filter((event) => event === 'INSERT_ITEM')).toHaveLength(2); expect(order).toContain('VERSION_EXPIRE'); expect(order).toContain('VERSION_INSERT'); expect(clientRelease).toHaveBeenCalledTimes(1); }); it('明细写入口径不变:price/sale_price 同值、cost_price 夹到 >=0、unit trim', async () => { const state = makeState(); installDb(state); await updateQuoteSheet({ quoteSheetCode: SHEET, items: [{ sku_code: 'SKU9', unit: ' 盒 ', sale_price: 12.5, cost_price: -3 }], ctx: { branchCode: BRANCH } as any, }); expect(state.items).toHaveLength(1); expect(state.items[0]).toMatchObject({ sku_code: 'SKU9', unit: '盒', price: '12.5', sale_price: '12.5', cost_price: '0', }); }); it('只改标题(不带 items/customer_codes)⇒ 不删不改明细、不删客户', async () => { const state = makeState(); installDb(state); await updateQuoteSheet({ quoteSheetCode: SHEET, title: '新标题', ctx: { branchCode: BRANCH } as any }); expect(state.events).toContain('UPDATE_SHEET'); expect(state.events).not.toContain('DELETE_ITEMS'); expect(state.events).not.toContain('DELETE_CUSTOMERS'); expect(state.items).toHaveLength(1); }); it('**不碰审批字段、不置其它共享单为 3**(不能走 activateQuoteSheet)', async () => { const state = makeState(); installDb(state); const seen: string[] = []; const record = (sql: unknown) => { seen.push(String(sql)); return undefined; }; poolQuery.mockImplementation(async (sql: string, params?: unknown[]) => { record(sql); return (await installDbAndCall(state, sql, params)) as any; }); clientQuery.mockImplementation(async (sql: string, params?: unknown[]) => { record(sql); return (await installDbAndCall(state, sql, params)) as any; }); await updateQuoteSheet({ quoteSheetCode: SHEET, items: ITEMS, ctx: { branchCode: BRANCH } as any }); for (const sql of seen) { expect(sql, sql).not.toMatch(/approval_status\s*=\s*30/); expect(sql, sql).not.toMatch(/approved_by\s*=/); expect(sql, sql).not.toMatch(/SET\s+status\s*=\s*3/i); expect(sql, sql).not.toMatch(/quote_sheet_code\s*<>\s*\$1/); } expect(allSql(state).length).toBeGreaterThan(0); }); }); /** 在断言 SQL 文本的同时复用同一套 DB 语义 */ async function installDbAndCall(state: State, sql: string, params?: unknown[]) { const handlerState = state; const text = String(sql); if (/^\s*(BEGIN|COMMIT|ROLLBACK)\s*;?\s*$/i.test(text)) { handlerState.events.push(text.trim().toUpperCase()); return { rows: [], rowCount: 0 }; } if (text.includes('UPDATE customer_quote_sheets') && text.includes('SET title = COALESCE')) { handlerState.events.push('UPDATE_SHEET'); return { rows: [], rowCount: 1 }; } if (text.includes('DELETE FROM customer_quote_sheet_items')) { handlerState.events.push('DELETE_ITEMS'); handlerState.items = []; return { rows: [], rowCount: 1 }; } if (text.includes('INSERT INTO customer_quote_sheet_items')) { handlerState.events.push('INSERT_ITEM'); handlerState.items.push({ sku_code: String(params?.[1]) }); return { rows: [], rowCount: 1 }; } if (text.includes('UPDATE customer_quote_versions') && text.includes('SET status = 0')) { handlerState.events.push('VERSION_EXPIRE'); return { rows: [], rowCount: 0 }; } if (text.includes('INSERT INTO customer_quote_versions')) { handlerState.events.push('VERSION_INSERT'); return { rows: [], rowCount: 1 }; } if (text.includes('SELECT COALESCE(MAX(version_no)')) return { rows: [{ next_version: 2 }] }; if (text.includes('FROM customer_quote_sheet_items')) return { rows: handlerState.items, rowCount: handlerState.items.length }; if (text.includes('FROM customer_quote_sheet_customers')) { return { rows: handlerState.customers.map((customer_code) => ({ customer_code, company_name: '客户' })) }; } if (text.includes('FROM customer_quote_sheets')) return { rows: [handlerState.sheet], rowCount: 1 }; return { rows: [], rowCount: 0 }; } describe('applyQuoteSheetUpdate({ client })(审核通过路径)', () => { it('传入 client 时**不自己** BEGIN/COMMIT/ROLLBACK(事务归调用方)', async () => { const state = makeState(); installDb(state); const detail = await applyQuoteSheetUpdate( { quoteSheetCode: SHEET, items: ITEMS, ctx: { branchCode: BRANCH } as any }, { client: { query: (...args: unknown[]) => clientQuery(...args) } as any } ); expect(detail?.quote_sheet_code).toBe(SHEET); expect(state.events).not.toContain('BEGIN'); expect(state.events).not.toContain('COMMIT'); expect(state.events).not.toContain('ROLLBACK'); expect(clientRelease).not.toHaveBeenCalled(); expect(state.events).toContain('DELETE_ITEMS'); expect(state.events.filter((event) => event === 'INSERT_ITEM')).toHaveLength(2); }); });