开发者 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 红(均基线)
1864 lines
80 KiB
TypeScript
1864 lines
80 KiB
TypeScript
import express from 'express';
|
||
import request from 'supertest';
|
||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||
import { readFileSync } from 'node:fs';
|
||
import path from 'node:path';
|
||
|
||
/**
|
||
* 主系统竞价「待报价 + 报价提交」——**独立补边界**(tester 任务,B1–B15 里自测薄弱的面)。
|
||
*
|
||
* 与开发者自测 `mainSystemBidQuote.test.ts` 的分工(那个文件**不修改**):
|
||
* 自测钉的是"每条主路径存在";本文件钉的是**边界与失败路径的可观测后果**:
|
||
*
|
||
* · B3 未绑定 / 未知编码推送 ⇒ ignored 且**零落库**;读不到绑定 ⇒ 不拦;大小写规范化;
|
||
* · B5 同步:`settings.enabled=false` + `data:[]` ⇒ **一个事务都不开**(不改本地状态);
|
||
* `data` 有行 ⇒ **只 upsert 邀约头**(零明细写入)+ 成功后清 `sync_error` + `item_count` 可收缩;
|
||
* · B6 整轮对齐:对方删行 ⇒ 本地行被删;对方撤回报价 ⇒ 本地价被清、状态回 pending;
|
||
* 对方 awarded 且该 SKU 无中标 ⇒ 读取视图 `lost`;有中标 ⇒ `won`;
|
||
* · B7 本地校验:7 种畸形单价 / 空报价 / 过截止 / 轮次 closed / SKU 不在本轮 —— **零外呼**;
|
||
* · B8 出站:401 只刷一次 token 且只重试一次、第二次 401 即失败;403 不重试;请求体 snake_case;
|
||
* 出站身份取**该邀约行**的 `supplier_code`(多绑定);
|
||
* · B9 失败不落价:5xx / 超时 / 2xx 退化载荷(`{}`、非 JSON、缺 data)⇒ 失败、**不动本地报价**、
|
||
* 只写 `sync_error`(并直接钉住"没有调用 applyBidDetail");404 ⇒ 软删 cancelled;
|
||
* · B15 多绑定同轮:不带 supplier ⇒ 409 `bid_invitation_ambiguous` 且零外呼;带 supplier ⇒ 精确命中;
|
||
* · 派生口径:优先级 cancelled > awarded > expired > quoted > pending、`respond_deadline=null`、
|
||
* 时钟/时区边界;
|
||
* · 迁移:两张表、两个幂等键、`IF NOT EXISTS`、6 种 `local_status` 的 CHECK。
|
||
*
|
||
* 造数方式(照仓内既有风格):
|
||
* · `vi.mock('../src/db')` —— 用一个**内存版两张表**(`createFakeBidDb`)接管 SQL,
|
||
* 这样才能断言"落库后的行到底长什么样",而不只是"发过某条 SQL";
|
||
* · `vi.stubGlobal('fetch')` —— 对方接口的每一个响应都可脚本化;
|
||
* · token / 配置 / 绑定列表都 mock,保证一个用例里"外呼次数"可数。
|
||
*
|
||
* 设计文档:docs/design/20261017-主系统竞价待报价与报价提交.md §8(B1–B15)
|
||
*/
|
||
|
||
/* ── mock 句柄(vi.hoisted:factory 里可用) ─────────────────────────────────── */
|
||
|
||
const H = vi.hoisted(() => ({
|
||
clientQuery: vi.fn(),
|
||
poolQuery: vi.fn(),
|
||
clientRelease: vi.fn(),
|
||
token: vi.fn(),
|
||
fetchMock: vi.fn(),
|
||
/** 该分公司生效绑定的 supplier_code 列表(B3/B5/B8 的开关) */
|
||
bindingCodes: vi.fn(),
|
||
/** 让绑定查询抛错(B3 的"读不到绑定 ⇒ 不拦") */
|
||
bindingError: { value: null as Error | null },
|
||
/** 包一层 applyBidDetail,既能调用真实现又能断言"没被调用"(B9) */
|
||
applyBidDetail: vi.fn(),
|
||
/** 登录上下文(REST 层用) */
|
||
tenantCtx: { value: null as Record<string, unknown> | null },
|
||
}));
|
||
|
||
vi.mock('../src/db', () => ({
|
||
pool: {
|
||
query: (...args: unknown[]) => H.poolQuery(...args),
|
||
connect: async () => ({
|
||
query: (...args: unknown[]) => H.clientQuery(...args),
|
||
release: () => H.clientRelease(),
|
||
}),
|
||
},
|
||
getRawPoolQuery: () => H.poolQuery,
|
||
}));
|
||
|
||
vi.mock('../src/services/mainSystem/token', () => ({
|
||
getMainSystemToken: (...args: unknown[]) => H.token(...args),
|
||
}));
|
||
|
||
// 配置齐备(否则 api 层直接返回 not_configured,测不到映射)
|
||
// 域名也固定成假值:这样本文件不依赖 `.env` 里有没有 MAIN_SYSTEM_BASE_URL(换环境也不会红)
|
||
vi.mock('../src/services/mainSystem/config', async (importOriginal) => {
|
||
const actual = await importOriginal<typeof import('../src/services/mainSystem/config')>();
|
||
return { ...actual, isMainSystemIntegrationEnabled: () => true, mainSystemBaseUrl: () => 'http://main-system.test' };
|
||
});
|
||
|
||
// 绑定列表:B3 校验编码、B5/B8 逐个绑定拉列表都走它
|
||
vi.mock('../src/services/mainSystemBranchApi', () => ({
|
||
listSupplierCodesForBranch: (...args: unknown[]) => {
|
||
if (H.bindingError.value) return Promise.reject(H.bindingError.value);
|
||
return H.bindingCodes(...args);
|
||
},
|
||
}));
|
||
|
||
// 保留真实现,只把 applyBidDetail 换成可计数的包装(B9 要证明"失败不落库")
|
||
vi.mock('../src/services/mainSystemBidInbox', async (importOriginal) => {
|
||
const actual = await importOriginal<typeof import('../src/services/mainSystemBidInbox')>();
|
||
H.applyBidDetail.mockImplementation(actual.applyBidDetail);
|
||
return { ...actual, applyBidDetail: (...args: unknown[]) => H.applyBidDetail(...args) };
|
||
});
|
||
|
||
// REST 层:只要能拿到"已登录 + 有权限 + 某分公司",鉴权本身不属本任务
|
||
vi.mock('../src/middleware/auth', () => ({
|
||
authMiddleware: (req: { userId?: string }, _res: unknown, next: () => void) => {
|
||
req.userId = 'user-1';
|
||
next();
|
||
},
|
||
}));
|
||
vi.mock('../src/services/tenantScope', async (importOriginal) => {
|
||
const actual = await importOriginal<typeof import('../src/services/tenantScope')>();
|
||
return { ...actual, loadTenantContext: async () => H.tenantCtx.value };
|
||
});
|
||
|
||
vi.stubGlobal('fetch', H.fetchMock);
|
||
|
||
const inbox = await import('../src/services/mainSystemBidInbox');
|
||
const quotes = await import('../src/services/mainSystemBidQuotes');
|
||
const bidApi = await import('../src/services/mainSystem/api/bids');
|
||
const { mountMainSystemBidWorkflowRoutes } = await import('../src/modules/workflow/routes/mainSystemBidRoutes');
|
||
|
||
const {
|
||
deriveLocalStatus,
|
||
findInvitationByRound,
|
||
getBidInvitationDetail,
|
||
recordBidOpened,
|
||
toBidInvitationItemDto,
|
||
applyBidDetail,
|
||
} = inbox;
|
||
|
||
/* ── 内存版两张表:接管 mainSystemBidInbox 用到的那些 SQL ────────────────────
|
||
* 只实现这两张表 + 只实现本任务涉及的语句;语义按迁移文件里的约束写
|
||
* (ON CONFLICT 幂等键、webhook 只增不减 / 权威刷新可收缩、终态不回退、整轮先清后写)。
|
||
* 这样用例断言的是**落库后的行**,比只断言"发过某条 SQL"强一档。
|
||
*/
|
||
|
||
type FakeInvitation = {
|
||
id: string;
|
||
branch_code: string;
|
||
supplier_code: string;
|
||
round_id: string;
|
||
round_code: string | null;
|
||
round_title: string | null;
|
||
order_code: string | null;
|
||
respond_deadline: string | null;
|
||
item_count: number;
|
||
round_status: string;
|
||
main_invitation_status: string | null;
|
||
local_status: string;
|
||
quoted_at: string | null;
|
||
webhook_received_at: string | null;
|
||
last_synced_at: string | null;
|
||
sync_error: string | null;
|
||
payload: unknown;
|
||
created_at: string;
|
||
updated_at: string;
|
||
};
|
||
|
||
type FakeItem = {
|
||
id: string;
|
||
invitation_id: string;
|
||
branch_code: string;
|
||
round_id: string;
|
||
sku_code: string;
|
||
sku_name: string | null;
|
||
unit: string | null;
|
||
unit_price: number | null;
|
||
remark: string | null;
|
||
quoted_at: string | null;
|
||
award_price: number | null;
|
||
award_qty: number | null;
|
||
award_status: 'won' | 'lost' | null;
|
||
};
|
||
|
||
type SqlEntry = { channel: 'pool' | 'client'; sql: string; params: unknown[] };
|
||
|
||
function createFakeBidDb() {
|
||
const invitations: FakeInvitation[] = [];
|
||
const items: FakeItem[] = [];
|
||
const log: SqlEntry[] = [];
|
||
let seq = 0;
|
||
const nowIso = () => new Date().toISOString();
|
||
const clone = <T>(row: T): T => ({ ...row });
|
||
|
||
const findInvitation = (id: string) => invitations.find((row) => row.id === id);
|
||
const scope = (sql: string, params: unknown[]) => {
|
||
// markInvitationSyncError / markInvitationCancelled 的 supplier 作用域:$4
|
||
const supplier = sql.includes('upper(supplier_code) = upper($4)') ? String(params[3] || '') : '';
|
||
return (row: FakeInvitation) =>
|
||
row.branch_code === params[0] &&
|
||
row.round_id === params[1] &&
|
||
(!supplier || String(row.supplier_code).toUpperCase() === supplier.toUpperCase());
|
||
};
|
||
|
||
function recompute(params: unknown[]) {
|
||
const invitation = findInvitation(String(params[0]));
|
||
if (!invitation) return { rows: [] as unknown[] };
|
||
const rows = items.filter((item) => item.invitation_id === invitation.id);
|
||
const quotedAt = rows
|
||
.map((item) => item.quoted_at)
|
||
.filter((value): value is string => Boolean(value))
|
||
.sort()
|
||
.pop();
|
||
return {
|
||
rows: [
|
||
{
|
||
round_status: invitation.round_status,
|
||
main_invitation_status: invitation.main_invitation_status,
|
||
respond_deadline: invitation.respond_deadline,
|
||
item_count: invitation.item_count,
|
||
quoted_count: rows.filter((item) => item.unit_price !== null).length,
|
||
has_award: rows.some((item) => item.award_status === 'won'),
|
||
quoted_at: quotedAt ?? null,
|
||
},
|
||
],
|
||
};
|
||
}
|
||
|
||
function dispatch(channel: 'pool' | 'client', rawSql: string, rawParams?: unknown[]) {
|
||
const sql = String(rawSql);
|
||
const params = (rawParams || []) as unknown[];
|
||
log.push({ channel, sql, params });
|
||
|
||
if (/^\s*(BEGIN|COMMIT|ROLLBACK)\s*$/i.test(sql)) return { rows: [] as unknown[] };
|
||
|
||
/* ── 邀约头 upsert(webhook / 列表 / 详情共用)── */
|
||
if (/INSERT INTO public\.main_system_bid_invitations AS i/.test(sql)) {
|
||
const [
|
||
branchCode,
|
||
supplierCode,
|
||
roundId,
|
||
roundCode,
|
||
roundTitle,
|
||
orderCode,
|
||
respondDeadline,
|
||
itemCount,
|
||
roundStatus,
|
||
mainInvitationStatus,
|
||
fromWebhook,
|
||
fromSync,
|
||
payloadJson,
|
||
] = params as [string, string, string, string | null, string | null, string | null, string | null, number, string, string | null, boolean, boolean, string | null];
|
||
const excludedCount = Number(itemCount) || 0;
|
||
let row = invitations.find(
|
||
(r) => r.branch_code === branchCode && r.round_id === roundId && r.supplier_code === supplierCode
|
||
);
|
||
if (!row) {
|
||
row = {
|
||
id: `inv-${++seq}`,
|
||
branch_code: branchCode,
|
||
supplier_code: supplierCode,
|
||
round_id: roundId,
|
||
round_code: roundCode,
|
||
round_title: roundTitle,
|
||
order_code: orderCode,
|
||
respond_deadline: respondDeadline,
|
||
item_count: excludedCount,
|
||
round_status: roundStatus || 'open',
|
||
main_invitation_status: mainInvitationStatus,
|
||
local_status: 'pending',
|
||
quoted_at: null,
|
||
webhook_received_at: fromWebhook === true ? nowIso() : null,
|
||
last_synced_at: fromSync === true ? nowIso() : null,
|
||
sync_error: null,
|
||
payload: payloadJson ? JSON.parse(payloadJson) : null,
|
||
created_at: nowIso(),
|
||
updated_at: nowIso(),
|
||
};
|
||
invitations.push(row);
|
||
return { rows: [{ id: row.id }] };
|
||
}
|
||
// ON CONFLICT DO UPDATE
|
||
row.round_code = roundCode ?? row.round_code;
|
||
row.round_title = roundTitle ?? row.round_title;
|
||
row.order_code = orderCode ?? row.order_code;
|
||
row.respond_deadline = respondDeadline ?? row.respond_deadline;
|
||
row.item_count = fromSync === true ? excludedCount : Math.max(Number(row.item_count) || 0, excludedCount);
|
||
row.round_status = ['closed', 'awarded', 'cancelled'].includes(String(row.round_status))
|
||
? row.round_status
|
||
: roundStatus || row.round_status;
|
||
row.main_invitation_status = mainInvitationStatus ?? row.main_invitation_status;
|
||
if (fromWebhook === true) row.webhook_received_at = nowIso();
|
||
if (fromSync === true) {
|
||
row.last_synced_at = nowIso();
|
||
row.sync_error = null;
|
||
}
|
||
if (payloadJson) row.payload = JSON.parse(payloadJson);
|
||
row.updated_at = nowIso();
|
||
return { rows: [{ id: row.id }] };
|
||
}
|
||
|
||
/* ── 重算 local_status ── */
|
||
if (/SELECT i\.round_status,/.test(sql)) return recompute(params);
|
||
if (/SET local_status = \$2, quoted_at = \$3/.test(sql)) {
|
||
const row = findInvitation(String(params[0]));
|
||
if (row) {
|
||
row.local_status = String(params[1]);
|
||
row.quoted_at = (params[2] as string | null) ?? null;
|
||
row.updated_at = nowIso();
|
||
}
|
||
return { rows: [] };
|
||
}
|
||
|
||
/* ── 明细:身份 upsert / 删除 / 报价 / 中标 ── */
|
||
if (/INSERT INTO public\.main_system_bid_invitation_items AS it/.test(sql)) {
|
||
const [invitationId, branchCode, roundId, skuCode, skuName, unit] = params as [
|
||
string,
|
||
string,
|
||
string,
|
||
string,
|
||
string | null,
|
||
string | null,
|
||
];
|
||
const existing = items.find((row) => row.invitation_id === invitationId && row.sku_code === skuCode);
|
||
if (existing) {
|
||
existing.sku_name = skuName ?? existing.sku_name;
|
||
existing.unit = unit ?? existing.unit;
|
||
return { rows: [] };
|
||
}
|
||
items.push({
|
||
id: `item-${++seq}`,
|
||
invitation_id: invitationId,
|
||
branch_code: branchCode,
|
||
round_id: roundId,
|
||
sku_code: skuCode,
|
||
sku_name: skuName,
|
||
unit,
|
||
unit_price: null,
|
||
remark: null,
|
||
quoted_at: null,
|
||
award_price: null,
|
||
award_qty: null,
|
||
award_status: null,
|
||
});
|
||
return { rows: [] };
|
||
}
|
||
if (/DELETE FROM public\.main_system_bid_invitation_items/.test(sql)) {
|
||
const invitationId = String(params[0]);
|
||
const keep = new Set((params[1] as string[]) || []);
|
||
for (let i = items.length - 1; i >= 0; i -= 1) {
|
||
if (items[i].invitation_id === invitationId && !keep.has(items[i].sku_code)) items.splice(i, 1);
|
||
}
|
||
return { rows: [] };
|
||
}
|
||
if (/SET unit_price = NULL, remark = NULL, quoted_at = NULL/.test(sql)) {
|
||
const invitationId = String(params[0]);
|
||
for (const row of items) {
|
||
if (row.invitation_id !== invitationId || row.unit_price === null) continue;
|
||
row.unit_price = null;
|
||
row.remark = null;
|
||
row.quoted_at = null;
|
||
}
|
||
return { rows: [] };
|
||
}
|
||
if (/SET unit_price = \$3, remark = \$4, quoted_at = COALESCE/.test(sql)) {
|
||
const [invitationId, skuCode, unitPrice, remark, quotedAt] = params as [string, string, number, string | null, string | null];
|
||
const row = items.find((it) => it.invitation_id === invitationId && it.sku_code === skuCode);
|
||
if (row) {
|
||
row.unit_price = Number(unitPrice);
|
||
row.remark = remark ?? null;
|
||
row.quoted_at = quotedAt ?? row.quoted_at;
|
||
}
|
||
return { rows: [] };
|
||
}
|
||
if (/SET award_price = NULL, award_qty = NULL, award_status = NULL/.test(sql)) {
|
||
const invitationId = String(params[0]);
|
||
for (const row of items) {
|
||
if (row.invitation_id !== invitationId) continue;
|
||
if (row.award_price === null && row.award_status === null) continue;
|
||
row.award_price = null;
|
||
row.award_qty = null;
|
||
row.award_status = null;
|
||
}
|
||
return { rows: [] };
|
||
}
|
||
if (/SET award_price = \$3, award_status = 'won'/.test(sql)) {
|
||
const [invitationId, skuCode, awardPrice] = params as [string, string, number];
|
||
const row = items.find((it) => it.invitation_id === invitationId && it.sku_code === skuCode);
|
||
if (row) {
|
||
row.award_price = awardPrice === null ? null : Number(awardPrice);
|
||
row.award_status = 'won';
|
||
}
|
||
return { rows: [] };
|
||
}
|
||
|
||
/* ── 读:定位 / 明细 / 列表 / 计数 ── */
|
||
if (/SELECT \* FROM public\.main_system_bid_invitations/.test(sql) && /round_id = \$2/.test(sql)) {
|
||
const [branchCode, roundId, supplierCode] = params as [string, string, string?];
|
||
let rows = invitations.filter((row) => row.branch_code === branchCode && row.round_id === roundId);
|
||
if (supplierCode) {
|
||
rows = rows.filter(
|
||
(row) => String(row.supplier_code).toUpperCase() === String(supplierCode).toUpperCase()
|
||
);
|
||
return { rows: rows.slice(0, 1).map(clone) };
|
||
}
|
||
return { rows: rows.sort((a, b) => String(b.created_at).localeCompare(String(a.created_at))).map(clone) };
|
||
}
|
||
if (/SELECT \* FROM public\.main_system_bid_invitation_items/.test(sql)) {
|
||
const invitationId = String(params[0]);
|
||
return {
|
||
rows: items
|
||
.filter((row) => row.invitation_id === invitationId)
|
||
.sort((a, b) => String(a.sku_code).localeCompare(String(b.sku_code)))
|
||
.map(clone),
|
||
};
|
||
}
|
||
if (/GROUP BY local_status/.test(sql)) {
|
||
const map = new Map<string, number>();
|
||
for (const row of invitations) {
|
||
if (row.branch_code !== params[0]) continue;
|
||
map.set(row.local_status, (map.get(row.local_status) || 0) + 1);
|
||
}
|
||
return { rows: [...map.entries()].map(([local_status, n]) => ({ local_status, n })) };
|
||
}
|
||
if (/SELECT \* FROM public\.main_system_bid_invitations/.test(sql)) {
|
||
let rows = invitations.filter((row) => row.branch_code === params[0]);
|
||
// listInvitationRows 的 status 过滤(`pending` / `history` 两种拼进来的谓词)
|
||
if (/AND local_status = 'pending'/.test(sql)) {
|
||
rows = rows.filter((row) => row.local_status === 'pending');
|
||
} else if (/AND local_status IN \('quoted', 'expired', 'won', 'lost', 'cancelled'\)/.test(sql)) {
|
||
rows = rows.filter((row) => ['quoted', 'expired', 'won', 'lost', 'cancelled'].includes(row.local_status));
|
||
}
|
||
return { rows: rows.map(clone) };
|
||
}
|
||
|
||
/* ── 写:sync_error / 软删 ── */
|
||
if (/SET round_status = 'cancelled'/.test(sql)) {
|
||
for (const row of invitations.filter(scope(sql, params))) {
|
||
row.round_status = 'cancelled';
|
||
row.local_status = 'cancelled';
|
||
row.sync_error = (params[2] as string | null) ?? null;
|
||
}
|
||
return { rows: [] };
|
||
}
|
||
if (/SET sync_error = \$3/.test(sql)) {
|
||
for (const row of invitations.filter(scope(sql, params))) {
|
||
row.sync_error = (params[2] as string | null) ?? null;
|
||
}
|
||
return { rows: [] };
|
||
}
|
||
|
||
throw new Error(`fakeBidDb 不认识的 SQL:\n${sql}`);
|
||
}
|
||
|
||
return {
|
||
invitations,
|
||
items,
|
||
log,
|
||
seedInvitation(over: Partial<FakeInvitation> = {}): FakeInvitation {
|
||
const row: FakeInvitation = {
|
||
id: `inv-${++seq}`,
|
||
branch_code: 'BR002',
|
||
supplier_code: 'SUP37831443',
|
||
round_id: 'round-1',
|
||
round_code: 'BID001',
|
||
round_title: '今日竞价',
|
||
order_code: 'ORD1',
|
||
respond_deadline: new Date(Date.now() + 3600_000).toISOString(),
|
||
item_count: 0,
|
||
round_status: 'open',
|
||
main_invitation_status: null,
|
||
local_status: 'pending',
|
||
quoted_at: null,
|
||
webhook_received_at: null,
|
||
last_synced_at: null,
|
||
sync_error: null,
|
||
payload: null,
|
||
created_at: nowIso(),
|
||
updated_at: nowIso(),
|
||
...over,
|
||
};
|
||
invitations.push(row);
|
||
return row;
|
||
},
|
||
seedItem(invitation: FakeInvitation, over: Partial<FakeItem> = {}): FakeItem {
|
||
const row: FakeItem = {
|
||
id: `item-${++seq}`,
|
||
invitation_id: invitation.id,
|
||
branch_code: invitation.branch_code,
|
||
round_id: invitation.round_id,
|
||
sku_code: 'SKU1',
|
||
sku_name: '草鱼',
|
||
unit: '斤',
|
||
unit_price: null,
|
||
remark: null,
|
||
quoted_at: null,
|
||
award_price: null,
|
||
award_qty: null,
|
||
award_status: null,
|
||
...over,
|
||
};
|
||
items.push(row);
|
||
return row;
|
||
},
|
||
/** 只看某个方向/某种语句的调用(断言"没发生"用) */
|
||
find(re: RegExp) {
|
||
return log.filter((entry) => re.test(entry.sql));
|
||
},
|
||
dispatch,
|
||
};
|
||
}
|
||
|
||
let db = createFakeBidDb();
|
||
|
||
/* ── 通用小工具 ───────────────────────────────────────────────────────────── */
|
||
|
||
/** 把 service 的失败对象读成断言用的形状(`kind/status/code/message` 只有失败时才存在) */
|
||
function failureOf(outcome: unknown): { kind: string; status: number; code: string; message: string } {
|
||
return outcome as { kind: string; status: number; code: string; message: string };
|
||
}
|
||
|
||
function jsonResponse(status: number, body: unknown) {
|
||
return { ok: status >= 200 && status < 300, status, json: async () => body };
|
||
}
|
||
|
||
function nonJsonResponse(status = 200) {
|
||
return {
|
||
ok: true,
|
||
status,
|
||
json: async () => {
|
||
throw new Error('Unexpected token < in JSON at position 0');
|
||
},
|
||
};
|
||
}
|
||
|
||
function abortError() {
|
||
return Object.assign(new Error('The operation was aborted'), { name: 'AbortError' });
|
||
}
|
||
|
||
const futureIso = () => new Date(Date.now() + 3600_000).toISOString();
|
||
const pastIso = () => new Date(Date.now() - 3600_000).toISOString();
|
||
|
||
/** 对方成功返回的一份"我的视角"详情 */
|
||
function detailPayload(over: Record<string, unknown> = {}) {
|
||
return {
|
||
data: {
|
||
round: {
|
||
id: 'round-1',
|
||
round_code: 'BID001',
|
||
title: '今日竞价',
|
||
order_code: 'ORD1',
|
||
status: 'open',
|
||
respond_deadline: futureIso(),
|
||
},
|
||
invitation: { status: 'pending', respond_deadline: futureIso() },
|
||
items: [{ sku_code: 'SKU1', sku_name: '草鱼', unit: '斤' }],
|
||
my_quotes: [],
|
||
awards: [],
|
||
...over,
|
||
},
|
||
};
|
||
}
|
||
|
||
function buildApp() {
|
||
const app = express();
|
||
app.use(express.json());
|
||
const router = express.Router();
|
||
mountMainSystemBidWorkflowRoutes(router);
|
||
app.use('/api/workflow', router);
|
||
return app;
|
||
}
|
||
|
||
beforeEach(() => {
|
||
db = createFakeBidDb();
|
||
H.clientQuery.mockReset();
|
||
H.poolQuery.mockReset();
|
||
H.clientQuery.mockImplementation(async (sql: string, params?: unknown[]) => db.dispatch('client', sql, params));
|
||
H.poolQuery.mockImplementation(async (sql: string, params?: unknown[]) => db.dispatch('pool', sql, params));
|
||
H.clientRelease.mockReset();
|
||
H.token.mockReset();
|
||
H.token.mockResolvedValue({ kind: 'ok', token: 'tok-1', branchCode: 'BR002', expiresAt: Date.now() + 60_000 });
|
||
H.fetchMock.mockReset();
|
||
H.bindingCodes.mockReset();
|
||
H.bindingCodes.mockResolvedValue(['SUP37831443']);
|
||
H.bindingError.value = null;
|
||
H.applyBidDetail.mockClear();
|
||
H.tenantCtx.value = {
|
||
branchCode: 'BR002',
|
||
permissions: ['order_manage'],
|
||
roles: ['admin'],
|
||
isSuperAdmin: false,
|
||
};
|
||
});
|
||
|
||
/* ══ 派生口径(§4 / 验收 B6 的"读取时派生")═════════════════════════════════ */
|
||
|
||
describe('派生口径:优先级与时钟边界(deriveLocalStatus)', () => {
|
||
const base = { itemCount: 2, quotedCount: 2, hasAward: false };
|
||
const future = new Date(Date.now() + 3600_000);
|
||
const past = new Date(Date.now() - 3600_000);
|
||
|
||
it('同一组输入只改一个维度:cancelled > awarded > expired > quoted > pending', () => {
|
||
// 每一行都比下一行多满足一条"更权威"的规则 ⇒ 顺序错就会显示成下面那行
|
||
expect(deriveLocalStatus({ ...base, roundStatus: 'cancelled', respondDeadline: past, mainInvitationStatus: 'quoted' })).toBe('cancelled');
|
||
expect(deriveLocalStatus({ ...base, roundStatus: 'awarded', respondDeadline: past, mainInvitationStatus: 'quoted' })).toBe('lost');
|
||
expect(deriveLocalStatus({ ...base, roundStatus: 'open', respondDeadline: past, mainInvitationStatus: 'quoted' })).toBe('expired');
|
||
expect(deriveLocalStatus({ ...base, roundStatus: 'open', respondDeadline: future, mainInvitationStatus: 'quoted' })).toBe('quoted');
|
||
expect(deriveLocalStatus({ ...base, quotedCount: 1, roundStatus: 'open', respondDeadline: future })).toBe('pending');
|
||
});
|
||
|
||
it('已定标时"中标"压过"过期":awarded + 过期 + 有中标 ⇒ won', () => {
|
||
expect(deriveLocalStatus({ ...base, roundStatus: 'awarded', hasAward: true, respondDeadline: past })).toBe('won');
|
||
});
|
||
|
||
it('respond_deadline 为 null / 不可解析 ⇒ 一律不判过期', () => {
|
||
expect(deriveLocalStatus({ ...base, roundStatus: 'open', respondDeadline: null })).toBe('quoted');
|
||
expect(deriveLocalStatus({ ...base, roundStatus: 'open', respondDeadline: 'not-a-date' })).toBe('quoted');
|
||
});
|
||
|
||
it('时钟边界:恰好在截止时刻**不算**过期(严格小于),早 1ms 算过期', () => {
|
||
const now = new Date('2026-10-17T02:30:00.000Z');
|
||
expect(
|
||
deriveLocalStatus({ ...base, roundStatus: 'open', respondDeadline: '2026-10-17T02:30:00.000Z', now })
|
||
).toBe('quoted');
|
||
expect(
|
||
deriveLocalStatus({ ...base, roundStatus: 'open', respondDeadline: '2026-10-17T02:29:59.999Z', now })
|
||
).toBe('expired');
|
||
expect(
|
||
deriveLocalStatus({ ...base, roundStatus: 'open', respondDeadline: '2026-10-17T02:30:00.001Z', now })
|
||
).toBe('quoted');
|
||
});
|
||
|
||
it('时区:+08:00 与等价的 Z 表示必须同结论(不能按字面比字符串)', () => {
|
||
const now = new Date('2026-10-17T02:00:00.000Z');
|
||
// 10:00+08:00 == 02:00Z ⇒ 与 now 相等,不过期
|
||
expect(
|
||
deriveLocalStatus({ ...base, roundStatus: 'open', respondDeadline: '2026-10-17T10:00:00+08:00', now })
|
||
).toBe('quoted');
|
||
// 09:59+08:00 == 01:59Z ⇒ 已过期
|
||
expect(
|
||
deriveLocalStatus({ ...base, roundStatus: 'open', respondDeadline: '2026-10-17T09:59:00+08:00', now })
|
||
).toBe('expired');
|
||
});
|
||
|
||
it('明细还没拉过(itemCount=0 且无对方状态)⇒ pending,不凭空说"已报价"', () => {
|
||
expect(deriveLocalStatus({ roundStatus: 'open', itemCount: 0, quotedCount: 0, hasAward: false })).toBe('pending');
|
||
});
|
||
|
||
it('明细 DTO:轮次 awarded 且无中标价 ⇒ lost;未定标 ⇒ null', () => {
|
||
const row = {
|
||
id: 'i1',
|
||
invitation_id: 'inv1',
|
||
branch_code: 'BR002',
|
||
round_id: 'round-1',
|
||
sku_code: 'SKU1',
|
||
sku_name: '草鱼',
|
||
unit: '斤',
|
||
unit_price: '12.5000',
|
||
remark: null,
|
||
quoted_at: null,
|
||
award_price: null,
|
||
award_qty: null,
|
||
award_status: null,
|
||
};
|
||
expect(toBidInvitationItemDto(row as never, 'awarded').awardStatus).toBe('lost');
|
||
expect(toBidInvitationItemDto(row as never, 'open').awardStatus).toBe(null);
|
||
});
|
||
});
|
||
|
||
/* ══ B3:未绑定 / 未知编码 / 读不到绑定 ═════════════════════════════════════ */
|
||
|
||
describe('B3 webhook `bid.opened`:供应商编码不在生效绑定里 ⇒ 只忽略、不落库', () => {
|
||
const payload = {
|
||
round_id: 'round-1',
|
||
round_code: 'BID001',
|
||
respond_deadline: futureIso(),
|
||
item_count: 1,
|
||
items: [{ sku_code: 'SKU1', sku_name: '草鱼', unit: '斤' }],
|
||
};
|
||
|
||
it('未知编码 ⇒ ignored/supplier_not_bound,且**一个事务都不开**(无邀约、无明细)', async () => {
|
||
H.bindingCodes.mockResolvedValue(['SUP37831443']);
|
||
const outcome = await recordBidOpened({ branchCode: 'BR002', supplierCode: 'SUP99999999', payload });
|
||
expect(outcome.status).toBe('ignored');
|
||
expect(outcome.reason).toBe('supplier_not_bound');
|
||
expect(db.invitations).toHaveLength(0);
|
||
expect(db.items).toHaveLength(0);
|
||
// 关键:连 BEGIN 都没有 —— 不是"先写后回滚"
|
||
expect(db.log).toHaveLength(0);
|
||
});
|
||
|
||
it('读不到绑定(空列表)⇒ 不拦(这是环境已知状态,不是本事件的错)', async () => {
|
||
H.bindingCodes.mockResolvedValue([]);
|
||
const outcome = await recordBidOpened({ branchCode: 'BR002', supplierCode: 'SUP_ANY_UNKNOWN', payload });
|
||
expect(outcome.status).toBe('recorded');
|
||
expect(db.invitations).toHaveLength(1);
|
||
expect(db.invitations[0].supplier_code).toBe('SUP_ANY_UNKNOWN');
|
||
});
|
||
|
||
it('绑定查询抛错 ⇒ 也只记日志、不阻断落库(fail-open,宁可多一行镜像也不丢待办)', async () => {
|
||
H.bindingError.value = new Error('bindings table unavailable');
|
||
const outcome = await recordBidOpened({ branchCode: 'BR002', supplierCode: 'SUP37831443', payload });
|
||
expect(outcome.status).toBe('recorded');
|
||
expect(db.invitations).toHaveLength(1);
|
||
});
|
||
|
||
it('大小写不敏感匹配并**规范成绑定里的写法**(否则同一轮会裂成两行)', async () => {
|
||
H.bindingCodes.mockResolvedValue(['SUP37831443']);
|
||
const outcome = await recordBidOpened({ branchCode: 'BR002', supplierCode: 'sup37831443', payload });
|
||
expect(outcome.status).toBe('recorded');
|
||
expect(db.invitations).toHaveLength(1);
|
||
expect(db.invitations[0].supplier_code).toBe('SUP37831443');
|
||
});
|
||
|
||
it('同一轮重复推送(含大小写不同的写法)仍只有 1 行邀约(幂等键落到规范化后的编码)', async () => {
|
||
H.bindingCodes.mockResolvedValue(['SUP37831443']);
|
||
await recordBidOpened({ branchCode: 'BR002', supplierCode: 'SUP37831443', payload });
|
||
await recordBidOpened({ branchCode: 'BR002', supplierCode: 'sup37831443', payload });
|
||
expect(db.invitations).toHaveLength(1);
|
||
expect(db.items).toHaveLength(1);
|
||
});
|
||
|
||
it('webhook 的 item_count 只增不减(退化载荷不能把已知行数改小)', async () => {
|
||
H.bindingCodes.mockResolvedValue(['SUP37831443']);
|
||
await recordBidOpened({
|
||
branchCode: 'BR002',
|
||
supplierCode: 'SUP37831443',
|
||
payload: { ...payload, item_count: 3, items: [payload.items[0], { sku_code: 'SKU2' }, { sku_code: 'SKU3' }] },
|
||
});
|
||
expect(db.invitations[0].item_count).toBe(3);
|
||
// 退化的补投(只剩 1 行)
|
||
await recordBidOpened({ branchCode: 'BR002', supplierCode: 'SUP37831443', payload });
|
||
expect(db.invitations[0].item_count).toBe(3);
|
||
});
|
||
|
||
it('终态不可回退:已 awarded 的轮次收到迟到的 `bid.opened` 仍是 awarded(不能变回 open)', async () => {
|
||
const invitation = db.seedInvitation({ round_id: 'round-1', round_status: 'awarded', local_status: 'lost', item_count: 1 });
|
||
db.seedItem(invitation, { sku_code: 'SKU1', unit_price: 12.5 });
|
||
await recordBidOpened({ branchCode: 'BR002', supplierCode: 'SUP37831443', payload });
|
||
expect(invitation.round_status).toBe('awarded');
|
||
expect(invitation.local_status).toBe('lost');
|
||
// 明细身份仍按 (invitation, sku) upsert(补投的新 SKU 要能进来)
|
||
expect(db.items).toHaveLength(1);
|
||
});
|
||
|
||
it('payload 里同一 SKU 重复出现 ⇒ 只算一行(红队 #7 的去重)', async () => {
|
||
H.bindingCodes.mockResolvedValue(['SUP37831443']);
|
||
await recordBidOpened({
|
||
branchCode: 'BR002',
|
||
supplierCode: 'SUP37831443',
|
||
payload: {
|
||
...payload,
|
||
item_count: 2,
|
||
items: [
|
||
{ sku_code: 'SKU1', sku_name: '草鱼', unit: '斤' },
|
||
{ sku_code: 'SKU1', sku_name: '草鱼(重复)', unit: '斤' },
|
||
{ sku_code: ' ', sku_name: '空编码行' },
|
||
],
|
||
},
|
||
});
|
||
expect(db.items).toHaveLength(1);
|
||
expect(db.items[0].sku_code).toBe('SKU1');
|
||
});
|
||
|
||
it('round_id 形态在**入站侧**就被挡掉(不再落"点不开"的僵尸台账)', async () => {
|
||
// 出站/查询侧要求 `[0-9A-Za-z_-]{1,64}`;入站侧若不校验,带控制字符的 round_id 会造出
|
||
// 一行"列表能看到、点开/提交都 400"的台账。2026-10-17 已在 `recordBidOpened` 入口加同一口径校验。
|
||
H.bindingCodes.mockResolvedValue(['SUP37831443']);
|
||
const outcome = await recordBidOpened({
|
||
branchCode: 'BR002',
|
||
supplierCode: 'SUP37831443',
|
||
payload: { ...payload, round_id: 'abc%00def' },
|
||
});
|
||
expect(outcome.status).toBe('ignored');
|
||
expect(outcome.reason).toBe('invalid_round_id');
|
||
expect(db.invitations).toHaveLength(0);
|
||
expect(H.fetchMock).not.toHaveBeenCalled();
|
||
});
|
||
});
|
||
|
||
/* ══ B4:本地清单(镜像读,不外呼)═════════════════════════════════════════ */
|
||
|
||
describe('B4 清单:status 过滤与 summary 口径', () => {
|
||
function seedThree() {
|
||
const pending = db.seedInvitation({ round_id: 'round-p', local_status: 'pending', item_count: 1 });
|
||
db.seedItem(pending, { sku_code: 'SKU1' });
|
||
const quoted = db.seedInvitation({ round_id: 'round-q', local_status: 'quoted', item_count: 1 });
|
||
db.seedItem(quoted, { sku_code: 'SKU1', unit_price: 1 });
|
||
const cancelled = db.seedInvitation({ round_id: 'round-c', local_status: 'cancelled', round_status: 'cancelled' });
|
||
return { pending, quoted, cancelled };
|
||
}
|
||
|
||
it('status=pending 只回待报价;history 回其余终态/已报', async () => {
|
||
seedThree();
|
||
const pendingOnly = await quotes.listBidInvitations({ branchCode: 'BR002', status: 'pending' });
|
||
expect(pendingOnly.rows.map((row) => row.roundId)).toEqual(['round-p']);
|
||
|
||
const history = await quotes.listBidInvitations({ branchCode: 'BR002', status: 'history' });
|
||
expect(history.rows.map((row) => row.roundId).sort()).toEqual(['round-c', 'round-q']);
|
||
expect(H.fetchMock).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('summary:closed = won + lost + cancelled(三个终态合并计数)', async () => {
|
||
seedThree();
|
||
const all = await quotes.listBidInvitations({ branchCode: 'BR002', status: 'all' });
|
||
expect(all.summary).toMatchObject({ pending: 1, quoted: 1, won: 0, lost: 0, cancelled: 1, closed: 1 });
|
||
});
|
||
|
||
it('其它分公司看不到(清单按 branch_code 过滤)', async () => {
|
||
seedThree();
|
||
const other = await quotes.listBidInvitations({ branchCode: 'BR999', status: 'all' });
|
||
expect(other.rows).toEqual([]);
|
||
});
|
||
});
|
||
|
||
/* ══ B5:同步(拉列表兜底)══════════════════════════════════════════════════ */
|
||
|
||
describe('B5 同步:settings.enabled=false ⇒ 不动本地;有行 ⇒ 只 upsert 邀约头', () => {
|
||
it('enabled=false 且 data:[] ⇒ 返回 0 同步,**一个事务都不开**,本地状态原样', async () => {
|
||
const seeded = db.seedInvitation({ round_id: 'round-old', item_count: 2, local_status: 'quoted', sync_error: '上次失败' });
|
||
db.seedItem(seeded, { sku_code: 'SKU1', unit_price: 12.5 });
|
||
H.fetchMock.mockResolvedValue(jsonResponse(200, { data: [], settings: { enabled: false } }));
|
||
|
||
const outcome = await quotes.syncBidInvitations('BR002');
|
||
|
||
expect(outcome).toMatchObject({ synced: 0, skipped: 0, unavailable: 0, enabled: false, bound: true });
|
||
expect(db.log).toHaveLength(0); // 没有 BEGIN/INSERT/UPDATE —— 不改任何本地状态
|
||
expect(seeded.local_status).toBe('quoted');
|
||
expect(seeded.sync_error).toBe('上次失败');
|
||
expect(seeded.item_count).toBe(2);
|
||
});
|
||
|
||
it('data 有行 ⇒ 只 upsert 邀约头(零明细写入),并写 last_synced_at / 清 sync_error', async () => {
|
||
const seeded = db.seedInvitation({
|
||
round_id: 'round-1',
|
||
item_count: 5,
|
||
main_invitation_status: null,
|
||
sync_error: '上次刷新失败',
|
||
});
|
||
H.fetchMock.mockResolvedValue(
|
||
jsonResponse(200, {
|
||
data: [
|
||
{
|
||
round_id: 'round-1',
|
||
round_code: 'BID001',
|
||
title: '今日竞价',
|
||
order_code: 'ORD1',
|
||
round_status: 'open',
|
||
status: 'pending',
|
||
respond_deadline: futureIso(),
|
||
item_count: 2,
|
||
},
|
||
],
|
||
settings: { enabled: true },
|
||
})
|
||
);
|
||
|
||
const outcome = await quotes.syncBidInvitations('BR002');
|
||
|
||
expect(outcome).toMatchObject({ synced: 1, unavailable: 0, enabled: true, bound: true });
|
||
// 只动邀约头:没有明细表的写(`it` 只出现在重算 local_status 的只读子查询里)
|
||
expect(db.find(/INSERT INTO public\.main_system_bid_invitation_items|DELETE FROM public\.main_system_bid_invitation_items|UPDATE public\.main_system_bid_invitation_items/)).toHaveLength(0);
|
||
const headerInserts = db.find(/INSERT INTO public\.main_system_bid_invitations AS i/);
|
||
expect(headerInserts).toHaveLength(1);
|
||
expect(String(headerInserts[0].sql)).toMatch(/ON CONFLICT \(branch_code, round_id, supplier_code\) DO UPDATE/);
|
||
// fromSync=true($12)⇒ item_count 可收缩、sync_error 清空
|
||
expect(headerInserts[0].params[11]).toBe(true);
|
||
expect(headerInserts[0].params[10]).toBe(false);
|
||
|
||
expect(seeded.item_count).toBe(2); // 5 → 2:权威刷新允许收缩
|
||
expect(seeded.main_invitation_status).toBe('pending');
|
||
expect(seeded.sync_error).toBe(null);
|
||
expect(seeded.last_synced_at).toBeTruthy();
|
||
expect(seeded.local_status).toBe('pending');
|
||
});
|
||
|
||
it('对方 5xx ⇒ unavailable+1、零 DB 写(不拿失败当"同步成功")', async () => {
|
||
H.fetchMock.mockResolvedValue(jsonResponse(500, { error: 'boom' }));
|
||
const seeded = db.seedInvitation({ round_id: 'round-old', item_count: 2 });
|
||
const outcome = await quotes.syncBidInvitations('BR002');
|
||
expect(outcome).toMatchObject({ synced: 0, unavailable: 1, enabled: false, bound: true });
|
||
expect(db.log).toHaveLength(0);
|
||
expect(seeded.item_count).toBe(2);
|
||
});
|
||
|
||
it('多绑定:逐个 supplier_code 各拉一次(身份取各绑定自己),合并 upsert', async () => {
|
||
H.bindingCodes.mockResolvedValue(['SUP-A', 'SUP-B']);
|
||
// 两次请求 URL 相同(对方按 token 区分身份),所以身份只能从 token 侧断言
|
||
H.fetchMock.mockResolvedValue(
|
||
jsonResponse(200, {
|
||
data: [{ round_id: 'round-x', round_status: 'open', status: 'pending', item_count: 1 }],
|
||
settings: { enabled: true },
|
||
})
|
||
);
|
||
|
||
const outcome = await quotes.syncBidInvitations('BR002');
|
||
|
||
expect(H.fetchMock).toHaveBeenCalledTimes(2);
|
||
expect(H.token.mock.calls.map((call) => call[0])).toEqual(['SUP-A', 'SUP-B']);
|
||
expect(outcome.synced).toBe(2);
|
||
const suppliers = db.invitations.map((row) => `${row.supplier_code}/${row.round_id}`).sort();
|
||
expect(suppliers).toEqual(['SUP-A/round-x', 'SUP-B/round-x']);
|
||
});
|
||
|
||
it('没有可出站绑定 ⇒ 一个请求都不发(bound=false)', async () => {
|
||
H.bindingCodes.mockResolvedValue([]);
|
||
const outcome = await quotes.syncBidInvitations('BR002');
|
||
expect(outcome).toMatchObject({ synced: 0, enabled: false, bound: false });
|
||
expect(H.fetchMock).not.toHaveBeenCalled();
|
||
expect(H.token).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('兜底链路:webhook 没到(本地无行)⇒ 打开某一轮先自动同步、再落台账', async () => {
|
||
// 对方 webhook 只重试 2 次 ⇒ 这条"打开时先同步"就是漏推的唯一自愈路径
|
||
H.fetchMock
|
||
// 1) resolveInvitation 找不到行 ⇒ refreshBidInvitation → syncIfMissing 拉列表
|
||
.mockResolvedValueOnce(
|
||
jsonResponse(200, {
|
||
data: [
|
||
{
|
||
round_id: 'round-1',
|
||
round_code: 'BID001',
|
||
title: '今日竞价',
|
||
round_status: 'open',
|
||
status: 'pending',
|
||
respond_deadline: futureIso(),
|
||
item_count: 1,
|
||
},
|
||
],
|
||
settings: { enabled: true },
|
||
})
|
||
)
|
||
// 2) 定位到之后拉详情
|
||
.mockResolvedValueOnce(jsonResponse(200, detailPayload()));
|
||
|
||
const outcome = await quotes.refreshBidInvitation({ branchCode: 'BR002', roundId: 'round-1' });
|
||
|
||
expect(outcome.kind).toBe('ok');
|
||
expect(H.fetchMock).toHaveBeenCalledTimes(2);
|
||
expect(db.invitations).toHaveLength(1);
|
||
expect(db.invitations[0]).toMatchObject({ round_id: 'round-1', supplier_code: 'SUP37831443' });
|
||
expect(db.items.map((row) => row.sku_code)).toEqual(['SKU1']);
|
||
});
|
||
});
|
||
|
||
/* ══ B6:整轮对齐 ═══════════════════════════════════════════════════════════ */
|
||
|
||
describe('B6 整轮对齐:对方删行 / 撤回报价 / 未中标', () => {
|
||
async function seedRoundWithTwoItems() {
|
||
const invitation = db.seedInvitation({ round_id: 'round-1', item_count: 2 });
|
||
db.seedItem(invitation, { sku_code: 'SKU1', unit_price: 12.5, quoted_at: pastIso() });
|
||
db.seedItem(invitation, { sku_code: 'SKU2', unit_price: 8, quoted_at: pastIso() });
|
||
return invitation;
|
||
}
|
||
|
||
it('对方删了一行 ⇒ 本地该行被删除,item_count 收缩(不是只加不减)', async () => {
|
||
const invitation = await seedRoundWithTwoItems();
|
||
|
||
await applyBidDetail({
|
||
branchCode: 'BR002',
|
||
supplierCode: 'SUP37831443',
|
||
roundId: 'round-1',
|
||
detail: {
|
||
round: { id: 'round-1', round_code: 'BID001', status: 'open' },
|
||
invitation: { status: 'pending' },
|
||
items: [{ sku_code: 'SKU1', sku_name: '草鱼', unit: '斤' }],
|
||
myQuotes: [{ sku_code: 'SKU1', unit_price: 12.5 }],
|
||
myAwards: [],
|
||
},
|
||
});
|
||
|
||
expect(db.items.map((row) => row.sku_code)).toEqual(['SKU1']);
|
||
expect(invitation.item_count).toBe(1);
|
||
const deletes = db.find(/DELETE FROM public\.main_system_bid_invitation_items/);
|
||
expect(deletes).toHaveLength(1);
|
||
expect(deletes[0].params[1]).toEqual(['SKU1']); // 只保留对方还给我的那些行
|
||
// 被删的那行报价也随之消失(不能留下"对方已经没有的行 + 我方的价格")
|
||
expect(db.items.find((row) => row.sku_code === 'SKU2')).toBeUndefined();
|
||
});
|
||
|
||
it('对方撤回报价 ⇒ 本地价被清空、quoted_at 清空、状态回 pending', async () => {
|
||
const invitation = await seedRoundWithTwoItems();
|
||
|
||
await applyBidDetail({
|
||
branchCode: 'BR002',
|
||
supplierCode: 'SUP37831443',
|
||
roundId: 'round-1',
|
||
detail: {
|
||
round: { id: 'round-1', round_code: 'BID001', status: 'open', respond_deadline: futureIso() },
|
||
invitation: { status: 'pending' },
|
||
items: [
|
||
{ sku_code: 'SKU1', sku_name: '草鱼', unit: '斤' },
|
||
{ sku_code: 'SKU2', sku_name: '鲤鱼', unit: '斤' },
|
||
],
|
||
myQuotes: [], // ← 对方那边我已经没有报价了
|
||
myAwards: [],
|
||
},
|
||
});
|
||
|
||
expect(db.items.map((row) => row.unit_price)).toEqual([null, null]);
|
||
expect(db.items.every((row) => row.quoted_at === null)).toBe(true);
|
||
expect(invitation.local_status).toBe('pending');
|
||
expect(invitation.quoted_at).toBe(null);
|
||
// 先清零、且没有为任何行写回价格
|
||
expect(db.find(/SET unit_price = NULL, remark = NULL, quoted_at = NULL/)).toHaveLength(1);
|
||
expect(db.find(/SET unit_price = \$3, remark = \$4/)).toHaveLength(0);
|
||
});
|
||
|
||
it('对方 withdrawn 我一行 ⇒ 另一行价格保留(清空是按"对方返回"重写,不是全表抹掉)', async () => {
|
||
const invitation = await seedRoundWithTwoItems();
|
||
|
||
await applyBidDetail({
|
||
branchCode: 'BR002',
|
||
supplierCode: 'SUP37831443',
|
||
roundId: 'round-1',
|
||
detail: {
|
||
round: { id: 'round-1', round_code: 'BID001', status: 'open' },
|
||
// 对方邀约状态仍是 pending(不是 quoted)⇒ 本地 2 行只 1 行有价 = 还没报完
|
||
invitation: { status: 'pending' },
|
||
items: [
|
||
{ sku_code: 'SKU1' },
|
||
{ sku_code: 'SKU2' },
|
||
],
|
||
myQuotes: [{ sku_code: 'SKU2', unit_price: 9.5, updated_at: '2026-10-17T02:10:00.000Z' }],
|
||
myAwards: [],
|
||
},
|
||
});
|
||
|
||
const bySku = new Map(db.items.map((row) => [row.sku_code, row]));
|
||
expect(bySku.get('SKU1')?.unit_price).toBe(null);
|
||
expect(bySku.get('SKU2')?.unit_price).toBe(9.5);
|
||
expect(bySku.get('SKU2')?.quoted_at).toBe('2026-10-17T02:10:00.000Z');
|
||
expect(invitation.local_status).toBe('pending'); // 只有一行有价 ⇒ 还不算"已报价"
|
||
});
|
||
|
||
it('对方说 invitation.status=quoted ⇒ 即便本地只 1 行有价也判 quoted(对方优先)', async () => {
|
||
const invitation = await seedRoundWithTwoItems();
|
||
await applyBidDetail({
|
||
branchCode: 'BR002',
|
||
supplierCode: 'SUP37831443',
|
||
roundId: 'round-1',
|
||
detail: {
|
||
round: { id: 'round-1', status: 'open', respond_deadline: futureIso() },
|
||
invitation: { status: 'quoted' },
|
||
items: [{ sku_code: 'SKU1' }, { sku_code: 'SKU2' }],
|
||
myQuotes: [{ sku_code: 'SKU2', unit_price: 9.5 }],
|
||
myAwards: [],
|
||
},
|
||
});
|
||
expect(invitation.local_status).toBe('quoted');
|
||
expect(invitation.main_invitation_status).toBe('quoted');
|
||
});
|
||
|
||
it('对方 awarded 但该 SKU 无中标 ⇒ 该行 lost(读取时派生),整轮 lost', async () => {
|
||
const invitation = await seedRoundWithTwoItems();
|
||
|
||
await applyBidDetail({
|
||
branchCode: 'BR002',
|
||
supplierCode: 'SUP37831443',
|
||
roundId: 'round-1',
|
||
detail: {
|
||
round: { id: 'round-1', round_code: 'BID001', status: 'awarded' },
|
||
invitation: { status: 'quoted' },
|
||
items: [{ sku_code: 'SKU1' }, { sku_code: 'SKU2' }],
|
||
myQuotes: [
|
||
{ sku_code: 'SKU1', unit_price: 12.5 },
|
||
{ sku_code: 'SKU2', unit_price: 8 },
|
||
],
|
||
myAwards: [], // ← 一个都没中
|
||
},
|
||
});
|
||
|
||
expect(db.items.every((row) => row.award_status === null && row.award_price === null)).toBe(true);
|
||
expect(db.find(/SET award_price = \$3, award_status = 'won'/)).toHaveLength(0);
|
||
expect(invitation.round_status).toBe('awarded');
|
||
expect(invitation.local_status).toBe('lost');
|
||
|
||
const detail = await getBidInvitationDetail({ branchCode: 'BR002', roundId: 'round-1' });
|
||
expect(detail?.invitation.localStatus).toBe('lost');
|
||
expect(detail?.items.map((item) => item.awardStatus)).toEqual(['lost', 'lost']);
|
||
expect(detail?.myAwards).toEqual([]);
|
||
});
|
||
|
||
it('对方 awarded 且只有一行中标 ⇒ 那行 won、其余 lost;整轮 won', async () => {
|
||
const invitation = await seedRoundWithTwoItems();
|
||
|
||
await applyBidDetail({
|
||
branchCode: 'BR002',
|
||
supplierCode: 'SUP37831443',
|
||
roundId: 'round-1',
|
||
detail: {
|
||
round: { id: 'round-1', round_code: 'BID001', status: 'awarded' },
|
||
invitation: { status: 'quoted' },
|
||
items: [{ sku_code: 'SKU1' }, { sku_code: 'SKU2' }],
|
||
myQuotes: [
|
||
{ sku_code: 'SKU1', unit_price: 12.5 },
|
||
{ sku_code: 'SKU2', unit_price: 8 },
|
||
],
|
||
myAwards: [{ sku_code: 'SKU1', unit_price: 11 }],
|
||
},
|
||
});
|
||
|
||
const bySku = new Map(db.items.map((row) => [row.sku_code, row]));
|
||
expect(bySku.get('SKU1')).toMatchObject({ award_status: 'won', award_price: 11 });
|
||
expect(bySku.get('SKU2')).toMatchObject({ award_status: null, award_price: null });
|
||
expect(invitation.local_status).toBe('won');
|
||
|
||
const detail = await getBidInvitationDetail({ branchCode: 'BR002', roundId: 'round-1' });
|
||
expect(detail?.items.map((item) => item.awardStatus).sort()).toEqual(['lost', 'won']);
|
||
expect(detail?.myAwards).toEqual([{ skuCode: 'SKU1', unitPrice: 11 }]);
|
||
// 中标价只读:不能把我方报价改写成中标价
|
||
expect(bySku.get('SKU1')?.unit_price).toBe(12.5);
|
||
});
|
||
|
||
it('对方改判(先 won 后 lost)⇒ 旧的中标价被清掉,不能留假事实', async () => {
|
||
const invitation = await seedRoundWithTwoItems();
|
||
await applyBidDetail({
|
||
branchCode: 'BR002',
|
||
supplierCode: 'SUP37831443',
|
||
roundId: 'round-1',
|
||
detail: {
|
||
round: { id: 'round-1', status: 'awarded' },
|
||
invitation: null,
|
||
items: [{ sku_code: 'SKU1' }, { sku_code: 'SKU2' }],
|
||
myQuotes: [],
|
||
myAwards: [{ sku_code: 'SKU1', unit_price: 11 }],
|
||
},
|
||
});
|
||
expect(invitation.local_status).toBe('won');
|
||
|
||
await applyBidDetail({
|
||
branchCode: 'BR002',
|
||
supplierCode: 'SUP37831443',
|
||
roundId: 'round-1',
|
||
detail: {
|
||
round: { id: 'round-1', status: 'awarded' },
|
||
invitation: null,
|
||
items: [{ sku_code: 'SKU1' }, { sku_code: 'SKU2' }],
|
||
myQuotes: [],
|
||
myAwards: [],
|
||
},
|
||
});
|
||
expect(db.items.every((row) => row.award_price === null && row.award_status === null)).toBe(true);
|
||
expect(invitation.local_status).toBe('lost');
|
||
});
|
||
|
||
it('对方返回 0 行明细(可识别)⇒ 本地旧行一并删掉,头与明细不会再打架', async () => {
|
||
// 能走到 applyBidDetail 说明响应是**可识别**的(`isDegenerateDetail` 已在 api 层挡掉空响应),
|
||
// 因此"0 行明细"本身就是事实 ⇒ 必须删(2026-10-17 修 tester F2)。
|
||
const invitation = await seedRoundWithTwoItems();
|
||
await applyBidDetail({
|
||
branchCode: 'BR002',
|
||
supplierCode: 'SUP37831443',
|
||
roundId: 'round-1',
|
||
detail: {
|
||
round: { id: 'round-1', round_code: 'BID001', status: 'open' },
|
||
invitation: { status: 'pending' },
|
||
items: [],
|
||
myQuotes: [],
|
||
myAwards: [],
|
||
},
|
||
});
|
||
expect(db.find(/DELETE FROM public\.main_system_bid_invitation_items/).length).toBeGreaterThan(0);
|
||
expect(db.items).toHaveLength(0);
|
||
expect(invitation.item_count).toBe(0);
|
||
});
|
||
|
||
it('孤儿保护:被删行的 award/报价不会写到别的 SKU 上(写入都按 (invitation, sku) 定位)', async () => {
|
||
const invitation = await seedRoundWithTwoItems();
|
||
await applyBidDetail({
|
||
branchCode: 'BR002',
|
||
supplierCode: 'SUP37831443',
|
||
roundId: 'round-1',
|
||
detail: {
|
||
round: { id: 'round-1', status: 'open' },
|
||
invitation: null,
|
||
items: [{ sku_code: 'SKU1' }],
|
||
myQuotes: [{ sku_code: 'SKU_DELETED', unit_price: 1 }],
|
||
myAwards: [{ sku_code: 'SKU_DELETED', unit_price: 2 }],
|
||
},
|
||
});
|
||
// SKU_DELETED 不在对方明细里 ⇒ 不该凭空建行,也不该把价格写到 SKU1
|
||
expect(db.items.map((row) => row.sku_code)).toEqual(['SKU1']);
|
||
expect(db.items[0].unit_price).toBe(null);
|
||
expect(invitation.local_status).toBe('pending');
|
||
});
|
||
});
|
||
|
||
/* ══ B7:提交前的本地校验(零外呼)══════════════════════════════════════════ */
|
||
|
||
describe('B7 本地校验:畸形单价 / 空报价 ⇒ 400 且零外呼', () => {
|
||
const badPrices: Array<[string, unknown]> = [
|
||
['0', 0],
|
||
['-1', -1],
|
||
['1.23456(5 位小数)', 1.23456],
|
||
['true(布尔会被 Number 洗白成 1)', true as unknown as number],
|
||
['[1.5](数组会被洗白成 1.5)', [1.5] as unknown as number],
|
||
["'abc'", 'abc' as unknown as number],
|
||
['9999999999(超对方 numeric(12,4))', 9999999999],
|
||
];
|
||
|
||
for (const [label, value] of badPrices) {
|
||
it(`单价 ${label} ⇒ 400 invalid_unit_price,且不发请求、不换 token、不碰库`, async () => {
|
||
const outcome = await quotes.submitBidQuotes({
|
||
branchCode: 'BR002',
|
||
roundId: 'round-1',
|
||
quotes: [{ skuCode: 'SKU1', unitPrice: value as number }],
|
||
});
|
||
expect(outcome.kind).toBe('rejected');
|
||
expect(failureOf(outcome).status).toBe(400);
|
||
expect(failureOf(outcome).code).toBe('invalid_unit_price');
|
||
expect(H.fetchMock).not.toHaveBeenCalled();
|
||
expect(H.token).not.toHaveBeenCalled();
|
||
expect(db.log).toHaveLength(0);
|
||
});
|
||
}
|
||
|
||
it('quotes: [] ⇒ 400 quotes_required,零外呼零落库', async () => {
|
||
const outcome = await quotes.submitBidQuotes({ branchCode: 'BR002', roundId: 'round-1', quotes: [] });
|
||
expect(failureOf(outcome).code).toBe('quotes_required');
|
||
expect(failureOf(outcome).status).toBe(400);
|
||
expect(H.fetchMock).not.toHaveBeenCalled();
|
||
expect(db.log).toHaveLength(0);
|
||
});
|
||
|
||
it('已过截止 ⇒ 409 quote_deadline_passed(本地时钟先挡,不打扰对方)', async () => {
|
||
const invitation = db.seedInvitation({ round_id: 'round-1', respond_deadline: pastIso(), item_count: 1 });
|
||
db.seedItem(invitation, { sku_code: 'SKU1' });
|
||
|
||
const outcome = await quotes.submitBidQuotes({
|
||
branchCode: 'BR002',
|
||
roundId: 'round-1',
|
||
quotes: [{ skuCode: 'SKU1', unitPrice: 12.5 }],
|
||
});
|
||
|
||
expect(failureOf(outcome).code).toBe('quote_deadline_passed');
|
||
expect(failureOf(outcome).status).toBe(409);
|
||
expect(H.fetchMock).not.toHaveBeenCalled();
|
||
expect(db.items[0].unit_price).toBe(null); // 一个字都没写
|
||
});
|
||
|
||
it('轮次 closed ⇒ 409 bid_not_open(终态不可再报)', async () => {
|
||
const invitation = db.seedInvitation({ round_id: 'round-1', round_status: 'closed', item_count: 1 });
|
||
db.seedItem(invitation, { sku_code: 'SKU1' });
|
||
|
||
const outcome = await quotes.submitBidQuotes({
|
||
branchCode: 'BR002',
|
||
roundId: 'round-1',
|
||
quotes: [{ skuCode: 'SKU1', unitPrice: 12.5 }],
|
||
});
|
||
|
||
expect(failureOf(outcome).code).toBe('bid_not_open');
|
||
expect(failureOf(outcome).status).toBe(409);
|
||
expect(H.fetchMock).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('轮次 draft ⇒ 409 bid_not_open(只有 open 可报)', async () => {
|
||
const invitation = db.seedInvitation({ round_id: 'round-1', round_status: 'draft', item_count: 1 });
|
||
db.seedItem(invitation, { sku_code: 'SKU1' });
|
||
const outcome = await quotes.submitBidQuotes({
|
||
branchCode: 'BR002',
|
||
roundId: 'round-1',
|
||
quotes: [{ skuCode: 'SKU1', unitPrice: 1 }],
|
||
});
|
||
expect(failureOf(outcome).code).toBe('bid_not_open');
|
||
expect(H.fetchMock).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('SKU 不在本轮明细 ⇒ 400 sku_not_in_round(不猜、不外呼)', async () => {
|
||
const invitation = db.seedInvitation({ round_id: 'round-1', item_count: 1 });
|
||
db.seedItem(invitation, { sku_code: 'SKU1' });
|
||
|
||
const outcome = await quotes.submitBidQuotes({
|
||
branchCode: 'BR002',
|
||
roundId: 'round-1',
|
||
quotes: [{ skuCode: 'SKU_NOBODY', unitPrice: 12.5 }],
|
||
});
|
||
|
||
expect(failureOf(outcome).code).toBe('sku_not_in_round');
|
||
expect(failureOf(outcome).status).toBe(400);
|
||
expect(String(failureOf(outcome).message)).toContain('SKU_NOBODY');
|
||
expect(H.fetchMock).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('多行里有一行非法 ⇒ 整单 400(不做部分提交)', async () => {
|
||
const invitation = db.seedInvitation({ round_id: 'round-1', item_count: 2 });
|
||
db.seedItem(invitation, { sku_code: 'SKU1' });
|
||
db.seedItem(invitation, { sku_code: 'SKU2' });
|
||
const outcome = await quotes.submitBidQuotes({
|
||
branchCode: 'BR002',
|
||
roundId: 'round-1',
|
||
quotes: [
|
||
{ skuCode: 'SKU1', unitPrice: 12.5 },
|
||
{ skuCode: 'SKU2', unitPrice: -0.01 },
|
||
],
|
||
});
|
||
expect(failureOf(outcome).code).toBe('invalid_unit_price');
|
||
expect(String(failureOf(outcome).message)).toContain('SKU2');
|
||
expect(H.fetchMock).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('本地没有这轮台账 ⇒ 404 bid_invitation_not_found(先同步也不认识 ⇒ 不猜)', async () => {
|
||
H.fetchMock.mockResolvedValue(jsonResponse(200, { data: [], settings: { enabled: true } }));
|
||
const outcome = await quotes.submitBidQuotes({
|
||
branchCode: 'BR002',
|
||
roundId: 'round-missing',
|
||
quotes: [{ skuCode: 'SKU1', unitPrice: 1 }],
|
||
});
|
||
expect(failureOf(outcome).code).toBe('bid_invitation_not_found');
|
||
expect(failureOf(outcome).status).toBe(404);
|
||
// 只发生了一次"同步"的列表请求,没有提交请求
|
||
expect(H.fetchMock).toHaveBeenCalledTimes(1);
|
||
expect(String((H.fetchMock.mock.calls[0] as unknown[])[0])).toContain('/api/supplier/bids');
|
||
});
|
||
});
|
||
|
||
/* ══ B8:出站(401 / 403 / 请求体 / 身份)════════════════════════════════════ */
|
||
|
||
describe('B8 出站:token 与重试纪律', () => {
|
||
function seedQuotableRound(over: Record<string, unknown> = {}) {
|
||
const invitation = db.seedInvitation({ round_id: 'round-1', item_count: 1, ...over });
|
||
db.seedItem(invitation, { sku_code: 'SKU1' });
|
||
return invitation;
|
||
}
|
||
|
||
it('401(刷新后仍 401)⇒ 失败,且恰好 2 次请求 / 2 次换 token(第二次 forceRefresh)', async () => {
|
||
seedQuotableRound();
|
||
H.fetchMock
|
||
.mockResolvedValueOnce(jsonResponse(401, { error: 'unauthorized' }))
|
||
.mockResolvedValueOnce(jsonResponse(401, { error: 'unauthorized' }));
|
||
|
||
const outcome = await quotes.submitBidQuotes({
|
||
branchCode: 'BR002',
|
||
roundId: 'round-1',
|
||
quotes: [{ skuCode: 'SKU1', unitPrice: 12.5 }],
|
||
});
|
||
|
||
expect(outcome.kind).toBe('unavailable');
|
||
expect(failureOf(outcome).status).toBe(502);
|
||
expect(H.fetchMock).toHaveBeenCalledTimes(2); // 没有第三次
|
||
expect(H.token).toHaveBeenCalledTimes(2);
|
||
expect(H.token.mock.calls[1][1]).toEqual({ forceRefresh: true });
|
||
});
|
||
|
||
it('401 后刷新成功 ⇒ 重试一次即成功,本地报价落库', async () => {
|
||
const invitation = seedQuotableRound();
|
||
H.fetchMock
|
||
.mockResolvedValueOnce(jsonResponse(401, { error: 'unauthorized' }))
|
||
.mockResolvedValueOnce(
|
||
jsonResponse(
|
||
200,
|
||
detailPayload({
|
||
my_quotes: [{ sku_code: 'SKU1', unit_price: 12.5, updated_at: pastIso() }],
|
||
invitation: { status: 'quoted' },
|
||
})
|
||
)
|
||
);
|
||
|
||
const outcome = await quotes.submitBidQuotes({
|
||
branchCode: 'BR002',
|
||
roundId: 'round-1',
|
||
quotes: [{ skuCode: 'SKU1', unitPrice: 12.5 }],
|
||
});
|
||
|
||
expect(outcome.kind).toBe('ok');
|
||
expect(H.fetchMock).toHaveBeenCalledTimes(2);
|
||
expect(db.items[0].unit_price).toBe(12.5);
|
||
expect(invitation.local_status).toBe('quoted');
|
||
});
|
||
|
||
it('403 是语义拒绝(不刷新 token、不重试)', async () => {
|
||
seedQuotableRound();
|
||
H.fetchMock.mockResolvedValueOnce(
|
||
jsonResponse(403, { error: 'supplier_category_mismatch', error_description: '商品 SKU1 不在你的经营品类内,无法报价' })
|
||
);
|
||
|
||
const outcome = await quotes.submitBidQuotes({
|
||
branchCode: 'BR002',
|
||
roundId: 'round-1',
|
||
quotes: [{ skuCode: 'SKU1', unitPrice: 12.5 }],
|
||
});
|
||
|
||
expect(outcome.kind).toBe('rejected');
|
||
expect(failureOf(outcome).status).toBe(403);
|
||
expect(failureOf(outcome).code).toBe('supplier_category_mismatch');
|
||
expect(H.fetchMock).toHaveBeenCalledTimes(1);
|
||
expect(H.token).toHaveBeenCalledTimes(1);
|
||
});
|
||
|
||
it('请求体是对方的 snake_case,URL 是 {bids}/:round/quotes,身份取**该邀约行**的编码', async () => {
|
||
const invitation = db.seedInvitation({ round_id: 'round-9', supplier_code: 'SUP-B', item_count: 2 });
|
||
db.seedItem(invitation, { sku_code: 'SKU1' });
|
||
db.seedItem(invitation, { sku_code: 'SKU2' });
|
||
H.fetchMock.mockResolvedValueOnce(
|
||
jsonResponse(
|
||
200,
|
||
detailPayload({
|
||
my_quotes: [
|
||
{ sku_code: 'SKU1', unit_price: 12.34 },
|
||
{ sku_code: 'SKU2', unit_price: 5, remark: null },
|
||
],
|
||
})
|
||
)
|
||
);
|
||
|
||
await quotes.submitBidQuotes({
|
||
branchCode: 'BR002',
|
||
roundId: 'round-9',
|
||
supplierCode: 'SUP-B',
|
||
quotes: [
|
||
{ skuCode: 'SKU1', unitPrice: 12.34, remark: '现杀' },
|
||
{ skuCode: 'SKU2', unitPrice: 5 },
|
||
],
|
||
});
|
||
|
||
const [url, init] = H.fetchMock.mock.calls[0] as [string, RequestInit];
|
||
expect(url).toBe('http://main-system.test/api/supplier/bids/round-9/quotes');
|
||
expect((init.headers as Record<string, string>).Authorization).toBe('Bearer tok-1');
|
||
expect(init.method).toBe('POST');
|
||
expect(JSON.parse(String(init.body))).toEqual({
|
||
quotes: [
|
||
{ sku_code: 'SKU1', unit_price: 12.34, remark: '现杀' },
|
||
{ sku_code: 'SKU2', unit_price: 5, remark: null },
|
||
],
|
||
});
|
||
// 换 token 用的是该邀约的 supplier_code(不是分公司编码)
|
||
expect(H.token.mock.calls[0][0]).toBe('SUP-B');
|
||
});
|
||
|
||
it('列表也按邀约行的编码出站(GET /api/supplier/bids,无子路径)', async () => {
|
||
H.fetchMock.mockResolvedValue(jsonResponse(200, { data: [], settings: { enabled: true } }));
|
||
const outcome = await bidApi.listMainSupplierBids('SUP37831443');
|
||
expect(outcome.kind).toBe('ok');
|
||
const [url, init] = H.fetchMock.mock.calls[0] as [string, RequestInit];
|
||
expect(url).toBe('http://main-system.test/api/supplier/bids');
|
||
expect(init.method).toBe('GET');
|
||
});
|
||
|
||
it('404 ⇒ 详情接口软删该行(round_status/local_status=cancelled)并留 sync_error', async () => {
|
||
const invitation = seedQuotableRound();
|
||
H.fetchMock.mockResolvedValueOnce(jsonResponse(404, { error: 'not_found' }));
|
||
|
||
const outcome = await quotes.submitBidQuotes({
|
||
branchCode: 'BR002',
|
||
roundId: 'round-1',
|
||
quotes: [{ skuCode: 'SKU1', unitPrice: 12.5 }],
|
||
});
|
||
|
||
expect(outcome.kind).toBe('rejected');
|
||
expect(failureOf(outcome).code).toBe('not_found');
|
||
expect(invitation.round_status).toBe('cancelled');
|
||
expect(invitation.local_status).toBe('cancelled');
|
||
expect(String(invitation.sync_error)).toContain('not_found');
|
||
expect(db.items[0].unit_price).toBe(null);
|
||
});
|
||
|
||
it('对方 403 forbidden(未受邀/编码未绑定)⇒ 软删该行 cancelled(不是只写 sync_error)', async () => {
|
||
const invitation = seedQuotableRound();
|
||
H.fetchMock.mockResolvedValueOnce(jsonResponse(403, { error: 'forbidden' }));
|
||
const outcome = await quotes.submitBidQuotes({
|
||
branchCode: 'BR002',
|
||
roundId: 'round-1',
|
||
quotes: [{ skuCode: 'SKU1', unitPrice: 12.5 }],
|
||
});
|
||
expect(failureOf(outcome).code).toBe('forbidden');
|
||
expect(failureOf(outcome).status).toBe(403);
|
||
expect(invitation.round_status).toBe('cancelled');
|
||
expect(invitation.local_status).toBe('cancelled');
|
||
expect(H.fetchMock).toHaveBeenCalledTimes(1); // 403 不重试
|
||
});
|
||
|
||
it('对接未配置 ⇒ 503 main_system_not_configured(不是 502:这是配置问题,重试无用)', async () => {
|
||
seedQuotableRound();
|
||
H.token.mockResolvedValue({ kind: 'not_configured', reason: '缺 client_secret' });
|
||
const outcome = await quotes.submitBidQuotes({
|
||
branchCode: 'BR002',
|
||
roundId: 'round-1',
|
||
quotes: [{ skuCode: 'SKU1', unitPrice: 12.5 }],
|
||
});
|
||
expect(outcome.kind).toBe('not_configured');
|
||
expect(failureOf(outcome).status).toBe(503);
|
||
expect(failureOf(outcome).code).toBe('main_system_not_configured');
|
||
expect(H.fetchMock).not.toHaveBeenCalled();
|
||
expect(db.items[0].unit_price).toBe(null);
|
||
});
|
||
|
||
it('换 token 失败(暂态)⇒ 502,且不发业务请求', async () => {
|
||
seedQuotableRound();
|
||
H.token.mockResolvedValue({ kind: 'unavailable', reason: '对方 oauth 503' });
|
||
const outcome = await quotes.submitBidQuotes({
|
||
branchCode: 'BR002',
|
||
roundId: 'round-1',
|
||
quotes: [{ skuCode: 'SKU1', unitPrice: 12.5 }],
|
||
});
|
||
expect(failureOf(outcome).status).toBe(502);
|
||
expect(failureOf(outcome).code).toBe('main_system_unavailable');
|
||
expect(H.fetchMock).not.toHaveBeenCalled();
|
||
});
|
||
});
|
||
|
||
/* ══ B9:失败不落价 ═════════════════════════════════════════════════════════ */
|
||
|
||
describe('B9 失败不落价:5xx / 超时 / 退化 2xx ⇒ 不动本地报价,只写 sync_error', () => {
|
||
function seedQuotedRound() {
|
||
const invitation = db.seedInvitation({
|
||
round_id: 'round-1',
|
||
item_count: 1,
|
||
local_status: 'quoted',
|
||
quoted_at: pastIso(),
|
||
});
|
||
db.seedItem(invitation, { sku_code: 'SKU1', unit_price: 12.5, quoted_at: pastIso(), remark: '原价' });
|
||
return invitation;
|
||
}
|
||
|
||
/** 每种失败都把 fetch 脚本化成"一次性响应/异常" */
|
||
const cases: Array<[string, () => void]> = [
|
||
['对方 500', () => H.fetchMock.mockResolvedValueOnce(jsonResponse(500, { error: 'internal_error' }))],
|
||
['对方 503', () => H.fetchMock.mockResolvedValueOnce(jsonResponse(503, { error: 'maintenance' }))],
|
||
['网络错误', () => H.fetchMock.mockRejectedValueOnce(new Error('ECONNREFUSED 127.0.0.1:3001'))],
|
||
['超时(AbortError)', () => H.fetchMock.mockRejectedValueOnce(abortError())],
|
||
['2xx 但载荷是 `{}`', () => H.fetchMock.mockResolvedValueOnce(jsonResponse(200, {}))],
|
||
['2xx 但 data 为 null', () => H.fetchMock.mockResolvedValueOnce(jsonResponse(200, { data: null }))],
|
||
['2xx 但非 JSON(网关 HTML)', () => H.fetchMock.mockResolvedValueOnce(nonJsonResponse(200))],
|
||
];
|
||
|
||
for (const [label, arrange] of cases) {
|
||
it(`${label} ⇒ 502 失败、applyBidDetail 未被调用、本地报价原样、只写 sync_error`, async () => {
|
||
const invitation = seedQuotedRound();
|
||
arrange();
|
||
|
||
const outcome = await quotes.submitBidQuotes({
|
||
branchCode: 'BR002',
|
||
roundId: 'round-1',
|
||
quotes: [{ skuCode: 'SKU1', unitPrice: 99.9999 }],
|
||
});
|
||
|
||
expect(outcome.kind).toBe('unavailable');
|
||
expect(failureOf(outcome).status).toBe(502);
|
||
expect(H.applyBidDetail).not.toHaveBeenCalled();
|
||
// 本地报价一个字都没变(含 quoted_at / remark / 状态)
|
||
expect(db.items[0]).toMatchObject({ unit_price: 12.5, remark: '原价' });
|
||
expect(invitation.local_status).toBe('quoted');
|
||
expect(db.find(/INSERT INTO public\.main_system_bid_invitation_items AS it/)).toHaveLength(0);
|
||
expect(db.find(/SET unit_price = \$3, remark = \$4/)).toHaveLength(0);
|
||
// 失败原因可追
|
||
expect(String(invitation.sync_error)).toContain(':');
|
||
expect(db.find(/SET sync_error = \$3/)).toHaveLength(1);
|
||
});
|
||
}
|
||
|
||
it('退化 2xx 的对外错误码在 service 层被收成 main_system_unavailable(见报告:契约写的 invalid_main_system_response 丢了)', async () => {
|
||
seedQuotedRound();
|
||
H.fetchMock.mockReset();
|
||
H.fetchMock.mockResolvedValueOnce(jsonResponse(200, {}));
|
||
|
||
// api 层仍保留精确码
|
||
const apiOutcome = await bidApi.getMainSupplierBidDetail('SUP37831443', 'round-1');
|
||
expect(apiOutcome.kind).toBe('unavailable');
|
||
expect(failureOf(apiOutcome).code).toBe('invalid_main_system_response');
|
||
|
||
const outcome = await quotes.submitBidQuotes({
|
||
branchCode: 'BR002',
|
||
roundId: 'round-1',
|
||
quotes: [{ skuCode: 'SKU1', unitPrice: 99 }],
|
||
});
|
||
expect(failureOf(outcome).code).toBe('main_system_unavailable');
|
||
expect(failureOf(outcome).kind).toBe('unavailable');
|
||
});
|
||
|
||
it('对方 400 bid_not_open ⇒ 状态码照对方(400)+ 码透出,并立刻按对方对齐一次', async () => {
|
||
seedQuotedRound();
|
||
H.fetchMock.mockReset();
|
||
H.fetchMock
|
||
.mockResolvedValueOnce(jsonResponse(400, { error: 'bid_not_open', error_description: '本轮已结束报价' }))
|
||
// 随后 refreshBidInvitation 的 GET(对方说已关闭)
|
||
.mockResolvedValueOnce(
|
||
jsonResponse(
|
||
200,
|
||
detailPayload({ round: { id: 'round-1', status: 'closed', respond_deadline: pastIso() } })
|
||
)
|
||
);
|
||
|
||
const outcome = await quotes.submitBidQuotes({
|
||
branchCode: 'BR002',
|
||
roundId: 'round-1',
|
||
quotes: [{ skuCode: 'SKU1', unitPrice: 99 }],
|
||
});
|
||
|
||
expect(failureOf(outcome).code).toBe('bid_not_open');
|
||
expect(failureOf(outcome).status).toBe(400);
|
||
expect(H.fetchMock).toHaveBeenCalledTimes(2); // POST + 自动刷新 GET
|
||
expect(String((H.fetchMock.mock.calls[1] as unknown[])[0])).toContain('/api/supplier/bids/round-1');
|
||
// 提交的 99 从未落库;本地价按对方返回重写(对方说这轮已关闭、我这边没有报价)
|
||
expect(db.items[0].unit_price).not.toBe(99);
|
||
expect(db.items[0].unit_price).toBe(null);
|
||
expect(db.invitations[0].round_status).toBe('closed');
|
||
});
|
||
|
||
it('对方 409 quote_deadline_passed ⇒ 409 + 码透出', async () => {
|
||
seedQuotedRound();
|
||
H.fetchMock.mockReset();
|
||
H.fetchMock
|
||
.mockResolvedValueOnce(jsonResponse(409, { error: 'quote_deadline_passed' }))
|
||
.mockResolvedValueOnce(jsonResponse(200, detailPayload()));
|
||
|
||
const outcome = await quotes.submitBidQuotes({
|
||
branchCode: 'BR002',
|
||
roundId: 'round-1',
|
||
quotes: [{ skuCode: 'SKU1', unitPrice: 99 }],
|
||
});
|
||
expect(failureOf(outcome).code).toBe('quote_deadline_passed');
|
||
expect(failureOf(outcome).status).toBe(409);
|
||
});
|
||
|
||
it('成功提交后用**对方返回**的视图落库(不是拿我发的入参当事实)', async () => {
|
||
const invitation = seedQuotedRound();
|
||
H.fetchMock.mockReset();
|
||
H.fetchMock.mockResolvedValueOnce(
|
||
jsonResponse(
|
||
200,
|
||
detailPayload({
|
||
invitation: { status: 'quoted' },
|
||
my_quotes: [{ sku_code: 'SKU1', unit_price: 13.75, updated_at: pastIso() }],
|
||
})
|
||
)
|
||
);
|
||
|
||
const outcome = await quotes.submitBidQuotes({
|
||
branchCode: 'BR002',
|
||
roundId: 'round-1',
|
||
quotes: [{ skuCode: 'SKU1', unitPrice: 13.75 }],
|
||
});
|
||
|
||
expect(outcome.kind).toBe('ok');
|
||
expect(db.items[0].unit_price).toBe(13.75);
|
||
expect(invitation.local_status).toBe('quoted');
|
||
expect(H.applyBidDetail).toHaveBeenCalledTimes(1);
|
||
});
|
||
});
|
||
|
||
/* ══ B15:多绑定同一轮 ═════════════════════════════════════════════════════ */
|
||
|
||
describe('B15 多绑定:同一 (branch, round) 两行邀约', () => {
|
||
function seedTwoBindings() {
|
||
const a = db.seedInvitation({ round_id: 'round-1', supplier_code: 'SUP-A', item_count: 1 });
|
||
db.seedItem(a, { sku_code: 'SKU1' });
|
||
const b = db.seedInvitation({ round_id: 'round-1', supplier_code: 'SUP-B', item_count: 1 });
|
||
db.seedItem(b, { sku_code: 'SKU1' });
|
||
return { a, b };
|
||
}
|
||
|
||
it('findInvitationByRound:不带 supplier 且两行 ⇒ ambiguous(列出候选,不猜)', async () => {
|
||
seedTwoBindings();
|
||
const outcome = await findInvitationByRound({ branchCode: 'BR002', roundId: 'round-1' });
|
||
expect(outcome.kind).toBe('ambiguous');
|
||
expect((outcome as unknown as { supplierCodes: string[] }).supplierCodes.sort()).toEqual(['SUP-A', 'SUP-B']);
|
||
});
|
||
|
||
it('findInvitationByRound:带 supplier(大小写不同也认)⇒ 精确命中', async () => {
|
||
const { b } = seedTwoBindings();
|
||
const outcome = await findInvitationByRound({
|
||
branchCode: 'BR002',
|
||
roundId: 'round-1',
|
||
supplierCode: 'sup-b',
|
||
});
|
||
expect(outcome.kind).toBe('found');
|
||
expect((outcome as unknown as { row: { id: string } }).row.id).toBe(b.id);
|
||
});
|
||
|
||
it('刷新不带 supplier ⇒ 409 bid_invitation_ambiguous,零外呼(绝不替用户选一家)', async () => {
|
||
seedTwoBindings();
|
||
const outcome = await quotes.refreshBidInvitation({ branchCode: 'BR002', roundId: 'round-1' });
|
||
expect(failureOf(outcome).code).toBe('bid_invitation_ambiguous');
|
||
expect(failureOf(outcome).status).toBe(409);
|
||
expect(H.fetchMock).not.toHaveBeenCalled();
|
||
expect(H.token).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('提交不带 supplier ⇒ 409 bid_invitation_ambiguous,零外呼', async () => {
|
||
seedTwoBindings();
|
||
const outcome = await quotes.submitBidQuotes({
|
||
branchCode: 'BR002',
|
||
roundId: 'round-1',
|
||
quotes: [{ skuCode: 'SKU1', unitPrice: 1 }],
|
||
});
|
||
expect(failureOf(outcome).code).toBe('bid_invitation_ambiguous');
|
||
expect(failureOf(outcome).status).toBe(409);
|
||
expect(H.fetchMock).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('带 supplier ⇒ 只用那一行的编码换 token(不会以另一家身份报价)', async () => {
|
||
const { b } = seedTwoBindings();
|
||
H.fetchMock.mockResolvedValueOnce(jsonResponse(200, detailPayload({ invitation: { status: 'quoted' } })));
|
||
const outcome = await quotes.refreshBidInvitation({
|
||
branchCode: 'BR002',
|
||
roundId: 'round-1',
|
||
supplierCode: 'SUP-B',
|
||
});
|
||
expect(outcome.kind).toBe('ok');
|
||
expect(H.token.mock.calls[0][0]).toBe('SUP-B');
|
||
// 只有 SUP-B 那行被刷新,SUP-A 的 last_synced_at 不动
|
||
expect(b.last_synced_at).toBeTruthy();
|
||
expect(db.invitations.find((row) => row.supplier_code === 'SUP-A')?.last_synced_at).toBe(null);
|
||
});
|
||
|
||
it('跨分公司隔离:别的分公司看不到这轮(定位永远带 branch_code,不只按 round_id)', async () => {
|
||
seedTwoBindings();
|
||
// 同步兜底也只会拉本分公司的绑定(这里显式返回空,避免"靠同步补出来"的假通过)
|
||
H.bindingCodes.mockResolvedValue([]);
|
||
const detail = await getBidInvitationDetail({ branchCode: 'BR999', roundId: 'round-1' });
|
||
expect(detail).toBe(null);
|
||
|
||
const refresh = await quotes.refreshBidInvitation({ branchCode: 'BR999', roundId: 'round-1' });
|
||
expect(failureOf(refresh).code).toBe('bid_invitation_not_found');
|
||
expect(failureOf(refresh).status).toBe(404);
|
||
expect(H.fetchMock).not.toHaveBeenCalled();
|
||
// 本分公司的两行没被动过
|
||
expect(db.invitations.every((row) => row.local_status === 'pending')).toBe(true);
|
||
});
|
||
});
|
||
|
||
/* ══ REST 层:HTTP 状态码与错误体形状(B7/B8/B15 的出口)════════════════════ */
|
||
|
||
describe('REST 层:4 个接口的状态码 / 错误体(sendBidFailure)', () => {
|
||
const url = (roundId: string) => `/api/workflow/main-system/bid-invitations/${roundId}`;
|
||
|
||
it('POST quotes 空 ⇒ 400 { error, error_description, error_kind }', async () => {
|
||
const res = await request(buildApp()).post(`${url('round-1')}/quotes`).send({ quotes: [] });
|
||
expect(res.status).toBe(400);
|
||
expect(res.body).toMatchObject({ error: 'quotes_required', error_kind: 'rejected' });
|
||
expect(typeof res.body.error_description).toBe('string');
|
||
expect(H.fetchMock).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('POST quotes 单价非法 ⇒ 400 invalid_unit_price', async () => {
|
||
const res = await request(buildApp())
|
||
.post(`${url('round-1')}/quotes`)
|
||
.send({ quotes: [{ skuCode: 'SKU1', unitPrice: 0 }] });
|
||
expect(res.status).toBe(400);
|
||
expect(res.body.error).toBe('invalid_unit_price');
|
||
});
|
||
|
||
it('POST quotes 过截止 ⇒ 409 quote_deadline_passed', async () => {
|
||
const invitation = db.seedInvitation({ round_id: 'round-1', respond_deadline: pastIso(), item_count: 1 });
|
||
db.seedItem(invitation, { sku_code: 'SKU1' });
|
||
const res = await request(buildApp())
|
||
.post(`${url('round-1')}/quotes`)
|
||
.send({ quotes: [{ skuCode: 'SKU1', unitPrice: 1 }] });
|
||
expect(res.status).toBe(409);
|
||
expect(res.body).toMatchObject({ error: 'quote_deadline_passed', error_kind: 'rejected' });
|
||
});
|
||
|
||
it('POST quotes 对方不可用 ⇒ 502 main_system_unavailable(error_kind=unavailable)', async () => {
|
||
const invitation = db.seedInvitation({ round_id: 'round-1', item_count: 1 });
|
||
db.seedItem(invitation, { sku_code: 'SKU1' });
|
||
H.fetchMock.mockResolvedValueOnce(jsonResponse(500, { error: 'boom' }));
|
||
const res = await request(buildApp())
|
||
.post(`${url('round-1')}/quotes`)
|
||
.send({ quotes: [{ skuCode: 'SKU1', unitPrice: 1 }] });
|
||
expect(res.status).toBe(502);
|
||
expect(res.body).toMatchObject({ error: 'main_system_unavailable', error_kind: 'unavailable' });
|
||
});
|
||
|
||
it('POST quotes 多绑定不带 supplierCode ⇒ 409 bid_invitation_ambiguous', async () => {
|
||
db.seedInvitation({ round_id: 'round-1', supplier_code: 'SUP-A', item_count: 1 });
|
||
db.seedInvitation({ round_id: 'round-1', supplier_code: 'SUP-B', item_count: 1 });
|
||
const res = await request(buildApp())
|
||
.post(`${url('round-1')}/quotes`)
|
||
.send({ quotes: [{ skuCode: 'SKU1', unitPrice: 1 }] });
|
||
expect(res.status).toBe(409);
|
||
expect(res.body.error).toBe('bid_invitation_ambiguous');
|
||
});
|
||
|
||
it('POST quotes 也接受 snake_case body(sku_code / unit_price / supplierCode)', async () => {
|
||
const invitation = db.seedInvitation({ round_id: 'round-1', item_count: 1 });
|
||
db.seedItem(invitation, { sku_code: 'SKU1' });
|
||
H.fetchMock.mockResolvedValueOnce(
|
||
jsonResponse(200, detailPayload({ invitation: { status: 'quoted' }, my_quotes: [{ sku_code: 'SKU1', unit_price: 3 }] }))
|
||
);
|
||
const res = await request(buildApp())
|
||
.post(`${url('round-1')}/quotes`)
|
||
.send({ quotes: [{ sku_code: 'SKU1', unit_price: 3 }] });
|
||
expect(res.status).toBe(200);
|
||
expect(res.body.error).toBe(null);
|
||
expect(res.body.data.items[0].unitPrice).toBe(3);
|
||
const body = JSON.parse(String((H.fetchMock.mock.calls[0] as [string, RequestInit])[1].body));
|
||
expect(body.quotes).toEqual([{ sku_code: 'SKU1', unit_price: 3, remark: null }]);
|
||
});
|
||
|
||
it('GET 清单无分公司上下文 ⇒ 400 branch_required(与 /main-system/preparations 同口径)', async () => {
|
||
H.tenantCtx.value = { branchCode: '', permissions: ['order_manage'], roles: ['admin'], isSuperAdmin: false };
|
||
const res = await request(buildApp()).get('/api/workflow/main-system/bid-invitations');
|
||
expect(res.status).toBe(400);
|
||
expect(res.body).toMatchObject({ error: 'branch_required', error_kind: 'rejected' });
|
||
});
|
||
|
||
it('GET :roundId 带 ?supplier= 时按该编码出站(多绑定精确命中)', async () => {
|
||
db.seedInvitation({ round_id: 'round-1', supplier_code: 'SUP-A', item_count: 1 });
|
||
db.seedInvitation({ round_id: 'round-1', supplier_code: 'SUP-B', item_count: 1 });
|
||
H.fetchMock.mockResolvedValueOnce(jsonResponse(200, detailPayload()));
|
||
const res = await request(buildApp()).get(`${url('round-1')}?supplier=SUP-B`);
|
||
expect(res.status).toBe(200);
|
||
expect(H.token.mock.calls[0][0]).toBe('SUP-B');
|
||
});
|
||
|
||
it('GET 清单只读本地镜像(不外呼、不换 token)', async () => {
|
||
const invitation = db.seedInvitation({ round_id: 'round-1', item_count: 1, local_status: 'pending' });
|
||
db.seedItem(invitation, { sku_code: 'SKU1' });
|
||
const res = await request(buildApp()).get('/api/workflow/main-system/bid-invitations?status=pending');
|
||
expect(res.status).toBe(200);
|
||
expect(Array.isArray(res.body.data)).toBe(true);
|
||
expect(res.body.data).toHaveLength(1);
|
||
expect(res.body.summary).toMatchObject({ pending: 1 });
|
||
expect(H.fetchMock).not.toHaveBeenCalled();
|
||
expect(H.token).not.toHaveBeenCalled();
|
||
});
|
||
});
|
||
|
||
/* ══ 迁移文件(§4,验收 B2/B15 的库侧约束)══════════════════════════════════ */
|
||
|
||
describe('迁移 20261055:两张表 / 两个幂等键 / IF NOT EXISTS / CHECK 覆盖', () => {
|
||
const sql = readFileSync(
|
||
path.join(__dirname, '../../migrations/20261055_main_system_bid_invitations.sql'),
|
||
'utf8'
|
||
);
|
||
|
||
it('两张表都建在 public,且都用 IF NOT EXISTS(可重跑迁移)', () => {
|
||
expect(sql).toMatch(/CREATE TABLE IF NOT EXISTS public\.main_system_bid_invitations \(/);
|
||
expect(sql).toMatch(/CREATE TABLE IF NOT EXISTS public\.main_system_bid_invitation_items \(/);
|
||
});
|
||
|
||
it('邀约幂等键 = (branch_code, round_id, supplier_code) 的 UNIQUE INDEX', () => {
|
||
expect(sql).toMatch(
|
||
/CREATE UNIQUE INDEX IF NOT EXISTS uq_main_system_bid_invitations_branch_round_supplier\s+ON public\.main_system_bid_invitations \(branch_code, round_id, supplier_code\)/
|
||
);
|
||
});
|
||
|
||
it('明细幂等键 = (invitation_id, sku_code) 的 UNIQUE INDEX,且外键 ON DELETE CASCADE', () => {
|
||
expect(sql).toMatch(
|
||
/CREATE UNIQUE INDEX IF NOT EXISTS uq_main_system_bid_invitation_items_invitation_sku\s+ON public\.main_system_bid_invitation_items \(invitation_id, sku_code\)/
|
||
);
|
||
expect(sql).toMatch(/REFERENCES public\.main_system_bid_invitations\(id\) ON DELETE CASCADE/);
|
||
});
|
||
|
||
it('local_status CHECK 覆盖 6 种状态(少一种会在写库时炸)', () => {
|
||
const block = sql.slice(
|
||
sql.indexOf('main_system_bid_invitations_local_status_check'),
|
||
sql.indexOf(');', sql.indexOf('main_system_bid_invitations_local_status_check'))
|
||
);
|
||
for (const status of ['pending', 'quoted', 'expired', 'won', 'lost', 'cancelled']) {
|
||
expect(block, status).toContain(`'${status}'`);
|
||
}
|
||
});
|
||
|
||
it('round_status CHECK 覆盖对方 5 种轮次状态;award_status 只允许 won/lost', () => {
|
||
for (const status of ['draft', 'open', 'closed', 'awarded', 'cancelled']) {
|
||
expect(sql, status).toContain(`'${status}'`);
|
||
}
|
||
expect(sql).toMatch(/CHECK \(award_status IS NULL OR award_status IN \('won', 'lost'\)\)/);
|
||
});
|
||
|
||
it('单价精度:numeric(14,4);`award_qty` numeric(14,3) 且默认无值(对方无数量列);单价 > 0 CHECK', () => {
|
||
expect(sql).toMatch(/unit_price numeric\(14,4\)/);
|
||
expect(sql).toMatch(/award_qty numeric\(14,3\)/);
|
||
expect(sql).toMatch(/CHECK \(unit_price IS NULL OR unit_price > 0\)/);
|
||
// 这两张是跨系统镜像台账 ⇒ 不放租户 schema(public)
|
||
expect(sql).not.toMatch(/CREATE TABLE[^;]*tenant_/i);
|
||
});
|
||
|
||
it('索引都带 IF NOT EXISTS(重跑不报 duplicate index);分支/状态索引与 round 定位索引存在', () => {
|
||
const indexLines = sql.split('\n').filter((line) => /^CREATE (UNIQUE )?INDEX/.test(line.trim()));
|
||
expect(indexLines.length).toBeGreaterThanOrEqual(4);
|
||
for (const line of indexLines) expect(line).toContain('IF NOT EXISTS');
|
||
expect(sql).toContain('idx_main_system_bid_invitations_branch_status');
|
||
expect(sql).toContain('idx_main_system_bid_invitations_round');
|
||
expect(sql).toContain('idx_main_system_bid_invitation_items_invitation');
|
||
});
|
||
|
||
it('迁移会被 runner 收录(migrations/*.sql 全部按名字执行)', () => {
|
||
const runner = readFileSync(path.join(__dirname, '../src/migrate.ts'), 'utf8');
|
||
expect(runner).toMatch(/endsWith\('\.sql'\)/);
|
||
expect(path.basename('20261055_main_system_bid_invitations.sql')).toMatch(/^\d{8}_.+\.sql$/);
|
||
});
|
||
});
|