- T1 资金/库存/报价/自采 P1(BIZ-1/2/3/4/10/13/14) - T2 主系统反向事件墓碑/改派/孤儿处理(BIZ-6/8/9) - T3 选分公司 ticket、trust proxy、角色权限收口(SEC-2/3/4) - T4 缺列/RLS/tenant 名单/FK/迁移执行器(DATA-1..8) - T5 401 登出/分页/映射口径/blob/ZIP 中文名(FE-1..4/BIZ-15) - T6 测试脚本目标守卫/config fail-fast/容器配置(OPS-2..8) - T7 前后端测试与 lint 门禁清零 - T8 应付卡片按关联订单日(口径 A) - T9 存储对象全链路归属校验、敏感列禁写、审计 target_id 超长修复
491 lines
23 KiB
TypeScript
491 lines
23 KiB
TypeScript
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 recalcHeader = vi.hoisted(() => vi.fn());
|
||
vi.mock('../src/services/mainSystemStockout', async (importOriginal) => {
|
||
const actual = await importOriginal<typeof import('../src/services/mainSystemStockout')>();
|
||
return { ...actual, recalcOrderHeaderTotals: (...args: unknown[]) => recalcHeader(...args) };
|
||
});
|
||
const clearDayPointer = vi.hoisted(() => vi.fn());
|
||
vi.mock('../src/services/mirrorOrderClosureService', () => ({
|
||
clearDayPointerIfPointsTo: (...args: unknown[]) => clearDayPointer(...args),
|
||
}));
|
||
const notifyRoleUsers = vi.hoisted(() => vi.fn());
|
||
vi.mock('../src/services/notificationService', () => ({
|
||
notifyRoleUsers: (...args: unknown[]) => notifyRoleUsers(...args),
|
||
}));
|
||
|
||
const {
|
||
applyItemNoLongerOurs,
|
||
applyOrderCancelledByMainSystem,
|
||
isReverseOrderEvent,
|
||
purgeReverseTombstones,
|
||
recordReverseTombstone,
|
||
ITEM_REMOVED_EVENT,
|
||
ORDER_CANCELLED_EVENT,
|
||
REALLOCATED_EVENT,
|
||
} = await import('../src/services/mainSystemReverseEvents');
|
||
|
||
beforeEach(() => {
|
||
poolQuery.mockReset();
|
||
tenantCtx.mockReset();
|
||
markPrep.mockReset();
|
||
removeItem.mockReset();
|
||
recalcHeader.mockReset();
|
||
recalcHeader.mockResolvedValue(undefined);
|
||
clearDayPointer.mockReset();
|
||
clearDayPointer.mockResolvedValue(0);
|
||
notifyRoleUsers.mockReset();
|
||
notifyRoleUsers.mockResolvedValue(undefined);
|
||
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 ⇒ 落持久墓碑 + 幂等忽略(BIZ-6)', () => {
|
||
it('台账查不到该 prep_id ⇒ 返回 ignored,同时写一条 prep 墓碑(ON CONFLICT DO UPDATE 合并 reason)', async () => {
|
||
poolQuery.mockResolvedValue({ rows: [], rowCount: 0 });
|
||
const outcome = await applyItemNoLongerOurs({
|
||
branchCode: 'BR002',
|
||
prepId: 'PREP-X',
|
||
reason: 'reallocated',
|
||
mainOrderCode: 'ORD_WEB_1',
|
||
});
|
||
expect(outcome.status).toBe('ignored');
|
||
expect(markPrep).not.toHaveBeenCalled();
|
||
expect(removeItem).not.toHaveBeenCalled();
|
||
const tombstone = poolQuery.mock.calls.find(([sql]: [string]) =>
|
||
/INSERT INTO public\.main_system_reverse_tombstones/i.test(String(sql))
|
||
);
|
||
expect(tombstone, '未知 prep_id 必须落墓碑,否则 E1 之后到达会把已删的行建回来').toBeTruthy();
|
||
expect(String(tombstone![0])).toMatch(/ON CONFLICT \(branch_code, kind, business_key\) DO UPDATE/);
|
||
// prep 业务键统一小写(UUID 大小写无关)
|
||
expect(tombstone![1]).toEqual(['BR002', 'prep', 'prep-x', 'reallocated', expect.any(String)]);
|
||
});
|
||
|
||
it('重复投递 ⇒ 墓碑幂等不重复(同 key 只一行)', async () => {
|
||
const rows: Array<{ key: string }> = [];
|
||
poolQuery.mockImplementation(async (sql: string, params: unknown[] = []) => {
|
||
const text = String(sql);
|
||
if (/INSERT INTO public\.main_system_reverse_tombstones/i.test(text) && text.includes('ON CONFLICT')) {
|
||
const key = `${params[0]}|${params[1]}|${params[2]}`;
|
||
if (!rows.some((row) => row.key === key)) rows.push({ key });
|
||
return { rows: [], rowCount: 1 };
|
||
}
|
||
return { rows: [], rowCount: 0 };
|
||
});
|
||
await applyItemNoLongerOurs({ branchCode: 'BR002', prepId: 'prep-x', reason: 'reallocated' });
|
||
await applyItemNoLongerOurs({ branchCode: 'BR002', prepId: 'prep-x', reason: 'reallocated' });
|
||
expect(rows).toHaveLength(1);
|
||
});
|
||
|
||
it('正常路径命中台账 ⇒ 不写墓碑(已有正常路径不变)', async () => {
|
||
poolQuery.mockImplementation(async (sql: string) => {
|
||
if (/FROM public\.main_system_order_import_items/i.test(String(sql))) {
|
||
return { rows: [{ our_order_code: 'ORD_API_1', our_order_item_id: null }], rowCount: 1 };
|
||
}
|
||
return { rows: [], rowCount: 0 };
|
||
});
|
||
const outcome = await applyItemNoLongerOurs({ branchCode: 'BR002', prepId: 'prep-1', reason: 'item_removed' });
|
||
expect(outcome.status).toBe('already_gone');
|
||
const tombstone = poolQuery.mock.calls.find(([sql]: [string]) =>
|
||
/INSERT INTO public\.main_system_reverse_tombstones/i.test(String(sql))
|
||
);
|
||
expect(tombstone).toBeUndefined();
|
||
});
|
||
});
|
||
|
||
describe('② 幂等按业务键 prep_id(不是 request_id)', () => {
|
||
it('命中台账 ⇒ 先置 disposition=reallocated(下一轮导入不会复活)再移除该行', { timeout: 10000 }, 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');
|
||
// BIZ-9:改派写 reallocated(可复活),删行写 removed(硬删阻断)
|
||
expect(markPrep).toHaveBeenCalledWith(
|
||
expect.objectContaining({ prepId: 'prep-1', disposition: 'reallocated' })
|
||
);
|
||
expect(removeItem).toHaveBeenCalledWith(
|
||
expect.objectContaining({ orderCode: 'ORD_API_1', itemId: 'item-1' })
|
||
);
|
||
// 删行后必须重算订单头,否则订单列表金额仍是旧值
|
||
expect(recalcHeader).toHaveBeenCalledWith({ branchCode: 'BR002', orderCode: 'ORD_API_1' });
|
||
});
|
||
|
||
it('item_removed(硬删)⇒ disposition=removed,与改派区分(BIZ-9)', 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: 'item_removed' });
|
||
expect(outcome.status).toBe('removed');
|
||
expect(markPrep).toHaveBeenCalledWith(
|
||
expect.objectContaining({ prepId: 'prep-1', disposition: 'removed' })
|
||
);
|
||
});
|
||
|
||
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();
|
||
expect(recalcHeader).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('B2:重复 item_removed 且目标行已被删(移除函数 404)⇒ already_gone,不抛出 500', async () => {
|
||
poolQuery.mockImplementation(async (sql: string) => {
|
||
if (/FROM public\.main_system_order_import_items/i.test(String(sql))) {
|
||
return { rows: [{ our_order_code: 'ORD_API_1', our_order_item_id: 'item-gone' }], rowCount: 1 };
|
||
}
|
||
return { rows: [], rowCount: 0 };
|
||
});
|
||
removeItem.mockRejectedValueOnce(
|
||
Object.assign(new Error('订单明细不存在或不属于该订单'), { status: 404, code: 'not_found' })
|
||
);
|
||
const outcome = await applyItemNoLongerOurs({ branchCode: 'BR002', prepId: 'prep-1', reason: 'item_removed' });
|
||
expect(outcome.status).toBe('already_gone');
|
||
// 台账处置仍然落(removed 优先级),不能因重复事件回滚
|
||
expect(markPrep).toHaveBeenCalledWith(expect.objectContaining({ disposition: 'removed' }));
|
||
});
|
||
|
||
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,且落 order 墓碑(BIZ-6)', async () => {
|
||
poolQuery.mockResolvedValue({ rows: [], rowCount: 0 });
|
||
const outcome = await applyOrderCancelledByMainSystem({ branchCode: 'BR002', orderCode: 'ORD_WEB_X', reason: 'x' });
|
||
expect(outcome.status).toBe('ignored');
|
||
const tombstone = poolQuery.mock.calls.find(([sql]: [string]) =>
|
||
/INSERT INTO public\.main_system_reverse_tombstones/i.test(String(sql))
|
||
);
|
||
expect(tombstone, '未知订单必须落 order 墓碑,否则 E1 之后到达会把它建回来').toBeTruthy();
|
||
expect(tombstone![1]).toEqual(['BR002', 'order', 'ORD_WEB_X', 'x', expect.any(String)]);
|
||
});
|
||
|
||
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');
|
||
// 停用后必须清当日占坑指针,否则下一批同日分配会往垃圾桶里的单追加
|
||
expect(clearDayPointer).toHaveBeenCalledWith('BR002', 'ORD_API_1');
|
||
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);
|
||
});
|
||
|
||
it('合并单:主系统只删 A ⇒ 只移除 A 的行,B 还在就**不得**软删整张我方单', async () => {
|
||
poolQuery.mockImplementation(async (sql: string) => {
|
||
if (/SELECT DISTINCT msi\.main_order_code/i.test(sql)) {
|
||
return { rows: [{ main_order_code: 'ORD_WEB_A', our_order_code: 'ORD_API_X' }], rowCount: 1 };
|
||
}
|
||
if (/SELECT order_code, order_status FROM orders/i.test(sql)) {
|
||
return { rows: [{ order_code: 'ORD_API_X', order_status: 40 }], rowCount: 1 };
|
||
}
|
||
if (/COUNT\(\*\)::int AS n/i.test(sql)) {
|
||
// B 的行仍在,且是**有来源**的行(其它主系统单/台账指向)⇒ 不得停用
|
||
return { rows: [{ order_code: 'ORD_API_X', n: 1, sourced_n: 1 }], rowCount: 1 };
|
||
}
|
||
if (/FROM order_items oi/i.test(sql)) {
|
||
return { rows: [{ id: 'item-A', order_code: 'ORD_API_X' }], rowCount: 1 };
|
||
}
|
||
if (/UPDATE orders/i.test(sql)) return { rows: [], rowCount: 1 };
|
||
return { rows: [], rowCount: 0 };
|
||
});
|
||
|
||
const outcome = await applyOrderCancelledByMainSystem({
|
||
branchCode: 'BR002',
|
||
orderCode: 'ORD_WEB_A',
|
||
reason: '主系统只删 A',
|
||
});
|
||
|
||
expect(outcome.status).toBe('already');
|
||
expect(removeItem).toHaveBeenCalledTimes(1);
|
||
expect(removeItem).toHaveBeenCalledWith(
|
||
expect.objectContaining({ orderCode: 'ORD_API_X', itemId: 'item-A' })
|
||
);
|
||
// 合并单保留时,订单头也必须按剩余行重算(否则列表金额仍含已删的 A 行)
|
||
expect(recalcHeader).toHaveBeenCalledWith({ branchCode: 'BR002', orderCode: 'ORD_API_X' });
|
||
// 订单还在 ⇒ 占坑指针不得清
|
||
expect(clearDayPointer).not.toHaveBeenCalled();
|
||
const sqls = poolQuery.mock.calls.map(([sql]: [string]) => String(sql));
|
||
expect(sqls.some((sql: string) => /UPDATE orders/i.test(sql))).toBe(false);
|
||
// A 的台账仍要置 cancelled(避免 A 被重新导入),但 B 的行不受影响
|
||
expect(sqls.some((sql: string) => /UPDATE public\.main_system_order_import_items/i.test(sql))).toBe(true);
|
||
});
|
||
|
||
it('已完成(90):整单删除 ⇒ 明细/订单/台账零改动,只留痕', async () => {
|
||
poolQuery.mockImplementation(async (sql: string) => {
|
||
if (/SELECT DISTINCT msi\.main_order_code/i.test(sql)) {
|
||
return { rows: [{ main_order_code: 'ORD_WEB_DONE', our_order_code: 'ORD_API_DONE' }], rowCount: 1 };
|
||
}
|
||
if (/SELECT order_code, order_status FROM orders/i.test(sql)) {
|
||
return { rows: [{ order_code: 'ORD_API_DONE', order_status: 90 }], rowCount: 1 };
|
||
}
|
||
return { rows: [], rowCount: 0 };
|
||
});
|
||
|
||
const outcome = await applyOrderCancelledByMainSystem({
|
||
branchCode: 'BR002',
|
||
orderCode: 'ORD_WEB_DONE',
|
||
reason: '主系统删单',
|
||
});
|
||
|
||
expect(outcome.status).toBe('skipped_completed');
|
||
expect(removeItem).not.toHaveBeenCalled();
|
||
expect(recalcHeader).not.toHaveBeenCalled();
|
||
expect(clearDayPointer).not.toHaveBeenCalled();
|
||
const sqls = poolQuery.mock.calls.map(([sql]: [string]) => String(sql));
|
||
expect(sqls.some((sql: string) => /UPDATE orders/i.test(sql))).toBe(false);
|
||
expect(sqls.some((sql: string) => /DELETE FROM order_items/i.test(sql))).toBe(false);
|
||
expect(sqls.some((sql: string) => /UPDATE public\.main_system_order_import_items/i.test(sql))).toBe(false);
|
||
// 只留痕:写一条 operation_logs(不是改业务数据)
|
||
expect(
|
||
poolQuery.mock.calls.some(
|
||
([sql, params]: [string, unknown[]]) =>
|
||
/INSERT INTO operation_logs/i.test(String(sql)) &&
|
||
JSON.stringify(params || []).includes('no_change_completed')
|
||
)
|
||
).toBe(true);
|
||
});
|
||
|
||
it('未完成且已无有效明细 ⇒ 停用订单(保留原有整单收口行为)', async () => {
|
||
poolQuery.mockImplementation(async (sql: string) => {
|
||
if (/SELECT DISTINCT msi\.main_order_code/i.test(sql)) {
|
||
return { rows: [{ main_order_code: 'ORD_WEB_ONLY', our_order_code: 'ORD_API_ONLY' }], rowCount: 1 };
|
||
}
|
||
if (/SELECT order_code, order_status FROM orders/i.test(sql)) {
|
||
return { rows: [{ order_code: 'ORD_API_ONLY', order_status: 40 }], rowCount: 1 };
|
||
}
|
||
if (/FROM order_items oi/i.test(sql)) {
|
||
return { rows: [{ id: 'item-1', order_code: 'ORD_API_ONLY' }], rowCount: 1 };
|
||
}
|
||
if (/COUNT\(\*\)::int AS n/i.test(sql)) return { rows: [], rowCount: 0 };
|
||
if (/UPDATE orders/i.test(sql)) return { rows: [], rowCount: 1 };
|
||
return { rows: [], rowCount: 0 };
|
||
});
|
||
|
||
const outcome = await applyOrderCancelledByMainSystem({
|
||
branchCode: 'BR002',
|
||
orderCode: 'ORD_WEB_ONLY',
|
||
reason: '主系统删单',
|
||
});
|
||
expect(outcome.status).toBe('cancelled');
|
||
expect(clearDayPointer).toHaveBeenCalledWith('BR002', 'ORD_API_ONLY');
|
||
const update = poolQuery.mock.calls.find(([sql]: [string]) => /UPDATE orders/i.test(String(sql)));
|
||
expect(update?.[1]?.[0]).toEqual(['ORD_API_ONLY']);
|
||
});
|
||
|
||
/**
|
||
* BIZ-8 / D5 策略 A:整单删后只剩 orphan(2 行)——旧实现认为"还有行"就不停用 ⇒
|
||
* 台账仍指向这张单,下一轮导入把它当有效单追加 ⇒ 订单永久卡死。
|
||
* 新口径:停用订单,但 **保留 orphan 行原样**(不物理删、不红冲)+ operation_logs + 通知 + 清占坑。
|
||
*/
|
||
it('全删且只剩 orphan(2 行)⇒ 停用订单、orphan 行保留、留痕+通知+清占坑', async () => {
|
||
poolQuery.mockImplementation(async (sql: string) => {
|
||
const text = String(sql);
|
||
if (/SELECT DISTINCT msi\.main_order_code/i.test(text)) {
|
||
return { rows: [{ main_order_code: 'ORD_WEB_A', our_order_code: 'ORD_API_ORPHAN' }], rowCount: 1 };
|
||
}
|
||
if (/SELECT order_code, order_status FROM orders/i.test(text)) {
|
||
return { rows: [{ order_code: 'ORD_API_ORPHAN', order_status: 40 }], rowCount: 1 };
|
||
}
|
||
if (/sourced_n/i.test(text)) {
|
||
// 剩余 2 行,全是 orphan(无 main_order_code / 不被台账指向)
|
||
return { rows: [{ order_code: 'ORD_API_ORPHAN', n: 2, sourced_n: 0 }], rowCount: 1 };
|
||
}
|
||
if (/FROM order_items oi/i.test(text)) {
|
||
// 被取消主系统单的"有来源"行已无(移除清单为空)
|
||
return { rows: [], rowCount: 0 };
|
||
}
|
||
if (/UPDATE orders/i.test(text)) return { rows: [], rowCount: 1 };
|
||
return { rows: [], rowCount: 0 };
|
||
});
|
||
|
||
const outcome = await applyOrderCancelledByMainSystem({
|
||
branchCode: 'BR002',
|
||
orderCode: 'ORD_WEB_A',
|
||
reason: '主系统删单(只剩孤儿)',
|
||
});
|
||
|
||
expect(outcome.status).toBe('cancelled');
|
||
// 订单被停用 + 清当日占坑指针
|
||
expect(clearDayPointer).toHaveBeenCalledWith('BR002', 'ORD_API_ORPHAN');
|
||
// orphan 行保留:不得物理删/更新 order_items
|
||
const sqls = poolQuery.mock.calls.map(([sql]: [string]) => String(sql));
|
||
expect(sqls.some((sql) => /DELETE\s+FROM\s+order_items/i.test(sql))).toBe(false);
|
||
expect(sqls.some((sql) => /UPDATE\s+order_items/i.test(sql))).toBe(false);
|
||
// operation_logs 留痕(含订单号/orphan 行数)
|
||
expect(
|
||
poolQuery.mock.calls.some(
|
||
([sql, params]: [string, unknown[]]) =>
|
||
/INSERT INTO operation_logs/i.test(String(sql)) &&
|
||
JSON.stringify(params || []).includes('main_system_order_deleted_orphans_kept') &&
|
||
JSON.stringify(params || []).includes('ORD_API_ORPHAN')
|
||
)
|
||
).toBe(true);
|
||
// 通知 admin/operator:N 行无来源需人工确认
|
||
expect(notifyRoleUsers).toHaveBeenCalledWith(
|
||
expect.objectContaining({
|
||
roles: ['admin', 'operator'],
|
||
notifyType: 'main_system_order_deleted_orphans_kept',
|
||
content: expect.stringContaining('2 行无来源'),
|
||
})
|
||
);
|
||
});
|
||
|
||
it('剩余行含**有来源**行(sourced_n>0)⇒ 保持当前"不停用"(合并单场景,BIZ-8 反例)', async () => {
|
||
poolQuery.mockImplementation(async (sql: string) => {
|
||
const text = String(sql);
|
||
if (/SELECT DISTINCT msi\.main_order_code/i.test(text)) {
|
||
return { rows: [{ main_order_code: 'ORD_WEB_A', our_order_code: 'ORD_API_MIX' }], rowCount: 1 };
|
||
}
|
||
if (/SELECT order_code, order_status FROM orders/i.test(text)) {
|
||
return { rows: [{ order_code: 'ORD_API_MIX', order_status: 40 }], rowCount: 1 };
|
||
}
|
||
if (/sourced_n/i.test(text)) {
|
||
return { rows: [{ order_code: 'ORD_API_MIX', n: 2, sourced_n: 1 }], rowCount: 1 };
|
||
}
|
||
if (/FROM order_items oi/i.test(text)) return { rows: [], rowCount: 0 };
|
||
if (/UPDATE orders/i.test(text)) return { rows: [], rowCount: 1 };
|
||
return { rows: [], rowCount: 0 };
|
||
});
|
||
|
||
const outcome = await applyOrderCancelledByMainSystem({
|
||
branchCode: 'BR002',
|
||
orderCode: 'ORD_WEB_A',
|
||
reason: '合并单只删 A(B 有来源)',
|
||
});
|
||
|
||
expect(outcome.status).toBe('already');
|
||
expect(clearDayPointer).not.toHaveBeenCalled();
|
||
const sqls = poolQuery.mock.calls.map(([sql]: [string]) => String(sql));
|
||
expect(sqls.some((sql) => /UPDATE orders/i.test(sql))).toBe(false);
|
||
});
|
||
});
|
||
|
||
describe('④ 墓碑清理(D6:只提供导出 + 单测,不接定时任务)', () => {
|
||
it('purgeReverseTombstones(days) 按 created_at 删除旧墓碑并返回行数', async () => {
|
||
poolQuery.mockResolvedValue({ rows: [], rowCount: 3 });
|
||
const deleted = await purgeReverseTombstones(30);
|
||
expect(deleted).toBe(3);
|
||
const call = poolQuery.mock.calls.find(([sql]: [string]) =>
|
||
/DELETE FROM public\.main_system_reverse_tombstones/i.test(String(sql))
|
||
);
|
||
expect(call).toBeTruthy();
|
||
expect(String(call![0])).toContain('created_at < NOW() - make_interval(days => $1::int)');
|
||
expect(call![1]).toEqual([30]);
|
||
});
|
||
|
||
it('null/undefined/NaN/负值 ⇒ 抛错且不查库(Number(null)=0 绝不能当"删 0 天"清空全部)', async () => {
|
||
for (const bad of [null, undefined, Number.NaN, -1] as unknown as number[]) {
|
||
await expect(purgeReverseTombstones(bad)).rejects.toThrow();
|
||
}
|
||
expect(poolQuery).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('0 天是合法值(显式清全部历史),仍按 SQL 删除', async () => {
|
||
poolQuery.mockResolvedValue({ rows: [], rowCount: 2 });
|
||
expect(await purgeReverseTombstones(0)).toBe(2);
|
||
const call = poolQuery.mock.calls.find(([sql]: [string]) =>
|
||
/DELETE FROM public\.main_system_reverse_tombstones/i.test(String(sql))
|
||
);
|
||
expect(call![1]).toEqual([0]);
|
||
});
|
||
|
||
it('recordReverseTombstone 幂等写入(ON CONFLICT DO UPDATE)', async () => {
|
||
poolQuery.mockResolvedValue({ rows: [], rowCount: 0 });
|
||
await recordReverseTombstone({ branchCode: 'BR002', kind: 'prep', businessKey: 'ABCD-UUID', reason: 'item_removed' });
|
||
const call = poolQuery.mock.calls.find(([sql]: [string]) =>
|
||
/INSERT INTO public\.main_system_reverse_tombstones/i.test(String(sql))
|
||
);
|
||
expect(call).toBeTruthy();
|
||
expect(String(call![0])).toContain('ON CONFLICT (branch_code, kind, business_key) DO UPDATE');
|
||
expect(call![1][1]).toBe('prep');
|
||
expect(call![1][2]).toBe('abcd-uuid');
|
||
});
|
||
});
|
||
|
||
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/);
|
||
});
|
||
});
|