- 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 超长修复
265 lines
12 KiB
TypeScript
265 lines
12 KiB
TypeScript
import { describe, expect, it, vi } from 'vitest';
|
||
|
||
/**
|
||
* GAP-1 / RELATED-1 / GAP-2(2026-10-19 T2 终局复攻):**捕获真实实现 SQL + 真 PG 执行**,
|
||
* 用于杀掉"去掉 PRESERVE 档"这类变异(旧测试复制了实现 SQL,改实现也不会红)。
|
||
*
|
||
* 断言:
|
||
* · repair 的三条清链 SQL 中,suspended/completed 只清"坏指针"、绝不清有效指针;
|
||
* · suspended 台账 `our_order_code=NULL` 时仍按保存档处理(不写回 order_code、不参与 upsert 映射);
|
||
* · `recordImportedPrepItems` 对 suspended + link=NULL 不得用本次映射填空;
|
||
* · follow 惰性同名对照:同名多行/加菜行/已被他人占用 ⇒ 不匹配(宁可不删)。
|
||
*/
|
||
|
||
const H = vi.hoisted(() => ({
|
||
client: null as null | { query: (sql: string, params?: unknown[]) => Promise<{ rows: Array<Record<string, unknown>>; rowCount?: number }> },
|
||
captured: [] as Array<{ sql: string; params: unknown[] }>,
|
||
}));
|
||
|
||
vi.mock('../src/db', () => ({
|
||
pool: {
|
||
query: async (sql: string, params?: unknown[]) => {
|
||
H.captured.push({ sql: String(sql), params: params || [] });
|
||
if (!H.client) throw new Error('pg client not ready');
|
||
return H.client.query(sql, params);
|
||
},
|
||
connect: async () => ({
|
||
query: async (sql: string, params?: unknown[]) => {
|
||
H.captured.push({ sql: String(sql), params: params || [] });
|
||
if (!H.client) throw new Error('pg client not ready');
|
||
return H.client.query(sql, params);
|
||
},
|
||
release: () => undefined,
|
||
}),
|
||
},
|
||
query: async (sql: string, params?: unknown[]) => H.client!.query(sql, params),
|
||
getRawPoolQuery: () => async (sql: string, params?: unknown[]) => H.client!.query(sql, params),
|
||
}));
|
||
|
||
vi.mock('../src/services/tenantDbContext', () => ({
|
||
runWithTenantDbContext: (_code: unknown, fn: () => Promise<unknown>) => fn(),
|
||
}));
|
||
|
||
import { repairMissingPrepLedgerRows, resolveOurItemIdByName } from '../src/services/mainSystemReturnFollow';
|
||
import { recordImportedPrepItems } from '../src/services/mainSystemPrepLedger';
|
||
|
||
type PgClient = {
|
||
connect: () => Promise<void>;
|
||
end: () => Promise<void>;
|
||
query: (sql: string, params?: unknown[]) => Promise<{ rows: Array<Record<string, unknown>>; rowCount?: number }>;
|
||
};
|
||
|
||
async function loadPgClient(): Promise<PgClient | null> {
|
||
const { loadEnv } = await import('../src/env');
|
||
loadEnv();
|
||
if (!process.env.DATABASE_URL) return null;
|
||
const pg = (await import('pg')).default as unknown as {
|
||
Client: new (cfg: { connectionString: string }) => PgClient;
|
||
};
|
||
const client = new pg.Client({ connectionString: process.env.DATABASE_URL });
|
||
try {
|
||
await client.connect();
|
||
} catch {
|
||
return null;
|
||
}
|
||
return client;
|
||
}
|
||
|
||
const BRANCH = '__T2_PRESERVE__';
|
||
const R_S = '11111111-0001-4000-8000-000000000001';
|
||
const R_RET = '11111111-0002-4000-8000-000000000002';
|
||
const R_X = '11111111-0003-4000-8000-000000000003';
|
||
const P_SUSP = 'cccccccc-0001-4000-8000-000000000001';
|
||
const P_MISS = 'cccccccc-0002-4000-8000-000000000002';
|
||
const P_OTHER = 'cccccccc-0003-4000-8000-000000000003';
|
||
|
||
function captureClears(): string[] {
|
||
return H.captured.map((c) => c.sql).filter((sql) => /UPDATE public\.main_system_order_import_items li/i.test(sql));
|
||
}
|
||
|
||
describe('GAP-1:repair 的保留档不依赖 our_order_code,真 PG 执行后 suspended 有效指针不被清', () => {
|
||
it('捕获真实清链 SQL:suspended/completed 只在坏指针时清;hard 档不含它们;再真 PG 执行验证', async (ctx) => {
|
||
const client = await loadPgClient();
|
||
if (!client) {
|
||
ctx.skip();
|
||
return;
|
||
}
|
||
H.client = client;
|
||
H.captured = [];
|
||
try {
|
||
await client.query('BEGIN');
|
||
await client.query(`
|
||
CREATE TEMP TABLE order_items (id uuid, order_code text, item_name text, sort_order int, created_at timestamptz,
|
||
is_returned boolean, is_extra_dish boolean) ON COMMIT DROP;
|
||
INSERT INTO order_items VALUES
|
||
('${R_S}'::uuid,'ORD_X','肉片',0,NOW(),false,false),
|
||
('${R_X}'::uuid,'ORD_X','牛肉',1,NOW(),false,false),
|
||
('${R_RET}'::uuid,'ORD_X','鸭肉',2,NOW(),true,false);
|
||
`);
|
||
await client.query('SET search_path TO pg_temp');
|
||
// 真实 ledger:suspended 且 our_order_code=NULL、有效指针 R_S;另放一条 removed 指向已退货行
|
||
await client.query(
|
||
`INSERT INTO public.main_system_order_import_items
|
||
(branch_code, main_order_code, prep_id, our_order_code, our_order_item_id, disposition)
|
||
VALUES ($1,'M_S',$2::uuid,NULL,$3::uuid,'suspended'),
|
||
($1,'M_R',$4::uuid,'ORD_X',$5::uuid,'removed')`,
|
||
[BRANCH, P_SUSP, R_S, P_MISS, R_RET]
|
||
);
|
||
// 让 repair 走一遍(fake 数据:payload 含 suspended+缺行;候选只给 R_X)
|
||
H.client = {
|
||
query: async (sql: string, params?: unknown[]) => {
|
||
if (/FROM public\.main_system_order_imports i/i.test(sql)) {
|
||
return {
|
||
rows: [{
|
||
main_order_code: 'M_S', main_supplier_code: 'SUP1', our_order_code: 'ORD_X',
|
||
payload: [{ id: P_SUSP, itemName: '肉片', prepareQty: 1 }, { id: P_MISS, itemName: '牛肉', prepareQty: 1 }],
|
||
}],
|
||
rowCount: 1,
|
||
};
|
||
}
|
||
if (/SELECT li\.prep_id::text AS prep_id, li\.disposition/i.test(sql)) {
|
||
return { rows: [{ prep_id: P_SUSP, disposition: 'suspended' }], rowCount: 1 };
|
||
}
|
||
if (/SELECT li\.prep_id::text AS prep_id, li\.our_order_item_id/i.test(sql)) {
|
||
return { rows: [], rowCount: 0 };
|
||
}
|
||
if (/^\s*SELECT[\s\S]*FROM order_items/i.test(sql)) {
|
||
return { rows: [{ id: R_X, item_name: '牛肉' }], rowCount: 1 };
|
||
}
|
||
return client.query(sql, params);
|
||
},
|
||
} as never;
|
||
await repairMissingPrepLedgerRows(BRANCH);
|
||
|
||
const clears = captureClears();
|
||
expect(clears.length, 'repair 应发出 3 条清链 UPDATE').toBe(3);
|
||
const [hard, preserve, revivable] = clears;
|
||
expect(hard, 'hard 档不含 suspended/completed').not.toMatch(/suspended|completed/);
|
||
expect(preserve).toMatch(/IN \('suspended', 'completed'\)/);
|
||
expect(preserve).toContain('NOT EXISTS');
|
||
expect(revivable).toMatch(/IN \('imported', 'pending', 'reallocated', 'skipped_stockout'\)/);
|
||
expect(clears.every((sql) => !/our_order_code/.test(sql)), 'GAP-1:清链/台账判定不得依赖 our_order_code').toBe(true);
|
||
// GAP-1:suspended 整行跳过 upsert(不写回 order_code / 不映射)
|
||
const upserts = H.captured.filter((c) => /INSERT INTO public\.main_system_order_import_items/i.test(c.sql));
|
||
expect(upserts.length).toBe(1);
|
||
expect(upserts[0].params[2], '只处理缺行 P_MISS,不碰 suspended').toBe(P_MISS);
|
||
|
||
// 真 PG 执行捕获到的 3 条清链(suspended 的有效指针必须保留;removed 的已退货指针清 NULL)
|
||
H.client = client;
|
||
for (const call of H.captured.filter((c) => /UPDATE public\.main_system_order_import_items li/i.test(c.sql))) {
|
||
await client.query(call.sql, call.params);
|
||
}
|
||
const rows = (
|
||
await client.query(
|
||
`SELECT prep_id::text AS prep_id, our_order_item_id::text AS link, our_order_code, disposition
|
||
FROM public.main_system_order_import_items WHERE branch_code=$1 ORDER BY prep_id`,
|
||
[BRANCH]
|
||
)
|
||
).rows;
|
||
const susp = rows.find((r) => r.prep_id === P_SUSP)!;
|
||
const removed = rows.find((r) => r.prep_id === P_MISS)!;
|
||
expect(susp).toMatchObject({ link: R_S, our_order_code: null, disposition: 'suspended' });
|
||
expect(removed.link).toBeNull();
|
||
} finally {
|
||
await client.query('ROLLBACK').catch(() => undefined);
|
||
await client.end();
|
||
H.client = null;
|
||
}
|
||
});
|
||
});
|
||
|
||
describe('RELATED-1:suspended + link=NULL 时 upsert 不得用 EXCLUDED 映射填空(真 PG)', () => {
|
||
it('真实 recordImportedPrepItems SQL 执行后仍保持 NULL', async (ctx) => {
|
||
const client = await loadPgClient();
|
||
if (!client) {
|
||
ctx.skip();
|
||
return;
|
||
}
|
||
H.client = client;
|
||
H.captured = [];
|
||
try {
|
||
await client.query('BEGIN');
|
||
await client.query(
|
||
`INSERT INTO public.main_system_order_import_items
|
||
(branch_code, main_order_code, prep_id, our_order_code, our_order_item_id, disposition)
|
||
VALUES ($1,'M_S',$2::uuid,'ORD_X',NULL,'suspended')`,
|
||
[BRANCH, P_SUSP]
|
||
);
|
||
await recordImportedPrepItems({
|
||
branchCode: BRANCH,
|
||
mainOrderCode: 'M_S',
|
||
supplierCode: null,
|
||
ourOrderCode: 'ORD_X',
|
||
prepRows: [{ id: P_SUSP, itemName: '肉片' }],
|
||
ourItems: [{ id: R_S, item_name: '肉片' }],
|
||
mapping: new Map([[P_SUSP, R_S]]),
|
||
});
|
||
const row = (
|
||
await client.query(
|
||
`SELECT our_order_item_id::text AS link, disposition FROM public.main_system_order_import_items
|
||
WHERE branch_code=$1 AND prep_id=$2::uuid`,
|
||
[BRANCH, P_SUSP]
|
||
)
|
||
).rows[0];
|
||
expect(row).toMatchObject({ link: null, disposition: 'suspended' });
|
||
const upsertSql = H.captured.map((c) => c.sql).find((sql) => /INSERT INTO public\.main_system_order_import_items/i.test(sql)) || '';
|
||
expect(upsertSql).toMatch(/IN \('suspended', 'completed'\)[\s\S]{0,240}our_order_item_id IS NULL[\s\S]{0,40}THEN NULL/);
|
||
} finally {
|
||
await client.query('ROLLBACK').catch(() => undefined);
|
||
await client.end();
|
||
H.client = null;
|
||
}
|
||
});
|
||
});
|
||
|
||
describe('GAP-2:follow 惰性同名对照不猜行(真 PG)', () => {
|
||
it('同名多行/加菜行/被他人占用 ⇒ 不匹配;唯一未占用同名行才匹配', async (ctx) => {
|
||
const client = await loadPgClient();
|
||
if (!client) {
|
||
ctx.skip();
|
||
return;
|
||
}
|
||
H.client = client;
|
||
try {
|
||
await client.query('BEGIN');
|
||
await client.query(`
|
||
CREATE TEMP TABLE order_items (id uuid, order_code text, item_name text, sort_order int, created_at timestamptz,
|
||
is_returned boolean, is_extra_dish boolean) ON COMMIT DROP;
|
||
`);
|
||
await client.query('SET search_path TO pg_temp');
|
||
const insert = (id: string, name: string, extra = false) =>
|
||
client.query(
|
||
`INSERT INTO order_items VALUES ($1::uuid,'ORD_X',$2,0,NOW(),false,$3)`,
|
||
[id, name, extra]
|
||
);
|
||
|
||
// ① 同名两行 ⇒ 不匹配
|
||
await insert(R_S, '肉片');
|
||
await insert(R_X, '肉片');
|
||
expect(await resolveOurItemIdByName(BRANCH, 'ORD_X', '肉片', P_OTHER)).toBe('');
|
||
|
||
// ② 只剩一行但它是加菜行 ⇒ 不匹配
|
||
await client.query(`DELETE FROM order_items WHERE id=$1::uuid`, [R_X]);
|
||
await client.query(`UPDATE order_items SET is_extra_dish=true WHERE id=$1::uuid`, [R_S]);
|
||
expect(await resolveOurItemIdByName(BRANCH, 'ORD_X', '肉片', P_OTHER)).toBe('');
|
||
|
||
// ③ 唯一同名非加菜行 ⇒ 匹配
|
||
await client.query(`UPDATE order_items SET is_extra_dish=false WHERE id=$1::uuid`, [R_S]);
|
||
expect(await resolveOurItemIdByName(BRANCH, 'ORD_X', '肉片', P_OTHER)).toBe(R_S);
|
||
|
||
// ④ 唯一同名行已被其它 prep 占用 ⇒ 不匹配(不然会删别人的行)
|
||
await client.query(
|
||
`INSERT INTO public.main_system_order_import_items
|
||
(branch_code, main_order_code, prep_id, our_order_code, our_order_item_id, disposition)
|
||
VALUES ($1,'M_O',$2::uuid,'ORD_X',$3::uuid,'imported')`,
|
||
[BRANCH, P_SUSP, R_S]
|
||
);
|
||
expect(await resolveOurItemIdByName(BRANCH, 'ORD_X', '肉片', P_OTHER)).toBe('');
|
||
} finally {
|
||
await client.query('ROLLBACK').catch(() => undefined);
|
||
await client.end();
|
||
H.client = null;
|
||
}
|
||
});
|
||
});
|