import { describe, expect, it } from 'vitest'; import { assertAllocationsWithinInvoiceAmount, invoiceWithLinksCteSql, normalizeInvoiceAllocations, } from '../src/services/invoiceStatementLinkService'; /** * 结算发票「上传即绑定」纯逻辑单测(设计 docs/design/20260923-invoice-statement-binding.md)。 * 归属校验需要 DB,另由页面/接口验收覆盖。 */ describe('invoice statement allocations', () => { it('合并同一结算单的多行分配,金额归到分', () => { expect( normalizeInvoiceAllocations([ { statement_no: 'O20260801001', amount: 100.005 }, { statement_no: 'O20260801001', amount: 200.004 }, { statement_no: 'O20260802001', amount: 50 }, ]) ).toEqual([ { statement_no: 'O20260801001', amount: 300.01 }, { statement_no: 'O20260802001', amount: 50 }, ]); }); it('缺省/空数组视为无绑定,不抛错', () => { expect(normalizeInvoiceAllocations(undefined)).toEqual([]); expect(normalizeInvoiceAllocations(null)).toEqual([]); expect(normalizeInvoiceAllocations([])).toEqual([]); }); it('非数组、空单号、非正金额一律 400', () => { expect(() => normalizeInvoiceAllocations({ statement_no: 'A', amount: 1 })).toThrow(); expect(() => normalizeInvoiceAllocations([{ statement_no: ' ', amount: 1 }])).toThrow(); expect(() => normalizeInvoiceAllocations([{ statement_no: 'A', amount: 0 }])).toThrow(); expect(() => normalizeInvoiceAllocations([{ statement_no: 'A', amount: -5 }])).toThrow(); }); it('分配合计不得超过票面金额(分位容差内放行)', () => { expect(() => assertAllocationsWithinInvoiceAmount([{ statement_no: 'A', amount: 1000 }], 1000) ).not.toThrow(); // 分位浮点容差 expect(() => assertAllocationsWithinInvoiceAmount([{ statement_no: 'A', amount: 1000.004 }], 1000) ).not.toThrow(); expect(() => assertAllocationsWithinInvoiceAmount([{ statement_no: 'A', amount: 1000.01 }], 1000) ).toThrow(); }); it('单语句同时写发票与绑定链接(数据修改 CTE)', () => { const sql = invoiceWithLinksCteSql('customer_code'); expect(sql).toContain('INSERT INTO invoices'); expect(sql).toContain('INSERT INTO invoice_statement_links'); expect(sql).toContain('invoice_id, statement_type, statement_no, amount, branch_code'); expect(sql).toContain('unnest($13::text[], $14::numeric[])'); expect(sql).toContain('SELECT * FROM inv'); }); });