主系统回执(对接清单 §4.5.24):他们管理端改备货行单位时,若价格没变就不发 price_changed ⇒ 我方镜像里的单位一直是旧的(他们 §10.4 / 本仓 §11.4-3 登记的同源 反向缺口)。他们已新增专用事实事件(提交 3608614d,开关 SUPPLIER_UNIT_CHANGED_PUSH_ENABLED 默认关,等我们接收端就绪),只推事实、不给我方造待审,请我们加接收端。 - mainSystemUnitChangedInbox.ts:applyUnitChangedFact —— 按 (branch_code, prep_id) 在 main_system_order_import_items 找到我方订单行,**只写 order_items.unit = final_unit** (价/量/状态/退货标记不动,不建任何待审);我方已是该单位 ⇒ ignored(幂等,他们那边 也有回声抑制);留一条操作日志 main_system_unit_changed_applied - mainSystemIntegration.ts:新增 preparations.unit_changed 分支,**就地 return** (不得落到末尾的「建单导入」兜底 —— 他们明确提醒:将来若被塞 data[] 会误建单) - 字段兼容:preparation_id/prep_id 都认;final_unit 优先、unit 作别名;before_unit 可缺; before_value/after_value 恒 null(无任何价格分支会碰它) - 安全:缺 prep_id/缺 final_unit/非 uuid/行对不上 ⇒ ignored + 原因,不猜不建行 验证: - server/tests/unitChangedInbox.test.ts(9 例:落值/幂等/大小写空白/缺字段/行对不上/落点顺序源码钉) - 真库 E2E(按他们 §二 载荷自签打进我方 dev API):applied ⇒ 我方单位 斤→件 且价/量未动; 同一条重投 ⇒ ignored(幂等跳过);坏签名 ⇒ 401;缺 final_unit ⇒ ignored;收尾还原 - 服务端 tsc 0 错;全量 26 failed / 376 passed 与基线持平(差异仅对方 WIP 的 pickingZoneOrder) - 设计文 §11.9(含"延迟重投"已知边界);对接清单 §4.5.24 五(我方回执,请他们开开关)
216 lines
9.6 KiB
TypeScript
216 lines
9.6 KiB
TypeScript
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||
import { readFileSync } from 'node:fs';
|
||
import path from 'node:path';
|
||
|
||
/**
|
||
* 主系统改**备货行单位** → 通知我方(事件 `preparations.unit_changed`,2026-10-13)。
|
||
*
|
||
* 反向缺口:他们管理端改单位时若价格没变就不发 `price_changed` ⇒ 我方镜像里的单位一直是旧的。
|
||
* 他们已新增专用事实事件(提交 `3608614d`,开关默认关,等我们接收端就绪)。
|
||
*
|
||
* 本文件钉住接收端的四条不变量:
|
||
* ① 落值:按 `prep_id` 找到我方行,**只写 `unit = final_unit`**(价/量/状态不动);
|
||
* ② 幂等:我方已是该单位 ⇒ `ignored`,不重复写、不刷日志;
|
||
* ③ 安全:缺 `prep_id`/缺 `final_unit`/非 uuid/行对不上 ⇒ `ignored` + 原因,**不猜不建行**;
|
||
* ④ 落点: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,
|
||
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',
|
||
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 / tenant 两侧的桩:link 命中 + 我方当前单位 unitNow */
|
||
function stub(params: { unitNow: string | null; link?: { our_order_code: string | null; our_order_item_id: string | null } | null }) {
|
||
const link = params.link === undefined ? { our_order_code: ORDER, our_order_item_id: ITEM } : params.link;
|
||
query.mockImplementation(async (sql: string) => {
|
||
if (String(sql).includes('FROM public.main_system_order_import_items')) {
|
||
return link ? { rowCount: 1, rows: [link] } : { rowCount: 0, rows: [] };
|
||
}
|
||
if (String(sql).startsWith('UPDATE public.main_system_price_qty_unit_deferred')) return { rowCount: 1, rows: [] };
|
||
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 params.unitNow === null
|
||
? { rowCount: 0, rows: [] }
|
||
: { rowCount: 1, rows: [{ unit: params.unitNow }] };
|
||
}
|
||
return { rowCount: 0, rows: [] };
|
||
},
|
||
})
|
||
);
|
||
return { updates };
|
||
}
|
||
|
||
beforeEach(() => {
|
||
query.mockReset();
|
||
withTenantData.mockReset();
|
||
audit.mockReset();
|
||
audit.mockResolvedValue(undefined);
|
||
});
|
||
|
||
describe('主系统改单位 ⇒ 我方接收端(preparations.unit_changed)', () => {
|
||
it('① 落值:只写 unit = final_unit,价/量/状态不碰,并留一条操作日志', async () => {
|
||
const { updates } = stub({ unitNow: '斤' });
|
||
const out = await applyUnitChangedFact({ branchCode: BRANCH, payload: payload() });
|
||
expect(out.status).toBe('applied');
|
||
expect(out.rowId).toBe(ITEM);
|
||
expect(out.unit).toBe('件');
|
||
expect(updates, '恰好写一次').toHaveLength(1);
|
||
expect(updates[0], '参数 = [order_code, item_id, 新单位]').toEqual([ORDER, ITEM, '件']);
|
||
// 操作日志
|
||
expect(audit).toHaveBeenCalledTimes(1);
|
||
const logged = audit.mock.calls[0][0] as any;
|
||
expect(logged.operationType).toBe('main_system_unit_changed_applied');
|
||
expect(logged.branchCode).toBe(BRANCH);
|
||
expect(logged.oldValue).toEqual({ unit: '斤' });
|
||
expect(logged.newValue.unit).toBe('件');
|
||
expect(logged.newValue.client_request_id).toBe(`uc_${PREP}_斤_件`);
|
||
expect(logged.newValue.source).toBe('admin_prep_edit');
|
||
});
|
||
|
||
it('①b 落值 SQL 只动 unit(源码钉:不得顺手改价/量)', () => {
|
||
const src = readFileSync(path.join(__dirname, '../src/services/mainSystemUnitChangedInbox.ts'), 'utf8');
|
||
expect(src).toContain('UPDATE order_items SET unit = $3');
|
||
expect(src).not.toMatch(/SET unit = \$3[^`]*?(price|quantity)/);
|
||
});
|
||
|
||
it('② 幂等:我方已是该单位 ⇒ ignored(不写、不留痕)', async () => {
|
||
const { updates } = stub({ unitNow: '件' });
|
||
const out = await applyUnitChangedFact({ branchCode: BRANCH, payload: payload() });
|
||
expect(out.status).toBe('ignored');
|
||
expect(String(out.reason)).toContain('幂等跳过');
|
||
expect(updates).toHaveLength(0);
|
||
expect(audit).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('②b 幂等比较对大小写/空白不敏感(他们那边同口径)', async () => {
|
||
const { updates } = stub({ unitNow: ' 件 ' });
|
||
const out = await applyUnitChangedFact({ branchCode: BRANCH, payload: payload({ final_unit: '件' }) });
|
||
expect(out.status).toBe('ignored');
|
||
expect(updates).toHaveLength(0);
|
||
});
|
||
|
||
it('③ 载荷:两个字段名都认(prep_id / unit 别名),before/after value 恒 null 不进结果', () => {
|
||
const mapped = mapUnitChangedPayload(
|
||
payload({ preparation_id: null, final_unit: null, unit: '箱', sku_code: 'SKU1' })
|
||
);
|
||
expect(mapped.prepId).toBe(PREP);
|
||
expect(mapped.finalUnit).toBe('箱');
|
||
expect(mapped.beforeUnit).toBe('斤');
|
||
// 只有单位语义,没有任何"价"字段被采纳
|
||
expect(Object.keys(mapped)).not.toContain('price');
|
||
});
|
||
|
||
it('③b 他们没给 before_unit 也能落值(before 只是留痕字段,不参与判定)', async () => {
|
||
const { updates } = stub({ unitNow: '斤' });
|
||
const out = await applyUnitChangedFact({
|
||
branchCode: BRANCH,
|
||
payload: payload({ before_unit: null, client_request_id: `uc_${PREP}__件` }),
|
||
});
|
||
expect(out.status).toBe('applied');
|
||
expect(updates).toHaveLength(1);
|
||
});
|
||
|
||
it('④ 安全:缺 prep_id / 缺 final_unit / 非 uuid / 行对不上 ⇒ ignored + 原因,不发写', async () => {
|
||
const cases: Array<[Record<string, unknown>, string]> = [
|
||
[{ 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'],
|
||
];
|
||
for (const [override, expected] of cases) {
|
||
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(withTenantData, '前置校验不通过时不该读租户库').not.toHaveBeenCalled();
|
||
}
|
||
|
||
// 行对不上(对照台账没有该 prep / 缺我们的行 id):不猜、不建行
|
||
const { updates } = stub({ unitNow: '斤', link: null });
|
||
const missing = await applyUnitChangedFact({ branchCode: BRANCH, payload: payload() });
|
||
expect(missing.status).toBe('ignored');
|
||
expect(String(missing.reason)).toContain('没有该备货行的对照行');
|
||
expect(updates).toHaveLength(0);
|
||
|
||
const { updates: updates2 } = stub({ unitNow: '斤', link: { our_order_code: ORDER, our_order_item_id: null } });
|
||
const noItem = await applyUnitChangedFact({ branchCode: BRANCH, payload: payload() });
|
||
expect(noItem.status).toBe('ignored');
|
||
expect(updates2).toHaveLength(0);
|
||
});
|
||
|
||
it('④b 我方订单行已不存在 ⇒ ignored(不是 applied)', async () => {
|
||
const { updates } = stub({ unitNow: null });
|
||
const out = await applyUnitChangedFact({ branchCode: BRANCH, payload: payload() });
|
||
expect(out.status).toBe('ignored');
|
||
expect(String(out.reason)).toContain('已不存在');
|
||
expect(updates).toHaveLength(0);
|
||
});
|
||
|
||
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);
|
||
// 分支内 return(就地收口)
|
||
const branchBody = route.slice(branchAt, fallbackAt);
|
||
expect(branchBody).toContain('return res.json({ ok: true, ...applied })');
|
||
});
|
||
});
|