Files
SupplierSystem/server/tests/unitDeferredResend.test.ts
T
Ubuntu 4fb4abb420
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
feat(跨系统): 单位载体走待审后的两处追赶(409 不算失败 / 驳回不再重发)
主系统 2026-10-13 单边把「我方送过去的单位载体」改成**走待审**(其提交 a0afc585):
单位变了 ⇒ 回 pending(他们的行先不变,审核通过后才写并推 price_qty_decided);
该行已有待审 ⇒ 回 409 pending_exists(原话「再等一轮即可,别重试轰炸」);
补单位(当前为空)仍免审。我方协议不用改,但有两处必须跟上:

1) 409 被我们误记成"提交失败":http.ts 把未分类 4xx 判 rejected ⇒ submitPriceQtyRequest
   落 failed ⇒ 设计文 §11.8 的定向补发每轮计 1 次尝试,5 轮(约 50 分钟)后判 abandoned。
   修法:api/priceQty.ts 把 409 映射为机器可读的 conflict='pending_exists' 并一路透传;
   补发遇到它时保持 waiting 且**把尝试次数退回**(不计重试预算),等那条待审落定后自然补发。

2) 单位载体被审核人驳回时,落定钩子会再发一次同一单位(可能被反复驳回)。
   修法:落定钩子把"刚落定的台账行"传给补发;若它是**单位载体**(kind='qty' 且
   proposed_qty === before_qty)且结论 rejected ⇒ 意图标 noop、不重发(尊重审核结论;
   操作员若仍要改,重新改一次单位即可 = 新的显式意图)。

不误伤(含反证用例):真失败仍按 5 次上限收敛;被驳回的是改量(proposed ≠ before)时单位照常补发。

测试:unitDeferredResend.test.ts 扩到 15 例(新增 ⑪/⑪b/⑫/⑫b/⑬);
服务端 tsc 0 错;全量 26 failed / 2653 passed 与基线持平(唯一差异仍是对方 WIP 的 pickingZoneOrder);
门禁 8 通过 / 1 既定红 / 1 未执行(与改前一致)。

文档:设计文 §11.10(新语义 + 两处追赶 + 补单位/他们的理由/已知边界);
对接清单 §4.5.24 七(我方回执:追赶明细 + 误发待审的处置结果 + 对其 六之补 的确认)。

另:误发待审那条(其请求驳回"成本价 6.5 → 10")——我方镜像价从未跟成 10;
代为驳回时其侧已查不到该 request_id(not_found),我方台账保持待审不变,
按既有 Q6 对账口径宽限期后自动关成 failed(已在回执里写清)。
2026-10-13 14:56:52 +08:00

312 lines
14 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 { 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);
});
/**
* 2026-10-13(主系统把「子系统改我方单位」改成走待审之后的追赶):
* ⑪ 409 `pending_exists` = "该行已有别的待审,再等一轮" ⇒ **不计重试次数**、绝不因此放弃;
* ⑫ 他们审核人**驳回**我们送的单位载体 ⇒ 不再自动重发(尊重审核结论)。
* 两条都带"不误伤"反证:真失败照样计数、被驳回的是**改量**(不是单位载体)时照旧补发。
*/
it('⑪ 409 pending_exists ⇒ 保持 waiting 且**不计**重试次数(连试多轮也不放弃)', async () => {
submitPriceQty.mockResolvedValue({
kind: 'failed',
reason: 'pending_exists:该备货行已有待审申请',
retryable: false,
conflict: 'pending_exists',
});
for (let i = 0; i < 6; i += 1) {
const outcome = await flushDeferredUnitResendForPrep({ branchCode: BRANCH, prepId: PREP, trigger: 'sweep' });
expect(outcome.kind).toBe('waiting');
expect(String(outcome.reason)).toContain('pending_exists');
}
expect(submitPriceQty, '每轮仍会试一次(10 分钟一跳,不是轰炸)').toHaveBeenCalledTimes(6);
expect(intent?.status, '始终留在 waiting,没有被判放弃').toBe('waiting');
expect(intent?.attempts, '不计入重试预算').toBe(0);
});
it('⑪b 反证:真正的失败仍按上限收敛(不会被这条豁免拖成永久重试)', 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');
});
it('⑫ 单位载体被驳回 ⇒ 不再自动重发(intent 标 noop、不发 HTTP)', async () => {
const outcome = await flushDeferredUnitResendForPrep({
branchCode: BRANCH,
prepId: PREP,
trigger: 'decided',
justDecided: { status: 'rejected', kind: 'qty', proposedQty: 10, beforeQty: 10 },
});
expect(outcome.kind).toBe('noop');
expect(String(outcome.reason)).toContain('驳回了这次单位变更');
expect(submitPriceQty, '尊重审核结论:不重发').not.toHaveBeenCalled();
expect(intent?.status).toBe('noop');
});
it('⑫b 反证:被驳回的是**改量**(proposed ≠ before)⇒ 单位仍照常补发', async () => {
const outcome = await flushDeferredUnitResendForPrep({
branchCode: BRANCH,
prepId: PREP,
trigger: 'decided',
justDecided: { status: 'rejected', kind: 'qty', proposedQty: 12, beforeQty: 10 },
});
expect(outcome.kind).toBe('sent');
expect(submitPriceQty).toHaveBeenCalledTimes(1);
});
it('⑬ 契约钉:对方 409 会被映射成 conflict=pending_exists(不是笼统的"被拒")', () => {
const apiSrc = readFileSync(
path.join(__dirname, '../src/services/mainSystem/api/priceQty.ts'),
'utf8'
);
expect(apiSrc).toContain("conflict: 'pending_exists' as const");
expect(apiSrc).toMatch(/result\.status === 409/);
expect(src).toContain("conflict === 'pending_exists'");
expect(src).toContain('attempts: Number(intent.attempts || 0)');
});
});