Files
SupplierSystem/server/tests/mainSystemReverseEvents.test.ts
T
Ubuntu c677908267
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
fix(主系统对接): order.cancelled 按主系统单号反查我方单(原来查不到 ⇒ ignored,订单与商品残留)
生产真机:载荷 order_code=ORD_WEB_…(主系统单号),旧实现按 our_order_code=该值查台账 ⇒ 0 行 ⇒ ignored。
改为 main_order_code=载荷单号(兼容传我方单号)反查到我方单(可能多张合并单),再逐单清行+停用+台账 cancelled。
2026-10-18 22:41:12 +08:00

164 lines
7.1 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)) {
// 载荷里的 order_code 是**主系统**单号;台账据此反查我方单号
return { rows: [{ main_order_code: 'ORD_WEB_1', our_order_code: 'ORD_API_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/);
});
});