Files
SupplierSystem/server/tests/t2TombstoneImportBoundary.test.ts
T
Ubuntu 5fa2bbfd55
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(audit-20261019): T1-T9 审计修复、存储归属与审计日志列宽
- 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 超长修复
2026-10-19 16:16:51 +08:00

260 lines
12 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 { beforeEach, describe, expect, it, vi } from 'vitest';
/**
* T2 独立边界复测 · 墓碑幂等 + 导入过滤(2026-10-19,tester)。
*
* 与 dev 的 `mainSystemTombstoneImport.test.ts` / `mainSystemReverseEvents.test.ts` 独立:
* 本文件用一个**带 UNIQUE + CHECK 语义的假墓碑表**直接钉 `recordReverseTombstone` /
* `listReverseTombstoneKeys`,再独立钉导入侧过滤的 4 个边界:
* a) 同一 prep/order 重复写两次 ⇒ 表里 1 行;大小写/空白归一;非法 kind 不落库;
* b) order 墓碑 ⇒ 整组 0 建单;prep 墓碑 ⇒ 仅该行不追加;无墓碑 ⇒ 行为不变;
* 墓碑查询抛错 ⇒ 导入不被阻断。
*/
const H = vi.hoisted(() => ({
poolQuery: vi.fn(),
listTombstones: vi.fn(),
realList: null as null | ((input: unknown) => Promise<Set<string>>),
submit: vi.fn(),
withTenantDataAccess: vi.fn(),
tenantCtx: vi.fn(),
}));
vi.mock('../src/db', () => ({
pool: { query: (...args: unknown[]) => H.poolQuery(...args), connect: vi.fn() },
query: (...args: unknown[]) => H.poolQuery(...args),
getRawPoolQuery: () => H.poolQuery,
}));
vi.mock('../src/services/tenantDbContext', () => ({
runWithTenantDbContext: (_code: unknown, fn: () => Promise<unknown>) => H.tenantCtx(fn),
}));
vi.mock('../src/services/tenantSchemaService', async (importOriginal) => {
const actual = await importOriginal<typeof import('../src/services/tenantSchemaService')>();
return {
...actual,
runWithTenantDataAccess: (...args: unknown[]) => H.withTenantDataAccess(...args),
resolveActiveTenantSchema: async () => 'tenant_br002',
};
});
vi.mock('../src/services/customerOrderSubmitService', () => ({
submitMobileCustomerOrder: (...args: unknown[]) => H.submit(...args),
}));
// 导入侧只从 reverseEvents 取 listReverseTombstoneKeys;把它可控化(含"抛错"场景)
vi.mock('../src/services/mainSystemReverseEvents', async (importOriginal) => {
const actual = await importOriginal<typeof import('../src/services/mainSystemReverseEvents')>();
H.realList = actual.listReverseTombstoneKeys;
return {
...actual,
listReverseTombstoneKeys: (...args: unknown[]) => H.listTombstones(...args),
};
});
import {
recordReverseTombstone,
listReverseTombstoneKeys,
} from '../src/services/mainSystemReverseEvents';
import {
filterTombstonedGroups,
importMainSystemGroups,
type MainOrderGroup,
} from '../src/services/mainSystemOrderImport';
type TableRow = { branch: string; kind: string; key: string; reason: string | null };
const state = { rows: [] as TableRow[] };
/** 假墓碑表:CHECK(kind IN ('prep','order')) + UNIQUE(branch,kind,key) + ON CONFLICT DO NOTHING */
function installTombstoneTable(): void {
H.poolQuery.mockReset();
H.poolQuery.mockImplementation(async (sql: string, params: unknown[] = []) => {
const text = String(sql);
if (/INSERT INTO public\.main_system_reverse_tombstones/i.test(text)) {
const [branch, kind, key, reason] = params as [string, string, string, string | null];
if (kind !== 'prep' && kind !== 'order') {
// 与迁移里的 CHECK 约束同义:非法 kind 必须被数据库拒绝(不得静默落库)
throw new Error('new row violates check constraint "main_system_reverse_tombstones_kind_check"');
}
const hard = (value: string | null) =>
['item_removed', 'deleted', 'removed'].includes(String(value || '').toLowerCase());
const existing = state.rows.find((r) => r.branch === branch && r.kind === kind && r.key === key);
if (!existing) {
state.rows.push({ branch, kind, key, reason });
return { rows: [], rowCount: 1 };
}
// 2026-10-19 T2 攻破 A:ON CONFLICT DO UPDATE 按 reason 优先级合并(硬删优先,reallocated 不降级)
if (/DO UPDATE/i.test(text)) {
if (hard(reason)) existing.reason = reason;
else if (!hard(existing.reason) && reason !== null) existing.reason = reason;
}
return { rows: [], rowCount: 1 };
}
if (/SELECT business_key FROM public\.main_system_reverse_tombstones/i.test(text)) {
const [branch, kind, keys] = params as [string, string, string[]];
const hit = state.rows
.filter((r) => r.branch === branch && r.kind === kind && keys.includes(r.key))
.map((r) => r.key);
return { rows: hit.map((key) => ({ business_key: key })), rowCount: hit.length };
}
return { rows: [], rowCount: 0 };
});
}
function group(orderCode: string, prepIds: string[]): MainOrderGroup {
return {
orderCode,
deliveryDate: '2026-10-21',
taskDay: '2026-10-21',
rows: prepIds.map((id, index) => ({
id,
itemName: `T2商品${index}`,
prepareQty: 1,
isStockout: false,
})) as unknown as MainOrderGroup['rows'],
};
}
beforeEach(() => {
state.rows = [];
H.poolQuery.mockReset();
H.listTombstones.mockReset();
H.listTombstones.mockImplementation((...args: unknown[]) => H.realList!(args[0] as never));
H.submit.mockReset();
H.tenantCtx.mockReset();
H.withTenantDataAccess.mockReset();
installTombstoneTable();
H.submit.mockResolvedValue({ order_code: 'ORD_API_T2', zero_price_count: 0, new_products_created: 0 });
H.tenantCtx.mockImplementation(async (fn: () => Promise<unknown>) => fn());
H.withTenantDataAccess.mockImplementation(async (_code: string, fn: (client: unknown) => Promise<unknown>) =>
fn({ query: async (sql: string, params: unknown[] = []) => H.poolQuery(sql, params) })
);
});
/* ── a) 墓碑幂等 / 归一 / 非法 kind ─────────────────────────────────────── */
describe('T2a:墓碑写入幂等与键归一', () => {
it('同一 prep 重复写两次(大小写/空白不同)⇒ 表里 1 行,键统一小写去空白', async () => {
await recordReverseTombstone({ branchCode: 'BR002', kind: 'prep', businessKey: ' ABCD-1234 ', reason: 'reallocated' });
await recordReverseTombstone({ branchCode: 'BR002', kind: 'prep', businessKey: 'abcd-1234', reason: 'item_removed' });
expect(state.rows).toHaveLength(1);
expect(state.rows[0]).toMatchObject({ branch: 'BR002', kind: 'prep', key: 'abcd-1234' });
// 2026-10-19 T2 攻破 A:第二次写 item_removed 必须**升级**为硬删(旧实现 DO NOTHING 保留 reallocated 是缺陷)
expect(state.rows[0].reason).toBe('item_removed');
const inserts = H.poolQuery.mock.calls.filter(([sql]: [string]) =>
/INSERT INTO public\.main_system_reverse_tombstones/i.test(String(sql))
);
expect(inserts).toHaveLength(2);
expect(inserts[0][1][2]).toBe('abcd-1234'); // 落库前已归一
expect(String(inserts[0][0])).toMatch(/ON CONFLICT \(branch_code, kind, business_key\) DO UPDATE/);
});
it('order 键只 trim、不改大小写(主系统单号大小写敏感)', async () => {
await recordReverseTombstone({ branchCode: 'BR002', kind: 'order', businessKey: ' ORD_WEB_X ' });
expect(state.rows).toHaveLength(1);
expect(state.rows[0].key).toBe('ORD_WEB_X');
const hit = await listReverseTombstoneKeys({ branchCode: 'BR002', kind: 'order', keys: [' ORD_WEB_X '] });
expect([...hit]).toEqual(['ORD_WEB_X']);
const miss = await listReverseTombstoneKeys({ branchCode: 'BR002', kind: 'order', keys: ['ord_web_x'] });
expect([...miss]).toEqual([]);
});
it('非法 kind 被数据库 CHECK 拒绝 ⇒ 抛错且表里 0 行(不误写)', async () => {
await expect(
recordReverseTombstone({ branchCode: 'BR002', kind: 'bogus' as never, businessKey: ' X ' })
).rejects.toThrow(/check constraint/);
expect(state.rows).toHaveLength(0);
});
it('listReverseTombstoneKeys:键去重+归一一次查询;空键/空分公司不发查询', async () => {
await recordReverseTombstone({ branchCode: 'BR002', kind: 'prep', businessKey: 'P-1' });
const hit = await listReverseTombstoneKeys({
branchCode: 'BR002',
kind: 'prep',
keys: ['P-1', ' p-1 ', 'P-1', 'p-2'],
});
expect([...hit]).toEqual(['p-1']);
const listCalls = H.poolQuery.mock.calls.filter(([sql]: [string]) =>
/SELECT business_key FROM public\.main_system_reverse_tombstones/i.test(String(sql))
);
expect(listCalls).toHaveLength(1);
expect(listCalls[0][1]).toEqual(['BR002', 'prep', ['p-1', 'p-2']]);
H.poolQuery.mockClear();
expect([...(await listReverseTombstoneKeys({ branchCode: 'BR002', kind: 'prep', keys: [] }))]).toEqual([]);
expect([...(await listReverseTombstoneKeys({ branchCode: ' ', kind: 'prep', keys: ['x'] }))]).toEqual([]);
expect(H.poolQuery).not.toHaveBeenCalled();
});
});
/* ── b) 导入过滤 ────────────────────────────────────────────────────────── */
describe('T2b:导入侧墓碑过滤边界', () => {
it('order 墓碑 ⇒ 整组跳过(skipped_tombstoned,且不触发建单/写订单)', async () => {
H.listTombstones.mockImplementation(async (input: { kind: string; keys: string[] }) =>
input.kind === 'order' ? new Set(input.keys.filter((k) => k === 'ORD_WEB_TOMB')) : new Set()
);
const filtered = await filterTombstonedGroups('BR002', [group('ORD_WEB_TOMB', ['p1', 'p2'])]);
expect(filtered.groups).toHaveLength(0);
expect(filtered.skipped).toHaveLength(1);
expect(filtered.skipped[0]).toMatchObject({
status: 'skipped_tombstoned',
mainOrderCode: 'ORD_WEB_TOMB',
ourOrderCode: null,
});
H.poolQuery.mockClear();
await importMainSystemGroups({
branchCode: 'BR002',
userId: null,
supplierCode: 'SUP1',
groups: [group('ORD_WEB_TOMB', ['p1', 'p2'])],
});
const sqls = H.poolQuery.mock.calls.map(([sql]: [string]) => String(sql));
expect(sqls.some((sql: string) => /INSERT\s+INTO\s+orders/i.test(sql))).toBe(false);
expect(sqls.some((sql: string) => /INSERT\s+INTO\s+order_items/i.test(sql))).toBe(false);
expect(H.submit).not.toHaveBeenCalled();
});
it('prep 墓碑 ⇒ 仅该行被剔除,其余行/组原样保留', async () => {
H.listTombstones.mockImplementation(async (input: { kind: string; keys: string[] }) =>
input.kind === 'prep' ? new Set(input.keys.filter((k) => k === 'prep-drop')) : new Set()
);
const filtered = await filterTombstonedGroups('BR002', [group('ORD_WEB_OK', ['prep-drop', 'prep-keep'])]);
expect(filtered.skipped).toEqual([]);
expect(filtered.groups).toHaveLength(1);
expect(filtered.groups[0].rows.map((row) => row.id)).toEqual(['prep-keep']);
});
it('无墓碑 ⇒ 行为不变(组/行原样放行,无 skipped)', async () => {
H.listTombstones.mockResolvedValue(new Set());
const groups = [group('ORD_WEB_OK', ['p1', 'p2'])];
const filtered = await filterTombstonedGroups('BR002', groups);
expect(filtered.skipped).toEqual([]);
expect(filtered.groups).toHaveLength(1);
expect(filtered.groups[0]).toBe(groups[0]); // 未命中时不重建对象
});
it('墓碑查询抛错 ⇒ 不过滤、不阻断导入(服务级 resolve 且无 skipped_tombstoned)', async () => {
H.listTombstones.mockRejectedValue(new Error('relation does not exist (tombstone table missing)'));
const filtered = await filterTombstonedGroups('BR002', [group('ORD_WEB_OK', ['p1'])]);
expect(filtered.groups).toHaveLength(1);
expect(filtered.skipped).toEqual([]);
const outcome = await importMainSystemGroups({
branchCode: 'BR002',
userId: null,
supplierCode: 'SUP1',
groups: [group('ORD_WEB_OK', ['p1'])],
});
expect(outcome.results.some((r) => r.status === 'skipped_tombstoned')).toBe(false);
});
});