import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; /** * D2 出站 mock(只 mock 配送侧只读接口):本文件的核心是**真库**语义(报价单明细 / proposal 表 / 台账), * `>200 行` 场景是"远端数据量",只能在 D2 侧造。 */ const remoteMock = vi.hoisted(() => ({ pages: [] as Array<{ rows: unknown[]; nextCursor: string | null }>, calls: [] as Array>, })); vi.mock('../src/services/mainSystem/api/quotePriceProposals', () => ({ submitQuotePriceProposal: vi.fn(async () => ({ kind: 'ok', status: 200, data: { proposal_id: 'remote-created', status: 'pending', replayed: false }, })), listQuotePriceProposals: vi.fn(async (input: Record) => { remoteMock.calls.push(input); const page = remoteMock.pages[remoteMock.calls.length - 1] || { rows: [], nextCursor: null }; return { kind: 'ok', status: 200, rows: page.rows, summary: null, nextCursor: page.nextCursor }; }), decideQuotePriceProposal: vi.fn(async () => ({ kind: 'ok', status: 200 })), })); /** * `quote_price_proposals` **真库**约束验证(默认跳过;`QUOTE_PRICE_PROPOSAL_DB_TEST=1` 才跑)。 * * verifier 抓到过一个真问题:T6 裁定「同方向重复提交 ⇒ 旧 pending 置 `superseded`」, * 但迁移最初的 CHECK 不含 `superseded` ⇒ 真库会 500。单测的 DB 是脚本化 mock,**永远发现不了枚举/约束**。 * 这里只验证不依赖对方系统的部分: * ① 迁移已落库(tenant_br002 + tenant_template 都有表),且 `status` CHECK **含 `superseded`**; * ② partial unique `(branch_code, quote_sheet_code, direction) WHERE status='pending'` 确实生效 * (同方向第二条 pending 撞唯一键 ⇒ 必须先 supersede 旧的); * ③ `superseded` 行不与 pending 冲突(旧行改成 superseded 后可以再插新 pending)。 * * 跑法(本地): * cd server && QUOTE_PRICE_PROPOSAL_DB_TEST=1 npx vitest run tests/quotePriceProposalDb.integration.test.ts */ const RUN = process.env.QUOTE_PRICE_PROPOSAL_DB_TEST === '1'; const SCHEMA = 'tenant_br002'; const BRANCH = 'BR002'; const SHEET = 'QS_TESTQPP_1'; const db = RUN ? await import('../src/db') : null; const pool = () => db!.pool; async function cleanup() { await pool().query(`DELETE FROM ${SCHEMA}.quote_price_proposals WHERE quote_sheet_code LIKE 'QS_TESTQPP_%'`); await pool().query(`DELETE FROM ${SCHEMA}.customer_quote_sheet_items WHERE quote_sheet_code LIKE 'QS_TESTQPP_%'`); await pool().query(`DELETE FROM ${SCHEMA}.customer_quote_sheets WHERE quote_sheet_code LIKE 'QS_TESTQPP_%'`); } async function insertProposal(input: { status: string; direction?: string }): Promise { const result = await pool().query<{ id: string }>( `INSERT INTO ${SCHEMA}.quote_price_proposals (branch_code, quote_sheet_code, main_branch_code, direction, items, payload_hash, status, client_request_id) VALUES ($1, $2, 'BR002', $3, '[]'::jsonb, 'fp-test', $4, gen_random_uuid()) RETURNING id::text AS id`, [BRANCH, SHEET, input.direction || 'to_delivery', input.status] ); return String(result.rows[0].id); } describe.skipIf(!RUN)('quote_price_proposals · 真库(T6 枚举 / partial unique)', () => { beforeAll(async () => { await cleanup(); }); afterAll(async () => { await cleanup(); await pool().end(); }); it('迁移已落库:tenant_template 与 tenant_br002 都有表,且 status CHECK 含 superseded', async () => { const tables = await pool().query<{ table_schema: string }>( `SELECT table_schema FROM information_schema.tables WHERE table_name = 'quote_price_proposals' AND table_schema IN ('tenant_template', 'tenant_br002') ORDER BY table_schema` ); expect(tables.rows.map((row) => row.table_schema)).toEqual(['tenant_br002', 'tenant_template']); const check = await pool().query<{ def: string }>( `SELECT pg_get_constraintdef(oid) AS def FROM pg_constraint WHERE conname = 'quote_price_proposals_status_chk' AND conrelid = '${SCHEMA}.quote_price_proposals'::regclass` ); expect(check.rows[0]?.def || '').toContain('superseded'); }); it('superseded 是合法状态(T6 写它不会 500)', async () => { const id = await insertProposal({ status: 'superseded' }); const row = await pool().query<{ status: string }>( `SELECT status FROM ${SCHEMA}.quote_price_proposals WHERE id = $1::uuid`, [id] ); expect(row.rows[0].status).toBe('superseded'); await pool().query(`DELETE FROM ${SCHEMA}.quote_price_proposals WHERE id = $1::uuid`, [id]); }); it('非法状态仍被 CHECK 拦住', async () => { await expect(insertProposal({ status: 'bogus' })).rejects.toThrow(); }); it('partial unique:同 (分支,单,方向) 第二条 pending 撞唯一键;把旧行改 superseded 后可插新 pending(T6 覆盖语义)', async () => { const first = await insertProposal({ status: 'pending' }); await expect(insertProposal({ status: 'pending' })).rejects.toThrow(/uq_quote_price_proposals_pending|duplicate key/); // T6 的正确顺序:旧 pending → superseded,再插新 pending await pool().query( `UPDATE ${SCHEMA}.quote_price_proposals SET status = 'superseded' WHERE id = $1::uuid`, [first] ); const second = await insertProposal({ status: 'pending' }); const rows = await pool().query<{ status: string }>( `SELECT status FROM ${SCHEMA}.quote_price_proposals WHERE quote_sheet_code = $1 AND direction = 'to_delivery' ORDER BY requested_at ASC`, [SHEET] ); expect(rows.rows.map((row) => row.status)).toEqual(['superseded', 'pending']); await pool().query(`DELETE FROM ${SCHEMA}.quote_price_proposals WHERE id = ANY($1::uuid[])`, [ [first, second], ]); }); it('A16 真库:旧 pending 被「远端 superseded」收口(不写价)后,新 pending 可插入(不撞唯一键)', async () => { const oldId = await insertProposal({ status: 'pending', direction: 'from_delivery' }); await pool().query( `UPDATE ${SCHEMA}.quote_price_proposals SET status = 'superseded', reject_reason = 'remote_superseded', updated_at = NOW() WHERE id = $1::uuid AND status = 'pending'`, [oldId] ); const oldRow = await pool().query<{ status: string; reject_reason: string | null }>( `SELECT status, reject_reason FROM ${SCHEMA}.quote_price_proposals WHERE id = $1::uuid`, [oldId] ); expect(oldRow.rows[0]).toMatchObject({ status: 'superseded', reject_reason: 'remote_superseded' }); // 收口后同 (分支,单,方向) 可以插新 pending(唯一的"在途"是新提议) const newId = await insertProposal({ status: 'pending', direction: 'from_delivery' }); expect(newId).not.toBe(oldId); await pool().query( `DELETE FROM ${SCHEMA}.quote_price_proposals WHERE id = ANY($1::uuid[])`, [[oldId, newId]] ); }); it('A16 真库 + >200 行远端:旧 id 不在第一页(已 superseded)⇒ approve 409,零写价、零推送', async () => { process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1'; const code = 'QS_TESTQPP_OLD'; const proposalId = '11111111-2222-4333-8444-555555555555'; const service = await import('../src/services/quotePriceProposalService'); const tenant = await import('../src/services/tenantDbContext'); await tenant.runWithTenantDbContext(BRANCH, async () => { await pool().query( `INSERT INTO customer_quote_sheets (quote_sheet_code, title, version_no, quote_cycle, effective_at, status, approval_status, branch_code, created_at, updated_at) VALUES ($1, '旧提议测试单', 1, 'month', NOW(), 1, 30, $2, NOW(), NOW())`, [code, BRANCH] ); await pool().query( `INSERT INTO customer_quote_sheet_items (quote_sheet_code, sku_code, sku_name, unit, price, cost_price, sale_price, sort_order) VALUES ($1, 'SKU_TESTQPP_1', '测试商品', '斤', 10, 5, 10, 0)`, [code] ); await pool().query( `INSERT INTO quote_price_proposals (id, branch_code, quote_sheet_code, main_branch_code, direction, items, payload_hash, status, client_request_id, remote_proposal_id, requested_at, updated_at) VALUES ($1::uuid, $2, $3, 'BR002', 'from_delivery', $4::jsonb, 'fp-init', 'pending', gen_random_uuid(), $5, NOW(), NOW())`, [ proposalId, BRANCH, code, JSON.stringify([{ sku_code: 'SKU_TESTQPP_1', unit: '斤', price: 11 }]), 'remote-old', ] ); }); // 远端 >200 行:第一页 200 条(最旧,不含目标行)+ 下一页游标;第二页才有目标行且已 superseded const filler = Array.from({ length: 200 }, (_, i) => ({ proposal_id: `filler-${i}`, direction: 'to_supplier', status: 'approved', supplier_quote_sheet_code: '', branch_code: 'BR002', items: [], note: null, reject_reason: null, applied: null, created_at: null, reviewed_at: null, })); remoteMock.calls.length = 0; remoteMock.pages = [ { rows: filler, nextCursor: 'page-2' }, { rows: [ { proposal_id: 'remote-old', direction: 'to_supplier', status: 'superseded', supplier_quote_sheet_code: code, branch_code: 'BR002', items: [], note: null, reject_reason: null, applied: null, created_at: null, reviewed_at: null, }, ], nextCursor: null, }, ]; await expect( tenant.runWithTenantDbContext(BRANCH, () => service.approvePriceProposal({ id: proposalId, ctx: { branchCode: BRANCH, userId: 'a0000000-0000-0000-0000-000000000001', roles: ['admin'] } as any, }) ) ).rejects.toMatchObject({ status: 409, code: 'proposal_not_pending' }); // 零写价:明细售价仍是 10 const item = await pool().query<{ sale_price: string }>( `SELECT sale_price FROM ${SCHEMA}.customer_quote_sheet_items WHERE quote_sheet_code = $1`, [code] ); expect(Number(item.rows[0].sale_price)).toBe(10); // 零推送:台账没有该单行 const ledger = await pool().query<{ n: number }>( `SELECT count(*)::int AS n FROM public.main_system_quote_cost_pushes WHERE quote_sheet_code = $1`, [code] ); expect(Number(ledger.rows[0].n)).toBe(0); // 本地提议仍 pending(留给下一轮 D2 收口),且确实翻到了第二页 const local = await pool().query<{ status: string }>( `SELECT status FROM ${SCHEMA}.quote_price_proposals WHERE id = $1::uuid`, [proposalId] ); expect(local.rows[0].status).toBe('pending'); expect(remoteMock.calls.length).toBe(2); expect(remoteMock.calls[1].cursor).toBe('page-2'); delete process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL; }); it('A16 真库:冲突接管(旧 pending 打 replaced_by_remote 后新 pending 落库)', async () => { const oldId = await insertProposal({ status: 'pending', direction: 'from_delivery' }); await pool().query( `UPDATE ${SCHEMA}.quote_price_proposals SET status = 'superseded', reject_reason = $2, updated_at = NOW() WHERE id = $1::uuid AND status = 'pending'`, [oldId, 'replaced_by_remote:remote-new'] ); const newId = await insertProposal({ status: 'pending', direction: 'from_delivery' }); const rows = await pool().query<{ status: string; reject_reason: string | null }>( `SELECT status, reject_reason FROM ${SCHEMA}.quote_price_proposals WHERE quote_sheet_code = $1 AND direction = 'from_delivery' ORDER BY requested_at ASC`, [SHEET] ); expect(rows.rows[0]).toMatchObject({ status: 'superseded', reject_reason: 'replaced_by_remote:remote-new' }); expect(rows.rows[1].status).toBe('pending'); await pool().query( `DELETE FROM ${SCHEMA}.quote_price_proposals WHERE id = ANY($1::uuid[])`, [[oldId, newId]] ); }); it('不同方向可各有一条 pending(A/B 互不挤占)', async () => { const a = await insertProposal({ status: 'pending', direction: 'to_delivery' }); // 已有一条 to_delivery pending ⇒ 先清掉,再验证 from_delivery 能建 await pool().query(`DELETE FROM ${SCHEMA}.quote_price_proposals WHERE id = $1::uuid`, [a]); const fromDelivery = await insertProposal({ status: 'pending', direction: 'from_delivery' }); const toDelivery = await insertProposal({ status: 'pending', direction: 'to_delivery' }); expect(fromDelivery).not.toBe(toDelivery); await pool().query( `DELETE FROM ${SCHEMA}.quote_price_proposals WHERE id = ANY($1::uuid[])`, [[fromDelivery, toDelivery]] ); }); });