Files
SupplierSystem/server/tests/mainSystemBidQuoteDb.integration.test.ts
T
Ubuntu fe10859f4d
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
feat(竞价报价): 接主系统「待报价」推送并回传单价(我方只报价、不定标)
开发者 2026-10-17 裁决:我方不做本地竞价管理(菜单已摘除),只做两件事 ——
收到主系统 bid.opened 后显示本轮要报什么、把单价报回去;中标后沿用既有「分配 → 建单」。

主系统契约(对方 docs/design/20261017-bid-opened-push.md):
· `bid.opened` 推送(单对象、无 data[]、同一套 X-Signature)
· `GET /api/supplier/bids`:列表兜底(对方 webhook 只重试 2 次)
· `GET /api/supplier/bids/:round_id`:单轮详情(明细 + 我的报价 + 我的中标)
· `POST /api/supplier/bids/:round_id/quotes`:提交报价(批量 upsert,只有我的视角)

我方实现:
· 迁移 20261055:public.main_system_bid_invitations / _invitation_items,
  幂等键 (branch_code, round_id, supplier_code)、明细 (invitation_id, sku_code)
· webhook 新增 bid.opened 分支(就地 return,绝不落进 preparations.allocated 建单兜底);
  验签逻辑一字未改;落库前按该分公司生效绑定校验并规范化 supplier_code
· 主系统调用走既有分层:services/mainSystem/{config,endpoints,http,token}.ts + api/bids.ts;
  401 强制刷新 token 只重试一次;403 判语义拒绝不重试
· 业务层:mainSystemBidInbox(整轮对齐/唯一派生口径 deriveLocalStatus)、
  mainSystemBidQuotes(列表/同步/刷新/提交 + 错误码中文映射)
· 页面侧 4 个 REST:GET 清单 / POST sync / GET :roundId / POST :roundId/quotes
  (挂 workflow 模块,权限沿用 order_manage|order_edit|order_entry)
· Web「待报价」页 + 菜单(orders-bid-invitations)+ 三语文案;复用既有 bids 命名空间

口径与边界(设计文 docs/design/20261017-主系统竞价待报价与报价提交.md):
· 事实源在主系统,我方两张表是镜像:刷新/提交成功一律「整轮先清空再写」
· 失败绝不改本地报价(不能让用户以为报上了);只写 sync_error 留痕
· 退化响应守卫:对方 2xx 但载荷不可识别 ⇒ 失败且不落库(否则会清空我方已报价与中标)
· 终态不可回退:closed / awarded / cancelled 收到迟到 bid.opened 不得改回 open
· item_count 只认去重后的实际明细行数(避免"列表 3 件、点开 2 件")
· 多绑定同一轮:页面每行带 supplierCode 精确定位;不带且命中多行 ⇒ 409 不猜
· 单价:只收 number 或纯数字字符串,>0、≤4 位小数、≤99999999.9999

验证(真实输出见交付说明):
· server/tests/mainSystemBidQuote.test.ts 28 用例、mainSystemBidQuoteBoundary.test.ts 91 用例、
  mainSystemBidQuoteDb.integration.test.ts 真库 11 用例(BID_DB_TEST=1 才跑)全过
· Web:BidInvitationsPage.render 7 用例 + 菜单契约/menuLayout 共 86 用例全过;
  npm run typecheck 0 错;cd server && npx tsc --noEmit 0 错
  (注意:根 tsconfig include 只有 src,后端必须单独 typecheck)
· 全量后端套件与基线 14d7afe 逐文件比对:失败集合完全一致(30 文件 / 38 用例,均既有失败)
· 本地真环境:伪造签名 401;真实签名连推两次只落 1 行 + 去重后 2 条明细;
  未绑定编码 ⇒ ignored 不落库;详情对不存在轮次 404 且台账自动 cancelled
· 独立复核(verifier)B1–B9/B11/B13 全 pass;红队(adversary)未发现误建单/跨租户/资金精度类高危,
  两条中危(多绑定错供应商、2xx 畸形响应清空本地)已修并被用例钉住
· 设计门禁:8 通过 / 1 已知红 check-ai-cost / verify-facts 因本地缺 tenant_br003 红(均基线)
2026-10-17 12:39:39 +08:00

415 lines
17 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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);
});
});