主系统回执指出「跳过 ≠ 排队」:某行有待审改量时改单位,我方本次不上报 (避免顶掉待审改量),但那条待审若最终被驳回,这次单位变更就永久丢失。 开发者裁决选 A:跳过时留一条意图,改量审核落定后定向补发一次。 - migrations/20261043:新表 public.main_system_price_qty_unit_deferred (waiting 部分唯一索引 (branch_code, prep_id) ⇒ 同一行只留最新意图) - mainSystemUnitDeferredResend.ts:recordDeferredUnitResend(跳过时 upsert 意图) + flushDeferredUnitResendForPrep(补发,三个前提:无任何 pending / 行仍在且单位未改回 / 开关仍开) + sweepDeferredUnitResends(15 分钟清扫,兜住无决策事件的情形) - mainSystemPriceQtyRequest.ts:跳过分支留意图;handlePriceQtyDecidedEvent 尾部补发 (webhook 与 Q6 对账共用该处理器 ⇒ 两条路径都覆盖) - scheduledJobs.ts:15 分钟 tick 挂清扫(内部限流 10 分钟) - 幂等:client_request_id = unit-deferred-<意图行 id>(确定性)⇒ 重复触发只上报一次 真机 E2E(本地栈 × 真库 × 主系统管理员真驳回,靶 c66d867e…/酸菜/BR002): 造待审改量(10→12) ⇒ 改单位 斤→箱 ⇒ 不上报但留意图(主系统仍 斤)⇒ 清扫被挡 ⇒ 真驳回(HTTP 200,webhook 落定) ⇒ 补发一次 ⇒ 主系统备货行单位 斤→箱、数量/价格未动 ⇒ 收尾还原。你们那条驳回事件实际投了 2 次,确定性幂等键让只发出 1 条载体。 测试:unitDeferredResend.test.ts(10 例)+ mainSystemPriceQtyRequest.test.ts 用例 ⑥⑦(共 53 例); 服务端 tsc 0 错;设计文 §11.8;对接清单新增 §2.15(我方后续回执)。
247 lines
10 KiB
TypeScript
247 lines
10 KiB
TypeScript
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||
import { readFileSync } from 'node:fs';
|
||
import path from 'node:path';
|
||
|
||
/**
|
||
* 单位变更「跳过」的定向补发(2026-10-13,开发者选 A;设计文 §11.8)。
|
||
*
|
||
* 主系统回执 §10.2-3 指出「跳过 ≠ 排队」:某行有待审改量时改单位 ⇒ 本次不报(否则顶掉待审改量),
|
||
* 而那条待审若被驳回,单位变更就永久丢了。本文件钉住模块自身的三条语义:
|
||
* · ⑧ 仍有 pending ⇒ **不补发**(保守:任何 kind 的 pending 都挡住),保持 `waiting`;
|
||
* · ⑨ 幂等:补发成功后再触发 ⇒ 不再发(意图已 `sent`,确定性幂等键兜第二层);
|
||
* · ⑩ 单位已改回旧值 ⇒ 标 `noop`,**不发 HTTP**;
|
||
* 另加:连试上限 ⇒ `abandoned`、清扫按分公司遍历、记录侧 upsert 语义(再次跳过就地刷新)。
|
||
*
|
||
* 接线(跳过时记意图、决策落定后补发)在 `mainSystemPriceQtyRequest.test.ts` 的用例 ⑥⑦ 里钉。
|
||
*/
|
||
|
||
const query = vi.hoisted(() => vi.fn());
|
||
const submitPriceQty = vi.hoisted(() => vi.fn());
|
||
const enabled = vi.hoisted(() => ({ value: true }));
|
||
const listBranches = vi.hoisted(() => vi.fn());
|
||
const withTenantData = vi.hoisted(() => vi.fn());
|
||
const audit = vi.hoisted(() => vi.fn());
|
||
|
||
vi.mock('../src/db', () => ({
|
||
pool: { query: (...args: unknown[]) => query(...args), connect: vi.fn() },
|
||
getRawPoolQuery: () => query,
|
||
}));
|
||
// 只桩掉"提交"这一个出口:补发形态(载体)由参数断言,提交内部的语义在另一个文件里钉
|
||
vi.mock('../src/services/mainSystemPriceQtyRequest', () => ({
|
||
isEnabled: () => enabled.value,
|
||
submitPriceQtyRequest: (...args: unknown[]) => submitPriceQty(...args),
|
||
}));
|
||
vi.mock('../src/services/tenantSchemaService', () => ({
|
||
runWithTenantDataAccess: (...args: unknown[]) => withTenantData(...args),
|
||
}));
|
||
vi.mock('../src/services/platformBranch', () => ({
|
||
listActiveBranchCodes: () => listBranches(),
|
||
}));
|
||
vi.mock('../src/services/auditService', () => ({
|
||
writeAuditLog: (...args: unknown[]) => audit(...args),
|
||
}));
|
||
|
||
import {
|
||
flushDeferredUnitResendForPrep,
|
||
recordDeferredUnitResend,
|
||
sweepDeferredUnitResends,
|
||
} from '../src/services/mainSystemUnitDeferredResend';
|
||
|
||
const BRANCH = 'SUP37831443';
|
||
const PREP = 'prep-1';
|
||
|
||
function makeIntent(overrides: Record<string, unknown> = {}) {
|
||
return {
|
||
id: 'intent-1',
|
||
branch_code: BRANCH,
|
||
prep_id: PREP,
|
||
main_order_code: 'ORD_WEB_X',
|
||
our_order_code: 'ORD_API_20261009_SUP37831443_0001',
|
||
our_order_item_id: '11111111-2222-3333-4444-555555555555',
|
||
before_unit: '斤',
|
||
target_unit: '件',
|
||
status: 'waiting',
|
||
attempts: 0,
|
||
last_error: null,
|
||
deferred_at: '2026-10-13T05:00:00.000Z',
|
||
resolved_at: null,
|
||
updated_at: '2026-10-13T05:00:00.000Z',
|
||
payload: {},
|
||
...overrides,
|
||
};
|
||
}
|
||
|
||
/** 内存里的"一条意图":UPDATE 会真的改它的状态,便于断言幂等与收敛 */
|
||
let intent: ReturnType<typeof makeIntent> | null = null;
|
||
let hasPending = false;
|
||
let itemUnit: string | null = '件';
|
||
let tenantReadFails = false;
|
||
|
||
beforeEach(() => {
|
||
intent = makeIntent();
|
||
hasPending = false;
|
||
itemUnit = '件';
|
||
tenantReadFails = false;
|
||
enabled.value = true;
|
||
query.mockReset();
|
||
submitPriceQty.mockReset();
|
||
listBranches.mockReset();
|
||
withTenantData.mockReset();
|
||
audit.mockReset();
|
||
audit.mockResolvedValue(undefined);
|
||
|
||
query.mockImplementation(async (sql: string, values?: unknown[]) => {
|
||
const text = String(sql);
|
||
if (text.startsWith('UPDATE public.main_system_price_qty_unit_deferred')) {
|
||
if (intent) {
|
||
intent = {
|
||
...intent,
|
||
status: String(values?.[1] || intent.status) as typeof intent.status,
|
||
last_error: values?.[2] != null ? String(values[2]) : null,
|
||
attempts: values?.[4] != null ? Number(values[4]) : intent.attempts,
|
||
target_unit: values?.[3] != null ? String(values[3]) : intent.target_unit,
|
||
} as typeof intent;
|
||
}
|
||
return { rowCount: 1, rows: [] };
|
||
}
|
||
if (text.includes('FROM public.main_system_price_qty_unit_deferred')) {
|
||
// ⚠️ 桩必须尊重 `status = 'waiting'` 过滤,否则"已 sent 的意图还会被再捞出来"(幂等用例会假绿)
|
||
const wantsWaiting = text.includes("status = 'waiting'");
|
||
const hit = intent && (!wantsWaiting || intent.status === 'waiting');
|
||
return hit ? { rowCount: 1, rows: [{ ...intent }] } : { rowCount: 0, rows: [] };
|
||
}
|
||
if (text.includes('SELECT 1 FROM public.main_system_price_qty_requests')) {
|
||
return hasPending ? { rowCount: 1, rows: [{}] } : { rowCount: 0, rows: [] };
|
||
}
|
||
return { rowCount: 0, rows: [] };
|
||
});
|
||
withTenantData.mockImplementation(async (_branch: string, fn: (client: unknown) => unknown) => {
|
||
if (tenantReadFails) throw new Error('租户库读失败');
|
||
return fn({
|
||
query: async () => ({ rowCount: itemUnit === null ? 0 : 1, rows: itemUnit === null ? [] : [{ unit: itemUnit, quantity: 10 }] }),
|
||
});
|
||
});
|
||
submitPriceQty.mockResolvedValue({
|
||
kind: 'ok',
|
||
row: { id: 'ledger-1' },
|
||
status: 'applied',
|
||
reviewRequired: false,
|
||
finalPrice: null,
|
||
finalQty: 10,
|
||
pendingFields: {},
|
||
message: '值与当前一致,无需审核',
|
||
appliedLocally: false,
|
||
applyNote: null,
|
||
});
|
||
});
|
||
|
||
describe('单位变更定向补发(§11.8)', () => {
|
||
const src = readFileSync(path.join(__dirname, '../src/services/mainSystemUnitDeferredResend.ts'), 'utf8');
|
||
|
||
it('⑧ 仍有 pending(任何 kind)⇒ 不补发、保持 waiting、不发 HTTP', async () => {
|
||
hasPending = true;
|
||
const outcome = await flushDeferredUnitResendForPrep({ branchCode: BRANCH, prepId: PREP, trigger: 'decided' });
|
||
expect(outcome.kind).toBe('blocked');
|
||
expect(String(outcome.reason)).toContain('待审');
|
||
expect(submitPriceQty).not.toHaveBeenCalled();
|
||
expect(intent?.status, '仍是待补发').toBe('waiting');
|
||
expect(intent?.attempts, '前提不成立不计尝试次数').toBe(0);
|
||
});
|
||
|
||
it('⑧b pending 清掉后(清扫触发)⇒ 补发一次,载体=当前数量+当前单位', async () => {
|
||
hasPending = false;
|
||
const outcome = await flushDeferredUnitResendForPrep({ branchCode: BRANCH, prepId: PREP, trigger: 'sweep' });
|
||
expect(outcome.kind).toBe('sent');
|
||
expect(submitPriceQty).toHaveBeenCalledTimes(1);
|
||
const call = submitPriceQty.mock.calls[0][0] as any;
|
||
expect(call.proposedUnit).toBe('件');
|
||
expect(call.beforeUnit).toBe('斤');
|
||
expect(call.proposedQty, '数量维度不传 ⇒ 走"只改单位"的载体').toBeUndefined();
|
||
expect(call.proposedPrice).toBeUndefined();
|
||
expect(call.clientRequestId, '确定性幂等键').toBe('unit-deferred-intent-1');
|
||
expect(String(call.reason)).toContain('单位变更补报');
|
||
expect(intent?.status).toBe('sent');
|
||
});
|
||
|
||
it('⑨ 幂等:补发成功后再触发 ⇒ 不再发(意图已 sent;确定性幂等键兜第二层)', async () => {
|
||
const first = await flushDeferredUnitResendForPrep({ branchCode: BRANCH, prepId: PREP, trigger: 'decided' });
|
||
expect(first.kind).toBe('sent');
|
||
const second = await flushDeferredUnitResendForPrep({ branchCode: BRANCH, prepId: PREP, trigger: 'sweep' });
|
||
expect(second.kind).toBe('none');
|
||
expect(submitPriceQty).toHaveBeenCalledTimes(1);
|
||
// 幂等键由意图行 id 派生(不是随机 uuid)⇒ 即便并发重放也命中台账唯一键
|
||
expect(src).toContain('clientRequestId: `unit-deferred-${intent.id}`');
|
||
});
|
||
|
||
it('⑩ 单位已改回旧值 ⇒ noop,不发 HTTP(不必补报)', async () => {
|
||
itemUnit = '斤';
|
||
const outcome = await flushDeferredUnitResendForPrep({ branchCode: BRANCH, prepId: PREP, trigger: 'decided' });
|
||
expect(outcome.kind).toBe('noop');
|
||
expect(submitPriceQty).not.toHaveBeenCalled();
|
||
expect(intent?.status).toBe('noop');
|
||
});
|
||
|
||
it('⑩b 我方订单行已不存在 ⇒ abandoned(收敛,不无限重试)', async () => {
|
||
itemUnit = null;
|
||
const outcome = await flushDeferredUnitResendForPrep({ branchCode: BRANCH, prepId: PREP, trigger: 'sweep' });
|
||
expect(outcome.kind).toBe('abandoned');
|
||
expect(intent?.status).toBe('abandoned');
|
||
});
|
||
|
||
it('⑩c 提交一直被挡(主系统不可用)⇒ 连试到上限就 abandoned + 留错误', async () => {
|
||
intent = makeIntent({ attempts: 4 });
|
||
submitPriceQty.mockResolvedValue({ kind: 'failed', reason: '主系统不可用', retryable: true });
|
||
const outcome = await flushDeferredUnitResendForPrep({ branchCode: BRANCH, prepId: PREP, trigger: 'sweep' });
|
||
expect(outcome.kind).toBe('abandoned');
|
||
expect(intent?.status).toBe('abandoned');
|
||
expect(String(intent?.last_error)).toContain('人工');
|
||
});
|
||
|
||
it('① 记录侧:单位没变 ⇒ 不建意图(skipped)', async () => {
|
||
const r = await recordDeferredUnitResend({
|
||
branchCode: BRANCH,
|
||
prepId: PREP,
|
||
ourOrderCode: 'ORD_X',
|
||
beforeUnit: '斤',
|
||
targetUnit: '斤',
|
||
});
|
||
expect(r.kind).toBe('skipped');
|
||
expect(query).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('② 记录侧:upsert(同一行只留最新意图,再次跳过就刷新并归零尝试)', async () => {
|
||
const r = await recordDeferredUnitResend({
|
||
branchCode: BRANCH,
|
||
prepId: PREP,
|
||
ourOrderCode: 'ORD_X',
|
||
ourOrderItemId: '11111111-2222-3333-4444-555555555555',
|
||
beforeUnit: '斤',
|
||
targetUnit: '箱',
|
||
});
|
||
expect(r.kind).toBe('recorded');
|
||
const call = query.mock.calls[0];
|
||
expect(String(call[0])).toContain("ON CONFLICT (branch_code, prep_id) WHERE status = 'waiting'");
|
||
expect(String(call[0])).toContain('attempts = 0');
|
||
const values = call[1] as unknown[];
|
||
expect(values[5]).toBe('斤');
|
||
expect(values[6]).toBe('箱');
|
||
});
|
||
|
||
it('①b 开关关掉 ⇒ 不补发(不发 HTTP、保持 waiting)', async () => {
|
||
enabled.value = false;
|
||
const outcome = await flushDeferredUnitResendForPrep({ branchCode: BRANCH, prepId: PREP, trigger: 'sweep' });
|
||
expect(outcome.kind).toBe('blocked');
|
||
expect(submitPriceQty).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('清扫:按分公司遍历 waiting 意图并汇总', async () => {
|
||
listBranches.mockResolvedValue([BRANCH]);
|
||
const result = await sweepDeferredUnitResends({ limit: 50 });
|
||
expect(result.branches).toBe(1);
|
||
expect(result.scanned).toBe(1);
|
||
expect(result.sent).toBe(1);
|
||
expect(result.abandoned).toBe(0);
|
||
expect(submitPriceQty).toHaveBeenCalledTimes(1);
|
||
});
|
||
});
|