- 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 超长修复
594 lines
25 KiB
TypeScript
594 lines
25 KiB
TypeScript
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||
|
||
/**
|
||
* **SKU 映射**(2026-10-18 冻结契约 `.team/sku-mapping-shared-sheet/contract.md` §5)服务层守卫。
|
||
*
|
||
* 钉住:
|
||
* · 开关关闭 ⇒ **零出站**(D4/D5 一次都不发);
|
||
* · D4:只推 `status` 有效的商品,>5000 自动分批,汇总 matched/pending/kept/total;
|
||
* · D5:按 `next_cursor` 翻页;幂等 upsert;**完整拉取**才删除远端已不存在的行(截断不删);
|
||
* · 方向 B 反查:只认 `status='active'` 且 `delivery_sku_code` 非空;映射不可编辑(无写接口);
|
||
* · 提交前统计:total / mapped / unmapped(不按名称猜)。
|
||
*/
|
||
|
||
const poolQuery = vi.hoisted(() => vi.fn());
|
||
const clientQuery = vi.hoisted(() => vi.fn());
|
||
vi.mock('../src/db', () => ({
|
||
pool: {
|
||
query: (...args: unknown[]) => poolQuery(...args),
|
||
connect: async () => ({ query: (...args: unknown[]) => clientQuery(...args), release: () => undefined }),
|
||
},
|
||
getRawPoolQuery: () => poolQuery,
|
||
}));
|
||
|
||
const tenantCtx = vi.hoisted(() => vi.fn());
|
||
vi.mock('../src/services/tenantDbContext', () => ({
|
||
runWithTenantDbContext: (...args: unknown[]) => tenantCtx(...args),
|
||
}));
|
||
|
||
const resolveMainSupplierCode = vi.hoisted(() => vi.fn());
|
||
vi.mock('../src/services/mainSystemQuoteCostSync', async (importOriginal) => {
|
||
const actual = await importOriginal<typeof import('../src/services/mainSystemQuoteCostSync')>();
|
||
return { ...actual, resolveMainSupplierCode: (...a: unknown[]) => resolveMainSupplierCode(...a) };
|
||
});
|
||
|
||
const pushSkuDictionary = vi.hoisted(() => vi.fn());
|
||
const pullSkuMappings = vi.hoisted(() => vi.fn());
|
||
vi.mock('../src/services/mainSystem/api/skuMappings', async (importOriginal) => {
|
||
const actual = await importOriginal<typeof import('../src/services/mainSystem/api/skuMappings')>();
|
||
return {
|
||
...actual,
|
||
pushSkuDictionary: (...a: unknown[]) => pushSkuDictionary(...a),
|
||
pullSkuMappings: (...a: unknown[]) => pullSkuMappings(...a),
|
||
};
|
||
});
|
||
|
||
import {
|
||
getMappingByDeliverySku,
|
||
getSheetMappingStats,
|
||
isSkuMappingEnabled,
|
||
listLocalSkuMappings,
|
||
pullMappingsForAllBranches,
|
||
pullMappingsFromMainSystem,
|
||
pushSkuDictionaryForBranch,
|
||
} from '../src/services/skuMappingService';
|
||
|
||
type MappingRow = {
|
||
supplier_sku_code: string;
|
||
supplier_sku_name: string | null;
|
||
supplier_unit: string | null;
|
||
delivery_sku_code: string | null;
|
||
delivery_sku_name: string | null;
|
||
status: string;
|
||
synced_at?: string;
|
||
};
|
||
|
||
type State = {
|
||
skus: Array<{ sku_code: string; sku_name: string | null; unit: string | null; status?: number | null }>;
|
||
mappings: MappingRow[];
|
||
sheetItems: Array<{ sku_code: string; sku_name: string | null }>;
|
||
bindings: string[];
|
||
/** 显式指定某分公司的**主系统**分公司码;不指定时按 branchCode 一对一(保持旧用例语义) */
|
||
mainBranchCodes?: string[];
|
||
sql: string[];
|
||
};
|
||
|
||
function makeState(overrides: Partial<State> = {}): State {
|
||
return {
|
||
skus: [
|
||
{ sku_code: 'SKU1', sku_name: '草鱼', unit: '斤', status: 1 },
|
||
{ sku_code: 'SKU2', sku_name: '鲤鱼', unit: '袋', status: 1 },
|
||
{ sku_code: 'SKU9', sku_name: '停用商品', unit: '斤', status: 0 },
|
||
],
|
||
mappings: [
|
||
{ supplier_sku_code: 'SKU1', supplier_sku_name: '草鱼', supplier_unit: '斤', delivery_sku_code: 'D-001', delivery_sku_name: '草鱼(配送)', status: 'active' },
|
||
{ supplier_sku_code: 'SKU2', supplier_sku_name: '鲤鱼', supplier_unit: '袋', delivery_sku_code: null, delivery_sku_name: null, status: 'pending' },
|
||
],
|
||
sheetItems: [
|
||
{ sku_code: 'SKU1', sku_name: '草鱼' },
|
||
{ sku_code: 'SKU2', sku_name: '鲤鱼' },
|
||
{ sku_code: 'SKU3', sku_name: '鲫鱼' },
|
||
],
|
||
bindings: ['BR002'],
|
||
mainBranchCodes: undefined,
|
||
sql: [],
|
||
...overrides,
|
||
};
|
||
}
|
||
|
||
function installDb(state: State): void {
|
||
const handler = async (sql: string, params: unknown[] = []) => {
|
||
const text = String(sql);
|
||
state.sql.push(text);
|
||
if (text.includes('FROM skus')) {
|
||
return { rows: state.skus.filter((row) => row.status === undefined || row.status === null || row.status === 1) };
|
||
}
|
||
if (text.includes('INSERT INTO main_system_sku_mappings')) {
|
||
const row: MappingRow = {
|
||
supplier_sku_code: String(params[0]),
|
||
supplier_sku_name: (params[1] as string) ?? null,
|
||
supplier_unit: (params[2] as string) ?? null,
|
||
delivery_sku_code: (params[3] as string) ?? null,
|
||
delivery_sku_name: (params[4] as string) ?? null,
|
||
status: String(params[5]),
|
||
synced_at: new Date().toISOString(),
|
||
};
|
||
const existing = state.mappings.findIndex((m) => m.supplier_sku_code === row.supplier_sku_code);
|
||
if (existing >= 0) state.mappings[existing] = row;
|
||
else state.mappings.push(row);
|
||
return { rows: [], rowCount: 1 };
|
||
}
|
||
if (text.includes('DELETE FROM main_system_sku_mappings') && text.includes('<> ALL')) {
|
||
const keep = new Set((params[0] as string[]) || []);
|
||
const before = state.mappings.length;
|
||
state.mappings = state.mappings.filter((row) => keep.has(row.supplier_sku_code));
|
||
return { rows: [], rowCount: before - state.mappings.length };
|
||
}
|
||
if (text.includes('FROM main_system_sku_mappings') && text.includes('delivery_sku_code = $1')) {
|
||
const row = state.mappings.find(
|
||
(m) => m.delivery_sku_code === String(params[0]) && m.status === 'active'
|
||
);
|
||
return { rows: row ? [row] : [], rowCount: row ? 1 : 0 };
|
||
}
|
||
if (text.includes('FROM main_system_sku_mappings') && text.includes('delivery_sku_code = ANY')) {
|
||
const list = new Set((params[0] as string[]) || []);
|
||
return { rows: state.mappings.filter((m) => m.delivery_sku_code && list.has(m.delivery_sku_code)) };
|
||
}
|
||
if (text.includes('FROM main_system_sku_mappings') && text.includes('supplier_sku_code = ANY')) {
|
||
const list = new Set((params[0] as string[]) || []);
|
||
return { rows: state.mappings.filter((m) => list.has(m.supplier_sku_code)) };
|
||
}
|
||
if (text.includes('count(*)::int AS total') && text.includes('FROM main_system_sku_mappings')) {
|
||
const total = state.mappings.length;
|
||
const mapped = state.mappings.filter((m) => m.status === 'active' && m.delivery_sku_code).length;
|
||
return { rows: [{ total, mapped }], rowCount: 1 };
|
||
}
|
||
if (text.includes('FROM main_system_sku_mappings') && text.includes('ORDER BY')) {
|
||
return { rows: state.mappings, rowCount: state.mappings.length };
|
||
}
|
||
if (text.includes('FROM customer_quote_sheet_items')) {
|
||
return { rows: state.sheetItems, rowCount: state.sheetItems.length };
|
||
}
|
||
if (text.includes('UPPER(TRIM(main_branch_code))') && text.includes('FROM public.main_supplier_bindings')) {
|
||
const codes = state.mainBranchCodes ?? [String(params[0] || '')];
|
||
return { rows: codes.filter(Boolean).map((code) => ({ code })) };
|
||
}
|
||
if (text.includes('DISTINCT branch_code FROM public.main_supplier_bindings')) {
|
||
return { rows: state.bindings.map((branch_code) => ({ branch_code })) };
|
||
}
|
||
return { rows: [], rowCount: 0 };
|
||
};
|
||
poolQuery.mockImplementation((sql: string, params?: unknown[]) => handler(sql, params || []));
|
||
clientQuery.mockImplementation((sql: string, params?: unknown[]) => handler(sql, params || []));
|
||
}
|
||
|
||
beforeEach(() => {
|
||
poolQuery.mockReset();
|
||
clientQuery.mockReset();
|
||
resolveMainSupplierCode.mockReset();
|
||
pushSkuDictionary.mockReset();
|
||
pullSkuMappings.mockReset();
|
||
tenantCtx.mockReset();
|
||
tenantCtx.mockImplementation(async (_branch: string, fn: () => Promise<unknown>) => fn());
|
||
resolveMainSupplierCode.mockResolvedValue('SUP-37831443');
|
||
delete process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL;
|
||
});
|
||
|
||
describe('开关', () => {
|
||
it('未设置 / 0 ⇒ 关闭;1/true/on ⇒ 打开', () => {
|
||
expect(isSkuMappingEnabled()).toBe(false);
|
||
process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1';
|
||
expect(isSkuMappingEnabled()).toBe(true);
|
||
process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '0';
|
||
expect(isSkuMappingEnabled()).toBe(false);
|
||
});
|
||
|
||
it('关闭 ⇒ 零出站:推字典 503、拉映射空跑、定时任务 skipped', async () => {
|
||
installDb(makeState());
|
||
await expect(pushSkuDictionaryForBranch({ branchCode: 'BR002' })).rejects.toMatchObject({
|
||
status: 503,
|
||
code: 'feature_disabled',
|
||
});
|
||
const pulled = await pullMappingsFromMainSystem({ branchCode: 'BR002' });
|
||
expect(pulled).toMatchObject({ upserted: 0, deleted: 0, truncated: false });
|
||
const all = await pullMappingsForAllBranches();
|
||
expect(all.skipped).toBe(true);
|
||
expect(pushSkuDictionary).not.toHaveBeenCalled();
|
||
expect(pullSkuMappings).not.toHaveBeenCalled();
|
||
expect(poolQuery).not.toHaveBeenCalled();
|
||
});
|
||
});
|
||
|
||
describe('D4 推送商品字典', () => {
|
||
beforeEach(() => {
|
||
process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1';
|
||
});
|
||
|
||
it('只推 status 有效的商品;>5000 自动分批;汇总 matched/pending/kept/total', async () => {
|
||
const state = makeState();
|
||
state.skus = [
|
||
...Array.from({ length: 5001 }, (_, i) => ({
|
||
sku_code: `SKU${i}`,
|
||
sku_name: `商品${i}`,
|
||
unit: '斤',
|
||
status: 1,
|
||
})),
|
||
{ sku_code: 'SKU_DISABLED', sku_name: '停用商品', unit: '斤', status: 0 },
|
||
];
|
||
installDb(state);
|
||
pushSkuDictionary
|
||
.mockResolvedValueOnce({ kind: 'ok', status: 200, data: { matched: 3, pending: 0, kept: 0, total: 5000 } })
|
||
.mockResolvedValueOnce({ kind: 'ok', status: 200, data: { matched: 1, pending: 0, kept: 0, total: 1 } });
|
||
|
||
const summary = await pushSkuDictionaryForBranch({ branchCode: 'BR002' });
|
||
expect(pushSkuDictionary).toHaveBeenCalledTimes(2);
|
||
expect((pushSkuDictionary.mock.calls[0][0] as any).items).toHaveLength(5000);
|
||
expect((pushSkuDictionary.mock.calls[1][0] as any).items).toHaveLength(1);
|
||
expect(summary).toMatchObject({ skus: 5001, batches: 2, matched: 4, total: 5001 });
|
||
// 停用商品没有被推
|
||
const pushedCodes = pushSkuDictionary.mock.calls.flatMap(([arg]) =>
|
||
(arg as any).items.map((item: any) => item.sku_code)
|
||
);
|
||
expect(pushedCodes).not.toContain('SKU_DISABLED');
|
||
});
|
||
|
||
it('D4 失败 ⇒ 抛错(rejected 状态码透传,unavailable 转 502)', async () => {
|
||
installDb(makeState());
|
||
pushSkuDictionary.mockResolvedValueOnce({
|
||
kind: 'rejected',
|
||
status: 403,
|
||
code: 'forbidden',
|
||
reason: '未绑定该分公司',
|
||
payload: null,
|
||
});
|
||
await expect(pushSkuDictionaryForBranch({ branchCode: 'BR002' })).rejects.toMatchObject({
|
||
status: 403,
|
||
code: 'forbidden',
|
||
});
|
||
});
|
||
});
|
||
|
||
describe('主系统分公司码解析(D4/D5 不得用我方 branch_code 顶替)', () => {
|
||
beforeEach(() => {
|
||
process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1';
|
||
});
|
||
|
||
it('存量分公司 branch_code=SUP…、绑定 main_branch_code=BR002 ⇒ D4/D5 都传 BR002', async () => {
|
||
const state = makeState({ mainBranchCodes: ['BR002'] });
|
||
installDb(state);
|
||
pushSkuDictionary.mockResolvedValue({
|
||
kind: 'ok',
|
||
status: 200,
|
||
data: { matched: 1, pending: 0, kept: 0, total: 1 },
|
||
});
|
||
pullSkuMappings.mockResolvedValueOnce({
|
||
kind: 'ok',
|
||
status: 200,
|
||
rows: [
|
||
{
|
||
supplier_sku_code: 'SKU1',
|
||
supplier_sku_name: '草鱼',
|
||
supplier_unit: '斤',
|
||
delivery_sku_code: 'D-001',
|
||
delivery_sku_name: null,
|
||
status: 'active',
|
||
match_type: 'manual',
|
||
updated_at: null,
|
||
},
|
||
],
|
||
nextCursor: null,
|
||
total: 1,
|
||
});
|
||
|
||
await pushSkuDictionaryForBranch({ branchCode: 'SUP35143228' });
|
||
await pullMappingsFromMainSystem({ branchCode: 'SUP35143228' });
|
||
|
||
expect((pushSkuDictionary.mock.calls[0][0] as any).mainBranchCode).toBe('BR002');
|
||
expect((pullSkuMappings.mock.calls[0][0] as any).mainBranchCode).toBe('BR002');
|
||
});
|
||
|
||
it('一个我方分公司绑多个主系统分公司 ⇒ D4/D5 逐个同步(不再只同步一个)', async () => {
|
||
const state = makeState({ mainBranchCodes: ['BR002', 'BR003'] });
|
||
installDb(state);
|
||
pushSkuDictionary.mockResolvedValue({
|
||
kind: 'ok',
|
||
status: 200,
|
||
data: { matched: 1, pending: 0, kept: 0, total: 1 },
|
||
});
|
||
pullSkuMappings.mockImplementation(async (arg: any) => ({
|
||
kind: 'ok',
|
||
status: 200,
|
||
rows: [
|
||
{
|
||
supplier_sku_code: `SKU-${arg.mainBranchCode}`,
|
||
supplier_sku_name: '草鱼',
|
||
supplier_unit: '斤',
|
||
delivery_sku_code: `D-${arg.mainBranchCode}`,
|
||
delivery_sku_name: null,
|
||
status: 'active',
|
||
match_type: 'manual',
|
||
updated_at: null,
|
||
},
|
||
],
|
||
nextCursor: null,
|
||
total: 1,
|
||
}));
|
||
|
||
await pushSkuDictionaryForBranch({ branchCode: 'SUP35143228' });
|
||
const pulled = await pullMappingsFromMainSystem({ branchCode: 'SUP35143228' });
|
||
|
||
expect(pushSkuDictionary.mock.calls.map(([arg]: [any]) => arg.mainBranchCode)).toEqual(['BR002', 'BR003']);
|
||
expect(pullSkuMappings.mock.calls.map(([arg]: [any]) => arg.mainBranchCode)).toEqual(['BR002', 'BR003']);
|
||
expect(pulled.total).toBe(2);
|
||
});
|
||
});
|
||
|
||
describe('D5 拉映射', () => {
|
||
beforeEach(() => {
|
||
process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1';
|
||
});
|
||
|
||
it('按 next_cursor 翻页、幂等 upsert、完整拉取后删除远端已不存在的行', async () => {
|
||
const state = makeState({
|
||
mappings: [
|
||
// 远端已不存在的一行(完整拉取后应被删)
|
||
{ supplier_sku_code: 'GONE', supplier_sku_name: '旧', supplier_unit: '斤', delivery_sku_code: 'D-X', delivery_sku_name: null, status: 'active' },
|
||
],
|
||
});
|
||
installDb(state);
|
||
pullSkuMappings
|
||
.mockResolvedValueOnce({
|
||
kind: 'ok',
|
||
status: 200,
|
||
rows: [
|
||
{ supplier_sku_code: 'SKU1', supplier_sku_name: '草鱼', supplier_unit: '斤', delivery_sku_code: 'D-001', delivery_sku_name: '草鱼(配送)', status: 'active', match_type: 'manual', updated_at: null },
|
||
],
|
||
nextCursor: 'p2',
|
||
total: null,
|
||
})
|
||
.mockResolvedValueOnce({
|
||
kind: 'ok',
|
||
status: 200,
|
||
rows: [
|
||
{ supplier_sku_code: 'SKU2', supplier_sku_name: '鲤鱼', supplier_unit: '袋', delivery_sku_code: null, delivery_sku_name: null, status: 'pending', match_type: 'none', updated_at: null },
|
||
],
|
||
nextCursor: null,
|
||
total: null,
|
||
});
|
||
|
||
const summary = await pullMappingsFromMainSystem({ branchCode: 'BR002' });
|
||
expect(summary).toMatchObject({ total: 2, upserted: 2, deleted: 1, truncated: false, pages: 2 });
|
||
expect(pullSkuMappings).toHaveBeenCalledTimes(2);
|
||
expect((pullSkuMappings.mock.calls[1][0] as any).cursor).toBe('p2');
|
||
const codes = state.mappings.map((row) => row.supplier_sku_code).sort();
|
||
expect(codes).toEqual(['SKU1', 'SKU2']);
|
||
expect(state.mappings.find((row) => row.supplier_sku_code === 'SKU1')!.status).toBe('active');
|
||
});
|
||
|
||
it('翻页截断(>最大页数)⇒ 不删本地行(避免误删)', async () => {
|
||
const state = makeState();
|
||
installDb(state);
|
||
const rows = [{ supplier_sku_code: 'SKU1', supplier_sku_name: '草鱼', supplier_unit: '斤', delivery_sku_code: 'D-001', delivery_sku_name: null, status: 'active', match_type: 'manual', updated_at: null }];
|
||
let page = 0;
|
||
pullSkuMappings.mockImplementation(async () => ({
|
||
kind: 'ok',
|
||
status: 200,
|
||
rows,
|
||
nextCursor: `c${++page}`, // 每页游标都不同,避免"游标不前进"提前 break
|
||
total: null,
|
||
}));
|
||
const summary = await pullMappingsFromMainSystem({ branchCode: 'BR002' });
|
||
expect(summary.truncated).toBe(true);
|
||
expect(summary.deleted).toBe(0);
|
||
expect(summary.pages).toBe(50);
|
||
});
|
||
|
||
it('D5 第一页失败 ⇒ 本次只做空刷新、**不删**本地行、truncated=true(不抛错丢上下文)', async () => {
|
||
const state = makeState();
|
||
installDb(state);
|
||
const before = JSON.stringify(state.mappings);
|
||
pullSkuMappings.mockResolvedValueOnce({ kind: 'unavailable', status: 502, code: 'main_system_error', reason: '对方不可用', payload: null });
|
||
const summary = await pullMappingsFromMainSystem({ branchCode: 'BR002' });
|
||
expect(summary).toMatchObject({ upserted: 0, deleted: 0, truncated: true, pages: 0 });
|
||
expect(JSON.stringify(state.mappings)).toBe(before);
|
||
});
|
||
});
|
||
|
||
describe('方向 B 反查与提交前统计', () => {
|
||
beforeEach(() => {
|
||
process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1';
|
||
});
|
||
|
||
it('只认 active 且 delivery_sku_code 非空的映射', async () => {
|
||
installDb(makeState());
|
||
expect(await getMappingByDeliverySku('BR002', 'D-001')).toMatchObject({ supplier_sku_code: 'SKU1' });
|
||
expect(await getMappingByDeliverySku('BR002', 'NOT-MAPPED')).toBeNull();
|
||
expect(await getMappingByDeliverySku('BR002', '')).toBeNull();
|
||
});
|
||
|
||
it('提交前统计:total / mapped / unmapped + 未映射清单(不按名称猜)', async () => {
|
||
installDb(makeState());
|
||
const stats = await getSheetMappingStats('QS1');
|
||
expect(stats).toMatchObject({ total: 3, mapped: 1, unmapped: 2 });
|
||
expect(stats.unmapped_skus.map((row) => row.sku_code)).toEqual(['SKU2', 'SKU3']);
|
||
});
|
||
|
||
it('FE-3:counts 与列表使用同一 WHERE(status/keyword 参数同序,不再全表汇总)', async () => {
|
||
const calls: Array<{ sql: string; params: unknown[] }> = [];
|
||
poolQuery.mockReset();
|
||
poolQuery.mockImplementation(async (sql: string, params: unknown[] = []) => {
|
||
calls.push({ sql: String(sql), params: params || [] });
|
||
return { rows: [], rowCount: 0 };
|
||
});
|
||
|
||
await listLocalSkuMappings({ branchCode: 'BR002', status: 'pending', keyword: '草', limit: 500 });
|
||
|
||
const counts = calls.find((call) => /SELECT count\(\*\)::int AS total/.test(call.sql));
|
||
expect(counts, '必须发出 counts 查询').toBeTruthy();
|
||
expect(counts!.sql).toContain('WHERE status = $1');
|
||
expect(counts!.sql).toContain('supplier_sku_name ILIKE $2');
|
||
expect(counts!.params, 'counts 参数必须与列表同序同值').toEqual(['pending', '%草%']);
|
||
|
||
const list = calls.find((call) => /ORDER BY \(delivery_sku_code IS NULL\)/.test(call.sql));
|
||
expect(list!.params).toEqual(['pending', '%草%', 500]);
|
||
});
|
||
|
||
it('只读列表带汇总(total/mapped/unmapped)', async () => {
|
||
installDb(makeState());
|
||
const listed = await listLocalSkuMappings({ branchCode: 'BR002' });
|
||
expect(listed.summary).toEqual({ total: 2, mapped: 1, unmapped: 1 });
|
||
expect(listed.rows).toHaveLength(2);
|
||
});
|
||
});
|
||
|
||
describe('定时任务', () => {
|
||
beforeEach(() => {
|
||
process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1';
|
||
});
|
||
|
||
it('按 active 绑定分公司逐个拉取;单个失败记 errors 不中断其它', async () => {
|
||
installDb(makeState({ bindings: ['BR002', 'BR007'] }));
|
||
pullSkuMappings
|
||
.mockResolvedValueOnce({ kind: 'ok', status: 200, rows: [{ supplier_sku_code: 'SKU1', supplier_sku_name: '草鱼', supplier_unit: '斤', delivery_sku_code: 'D-001', delivery_sku_name: null, status: 'active', match_type: 'manual', updated_at: null }], nextCursor: null, total: null })
|
||
.mockResolvedValueOnce({ kind: 'unavailable', status: 502, code: 'main_system_error', reason: '对方不可用', payload: null });
|
||
const summary = await pullMappingsForAllBranches();
|
||
expect(summary).toMatchObject({ branches: 2, pulled: 1, errors: 1, skipped: false });
|
||
});
|
||
});
|
||
|
||
/* ── verifier 阻断项(>200 行):完整性判据 + 截断绝不删本地行 ───────────────── */
|
||
|
||
describe('D5 完整性判据(>200 行不再误删本地映射)', () => {
|
||
beforeEach(() => {
|
||
process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1';
|
||
});
|
||
|
||
const row = (code: string) => ({
|
||
supplier_sku_code: code,
|
||
supplier_sku_name: code,
|
||
supplier_unit: '斤',
|
||
delivery_sku_code: `D-${code}`,
|
||
delivery_sku_name: null,
|
||
status: 'active',
|
||
match_type: 'manual',
|
||
updated_at: null,
|
||
});
|
||
|
||
it('首屏恰好 200 行、对方没给 next_cursor 也没给 total ⇒ 无法证明拉全 ⇒ truncated=true 且**不删**本地行', async () => {
|
||
const local = Array.from({ length: 250 }, (_, i) => ({
|
||
supplier_sku_code: `SKU${i}`,
|
||
supplier_sku_name: '本地',
|
||
supplier_unit: '斤',
|
||
delivery_sku_code: `D-SKU${i}`,
|
||
delivery_sku_name: null,
|
||
status: 'active',
|
||
}));
|
||
const state = makeState({ mappings: local });
|
||
installDb(state);
|
||
pullSkuMappings.mockResolvedValueOnce({
|
||
kind: 'ok',
|
||
status: 200,
|
||
rows: Array.from({ length: 200 }, (_, i) => row(`REMOTE-${i}`)),
|
||
nextCursor: null,
|
||
total: null,
|
||
});
|
||
|
||
const summary = await pullMappingsFromMainSystem({ branchCode: 'BR002' });
|
||
expect(summary.truncated).toBe(true);
|
||
expect(summary.deleted).toBe(0);
|
||
// 本地 250 行必须原样保留(旧实现会在这里删掉 50 行)
|
||
expect(state.mappings.filter((item) => item.supplier_sku_code.startsWith('SKU'))).toHaveLength(250);
|
||
expect(summary.upserted).toBe(200);
|
||
});
|
||
|
||
it('翻页中途失败 ⇒ truncated=true、保留已拉到的部分、**不删**本地行', async () => {
|
||
const state = makeState({
|
||
mappings: [
|
||
{ supplier_sku_code: 'OLD', supplier_sku_name: '旧', supplier_unit: '斤', delivery_sku_code: 'D-OLD', delivery_sku_name: null, status: 'active' },
|
||
],
|
||
});
|
||
installDb(state);
|
||
pullSkuMappings
|
||
.mockResolvedValueOnce({ kind: 'ok', status: 200, rows: [row('NEW-1')], nextCursor: 'p2', total: 300 })
|
||
.mockResolvedValueOnce({ kind: 'unavailable', status: 502, code: 'main_system_error', reason: '对方不可用', payload: null });
|
||
|
||
const summary = await pullMappingsFromMainSystem({ branchCode: 'BR002' });
|
||
expect(summary.truncated).toBe(true);
|
||
expect(summary.deleted).toBe(0);
|
||
expect(summary.upserted).toBe(1);
|
||
expect(state.mappings.map((item) => item.supplier_sku_code).sort()).toEqual(['NEW-1', 'OLD']);
|
||
});
|
||
|
||
it('完整拉取(total 对得上、翻页到 null)⇒ 删除远端已不存在的行', async () => {
|
||
const state = makeState({
|
||
mappings: [
|
||
{ supplier_sku_code: 'GONE', supplier_sku_name: '旧', supplier_unit: '斤', delivery_sku_code: 'D-GONE', delivery_sku_name: null, status: 'active' },
|
||
],
|
||
});
|
||
installDb(state);
|
||
pullSkuMappings
|
||
.mockResolvedValueOnce({ kind: 'ok', status: 200, rows: [row('A')], nextCursor: 'p2', total: 2 })
|
||
.mockResolvedValueOnce({ kind: 'ok', status: 200, rows: [row('B')], nextCursor: null, total: 2 });
|
||
|
||
const summary = await pullMappingsFromMainSystem({ branchCode: 'BR002' });
|
||
expect(summary.truncated).toBe(false);
|
||
expect(summary.deleted).toBe(1);
|
||
expect(state.mappings.map((item) => item.supplier_sku_code).sort()).toEqual(['A', 'B']);
|
||
});
|
||
});
|
||
|
||
/* ── 定时任务:D4 推字典 + D5 拉映射,两个计数都要有 ─────────────────────────── */
|
||
|
||
describe('定时任务(D4 + D5)', () => {
|
||
beforeEach(() => {
|
||
process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1';
|
||
});
|
||
|
||
it('按分公司推字典 + 拉映射,返回 push/pull 计数;单点失败记 errors 不中断', async () => {
|
||
const state = makeState({
|
||
bindings: ['BR002', 'BR007'],
|
||
skus: Array.from({ length: 10 }, (_, i) => ({
|
||
sku_code: `SKU${i}`,
|
||
sku_name: `商品${i}`,
|
||
unit: '斤',
|
||
status: 1,
|
||
})),
|
||
});
|
||
installDb(state);
|
||
pushSkuDictionary
|
||
.mockResolvedValueOnce({ kind: 'ok', status: 200, data: { matched: 9, pending: 1, kept: 0, total: 10 } })
|
||
.mockResolvedValueOnce({ kind: 'unavailable', status: 502, code: 'main_system_error', reason: '对方不可用', payload: null });
|
||
pullSkuMappings
|
||
.mockResolvedValueOnce({
|
||
kind: 'ok',
|
||
status: 200,
|
||
rows: [{ supplier_sku_code: 'SKU1', supplier_sku_name: '草鱼', supplier_unit: '斤', delivery_sku_code: 'D-001', delivery_sku_name: null, status: 'active', match_type: 'manual', updated_at: null }],
|
||
nextCursor: null,
|
||
total: 1,
|
||
})
|
||
.mockResolvedValueOnce({ kind: 'ok', status: 200, rows: [], nextCursor: null, total: 0 });
|
||
|
||
const { syncDictionaryAndMappingsForAllBranches } = await import('../src/services/skuMappingService');
|
||
const summary = await syncDictionaryAndMappingsForAllBranches();
|
||
expect(summary).toMatchObject({
|
||
branches: 2,
|
||
pushedSkus: 10, // BR002 推 10 条成功;BR007 推字典失败(不计入)
|
||
pushBatches: 1,
|
||
pulled: 1,
|
||
skipped: false,
|
||
});
|
||
expect(summary.errors).toBeGreaterThanOrEqual(1); // BR007 推字典失败
|
||
expect(pushSkuDictionary).toHaveBeenCalledTimes(2);
|
||
});
|
||
|
||
it('开关关闭 ⇒ 定时任务零出站(skipped=true)', async () => {
|
||
delete process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL;
|
||
installDb(makeState());
|
||
const { syncDictionaryAndMappingsForAllBranches } = await import('../src/services/skuMappingService');
|
||
const summary = await syncDictionaryAndMappingsForAllBranches();
|
||
expect(summary.skipped).toBe(true);
|
||
expect(pushSkuDictionary).not.toHaveBeenCalled();
|
||
expect(pullSkuMappings).not.toHaveBeenCalled();
|
||
});
|
||
});
|