Files
SupplierSystem/server/tests/quotePriceProposal.test.ts
T

1450 lines
57 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 冻结契约 + Lead 7 条 T 裁定)—— 服务层契约守卫。
*
* 钉住(做反就要返工):
* · 开关默认关 ⇒ 零出站、零写库(三个入口一律 503);
* · 方向 A:内部审核无在途 pending 才允许;整单提交调用 D1(出站),本地建 pending,**不写价**;
* T6:同 payload 同 hash ⇒ 回放;不同 hash ⇒ 旧 pending 置 `superseded`;
* · 方向 B:T2 按 `MAIN_<主系统分公司>` 解析**唯一生效单**(0 ⇒ no_quote_sheet,多 ⇒ ambiguous_sheet);
* **T3 只按行 UPDATE**(绝不整表 DELETE+INSERT,payload 只含 2 个 SKU 时其余 SKU 行必须原样保留);
* 缺行/单位不一致/金额非法 ⇒ 跳过并记录;值未变不写;
* · approve 后:**不再调用 `triggerQuoteCostSync`**(verifier 阻断项修正:由配送侧按 D3 `approved` 落地写价),只发 D3 回执;
* · 重复决策 ⇒ already_decided;驳回 ⇒ 不写价、零推送、D3 回执带理由;
* · T8:本地已终态、远端仍 pending ⇒ 下次 D2 轮询补发 D3;
* · T10:D2 带游标,用返回的 `next_cursor` 增量拉。
*/
/* ── mock:DB(脚本化,内存台账)──────────────────────────────────────────── */
const poolQuery = vi.hoisted(() => vi.fn());
const clientQuery = vi.hoisted(() => vi.fn());
const clientRelease = vi.hoisted(() => vi.fn());
vi.mock('../src/db', () => ({
pool: {
query: (...args: unknown[]) => poolQuery(...args),
connect: async () => ({
query: (...args: unknown[]) => clientQuery(...args),
release: () => clientRelease(),
}),
},
getRawPoolQuery: () => poolQuery,
}));
const tenantCtx = vi.hoisted(() => vi.fn());
vi.mock('../src/services/tenantDbContext', () => ({
runWithTenantDbContext: (...args: unknown[]) => tenantCtx(...args),
}));
// 报价单服务:方向 B 不再走 applyQuoteSheetUpdate(T3),只 mock 读取守卫;改为断言它从未被调用
const applyQuoteSheetUpdate = vi.hoisted(() => vi.fn());
const loadQuoteSheetForUpdate = vi.hoisted(() => vi.fn());
vi.mock('../src/services/quoteSheetService', async (importOriginal) => {
const actual = await importOriginal<typeof import('../src/services/quoteSheetService')>();
return {
...actual,
applyQuoteSheetUpdate: (...args: unknown[]) => applyQuoteSheetUpdate(...args),
loadQuoteSheetForUpdate: (...args: unknown[]) => loadQuoteSheetForUpdate(...args),
};
});
// 成本价同步:触发入口 + 供应商编码解析 mock;指纹算法用真实现
const triggerQuoteCostSync = vi.hoisted(() => vi.fn());
const resolveMainSupplierCode = vi.hoisted(() => vi.fn());
vi.mock('../src/services/mainSystemQuoteCostSync', async (importOriginal) => {
const actual = await importOriginal<typeof import('../src/services/mainSystemQuoteCostSync')>();
return {
...actual,
triggerQuoteCostSync: (...args: unknown[]) => triggerQuoteCostSync(...args),
resolveMainSupplierCode: (...args: unknown[]) => resolveMainSupplierCode(...args),
};
});
// 出站封装:D1/D2/D3 全 mock(零真网络)
const submitRemote = vi.hoisted(() => vi.fn());
const listRemote = vi.hoisted(() => vi.fn());
const decideRemote = vi.hoisted(() => vi.fn());
vi.mock('../src/services/mainSystem/api/quotePriceProposals', async (importOriginal) => {
const actual = await importOriginal<typeof import('../src/services/mainSystem/api/quotePriceProposals')>();
return {
...actual,
submitQuotePriceProposal: (...args: unknown[]) => submitRemote(...args),
listQuotePriceProposals: (...args: unknown[]) => listRemote(...args),
decideQuotePriceProposal: (...args: unknown[]) => decideRemote(...args),
};
});
const writeAuditLog = vi.hoisted(() => vi.fn());
vi.mock('../src/services/auditService', () => ({
writeAuditLog: (...args: unknown[]) => writeAuditLog(...args),
}));
import {
approvePriceProposal,
isQuotePriceProposalEnabled,
listPriceProposals,
rejectPriceProposal,
submitPriceProposal,
syncQuotePriceProposals,
resetQuotePriceProposalSyncCursor,
} from '../src/services/quotePriceProposalService';
/* ── 脚本化 DB ──────────────────────────────────────────────────────────── */
type LocalProposal = Record<string, any>;
type DbState = {
sheet: Record<string, any>;
sheetCustomers: string[];
items: Array<Record<string, any>>;
proposals: LocalProposal[];
changeRequests: Array<{ status: string }>;
activeSheets: string[];
bindings: Array<{ branch_code: string; main_branch_code: string; main_supplier_code: string }>;
sql: string[];
events: string[];
/** 模拟极端并发:INSERT 永远撞唯一键 */
forceInsertConflict?: boolean;
/** 模拟极端并发:查不到本地 pending(旧行刚被别的请求接管) */
forceNoPending?: boolean;
/** 本地 SKU 映射副本(默认恒等映射:配送 SKU = 我方 SKU,保证既有用例语义不变) */
mappings?: Array<{
supplier_sku_code: string;
supplier_sku_name: string | null;
supplier_unit: string | null;
delivery_sku_code: string | null;
delivery_sku_name: string | null;
status: string;
}>;
};
const SHEET = 'QS1';
const BRANCH = 'BR002';
const MAIN_BRANCH = 'BR002';
function makeState(overrides: Partial<DbState> = {}): DbState {
return {
sheet: {
quote_sheet_code: SHEET,
branch_code: BRANCH,
title: '报价单 V1',
version_no: 1,
status: 1,
approval_status: 30,
expires_at: new Date(Date.now() + 86400_000).toISOString(),
auto_sale_price_by_cost: false,
},
sheetCustomers: ['MAIN_BR002'],
items: [
{ id: 'item-1', sku_code: 'SKU1', sku_name: '草鱼', unit: '斤', sale_price: '10.00', price: '10.00', cost_price: '5.00', markup_ratio: null, sort_order: 0 },
{ id: 'item-2', sku_code: 'SKU2', sku_name: '鲤鱼', unit: '袋', sale_price: '20.00', price: '20.00', cost_price: '9.00', markup_ratio: null, sort_order: 1 },
{ id: 'item-3', sku_code: 'SKU3', sku_name: '鲫鱼', unit: '斤', sale_price: '30.00', price: '30.00', cost_price: '12.00', markup_ratio: null, sort_order: 2 },
],
proposals: [],
changeRequests: [],
activeSheets: [SHEET],
bindings: [{ branch_code: BRANCH, main_branch_code: MAIN_BRANCH, main_supplier_code: 'SUP1' }],
sql: [],
events: [],
mappings: [
{ supplier_sku_code: 'SKU1', supplier_sku_name: '草鱼', supplier_unit: '斤', delivery_sku_code: 'SKU1', delivery_sku_name: '草鱼', status: 'active' },
{ supplier_sku_code: 'SKU2', supplier_sku_name: '鲤鱼', supplier_unit: '袋', delivery_sku_code: 'SKU2', delivery_sku_name: '鲤鱼', status: 'active' },
{ supplier_sku_code: 'SKU3', supplier_sku_name: '鲫鱼', supplier_unit: '斤', delivery_sku_code: 'SKU3', delivery_sku_name: '鲫鱼', status: 'active' },
],
...overrides,
};
}
function seedLocalProposal(state: DbState, patch: LocalProposal = {}): LocalProposal {
const row: LocalProposal = {
id: patch.id ?? '11111111-1111-4111-8111-111111111111',
branch_code: patch.branch_code ?? BRANCH,
quote_sheet_code: patch.quote_sheet_code ?? SHEET,
main_branch_code: patch.main_branch_code ?? MAIN_BRANCH,
direction: patch.direction ?? 'from_delivery',
items: patch.items ?? [{ sku_code: 'SKU1', unit: '斤', price: 11 }],
payload_hash: patch.payload_hash ?? 'fp',
status: patch.status ?? 'pending',
reject_reason: patch.reject_reason ?? null,
client_request_id: patch.client_request_id ?? 'cr-local',
remote_proposal_id: patch.remote_proposal_id ?? 'remote-1',
requested_by: patch.requested_by ?? 'u1',
requested_by_name: patch.requested_by_name ?? '甲',
requested_at: patch.requested_at ?? '2026-10-18T01:00:00.000Z',
reviewed_by: patch.reviewed_by ?? null,
reviewed_by_name: patch.reviewed_by_name ?? null,
reviewed_at: patch.reviewed_at ?? null,
applied_at: patch.applied_at ?? null,
updated_at: patch.updated_at ?? '2026-10-18T01:00:00.000Z',
};
state.proposals.push(row);
return row;
}
function installDb(state: DbState): void {
const handler = async (sql: string, params: unknown[] = [], fromClient: boolean) => {
const text = String(sql);
state.sql.push(text);
if (/^\s*(BEGIN|COMMIT|ROLLBACK)\s*;?\s*$/i.test(text)) {
if (fromClient) state.events.push(text.trim().toUpperCase());
return { rows: [], rowCount: 0 };
}
// 生效单解析(T2)
if (text.includes('FROM customer_quote_sheets qs') && text.includes('EXISTS')) {
return { rows: state.activeSheets.map((quote_sheet_code) => ({ quote_sheet_code })) };
}
if (text.includes('FROM quote_price_proposals') && text.includes('WHERE id = $1::uuid')) {
const row = state.proposals.find((item) => item.id === String(params[0]));
return { rows: row ? [row] : [], rowCount: row ? 1 : 0 };
}
if (text.includes('FROM quote_price_proposals') && text.includes('FOR UPDATE')) {
state.events.push('PROPOSAL_LOCK');
const row = state.proposals.find((item) => item.id === String(params[0]));
return { rows: row ? [row] : [], rowCount: row ? 1 : 0 };
}
if (text.includes('FROM quote_price_proposals') && text.includes('remote_proposal_id = $1')) {
const row = state.proposals.find((item) => item.remote_proposal_id === String(params[0]));
return { rows: row ? [row] : [], rowCount: row ? 1 : 0 };
}
if (text.includes('FROM quote_price_proposals') && text.includes("status = 'pending'")) {
if (state.forceNoPending) return { rows: [], rowCount: 0 };
const row = state.proposals.find(
(item) =>
item.branch_code === params[0] &&
item.quote_sheet_code === params[1] &&
item.direction === params[2] &&
item.status === 'pending'
);
return { rows: row ? [row] : [], rowCount: row ? 1 : 0 };
}
if (text.includes('INSERT INTO quote_price_proposals')) {
state.events.push('PROPOSAL_INSERT');
if (text.includes('ON CONFLICT')) {
const direction = text.includes("'from_delivery'") ? 'from_delivery' : 'to_delivery';
if (state.forceInsertConflict) return { rows: [], rowCount: 0 };
const conflict = state.proposals.some(
(item) =>
item.branch_code === params[0] &&
item.quote_sheet_code === params[1] &&
item.direction === direction &&
item.status === 'pending'
);
if (conflict) return { rows: [], rowCount: 0 };
}
const row: LocalProposal = {
id: `local-${state.proposals.length + 1}`,
branch_code: params[0],
quote_sheet_code: params[1],
main_branch_code: params[2],
direction: text.includes("'from_delivery'") ? 'from_delivery' : 'to_delivery',
items: JSON.parse(String(params[3])),
payload_hash: params[4],
status: 'pending',
reject_reason: null,
client_request_id: params[5],
remote_proposal_id: params[6],
requested_by: params[7] ?? null,
requested_at: new Date().toISOString(),
reviewed_by: null,
reviewed_at: null,
applied_at: null,
updated_at: new Date().toISOString(),
};
state.proposals.push(row);
return { rows: [row], rowCount: 1 };
}
if (text.includes('UPDATE quote_price_proposals') && text.includes("SET status = 'superseded'")) {
state.events.push('PROPOSAL_SUPERSEDE');
if (text.includes('WHERE id = $1::uuid')) {
// 收口单行(sync:remote_superseded 是 SQL 字面量;replaced_by_remote 是参数 $2)
const row = state.proposals.find((item) => item.id === String(params[0]));
if (row) {
row.status = 'superseded';
if (text.includes("reject_reason = 'remote_superseded'")) row.reject_reason = 'remote_superseded';
else if (params[1]) row.reject_reason = params[1];
}
return { rows: [], rowCount: row ? 1 : 0 };
}
for (const row of state.proposals) {
if (
row.branch_code === params[0] &&
row.quote_sheet_code === params[1] &&
row.direction === 'to_delivery' &&
row.status === 'pending'
) {
row.status = 'superseded';
}
}
return { rows: [], rowCount: 1 };
}
if (text.includes('UPDATE quote_price_proposals') && text.includes("SET status = 'approved'")) {
state.events.push('PROPOSAL_APPROVED');
const row = state.proposals.find((item) => item.id === String(params[0]) && item.status === 'pending');
if (!row) return { rows: [], rowCount: 0 };
row.status = 'approved';
row.quote_sheet_code = params[1];
row.reviewed_by = params[2] ?? null;
row.applied_at = new Date().toISOString();
return { rows: [row], rowCount: 1 };
}
if (text.includes('UPDATE quote_price_proposals') && text.includes("SET status = 'rejected'")) {
state.events.push('PROPOSAL_REJECTED');
const row = state.proposals.find((item) => item.id === String(params[0]) && item.status === 'pending');
if (!row) return { rows: [], rowCount: 0 };
row.status = 'rejected';
row.reject_reason = params[1];
return { rows: [row], rowCount: 1 };
}
if (text.includes('UPDATE quote_price_proposals') && text.includes('SET status = $2::varchar')) {
state.events.push('PROPOSAL_SYNC_STATUS');
const row = state.proposals.find((item) => item.id === String(params[0]));
if (row) {
row.status = params[1];
if (params[2]) row.reject_reason = params[2];
}
return { rows: [], rowCount: row ? 1 : 0 };
}
if (text.includes('FROM main_system_sku_mappings') && text.includes('delivery_sku_code = $1')) {
const row = (state.mappings || []).find(
(item) => item.delivery_sku_code === String(params[0]) && item.status === 'active'
);
return { rows: row ? [row] : [], rowCount: row ? 1 : 0 };
}
if (text.includes('FROM main_system_sku_mappings') && text.includes('delivery_sku_code = ANY')) {
const list = new Set((params[0] as string[]) || []);
return { rows: (state.mappings || []).filter((item) => item.delivery_sku_code && list.has(item.delivery_sku_code)) };
}
if (text.includes('FROM main_system_sku_mappings') && text.includes('supplier_sku_code = ANY')) {
const list = new Set((params[0] as string[]) || []);
return { rows: (state.mappings || []).filter((item) => list.has(item.supplier_sku_code)) };
}
if (text.includes('FROM quote_price_proposals p')) {
return {
rows: state.proposals.map((row) => ({
...row,
requested_by_name: row.requested_by_name ?? '甲',
reviewed_by_name: row.reviewed_by_name ?? '',
})),
};
}
if (text.includes('FROM quote_sheet_change_requests')) {
return { rows: state.changeRequests, rowCount: state.changeRequests.length };
}
if (text.includes('FROM customer_quote_sheet_customers') && text.includes('ORDER BY customer_code')) {
return { rows: state.sheetCustomers.map((customer_code) => ({ customer_code })) };
}
if (text.includes('FROM customer_quote_sheet_customers')) {
return { rows: state.sheetCustomers.map((customer_code) => ({ customer_code, company_name: '客户' })) };
}
// T3:唯一写价语句
if (text.includes('UPDATE customer_quote_sheet_items') && text.includes('SET sale_price = $3, price = $3')) {
state.events.push('ITEM_UPDATE');
const row = state.items.find(
(item) => item.quote_sheet_code === params[0] || item.sku_code === params[1]
);
const target = state.items.find((item) => item.sku_code === String(params[1]));
if (!target) return { rows: [], rowCount: 0 };
target.sale_price = String(params[2]);
target.price = String(params[2]);
return { rows: [{ id: target.id }], rowCount: 1 };
}
if (text.includes('FROM customer_quote_sheet_items')) {
return {
rows: state.items.map((item) => ({ ...item, quote_sheet_code: item.quote_sheet_code ?? SHEET })),
rowCount: state.items.length,
};
}
if (text.includes('SELECT 1 FROM customer_quote_sheets')) {
return { rows: state.activeSheets.includes(String(params[0])) ? [{ 1: 1 }] : [] };
}
if (text.includes('FROM customer_quote_sheets')) {
return { rows: [state.sheet], rowCount: 1 };
}
if (text.includes('FROM public.main_supplier_bindings')) {
return { rows: state.bindings, rowCount: state.bindings.length };
}
return { rows: [], rowCount: 0 };
};
poolQuery.mockImplementation((sql: string, params?: unknown[]) => handler(sql, params || [], false));
clientQuery.mockImplementation((sql: string, params?: unknown[]) => handler(sql, params || [], true));
}
const okSubmit = (proposalId = 'remote-1') => ({
kind: 'ok' as const,
status: 200,
data: { proposal_id: proposalId, status: 'pending', replayed: false },
});
beforeEach(() => {
poolQuery.mockReset();
clientQuery.mockReset();
clientRelease.mockReset();
applyQuoteSheetUpdate.mockReset();
loadQuoteSheetForUpdate.mockReset();
triggerQuoteCostSync.mockReset();
resolveMainSupplierCode.mockReset();
submitRemote.mockReset();
listRemote.mockReset();
decideRemote.mockReset();
writeAuditLog.mockReset();
tenantCtx.mockReset();
tenantCtx.mockImplementation(async (_code: string, fn: () => Promise<unknown>) => fn());
resetQuotePriceProposalSyncCursor();
delete process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL;
loadQuoteSheetForUpdate.mockResolvedValue({
quote_sheet_code: SHEET,
branch_code: BRANCH,
version_no: 1,
status: 1,
approval_status: 30,
auto_sale_price_by_cost: false,
});
resolveMainSupplierCode.mockResolvedValue('SUP1');
submitRemote.mockResolvedValue(okSubmit());
// 默认:D2 精确查(带 proposalId)返回"该提议仍 pending";不带 id 的批量拉取返回空
listRemote.mockImplementation(async (input: any) => ({
kind: 'ok' as const,
status: 200,
rows: input?.proposalId
? [
{
proposal_id: String(input.proposalId),
direction: 'to_supplier',
status: 'pending',
supplier_quote_sheet_code: SHEET,
branch_code: MAIN_BRANCH,
items: [],
note: null,
reject_reason: null,
applied: null,
created_at: null,
reviewed_at: null,
},
]
: [],
summary: null,
nextCursor: null,
}));
decideRemote.mockResolvedValue({ kind: 'ok', status: 200 });
writeAuditLog.mockResolvedValue(undefined);
});
/* ── 开关 ───────────────────────────────────────────────────────────────── */
describe('开关(默认关)', () => {
it('未设置 / 0 / false ⇒ 关;1 / true / on ⇒ 开', () => {
expect(isQuotePriceProposalEnabled()).toBe(false);
for (const value of ['1', 'true', 'on', 'TRUE']) {
process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = value;
expect(isQuotePriceProposalEnabled(), value).toBe(true);
}
for (const value of ['0', 'false', 'off']) {
process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = value;
expect(isQuotePriceProposalEnabled(), value).toBe(false);
}
});
it('关 ⇒ 三个入口 503 feature_disabled,且零出站 / 零查库', async () => {
installDb(makeState());
await expect(submitPriceProposal({ quoteSheetCode: SHEET, ctx: { branchCode: BRANCH } as any })).rejects.toMatchObject({
status: 503,
code: 'feature_disabled',
});
await expect(
approvePriceProposal({ id: '11111111-1111-4111-8111-111111111111' })
).rejects.toMatchObject({ status: 503, code: 'feature_disabled' });
await expect(
rejectPriceProposal({ id: '11111111-1111-4111-8111-111111111111', reason: 'x' })
).rejects.toMatchObject({ status: 503, code: 'feature_disabled' });
const sync = await syncQuotePriceProposals();
expect(sync.pulled + sync.synced + sync.receipts + sync.errors).toBe(0);
expect(poolQuery).not.toHaveBeenCalled();
expect(submitRemote).not.toHaveBeenCalled();
expect(listRemote).not.toHaveBeenCalled();
});
});
/* ── 方向 A:发起 ───────────────────────────────────────────────────────── */
describe('方向 A:提交配送商审核(不写价)', () => {
beforeEach(() => {
process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1';
});
it('整单 items 调 D1、本地建 pending,**不写价**(applyQuoteSheetUpdate 从未被调用)', async () => {
const state = makeState();
installDb(state);
// 记录 D1 出站事件,用于断言"出站先于任何 BEGIN"(HTTP 必须在事务之外)
submitRemote.mockImplementationOnce(async () => {
state.events.push('D1_OUTBOUND');
return okSubmit();
});
const result = await submitPriceProposal({
quoteSheetCode: SHEET,
note: '请审核',
requestedBy: 'u1',
ctx: { branchCode: BRANCH, userId: 'u1', roles: ['operator'] } as any,
});
expect(result.applied).toBe(false);
expect(submitRemote).toHaveBeenCalledTimes(1);
const call = submitRemote.mock.calls[0][0] as any;
expect(call).toMatchObject({
supplierCode: 'SUP1',
supplierQuoteSheetCode: SHEET,
mainBranchCode: MAIN_BRANCH,
note: '请审核',
});
expect(call.items).toEqual([
{ sku_code: 'SKU1', unit: '斤', price: 10 },
{ sku_code: 'SKU2', unit: '袋', price: 20 },
{ sku_code: 'SKU3', unit: '斤', price: 30 },
]);
expect(state.proposals).toHaveLength(1);
expect(state.proposals[0]).toMatchObject({
direction: 'to_delivery',
status: 'pending',
remote_proposal_id: 'remote-1',
});
expect(applyQuoteSheetUpdate).not.toHaveBeenCalled();
expect(triggerQuoteCostSync).not.toHaveBeenCalled();
// 出站必须发生在落库事务之前(HTTP 永远在事务之外)
expect(state.events.indexOf('D1_OUTBOUND')).toBeGreaterThan(-1);
expect(state.events.indexOf('D1_OUTBOUND')).toBeLessThan(state.events.indexOf('BEGIN'));
});
it('没有 MAIN_ 客户 / 多个主系统分公司 ⇒ 400(不猜、不扇出)', async () => {
const none = makeState({ sheetCustomers: ['CUS1', '__RETAIL__'] });
installDb(none);
await expect(submitPriceProposal({ quoteSheetCode: SHEET, ctx: { branchCode: BRANCH } as any })).rejects.toMatchObject({
status: 400,
code: 'not_usage_company',
});
const many = makeState({ sheetCustomers: ['MAIN_BR002', 'MAIN_BR007'] });
installDb(many);
await expect(submitPriceProposal({ quoteSheetCode: SHEET, ctx: { branchCode: BRANCH } as any })).rejects.toMatchObject({
status: 400,
code: 'ambiguous_main_branch',
});
expect(submitRemote).not.toHaveBeenCalled();
});
it('T6:同 payload 再提交 ⇒ 回放(不重复出站),不同 payload ⇒ 旧 pending 置 superseded 再建新行', async () => {
const state = makeState();
installDb(state);
const first = await submitPriceProposal({ quoteSheetCode: SHEET, ctx: { branchCode: BRANCH } as any });
expect(first.replayed).toBe(false);
expect(submitRemote).toHaveBeenCalledTimes(1);
// 同 payload ⇒ 回放
const replay = await submitPriceProposal({ quoteSheetCode: SHEET, ctx: { branchCode: BRANCH } as any });
expect(replay.replayed).toBe(true);
expect(submitRemote).toHaveBeenCalledTimes(1);
expect(state.proposals).toHaveLength(1);
// 改价后再提交 ⇒ 旧行 superseded、新行 pending
state.items = state.items.map((item) =>
item.sku_code === 'SKU1' ? { ...item, sale_price: '11.00', price: '11.00' } : item
);
submitRemote.mockResolvedValueOnce(okSubmit('remote-2'));
const second = await submitPriceProposal({ quoteSheetCode: SHEET, ctx: { branchCode: BRANCH } as any });
expect(second.replayed).toBe(false);
expect(state.events).toContain('PROPOSAL_SUPERSEDE');
expect(state.proposals.filter((row) => row.status === 'superseded')).toHaveLength(1);
expect(state.proposals.filter((row) => row.status === 'pending')).toHaveLength(1);
expect(state.proposals.find((row) => row.status === 'pending')!.remote_proposal_id).toBe('remote-2');
});
it('D1 失败 ⇒ 抛错且不落本地行(旧 pending 不动)', async () => {
const state = makeState();
installDb(state);
submitRemote.mockResolvedValueOnce({
kind: 'unavailable',
status: 502,
code: 'main_system_error',
reason: '对方不可用',
payload: null,
});
await expect(submitPriceProposal({ quoteSheetCode: SHEET, ctx: { branchCode: BRANCH } as any })).rejects.toMatchObject({
status: 502,
code: 'main_system_error',
});
expect(state.proposals).toHaveLength(0);
});
});
/* ── 同步(D2):A 结果 + B 拉取 + T8 回执重试 + T10 游标 ─────────────── */
describe('同步 D2', () => {
beforeEach(() => {
process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1';
});
it('方向 A 的结果(from_supplier approved)⇒ 回写本地状态', async () => {
const state = makeState();
seedLocalProposal(state, {
id: 'local-a',
direction: 'to_delivery',
status: 'pending',
remote_proposal_id: 'remote-a',
});
installDb(state);
listRemote.mockResolvedValueOnce({
kind: 'ok',
status: 200,
rows: [
{
proposal_id: 'remote-a',
direction: 'from_supplier',
status: 'approved',
supplier_quote_sheet_code: SHEET,
branch_code: MAIN_BRANCH,
items: [],
note: null,
reject_reason: null,
applied: { updated: 0, skipped: [] },
created_at: null,
reviewed_at: '2026-10-18T02:00:00.000Z',
},
],
summary: null,
nextCursor: 'cursor-1',
});
const summary = await syncQuotePriceProposals();
expect(summary.synced).toBe(1);
expect(state.proposals[0].status).toBe('approved');
});
it('T2:方向 B(to_supplier pending)拉回时按 MAIN_ 解析生效单并建本地 pending', async () => {
const state = makeState();
installDb(state);
listRemote.mockResolvedValueOnce({
kind: 'ok',
status: 200,
rows: [
{
proposal_id: 'remote-b',
direction: 'to_supplier',
status: 'pending',
supplier_quote_sheet_code: '',
branch_code: MAIN_BRANCH,
items: [
{ sku_code: 'SKU1', unit: '斤', price: 12 },
{ sku_code: 'SKU9', unit: '斤', price: 8 },
],
note: '成本上调',
reject_reason: null,
applied: null,
created_at: null,
reviewed_at: null,
},
],
summary: null,
nextCursor: null,
});
const summary = await syncQuotePriceProposals();
expect(summary.pulled).toBe(1);
const row = state.proposals.find((item) => item.direction === 'from_delivery')!;
expect(row).toMatchObject({ quote_sheet_code: SHEET, status: 'pending', remote_proposal_id: 'remote-b' });
expect(row.items).toEqual([
{ sku_code: 'SKU1', unit: '斤', price: 12 },
{ sku_code: 'SKU9', unit: '斤', price: 8 },
]);
});
it('T2:MAIN_ 对应多张生效单 ⇒ 不猜、不落行(跳过并告警)', async () => {
const state = makeState({ activeSheets: ['QS1', 'QS2'] });
installDb(state);
listRemote.mockResolvedValueOnce({
kind: 'ok',
status: 200,
rows: [
{
proposal_id: 'remote-b2',
direction: 'to_supplier',
status: 'pending',
supplier_quote_sheet_code: '',
branch_code: MAIN_BRANCH,
items: [{ sku_code: 'SKU1', unit: '斤', price: 12 }],
note: null,
reject_reason: null,
applied: null,
created_at: null,
reviewed_at: null,
},
],
summary: null,
nextCursor: null,
});
const summary = await syncQuotePriceProposals();
expect(summary.pulled).toBe(0);
expect(state.proposals).toHaveLength(0);
expect(summary.skipped).toBe(1);
});
it('T8:本地已终态、远端仍 pending ⇒ 补发 D3(幂等)', async () => {
const state = makeState();
seedLocalProposal(state, {
direction: 'from_delivery',
status: 'approved',
remote_proposal_id: 'remote-c',
});
installDb(state);
listRemote.mockResolvedValueOnce({
kind: 'ok',
status: 200,
rows: [
{
proposal_id: 'remote-c',
direction: 'to_supplier',
status: 'pending',
supplier_quote_sheet_code: SHEET,
branch_code: MAIN_BRANCH,
items: [],
note: null,
reject_reason: null,
applied: null,
created_at: null,
reviewed_at: null,
},
],
summary: null,
nextCursor: null,
});
const summary = await syncQuotePriceProposals();
expect(summary.receipts).toBe(1);
expect(decideRemote).toHaveBeenCalledWith(
expect.objectContaining({ proposalId: 'remote-c', decision: 'approved' })
);
});
it('T10:第二轮带上服务端返回的 next_cursor 增量拉取', async () => {
const state = makeState();
installDb(state);
listRemote
.mockResolvedValueOnce({ kind: 'ok', status: 200, rows: [], summary: null, nextCursor: 'c1' })
.mockResolvedValueOnce({ kind: 'ok', status: 200, rows: [], summary: null, nextCursor: 'c2' });
await syncQuotePriceProposals();
await syncQuotePriceProposals();
expect((listRemote.mock.calls[0][0] as any).cursor).toBeNull();
expect((listRemote.mock.calls[1][0] as any).cursor).toBe('c1');
});
});
/* ── 方向 B:审批(T3 按行 UPDATE)──────────────────────────────────────── */
describe('方向 B:approve 只按行 UPDATE(T3)', () => {
beforeEach(() => {
process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1';
});
it('payload 只含 2 个 SKU ⇒ 只更新这 2 行,第三行原样保留(无 DELETE / 无 INSERT / 不整表替换)', async () => {
const state = makeState();
seedLocalProposal(state, {
items: [
{ sku_code: 'SKU1', unit: '斤', price: 11 },
{ sku_code: 'SKU2', unit: '袋', price: 21 },
],
});
installDb(state);
const result = await approvePriceProposal({
id: '11111111-1111-4111-8111-111111111111',
ctx: { branchCode: BRANCH, userId: 'u2', roles: ['admin'] } as any,
reviewedBy: 'u2',
});
expect(result.applied.updated).toBe(2);
expect(result.applied.skipped).toEqual([]);
// 只对 payload 的 SKU 发 UPDATE(2 条),第 3 个 SKU 没被碰
const itemUpdates = state.sql.filter((sql) => sql.includes('SET sale_price = $3, price = $3'));
expect(itemUpdates).toHaveLength(2);
expect(state.events.filter((event) => event === 'ITEM_UPDATE')).toHaveLength(2);
// 绝不整表替换
expect(state.sql.some((sql) => /DELETE\s+FROM\s+customer_quote_sheet_items/i.test(sql))).toBe(false);
expect(state.sql.some((sql) => /INSERT\s+INTO\s+customer_quote_sheet_items/i.test(sql))).toBe(false);
expect(applyQuoteSheetUpdate).not.toHaveBeenCalled();
// 第三行未被修改
expect(state.items.find((item) => item.sku_code === 'SKU3')!.sale_price).toBe('30.00');
expect(state.items.find((item) => item.sku_code === 'SKU1')!.sale_price).toBe('11');
});
it('写价后:COMMIT 早于 D3 回执;**不再出站旧成本同步通道**;本地置 approved', async () => {
const state = makeState();
seedLocalProposal(state, { items: [{ sku_code: 'SKU1', unit: '斤', price: 11 }] });
installDb(state);
const order: string[] = [];
triggerQuoteCostSync.mockImplementation(() => order.push('trigger'));
decideRemote.mockImplementation(async () => {
order.push('d3');
return { kind: 'ok', status: 200 };
});
const result = await approvePriceProposal({
id: '11111111-1111-4111-8111-111111111111',
ctx: { branchCode: BRANCH, userId: 'u2', roles: ['admin'] } as any,
reviewedBy: 'u2',
});
expect(state.events.indexOf('COMMIT')).toBeGreaterThan(-1);
// verifier 阻断项:B 审批不再走旧通道(旧通道按 sku_code 直猜且跳过共享单,配送 cost_price 会静默不变)
expect(order).toEqual(['d3']);
expect(triggerQuoteCostSync).not.toHaveBeenCalled();
expect(result.receiptSent).toBe(true);
expect(state.proposals[0].status).toBe('approved');
expect(decideRemote).toHaveBeenCalledWith(
expect.objectContaining({ proposalId: 'remote-1', decision: 'approved' })
);
// 每行一条审计(best-effort,提交后写)
await new Promise((resolve) => setTimeout(resolve, 0));
expect(writeAuditLog).toHaveBeenCalled();
expect((writeAuditLog.mock.calls[0][0] as any).operationType).toBe('quote_price_proposal_apply');
});
it('未映射 ⇒ sku_unmapped;单位不一致 ⇒ unit_mismatch;金额非法 ⇒ invalid_price', async () => {
const state = makeState();
seedLocalProposal(state, {
items: [
{ sku_code: 'SKU1', unit: '袋', price: 11 }, // 单里 SKU1 是「斤」⇒ unit_mismatch
{ sku_code: 'SKU9', unit: '斤', price: 9 }, // 单里没有 ⇒ sku_not_in_sheet
{ sku_code: 'SKU3', unit: '斤', price: 0 }, // 金额非法 ⇒ invalid_price
],
});
installDb(state);
const result = await approvePriceProposal({
id: '11111111-1111-4111-8111-111111111111',
ctx: { branchCode: BRANCH } as any,
});
expect(result.applied.updated).toBe(0);
expect(result.applied.skipped).toEqual(
expect.arrayContaining([
{ sku_code: 'SKU1', reason: 'unit_mismatch', detail: '袋 vs 斤' },
{ sku_code: 'SKU9', reason: 'sku_unmapped' },
{ sku_code: 'SKU3', reason: 'invalid_price' },
])
);
expect(state.events).not.toContain('ITEM_UPDATE');
});
it('值未变 ⇒ 不写 UPDATE(计入 unchanged)', async () => {
const state = makeState();
seedLocalProposal(state, { items: [{ sku_code: 'SKU1', unit: '斤', price: 10 }] });
installDb(state);
const result = await approvePriceProposal({
id: '11111111-1111-4111-8111-111111111111',
ctx: { branchCode: BRANCH } as any,
});
expect(result.applied.updated).toBe(0);
expect(result.applied.unchanged).toBe(1);
expect(state.events).not.toContain('ITEM_UPDATE');
// 状态仍要推进(T9:零写入也是 approved);但**不**再触发旧成本同步通道
expect(state.proposals[0].status).toBe('approved');
expect(triggerQuoteCostSync).not.toHaveBeenCalled();
});
it('T2:目标单 0 张 ⇒ 409 no_quote_sheet;多张 ⇒ 409 ambiguous_sheet', async () => {
const none = makeState({ activeSheets: [] });
seedLocalProposal(none, {});
installDb(none);
await expect(
approvePriceProposal({ id: '11111111-1111-4111-8111-111111111111', ctx: { branchCode: BRANCH } as any })
).rejects.toMatchObject({ status: 409, code: 'no_quote_sheet' });
const many = makeState({ activeSheets: ['QS1', 'QS2'] });
seedLocalProposal(many, {});
installDb(many);
await expect(
approvePriceProposal({ id: '11111111-1111-4111-8111-111111111111', ctx: { branchCode: BRANCH } as any })
).rejects.toMatchObject({ status: 409, code: 'ambiguous_sheet' });
});
it('重复决策 ⇒ 409 already_decided;错误方向 ⇒ 400 wrong_direction', async () => {
const decided = makeState();
seedLocalProposal(decided, { status: 'approved' });
installDb(decided);
await expect(
approvePriceProposal({ id: '11111111-1111-4111-8111-111111111111', ctx: { branchCode: BRANCH } as any })
).rejects.toMatchObject({ status: 409, code: 'already_decided' });
const toDelivery = makeState();
seedLocalProposal(toDelivery, { direction: 'to_delivery' });
installDb(toDelivery);
await expect(
approvePriceProposal({ id: '11111111-1111-4111-8111-111111111111', ctx: { branchCode: BRANCH } as any })
).rejects.toMatchObject({ status: 400, code: 'wrong_direction' });
});
});
describe('方向 B:reject', () => {
beforeEach(() => {
process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1';
});
it('驳回 ⇒ 不写价、零推送、D3 回执 rejected + 理由', async () => {
const state = makeState();
seedLocalProposal(state, {});
installDb(state);
const result = await rejectPriceProposal({
id: '11111111-1111-4111-8111-111111111111',
reason: '成本谈不拢',
ctx: { branchCode: BRANCH, userId: 'u2', roles: ['admin'] } as any,
reviewedBy: 'u2',
});
expect(result.proposal.status).toBe('rejected');
expect(state.events).not.toContain('ITEM_UPDATE');
expect(applyQuoteSheetUpdate).not.toHaveBeenCalled();
expect(triggerQuoteCostSync).not.toHaveBeenCalled();
expect(decideRemote).toHaveBeenCalledWith(
expect.objectContaining({ decision: 'rejected', reason: '成本谈不拢' })
);
});
it('驳回必须给理由(400 reject_reason_required)', async () => {
installDb(makeState());
await expect(
rejectPriceProposal({ id: '11111111-1111-4111-8111-111111111111', reason: ' ', ctx: { branchCode: BRANCH } as any })
).rejects.toMatchObject({ status: 400, code: 'reject_reason_required' });
});
});
/* ── 列表 ──────────────────────────────────────────────────────────────── */
describe('列表', () => {
beforeEach(() => {
process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1';
});
it('返回本地行 + 提交人;pending 的 B 行带「改前 → 改后」与等待天数', async () => {
const state = makeState();
seedLocalProposal(state, {
direction: 'from_delivery',
items: [{ sku_code: 'SKU1', unit: '斤', price: 11 }],
requested_at: new Date(Date.now() - 3 * 86400000).toISOString(),
});
installDb(state);
const { rows } = await listPriceProposals({ branchCode: BRANCH, status: 'pending' });
expect(rows).toHaveLength(1);
expect(rows[0].requested_by_name).toBe('甲');
expect(rows[0].waited_days).toBe(3);
expect(rows[0].lines?.[0]).toMatchObject({
sku_code: 'SKU1',
before_sale_price: 10,
after_sale_price: 11,
change: 'updated',
});
});
});
/* ── ⑩ verifier 阻断项(A16/T6 交叉):远端 superseded / 旧 id / 冲突接管 / D3 带 applied ─── */
describe('A16/T6 交叉:远端 superseded 必须收口本地 pending', () => {
beforeEach(() => {
process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1';
});
const remoteRow = (over: Record<string, unknown>) => ({
proposal_id: 'remote-old',
direction: 'to_supplier',
status: 'superseded',
supplier_quote_sheet_code: SHEET,
branch_code: MAIN_BRANCH,
items: [{ sku_code: 'SKU1', unit: '斤', price: 11 }],
note: null,
reject_reason: null,
applied: null,
created_at: null,
reviewed_at: null,
...over,
});
it('一轮内「旧 id=superseded + 新 id=pending」⇒ 本地旧 pending 变 superseded、新 pending 落库', async () => {
const state = makeState();
seedLocalProposal(state, {
id: 'local-old',
direction: 'from_delivery',
status: 'pending',
remote_proposal_id: 'remote-old',
items: [{ sku_code: 'SKU1', unit: '斤', price: 11 }],
});
installDb(state);
listRemote.mockResolvedValueOnce({
kind: 'ok',
status: 200,
rows: [
remoteRow({ proposal_id: 'remote-old', status: 'superseded' }),
remoteRow({ proposal_id: 'remote-new', status: 'pending', supplier_quote_sheet_code: '', items: [{ sku_code: 'SKU1', unit: '斤', price: 13 }] }),
],
summary: null,
nextCursor: null,
});
const summary = await syncQuotePriceProposals();
const oldRow = state.proposals.find((row) => row.id === 'local-old')!;
expect(oldRow.status).toBe('superseded'); // 不再卡在 pending
expect(oldRow.reject_reason).toBe('remote_superseded');
const newRow = state.proposals.find((row) => row.remote_proposal_id === 'remote-new');
expect(newRow, '新远端 pending 必须落本地(不能 DO NOTHING 静默丢)').toBeTruthy();
expect(newRow!.status).toBe('pending');
expect(newRow!.remote_proposal_id).toBe('remote-new');
expect(summary.pulled).toBe(1);
expect(summary.synced).toBe(1);
});
it('旧 id 已 superseded + 新 pending 撞本地部分唯一键 ⇒ 旧行被接管(reason=replaced_by_remote)后新行插入', async () => {
const state = makeState();
// 旧本地 pending 的 remote id 与远端新提议不同,但远端本轮只返回新 pending(旧行还没收到 superseded 通知)
seedLocalProposal(state, {
id: 'local-old',
direction: 'from_delivery',
status: 'pending',
remote_proposal_id: 'remote-old',
});
installDb(state);
listRemote.mockResolvedValueOnce({
kind: 'ok',
status: 200,
rows: [remoteRow({ proposal_id: 'remote-new', status: 'pending', supplier_quote_sheet_code: '' })],
summary: null,
nextCursor: null,
});
await syncQuotePriceProposals();
const oldRow = state.proposals.find((row) => row.id === 'local-old')!;
expect(oldRow.status).toBe('superseded');
expect(oldRow.reject_reason).toBe('replaced_by_remote:remote-new');
expect(state.proposals.find((row) => row.remote_proposal_id === 'remote-new')!.status).toBe('pending');
});
it('同一远端 id 再拉一次 ⇒ 幂等跳过(不重复插、不动已有行)', async () => {
const state = makeState();
seedLocalProposal(state, { id: 'local-old', direction: 'from_delivery', remote_proposal_id: 'remote-old' });
installDb(state);
listRemote.mockResolvedValue({
kind: 'ok',
status: 200,
rows: [remoteRow({ proposal_id: 'remote-old', status: 'pending' })],
summary: null,
nextCursor: null,
});
await syncQuotePriceProposals();
await syncQuotePriceProposals();
expect(state.proposals.filter((row) => row.direction === 'from_delivery')).toHaveLength(1);
expect(state.proposals[0].status).toBe('pending');
});
});
describe('A16:旧 id approve 必须被拒(不能写已撤回的价)', () => {
beforeEach(() => {
process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1';
});
it('本地仍 pending 但远端已 superseded ⇒ 409 proposal_not_pending,零写价、零推送、零回执', async () => {
const state = makeState();
seedLocalProposal(state, {
direction: 'from_delivery',
status: 'pending',
remote_proposal_id: 'remote-old',
items: [{ sku_code: 'SKU1', unit: '斤', price: 11 }],
});
installDb(state);
listRemote.mockResolvedValueOnce({
kind: 'ok',
status: 200,
rows: [
{
proposal_id: 'remote-old',
direction: 'to_supplier',
status: 'superseded',
supplier_quote_sheet_code: SHEET,
branch_code: MAIN_BRANCH,
items: [],
note: null,
reject_reason: null,
applied: null,
created_at: null,
reviewed_at: null,
},
],
summary: null,
nextCursor: null,
});
await expect(
approvePriceProposal({
id: '11111111-1111-4111-8111-111111111111',
ctx: { branchCode: BRANCH, userId: 'u2', roles: ['admin'] } as any,
})
).rejects.toMatchObject({ status: 409, code: 'proposal_not_pending' });
expect(state.events).not.toContain('ITEM_UPDATE');
expect(applyQuoteSheetUpdate).not.toHaveBeenCalled();
expect(triggerQuoteCostSync).not.toHaveBeenCalled();
expect(decideRemote).not.toHaveBeenCalled();
expect(state.proposals[0].status).toBe('pending'); // 本地行未变(留给下一轮同步收口)
});
it('无法确认远端状态(D2 不可用)⇒ 409 remote_status_unverified(失败关闭,不写价)', async () => {
const state = makeState();
seedLocalProposal(state, { direction: 'from_delivery', status: 'pending', remote_proposal_id: 'remote-old' });
installDb(state);
listRemote.mockResolvedValueOnce({
kind: 'unavailable',
status: 502,
code: 'main_system_error',
reason: '对方不可用',
payload: null,
});
await expect(
approvePriceProposal({ id: '11111111-1111-4111-8111-111111111111', ctx: { branchCode: BRANCH } as any })
).rejects.toMatchObject({ status: 409, code: 'remote_status_unverified' });
expect(state.events).not.toContain('ITEM_UPDATE');
expect(triggerQuoteCostSync).not.toHaveBeenCalled();
});
});
describe('A20:D3 回执必须带 applied(写价统计)', () => {
beforeEach(() => {
process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1';
});
it('新 id approve 正常写价 + rearm 推送,且 D3 body 带 applied', async () => {
const state = makeState();
seedLocalProposal(state, {
direction: 'from_delivery',
status: 'pending',
remote_proposal_id: 'remote-new',
items: [
{ sku_code: 'SKU1', unit: '斤', price: 11 },
{ sku_code: 'SKU9', unit: '斤', price: 9 },
],
});
installDb(state);
// 远端仍是 pending ⇒ 预检通过
listRemote.mockResolvedValueOnce({
kind: 'ok',
status: 200,
rows: [
{
proposal_id: 'remote-new',
direction: 'to_supplier',
status: 'pending',
supplier_quote_sheet_code: SHEET,
branch_code: MAIN_BRANCH,
items: [],
note: null,
reject_reason: null,
applied: null,
created_at: null,
reviewed_at: null,
},
],
summary: null,
nextCursor: null,
});
const result = await approvePriceProposal({
id: '11111111-1111-4111-8111-111111111111',
ctx: { branchCode: BRANCH, userId: 'u2', roles: ['admin'] } as any,
reviewedBy: 'u2',
});
expect(result.applied.updated).toBe(1);
expect(result.applied.skipped).toEqual([
{ sku_code: 'SKU9', reason: 'sku_unmapped' },
]);
const d3 = decideRemote.mock.calls.find(([arg]) => (arg as any).decision === 'approved');
expect(d3, '通过必须回执').toBeTruthy();
expect((d3![0] as any).applied).toEqual({
updated: 1,
skipped: [{ sku_code: 'SKU9', reason: 'sku_unmapped' }],
});
// 配送侧按 D3 落地写价;本侧不再推旧通道
expect(triggerQuoteCostSync).not.toHaveBeenCalled();
});
});
/* ── ⑪ verifier 第二轮:预检精确查 + 翻页兜底 + 失败关闭 + 接管不丢数据 ──────────── */
describe('A16 残余:旧 id 预检必须精确查 / 翻页兜底 / 失败关闭', () => {
beforeEach(() => {
process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1';
});
const decidedRemote = (id: string, status: string) => ({
proposal_id: id,
direction: 'to_supplier',
status,
supplier_quote_sheet_code: SHEET,
branch_code: MAIN_BRANCH,
items: [],
note: null,
reject_reason: null,
applied: null,
created_at: null,
reviewed_at: null,
});
it('先按 proposal_id 精确查(一次命中即通过,不多拉 200 行)', async () => {
const state = makeState();
seedLocalProposal(state, { direction: 'from_delivery', status: 'pending', remote_proposal_id: 'remote-xyz' });
installDb(state);
listRemote.mockClear();
await approvePriceProposal({
id: '11111111-1111-4111-8111-111111111111',
ctx: { branchCode: BRANCH, userId: 'u2', roles: ['admin'] } as any,
});
expect(listRemote).toHaveBeenCalledTimes(1);
expect((listRemote.mock.calls[0][0] as any).proposalId).toBe('remote-xyz');
expect(state.items.find((item) => item.sku_code === 'SKU1')!.sale_price).toBe('11');
});
it('>200 行(旧行不在第一页)⇒ 翻页找到 superseded 后 409 proposal_not_pending,零写价零推送', async () => {
const state = makeState();
seedLocalProposal(state, {
direction: 'from_delivery',
status: 'pending',
remote_proposal_id: 'remote-old',
items: [{ sku_code: 'SKU1', unit: '斤', price: 11 }],
});
installDb(state);
const filler = (n: number) => Array.from({ length: n }, (_, i) => decidedRemote(`filler-${i}`, 'approved'));
// 精确查不支持/未命中 ⇒ 返回最旧 200 行 + 下一页游标;目标行在第 2 页(superseded)
listRemote
.mockResolvedValueOnce({ kind: 'ok', status: 200, rows: filler(200), summary: null, nextCursor: 'p2' })
.mockResolvedValueOnce({
kind: 'ok',
status: 200,
rows: [decidedRemote('remote-old', 'superseded')],
summary: null,
nextCursor: null,
});
await expect(
approvePriceProposal({ id: '11111111-1111-4111-8111-111111111111', ctx: { branchCode: BRANCH } as any })
).rejects.toMatchObject({ status: 409, code: 'proposal_not_pending' });
expect(listRemote).toHaveBeenCalledTimes(2);
expect((listRemote.mock.calls[1][0] as any).cursor).toBe('p2');
expect(state.events).not.toContain('ITEM_UPDATE');
expect(applyQuoteSheetUpdate).not.toHaveBeenCalled();
expect(triggerQuoteCostSync).not.toHaveBeenCalled();
expect(decideRemote).not.toHaveBeenCalled();
expect(state.proposals[0].status).toBe('pending'); // 本地行留给下一轮 D2 收口
});
it('翻页耗尽仍找不到该提议 ⇒ 409 remote_status_unverified(失败关闭,绝不放行)', async () => {
const state = makeState();
seedLocalProposal(state, { direction: 'from_delivery', status: 'pending', remote_proposal_id: 'remote-old' });
installDb(state);
listRemote
.mockResolvedValueOnce({
kind: 'ok',
status: 200,
rows: [decidedRemote('other-1', 'pending')],
summary: null,
nextCursor: 'p2',
})
.mockResolvedValueOnce({
kind: 'ok',
status: 200,
rows: [decidedRemote('other-2', 'pending')],
summary: null,
nextCursor: null,
});
await expect(
approvePriceProposal({ id: '11111111-1111-4111-8111-111111111111', ctx: { branchCode: BRANCH } as any })
).rejects.toMatchObject({ status: 409, code: 'remote_status_unverified' });
expect(state.events).not.toContain('ITEM_UPDATE');
expect(triggerQuoteCostSync).not.toHaveBeenCalled();
});
});
describe('A16 残余:接管循环不再静默丢新提议', () => {
beforeEach(() => {
process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1';
});
it('极端并发:接管耗尽 ⇒ 记 errors + 重置游标(下轮全量重拉),不返回 skipped 吞掉', async () => {
const state = makeState({ forceInsertConflict: true, forceNoPending: true });
installDb(state);
listRemote.mockResolvedValue({
kind: 'ok',
status: 200,
rows: [
{
proposal_id: 'remote-new',
direction: 'to_supplier',
status: 'pending',
supplier_quote_sheet_code: '',
branch_code: MAIN_BRANCH,
items: [{ sku_code: 'SKU1', unit: '斤', price: 12 }],
note: null,
reject_reason: null,
applied: null,
created_at: null,
reviewed_at: null,
},
],
summary: null,
nextCursor: 'c1',
});
const summary = await syncQuotePriceProposals();
expect(summary.errors).toBe(1);
expect(summary.pulled).toBe(0);
// 游标应已重置 ⇒ 下一轮从 cursor=null 全量重拉(新提议不会因"游标已过"而丢)
listRemote.mockClear();
await syncQuotePriceProposals();
expect((listRemote.mock.calls[0][0] as any).cursor).toBeNull();
});
});
/* ── ⑫ SKU 映射(2026-10-18 增量):方向 B 必须经映射反查,不按 sku_code 猜 ─────────── */
describe('SKU 映射:方向 B 用配送 SKU 反查我方 SKU', () => {
beforeEach(() => {
process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1';
});
it('配送 SKU 与我方 SKU 不同 ⇒ 通过映射写到我方行(不按 sku_code 猜)', async () => {
const state = makeState({
mappings: [
{ supplier_sku_code: 'SKU1', supplier_sku_name: '草鱼', supplier_unit: '斤', delivery_sku_code: 'D-001', delivery_sku_name: '草鱼(配送)', status: 'active' },
],
});
seedLocalProposal(state, {
direction: 'from_delivery',
status: 'pending',
remote_proposal_id: 'remote-map',
items: [{ sku_code: 'D-001', unit: '斤', price: 11 }],
});
installDb(state);
listRemote.mockResolvedValueOnce({
kind: 'ok',
status: 200,
rows: [
{
proposal_id: 'remote-map',
direction: 'to_supplier',
status: 'pending',
supplier_quote_sheet_code: SHEET,
branch_code: MAIN_BRANCH,
items: [],
note: null,
reject_reason: null,
applied: null,
created_at: null,
reviewed_at: null,
},
],
summary: null,
nextCursor: null,
});
const result = await approvePriceProposal({
id: '11111111-1111-4111-8111-111111111111',
ctx: { branchCode: BRANCH, userId: 'u2', roles: ['admin'] } as any,
});
expect(result.applied.updated).toBe(1);
expect(result.applied.skipped).toEqual([]);
// 写的是我方 SKU1 行(而不是 D-001 行)
expect(state.items.find((item) => item.sku_code === 'SKU1')!.sale_price).toBe('11');
expect(state.events.filter((event) => event === 'ITEM_UPDATE')).toHaveLength(1);
});
it('配送 SKU 没有 active 映射 ⇒ skipped sku_unmapped,零写价、零推送', async () => {
const state = makeState({ mappings: [] });
seedLocalProposal(state, {
direction: 'from_delivery',
status: 'pending',
remote_proposal_id: 'remote-unmapped',
items: [{ sku_code: 'D-999', unit: '斤', price: 11 }],
});
installDb(state);
listRemote.mockResolvedValueOnce({
kind: 'ok',
status: 200,
rows: [
{
proposal_id: 'remote-unmapped',
direction: 'to_supplier',
status: 'pending',
supplier_quote_sheet_code: SHEET,
branch_code: MAIN_BRANCH,
items: [],
note: null,
reject_reason: null,
applied: null,
created_at: null,
reviewed_at: null,
},
],
summary: null,
nextCursor: null,
});
const result = await approvePriceProposal({
id: '11111111-1111-4111-8111-111111111111',
ctx: { branchCode: BRANCH } as any,
});
expect(result.applied.updated).toBe(0);
expect(result.applied.skipped).toEqual([{ sku_code: 'D-999', reason: 'sku_unmapped' }]);
expect(state.events).not.toContain('ITEM_UPDATE');
expect(triggerQuoteCostSync).not.toHaveBeenCalled(); // 不再走旧通道,由 D3 让配送侧落地
});
it('A 提交响应带本单映射统计(未映射不阻止提交)', async () => {
const state = makeState({
mappings: [
{ supplier_sku_code: 'SKU1', supplier_sku_name: '草鱼', supplier_unit: '斤', delivery_sku_code: 'D-001', delivery_sku_name: null, status: 'active' },
{ supplier_sku_code: 'SKU2', supplier_sku_name: '鲤鱼', supplier_unit: '袋', delivery_sku_code: null, delivery_sku_name: null, status: 'pending' },
],
});
installDb(state);
const result = await submitPriceProposal({
quoteSheetCode: SHEET,
ctx: { branchCode: BRANCH } as any,
});
expect(result.mapping).toMatchObject({ quote_sheet_code: SHEET, total: 3, mapped: 1, unmapped: 2 });
expect(result.mapping.unmapped_skus.map((row) => row.sku_code)).toEqual(['SKU2', 'SKU3']);
});
it('列表的「改前 → 改后」按映射反查我方行;未映射标 unmapped', async () => {
const state = makeState({
mappings: [
{ supplier_sku_code: 'SKU1', supplier_sku_name: '草鱼', supplier_unit: '斤', delivery_sku_code: 'D-001', delivery_sku_name: null, status: 'active' },
],
});
seedLocalProposal(state, {
direction: 'from_delivery',
items: [
{ sku_code: 'D-001', unit: '斤', price: 11 },
{ sku_code: 'D-777', unit: '斤', price: 9 },
],
});
installDb(state);
const { rows } = await listPriceProposals({ branchCode: BRANCH, status: 'pending' });
const lines = rows[0].lines || [];
expect(lines[0]).toMatchObject({
sku_code: 'D-001',
supplier_sku_code: 'SKU1',
before_sale_price: 10,
after_sale_price: 11,
change: 'updated',
});
expect(lines[1]).toMatchObject({ sku_code: 'D-777', supplier_sku_code: null, change: 'unmapped' });
});
});