Files
SupplierSystem/server/tests/mainSystemTombstoneImport.test.ts
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

294 lines
14 KiB
TypeScript
Raw Permalink 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';
/**
* BIZ-6(2026-10-19,T2):反向事件墓碑 → E1 导入侧命中即跳过。
*
* 事故:反向事件(改派/删行/删单)**先于 E1** 到达时旧实现只 `ignored`;等 E1 之后到达,
* 已被删除/改派的备货行/订单会被重新建回来。墓碑表(public.main_system_reverse_tombstones)
* 持久记住这些业务键,导入侧在**建单/追加之前**精确过滤:
* · order 墓碑 ⇒ 整组不建单/不建行(status=`skipped_tombstoned`,调用方/日志可识别);
* · prep 墓碑 ⇒ 该行不追加、不建行;
* · 键精确到 main_order_code / prep_id,绝不按 branch/日期放宽。
*/
const H = vi.hoisted(() => ({
poolQuery: vi.fn(),
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),
}));
import { recordReverseTombstone } from '../src/services/mainSystemReverseEvents';
import {
filterTombstonedGroups,
importMainSystemGroups,
type MainOrderGroup,
} from '../src/services/mainSystemOrderImport';
type Tombstones = {
order: Set<string>;
/** prep_id → tombstone reason(`reallocated` 不阻断,其余硬删语义阻断) */
prep: Map<string, string>;
};
let tombstones: Tombstones = { order: new Set(), prep: new Map() };
const clearedTombstones: string[] = [];
/** 模拟 TOCTOU:读到 reallocated 后、DELETE 前墓碑已被并发升级为硬删 */
let clearRaceUpgradedToHard = false;
function installPool(): void {
H.poolQuery.mockImplementation(async (sql: string, params: unknown[] = []) => {
const text = String(sql);
// 全部墓碑键(listReverseTombstoneKeys)
if (/SELECT business_key FROM public\.main_system_reverse_tombstones/i.test(text)) {
const kind = String(params[1] === 'order' ? 'order' : 'prep');
const rawKeys = (params[2] as string[]) || [];
if (kind === 'order') {
const rows = rawKeys
.filter((key) => tombstones.order.has(key))
.map((key) => ({ business_key: key }));
return { rows, rowCount: rows.length };
}
const keys = rawKeys.map((key) => key.toLowerCase());
const rows = keys
.filter((key) => tombstones.prep.has(key))
.map((key) => ({ business_key: key }));
return { rows, rowCount: rows.length };
}
// 墓碑写入(recordReverseTombstone):ON CONFLICT DO UPDATE 按 reason 优先级合并
if (/INSERT INTO public\.main_system_reverse_tombstones/i.test(text)) {
const [branch, kind, key, rawReason] = params as [string, string, string, string | null];
const reason = rawReason === null || rawReason === undefined ? null : String(rawReason).trim() || null;
const hard = (value: string | null) =>
['item_removed', 'deleted', 'removed'].includes(String(value || '').trim().toLowerCase());
const lowerKey = kind === 'prep' ? key.toLowerCase() : key;
if (kind === 'order') {
if (!tombstones.order.has(lowerKey)) tombstones.order.add(lowerKey);
return { rows: [], rowCount: 1 };
}
const existing = tombstones.prep.get(lowerKey);
if (existing === undefined) {
tombstones.prep.set(lowerKey, String(reason ?? ''));
} else if (/DO UPDATE/i.test(text)) {
if (hard(reason)) tombstones.prep.set(lowerKey, String(reason));
else if (!hard(existing) && reason !== null) tombstones.prep.set(lowerKey, String(reason));
}
return { rows: [], rowCount: 1 };
}
// 改派墓碑键(listReallocatedReverseTombstones,reason='reallocated')
if (/SELECT business_key AS key FROM public\.main_system_reverse_tombstones/i.test(text)) {
const keys = ((params[1] as string[]) || []).map((key) => key.toLowerCase());
const rows = keys
.filter((key) => tombstones.prep.get(key) === 'reallocated')
.map((key) => ({ key }));
return { rows, rowCount: rows.length };
}
if (/DELETE FROM public\.main_system_reverse_tombstones/i.test(text)) {
const key = String(params[2] || '').toLowerCase();
// 与生产 SQL 一致:只删 reason='reallocated' 的墓碑
if (/LOWER\(TRIM\(COALESCE\(reason, ''\)\)\) = 'reallocated'/.test(text)) {
if (clearRaceUpgradedToHard) {
// 并发的 item_removed 已升级窗口:DELETE 命中 0 行
tombstones.prep.set(key, 'item_removed');
clearRaceUpgradedToHard = false;
return { rows: [], rowCount: 0 };
}
if (String(tombstones.prep.get(key) || '').trim().toLowerCase() !== 'reallocated') {
return { rows: [], rowCount: 0 };
}
}
clearedTombstones.push(key);
tombstones.prep.delete(key);
return { rows: [], rowCount: 1 };
}
return { rows: [], rowCount: 0 };
});
}
function group(orderCode: string, prepIds: string[]): MainOrderGroup {
return {
orderCode,
deliveryDate: '2026-10-20',
taskDay: '2026-10-20',
rows: prepIds.map((id, index) => ({
id,
itemName: `商品${index}`,
prepareQty: 1,
isStockout: false,
})) as unknown as MainOrderGroup['rows'],
};
}
beforeEach(() => {
tombstones = { order: new Set(), prep: new Map() };
clearedTombstones.length = 0;
clearRaceUpgradedToHard = false;
H.poolQuery.mockReset();
H.submit.mockReset();
H.submit.mockResolvedValue({ order_code: 'ORD_API_SHOULD_NOT_BE_CREATED', zero_price_count: 0, new_products_created: 0 });
H.tenantCtx.mockReset();
H.tenantCtx.mockImplementation(async (fn: () => Promise<unknown>) => fn());
H.withTenantDataAccess.mockReset();
H.withTenantDataAccess.mockImplementation(async (_code: string, fn: (client: unknown) => Promise<unknown>) =>
fn({
query: async (sql: string, params: unknown[] = []) => H.poolQuery(sql, params),
})
);
installPool();
});
describe('BIZ-6:order 墓碑 ⇒ 整组跳过(不建单/不建行)', () => {
it('main_order_code 命中 order 墓碑 ⇒ skipped_tombstoned,且不调用建单、无写订单 SQL', async () => {
tombstones.order.add('ORD_WEB_TOMBSTONE');
const groups = [group('ORD_WEB_TOMBSTONE', ['prep-1', 'prep-2']), group('ORD_WEB_OK', ['prep-3'])];
const outcome = await importMainSystemGroups({
branchCode: 'BR002',
userId: null,
supplierCode: 'SUP1',
groups,
});
expect(outcome.results.some((r) => r.status === 'skipped_tombstoned' && r.mainOrderCode === 'ORD_WEB_TOMBSTONE')).toBe(true);
// 墓碑命中的组不得触发建单;另一组因无库存/无客户等前置条件可能走失败分支,但绝不能是墓碑组
expect(H.submit).not.toHaveBeenCalledWith(expect.objectContaining({ remark: expect.stringContaining('ORD_WEB_TOMBSTONE') }));
const sqls = H.poolQuery.mock.calls.map(([sql]: [string]) => String(sql));
expect(sqls.some((sql) => /INSERT\s+INTO\s+orders/i.test(sql))).toBe(false);
expect(sqls.some((sql) => /INSERT\s+INTO\s+order_items/i.test(sql))).toBe(false);
});
it('墓碑不存在 ⇒ 行为不变(filter 原样放行,无 skipped)', async () => {
const groups = [group('ORD_WEB_OK', ['prep-1'])];
const filtered = await filterTombstonedGroups('BR002', groups);
expect(filtered.skipped).toEqual([]);
expect(filtered.groups).toHaveLength(1);
expect(filtered.groups[0].rows.map((row) => row.id)).toEqual(['prep-1']);
});
});
describe('BIZ-6:prep 墓碑 ⇒ 只跳过该行(不追加/不建行)', () => {
it('同组两条行,一条命中 prep 墓碑 ⇒ 只保留另一条', async () => {
tombstones.prep.set('prep-removed', 'item_removed');
const filtered = await filterTombstonedGroups('BR002', [
group('ORD_WEB_OK', ['prep-removed', '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_tombstoned(不建空单)', async () => {
tombstones.prep.set('prep-a', 'item_removed');
tombstones.prep.set('prep-b', 'item_removed');
const filtered = await filterTombstonedGroups('BR002', [group('ORD_WEB_OK', ['prep-a', 'prep-b'])]);
expect(filtered.groups).toHaveLength(0);
expect(filtered.skipped).toHaveLength(1);
expect(filtered.skipped[0]).toMatchObject({ status: 'skipped_tombstoned', mainOrderCode: 'ORD_WEB_OK' });
});
it('reallocated 墓碑(改派走)⇒ 不阻断,E1 回来时解除墓碑并放行(攻破 1)', async () => {
tombstones.prep.set('prep-realloc', 'reallocated');
const filtered = await filterTombstonedGroups('BR002', [group('ORD_WEB_OK', ['prep-realloc'])]);
expect(filtered.skipped).toEqual([]);
expect(filtered.groups[0].rows.map((row) => row.id)).toEqual(['prep-realloc']);
// E1 重新分配回来 ⇒ 解除墓碑(否则永久跳过,全仓无解)
expect(clearedTombstones).toContain('prep-realloc');
expect(tombstones.prep.has('prep-realloc')).toBe(false);
});
it('item_removed 墓碑(硬删)⇒ E1 回来仍 skipped_tombstoned(不复活)', async () => {
tombstones.prep.set('prep-deleted', 'item_removed');
const filtered = await filterTombstonedGroups('BR002', [group('ORD_WEB_OK', ['prep-deleted'])]);
expect(filtered.groups).toHaveLength(0);
expect(filtered.skipped[0]).toMatchObject({ status: 'skipped_tombstoned' });
expect(clearedTombstones).toEqual([]);
});
it('order 墓碑一律阻断(不受 reallocated 语义影响)', async () => {
tombstones.order.add('ORD_WEB_TOMBSTONE');
const filtered = await filterTombstonedGroups('BR002', [group('ORD_WEB_TOMBSTONE', ['prep-1'])]);
expect(filtered.groups).toHaveLength(0);
expect(filtered.skipped[0]).toMatchObject({ status: 'skipped_tombstoned', mainOrderCode: 'ORD_WEB_TOMBSTONE' });
});
it('攻破 A:reallocated → item_removed ⇒ 墓碑升级为硬删(E1 回来后仍阻断、不清除)', async () => {
await recordReverseTombstone({ branchCode: 'BR002', kind: 'prep', businessKey: 'prep-up', reason: 'reallocated' });
await recordReverseTombstone({ branchCode: 'BR002', kind: 'prep', businessKey: 'prep-up', reason: 'item_removed' });
expect(tombstones.prep.get('prep-up'), '硬删语义必须升级,不能停在 reallocated').toBe('item_removed');
const filtered = await filterTombstonedGroups('BR002', [group('ORD_WEB_OK', ['prep-up'])]);
expect(filtered.groups).toHaveLength(0);
expect(filtered.skipped[0]).toMatchObject({ status: 'skipped_tombstoned' });
expect(clearedTombstones).toEqual([]);
});
it('攻破 A 反向:item_removed → reallocated ⇒ 仍硬删(reallocated 不得降级)', async () => {
await recordReverseTombstone({ branchCode: 'BR002', kind: 'prep', businessKey: 'prep-stay', reason: 'item_removed' });
await recordReverseTombstone({ branchCode: 'BR002', kind: 'prep', businessKey: 'prep-stay', reason: 'reallocated' });
expect(tombstones.prep.get('prep-stay')).toBe('item_removed');
const filtered = await filterTombstonedGroups('BR002', [group('ORD_WEB_OK', ['prep-stay'])]);
expect(filtered.groups).toHaveLength(0);
expect(clearedTombstones).toEqual([]);
});
it('攻破 A 对照:单独 reallocated 仍放行并解除墓碑', async () => {
await recordReverseTombstone({ branchCode: 'BR002', kind: 'prep', businessKey: 'prep-ok', reason: 'reallocated' });
const filtered = await filterTombstonedGroups('BR002', [group('ORD_WEB_OK', ['prep-ok'])]);
expect(filtered.groups).toHaveLength(1);
expect(clearedTombstones).toContain('prep-ok');
});
it('A1:reason 前后空白也必须认出硬删(\' item_removed \' 不被迟到 reallocated 降级)', async () => {
await recordReverseTombstone({ branchCode: 'BR002', kind: 'prep', businessKey: 'prep-space', reason: ' item_removed ' });
expect(tombstones.prep.get('prep-space'), '写库前必须 trim').toBe('item_removed');
await recordReverseTombstone({ branchCode: 'BR002', kind: 'prep', businessKey: 'prep-space', reason: 'reallocated' });
expect(tombstones.prep.get('prep-space')).toBe('item_removed');
const filtered = await filterTombstonedGroups('BR002', [group('ORD_WEB_OK', ['prep-space'])]);
expect(filtered.groups).toHaveLength(0);
expect(clearedTombstones).toEqual([]);
});
it('A2:clear 带 reason 守卫 + TOCTOU(读到 reallocated 后并发升级 ⇒ DELETE 0 行,不得放行导入)', async () => {
tombstones.prep.set('prep-race', 'reallocated');
clearRaceUpgradedToHard = true; // 模拟 list 之后、DELETE 之前被 item_removed 升级
const filtered = await filterTombstonedGroups('BR002', [group('ORD_WEB_OK', ['prep-race'])]);
expect(filtered.groups, 'DELETE 命中 0 行时必须按 blocked 处理').toHaveLength(0);
expect(filtered.skipped[0]).toMatchObject({ status: 'skipped_tombstoned' });
expect(tombstones.prep.get('prep-race')).toBe('item_removed');
const deleteCalls = H.poolQuery.mock.calls.filter(([sql]: [string]) =>
/DELETE FROM public\.main_system_reverse_tombstones/i.test(String(sql))
);
expect(String(deleteCalls[0][0])).toContain("LOWER(TRIM(COALESCE(reason, ''))) = 'reallocated'");
});
it('墓碑键精确到业务键:branch 相同但 key 不同 ⇒ 不误杀', async () => {
tombstones.prep.set('prep-someone-else', 'item_removed');
const filtered = await filterTombstonedGroups('BR002', [group('ORD_WEB_OK', ['prep-keep'])]);
expect(filtered.skipped).toEqual([]);
expect(filtered.groups[0].rows).toHaveLength(1);
});
});