Files
SupplierSystem/server/tests/mainSystemReverseEvents.test.ts
T
Ubuntu f5cf2a8b37
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(主系统对接): 接收反向事件 preparations.reallocated / item_removed / order.cancelled
按 2026-10-17 与主系统确认的契约落地(不改事件名/字段):
· preparations.reallocated:改派后发给**原供应商**,我方把该行从本地单里移除;
· preparations.item_removed:删商品行后移除该行;
· order.cancelled:整单作废,我方**只停用不物理删**(进垃圾桶 + 台账置 cancelled)。

纪律(对方明确要求):
· 可能先收到反向事件、后收到/收不到 E1(E1 受其 auto/manual/scheduled 三档闸门)
  ⇒ 未知 prep_id/未知订单一律**幂等忽略**,不报错、不建数据;
· 幂等按**业务键**(prep_id;E4 按 order_code),**不按 request_id**(对方每次投递都是新 id);
· prep_id 会复用 ⇒ 重复投递第二次为 no-op(already_gone),不会二次红冲;
· 行移除复用既有 removeOrderItemForMainSystemReturn(与退货跟随同一套红冲/释放语义),不新造财务口径;
· 业务失败一律 200(重推解决不了前置;轮询兜底仍在)。

接线:mainSystemIntegration 新增分支,位于 bid.opened 之后、履约事件之前,就地 return(不落建单兜底)。

验证:npx tsc --noEmit 0 错;新增 mainSystemReverseEvents 单测 9 条全过
(未知 prep_id 忽略/零写库、业务键幂等、E4 无 DELETE FROM orders、webhook 分支位置)。
2026-10-17 23:41:17 +08:00

163 lines
7.0 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 { readFileSync } from 'node:fs';
import path from 'node:path';
import { beforeEach, describe, expect, it, vi } from 'vitest';
/**
* 主系统**反向事件**接收端(2026-10-17 与主系统确认的契约):
* `preparations.reallocated` / `preparations.item_removed` / `order.cancelled`。
*
* 对方明确的三条约束,必须钉住:
* ① **可能先收到反向事件、后收到/收不到 E1**(E1 受它们三档发送闸门)⇒ 未知 `prep_id` 幂等忽略、不报错;
* ② **幂等按业务键**(prep_id / order_code),**不按 request_id**(每次投递都是新 id);
* ③ 删单(E4)我方**只停用不物理删**。
*/
const poolQuery = vi.hoisted(() => vi.fn());
vi.mock('../src/db', () => ({
pool: { query: (...args: unknown[]) => poolQuery(...args), connect: vi.fn() },
getRawPoolQuery: () => poolQuery,
}));
const tenantCtx = vi.hoisted(() => vi.fn());
vi.mock('../src/services/tenantDbContext', () => ({
runWithTenantDbContext: (_code: unknown, fn: () => Promise<unknown>) => tenantCtx(fn),
}));
const markPrep = vi.hoisted(() => vi.fn());
vi.mock('../src/services/mainSystemPrepLedger', () => ({
markPrepDisposition: (...args: unknown[]) => markPrep(...args),
}));
const removeItem = vi.hoisted(() => vi.fn());
vi.mock('../src/services/orderManageItemsService', () => ({
removeOrderItemForMainSystemReturn: (...args: unknown[]) => removeItem(...args),
}));
const {
applyItemNoLongerOurs,
applyOrderCancelledByMainSystem,
isReverseOrderEvent,
ITEM_REMOVED_EVENT,
ORDER_CANCELLED_EVENT,
REALLOCATED_EVENT,
} = await import('../src/services/mainSystemReverseEvents');
beforeEach(() => {
poolQuery.mockReset();
tenantCtx.mockReset();
markPrep.mockReset();
removeItem.mockReset();
tenantCtx.mockImplementation(async (fn: () => Promise<unknown>) => fn());
markPrep.mockResolvedValue(undefined);
removeItem.mockResolvedValue('deleted');
});
describe('事件识别', () => {
it('只认三个反向事件', () => {
for (const name of [REALLOCATED_EVENT, ITEM_REMOVED_EVENT, ORDER_CANCELLED_EVENT]) {
expect(isReverseOrderEvent(name)).toBe(true);
}
expect(isReverseOrderEvent('preparations.allocated')).toBe(false);
expect(isReverseOrderEvent('order.restored')).toBe(false);
expect(isReverseOrderEvent(undefined)).toBe(false);
});
});
describe('① 未知 prep_id ⇒ 幂等忽略,不写任何东西', () => {
it('台账查不到该 prep_id 就返回 ignored,且不处置、不移除', async () => {
poolQuery.mockResolvedValue({ rows: [], rowCount: 0 });
const outcome = await applyItemNoLongerOurs({ branchCode: 'BR002', prepId: 'prep-x', reason: 'reallocated' });
expect(outcome.status).toBe('ignored');
expect(markPrep).not.toHaveBeenCalled();
expect(removeItem).not.toHaveBeenCalled();
});
it('定位不到行级台账时不建任何数据(只读一次台账,无写库)', async () => {
poolQuery.mockResolvedValue({ rows: [], rowCount: 0 });
await applyItemNoLongerOurs({ branchCode: 'BR002', prepId: 'prep-x', reason: 'item_removed' });
const sqls = poolQuery.mock.calls.map(([sql]: [string]) => String(sql));
expect(sqls.every((sql: string) => /SELECT/i.test(sql))).toBe(true);
});
});
describe('② 幂等按业务键 prep_id(不是 request_id)', () => {
it('命中台账 ⇒ 先置 disposition=cancelled(下一轮导入不会复活)再移除该行', async () => {
poolQuery.mockResolvedValue({
rows: [{ our_order_code: 'ORD_API_1', our_order_item_id: 'item-1' }],
rowCount: 1,
});
const outcome = await applyItemNoLongerOurs({
branchCode: 'BR002',
prepId: 'prep-1',
reason: 'reallocated',
mainOrderCode: 'ORD_WEB_1',
});
expect(outcome.status).toBe('removed');
expect(markPrep).toHaveBeenCalledWith(
expect.objectContaining({ prepId: 'prep-1', disposition: 'cancelled' })
);
expect(removeItem).toHaveBeenCalledWith(
expect.objectContaining({ orderCode: 'ORD_API_1', itemId: 'item-1' })
);
});
it('重复投递(第二次)⇒ already_gone(行已不在),不会二次红冲', async () => {
poolQuery.mockResolvedValue({
rows: [{ our_order_code: 'ORD_API_1', our_order_item_id: null }],
rowCount: 1,
});
const outcome = await applyItemNoLongerOurs({ branchCode: 'BR002', prepId: 'prep-1', reason: 'item_removed' });
expect(outcome.status).toBe('already_gone');
expect(removeItem).not.toHaveBeenCalled();
});
it('服务里完全不出现 request_id(幂等键只有业务键)', () => {
const source = readFileSync(path.join(__dirname, '../src/services/mainSystemReverseEvents.ts'), 'utf8');
// 只看代码行(注释里明确写了"不要用 request_id 去重",不算违规)
const codeOnly = source
.split('\n')
.filter((line) => !/^\s*(\*|\/\/|\/\*)/.test(line))
.join('\n');
expect(codeOnly).not.toMatch(/request_id/);
});
});
describe('③ 删单(E4):只停用、不物理删', () => {
it('不是主系统单(台账无对照)⇒ ignored', async () => {
poolQuery.mockResolvedValue({ rows: [], rowCount: 0 });
const outcome = await applyOrderCancelledByMainSystem({ branchCode: 'BR002', orderCode: 'ORD_X', reason: 'x' });
expect(outcome.status).toBe('ignored');
});
it('主系统单 ⇒ 写 deleted_at + cancel_reason,台账置 cancelled;全程无 DELETE FROM orders', async () => {
poolQuery.mockImplementation(async (sql: string) => {
if (/SELECT DISTINCT msi\.main_order_code/i.test(sql)) {
return { rows: [{ main_order_code: 'ORD_WEB_1' }], rowCount: 1 };
}
if (/UPDATE orders/i.test(sql)) return { rows: [], rowCount: 1 };
return { rows: [], rowCount: 0 };
});
const outcome = await applyOrderCancelledByMainSystem({
branchCode: 'BR002',
orderCode: 'ORD_API_1',
reason: '客户取消',
});
expect(outcome.status).toBe('cancelled');
const sqls = poolQuery.mock.calls.map(([sql]: [string]) => String(sql));
expect(sqls.some((sql: string) => /UPDATE orders[\s\S]*deleted_at = COALESCE\(deleted_at, NOW\(\)\)/i.test(sql))).toBe(true);
expect(sqls.some((sql: string) => /UPDATE public\.main_system_order_import_items[\s\S]*cancelled/i.test(sql))).toBe(true);
expect(sqls.some((sql: string) => /DELETE\s+FROM\s+orders/i.test(sql))).toBe(false);
});
});
describe('④ webhook 接线', () => {
it('反向事件分支在履约事件之前、且就地 return(不落到建单兜底)', () => {
const routes = readFileSync(path.join(__dirname, '../src/routes/mainSystemIntegration.ts'), 'utf8');
const start = routes.indexOf('if (isReverseOrderEvent(event))');
expect(start).toBeGreaterThan(-1);
const tail = routes.slice(start);
const end = tail.indexOf("if (isFulfillmentEvent(event))");
const block = tail.slice(0, end);
expect(block).toMatch(/return res\.json\(/);
expect(block).not.toMatch(/importMainSystemGroups/);
expect(block).toMatch(/applyItemNoLongerOurs/);
expect(block).toMatch(/applyOrderCancelledByMainSystem/);
});
});