开发者 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 红(均基线)
505 lines
21 KiB
TypeScript
505 lines
21 KiB
TypeScript
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||
import { readFileSync } from 'node:fs';
|
||
import path from 'node:path';
|
||
|
||
/**
|
||
* 主系统竞价「待报价」:**我方只报价、不定标**
|
||
* (设计文 docs/design/20261017-主系统竞价待报价与报价提交.md,验收 B1–B9)。
|
||
*
|
||
* 这个文件钉住四组东西:
|
||
* ① 派生口径 `deriveLocalStatus()` —— 页面 6 种状态的**唯一**算法(顺序错就会把"已中标"显示成"待报价");
|
||
* ② webhook `bid.opened` 的**接收纪律**:要就地 return(不得落进建单兜底)、不写价格、幂等键;
|
||
* ③ 提交前的本地校验 + 对方错误码映射(`bid_not_open` / `quote_deadline_passed` /
|
||
* `supplier_category_mismatch` / 401 刷新重试一次);
|
||
* ④ 失败**不改本地报价**(不能让人"以为报上了")。
|
||
*/
|
||
|
||
/* ── mock:DB(脚本化 fake client)──────────────────────────────────────────── */
|
||
|
||
const clientQuery = vi.hoisted(() => vi.fn());
|
||
const poolQuery = 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,
|
||
}));
|
||
|
||
const getMainSystemToken = vi.hoisted(() => vi.fn());
|
||
vi.mock('../src/services/mainSystem/token', () => ({
|
||
getMainSystemToken: (...args: unknown[]) => getMainSystemToken(...args),
|
||
}));
|
||
|
||
// 配置齐备(否则 api 层直接返回 not_configured,测不到映射)
|
||
vi.mock('../src/services/mainSystem/config', async (importOriginal) => {
|
||
const actual = await importOriginal<typeof import('../src/services/mainSystem/config')>();
|
||
return { ...actual, isMainSystemIntegrationEnabled: () => true };
|
||
});
|
||
|
||
const fetchMock = vi.hoisted(() => vi.fn());
|
||
vi.stubGlobal('fetch', fetchMock);
|
||
|
||
const {
|
||
deriveLocalStatus,
|
||
findInvitationByRound,
|
||
isBidOpenedEvent,
|
||
recordBidOpened,
|
||
toBidInvitationItemDto,
|
||
} = await import('../src/services/mainSystemBidInbox');
|
||
|
||
const {
|
||
isValidBidRoundId,
|
||
isValidBidUnitPrice,
|
||
submitBidQuotes,
|
||
BID_ERROR_COPY,
|
||
bidErrorCopy,
|
||
} = await import('../src/services/mainSystemBidQuotes');
|
||
|
||
const {
|
||
listMainSupplierBids,
|
||
getMainSupplierBidDetail,
|
||
submitMainSupplierBidQuotes,
|
||
readBidErrorCode,
|
||
} = await import('../src/services/mainSystem/api/bids');
|
||
|
||
/** 造一个 fetch 响应 */
|
||
function jsonResponse(status: number, body: unknown) {
|
||
return {
|
||
ok: status >= 200 && status < 300,
|
||
status,
|
||
json: async () => body,
|
||
};
|
||
}
|
||
|
||
beforeEach(() => {
|
||
clientQuery.mockReset();
|
||
poolQuery.mockReset();
|
||
// 绑定查询默认返回空(= 读不到绑定 ⇒ 不拦),个别用例用 mockResolvedValueOnce 覆盖
|
||
poolQuery.mockResolvedValue({ rows: [] });
|
||
clientRelease.mockReset();
|
||
getMainSystemToken.mockReset();
|
||
fetchMock.mockReset();
|
||
getMainSystemToken.mockResolvedValue({
|
||
kind: 'ok',
|
||
token: 'tok-1',
|
||
branchCode: 'BR002',
|
||
expiresAt: Date.now() + 60_000,
|
||
});
|
||
});
|
||
|
||
/* ── ① 派生口径 ───────────────────────────────────────────────────────────── */
|
||
|
||
describe('待报价状态派生(deriveLocalStatus,唯一口径)', () => {
|
||
const base = { itemCount: 2, quotedCount: 0, hasAward: false };
|
||
const future = new Date(Date.now() + 3600_000);
|
||
const past = new Date(Date.now() - 3600_000);
|
||
|
||
it('轮次取消 ⇒ cancelled(比"过期"更权威)', () => {
|
||
expect(deriveLocalStatus({ ...base, roundStatus: 'cancelled', respondDeadline: past })).toBe('cancelled');
|
||
});
|
||
|
||
it('轮次已定标 ⇒ 有中标行 won,没有 lost(即使已过截止)', () => {
|
||
expect(deriveLocalStatus({ ...base, roundStatus: 'awarded', hasAward: true, respondDeadline: past })).toBe('won');
|
||
expect(deriveLocalStatus({ ...base, roundStatus: 'awarded', hasAward: false, respondDeadline: past })).toBe('lost');
|
||
});
|
||
|
||
it('截止已过 或 对方说 expired ⇒ expired', () => {
|
||
expect(deriveLocalStatus({ ...base, roundStatus: 'open', respondDeadline: past })).toBe('expired');
|
||
expect(
|
||
deriveLocalStatus({ ...base, roundStatus: 'open', mainInvitationStatus: 'expired', respondDeadline: future })
|
||
).toBe('expired');
|
||
});
|
||
|
||
it('对方说 quoted 或 本地每行都有价 ⇒ quoted;否则 pending', () => {
|
||
expect(
|
||
deriveLocalStatus({ ...base, roundStatus: 'open', mainInvitationStatus: 'quoted', respondDeadline: future })
|
||
).toBe('quoted');
|
||
expect(deriveLocalStatus({ ...base, roundStatus: 'open', quotedCount: 2, respondDeadline: future })).toBe('quoted');
|
||
expect(deriveLocalStatus({ ...base, roundStatus: 'open', quotedCount: 1, respondDeadline: future })).toBe('pending');
|
||
// 明细还没拉到(itemCount=0)且没有对方状态 ⇒ 只能是 pending,不能凭空说"已报价"
|
||
expect(deriveLocalStatus({ ...base, roundStatus: 'open', itemCount: 0, respondDeadline: future })).toBe('pending');
|
||
});
|
||
|
||
it('没有截止时间 ⇒ 不判过期(只看轮次/邀约状态)', () => {
|
||
expect(deriveLocalStatus({ ...base, roundStatus: 'open', respondDeadline: null })).toBe('pending');
|
||
});
|
||
});
|
||
|
||
describe('明细 DTO:中标行的判定', () => {
|
||
const row = (over: Record<string, unknown>) => ({
|
||
id: 'i1',
|
||
invitation_id: 'inv1',
|
||
branch_code: 'BR002',
|
||
round_id: 'r1',
|
||
sku_code: 'SKU1',
|
||
sku_name: '草鱼',
|
||
unit: '斤',
|
||
unit_price: null,
|
||
remark: null,
|
||
quoted_at: null,
|
||
award_price: null,
|
||
award_qty: null,
|
||
award_status: null,
|
||
...over,
|
||
});
|
||
|
||
it('轮次已定标且我这行没中标价 ⇒ lost(不是我"还没报")', () => {
|
||
expect(toBidInvitationItemDto(row({}) as any, 'awarded').awardStatus).toBe('lost');
|
||
});
|
||
|
||
it('有中标价 ⇒ won;轮次未定标 ⇒ null', () => {
|
||
expect(toBidInvitationItemDto(row({ award_price: '12.5', award_status: 'won' }) as any, 'awarded').awardStatus).toBe(
|
||
'won'
|
||
);
|
||
expect(toBidInvitationItemDto(row({}) as any, 'open').awardStatus).toBe(null);
|
||
});
|
||
});
|
||
|
||
/* ── ② webhook 接收 ───────────────────────────────────────────────────────── */
|
||
|
||
describe('bid.opened:事件识别与落库纪律', () => {
|
||
it('只认 bid.opened(别的 bid.* 一律不接)', () => {
|
||
expect(isBidOpenedEvent('bid.opened')).toBe(true);
|
||
expect(isBidOpenedEvent('bid.closed')).toBe(false);
|
||
expect(isBidOpenedEvent(undefined)).toBe(false);
|
||
});
|
||
|
||
it('重复推送走 ON CONFLICT(幂等键 branch_code + round_id + supplier_code)', async () => {
|
||
clientQuery.mockImplementation(async (sql: string) => {
|
||
if (/INSERT INTO public\.main_system_bid_invitations AS i/i.test(sql)) {
|
||
return { rows: [{ id: 'inv-1' }] };
|
||
}
|
||
if (/SELECT i\.round_status/i.test(sql)) {
|
||
return {
|
||
rows: [
|
||
{
|
||
round_status: 'open',
|
||
main_invitation_status: null,
|
||
respond_deadline: new Date(Date.now() + 60_000).toISOString(),
|
||
item_count: 1,
|
||
quoted_count: 0,
|
||
has_award: false,
|
||
quoted_at: null,
|
||
},
|
||
],
|
||
};
|
||
}
|
||
return { rows: [] };
|
||
});
|
||
|
||
const outcome = await recordBidOpened({
|
||
branchCode: 'BR002',
|
||
supplierCode: 'SUP37831443',
|
||
payload: {
|
||
round_id: 'round-1',
|
||
round_code: 'BID001',
|
||
respond_deadline: new Date(Date.now() + 60_000).toISOString(),
|
||
item_count: 1,
|
||
items: [{ sku_code: 'SKU1', sku_name: '草鱼', unit: '斤' }],
|
||
},
|
||
});
|
||
|
||
expect(outcome.status).toBe('recorded');
|
||
expect(outcome.roundId).toBe('round-1');
|
||
const headerSql = clientQuery.mock.calls
|
||
.map(([sql]: [string]) => sql)
|
||
.find((sql: string) => /INSERT INTO public\.main_system_bid_invitations AS i/i.test(sql));
|
||
expect(headerSql).toMatch(/ON CONFLICT \(branch_code, round_id, supplier_code\) DO UPDATE/);
|
||
// 已截标/已定标/已取消都是终态,迟到的补投(含 webhook 硬编码的 open)不得改回去
|
||
expect(headerSql).toMatch(/i\.round_status IN \('closed', 'awarded', 'cancelled'\)/);
|
||
// 全程要有事务(幂等 + 头/行一致)
|
||
const sqls = clientQuery.mock.calls.map(([sql]: [string]) => sql);
|
||
expect(sqls[0]).toBe('BEGIN');
|
||
expect(sqls[sqls.length - 1]).toBe('COMMIT');
|
||
expect(clientRelease).toHaveBeenCalled();
|
||
});
|
||
|
||
it('webhook **不写价格**(价格只由拉详情/提交成功后的返回写)', async () => {
|
||
clientQuery.mockImplementation(async (sql: string) => {
|
||
if (/INSERT INTO public\.main_system_bid_invitations AS i/i.test(sql)) return { rows: [{ id: 'inv-1' }] };
|
||
if (/SELECT i\.round_status/i.test(sql)) {
|
||
return {
|
||
rows: [
|
||
{
|
||
round_status: 'open',
|
||
main_invitation_status: null,
|
||
respond_deadline: null,
|
||
item_count: 1,
|
||
quoted_count: 0,
|
||
has_award: false,
|
||
quoted_at: null,
|
||
},
|
||
],
|
||
};
|
||
}
|
||
return { rows: [] };
|
||
});
|
||
await recordBidOpened({
|
||
branchCode: 'BR002',
|
||
supplierCode: 'SUP1',
|
||
payload: { round_id: 'r1', items: [{ sku_code: 'SKU1', sku_name: '草鱼', unit: '斤', unit_price: 99 }] },
|
||
});
|
||
const itemInsert = clientQuery.mock.calls
|
||
.map(([sql]: [string]) => sql)
|
||
.find((sql: string) => /INSERT INTO public\.main_system_bid_invitation_items AS it/i.test(sql));
|
||
expect(itemInsert).toBeTruthy();
|
||
expect(itemInsert).not.toMatch(/unit_price/i);
|
||
expect(itemInsert).not.toMatch(/award_/i);
|
||
});
|
||
|
||
it('缺 round_id / 缺 supplier_code ⇒ ignored,且不落任何行', async () => {
|
||
const missingRound = await recordBidOpened({
|
||
branchCode: 'BR002',
|
||
supplierCode: 'SUP1',
|
||
payload: { items: [] },
|
||
});
|
||
expect(missingRound.status).toBe('ignored');
|
||
const missingSupplier = await recordBidOpened({
|
||
branchCode: 'BR002',
|
||
supplierCode: '',
|
||
payload: { round_id: 'r1' },
|
||
});
|
||
expect(missingSupplier.status).toBe('ignored');
|
||
expect(clientQuery).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('webhook 路由:bid.opened 分支就地 return,**不会**落进建单兜底', () => {
|
||
const routes = readFileSync(path.join(__dirname, '../src/routes/mainSystemIntegration.ts'), 'utf8');
|
||
const start = routes.indexOf('if (isBidOpenedEvent(event))');
|
||
expect(start).toBeGreaterThan(-1);
|
||
const block = routes.slice(start, routes.indexOf("if (isFulfillmentEvent(event))", start));
|
||
expect(block).toMatch(/recordBidOpened\(/);
|
||
expect(block).toMatch(/return res\.json\(/);
|
||
// 该分支内不得出现建单/导入调用(`data[]` 兜底在文件更下方)
|
||
expect(block).not.toMatch(/importMainSystemGroups/);
|
||
// 事件名必须出现在分支判定**之前**的注释之外没有意义 —— 钉住分支位置:在 branchCode 闸门之后
|
||
const gateIdx = routes.indexOf('return res.json({ ok: true, ignored: true, reason: resolved.ok ? \'not_bound\' : resolved.reason });');
|
||
expect(gateIdx).toBeGreaterThan(-1);
|
||
expect(start).toBeGreaterThan(gateIdx);
|
||
});
|
||
});
|
||
|
||
/* ── ③ 提交前的本地校验 ─────────────────────────────────────────────────────── */
|
||
|
||
describe('报价单价合法性(> 0 且最多 4 位小数)', () => {
|
||
it('挡住 0 / 负数 / 非数字 / 5 位小数', () => {
|
||
expect(isValidBidUnitPrice(0)).toBe(false);
|
||
expect(isValidBidUnitPrice(-1)).toBe(false);
|
||
expect(isValidBidUnitPrice('abc')).toBe(false);
|
||
expect(isValidBidUnitPrice(1.23456)).toBe(false);
|
||
});
|
||
|
||
it('放行 4 位小数与整数', () => {
|
||
expect(isValidBidUnitPrice(1.2345)).toBe(true);
|
||
expect(isValidBidUnitPrice(12)).toBe(true);
|
||
expect(isValidBidUnitPrice('0.0001')).toBe(true);
|
||
});
|
||
});
|
||
|
||
describe('submitBidQuotes:本地校验先挡(不打扰主系统)', () => {
|
||
it('空报价 ⇒ 400 quotes_required,且一个请求都不发', async () => {
|
||
const outcome = await submitBidQuotes({ branchCode: 'BR002', roundId: 'r1', quotes: [] });
|
||
expect(outcome.kind).toBe('rejected');
|
||
expect((outcome as any).code).toBe('quotes_required');
|
||
expect(fetchMock).not.toHaveBeenCalled();
|
||
expect(poolQuery).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('单价不合法 ⇒ 400 invalid_unit_price(带 SKU 前缀,便于行内提示)', async () => {
|
||
const outcome = await submitBidQuotes({
|
||
branchCode: 'BR002',
|
||
roundId: 'r1',
|
||
quotes: [{ skuCode: 'SKU1', unitPrice: 0 }],
|
||
});
|
||
expect((outcome as any).code).toBe('invalid_unit_price');
|
||
expect((outcome as any).message).toContain('SKU1');
|
||
expect(fetchMock).not.toHaveBeenCalled();
|
||
});
|
||
});
|
||
|
||
/* ── ④ 对方错误码映射 / 401 重试 ────────────────────────────────────────────── */
|
||
|
||
describe('主系统接口封装:错误码与 401', () => {
|
||
it('列表:settings.enabled 与邀约行都映射出来', async () => {
|
||
fetchMock.mockResolvedValue(
|
||
jsonResponse(200, {
|
||
data: [
|
||
{
|
||
round_id: 'r1',
|
||
round_code: 'BID001',
|
||
title: '今日竞价',
|
||
order_code: 'ORD1',
|
||
round_status: 'open',
|
||
status: 'pending',
|
||
respond_deadline: '2026-10-17T02:30:00.000Z',
|
||
item_count: 2,
|
||
},
|
||
],
|
||
settings: { enabled: true },
|
||
})
|
||
);
|
||
const outcome = await listMainSupplierBids('SUP1');
|
||
expect(outcome.kind).toBe('ok');
|
||
if (outcome.kind !== 'ok') return;
|
||
expect(outcome.enabled).toBe(true);
|
||
expect(outcome.rows[0]).toMatchObject({
|
||
roundId: 'r1',
|
||
roundCode: 'BID001',
|
||
roundTitle: '今日竞价',
|
||
roundStatus: 'open',
|
||
invitationStatus: 'pending',
|
||
itemCount: 2,
|
||
});
|
||
});
|
||
|
||
it('提交:请求体是对方的 snake_case(sku_code / unit_price / remark)', async () => {
|
||
fetchMock.mockResolvedValue(jsonResponse(200, { data: { round: { id: 'r1' }, items: [], my_quotes: [], awards: [] } }));
|
||
await submitMainSupplierBidQuotes({
|
||
supplierCode: 'SUP1',
|
||
roundId: 'r1',
|
||
quotes: [{ skuCode: 'SKU1', unitPrice: 12.5, remark: '现杀' }],
|
||
});
|
||
const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||
expect(JSON.parse(String(init.body))).toEqual({
|
||
quotes: [{ sku_code: 'SKU1', unit_price: 12.5, remark: '现杀' }],
|
||
});
|
||
});
|
||
|
||
it('401 ⇒ 强制刷新 token 后重试一次(只重试一次)', async () => {
|
||
fetchMock
|
||
.mockResolvedValueOnce(jsonResponse(401, { error: 'invalid_token' }))
|
||
.mockResolvedValueOnce(jsonResponse(200, { data: { round: { id: 'r1' }, items: [], my_quotes: [], awards: [] } }));
|
||
const outcome = await submitMainSupplierBidQuotes({
|
||
supplierCode: 'SUP1',
|
||
roundId: 'r1',
|
||
quotes: [{ skuCode: 'SKU1', unitPrice: 1 }],
|
||
});
|
||
expect(outcome.kind).toBe('ok');
|
||
expect(getMainSystemToken).toHaveBeenCalledTimes(2);
|
||
expect(getMainSystemToken.mock.calls[1][1]).toEqual({ forceRefresh: true });
|
||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||
});
|
||
|
||
it('403 判成"语义拒绝"(不是网络故障),错误码透出', async () => {
|
||
fetchMock.mockResolvedValue(jsonResponse(403, { error: 'supplier_category_mismatch', error_description: '不在品类' }));
|
||
const outcome = await submitMainSupplierBidQuotes({
|
||
supplierCode: 'SUP1',
|
||
roundId: 'r1',
|
||
quotes: [{ skuCode: 'SKU1', unitPrice: 1 }],
|
||
});
|
||
expect(outcome.kind).toBe('rejected');
|
||
expect((outcome as any).code).toBe('supplier_category_mismatch');
|
||
expect(readBidErrorCode({ error: 'bid_not_open' }, 400)).toBe('bid_not_open');
|
||
// 没带 error 时按状态码兜稳定内部码
|
||
expect(readBidErrorCode(null, 404)).toBe('not_found');
|
||
});
|
||
});
|
||
|
||
describe('错误码 → 中文文案(界面唯一映射表)', () => {
|
||
it('supplier_category_mismatch 透出对方原文(前端靠里面的 sku 标红那一行)', async () => {
|
||
fetchMock.mockResolvedValue(
|
||
jsonResponse(403, {
|
||
error: 'supplier_category_mismatch',
|
||
error_description: '商品 SKU78661366595 不在你的经营品类内,无法报价',
|
||
})
|
||
);
|
||
// 走 service 层(需要在本地有台账行)⇒ 这里直接验 api→文案的映射函数组合
|
||
const outcome = await submitMainSupplierBidQuotes({
|
||
supplierCode: 'SUP1',
|
||
roundId: 'r1',
|
||
quotes: [{ skuCode: 'SKU78661366595', unitPrice: 1 }],
|
||
});
|
||
expect(outcome.kind).toBe('rejected');
|
||
expect((outcome as any).code).toBe('supplier_category_mismatch');
|
||
});
|
||
|
||
it('契约里的四个错误码都有专门文案', () => {
|
||
for (const code of ['bid_not_open', 'quote_deadline_passed', 'supplier_category_mismatch', 'bid_disabled']) {
|
||
expect(BID_ERROR_COPY[code], code).toBeTruthy();
|
||
expect(bidErrorCopy(code)).not.toContain('请稍后重试,请稍后重试');
|
||
}
|
||
});
|
||
|
||
it('未知码回落到对方 error_description,再回落通用文案', () => {
|
||
expect(bidErrorCopy('unknown_code', '对方说明')).toBe('对方说明');
|
||
expect(bidErrorCopy('unknown_code')).toBe(BID_ERROR_COPY.request_failed);
|
||
});
|
||
});
|
||
|
||
describe('红队/复核后的加固(退化载荷、严格单价、多绑定、终态)', () => {
|
||
it('对方 200 但载荷不可识别({} / 非 JSON)⇒ 失败、绝不落库', async () => {
|
||
// `{}`:既无 round、也无 items/quotes/awards
|
||
fetchMock.mockResolvedValueOnce(jsonResponse(200, {}));
|
||
const emptyPayload = await submitMainSupplierBidQuotes({
|
||
supplierCode: 'SUP1',
|
||
roundId: 'r1',
|
||
quotes: [{ skuCode: 'SKU1', unitPrice: 1 }],
|
||
});
|
||
expect(emptyPayload.kind).toBe('unavailable');
|
||
expect((emptyPayload as any).code).toBe('invalid_main_system_response');
|
||
|
||
// 非 JSON(对方网关回了 HTML):http 层把 json() 解析失败吞成 null ⇒ 同样必须判失败
|
||
fetchMock.mockResolvedValueOnce({
|
||
ok: true,
|
||
status: 200,
|
||
json: async () => {
|
||
throw new Error('Unexpected token < in JSON');
|
||
},
|
||
});
|
||
const nonJson = await getMainSupplierBidDetail('SUP1', 'r1');
|
||
expect(nonJson.kind).toBe('unavailable');
|
||
expect((nonJson as any).code).toBe('invalid_main_system_response');
|
||
});
|
||
|
||
it('单价:拒绝布尔/数组/科学计数法/超上限,放行大数 4 位小数', async () => {
|
||
expect(isValidBidUnitPrice(true)).toBe(false);
|
||
expect(isValidBidUnitPrice([1.5])).toBe(false);
|
||
expect(isValidBidUnitPrice('1e-7')).toBe(false);
|
||
expect(isValidBidUnitPrice(99_999_999_999)).toBe(false);
|
||
expect(isValidBidUnitPrice('12.3456')).toBe(true);
|
||
expect(isValidBidUnitPrice(12_345_678.1234)).toBe(true);
|
||
});
|
||
|
||
it('多绑定同一轮:给了 supplier 才定位;没给且多行 ⇒ ambiguous(不猜)', async () => {
|
||
poolQuery.mockResolvedValueOnce({
|
||
rows: [
|
||
{ id: 'a', supplier_code: 'SUP-A' },
|
||
{ id: 'b', supplier_code: 'SUP-B' },
|
||
],
|
||
});
|
||
const ambiguous = await findInvitationByRound({ branchCode: 'BR002', roundId: 'r1' });
|
||
expect(ambiguous.kind).toBe('ambiguous');
|
||
expect((ambiguous as any).supplierCodes).toEqual(['SUP-A', 'SUP-B']);
|
||
|
||
poolQuery.mockResolvedValueOnce({ rows: [{ id: 'b', supplier_code: 'SUP-B' }] });
|
||
const picked = await findInvitationByRound({ branchCode: 'BR002', roundId: 'r1', supplierCode: 'SUP-B' });
|
||
expect(picked.kind).toBe('found');
|
||
// 精确查询的 SQL 必须按 supplier_code 过滤(大小写不敏感)
|
||
const sql = String(poolQuery.mock.calls[poolQuery.mock.calls.length - 1][0]);
|
||
expect(sql).toMatch(/upper\(supplier_code\) = upper\(\$3\)/);
|
||
});
|
||
|
||
it('轮次 ID 形态校验挡住控制字符/超长(防 500 + 原始 PG 错误回显)', async () => {
|
||
expect(isValidBidRoundId('11111111-2222-3333-4444-555555555555')).toBe(true);
|
||
expect(isValidBidRoundId('abc%00def')).toBe(false);
|
||
expect(isValidBidRoundId('a'.repeat(65))).toBe(false);
|
||
expect(isValidBidRoundId('')).toBe(false);
|
||
});
|
||
|
||
it('提交前本地校验失败 ⇒ 一个外部请求都不发(含 strict 单价)', async () => {
|
||
fetchMock.mockClear();
|
||
const outcome = await submitBidQuotes({
|
||
branchCode: 'BR002',
|
||
roundId: 'r1',
|
||
quotes: [{ skuCode: 'SKU1', unitPrice: true as unknown as number }],
|
||
});
|
||
expect((outcome as any).code).toBe('invalid_unit_price');
|
||
expect(fetchMock).not.toHaveBeenCalled();
|
||
});
|
||
});
|