/** @jest-environment node */ import { createHash } from 'node:crypto' import { mkdir, lstat, rename } from 'node:fs/promises' import { createDesktopDelivery } from '@/lib/desktop-client/deliveries' import { findDetailMaterialMatches } from '@/lib/detail-generator/materials' import { queueXiaoyiAutoListingNotification } from '@/lib/external-auto-listing' import { prisma } from '@/lib/prisma' import { getOwnedUploadSession } from '@/lib/upload-sessions' import { inspectUploadOutput } from '@/lib/upload-paths' import fixture from './fixtures/xiaoyi-free-barcode.json' jest.mock('@/lib/prisma', () => ({ prisma: { $queryRawUnsafe: jest.fn(), $queryRaw: jest.fn(), $transaction: jest.fn(), $executeRawUnsafe: jest.fn(), material: { create: jest.fn() }, } })) jest.mock('@/lib/detail-generator/materials', () => ({ findDetailMaterialMatches: jest.fn() })) jest.mock('node:fs', () => ({ createReadStream: jest.fn(() => [Buffer.from('x')]) })) jest.mock('node:fs/promises', () => ({ mkdir: jest.fn(), lstat: jest.fn(), copyFile: jest.fn(), rename: jest.fn(), unlink: jest.fn() })) jest.mock('@/lib/material-facets-cache', () => ({ invalidateMaterialFacetsCache: jest.fn() })) jest.mock('@/lib/remote-upload-sync', () => ({ syncStoredUploadFileToRemote: jest.fn() })) jest.mock('@/lib/upload-sessions', () => ({ getOwnedUploadSession: jest.fn() })) jest.mock('@/lib/upload-paths', () => ({ getUploadRootDir: () => '/test', buildStoredUploadPath: jest.fn(), getUploadStorageExtension: jest.fn(), inspectUploadOutput: jest.fn(), })) jest.mock('@/lib/path-security', () => ({ resolveStrictChildPath: () => '/test/temp' })) jest.mock('@/lib/detail-generator/repository', () => ({ detailTransactionLock: jest.fn() })) jest.mock('@/lib/external-auto-listing', () => ({ ensureExternalNotificationTables: jest.fn(), queueXiaoyiAutoListingNotification: jest.fn(), wakeXiaoyiAutoListingNotifications: jest.fn(), })) const digest = createHash('sha256').update('x').digest('hex') const file = (uploadId: string, fileName: string) => ({ uploadId, fileName, fileSize: 1, sha256: digest }) const account = { id: 'owner', name: '登录账号' } const authorize = async () => account const input = { projectId: 'project-1', requestId: 'request-1', kind: 'detail' as const, productModel: 'SPU-1', assets: { main: [file('upload-main', 'main.jpg')], detail: [file('upload-detail', 'detail.jpg')], sku: [{ ...file('upload-sku', 'DNZ030516N717V01.jpg'), barcode: 'DNZ030516N717V01' }], }, } beforeEach(() => { jest.resetAllMocks() // resetAllMocks also clears the stream mock used by the upload digest. jest.mocked(require('node:fs').createReadStream).mockReturnValue([Buffer.from('x')]) jest.mocked(mkdir).mockRejectedValue(new Error('upload-stage')) ;(prisma.$queryRawUnsafe as jest.Mock).mockImplementation(async (sql: string) => sql.startsWith('SELECT id FROM desktop_workspace_projects') ? [{ id: 'project-1' }] : []) jest.mocked(prisma.$queryRaw).mockResolvedValue([]) jest.mocked(findDetailMaterialMatches).mockResolvedValue([]) }) test('未登记的条码可按用户填写入库', async () => { ;(findDetailMaterialMatches as jest.Mock).mockResolvedValue([]) await expect(createDesktopDelivery('owner', input, authorize)).rejects.toThrow('upload-stage') expect(findDetailMaterialMatches).toHaveBeenCalledWith('owner', 'barcode', 'DNZ030516N717V01', true) }) test('条码已属于另一个 SPU 时终止入库', async () => { ;(findDetailMaterialMatches as jest.Mock).mockResolvedValueOnce([]) .mockResolvedValueOnce([{ productModel: 'SPU-2', skuCode: 'SKU', barcodes: ['DNZ030516N717V01'] }]) await expect(createDesktopDelivery('owner', input, authorize)).rejects.toThrow('条码 DNZ030516N717V01 已登记在其他 SPU') }) test('该 SPU 的登记条码可继续入库', async () => { ;(findDetailMaterialMatches as jest.Mock).mockResolvedValueOnce([ { productModel: 'SPU-1', skuCode: 'SKU', barcodes: ['DNZ030516N717V01'] }, ]) await expect(createDesktopDelivery('owner', input, authorize)).rejects.toThrow('upload-stage') expect(findDetailMaterialMatches).toHaveBeenCalledTimes(1) }) test('多条码保持原始格式和大小写,主条码单独核查', async () => { const request = { ...input, identifier: ' SPU-2 ', deliverySpu: 'OLD', detailBarcode: ' SJ021613N16V01 ', assets: { ...input.assets, sku: [ { ...file('sku-red', '红色.webp'), barcodes: [' CY001307N35V01 ', 'cy001301N35', ' SG008839N1049V01 ', 'SG008839N1049V01'] }, { ...file('sku-blue', '蓝色.png'), barcodes: ['sg008839n1049v01'] }, ] }, } await expect(createDesktopDelivery(account.id, request, authorize)).rejects.toThrow('upload-stage') expect(findDetailMaterialMatches).toHaveBeenNthCalledWith(1, account.id, 'spu', 'SPU-2', true) expect(jest.mocked(findDetailMaterialMatches).mock.calls.slice(1).map(call => call[2])) .toEqual(['CY001307N35V01', 'cy001301N35', 'SG008839N1049V01', 'sg008839n1049v01', 'SJ021613N16V01']) request.assets.sku[1].barcodes.push(' SG008839N1049V01 ') await expect(createDesktopDelivery(account.id, request, authorize)).rejects.toThrow('产品条码 SG008839N1049V01 不能同时绑定两张 SKU 图') }) test.each([ { detailBarcode: ' ' }, { assets: { ...input.assets, sku: [{ ...file('upload-sku', 'sku-001.jpg'), barcodes: [' '] }] } }, ])('拒绝纯空白的详情主条码和 SKU 条码', async fields => { await expect(createDesktopDelivery(account.id, { ...input, ...fields }, authorize)) .rejects.toThrow('产品条码须为非空字符串') expect(mkdir).not.toHaveBeenCalled() }) test('旧客户端没有 JSON 条码时沿用 JPG 文件名中的条码', async () => { const legacy = file('upload-sku', '001 Foo;甲.jpg') const request = { ...input, assets: { ...input.assets, sku: [legacy] } } await expect(createDesktopDelivery(account.id, request, authorize)).rejects.toThrow('upload-stage') expect(findDetailMaterialMatches).toHaveBeenCalledWith('owner', 'barcode', '001 Foo;甲', true) }) test('同一花色的多张 SKU 图可共享原值数组', async () => { const [first, second] = fixture.sku const request = { ...input, identifier: fixture.identifier, assets: { ...input.assets, sku: [ { ...file('sku-1', first.fileName), ...first }, { ...file('sku-2', second.fileName), ...second }, { ...file('sku-3', 'sku-003.jpg'), variantId: first.variantId, barcodes: first.barcodes }, ] } } await expect(createDesktopDelivery(account.id, request, authorize)).rejects.toThrow('upload-stage') request.assets.sku[2].variantId = second.variantId await expect(createDesktopDelivery(account.id, request, authorize)).rejects.toThrow('不能同时绑定') }) test('兼容此前以 productModel 和单条码签名的交付重试', async () => { const fingerprint = createHash('sha256').update(JSON.stringify({ projectId: input.projectId, requestId: input.requestId, kind: input.kind, productModel: input.productModel, categoryName: '', productCategoryName: '', brandName: '', productName: '', identifierType: '', files: ['main', 'sku', 'detail'].map(group => { const { uploadId, ...asset } = input.assets[group as keyof typeof input.assets][0] return { group, ...asset } }), })).digest('hex') jest.mocked(prisma.$queryRawUnsafe).mockResolvedValueOnce([{ id: 'project-1' }]).mockResolvedValueOnce([ { requestId: input.requestId, fingerprint, materialId: 'old-material', materialType: '自动上架-详情', state: 'completed' }, ]) await expect(createDesktopDelivery(account.id, input, authorize)).resolves.toMatchObject({ materialId: 'old-material' }) expect(mkdir).not.toHaveBeenCalled() }) test('旧 deliverySpu 只在缺少 identifier 时读取', async () => { const { productModel, ...request } = input await expect(createDesktopDelivery(account.id, { ...request, deliverySpu: ' OLD-SPU ' }, authorize)).rejects.toThrow('upload-stage') expect(findDetailMaterialMatches).toHaveBeenNthCalledWith(1, account.id, 'spu', 'OLD-SPU', true) }) test('三种成品共用项目和 SPU,作者取自再次校验的会话,详情主条码独立落库', async () => { jest.mocked(mkdir).mockResolvedValue(undefined) jest.mocked(lstat).mockResolvedValue({ size: 1, isFile: () => true, isSymbolicLink: () => false } as any) jest.mocked(rename).mockResolvedValue(undefined) jest.mocked(inspectUploadOutput).mockResolvedValue({ existing: { filePath: '/test/file' } } as any) jest.mocked(prisma.$transaction).mockImplementation(async action => action(prisma)) jest.mocked(prisma.$queryRaw).mockResolvedValueOnce([]).mockResolvedValueOnce([]).mockResolvedValue([{ identifier: 'SPU-9' }]) jest.mocked(prisma.material.create).mockResolvedValueOnce({ id: 'detail' } as any) .mockResolvedValueOnce({ id: 'video' } as any).mockResolvedValueOnce({ id: 'buyer-show' } as any) const session = jest.fn(authorize).mockResolvedValueOnce(account).mockResolvedValueOnce({ ...account, name: '已更名账号' }) const shipments = [ { ...input, identifier: fixture.identifier, detailBarcode: fixture.detailBarcode, authorName: '伪造作者', userId: 'other-user', assets: { ...input.assets, sku: fixture.sku.map(sku => ({ ...file('upload-' + sku.variantId, sku.fileName), ...sku })) }, }, { ...input, requestId: 'video-request', kind: 'video' as const, identifier: 'spu-9', assets: { files: [file('video', '成品.mp4')] } }, { ...input, requestId: 'show-request', kind: 'buyer_show' as const, identifier: 'SPU-9', assets: { files: [file('show', '买家秀.jpg')] } }, ] for (const shipment of shipments) { const files = Object.values(shipment.assets).flat() jest.mocked(getOwnedUploadSession).mockImplementation(async uploadId => ({ ...files.find(item => item.uploadId === uploadId), uploadPurpose: 'xiaoyi:project-1:' + shipment.requestId, } as any)) await expect(createDesktopDelivery(account.id, shipment, session)).resolves.toMatchObject({ state: 'completed' }) } expect(session).toHaveBeenCalledTimes(6) expect(jest.mocked(prisma.material.create).mock.calls.map(([{ data }]) => [data.userId, data.authorName, data.productModel, data.isFullSet])) .toEqual([['owner', '已更名账号', 'SPU-9', true], ['owner', '登录账号', 'SPU-9', false], ['owner', '登录账号', 'SPU-9', false]]) expect(jest.mocked(prisma.material.create).mock.calls[0][0].data.assets?.create).toEqual([ expect.objectContaining({ assetType: 'main' }), ...fixture.sku.map(({ fileName, barcodes }) => expect.objectContaining({ assetType: 'sku', fileName, barcodes: { create: barcodes.map(barcode => ({ barcode })) }, })), expect.objectContaining({ assetType: 'detail', barcodes: { create: [{ barcode: fixture.detailBarcode }] } }), ]) expect(jest.mocked(queueXiaoyiAutoListingNotification).mock.calls.map(([, options]) => [options.projectId, options.outcomeKind, options.materialId])) .toEqual([['project-1', 'detail', 'detail'], ['project-1', 'video', 'video'], ['project-1', 'buyer_show', 'buyer-show']]) await expect(createDesktopDelivery(account.id, { ...shipments[2], identifier: 'OTHER-SPU' }, session)) .rejects.toMatchObject({ status: 409, code: 'delivery_identifier_conflict' }) expect(prisma.material.create).toHaveBeenCalledTimes(3) expect(mkdir).toHaveBeenCalledTimes(3) })