Files
SupplierSystem/server/tests/stockInboundArchiveWriteback.test.ts
T
Ubuntu 1d47267a8d
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
chore(sync): 提交剩余本地改动(规则文档 / 部署配置 / 小程序入库归档 / 工具与测试)
- .cursor/rules + AGENTS.md:供应商二次开发的隔离硬规则落库(库/端口/上传目录/对象前缀)
- 部署与本地配置:docker-compose*.yml、.env.*.example(仅占位值)、start-split-native / sync-prod-db-to-local 脚本
- 小程序:入库归档识别(stockInboundArchive + 识别与入库面板改动)
- tools:设计门禁脚本(check-migrations / run-all / verify-facts)与架构图脚本更新
- docs:跨系统改价改量审核、第三方订单退货跟随、免入库推进、500+ 分公司规模改造、
  拍照入库识别与档案回写等设计文档;对接清单新增 §4.5.4 我方回执(第六批端到端)
- server:存量修数脚本(legacy CS / 供应商应付 / 结算口径)、采购耳标核对脚本;
  新增测试:入库归档回写、租户优选顺序、规模并发
2026-10-09 22:28:15 +08:00

279 lines
11 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 { describe, expect, it, vi, beforeEach } from 'vitest';
/**
* 拍照入库:人工改过的规格/品牌/厂家回写商品档案。
* 口径见 docs/design/20261012-拍照入库识别规格厂家品牌与档案回写.md §3.2。
*
* 三条不变量:
* ① 只写调用方显式传进来的字段(未传 = 不写,防未经确认的 AI 识别值污染档案);
* ② 规格/品牌写 `product_catalog`(触发器再同步到 skus),厂家**显式**写 `skus.origin`;
* ③ 一个字段都没传 ⇒ 一条 SQL 都不产生。
*/
const query = vi.fn();
const connect = async () => ({ query, release: () => undefined });
// 注意:模块图里 `tenantScope.ts` → `tenantSchemaFallback.ts` 会在**导入期**调用
// `getRawPoolQuery()` / `getRawPoolConnect()`。旧测试(tests/stockInbound.test.ts)漏了这两个导出,
// 导致该文件 3 个用例在导入期即失败(2026-10-12 实测:与本次改动无关,stash 后同样失败)。
// 本文件补齐,勿删。
vi.mock('../src/db', () => ({
pool: { connect, query },
query,
getRawPoolQuery: () => query,
getRawPoolConnect: () => connect,
}));
vi.mock('../src/services/auditService', () => ({
writeAuditLog: vi.fn(async () => undefined),
}));
vi.mock('../src/services/stockModeService', () => ({
resolveStockMode: vi.fn(async () => 'inventory'),
}));
vi.mock('../src/services/storageUploadService', () => ({
saveBase64Upload: vi.fn(async () => null),
}));
vi.mock('../src/services/zeroSupplyCostConfigService', () => ({
isZeroSupplyCostAllowed: vi.fn(async () => false),
}));
vi.mock('../src/services/inventorySurplusCostService', () => ({
upsertInventoryHoldingCost: vi.fn(async () => undefined),
}));
vi.mock('../src/services/independentInboundService', () => ({
createIndependentInboundInspection: vi.fn(async () => ({
inspectionId: 'INS1',
batchNo: 'STK1',
})),
}));
type Call = { sql: string; params?: unknown[] };
function fakeDb(calls: Call[]) {
return {
query: async (sql: string, params?: unknown[]) => {
calls.push({ sql: String(sql), params });
return { rowCount: 0, rows: [] };
},
};
}
describe('applyArchiveWriteback', () => {
beforeEach(() => {
query.mockReset();
});
it('规格+品牌写 product_catalog,厂家显式写 skus.origin', async () => {
const calls: Call[] = [];
const { applyArchiveWriteback } = await import('../src/services/stockInboundService');
await applyArchiveWriteback(fakeDb(calls) as any, {
skuCode: 'SKU1',
branchCode: 'B1',
archive: { spec: '约500g', brand: '蒙牛', manufacturer: '内蒙古' },
});
const catalog = calls.find((c) => c.sql.includes('UPDATE product_catalog'));
const skus = calls.find((c) => c.sql.includes('UPDATE skus SET origin'));
expect(catalog).toBeTruthy();
expect(skus).toBeTruthy();
// 两个「是否写入」开关都为 true,值按 spec / brand 顺序传入
expect(catalog!.params).toEqual([true, '约500g', true, '蒙牛', 'SKU1']);
expect(skus!.params).toEqual(['SKU1', '内蒙古']);
// 厂家绝不能写进 product_catalog(该表无 origin 列)
expect(catalog!.sql.includes('origin')).toBe(false);
});
it('只传规格时,品牌开关为 false(不得顺手清空品牌)', async () => {
const calls: Call[] = [];
const { applyArchiveWriteback } = await import('../src/services/stockInboundService');
await applyArchiveWriteback(fakeDb(calls) as any, {
skuCode: 'SKU1',
branchCode: 'B1',
archive: { spec: '5kg' },
});
const catalog = calls.find((c) => c.sql.includes('UPDATE product_catalog'));
expect(catalog!.params).toEqual([true, '5kg', false, null, 'SKU1']);
// 没传厂家 ⇒ 不碰 skus.origin
expect(calls.some((c) => c.sql.includes('UPDATE skus SET origin'))).toBe(false);
});
it('只传厂家时,不产生 product_catalog 写入', async () => {
const calls: Call[] = [];
const { applyArchiveWriteback } = await import('../src/services/stockInboundService');
await applyArchiveWriteback(fakeDb(calls) as any, {
skuCode: 'SKU1',
branchCode: 'B1',
archive: { manufacturer: '蒙牛' },
});
expect(calls.some((c) => c.sql.includes('UPDATE product_catalog'))).toBe(false);
expect(calls.filter((c) => c.sql.includes('UPDATE skus SET origin')).length).toBe(1);
});
it('空串是一次真实的清空(开关为 true、值为空)', async () => {
const calls: Call[] = [];
const { applyArchiveWriteback } = await import('../src/services/stockInboundService');
await applyArchiveWriteback(fakeDb(calls) as any, {
skuCode: 'SKU1',
branchCode: 'B1',
archive: { brand: '' },
});
const catalog = calls.find((c) => c.sql.includes('UPDATE product_catalog'));
expect(catalog!.params).toEqual([false, null, true, '', 'SKU1']);
});
it('未传 archive / 空对象 ⇒ 一条 SQL 都不产生', async () => {
const calls: Call[] = [];
const { applyArchiveWriteback } = await import('../src/services/stockInboundService');
await applyArchiveWriteback(fakeDb(calls) as any, { skuCode: 'SKU1', branchCode: 'B1' });
await applyArchiveWriteback(fakeDb(calls) as any, {
skuCode: 'SKU1',
branchCode: 'B1',
archive: null,
});
await applyArchiveWriteback(fakeDb(calls) as any, {
skuCode: 'SKU1',
branchCode: 'B1',
archive: {},
});
expect(calls.length).toBe(0);
});
});
describe('inboundFromWeigh · 档案回写接线', () => {
beforeEach(() => {
query.mockReset();
});
function mockInboundQueries(onSql?: (sql: string) => void) {
query.mockImplementation(async (sql: string) => {
const s = String(sql);
onSql?.(s);
if (s.includes('BEGIN') || s.includes('ROLLBACK') || s.includes('COMMIT')) {
return { rowCount: 0, rows: [] };
}
if (s.includes('FROM skus')) {
return { rowCount: 1, rows: [{ sku_code: 'SKU1', sku_name: '番茄', unit: '斤' }] };
}
if (s.includes('INSERT INTO inventory ')) {
return { rowCount: 1, rows: [{ id: '1' }] };
}
return { rowCount: 0, rows: [] };
});
}
it('传了 archive ⇒ 入库事务里出现档案回写;未传 ⇒ 没有', async () => {
const withArchive: string[] = [];
mockInboundQueries((s) => withArchive.push(s));
const { inboundFromWeigh: run1 } = await import('../src/services/stockInboundService');
await run1({
skuCode: 'SKU1',
qty: 2,
unitCost: 3.5,
branchCode: 'B1',
archive: { spec: '约500g', manufacturer: '内蒙古' },
});
expect(withArchive.some((s) => s.includes('UPDATE product_catalog'))).toBe(true);
expect(withArchive.some((s) => s.includes('UPDATE skus SET origin'))).toBe(true);
// 回写必须在 COMMIT 之前(同事务)
expect(withArchive.findIndex((s) => s.includes('UPDATE product_catalog'))).toBeLessThan(
withArchive.findIndex((s) => s.includes('COMMIT'))
);
const withoutArchive: string[] = [];
mockInboundQueries((s) => withoutArchive.push(s));
const { inboundFromWeigh: run2 } = await import('../src/services/stockInboundService');
await run2({ skuCode: 'SKU1', qty: 2, unitCost: 3.5, branchCode: 'B1' });
expect(withoutArchive.some((s) => s.includes('UPDATE product_catalog'))).toBe(false);
expect(withoutArchive.some((s) => s.includes('UPDATE skus SET origin'))).toBe(false);
});
it('校验失败(过手商品)⇒ 档案回写随事务 ROLLBACK,不最终落库', async () => {
const seen: string[] = [];
const { resolveStockMode } = await import('../src/services/stockModeService');
(resolveStockMode as any).mockResolvedValueOnce('pass_through');
query.mockImplementation(async (sql: string) => {
const s = String(sql);
seen.push(s);
if (s.includes('FROM skus')) {
return { rowCount: 1, rows: [{ sku_code: 'SKU1', sku_name: '番茄', unit: '斤' }] };
}
return { rowCount: 0, rows: [] };
});
const { inboundFromWeigh } = await import('../src/services/stockInboundService');
await expect(
inboundFromWeigh({
skuCode: 'SKU1',
qty: 2,
unitCost: 3.5,
branchCode: 'B1',
archive: { spec: '约500g', brand: '蒙牛', manufacturer: '内蒙古' },
})
).rejects.toMatchObject({ code: 'pass_through_rejected' });
// 回写语句确实在事务内被发出,但**必须发生在 BEGIN 之后、ROLLBACK 之前** ——
// 「不最终落库」靠的是回滚,不是靠不写;别把断言写成"一条 UPDATE 都没有"
// (那是错的:回写在 pass_through 判定之前执行,见 stockInboundService 注释)。
const beginIdx = seen.findIndex((s) => s.includes('BEGIN'));
const writeIdx = seen.findIndex((s) => s.includes('UPDATE product_catalog'));
const rollbackIdx = seen.findIndex((s) => s.includes('ROLLBACK'));
expect(beginIdx).toBeGreaterThanOrEqual(0);
expect(writeIdx).toBeGreaterThan(beginIdx);
expect(rollbackIdx).toBeGreaterThan(writeIdx);
expect(seen.some((s) => s.includes('COMMIT'))).toBe(false);
});
});
describe('normalizeArchive(移动端入参归一化)', () => {
it('未传 / 非对象 / 空对象 / 无有效字段 ⇒ null', async () => {
const { normalizeArchive } = await import('../src/services/stockInboundService');
expect(normalizeArchive(undefined)).toBeNull();
expect(normalizeArchive(null)).toBeNull();
expect(normalizeArchive('spec=x')).toBeNull();
expect(normalizeArchive(['spec'])).toBeNull();
expect(normalizeArchive({})).toBeNull();
// 只带 null 值 = 没有有效字段
expect(normalizeArchive({ spec: null })).toBeNull();
// 白名单外的键被忽略
expect(normalizeArchive({ qty: '5' })).toBeNull();
});
it('只保留客户端真正上报的字段(未上报的键不出现)', async () => {
const { normalizeArchive } = await import('../src/services/stockInboundService');
expect(normalizeArchive({ spec: '约500g' })).toEqual({ spec: '约500g' });
expect(Object.keys(normalizeArchive({ brand: '蒙牛' }) || {})).toEqual(['brand']);
expect(normalizeArchive({ manufacturer: '内蒙古' })).toEqual({ manufacturer: '内蒙古' });
expect(normalizeArchive({ spec: 'a', brand: 'b', manufacturer: 'c' })).toEqual({
spec: 'a',
brand: 'b',
manufacturer: 'c',
});
});
it('空串保留(= 一次真实的清空),数字转字符串', async () => {
const { normalizeArchive } = await import('../src/services/stockInboundService');
expect(normalizeArchive({ brand: '' })).toEqual({ brand: '' });
expect(normalizeArchive({ spec: 500 })).toEqual({ spec: '500' });
});
it('超长值截断,防止把超大载荷带进 SQL', async () => {
const { normalizeArchive } = await import('../src/services/stockInboundService');
const long = 'x'.repeat(500);
const out = normalizeArchive({ spec: long });
expect(out!.spec!.length).toBe(200);
});
});