- 分公司类型模板:超管配置隐藏路由/菜单 + 中文文案覆盖,仅对挂类型的分公司生效(后端 service/routes、前端 Provider/守卫/配置页) - 超管模板 iframe 真还原预览:28 个业务页注册、白名单点选编辑、空/示例数据 fixture、白名单漂移检测工具 - 商品/SKU 下拉远程搜索:服务端关键词搜索 + 前端 useRemoteOptionSearch/SearchableSelect 接入(订单/采购/商品等页) - 主系统联调:子系统主动解绑主系统授权(幂等重试/本地兜底)、追加修改 price_amend 视图代理与 amend-price 转发 - 修复:仓内加工重复建单幂等(已完成需求单 guard、order 任务一商品一单 guard) - 修复:出入库记录只取前 100 条 → 服务端分页 + 真实总数 - 其它:库存/订单若干修复、分公司管理响应式布局、i18n 文案、设计文档与回归测试
439 lines
22 KiB
TypeScript
439 lines
22 KiB
TypeScript
import { readFileSync } from 'node:fs';
|
||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||
|
||
/**
|
||
* T1:通用 SKU/商品档案关键词搜索接口(q + codes + limit≤50 + 三层排序)。
|
||
* 目标:>1000 条商品时服务端精准命中,不再依赖前端全量加载 + 本地过滤。
|
||
*/
|
||
const runtime = vi.hoisted(() => ({
|
||
query: vi.fn(),
|
||
poolQuery: vi.fn(),
|
||
release: vi.fn(),
|
||
connect: vi.fn(),
|
||
}));
|
||
|
||
vi.mock('../src/db', () => ({
|
||
pool: { connect: () => runtime.connect(), query: (...args: unknown[]) => runtime.poolQuery(...args) },
|
||
}));
|
||
|
||
import {
|
||
isBranchAvailable,
|
||
normalizeOptionLimit,
|
||
normalizeOptionQuery,
|
||
parseCatalogOptionQuery,
|
||
parseOptionCodes,
|
||
searchProductOptions,
|
||
searchSkuOptions,
|
||
} from '../src/services/productOptionSearchService';
|
||
|
||
const serviceSource = readFileSync(
|
||
new URL('../src/services/productOptionSearchService.ts', import.meta.url),
|
||
'utf8'
|
||
);
|
||
const routeSource = readFileSync(
|
||
new URL('../src/modules/workflow/routes/catalogRoutes.ts', import.meta.url),
|
||
'utf8'
|
||
);
|
||
const modulesSource = readFileSync(
|
||
new URL('../src/modules/businessModules.ts', import.meta.url),
|
||
'utf8'
|
||
);
|
||
|
||
function lastCall(): [string, unknown[]] {
|
||
return runtime.query.mock.calls[runtime.query.mock.calls.length - 1] as [string, unknown[]];
|
||
}
|
||
|
||
beforeEach(() => {
|
||
vi.clearAllMocks();
|
||
runtime.connect.mockResolvedValue({ query: runtime.query, release: runtime.release });
|
||
runtime.query.mockResolvedValue({ rows: [] });
|
||
runtime.poolQuery.mockResolvedValue({ rows: [{ exists: 1 }], rowCount: 1 });
|
||
});
|
||
|
||
describe('T1 limit / codes 参数规范化', () => {
|
||
it('limit:默认 20、0→1、999→50、闭区间 1..50', () => {
|
||
expect(normalizeOptionLimit(undefined)).toBe(20);
|
||
expect(normalizeOptionLimit('')).toBe(20);
|
||
expect(normalizeOptionLimit(0)).toBe(1);
|
||
expect(normalizeOptionLimit(-5)).toBe(1);
|
||
expect(normalizeOptionLimit(999)).toBe(50);
|
||
expect(normalizeOptionLimit(50)).toBe(50);
|
||
expect(normalizeOptionLimit(20.9)).toBe(20);
|
||
expect(normalizeOptionLimit('abc')).toBe(20);
|
||
});
|
||
|
||
it('codes:逗号分隔去空白/去重/最多 50,支持数组', () => {
|
||
expect(parseOptionCodes(' a, b, a ,, c ')).toEqual(['a', 'b', 'c']);
|
||
expect(parseOptionCodes(['x', ' y ', 'x'])).toEqual(['x', 'y']);
|
||
const many = Array.from({ length: 80 }, (_, i) => `SKU-${i}`);
|
||
expect(parseOptionCodes(many.join(','))).toHaveLength(50);
|
||
expect(parseOptionCodes(undefined)).toEqual([]);
|
||
});
|
||
});
|
||
|
||
describe('T1 SKU 搜索 SQL / limit / codes / missing_spec / branch', () => {
|
||
it('limit 传给 SQL 首位并 clamp;查询含三层排序与 branch NULL 兼容', async () => {
|
||
await searchSkuOptions({ branchCode: 'BR002', q: '黄玉米棒', limit: 999 });
|
||
const [sql, params] = lastCall();
|
||
expect(params[0]).toBe(50);
|
||
expect(sql).toContain('ILIKE');
|
||
expect(sql).toContain('sku_name');
|
||
expect(sql).toContain('sku_code');
|
||
// 三层:完整匹配 → 前缀 → 包含(ELSE 2)
|
||
expect(sql).toMatch(/=\s*LOWER\(\$3\)/);
|
||
expect(sql).toMatch(/ILIKE \$3 \|\| '%'/);
|
||
expect(sql).toContain('match_rank ASC');
|
||
// branch NULL 兼容(参照 listInboundSkuOptions)
|
||
expect(sql).toContain('s.branch_code IS NULL OR s.branch_code = $2');
|
||
expect(params[1]).toBe('BR002');
|
||
expect(params[2]).toBe('黄玉米棒');
|
||
// 无 codes 时不发回显查询
|
||
expect(runtime.query).toHaveBeenCalledTimes(1);
|
||
expect(runtime.release).toHaveBeenCalled();
|
||
});
|
||
|
||
it('q 为空:按名称返回前 N(不再前端全量加载)', async () => {
|
||
await searchSkuOptions({ branchCode: 'BR002', q: '', limit: 20 });
|
||
const [sql, params] = lastCall();
|
||
expect(params[2]).toBe('');
|
||
expect(sql).toContain("$3 = ''");
|
||
expect(params[0]).toBe(20);
|
||
});
|
||
|
||
it('codes 回显:忽略 status、最多 50、与 q 结果合并去重(q 优先)', async () => {
|
||
runtime.query
|
||
.mockResolvedValueOnce({ rows: [{ sku_code: 'SKU-A', sku_name: 'A', unit: 'kg', spec: null, category_code: null, branch_code: 'BR002' }] })
|
||
.mockResolvedValueOnce({
|
||
rows: [
|
||
{ sku_code: 'SKU-A', sku_name: 'A', unit: 'kg', spec: null, category_code: null, branch_code: 'BR002' },
|
||
{ sku_code: 'SKU-B', sku_name: 'B', unit: 'kg', spec: null, category_code: null, branch_code: null },
|
||
],
|
||
});
|
||
const rows = await searchSkuOptions({
|
||
branchCode: 'BR002',
|
||
q: 'A',
|
||
limit: 20,
|
||
codes: ['SKU-A', 'SKU-B'],
|
||
});
|
||
expect(rows.map((row) => row.sku_code)).toEqual(['SKU-A', 'SKU-B']);
|
||
expect(runtime.query).toHaveBeenCalledTimes(2);
|
||
const [recallSql, recallParams] = lastCall();
|
||
expect(recallSql).toContain('ANY($1::text[])');
|
||
expect(recallSql).not.toContain('status = 1');
|
||
expect(recallSql).toContain('branch_code IS NULL OR s.branch_code = $2');
|
||
expect(recallParams).toEqual([['SKU-A', 'SKU-B'], 'BR002', false]); // T5-B8:第三参 missingSpec
|
||
});
|
||
|
||
it('missing_spec=1:SQL 只返回空规格行(TRIM(spec) 为空)', async () => {
|
||
await searchSkuOptions({ branchCode: 'BR002', q: '', missingSpec: true });
|
||
const [sql, params] = lastCall();
|
||
expect(sql).toContain("s.spec IS NULL OR TRIM(s.spec) = ''");
|
||
expect(params[3]).toBe(true);
|
||
});
|
||
|
||
it('无分公司编码:不查库直接返回空(路由层会 400)', async () => {
|
||
expect(await searchSkuOptions({ branchCode: '', q: 'x' })).toEqual([]);
|
||
expect(runtime.connect).not.toHaveBeenCalled();
|
||
});
|
||
});
|
||
|
||
describe('T1 商品档案(product_catalog)搜索', () => {
|
||
it('item_type=product + status=1 + branch NULL 兼容 + name/code 三层排序 + limit clamp', async () => {
|
||
runtime.query
|
||
.mockResolvedValueOnce({ rows: [{ code: 'P-1', name: '示例', unit: 'kg', spec: null, branch_code: 'BR002' }] })
|
||
.mockResolvedValueOnce({ rows: [] });
|
||
const rows = await searchProductOptions({ branchCode: 'BR002', q: '示例', limit: 0, codes: 'P-1' });
|
||
expect(rows.map((row) => row.code)).toEqual(['P-1']);
|
||
const [mainSql, mainParams] = runtime.query.mock.calls[0] as [string, unknown[]];
|
||
// T6-N1:q 非空不预留 codes 名额 ⇒ mainLimit = limit = 1(关键词结果不减少)
|
||
expect(mainParams[0]).toBe(1);
|
||
expect(mainSql).toContain("p.item_type = 'product'");
|
||
expect(mainSql).toContain('p.status = 1');
|
||
expect(mainSql).toContain('p.branch_code IS NULL OR p.branch_code = $2');
|
||
expect(mainSql).toMatch(/=\s*LOWER\(\$3\)/);
|
||
expect(mainSql).toMatch(/ILIKE \$3 \|\| '%'/);
|
||
const [recallSql, recallParams] = lastCall();
|
||
expect(recallSql).toContain('ANY($1::text[])');
|
||
expect(recallSql).not.toContain('p.status = 1');
|
||
expect(recallParams).toEqual([['P-1'], 'BR002']);
|
||
});
|
||
});
|
||
|
||
describe('T1 路由参数解析 + 挂载 + 禁内嵌 SQL', () => {
|
||
it('q 兼容 search;limit 默认/clamp;codes 解析;missing_spec=1/true', () => {
|
||
expect(parseCatalogOptionQuery({ q: '黄玉米棒' })).toMatchObject({ q: '黄玉米棒', limit: 20, codes: [] });
|
||
expect(parseCatalogOptionQuery({ search: '旧参数' }).q).toBe('旧参数');
|
||
expect(parseCatalogOptionQuery({ limit: '0' }).limit).toBe(1);
|
||
expect(parseCatalogOptionQuery({ limit: '999' }).limit).toBe(50);
|
||
expect(parseCatalogOptionQuery({ codes: 'A,B,A' }).codes).toEqual(['A', 'B']);
|
||
expect(parseCatalogOptionQuery({ missing_spec: '1' }).missingSpec).toBe(true);
|
||
expect(parseCatalogOptionQuery({ missing_spec: 'true' }).missingSpec).toBe(true);
|
||
expect(parseCatalogOptionQuery({ missing_spec: '0' }).missingSpec).toBe(false);
|
||
});
|
||
|
||
it('路由:登录即可(authMiddleware)、缺 branch 400、响应 {data}、SQL 不在路由层', () => {
|
||
expect(routeSource).toContain("router.get('/sku-options', authMiddleware");
|
||
expect(routeSource).toContain("router.get('/product-options', authMiddleware");
|
||
expect(routeSource).toContain('getEffectiveBranchCode(ctx, readOperatingBranchCode(req))');
|
||
expect(routeSource).toContain("status(400)");
|
||
expect(routeSource).toContain('branch_required');
|
||
expect(routeSource).toContain('res.json({ data })');
|
||
expect(routeSource).not.toContain('SELECT ');
|
||
expect(serviceSource).toContain('SELECT');
|
||
expect(serviceSource).toContain('LIMIT $1');
|
||
});
|
||
|
||
it('businessModules 挂载:productModule 注册 catalogRoutes(/api/workflow/sku-options、/product-options)', () => {
|
||
expect(modulesSource).toContain("import { mountCatalogWorkflowRoutes } from './workflow/routes/catalogRoutes'");
|
||
expect(modulesSource).toContain('mountCatalogWorkflowRoutes(router)');
|
||
});
|
||
});
|
||
|
||
describe('T1 真实场景契约:>1000 条商品末位可精准命中', () => {
|
||
it('服务端关键词搜索(而非前端全量)——按名称精准搜「黄玉米棒」返回该行', async () => {
|
||
runtime.query.mockResolvedValueOnce({
|
||
rows: [
|
||
{
|
||
sku_code: 'SKU-1050',
|
||
sku_name: '黄玉米棒',
|
||
unit: '根',
|
||
spec: '散装',
|
||
category_code: 'CAT-VEG',
|
||
branch_code: null,
|
||
},
|
||
],
|
||
});
|
||
const rows = await searchSkuOptions({ branchCode: 'BR002', q: '黄玉米棒', limit: 20 });
|
||
expect(rows).toHaveLength(1);
|
||
expect(rows[0]).toMatchObject({ sku_code: 'SKU-1050', sku_name: '黄玉米棒', unit: '根' });
|
||
const [, params] = lastCall();
|
||
expect(params[0]).toBe(20);
|
||
expect(params[2]).toBe('黄玉米棒');
|
||
});
|
||
});
|
||
|
||
|
||
describe('T5 红队修复:limit/NUL/分支/反包含/status/missing_spec+codes', () => {
|
||
it('B1:q+codes 合并去重后 ≤ limit(codes 计入上限)', async () => {
|
||
const mainRows = Array.from({ length: 20 }, (_, i) => ({
|
||
sku_code: `MAIN-${i}`, sku_name: `主${i}`, unit: 'kg', spec: null, category_code: null, branch_code: null, status: 1,
|
||
}));
|
||
const codeRows = Array.from({ length: 40 }, (_, i) => ({
|
||
sku_code: `CODE-${i}`, sku_name: `码${i}`, unit: 'kg', spec: null, category_code: null, branch_code: null, status: 0,
|
||
}));
|
||
runtime.query.mockResolvedValueOnce({ rows: mainRows }).mockResolvedValueOnce({ rows: codeRows });
|
||
const rows = await searchSkuOptions({ branchCode: 'BR002', q: '主', limit: 20, codes: codeRows.map((r) => r.sku_code) });
|
||
expect(rows.length).toBeLessThanOrEqual(20);
|
||
expect(new Set(rows.map((r) => r.sku_code)).size).toBe(rows.length);
|
||
});
|
||
|
||
it('B1 修正:主结果已满 + 已选 codes 不在前排 ⇒ 回显优先保留且总数≤limit', async () => {
|
||
const mainRows = Array.from({ length: 18 }, (_, i) => ({
|
||
sku_code: `MAIN-${i}`, sku_name: `主${i}`, unit: 'kg', spec: null, category_code: null, branch_code: 'BR002', status: 1,
|
||
}));
|
||
runtime.query
|
||
.mockResolvedValueOnce({ rows: [{ sku_code: 'ZZTEST_T5P040', sku_name: 'ZZZ_T5_黄玉米棒加长版', unit: 'kg', spec: null, category_code: null, branch_code: 'BR002', status: 1 }] })
|
||
.mockResolvedValueOnce({ rows: mainRows });
|
||
const rows = await searchSkuOptions({ branchCode: 'BR002', q: '', limit: 20, codes: ['ZZTEST_T5P040'] });
|
||
expect(rows.length).toBeLessThanOrEqual(20);
|
||
expect(rows.map((row) => row.sku_code)).toContain('ZZTEST_T5P040');
|
||
// T7-P1′:q='' 按实际回显数预留 1 个名额 ⇒ 主查询 limit=19
|
||
expect(lastCallParamsFirst()).toBe(19);
|
||
});
|
||
|
||
function lastCallParamsFirst(): number {
|
||
const calls = runtime.query.mock.calls;
|
||
// 该断言在 SKU 主查询完成后想读主查询参数:取倒数第二个调用(最后一个为 codes 回显)
|
||
// q='' 时顺序为:codes 回显查询 → 主查询(主查询为最后一次调用)
|
||
const target = calls[calls.length - 1] as [string, unknown[]];
|
||
return Number(target[1][0]);
|
||
}
|
||
|
||
it('T5b:Product 39 个名称候选 + 目标 codes 排第40、limit=30 → 含目标且 ≤30', async () => {
|
||
const mainRows = Array.from({ length: 29 }, (_, i) => ({
|
||
code: `AAA_${String(i).padStart(2, '0')}`, name: `AAA_${i}`, unit: 'kg', spec: null, branch_code: 'BR002', status: 1,
|
||
}));
|
||
runtime.query
|
||
.mockResolvedValueOnce({ rows: [{ code: 'ZZTEST_T5P040', name: 'ZZZ_T5_黄玉米棒加长版', unit: 'kg', spec: null, branch_code: 'BR002', status: 1 }] })
|
||
.mockResolvedValueOnce({ rows: mainRows });
|
||
const rows = await searchProductOptions({ branchCode: 'BR002', q: '', limit: 30, codes: ['ZZTEST_T5P040'] });
|
||
expect(rows.length).toBeLessThanOrEqual(30);
|
||
expect(rows.map((row) => row.code)).toContain('ZZTEST_T5P040');
|
||
// 主查询预留 1 个 codes 名额:30 - 1 = 29
|
||
const mainCall = runtime.query.mock.calls[runtime.query.mock.calls.length - 1] as [string, unknown[]];
|
||
expect(Number(mainCall[1][0])).toBe(29);
|
||
});
|
||
|
||
it('B3:NUL/控制字符 → 400 invalid_request;10k 搜索词截断到 200', async () => {
|
||
expect(() => normalizeOptionQuery('黄\u0000玉米')).toThrow();
|
||
try {
|
||
normalizeOptionQuery('黄\u0000玉米');
|
||
} catch (error: any) {
|
||
expect(error.status).toBe(400);
|
||
expect(error.code).toBe('invalid_request');
|
||
}
|
||
expect(normalizeOptionQuery('x'.repeat(10000))).toHaveLength(200);
|
||
expect(() => normalizeOptionQuery('黄玉米棒😀')).not.toThrow();
|
||
await expect(searchSkuOptions({ branchCode: 'BR002', q: '\u0000' })).rejects.toMatchObject({ status: 400 });
|
||
});
|
||
|
||
it('B4/N4/N5:分公司校验(branches status=1 + tenant_schema_registry active)', async () => {
|
||
runtime.poolQuery
|
||
.mockResolvedValueOnce({ rows: [{ status: 1 }], rowCount: 1 })
|
||
.mockResolvedValueOnce({ rows: [{ schema_name: 'tenant_br002', status: 'active' }], rowCount: 1 });
|
||
expect(await isBranchAvailable('BR002')).toBe(true);
|
||
expect(runtime.poolQuery.mock.calls[0][0]).toContain('FROM public.branches');
|
||
|
||
runtime.poolQuery.mockResolvedValueOnce({ rows: [], rowCount: 0 });
|
||
expect(await isBranchAvailable('BR999')).toBe(false);
|
||
|
||
// N5:停用分公司
|
||
runtime.poolQuery.mockResolvedValueOnce({ rows: [{ status: 0 }], rowCount: 1 });
|
||
expect(await isBranchAvailable('BR003')).toBe(false);
|
||
|
||
// N4:有分公司但无 active tenant schema
|
||
runtime.poolQuery
|
||
.mockResolvedValueOnce({ rows: [{ status: 1 }], rowCount: 1 })
|
||
.mockResolvedValueOnce({ rows: [{ schema_name: 'tenant_br002', status: 'inactive' }], rowCount: 1 });
|
||
expect(await isBranchAvailable('BR002')).toBe(false);
|
||
|
||
// 旧库无注册表(42P01)→ 兼容放行(branches 已校验)
|
||
runtime.poolQuery
|
||
.mockResolvedValueOnce({ rows: [{ status: 1 }], rowCount: 1 })
|
||
.mockRejectedValueOnce(Object.assign(new Error('relation does not exist'), { code: '42P01' }));
|
||
expect(await isBranchAvailable('BR002')).toBe(true);
|
||
});
|
||
|
||
it('B5:reverse_contains=1 时 SQL 增加反向包含且参数默认关闭/开启', async () => {
|
||
await searchSkuOptions({ branchCode: 'BR002', q: '黄玉米棒加长版', limit: 5 });
|
||
let [sql, params] = lastCall();
|
||
// T6-N6:位置匹配(不再用 LIKE 反包含,避免 %/_ 假阳性)
|
||
expect(sql).toContain('POSITION(LOWER(COALESCE(s.sku_name, \'\')) IN LOWER($3)) > 0');
|
||
expect(params[4]).toBe(false);
|
||
|
||
await searchSkuOptions({ branchCode: 'BR002', q: '黄玉米棒加长版', limit: 5, reverseContains: true });
|
||
[sql, params] = lastCall();
|
||
expect(params[4]).toBe(true);
|
||
});
|
||
|
||
it('B8/B2:missing_spec 同时过滤 codes 回显;返回 status 字段', async () => {
|
||
runtime.query
|
||
.mockResolvedValueOnce({ rows: [{ sku_code: 'OLD-1', sku_name: '旧', unit: 'kg', spec: null, category_code: null, branch_code: null, status: 0 }] })
|
||
.mockResolvedValueOnce({ rows: [] });
|
||
const rows = await searchSkuOptions({ branchCode: 'BR002', codes: ['OLD-1'], missingSpec: true, limit: 20 });
|
||
expect(rows[0]).toMatchObject({ sku_code: 'OLD-1', status: 0 });
|
||
// q='' 时 codes 查询先执行(calls[0]),第三参 = missingSpec
|
||
const codesCall = runtime.query.mock.calls[0] as [string, unknown[]];
|
||
expect(codesCall[1][2]).toBe(true);
|
||
expect(String(codesCall[0])).toContain("TRIM(s.spec) = ''");
|
||
});
|
||
|
||
it('B2:正常候选返回 status=1(路由透传)', async () => {
|
||
runtime.query.mockResolvedValueOnce({
|
||
rows: [{ sku_code: 'SKU-1', sku_name: '新', unit: 'kg', spec: null, category_code: null, branch_code: null, status: 1 }],
|
||
});
|
||
const rows = await searchSkuOptions({ branchCode: 'BR002', q: '新', limit: 5 });
|
||
expect(rows[0].status).toBe(1);
|
||
});
|
||
});
|
||
|
||
|
||
describe('T6 红队二轮:N1/N2/N3/N6/B2', () => {
|
||
it('N1:q 非空不预留 codes 名额 —— 关键词结果不减少;额度内补 codes;总≤limit', async () => {
|
||
const qRows = Array.from({ length: 5 }, (_, i) => ({
|
||
sku_code: `HIT-${i}`, sku_name: `黄玉米棒${i}`, unit: 'kg', spec: null, category_code: null, branch_code: 'BR002', status: 1,
|
||
}));
|
||
runtime.query
|
||
.mockResolvedValueOnce({ rows: qRows })
|
||
.mockResolvedValueOnce({ rows: [{ sku_code: 'OLD-1', sku_name: '旧品', unit: 'kg', spec: null, category_code: null, branch_code: 'BR002', status: 0 }] });
|
||
const rows = await searchSkuOptions({ branchCode: 'BR002', q: '黄玉米棒', limit: 5, codes: ['OLD-1'] });
|
||
// 主查询不预留:q 结果 5 条全部保留(不被 codes 挤掉),codes 无剩余空位丢弃
|
||
expect(rows).toHaveLength(5);
|
||
expect(rows.every((row) => row.sku_code.startsWith('HIT-'))).toBe(true);
|
||
const mainCall = runtime.query.mock.calls[runtime.query.mock.calls.length - 2] as [string, unknown[]];
|
||
expect(Number(mainCall[1][0])).toBe(5);
|
||
});
|
||
|
||
it('N1:q 为空时目标 codes 不在前 N 仍回显(回显优先占位)', async () => {
|
||
const mainRows = Array.from({ length: 29 }, (_, i) => ({
|
||
sku_code: `AAA_${i}`, sku_name: `AAA_${i}`, unit: 'kg', spec: null, category_code: null, branch_code: 'BR002', status: 1,
|
||
}));
|
||
runtime.query
|
||
.mockResolvedValueOnce({ rows: [{ sku_code: 'ZZTEST_T6P040', sku_name: 'ZZZ_T6_黄玉米棒', unit: 'kg', spec: null, category_code: null, branch_code: 'BR002', status: 1 }] })
|
||
.mockResolvedValueOnce({ rows: mainRows });
|
||
const rows = await searchSkuOptions({ branchCode: 'BR002', q: '', limit: 30, codes: ['ZZTEST_T6P040'] });
|
||
expect(rows).toHaveLength(30);
|
||
expect(rows.map((row) => row.sku_code)).toContain('ZZTEST_T6P040');
|
||
});
|
||
|
||
it('N2:codes 含 NUL → 400 invalid_request(不再 500/22021)', async () => {
|
||
expect(() => parseOptionCodes('ZZTEST_A01\u0000X')).toThrow();
|
||
try {
|
||
parseOptionCodes('ZZTEST_A01\u0000X');
|
||
} catch (error: any) {
|
||
expect(error.status).toBe(400);
|
||
expect(error.code).toBe('invalid_request');
|
||
}
|
||
await expect(searchSkuOptions({ branchCode: 'BR002', codes: ['A\u0000X'] })).rejects.toMatchObject({ status: 400 });
|
||
});
|
||
|
||
it('N3:q 内 \n/\t/\r 清洗为空格(不整行失败);仅 NUL 拒绝', () => {
|
||
expect(normalizeOptionQuery('黄玉米\n棒')).toBe('黄玉米 棒');
|
||
expect(normalizeOptionQuery(' 黄\t玉米\r棒 ')).toBe('黄 玉米 棒');
|
||
expect(() => normalizeOptionQuery('黄\u0000玉米')).toThrow();
|
||
});
|
||
|
||
it('N6:反向包含 SQL 使用 POSITION 而非 LIKE(%/_ 不假阳性)', async () => {
|
||
await searchSkuOptions({ branchCode: 'BR002', q: '黄玉米棒加长版', limit: 5, reverseContains: true });
|
||
const [sql] = lastCall();
|
||
expect(sql).toContain('POSITION(LOWER(COALESCE(s.sku_name');
|
||
expect(sql).not.toContain("$3 ILIKE '%' || COALESCE(s.sku_name");
|
||
});
|
||
|
||
it('B2:最终 SELECT 含 status,服务返回行 key 形状一致(不靠 mock 掩盖)', async () => {
|
||
runtime.query.mockResolvedValueOnce({
|
||
rows: [{ sku_code: 'SKU-1', sku_name: '新', unit: 'kg', spec: null, category_code: null, branch_code: 'BR002', status: 1 }],
|
||
});
|
||
const rows = await searchSkuOptions({ branchCode: 'BR002', q: '新', limit: 5 });
|
||
expect(Object.keys(rows[0]).sort()).toEqual(
|
||
['branch_code', 'category_code', 'sku_code', 'sku_name', 'spec', 'status', 'unit'].sort()
|
||
);
|
||
const [sql] = lastCall();
|
||
expect(sql).toMatch(/SELECT sku_code, sku_name, unit, spec, category_code, branch_code, status/);
|
||
});
|
||
});
|
||
|
||
|
||
describe('T7-P1′:q 为空时按实际回显数预留(不存在 codes 不挤空初始候选)', () => {
|
||
it("q=''+20 个不存在 codes、limit=20 → 初始候选 ≥1 且 ≤20(主查询限 20)", async () => {
|
||
const mainRows = Array.from({ length: 20 }, (_, i) => ({
|
||
sku_code: `MAIN-${i}`, sku_name: `候选${i}`, unit: 'kg', spec: null, category_code: null, branch_code: 'BR002', status: 1,
|
||
}));
|
||
runtime.query
|
||
.mockResolvedValueOnce({ rows: [] }) // codes 实际不存在
|
||
.mockResolvedValueOnce({ rows: mainRows }); // 主查询
|
||
const codes = Array.from({ length: 20 }, (_, i) => `MISSING-${i}`);
|
||
const rows = await searchSkuOptions({ branchCode: 'BR002', q: '', limit: 20, codes });
|
||
expect(rows.length).toBeGreaterThanOrEqual(1);
|
||
expect(rows.length).toBeLessThanOrEqual(20);
|
||
const mainCall = runtime.query.mock.calls[runtime.query.mock.calls.length - 1] as [string, unknown[]];
|
||
expect(Number(mainCall[1][0])).toBe(20); // 实际回显 0 ⇒ 不预留,主查 20
|
||
});
|
||
|
||
it("q=''+20 个存在 codes、limit=20 → 回显优先且至少留 1 条主候选", async () => {
|
||
const recalled = Array.from({ length: 20 }, (_, i) => ({
|
||
sku_code: `CODE-${i}`, sku_name: `码${i}`, unit: 'kg', spec: null, category_code: null, branch_code: 'BR002', status: 1,
|
||
}));
|
||
runtime.query
|
||
.mockResolvedValueOnce({ rows: recalled })
|
||
.mockResolvedValueOnce({ rows: [{ sku_code: 'MAIN-1', sku_name: '主', unit: 'kg', spec: null, category_code: null, branch_code: 'BR002', status: 1 }] });
|
||
const rows = await searchSkuOptions({
|
||
branchCode: 'BR002', q: '', limit: 20, codes: recalled.map((row) => row.sku_code),
|
||
});
|
||
expect(rows.length).toBeLessThanOrEqual(20);
|
||
expect(rows.some((row) => row.sku_code === 'MAIN-1')).toBe(true); // 至少 1 条主候选
|
||
const mainCall = runtime.query.mock.calls[runtime.query.mock.calls.length - 1] as [string, unknown[]];
|
||
expect(Number(mainCall[1][0])).toBe(1); // 20 - min(20, 19) = 1
|
||
});
|
||
});
|