合并 feat/quote-price-sync 的报价单与竞价台账改动,补齐类型(includeDeleted/deletedAt)与缺失文件 (mainSystem/api/quotePriceProposals.ts、迁移 20261058)。
534 lines
22 KiB
TypeScript
534 lines
22 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');
|
||
// 2026-10-18 口径变更(开发者裁决 Q5):只有我方明确落标(award_status='lost')才显示「未中标」
|
||
expect(
|
||
deriveLocalStatus({ ...base, roundStatus: 'awarded', hasAward: false, hasLost: true, respondDeadline: past })
|
||
).toBe('lost');
|
||
// 明细已拉到(itemCount>0)⇒ 我方没中标行就是对方的定标事实 ⇒ 未中标
|
||
expect(deriveLocalStatus({ ...base, roundStatus: 'awarded', hasAward: false, respondDeadline: past })).toBe('lost');
|
||
// 明细还没拉到(itemCount=0)⇒ 不臆造未中标:报过价回落「已报价」,否则「待报价」
|
||
expect(
|
||
deriveLocalStatus({ ...base, itemCount: 0, roundStatus: 'awarded', hasAward: false, respondDeadline: past })
|
||
).toBe('pending');
|
||
expect(
|
||
deriveLocalStatus({
|
||
...base,
|
||
itemCount: 0,
|
||
quotedCount: 2,
|
||
roundStatus: 'awarded',
|
||
hasAward: false,
|
||
respondDeadline: past,
|
||
})
|
||
).toBe('pending');
|
||
});
|
||
|
||
it('报过价 ⇒ 已报价,即使已过截止(报价事实优先于截止时间)', () => {
|
||
// 2026-10-18 口径变更(开发者裁决 Q4):过期不再吃掉「已报价」
|
||
expect(deriveLocalStatus({ ...base, roundStatus: 'open', quotedCount: 2, respondDeadline: past })).toBe('quoted');
|
||
// 未报过价、已过截止 ⇒ 仍是已截止
|
||
expect(deriveLocalStatus({ ...base, roundStatus: 'open', quotedCount: 0, respondDeadline: past })).toBe('expired');
|
||
});
|
||
|
||
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('中标判定只认 award_status:award_price 单独不再判 won;已定标无中标行判 lost', () => {
|
||
// 2026-10-18 口径变更(开发者裁决):award_price 非空可能只是回显报价,不据此判「已中标」
|
||
expect(toBidInvitationItemDto(row({ award_price: '12.5' }) as any, 'awarded').awardStatus).toBe('lost');
|
||
expect(toBidInvitationItemDto(row({ award_price: '12.5' }) as any, 'open').awardStatus).toBe(null);
|
||
expect(toBidInvitationItemDto(row({ award_status: 'lost' }) 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();
|
||
});
|
||
});
|