主系统 2026-10-13 §4.5.25 请求(原话「自己只能改自己 —— 与改价完全同款,我方不替你们落库」):
我们原来的 `applyUnitChangedFact` 是"收到即直接 UPDATE 我方镜像行",
等于他们一改单位就把我们的数据改了,与改价那条(事实 + 待审)不一致,而且**我们界面看不到任何申请**。
改后(默认):
- `mainSystemUnitChangedInbox.applyUnitChangedFact` ⇒ **登记待审**:
写 `public.main_system_actual_qty_requests`(field='unit'、node='unit_changed'、
before_unit/unit、client_request_id、operator、applied_at=changed_at、fact_registered=true、
payload.local_only=true),**不再写 order_items**;
- **只留最新**:同 (branch, prep) 的旧 pending 单位行先转 superseded;
- **幂等**:同一 request_id / client_request_id 重投 ⇒ 唯一键冲突 ⇒ ignored(不建第二行);
- 审核通过 ⇒ 复用既有 `applyActualQtySyncValue`(它本来就支持 field='unit':写
order_items.unit + 验收/核货单位 + 审计);驳回 ⇒ 不写、只留痕;
- **不回传**(local_only;他们只报事实,不需要回执);
- 回退开关 `UNIT_CHANGED_AUTO_APPLY=1` = 旧的"收到即改"(仅线上异常回退),已按闸门登记
server/.env.example + 部署手册。
无需迁移:`main_system_actual_qty_requests` 建表起就允许 field IN ('qty','unit','price') 且有
before_unit/unit 列(20261022);审核页 `PriceQtyRequestsPage` 也早已支持 field='unit' 的
"旧单位 → 新单位"渲染 —— 缺的只是接收端登记这一步。
验证:
- `server/tests/unitChangedInbox.test.ts` 重写为 8 例(默认待审 / 字段齐全且不写 order_items /
只留最新先 UPDATE 后 INSERT / 幂等 / 校验四连 / 回退开关两条 / 落点源码钉);
- 真库端到端(自签 webhook × 真审核接口):返回 pending 且我方单位不动 ⇒ **审核页接口
scope=pending 能列到**("单位 斤 → 件")⇒ 通过 ⇒ 单位落 件 + 台账 approved + 留痕 ⇒
反向再走一遍并审核 ⇒ 还原、无遗留 pending;复跑同一事件 ⇒ ignored;
- 双端 tsc 0 错;全量 26 failed / 2666 passed 与基线持平(唯一差异仍是对方 WIP 的 pickingZoneOrder);
门禁 8 通过 / 1 既定红 / 1 未执行。
文档:设计文 §11.9 加口径翻转提示 + 新增 §11.11(改后行为表 / 验收 U16–U24 / 与 §11.8、§11.10 的关系);
对接清单新增「八、我方回执」(告诉对方可以这样验:他们改一次单位 ⇒ 我们多一条待审)。
249 lines
11 KiB
TypeScript
249 lines
11 KiB
TypeScript
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
|
||
import { readFileSync } from 'node:fs';
|
||
import path from 'node:path';
|
||
|
||
/**
|
||
* 主系统改**备货行单位** → 通知我方(事件 `preparations.unit_changed`,2026-10-13)。
|
||
*
|
||
* 反向缺口:他们管理端改单位时若价格没变就不发 `price_changed` ⇒ 我方镜像里的单位一直是旧的。
|
||
* 他们新增了专用事实事件(提交 `3608614d`)。
|
||
*
|
||
* ⚠️ **口径翻转(2026-10-13 晚,他们 §4.5.25 请求)**:原来是"收到即改我方镜像行",
|
||
* 等于"他们一改就把我们的数据改了",与"自己只能改自己"(改价早已是"事实 + 待审")冲突
|
||
* ⇒ 现在默认**登记待审**(`main_system_actual_qty_requests`,`field='unit'`),
|
||
* 审核页看得到、由人决定跟不跟;通过时才写 `order_items.unit`。
|
||
* `UNIT_CHANGED_AUTO_APPLY=1` 可整体回退旧行为。
|
||
*
|
||
* 本文件钉住:
|
||
* ① 默认:登记一条**待审**行(含 before_unit/unit/client_request_id/local_only),**不写** order_items;
|
||
* ② 只留最新:同 prep 的旧 pending 单位行转 superseded;
|
||
* ③ 幂等:同一事实重投(唯一键冲突)⇒ ignored,不新增第二行;
|
||
* ④ 安全:缺 prep_id / 缺 final_unit / 非 uuid / 行对不上 ⇒ ignored + 原因,不建行;
|
||
* ⑤ 回退开关:`UNIT_CHANGED_AUTO_APPLY=1` ⇒ 回到"收到即改"(旧用例语义);
|
||
* ⑥ 落点:webhook 里**就地 return**,不落到「建单导入」兜底。
|
||
*/
|
||
|
||
const query = 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/tenantSchemaService', () => ({
|
||
runWithTenantDataAccess: (...args: unknown[]) => withTenantData(...args),
|
||
}));
|
||
vi.mock('../src/services/auditService', () => ({
|
||
writeAuditLog: (...args: unknown[]) => audit(...args),
|
||
}));
|
||
|
||
import {
|
||
applyUnitChangedFact,
|
||
isUnitChangedReviewRequired,
|
||
mapUnitChangedPayload,
|
||
} from '../src/services/mainSystemUnitChangedInbox';
|
||
|
||
const BRANCH = 'BR002';
|
||
const PREP = 'c66d867e-3a98-4d5e-b15a-a46321fa5403';
|
||
const ORDER = 'ORD_API_20261012_BR002_0001';
|
||
const ITEM = '3e65a38f-ad78-4010-b370-4142650308fd';
|
||
|
||
function payload(overrides: Record<string, unknown> = {}) {
|
||
return {
|
||
event: 'preparations.unit_changed',
|
||
request_id: 'evt-unit-1',
|
||
branch_code: BRANCH,
|
||
supplier_code: 'SUP37831443',
|
||
subsystem_code: 'SCF69N8ZQEVQ',
|
||
order_code: 'ORD_WEB_20261012_BR002_0004',
|
||
preparation_id: PREP,
|
||
prep_id: PREP,
|
||
sku_code: 'SKU78659863567',
|
||
before_unit: '斤',
|
||
final_unit: '件',
|
||
unit: '件',
|
||
before_value: null,
|
||
after_value: null,
|
||
client_request_id: `uc_${PREP}_斤_件`,
|
||
source: 'admin_prep_edit',
|
||
operator: 'u-1',
|
||
operator_role: 'admin',
|
||
changed_at: '2026-10-13T06:03:54.000Z',
|
||
...overrides,
|
||
};
|
||
}
|
||
|
||
/** pool 侧桩:link 命中 + 待审登记(INSERT/UPDATE)记录 */
|
||
function stub(params: {
|
||
link?: { our_order_code: string | null; our_order_item_id: string | null } | null;
|
||
insertFails?: boolean;
|
||
currentUnit?: string | null;
|
||
}) {
|
||
const link =
|
||
params.link === undefined ? { our_order_code: ORDER, our_order_item_id: ITEM } : params.link;
|
||
const calls: Array<{ sql: string; params?: unknown[] }> = [];
|
||
query.mockImplementation(async (sql: string, values?: unknown[]) => {
|
||
const text = String(sql);
|
||
calls.push({ sql: text, params: values });
|
||
if (text.includes('FROM public.main_system_order_import_items')) {
|
||
return link ? { rowCount: 1, rows: [link] } : { rowCount: 0, rows: [] };
|
||
}
|
||
if (text.startsWith('UPDATE public.main_system_actual_qty_requests')) {
|
||
return { rowCount: 1, rows: [] };
|
||
}
|
||
if (text.startsWith('INSERT INTO public.main_system_actual_qty_requests')) {
|
||
if (params.insertFails) {
|
||
throw Object.assign(new Error('duplicate key'), { code: '23505' });
|
||
}
|
||
return { rowCount: 1, rows: [{ id: 'pending-row-1' }] };
|
||
}
|
||
return { rowCount: 0, rows: [] };
|
||
});
|
||
const updates: unknown[][] = [];
|
||
withTenantData.mockImplementation(async (_branch: string, fn: (client: unknown) => unknown) =>
|
||
fn({
|
||
query: async (sql: string, values?: unknown[]) => {
|
||
if (String(sql).startsWith('UPDATE order_items')) {
|
||
updates.push(values || []);
|
||
return { rowCount: 1, rows: [{ id: ITEM }] };
|
||
}
|
||
if (String(sql).includes('FROM order_items')) {
|
||
return { rowCount: 1, rows: [{ unit: params.currentUnit ?? '斤' }] };
|
||
}
|
||
return { rowCount: 0, rows: [] };
|
||
},
|
||
})
|
||
);
|
||
return { calls, updates };
|
||
}
|
||
|
||
beforeEach(() => {
|
||
query.mockReset();
|
||
withTenantData.mockReset();
|
||
audit.mockReset();
|
||
audit.mockResolvedValue(undefined);
|
||
delete process.env.UNIT_CHANGED_AUTO_APPLY;
|
||
});
|
||
|
||
afterEach(() => {
|
||
delete process.env.UNIT_CHANGED_AUTO_APPLY;
|
||
});
|
||
|
||
describe('单位变更接收端:默认**登记待审**(2026-10-13 口径翻转)', () => {
|
||
it('① 登记一条待审行:带 before_unit/unit/幂等键 + local_only,且**不写** order_items', async () => {
|
||
const { calls, updates } = stub({});
|
||
const out = await applyUnitChangedFact({ branchCode: BRANCH, payload: payload() });
|
||
expect(out.status).toBe('pending');
|
||
expect(out.requestRowId).toBe('pending-row-1');
|
||
expect(String(out.reason)).toContain('已登记待审');
|
||
expect(updates, '待审阶段不得改我方单位').toHaveLength(0);
|
||
|
||
const insert = calls.find((c) => c.sql.startsWith('INSERT INTO public.main_system_actual_qty_requests'));
|
||
expect(insert, '必须写入待审台账').toBeTruthy();
|
||
// 列里写死的部分(node/field/status/fact_registered)走 SQL 文本断言,参数按下标断言
|
||
expect(insert?.sql).toContain("'unit_changed','unit'");
|
||
expect(insert?.sql).toContain("'pending', true");
|
||
const v = insert?.params as unknown[];
|
||
expect(v[1], 'request_id').toBe('evt-unit-1');
|
||
expect(v[2], 'prep_id').toBe(PREP);
|
||
expect(v[6], 'before_unit').toBe('斤');
|
||
expect(v[7], 'unit=新单位').toBe('件');
|
||
expect(v[10], 'client_request_id 幂等键').toBe(`uc_${PREP}_斤_件`);
|
||
expect(String(v[11]), 'local_only(审核结论不回传)').toContain('"local_only":true');
|
||
});
|
||
|
||
it('② 只留最新:同 prep 的旧 pending 单位行先转 superseded', async () => {
|
||
const { calls } = stub({});
|
||
await applyUnitChangedFact({ branchCode: BRANCH, payload: payload() });
|
||
const supersede = calls.find((c) => c.sql.startsWith('UPDATE public.main_system_actual_qty_requests'));
|
||
expect(supersede, '必须先清理旧待审').toBeTruthy();
|
||
expect(supersede?.sql).toContain("status = 'superseded'");
|
||
expect(supersede?.sql).toContain("field = 'unit'");
|
||
// 顺序:先 supersede 再 INSERT
|
||
const idxUpdate = calls.findIndex((c) => c.sql.startsWith('UPDATE public.main_system_actual_qty_requests'));
|
||
const idxInsert = calls.findIndex((c) => c.sql.startsWith('INSERT INTO public.main_system_actual_qty_requests'));
|
||
expect(idxUpdate).toBeLessThan(idxInsert);
|
||
});
|
||
|
||
it('③ 幂等:同一事实重投(唯一键冲突)⇒ ignored,不新增第二行', async () => {
|
||
const { calls } = stub({ insertFails: true });
|
||
const out = await applyUnitChangedFact({ branchCode: BRANCH, payload: payload() });
|
||
expect(out.status).toBe('ignored');
|
||
expect(String(out.reason)).toContain('幂等跳过');
|
||
expect(calls.filter((c) => c.sql.startsWith('INSERT INTO'))).toHaveLength(1);
|
||
});
|
||
|
||
it('④ 安全:缺 prep_id / 缺 final_unit / 非 uuid / 行对不上 ⇒ 不建行', async () => {
|
||
for (const [override, expected] of [
|
||
[{ preparation_id: null, prep_id: null }, '缺少 preparation_id'],
|
||
[{ final_unit: null, unit: null }, '缺少 final_unit'],
|
||
[{ preparation_id: 'not-a-uuid', prep_id: 'not-a-uuid' }, '不是 uuid'],
|
||
] as Array<[Record<string, unknown>, string]>) {
|
||
query.mockReset();
|
||
withTenantData.mockReset();
|
||
const out = await applyUnitChangedFact({ branchCode: BRANCH, payload: payload(override) });
|
||
expect(out.status).toBe('ignored');
|
||
expect(String(out.reason)).toContain(expected);
|
||
expect(query).not.toHaveBeenCalled();
|
||
}
|
||
const { calls } = stub({ link: null });
|
||
const missing = await applyUnitChangedFact({ branchCode: BRANCH, payload: payload() });
|
||
expect(missing.status).toBe('ignored');
|
||
expect(String(missing.reason)).toContain('没有该备货行的对照行');
|
||
expect(calls.some((c) => c.sql.startsWith('INSERT INTO'))).toBe(false);
|
||
});
|
||
});
|
||
|
||
describe('回退开关:UNIT_CHANGED_AUTO_APPLY=1 ⇒ 旧的"收到即改"', () => {
|
||
it('① 开关打开:直接写 order_items.unit,不建待审', async () => {
|
||
process.env.UNIT_CHANGED_AUTO_APPLY = '1';
|
||
expect(isUnitChangedReviewRequired()).toBe(false);
|
||
const { calls, updates } = stub({});
|
||
const out = await applyUnitChangedFact({ branchCode: BRANCH, payload: payload() });
|
||
expect(out.status).toBe('applied');
|
||
expect(updates).toHaveLength(1);
|
||
expect(updates[0]).toEqual([ORDER, ITEM, '件']);
|
||
expect(calls.some((c) => c.sql.startsWith('INSERT INTO public.main_system_actual_qty_requests'))).toBe(false);
|
||
// 审计日志仍在
|
||
expect(audit).toHaveBeenCalledTimes(1);
|
||
expect((audit.mock.calls[0][0] as { operationType: string }).operationType).toBe(
|
||
'main_system_unit_changed_applied'
|
||
);
|
||
});
|
||
|
||
it('② 开关打开时,我方已是该单位 ⇒ ignored(旧幂等语义保留)', async () => {
|
||
process.env.UNIT_CHANGED_AUTO_APPLY = '1';
|
||
const { updates } = stub({ currentUnit: '件' });
|
||
const out = await applyUnitChangedFact({ branchCode: BRANCH, payload: payload() });
|
||
expect(out.status).toBe('ignored');
|
||
expect(String(out.reason)).toContain('幂等跳过');
|
||
expect(updates).toHaveLength(0);
|
||
});
|
||
});
|
||
|
||
describe('载荷映射与落点', () => {
|
||
it('两个字段名都认(prep_id / unit 别名),并带出 request_id / reason', () => {
|
||
const mapped = mapUnitChangedPayload(
|
||
payload({ preparation_id: null, final_unit: null, unit: '箱', reason: '复称' })
|
||
);
|
||
expect(mapped.prepId).toBe(PREP);
|
||
expect(mapped.finalUnit).toBe('箱');
|
||
expect(mapped.beforeUnit).toBe('斤');
|
||
expect(mapped.requestId).toBe('evt-unit-1');
|
||
expect(mapped.reason).toBe('复称');
|
||
expect(Object.keys(mapped)).not.toContain('price');
|
||
});
|
||
|
||
it('落点:webhook 里就地 return,不落到「建单导入」兜底(源码钉)', () => {
|
||
const route = readFileSync(path.join(__dirname, '../src/routes/mainSystemIntegration.ts'), 'utf8');
|
||
const branchAt = route.indexOf("event === 'preparations.unit_changed'");
|
||
const fallbackAt = route.indexOf("if (event !== 'preparations.allocated')");
|
||
const importAt = route.indexOf('importMainSystemGroups({');
|
||
expect(branchAt, '必须存在 unit_changed 分支').toBeGreaterThan(-1);
|
||
expect(branchAt, 'unit_changed 分支必须在未知事件兜底之前').toBeLessThan(fallbackAt);
|
||
expect(branchAt, 'unit_changed 分支必须在建单导入之前').toBeLessThan(importAt);
|
||
expect(route.slice(branchAt, fallbackAt)).toContain('return res.json({ ok: true, ...applied })');
|
||
});
|
||
});
|