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); }); }); /** * 批量入库(bulkStockInbound)也接档案回写(2026-10-16 方案 A): * 行上带 `archive` ⇒ 在该行事务内写 `product_catalog.spec`;不带 ⇒ 不产生任何档案写。 * 设计见 docs/design/20261016-批量入库规格回写商品档案.md。 */ describe('bulkStockInbound · 档案回写接线', () => { beforeEach(() => { query.mockReset(); }); function mockBulkQueries(onSql?: (sql: string, params?: unknown[]) => void) { query.mockImplementation(async (sql: string, params?: unknown[]) => { const s = String(sql); onSql?.(s, params); 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', available_qty: 5, inserted: true }] }; } return { rowCount: 0, rows: [] }; }); } it('行带 archive ⇒ 该行事务里出现规格回写(BEGIN 之后、COMMIT 之前)', async () => { const seen: string[] = []; let catalogParams: unknown[] | undefined; mockBulkQueries((s, params) => { seen.push(s); if (s.includes('UPDATE product_catalog')) catalogParams = params; }); const { bulkStockInbound } = await import('../src/services/stockInboundService'); const res = await bulkStockInbound({ branchCode: 'B1', rows: [{ skuCode: 'SKU1', qty: 5, unitCost: 0, archive: { spec: '约500g' } }], }); expect(res.ok_count).toBe(1); expect(catalogParams).toEqual([true, '约500g', false, null, 'SKU1']); const beginIdx = seen.findIndex((s) => s.includes('BEGIN')); const writeIdx = seen.findIndex((s) => s.includes('UPDATE product_catalog')); const commitIdx = seen.findIndex((s) => s.includes('COMMIT')); expect(beginIdx).toBeGreaterThanOrEqual(0); expect(writeIdx).toBeGreaterThan(beginIdx); expect(commitIdx).toBeGreaterThan(writeIdx); }); it('行不带 archive ⇒ 一条档案写都不产生(人工值不得冒充 AI/预填值)', async () => { const seen: string[] = []; mockBulkQueries((s) => seen.push(s)); const { bulkStockInbound } = await import('../src/services/stockInboundService'); const res = await bulkStockInbound({ branchCode: 'B1', rows: [{ skuCode: 'SKU1', qty: 5, unitCost: 0 }], }); expect(res.ok_count).toBe(1); expect(seen.some((s) => s.includes('UPDATE product_catalog'))).toBe(false); expect(seen.some((s) => s.includes('UPDATE skus SET origin'))).toBe(false); }); });