import express from 'express'; import request from 'supertest'; import { readFileSync } from 'fs'; import path from 'path'; import { beforeEach, describe, expect, it, vi } from 'vitest'; /** * 称端合并入库:照片闸门导致的「假失败 500」与 already_submitted 幂等。 * 背景与证据链见 docs/design/20260917-weigh-merge-photo-gate-and-false-failure.md */ const mocks = vi.hoisted(() => ({ submitInspectionWeighMergeByProduct: vi.fn(), consoleError: vi.fn(), })); vi.mock('../src/middleware/auth', () => ({ authMiddleware: (req: any, _res: any, next: any) => { req.userId = 'u1'; next(); }, })); vi.mock('../src/routes/mobile/mobileShared', () => ({ requireInspectionManageRole: async () => undefined, requireMobileRoles: () => undefined, requirePickingAccess: async () => undefined, })); // 只替换合并入库入口,其余保持真实实现(路由挂载时会用到同模块其它导出) vi.mock('../src/services/weighStationService', async (importOriginal) => { const actual = await importOriginal>(); return { ...actual, submitInspectionWeighMergeByProduct: mocks.submitInspectionWeighMergeByProduct }; }); import mobileWarehouseRoutes from '../src/routes/mobile/mobileWarehouseRoutes'; const readSource = (rel: string) => readFileSync(path.join(__dirname, '..', rel), 'utf8'); function buildApp() { const app = express(); app.use(express.json({ limit: '10mb' })); app.use('/api/mobile', mobileWarehouseRoutes); return app; } describe('POST /api/mobile/inspection/complete-merge:幂等与可观测', () => { beforeEach(() => { vi.clearAllMocks(); vi.spyOn(console, 'error').mockImplementation(mocks.consoleError); }); it('已提交(already_submitted)返回 200 幂等结果,而不是 400', async () => { mocks.submitInspectionWeighMergeByProduct.mockRejectedValue( Object.assign(new Error('该验收单已提交,不能重复验收'), { status: 400, code: 'already_submitted', }) ); const res = await request(buildApp()) .post('/api/mobile/inspection/complete-merge') .send({ id: 'abc-123', actual_qty: 5, force_complete: true }); expect(res.status).toBe(200); expect(res.body.success).toBe(true); expect(res.body.data.alreadySubmitted).toBe(true); // 幂等分支不是错误,不应打 error 日志 expect(mocks.consoleError).not.toHaveBeenCalled(); }); it('真实失败仍按原状返回,并写 error 日志(含单号与 code)', async () => { mocks.submitInspectionWeighMergeByProduct.mockRejectedValue( Object.assign(new Error('预包装商品验收校验未通过'), { status: 400, code: 'prepack_inspection_invalid', }) ); const res = await request(buildApp()) .post('/api/mobile/inspection/complete-merge') .send({ id: 'abc-456', actual_qty: 30, force_complete: true }); expect(res.status).toBe(400); expect(res.body.error).toBe('prepack_inspection_invalid'); expect(mocks.consoleError).toHaveBeenCalled(); const logged = String(mocks.consoleError.mock.calls[0]?.[0] || ''); expect(logged).toContain('complete-merge'); expect(logged).toContain('abc-456'); expect(logged).toContain('prepack_inspection_invalid'); }); it('入库成功照常 200', async () => { mocks.submitInspectionWeighMergeByProduct.mockResolvedValue({ merged: true, forceComplete: true, mergedCount: 2, }); const res = await request(buildApp()) .post('/api/mobile/inspection/complete-merge') .send({ id: 'abc-789', actual_qty: 7, force_complete: true }); expect(res.status).toBe(200); expect(res.body.data.merged).toBe(true); }); }); describe('服务端源码契约:兄弟行放行 + 裸 Error 不再成 500', () => { const weigh = readSource('src/services/weighStationService.ts'); const compliance = readSource('src/services/inspectionComplianceService.ts'); const routes = readSource('src/routes/mobile/mobileWarehouseRoutes.ts'); it('合并入库为兄弟行放行照片/预包装校验(只有第 1 行强校验)', () => { expect(weigh).toContain('MERGE_SIBLING_COMPLIANCE_OPTIONS'); expect(weigh).toContain('allowMissingPhotos: true'); expect(weigh).toContain('allowBypassPrepackagedCheck: true'); // 分配行:i>0 传选项;清零结案行:同样传选项 expect(weigh).toContain('i === 0 ? undefined : MERGE_SIBLING_COMPLIANCE_OPTIONS'); expect(weigh.match(/MERGE_SIBLING_COMPLIANCE_OPTIONS/g)?.length ?? 0).toBeGreaterThanOrEqual(3); }); it('照片/预包装/单价三处校验失败必须是 400 + code,不得裸抛', () => { expect(compliance).not.toContain("throw new Error('请先拍照验收')"); expect(compliance).not.toContain("throw new Error(prepackValidation.message || '预包装商品验收校验未通过')"); expect(compliance).not.toContain("throw new Error('入库单价无效')"); for (const code of ['inspection_photo_required', 'prepack_inspection_invalid', 'invalid_cost']) { expect(compliance, code).toContain(code); } }); it('COMMIT 之后的订单推进准备整块有兜底,失败不上抛', () => { expect(compliance).toContain('advancePrepError'); expect(compliance).toContain('入库后订单推进准备失败(已入库,等待同步任务重试)'); // 兜底必须发生在 COMMIT 之后 expect(compliance.indexOf('await client.query(\'COMMIT\')')).toBeLessThan( compliance.indexOf('advancePrepError') ); }); it('路由 catch 必须记日志(5xx 可排查)', () => { expect(routes).toContain('[mobile/inspection] complete-merge 失败'); expect(routes).toContain('[mobile/inspection] complete 失败'); expect(routes).toContain("error?.code === 'already_submitted'"); }); });