Files
SupplierSystem/server/tests/mainSystemQuoteCostSync.test.ts
T
Ubuntu 3e4bc35b26 feat(报价单): 双向价格传递/改价审核/SKU 映射/成本同步推送(供应商侧)
- 报价单生效自动推销售价 → 配送成本价(台账+重试+rearm,映射优先)
- 编辑生效单改价走内部审核(quote_sheet_change_requests)
- 双向价格传递:A 提交配送商审核 / B 拉回并反查映射后写价、D3 回执
- SKU 映射:D4 字典推送、D5 完整拉取(截断不删)、只读本地副本
- 迁移登记 tenant_business_tables(三张租户表数组互相补齐,避免顺序敏感)
2026-10-18 20:10:58 +08:00

1023 lines
41 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { beforeEach, describe, expect, it, vi } from 'vitest';
/**
* 报价单销售价 → 主系统报价单成本价(**推送端**)—— 契约守卫。
*
* 冻结契约 2026-10-18(详见 docs/design/20261018-报价单成本价同步推送.md)。
* 这个文件钉住七类**做反就要返工**的行为:
* ① 默认关 ⇒ 零查库、零出站(审批/建单行为逐字节不变);
* ② 客户码闸门:只有 `MAIN_<码>` 才推;真实客户与 `__*__` 哨兵记 `not_usage_company`;
* ③ 一单多分公司各推一次,台账唯一键保证"一张单 × 一个分公司只推一次";
* ④ 明细口径:只推 `sale_price ?? price > 0`,单位超长/缺失带 null,金额按 2 位小数归一;
* ⑤ 台账状态机:2xx→sent、403→forbidden(不重试)、其它失败→failed;
* ⑥ 重试:只选 `failed && attempts<5`,**复用原 client_request_id**;
* ⑦ 旁路纪律:tenant 上下文 `isolate + requestClient:false`(不踩请求归还后的连接)。
*/
/* ── mock:DB(脚本化)────────────────────────────────────────────────────── */
const poolQuery = vi.hoisted(() => vi.fn());
vi.mock('../src/db', () => ({
pool: { query: (...args: unknown[]) => poolQuery(...args) },
getRawPoolQuery: () => poolQuery,
}));
const tenantCtx = vi.hoisted(() => vi.fn());
vi.mock('../src/services/tenantDbContext', () => ({
runWithTenantDbContext: (...args: unknown[]) => tenantCtx(...args),
}));
const submit = vi.hoisted(() => vi.fn());
vi.mock('../src/services/mainSystem/api/quoteCostSync', async (importOriginal) => {
const actual = await importOriginal<typeof import('../src/services/mainSystem/api/quoteCostSync')>();
return { ...actual, submitQuoteCostSync: (...args: unknown[]) => submit(...args) };
});
import {
MAIN_BRANCH_CUSTOMER_RE,
QUOTE_COST_SYNC_MAX_ATTEMPTS,
QUOTE_COST_SYNC_MAX_ITEMS,
collectQuoteCostSyncPlan,
isQuoteCostSyncEnabled,
normalizeQuoteCostSyncUnit,
parseMainBranchCode,
pushQuoteCostSyncForSheet,
quoteCostSyncItemsFingerprint,
readQuoteCostSyncSalePrice,
retryQuoteCostSyncPushes,
triggerQuoteCostSync,
} from '../src/services/mainSystemQuoteCostSync';
/* ── 脚本化 DB(含一条内存台账:唯一键 / attempts / response 都按真库语义走)─────────── */
type LedgerInsert = { sql: string; params: unknown[]; row: Record<string, unknown> | null };
type LedgerUpdate = { sql: string; params: unknown[] };
/** 内存台账行(模拟 `public.main_system_quote_cost_pushes`) */
type MockLedgerRow = {
id: string;
branch_code: string;
quote_sheet_code: string;
main_branch_code: string;
client_request_id: string;
status: string;
attempts: number;
last_error: string | null;
response: any;
/** 毫秒时间戳(模拟 updated_at;R-1 的"卡住超过 10 分钟"靠它) */
updated_at: number;
};
type DbState = {
sheet: Record<string, unknown> | null;
customers: string[];
items: Array<Record<string, unknown>>;
supplierCode: string | null;
/** 内存台账:键 = `quote_sheet_code::main_branch_code` */
ledger: Record<string, MockLedgerRow>;
/** 显式指定重试扫描结果(不给则按内存台账推导,见 installDb) */
retryRows: Array<Record<string, unknown>>;
inserts: LedgerInsert[];
updates: LedgerUpdate[];
};
function makeState(overrides: Partial<DbState> = {}): DbState {
return {
sheet: {
quote_sheet_code: 'QS1',
branch_code: 'BR002',
status: 1,
approval_status: 30,
approved_at: '2026-10-18T01:00:00.000Z',
effective_at: '2026-10-18T01:00:00.000Z',
expires_at: new Date(Date.now() + 86400_000).toISOString(),
},
customers: ['MAIN_BR002'],
items: [{ sku_code: 'SKU1', unit: '斤', sale_price: '12.34', price: '12.34' }],
supplierCode: 'SUP37831443',
ledger: {},
retryRows: [],
inserts: [],
updates: [],
...overrides,
};
}
/** 预置一行台账(模拟"上一次推送留下的行") */
function seedLedger(
state: DbState,
patch: Partial<MockLedgerRow> = {}
): MockLedgerRow {
const row: MockLedgerRow = {
id: patch.id ?? 'lid-seed',
branch_code: patch.branch_code ?? 'BR002',
quote_sheet_code: patch.quote_sheet_code ?? 'QS1',
main_branch_code: patch.main_branch_code ?? 'BR002',
client_request_id: patch.client_request_id ?? 'cr-seed',
status: patch.status ?? 'sent',
attempts: patch.attempts ?? 1,
last_error: patch.last_error ?? null,
response: patch.response ?? null,
updated_at: patch.updated_at ?? Date.now(),
};
state.ledger[`${row.quote_sheet_code}::${row.main_branch_code}`] = row;
return row;
}
const LEDGER_TABLE = 'FROM public.main_system_quote_cost_pushes';
function installDb(state: DbState): void {
const findById = (id: unknown) => Object.values(state.ledger).find((row) => row.id === String(id));
poolQuery.mockImplementation(async (sql: string, params: unknown[] = []) => {
// ① 重试扫描:failed && attempts<5 **或** 卡住 >10 分钟的 pending(R-1)
if (sql.includes("status = 'failed' AND attempts <")) {
if (state.retryRows.length) return { rows: state.retryRows };
const now = Date.now();
const rows = Object.values(state.ledger).filter(
(row) =>
(row.status === 'failed' && row.attempts < Number(params[0])) ||
(row.status === 'pending' && row.updated_at < now - 10 * 60 * 1000)
);
return {
rows: rows.map((row) => ({
id: row.id,
branch_code: row.branch_code,
quote_sheet_code: row.quote_sheet_code,
main_branch_code: row.main_branch_code,
client_request_id: row.client_request_id,
attempts: row.attempts,
status: row.status,
})),
};
}
// ② 读一行台账(判重 / 改价重推用)
if (sql.includes(LEDGER_TABLE) && sql.includes('WHERE quote_sheet_code = $1 AND main_branch_code = $2')) {
const row = state.ledger[`${params[0]}::${params[1]}`];
if (!row) return { rows: [], rowCount: 0 };
return {
rows: [
{
id: row.id,
status: row.status,
attempts: row.attempts,
client_request_id: row.client_request_id,
response: row.response,
},
],
rowCount: 1,
};
}
// ③ 台账 INSERT ... ON CONFLICT DO NOTHING
if (sql.includes('INSERT INTO public.main_system_quote_cost_pushes')) {
const key = `${params[1]}::${params[2]}`;
if (state.ledger[key]) {
state.inserts.push({ sql, params, row: null });
return { rows: [], rowCount: 0 };
}
const row: MockLedgerRow = {
id: `lid-${Object.keys(state.ledger).length + 1}`,
branch_code: String(params[0]),
quote_sheet_code: String(params[1]),
main_branch_code: String(params[2]),
client_request_id: String(params[3]),
status: String(params[4]),
attempts: 0,
last_error: (params[5] as string | null) ?? null,
response: params[6] ? JSON.parse(String(params[6])) : null,
updated_at: Date.now(),
};
state.ledger[key] = row;
state.inserts.push({ sql, params, row: { id: row.id, client_request_id: row.client_request_id } });
return { rows: [{ id: row.id, client_request_id: row.client_request_id }], rowCount: 1 };
}
// ④ 台账 UPDATE(普通回写 / 409 换号 / 改价重推)
if (sql.includes('UPDATE public.main_system_quote_cost_pushes')) {
state.updates.push({ sql, params });
const row = findById(params[0]);
if (sql.includes('payload_changed_rotate_id')) {
// $1=id, $2=新请求号, $3=409 明细
if (row) {
row.client_request_id = String(params[1]);
row.attempts = 0;
row.status = 'failed';
row.last_error = 'payload_changed_rotate_id';
row.response = { ...(row.response || {}), last_conflict_409: params[2] };
row.updated_at = Date.now();
}
return { rows: [{ client_request_id: params[1] }], rowCount: 1 };
}
if (sql.includes('rearmed_after_change')) {
// $1=id, $2=新请求号, $3=当前指纹
if (row) {
row.client_request_id = String(params[1]);
row.attempts = 0;
row.status = 'pending';
row.last_error = 'rearmed_after_change';
row.response = {
...(row.response || {}),
local: {
...((row.response || {}).local || {}),
sheet_reason: 'rearmed_after_change',
items_fingerprint: params[2],
},
};
row.updated_at = Date.now();
}
return { rows: [{ id: params[0], client_request_id: params[1] }], rowCount: 1 };
}
// 重试异常兜底:`attempts+1` + 把 pending 收口成 failed($1=id, $2=last_error)
if (sql.includes('status = CASE WHEN status =')) {
if (row) {
row.attempts += 1;
if (row.status === 'pending') row.status = 'failed';
row.last_error = String(params[1]);
row.updated_at = Date.now();
}
return { rows: [], rowCount: 1 };
}
// 普通 markLedger:$1=id, $2=status, $3=last_error, $4=response
if (row) {
row.status = String(params[1]);
row.attempts += 1;
row.last_error = (params[2] as string | null) ?? null;
row.response = params[3] ? JSON.parse(String(params[3])) : null;
row.updated_at = Date.now();
}
return { rows: [], rowCount: 1 };
}
if (sql.includes('AS code')) {
return { rows: [{ code: state.supplierCode }] };
}
if (sql.includes('FROM customer_quote_sheets')) {
return { rows: state.sheet ? [state.sheet] : [] };
}
if (sql.includes('FROM customer_quote_sheet_customers')) {
return { rows: state.customers.map((customer_code) => ({ customer_code })) };
}
if (sql.includes('FROM customer_quote_sheet_items')) {
return { rows: state.items };
}
return { rows: [] };
});
}
const okResult = () => ({
kind: 'ok' as const,
status: 200,
data: {
client_request_id: 'cr',
replayed: false,
main_branch_code: 'BR002',
updated: 1,
sheets: ['QS-THEIR'],
skipped: [],
warnings: [],
},
});
beforeEach(() => {
poolQuery.mockReset();
submit.mockReset();
tenantCtx.mockReset();
tenantCtx.mockImplementation(async (_code: string, fn: () => Promise<unknown>) => fn());
submit.mockResolvedValue(okResult());
delete process.env.MAIN_SYSTEM_QUOTE_COST_SYNC;
});
/* ── ① 开关与纯函数 ──────────────────────────────────────────────────────── */
describe('开关(默认关)', () => {
it('未设置 / 0 / 其它值 ⇒ 关;1 / true / on(大小写不敏感)⇒ 开', () => {
expect(isQuoteCostSyncEnabled()).toBe(false);
for (const value of ['0', '', 'false', 'off', 'yes']) {
process.env.MAIN_SYSTEM_QUOTE_COST_SYNC = value;
expect(isQuoteCostSyncEnabled(), value).toBe(false);
}
for (const value of ['1', 'true', 'TRUE', 'on', 'On']) {
process.env.MAIN_SYSTEM_QUOTE_COST_SYNC = value;
expect(isQuoteCostSyncEnabled(), value).toBe(true);
}
});
});
describe('客户码闸门 parseMainBranchCode', () => {
it('只认 ^MAIN_([0-9A-Za-z_-]{1,32})$(前缀大小写不敏感),且结果 UPPER', () => {
expect(MAIN_BRANCH_CUSTOMER_RE.test('MAIN_BR002')).toBe(true);
expect(parseMainBranchCode('MAIN_BR002')).toBe('BR002');
expect(parseMainBranchCode(' MAIN_br002 ')).toBe('BR002');
expect(parseMainBranchCode('MAIN_BR-002_A')).toBe('BR-002_A');
// 超长(33 字符)与空码都不成立
expect(parseMainBranchCode(`MAIN_${'A'.repeat(33)}`)).toBeNull();
expect(parseMainBranchCode('MAIN_')).toBeNull();
});
it('前缀大小写归一(A2):main_br002 / Main_BR002 与 MAIN_BR002 等价', () => {
for (const code of ['main_br002', 'Main_BR002', 'main_BR002', 'MaIn_br002', ' main_br002 ']) {
expect(parseMainBranchCode(code), code).toBe('BR002');
}
// X 段本身也归一成大写(对方分公司码是 BRxxx)
expect(parseMainBranchCode('main_br-002_a')).toBe('BR-002_A');
});
it('真实客户与哨兵客户一律不匹配(不写、不猜)', () => {
for (const code of [
'CUS98392383347',
'real_customer',
'__INDEPENDENT_INBOUND__',
'__RETAIL__',
'MAINBR002',
'',
]) {
expect(parseMainBranchCode(code), code).toBeNull();
}
});
});
describe('明细口径(单位 / 售价)', () => {
it('单位:trim 后 1~20 字符才带,否则 null(对方按 skus.unit 比)', () => {
expect(normalizeQuoteCostSyncUnit(' 斤 ')).toBe('斤');
expect(normalizeQuoteCostSyncUnit('袋装(500g)')).toBe('袋装(500g)');
expect(normalizeQuoteCostSyncUnit('')).toBeNull();
expect(normalizeQuoteCostSyncUnit(null)).toBeNull();
expect(normalizeQuoteCostSyncUnit('A'.repeat(21))).toBeNull();
});
it('售价:sale_price ?? price,只认 >0 的有限数,按 2 位小数归一', () => {
expect(readQuoteCostSyncSalePrice({ sale_price: '12.34', price: '9' })).toBe(12.34);
expect(readQuoteCostSyncSalePrice({ sale_price: null, price: '9.00' })).toBe(9);
expect(readQuoteCostSyncSalePrice({ sale_price: '12.345' })).toBe(12.35);
for (const bad of [null, undefined, '', '0', 0, -1, 'abc', 'NaN']) {
expect(readQuoteCostSyncSalePrice({ sale_price: bad as unknown }), String(bad)).toBeNull();
}
});
});
/* ── ② 门禁:零出站 ─────────────────────────────────────────────────────── */
describe('默认关 ⇒ 零查库、零出站', () => {
it('pushQuoteCostSyncForSheet 关时直接返回(不查库、不出站)', async () => {
const summary = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' });
expect(summary.attempted).toBe(0);
expect(poolQuery).not.toHaveBeenCalled();
expect(submit).not.toHaveBeenCalled();
expect(tenantCtx).not.toHaveBeenCalled();
});
it('retryQuoteCostSyncPushes 关时直接返回(连台账都不查)', async () => {
const summary = await retryQuoteCostSyncPushes({ limit: 10 });
expect(summary).toEqual({ rows: 0, attempted: 0, sent: 0, failed: 0, forbidden: 0, skipped: 0, errors: 0 });
expect(poolQuery).not.toHaveBeenCalled();
expect(submit).not.toHaveBeenCalled();
});
it('triggerQuoteCostSync 关时零动作(含参数缺失)', () => {
triggerQuoteCostSync({ branchCode: 'BR002', quoteSheetCode: 'QS1' });
expect(poolQuery).not.toHaveBeenCalled();
process.env.MAIN_SYSTEM_QUOTE_COST_SYNC = '1';
triggerQuoteCostSync({ branchCode: '', quoteSheetCode: 'QS1' });
triggerQuoteCostSync({ quoteSheetCode: 'QS1' });
expect(poolQuery).not.toHaveBeenCalled();
expect(submit).not.toHaveBeenCalled();
});
it('租户上下文按 isolate + requestClient:false 打开(不复用请求连接)', async () => {
process.env.MAIN_SYSTEM_QUOTE_COST_SYNC = '1';
installDb(makeState());
await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' });
expect(tenantCtx).toHaveBeenCalledTimes(1);
expect(tenantCtx.mock.calls[0][0]).toBe('BR002');
expect(tenantCtx.mock.calls[0][2]).toEqual({ isolate: true, requestClient: false });
});
});
/* ── ③ 推送主链路 ───────────────────────────────────────────────────────── */
describe('推送:单分公司', () => {
beforeEach(() => {
process.env.MAIN_SYSTEM_QUOTE_COST_SYNC = '1';
});
it('生效单 + MAIN_BR002 ⇒ 1 条台账 + 1 次出站(字段名照契约、请求号取自台账)', async () => {
const state = makeState();
installDb(state);
const summary = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' });
expect(summary.sent).toBe(1);
expect(summary.attempted).toBe(1);
expect(state.inserts).toHaveLength(1);
const insertParams = state.inserts[0].params;
expect(insertParams[0]).toBe('BR002');
expect(insertParams[1]).toBe('QS1');
expect(insertParams[2]).toBe('BR002');
expect(insertParams[4]).toBe('pending');
expect(submit).toHaveBeenCalledTimes(1);
const call = submit.mock.calls[0][0] as any;
expect(call.supplierCode).toBe('SUP37831443');
expect(call.body).toEqual({
client_request_id: insertParams[3],
supplier_quote_sheet_code: 'QS1',
main_branch_code: 'BR002',
activated_at: '2026-10-18T01:00:00.000Z',
items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 12.34 }],
});
expect(state.updates).toHaveLength(1);
expect(state.updates[0].params[1]).toBe('sent');
expect(state.updates[0].params[2]).toBeNull();
// 回执与本地口径都留在台账里
expect(String(state.updates[0].params[3])).toContain('QS-THEIR');
});
it('一单绑两个 MAIN 客户 ⇒ 按分公司各推一次(items 相同、分公司不同)', async () => {
const state = makeState({ customers: ['MAIN_BR003', 'MAIN_BR002', '__RETAIL__'] });
installDb(state);
const summary = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' });
expect(summary.sent).toBe(2);
expect(state.inserts.map((i) => i.params[2])).toEqual(['BR002', 'BR003']);
const branches = submit.mock.calls.map((c) => (c[0] as any).body.main_branch_code);
expect(branches).toEqual(['BR002', 'BR003']);
// 两个分公司各自独立的請求号
const ids = submit.mock.calls.map((c) => (c[0] as any).body.client_request_id);
expect(new Set(ids).size).toBe(2);
});
it('台账已有行且明细未变 ⇒ 不再出站(一张单 × 一个分公司只推一次)', async () => {
const state = makeState();
seedLedger(state, {
status: 'sent',
client_request_id: 'cr-old',
response: {
local: { items_fingerprint: quoteCostSyncItemsFingerprint([{ sku_code: 'SKU1', unit: '斤', sale_price: 12.34 }]) },
},
});
installDb(state);
const summary = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' });
expect(summary.duplicates).toBe(1);
expect(summary.attempted).toBe(0);
expect(summary.rearmed).toBe(0);
expect(submit).not.toHaveBeenCalled();
expect(state.updates).toHaveLength(0);
});
it('非 MAIN_ 客户(真实客户 + 两个哨兵)⇒ 整单记 skipped,零出站', async () => {
const state = makeState({ customers: ['CUS98392383347', '__INDEPENDENT_INBOUND__', '__RETAIL__'] });
installDb(state);
const summary = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' });
expect(summary.skipped).toBe(1);
expect(submit).not.toHaveBeenCalled();
expect(state.inserts).toHaveLength(1);
expect(state.inserts[0].params[2]).toBe('*'); // 整单级台账行
expect(state.inserts[0].params[4]).toBe('skipped');
expect(String(state.inserts[0].params[5])).toContain('not_usage_company');
});
it('全部明细 sale_price<=0(或缺失)⇒ 整单 skipped,零出站', async () => {
const state = makeState({
items: [
{ sku_code: 'SKU1', unit: '斤', sale_price: '0', price: '0' },
{ sku_code: 'SKU2', unit: '斤', sale_price: null, price: null },
],
});
installDb(state);
const summary = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' });
expect(summary.skipped).toBe(1);
expect(submit).not.toHaveBeenCalled();
expect(String(state.inserts[0].params[5])).toContain('no_pushable_items');
});
it('只推 >0 的行:零价行被过滤,但正价行照推', async () => {
const state = makeState({
items: [
{ sku_code: 'SKU1', unit: '斤', sale_price: '9', price: '9' },
{ sku_code: 'SKU2', unit: '斤', sale_price: '0', price: '0' },
],
});
installDb(state);
await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' });
const body = (submit.mock.calls[0][0] as any).body;
expect(body.items).toEqual([{ sku_code: 'SKU1', unit: '斤', sale_price: 9 }]);
});
it(`可推行超过 ${QUOTE_COST_SYNC_MAX_ITEMS} 条 ⇒ 整单 skipped(不做截断/分批)`, async () => {
const items = Array.from({ length: QUOTE_COST_SYNC_MAX_ITEMS + 1 }, (_, i) => ({
sku_code: `SKU${i}`,
unit: '斤',
sale_price: '1.00',
price: '1.00',
}));
const state = makeState({ items });
installDb(state);
const summary = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' });
expect(summary.skipped).toBe(1);
expect(submit).not.toHaveBeenCalled();
expect(String(state.inserts[0].params[5])).toContain('too_many_items');
});
it('报价单不存在 ⇒ skipped(不写台账)', async () => {
const state = makeState({ sheet: null });
installDb(state);
const summary = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' });
expect(summary.skipped).toBe(1);
expect(state.inserts).toHaveLength(0);
expect(submit).not.toHaveBeenCalled();
});
it('非生效单(已驳回 approval_status=40)⇒ skipped,零出站', async () => {
const state = makeState({
sheet: {
quote_sheet_code: 'QS1',
branch_code: 'BR002',
status: 0,
approval_status: 40,
approved_at: null,
effective_at: null,
expires_at: null,
},
});
installDb(state);
const summary = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' });
expect(summary.skipped).toBe(1);
expect(submit).not.toHaveBeenCalled();
expect(String(state.inserts[0].params[5])).toContain('quote_sheet_not_active');
});
it('没有主系统供应商编码 ⇒ 落 failed 等人工(不猜编码、不出站)', async () => {
const state = makeState({ supplierCode: null });
installDb(state);
const summary = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' });
expect(summary.failed).toBe(1);
expect(submit).not.toHaveBeenCalled();
expect(state.inserts[0].params[4]).toBe('failed');
expect(String(state.inserts[0].params[5])).toContain('main_supplier_code_missing');
});
});
/* ── ④ 回执 → 台账状态 ───────────────────────────────────────────────────── */
describe('出站结果映射', () => {
beforeEach(() => {
process.env.MAIN_SYSTEM_QUOTE_COST_SYNC = '1';
});
function lastUpdateStatus(state: DbState): string {
return String(state.updates[state.updates.length - 1]?.params[1]);
}
it('200 + replayed:true ⇒ sent(对方幂等命中也是同步成功)', async () => {
installDb(makeState());
submit.mockResolvedValue({
...okResult(),
data: { ...okResult().data, replayed: true, updated: 0 },
});
const summary = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' });
expect(summary.sent).toBe(1);
expect(summary.results[0].replayed).toBe(true);
});
it('403 branch_not_bound ⇒ forbidden(终态,不重试)', async () => {
const state = makeState();
installDb(state);
submit.mockResolvedValue({
kind: 'rejected',
status: 403,
code: 'branch_not_bound',
reason: '该供应商未绑定此分公司',
payload: { error: 'branch_not_bound' },
});
const summary = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' });
expect(summary.forbidden).toBe(1);
expect(lastUpdateStatus(state)).toBe('forbidden');
expect(String(state.updates[0].params[2])).toContain('branch_not_bound');
});
it('503 feature_disabled / 5xx / 网络 ⇒ failed(可重试)', async () => {
for (const outcome of [
{ kind: 'unavailable', status: 503, code: 'feature_disabled', reason: '对方开关未开', payload: null },
{ kind: 'unavailable', status: 500, code: 'main_system_error', reason: 'HTTP 500', payload: null },
{ kind: 'unavailable', status: 0, code: 'request_failed', reason: '调用主系统超时', payload: null },
]) {
const state = makeState();
installDb(state);
submit.mockResolvedValueOnce(outcome);
const summary = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' });
expect(summary.failed, JSON.stringify(outcome)).toBe(1);
expect(lastUpdateStatus(state)).toBe('failed');
expect(String(state.updates[0].params[2])).toContain(String((outcome as any).code));
}
});
it('出站层抛异常 ⇒ 台账收口成 failed(不留 pending)+ 不影响其它分公司', async () => {
const state = makeState({ customers: ['MAIN_BR002', 'MAIN_BR003'] });
installDb(state);
submit
.mockRejectedValueOnce(new Error('boom'))
.mockResolvedValueOnce(okResult());
const summary = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' });
expect(summary.failed).toBe(1);
expect(summary.sent).toBe(1);
expect(lastUpdateStatus(state)).toBe('sent');
// 第一行也必须被收口(不能停在 pending)
expect(state.updates[0].params[1]).toBe('failed');
expect(String(state.updates[0].params[2])).toContain('exception');
});
});
/* ── ⑤ 采集(plan)──────────────────────────────────────────────────────── */
describe('collectQuoteCostSyncPlan', () => {
beforeEach(() => {
process.env.MAIN_SYSTEM_QUOTE_COST_SYNC = '1';
});
it('跳过明细带 reason,主系统分公司去重升序', async () => {
installDb(
makeState({
customers: ['MAIN_BR003', 'MAIN_BR002', 'MAIN_BR002', 'CUS1', '__RETAIL__'],
items: [
{ sku_code: 'SKU1', unit: '斤', sale_price: '4.5', price: '4.5' },
{ sku_code: 'SKU2', unit: '斤', sale_price: '0', price: '0' },
{ sku_code: '', unit: '斤', sale_price: '5', price: '5' },
],
})
);
const plan = await collectQuoteCostSyncPlan({ branchCode: 'BR002', quoteSheetCode: 'QS1' });
expect(plan.mainBranchCodes).toEqual(['BR002', 'BR003']);
expect(plan.items).toEqual([{ sku_code: 'SKU1', unit: '斤', sale_price: 4.5 }]);
expect(plan.skipped).toEqual([
{ reason: 'not_usage_company', customer_code: 'CUS1' },
{ reason: 'not_usage_company', customer_code: '__RETAIL__' },
{ reason: 'source_price_missing', sku_code: 'SKU2' },
]);
expect(plan.itemRowCount).toBe(2); // 空 sku_code 不计入
expect(plan.isActive).toBe(true);
});
});
/* ── ⑥ 重试 ─────────────────────────────────────────────────────────────── */
describe('定时重试', () => {
beforeEach(() => {
process.env.MAIN_SYSTEM_QUOTE_COST_SYNC = '1';
});
it('只选 failed && attempts<5,复用原 client_request_id 重放', async () => {
const state = makeState({
retryRows: [
{
id: 'lid-9',
branch_code: 'BR002',
quote_sheet_code: 'QS1',
main_branch_code: 'BR002',
client_request_id: 'cr-original',
attempts: 2,
},
],
});
installDb(state);
const summary = await retryQuoteCostSyncPushes({ limit: 10 });
// SELECT 的 where/limit 就是重试口径(不是"所有历史行")
const selectSql = String(poolQuery.mock.calls[0][0]);
expect(selectSql).toContain("status = 'failed' AND attempts <");
expect(poolQuery.mock.calls[0][1]).toEqual([QUOTE_COST_SYNC_MAX_ATTEMPTS, 10]);
expect(summary.rows).toBe(1);
expect(summary.sent).toBe(1);
expect((submit.mock.calls[0][0] as any).body.client_request_id).toBe('cr-original');
expect((submit.mock.calls[0][0] as any).body.main_branch_code).toBe('BR002');
expect(String(state.updates[0].params[1])).toBe('sent');
expect(String(state.updates[0].params[3])).toContain('retried');
});
it('客户绑定被撤掉(目标分公司已不在 MAIN_ 里)⇒ skipped,零出站', async () => {
const state = makeState({
customers: ['MAIN_BR003'],
retryRows: [
{
id: 'lid-9',
branch_code: 'BR002',
quote_sheet_code: 'QS1',
main_branch_code: 'BR002',
client_request_id: 'cr-original',
attempts: 1,
},
],
});
installDb(state);
const summary = await retryQuoteCostSyncPushes();
expect(summary.skipped).toBe(1);
expect(submit).not.toHaveBeenCalled();
expect(String(state.updates[0].params[2])).toContain('main_branch_customer_removed');
});
it('重试遇 403 ⇒ forbidden(此后不再被选中)', async () => {
const state = makeState({
retryRows: [
{
id: 'lid-9',
branch_code: 'BR002',
quote_sheet_code: 'QS1',
main_branch_code: 'BR002',
client_request_id: 'cr-original',
attempts: 1,
},
],
});
installDb(state);
submit.mockResolvedValue({ kind: 'rejected', status: 403, code: 'branch_not_bound', reason: 'x', payload: null });
const summary = await retryQuoteCostSyncPushes();
expect(summary.forbidden).toBe(1);
expect(String(state.updates[0].params[1])).toBe('forbidden');
});
it('单行异常不影响其它行,且异常行 attempts 也 +1(防止无限重试)', async () => {
const state = makeState({
retryRows: [
{
id: 'lid-1',
branch_code: 'BR002',
quote_sheet_code: 'QS1',
main_branch_code: 'BR002',
client_request_id: 'cr-1',
attempts: 1,
},
{
id: 'lid-2',
branch_code: 'BR002',
quote_sheet_code: 'QS1',
main_branch_code: 'BR002',
client_request_id: 'cr-2',
attempts: 1,
},
],
});
installDb(state);
submit.mockRejectedValueOnce(new Error('boom')).mockResolvedValueOnce(okResult());
const summary = await retryQuoteCostSyncPushes();
expect(summary.errors).toBe(1);
expect(summary.sent).toBe(1);
const bump = state.updates.find((u) => String(u.params[1] ?? '').includes('retry_exception'));
expect(bump).toBeTruthy();
});
});
/* ── ⑥ tester 补充(2026-10-18):验收边界里原本没被钉住的形态 ─────────────────── */
describe('tester 补充:client 的 MAIN_BR007 不在 S(对方授权集合)', () => {
beforeEach(() => {
process.env.MAIN_SYSTEM_QUOTE_COST_SYNC = '1';
});
it('一单混绑 MAIN_BR002(已授权)+ MAIN_BR007(未授权)⇒ BR002 sent、BR007 forbidden,且 forbidden 不再重试', async () => {
const state = makeState({ customers: ['MAIN_BR002', 'MAIN_BR007'] });
installDb(state);
submit.mockImplementation(async (input: any) => {
if (input.body.main_branch_code === 'BR007') {
// 对方验收 A3/§1.3:该供应商未绑定 BR007 ⇒ 403 branch_not_bound(NOT `not_bound` skip)
return {
kind: 'rejected',
status: 403,
code: 'branch_not_bound',
reason: '供应商未绑定分公司 BR007',
payload: { error: 'branch_not_bound' },
};
}
return okResult();
});
const summary = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' });
expect(summary.sent).toBe(1);
expect(summary.forbidden).toBe(1);
expect(summary.failed).toBe(0);
// 两个分公司各自一行台账(唯一键是 (单号, 分公司),不是整单一行)
expect(state.inserts.map((i) => i.params[2])).toEqual(['BR002', 'BR007']);
// markLedger 的参数顺序是 (id, status, last_error, response) ⇒ 按出站顺序是 sent 然后 forbidden
expect(state.updates.map((u) => String(u.params[1]))).toEqual(['sent', 'forbidden']);
expect(String(state.updates[1].params[2])).toContain('branch_not_bound');
// 终态语义:`forbidden` 是终态,重试只选 `status='failed'`(重试口径由「定时重试」组钉住)
expect(summary.results.map((r) => r.status)).toEqual(['sent', 'forbidden']);
});
it('全部客户都非 MAIN_(含 `MAIN_*` 这种伪形态)⇒ 一条台账 skipped、零出站、零主系统分公司', async () => {
const state = makeState({ customers: ['MAIN_*', 'MAIN_BR 002', 'MAIN_A'.padEnd(40, 'A')] });
installDb(state);
const plan = await collectQuoteCostSyncPlan({ branchCode: 'BR002', quoteSheetCode: 'QS1' });
expect(plan.mainBranchCodes).toEqual([]);
expect(plan.skipped.filter((s) => s.reason === 'not_usage_company')).toHaveLength(3);
const summary = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' });
expect(summary.skipped).toBe(1);
expect(summary.attempted).toBe(0);
expect(submit).not.toHaveBeenCalled();
expect(state.inserts[0].params[2]).toBe('*');
});
});
describe('tester 补充:源金额口径(上限由接收端判)', () => {
beforeEach(() => {
process.env.MAIN_SYSTEM_QUOTE_COST_SYNC = '1';
});
it('超过 9,999,999.99 的源价**不在发送端丢弃**(对方按行记 invalid_price,口径单点维护)', async () => {
const state = makeState({
items: [
{ sku_code: 'SKU_BIG', unit: '斤', sale_price: '10000000', price: '10000000' },
{ sku_code: 'SKU_OK', unit: '斤', sale_price: '9.99', price: '9.99' },
],
});
installDb(state);
await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' });
const body = (submit.mock.calls[0][0] as any).body;
expect(body.items.map((i: any) => i.sku_code)).toEqual(['SKU_BIG', 'SKU_OK']);
expect(body.items[0].sale_price).toBe(10000000);
});
it('0 / 负数 / 非数字的源价行一律 source_price_missing(不兜底成 0 推送)', async () => {
const state = makeState({
items: [
{ sku_code: 'SKU_ZERO', unit: '斤', sale_price: '0', price: '0' },
{ sku_code: 'SKU_NEG', unit: '斤', sale_price: '-3', price: '-3' },
{ sku_code: 'SKU_NAN', unit: '斤', sale_price: 'abc', price: 'abc' },
],
});
installDb(state);
const plan = await collectQuoteCostSyncPlan({ branchCode: 'BR002', quoteSheetCode: 'QS1' });
expect(plan.items).toHaveLength(0);
expect(plan.skipped.filter((s) => s.reason === 'source_price_missing')).toHaveLength(3);
expect(submit).not.toHaveBeenCalled();
});
it('对方 409 idempotency_conflict ⇒(R-2 修正)轮换 client_request_id、attempts 归零,下一轮用新号', async () => {
const state = makeState();
installDb(state);
submit.mockResolvedValue({
kind: 'rejected',
status: 409,
code: 'idempotency_conflict',
reason: '同一 client_request_id 已用于不同内容',
payload: { error: 'idempotency_conflict' },
});
const summary = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' });
expect(summary.failed).toBe(1);
const row = state.ledger['QS1::BR002'];
expect(row.status).toBe('failed');
expect(row.attempts).toBe(0);
expect(row.last_error).toBe('payload_changed_rotate_id');
expect(row.client_request_id).not.toBe(state.inserts[0].params[3]); // 已换成新号
// 换号的 UPDATE 也把 409 原始原因留在台账里(排障)
expect(JSON.stringify(row.response)).toContain('idempotency_conflict');
});
});
/* ── ⑦ 红队 R-1 / R-2 修复(contract.md §7.3 / §7.4)──────────────────────────── */
describe('R-1:pending 卡死(进程在"台账已落、结果未回写"之间被杀)', () => {
beforeEach(() => {
process.env.MAIN_SYSTEM_QUOTE_COST_SYNC = '1';
});
it('卡住超过 10 分钟的 pending ⇒ 本轮扫描到,用**原 client_request_id** 重放并收口成 sent', async () => {
const state = makeState();
seedLedger(state, {
status: 'pending',
attempts: 0,
client_request_id: 'cr-pending-old',
response: null,
updated_at: Date.now() - 11 * 60 * 1000,
});
installDb(state);
submit.mockResolvedValueOnce(okResult());
const summary = await retryQuoteCostSyncPushes();
expect(summary.rows).toBe(1);
expect(summary.sent).toBe(1);
expect((submit.mock.calls[0][0] as any).body.client_request_id).toBe('cr-pending-old');
const row = state.ledger['QS1::BR002'];
expect(row.status).toBe('sent');
expect(row.attempts).toBe(1);
});
it('刚落下的 pending(未超 10 分钟)不抢跑(避免和正在飞的出站重复写)', async () => {
const state = makeState();
seedLedger(state, { status: 'pending', attempts: 0, client_request_id: 'cr-pending-fresh', updated_at: Date.now() });
installDb(state);
const summary = await retryQuoteCostSyncPushes();
expect(summary.rows).toBe(0);
expect(submit).not.toHaveBeenCalled();
});
it('重试 SQL 同时覆盖两类行(failed<5 / 卡住的 pending)', async () => {
const state = makeState();
installDb(state);
await retryQuoteCostSyncPushes();
const sql = String(poolQuery.mock.calls[0][0]);
expect(sql).toContain("status = 'failed' AND attempts <");
expect(sql).toContain("status = 'pending' AND updated_at < NOW() - INTERVAL '10 minutes'");
});
});
describe('R-2:改价后新价必须能同步过去', () => {
beforeEach(() => {
process.env.MAIN_SYSTEM_QUOTE_COST_SYNC = '1';
});
it('① 重试遇 409 ⇒ 换新号 + attempts 归零;下一轮用新号成功', async () => {
const state = makeState();
seedLedger(state, {
status: 'failed',
attempts: 2,
client_request_id: 'cr-old',
response: { local: { items_fingerprint: 'stale-fingerprint' } },
});
installDb(state);
submit.mockResolvedValueOnce({
kind: 'rejected',
status: 409,
code: 'idempotency_conflict',
reason: '同一 client_request_id 已用于不同内容',
payload: { error: 'idempotency_conflict' },
});
const first = await retryQuoteCostSyncPushes();
expect(first.failed).toBe(1);
const row = state.ledger['QS1::BR002'];
expect(row.status).toBe('failed');
expect(row.attempts).toBe(0);
expect(row.last_error).toBe('payload_changed_rotate_id');
expect(row.client_request_id).not.toBe('cr-old');
const newId = row.client_request_id;
// 下一轮:同一台账行已换成新号 ⇒ 成功
submit.mockResolvedValueOnce(okResult());
const second = await retryQuoteCostSyncPushes();
expect(second.sent).toBe(1);
expect((submit.mock.calls[1][0] as any).body.client_request_id).toBe(newId);
expect(state.ledger['QS1::BR002'].status).toBe('sent');
});
it('② 首推成功后改价 ⇒ 再触发真推出去(换新号,不是 duplicate)', async () => {
const state = makeState();
installDb(state);
const first = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' });
expect(first.sent).toBe(1);
const firstId = state.ledger['QS1::BR002'].client_request_id;
// 运营改了销售价(举例 12.34 → 99)
state.items = [{ sku_code: 'SKU1', unit: '斤', sale_price: '99.00', price: '99.00' }];
submit.mockClear();
submit.mockResolvedValueOnce(okResult());
const second = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' });
expect(second.duplicates).toBe(0);
expect(second.rearmed).toBe(1);
expect(second.sent).toBe(1);
const body = (submit.mock.calls[0][0] as any).body;
expect(body.items).toEqual([{ sku_code: 'SKU1', unit: '斤', sale_price: 99 }]);
expect(body.client_request_id).not.toBe(firstId);
const row = state.ledger['QS1::BR002'];
expect(row.response.local.sheet_reason).toBe('rearmed_after_change');
expect(row.status).toBe('sent');
expect(row.attempts).toBe(1);
});
it('③ 未改价 ⇒ 仍 duplicate、零出站、请求号不变', async () => {
const state = makeState();
installDb(state);
await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' });
const firstId = state.ledger['QS1::BR002'].client_request_id;
submit.mockClear();
const second = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' });
expect(second.duplicates).toBe(1);
expect(second.rearmed).toBe(0);
expect(second.attempted).toBe(0);
expect(submit).not.toHaveBeenCalled();
expect(state.ledger['QS1::BR002'].client_request_id).toBe(firstId);
});
it('非 409 的失败(5xx / 超时 / 网络)**仍复用同一请求号**(不得换号)', async () => {
const state = makeState();
seedLedger(state, { status: 'failed', attempts: 1, client_request_id: 'cr-keep' });
installDb(state);
submit.mockResolvedValueOnce({
kind: 'unavailable',
status: 500,
code: 'main_system_error',
reason: 'HTTP 500',
payload: null,
});
const summary = await retryQuoteCostSyncPushes();
expect(summary.failed).toBe(1);
expect((submit.mock.calls[0][0] as any).body.client_request_id).toBe('cr-keep');
const row = state.ledger['QS1::BR002'];
expect(row.client_request_id).toBe('cr-keep');
expect(row.status).toBe('failed');
expect(row.attempts).toBe(2);
});
});