import { afterAll, beforeAll, describe, expect, it } from 'vitest'; /** * 竞价台账**真库**验证(默认跳过;`BID_DB_TEST=1` 才跑)。 * * 为什么需要这一份:`mainSystemBidQuoteBoundary.test.ts` 用一个内存版两张表接管 SQL —— 那是 * **我写的第二份 SQL 语义**,可能骗过自己。这一份连真 Postgres(本地 `supplier_delivery`), * 只验证**不依赖对方系统**的那一半: * * · 幂等键 `(branch_code, round_id, supplier_code)` 真的会被 ON CONFLICT 命中; * · `applyBidDetail` 的"先清空再按对方返回重写"在真库里确实删行 / 清价; * · `awarded` 且无中标时 `local_status` 真的是 `lost`(不是读到 `pending`); * · 迁移里的 CHECK / 唯一索引**确实已生效**(不是只写在文件里)。 * * 纪律:只碰 `public.main_system_bid_*`,且只碰 `branch_code` 以 `BR_TESTBID` 开头的临时行, * 跑完级联删除干净(`ON DELETE CASCADE` 会带走明细)。 * * 跑法(本地): * cd server && BID_DB_TEST=1 npx vitest run tests/mainSystemBidQuoteDb.integration.test.ts */ const RUN = process.env.BID_DB_TEST === '1'; const TEST_BRANCH = `BR_TESTBID_${Date.now()}`; const SUPPLIER_A = 'SUP_TESTBID_A'; const SUPPLIER_B = 'SUP_TESTBID_B'; // 默认(未设 BID_DB_TEST)连 src/db 都不加载,保证常规套件不受影响 const real = RUN ? { db: await import('../src/db'), inbox: await import('../src/services/mainSystemBidInbox'), quotes: await import('../src/services/mainSystemBidQuotes'), } : null; const pool = () => real!.db.pool; async function cleanup() { await pool().query(`DELETE FROM public.main_system_bid_invitations WHERE branch_code = $1 OR branch_code LIKE 'BR_TESTBID%'`, [ TEST_BRANCH, ]); } describe.skipIf(!RUN)('竞价台账 · 真库(B2/B6/B15 + 迁移约束)', () => { beforeAll(async () => { await cleanup(); }); afterAll(async () => { await cleanup(); await pool().end(); }); it('迁移已在本地库生效:两张表都在 public', async () => { const { rows } = await pool().query( `SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_name IN ('main_system_bid_invitations','main_system_bid_invitation_items') ORDER BY table_name` ); expect(rows.map((row: { table_name: string }) => row.table_name)).toEqual([ 'main_system_bid_invitation_items', 'main_system_bid_invitations', ]); }); it('B2 幂等:webhook 连推两次 ⇒ 1 行邀约 + 2 行明细(ON CONFLICT 生效)', async () => { const roundId = `round-it-${Date.now()}-idem`; const payload = { round_id: roundId, round_code: 'BID-IT', respond_deadline: new Date(Date.now() + 3600_000).toISOString(), item_count: 2, items: [ { sku_code: 'SKU_IT_1', sku_name: '草鱼', unit: '斤' }, { sku_code: 'SKU_IT_2', sku_name: '鲤鱼', unit: '斤' }, ], }; const first = await real!.inbox.recordBidOpened({ branchCode: TEST_BRANCH, supplierCode: SUPPLIER_A, payload }); const second = await real!.inbox.recordBidOpened({ branchCode: TEST_BRANCH, supplierCode: SUPPLIER_A, payload }); expect(first.status).toBe('recorded'); expect(second.status).toBe('recorded'); expect(second.roundId).toBe(first.roundId); const { rows } = await pool().query( `SELECT id, item_count, round_status, local_status FROM public.main_system_bid_invitations WHERE branch_code = $1 AND round_id = $2`, [TEST_BRANCH, roundId] ); expect(rows).toHaveLength(1); expect(Number(rows[0].item_count)).toBe(2); expect(rows[0].round_status).toBe('open'); expect(rows[0].local_status).toBe('pending'); const items = await pool().query( `SELECT sku_code FROM public.main_system_bid_invitation_items WHERE invitation_id = $1 ORDER BY sku_code`, [rows[0].id] ); expect(items.rows.map((row: { sku_code: string }) => row.sku_code)).toEqual(['SKU_IT_1', 'SKU_IT_2']); }); it('唯一索引不允许同 (branch, round, supplier) 两行(裸 INSERT 会炸)', async () => { const roundId = `round-it-${Date.now()}-uniq`; await real!.inbox.recordBidOpened({ branchCode: TEST_BRANCH, supplierCode: SUPPLIER_A, payload: { round_id: roundId, items: [] }, }); await expect( pool().query( `INSERT INTO public.main_system_bid_invitations (branch_code, supplier_code, round_id) VALUES ($1, $2, $3)`, [TEST_BRANCH, SUPPLIER_A, roundId] ) ).rejects.toThrow(/duplicate key|uq_main_system_bid_invitations_branch_round_supplier/); }); it('B6 对方删行 ⇒ 真库里那一行被 DELETE,item_count 收缩', async () => { const roundId = `round-it-${Date.now()}-del`; await real!.inbox.recordBidOpened({ branchCode: TEST_BRANCH, supplierCode: SUPPLIER_A, payload: { round_id: roundId, item_count: 2, items: [ { sku_code: 'SKU_IT_1', sku_name: '草鱼', unit: '斤' }, { sku_code: 'SKU_IT_2', sku_name: '鲤鱼', unit: '斤' }, ], }, }); const result = await real!.inbox.applyBidDetail({ branchCode: TEST_BRANCH, supplierCode: SUPPLIER_A, roundId, detail: { round: { id: roundId, status: 'open', respond_deadline: new Date(Date.now() + 3600_000).toISOString() }, invitation: { status: 'pending' }, items: [{ sku_code: 'SKU_IT_1', sku_name: '草鱼', unit: '斤' }], myQuotes: [{ sku_code: 'SKU_IT_1', unit_price: 12.5 }], myAwards: [], }, }); // 剩下那行有价且行数=1 ⇒ 真库重算后是 quoted(同时也证明 item_count 参与派生) expect(result.localStatus).toBe('quoted'); const header = await pool().query( `SELECT id, item_count FROM public.main_system_bid_invitations WHERE branch_code = $1 AND round_id = $2`, [TEST_BRANCH, roundId] ); expect(Number(header.rows[0].item_count)).toBe(1); const items = await pool().query( `SELECT sku_code, unit_price FROM public.main_system_bid_invitation_items WHERE invitation_id = $1`, [header.rows[0].id] ); expect(items.rows).toHaveLength(1); expect(items.rows[0].sku_code).toBe('SKU_IT_1'); expect(Number(items.rows[0].unit_price)).toBe(12.5); }); it('B6 对方撤回报价 ⇒ 真库里 unit_price / quoted_at 变 NULL,local_status 回 pending', async () => { const roundId = `round-it-${Date.now()}-withdraw`; await real!.inbox.recordBidOpened({ branchCode: TEST_BRANCH, supplierCode: SUPPLIER_A, payload: { round_id: roundId, item_count: 1, items: [{ sku_code: 'SKU_IT_1' }] }, }); const first = await real!.inbox.applyBidDetail({ branchCode: TEST_BRANCH, supplierCode: SUPPLIER_A, roundId, detail: { round: { id: roundId, status: 'open', respond_deadline: new Date(Date.now() + 3600_000).toISOString() }, invitation: { status: 'quoted' }, items: [{ sku_code: 'SKU_IT_1' }], myQuotes: [{ sku_code: 'SKU_IT_1', unit_price: 12.5, updated_at: new Date().toISOString() }], myAwards: [], }, }); expect(first.localStatus).toBe('quoted'); const second = await real!.inbox.applyBidDetail({ branchCode: TEST_BRANCH, supplierCode: SUPPLIER_A, roundId, detail: { round: { id: roundId, status: 'open', respond_deadline: new Date(Date.now() + 3600_000).toISOString() }, invitation: { status: 'pending' }, items: [{ sku_code: 'SKU_IT_1' }], myQuotes: [], myAwards: [], }, }); expect(second.localStatus).toBe('pending'); const row = await pool().query( `SELECT it.unit_price, it.quoted_at FROM public.main_system_bid_invitation_items it JOIN public.main_system_bid_invitations i ON i.id = it.invitation_id WHERE i.branch_code = $1 AND i.round_id = $2`, [TEST_BRANCH, roundId] ); expect(row.rows[0].unit_price).toBe(null); expect(row.rows[0].quoted_at).toBe(null); }); it('B6 awarded 且该 SKU 无中标 ⇒ 真库 award 列为空、读取视图 local_status/awardStatus 都是 lost', async () => { const roundId = `round-it-${Date.now()}-lost`; await real!.inbox.recordBidOpened({ branchCode: TEST_BRANCH, supplierCode: SUPPLIER_A, payload: { round_id: roundId, item_count: 1, items: [{ sku_code: 'SKU_IT_1' }] }, }); const applied = await real!.inbox.applyBidDetail({ branchCode: TEST_BRANCH, supplierCode: SUPPLIER_A, roundId, detail: { round: { id: roundId, status: 'awarded' }, invitation: { status: 'quoted' }, items: [{ sku_code: 'SKU_IT_1' }], myQuotes: [{ sku_code: 'SKU_IT_1', unit_price: 12.5 }], myAwards: [], }, }); expect(applied.localStatus).toBe('lost'); const detail = await real!.inbox.getBidInvitationDetail({ branchCode: TEST_BRANCH, roundId }); expect(detail?.invitation.localStatus).toBe('lost'); expect(detail?.items.map((item) => item.awardStatus)).toEqual(['lost']); expect(detail?.myAwards).toEqual([]); expect(detail?.canQuote).toBe(false); const stored = await pool().query( `SELECT it.award_price, it.award_status FROM public.main_system_bid_invitation_items it JOIN public.main_system_bid_invitations i ON i.id = it.invitation_id WHERE i.branch_code = $1 AND i.round_id = $2`, [TEST_BRANCH, roundId] ); expect(stored.rows[0].award_price).toBe(null); expect(stored.rows[0].award_status).toBe(null); }); it('B6 awarded 且中标 ⇒ award_price 落 numeric(14,4),localStatus=won', async () => { const roundId = `round-it-${Date.now()}-won`; await real!.inbox.recordBidOpened({ branchCode: TEST_BRANCH, supplierCode: SUPPLIER_A, payload: { round_id: roundId, item_count: 1, items: [{ sku_code: 'SKU_IT_1' }] }, }); const applied = await real!.inbox.applyBidDetail({ branchCode: TEST_BRANCH, supplierCode: SUPPLIER_A, roundId, detail: { round: { id: roundId, status: 'awarded' }, invitation: { status: 'quoted' }, items: [{ sku_code: 'SKU_IT_1' }], myQuotes: [{ sku_code: 'SKU_IT_1', unit_price: 12.5 }], myAwards: [{ sku_code: 'SKU_IT_1', unit_price: 11.2345 }], }, }); expect(applied.localStatus).toBe('won'); const stored = await pool().query( `SELECT it.award_price::text AS award_price, it.award_status, it.unit_price::text AS unit_price FROM public.main_system_bid_invitation_items it JOIN public.main_system_bid_invitations i ON i.id = it.invitation_id WHERE i.branch_code = $1 AND i.round_id = $2`, [TEST_BRANCH, roundId] ); // numeric(14,4) 至少保留到 4 位小数(11.2345 不能被舍成 11.23) expect(Number(stored.rows[0].award_price)).toBe(11.2345); expect(stored.rows[0].award_status).toBe('won'); expect(Number(stored.rows[0].unit_price)).toBe(12.5); }); it('B15 真库两行同轮不同 supplier ⇒ ambiguous;带 supplier 精确命中', async () => { const roundId = `round-it-${Date.now()}-multi`; for (const supplierCode of [SUPPLIER_A, SUPPLIER_B]) { await real!.inbox.recordBidOpened({ branchCode: TEST_BRANCH, supplierCode, payload: { round_id: roundId, item_count: 1, items: [{ sku_code: 'SKU_IT_1' }] }, }); } const ambiguous = await real!.inbox.findInvitationByRound({ branchCode: TEST_BRANCH, roundId }); expect(ambiguous.kind).toBe('ambiguous'); expect( (ambiguous as unknown as { supplierCodes: string[] }).supplierCodes.sort() ).toEqual([SUPPLIER_A, SUPPLIER_B]); const exact = await real!.inbox.findInvitationByRound({ branchCode: TEST_BRANCH, roundId, supplierCode: SUPPLIER_B.toLowerCase(), }); expect(exact.kind).toBe('found'); expect((exact as unknown as { row: { supplier_code: string } }).row.supplier_code).toBe(SUPPLIER_B); }); it('迁移 CHECK 真的生效:local_status / round_status / award_status / unit_price>0 被库拒绝', async () => { const base = `round-it-${Date.now()}-check`; const insert = (roundId: string, localStatus: string) => pool().query( `INSERT INTO public.main_system_bid_invitations (branch_code, supplier_code, round_id, local_status) VALUES ($1, $2, $3, $4)`, [TEST_BRANCH, SUPPLIER_A, roundId, localStatus] ); await expect(insert(`${base}-1`, 'weird')).rejects.toThrow(/local_status_check|violates check constraint/); await expect(insert(`${base}-2`, 'closed')).rejects.toThrow(/local_status_check|violates check constraint/); await expect( pool().query( `INSERT INTO public.main_system_bid_invitations (branch_code, supplier_code, round_id, round_status) VALUES ($1, $2, $3, 'weird')`, [TEST_BRANCH, SUPPLIER_A, `${base}-3`] ) ).rejects.toThrow(/round_status_check|violates check constraint/); // 明细的两条 CHECK:award_status 只允许 won/lost;unit_price 必须 > 0 await real!.inbox.recordBidOpened({ branchCode: TEST_BRANCH, supplierCode: SUPPLIER_A, payload: { round_id: `${base}-4`, item_count: 1, items: [{ sku_code: 'SKU_IT_1' }] }, }); const invitation = await real!.inbox.findInvitationByRound({ branchCode: TEST_BRANCH, roundId: `${base}-4` }); expect(invitation.kind).toBe('found'); const invitationId = (invitation as unknown as { row: { id: string } }).row.id; await expect( pool().query( `INSERT INTO public.main_system_bid_invitation_items (invitation_id, branch_code, round_id, sku_code, award_status) VALUES ($1, $2, $3, 'SKU_IT_X', 'maybe')`, [invitationId, TEST_BRANCH, `${base}-4`] ) ).rejects.toThrow(/award_status_check|violates check constraint/); await expect( pool().query( `INSERT INTO public.main_system_bid_invitation_items (invitation_id, branch_code, round_id, sku_code, unit_price) VALUES ($1, $2, $3, 'SKU_IT_Y', 0)`, [invitationId, TEST_BRANCH, `${base}-4`] ) ).rejects.toThrow(/unit_price_check|violates check constraint/); }); it('B4 清单:真 SQL 的 status 过滤 + summary 口径(pending/history、closed=终态之和)', async () => { const branch = `${TEST_BRANCH}_B4`; // 三种状态各造一行:pending / quoted / cancelled await real!.inbox.recordBidOpened({ branchCode: branch, supplierCode: SUPPLIER_A, payload: { round_id: 'round-b4-p', item_count: 1, items: [{ sku_code: 'SKU_IT_1' }] }, }); await real!.inbox.recordBidOpened({ branchCode: branch, supplierCode: SUPPLIER_A, payload: { round_id: 'round-b4-q', item_count: 1, items: [{ sku_code: 'SKU_IT_1' }] }, }); await real!.inbox.applyBidDetail({ branchCode: branch, supplierCode: SUPPLIER_A, roundId: 'round-b4-q', detail: { round: { id: 'round-b4-q', status: 'open', respond_deadline: new Date(Date.now() + 3600_000).toISOString() }, invitation: { status: 'quoted' }, items: [{ sku_code: 'SKU_IT_1' }], myQuotes: [{ sku_code: 'SKU_IT_1', unit_price: 5 }], myAwards: [], }, }); await real!.inbox.recordBidOpened({ branchCode: branch, supplierCode: SUPPLIER_A, payload: { round_id: 'round-b4-c', item_count: 1, items: [{ sku_code: 'SKU_IT_1' }] }, }); await real!.inbox.markInvitationCancelled({ branchCode: branch, roundId: 'round-b4-c', supplierCode: SUPPLIER_A, reason: 'it: cancelled', }); const pending = await real!.quotes.listBidInvitations({ branchCode: branch, status: 'pending' }); expect(pending.rows.map((row) => row.roundId)).toEqual(['round-b4-p']); const history = await real!.quotes.listBidInvitations({ branchCode: branch, status: 'history' }); expect(history.rows.map((row) => row.roundId).sort()).toEqual(['round-b4-c', 'round-b4-q']); const all = await real!.quotes.listBidInvitations({ branchCode: branch, status: 'all' }); expect(all.summary).toMatchObject({ pending: 1, quoted: 1, cancelled: 1, closed: 1 }); const other = await real!.quotes.listBidInvitations({ branchCode: 'BR_TESTBID_NOPE', status: 'all' }); expect(other.rows).toEqual([]); }); it('派生口径在真库时钟下成立:截止已过 ⇒ expired(读库取 timestamptz)', async () => { const roundId = `round-it-${Date.now()}-expired`; const past = new Date(Date.now() - 60_000).toISOString(); await real!.inbox.recordBidOpened({ branchCode: TEST_BRANCH, supplierCode: SUPPLIER_A, payload: { round_id: roundId, respond_deadline: past, item_count: 1, items: [{ sku_code: 'SKU_IT_1' }] }, }); const detail = await real!.inbox.getBidInvitationDetail({ branchCode: TEST_BRANCH, roundId }); expect(detail?.deadlinePassed).toBe(true); expect(detail?.invitation.localStatus).toBe('expired'); expect(detail?.canQuote).toBe(false); }); }); describe.skipIf(RUN)('真库验证(默认跳过)', () => { it('设置 BID_DB_TEST=1 才连真库;常规套件不加载 src/db', () => { expect(real).toBe(null); }); });