/** @jest-environment node */ import { createHash } from 'node:crypto' import { copyFile, mkdir, lstat, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import path from 'node:path' 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 { buildStoredUploadPath, getUploadRootDir, 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(), update: jest.fn(), findUniqueOrThrow: jest.fn() }, materialAsset: { deleteMany: jest.fn() }, materialLog: { create: jest.fn(), findFirst: jest.fn() }, deliveryRevision: { create: jest.fn(), findUnique: jest.fn() }, xiaoyiAutoListingEvent: { findUnique: 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(), rm: jest.fn() })) jest.mock('@/lib/material-facets-cache', () => ({ invalidateMaterialFacetsCache: jest.fn() })) jest.mock('@/lib/remote-upload-sync', () => ({ syncStoredUploadFileToRemote: jest.fn(), isRemoteUploadSyncEnabled: jest.fn(() => false) })) jest.mock('@/lib/upload-sessions', () => ({ getOwnedUploadSession: jest.fn() })) jest.mock('@/lib/upload-paths', () => ({ getUploadRootDir: jest.fn(), 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', brandName: '示例品牌', 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(getUploadRootDir).mockReturnValue('/test') jest.mocked(buildStoredUploadPath).mockImplementation((...segments) => ['uploads', ...segments].join('/')) jest.mocked(mkdir).mockRejectedValue(new Error('upload-stage')) jest.mocked(rm).mockResolvedValue(undefined) ;(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(prisma.deliveryRevision.findUnique).mockResolvedValue(null) jest.mocked(prisma.deliveryRevision.create).mockResolvedValue({ id: 'revision-new' } as any) jest.mocked(findDetailMaterialMatches).mockResolvedValue([]) }) function mockSuccessfulUpload(files: Array<{ uploadId: string; fileName: string; fileSize: number }>) { jest.mocked(mkdir).mockResolvedValue(undefined) jest.mocked(lstat).mockResolvedValue({ size: 1, isFile: () => true, isSymbolicLink: () => false } as any) jest.mocked(inspectUploadOutput).mockResolvedValue({ existing: { filePath: '/test/file' } } as any) jest.mocked(prisma.$transaction).mockImplementation(async action => action(prisma)) jest.mocked(prisma.material.create).mockResolvedValue({ id: 'material' } as any) jest.mocked(getOwnedUploadSession).mockImplementation(async uploadId => ({ ...files.find(item => item.uploadId === uploadId), uploadPurpose: 'xiaoyi:project-1:request-1', } as any)) } 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('同条码的两种尺寸入库时保留纯条码文件名并分别存放', async () => { const code = '001-A' const request = { ...input, assets: { ...input.assets, sku: [800, 1440].map(size => ({ ...file('sku-' + size, code + '.jpg'), width: size, height: size, skuCode: 'SKU-1', barcodes: [code], variantId: 'white', })) } } mockSuccessfulUpload(Object.values(request.assets).flat()) await expect(createDesktopDelivery(account.id, request, authorize)).resolves.toMatchObject({ state: 'completed' }) const destinations = jest.mocked(copyFile).mock.calls.map(([, target]) => String(target).replaceAll('\\', '/')) expect(destinations).toEqual(expect.arrayContaining([ expect.stringMatching(/\/sku\/800x800\/[a-f0-9]{64}\/001-A\.jpg$/), expect.stringMatching(/\/sku\/1440x1440\/[a-f0-9]{64}\/001-A\.jpg$/), ])) expect(jest.mocked(prisma.material.create).mock.calls[0][0].data.assets?.create).toEqual(expect.arrayContaining( [800, 1440].map(() => expect.objectContaining({ assetType: 'sku', fileName: '001-A.jpg', skuCode: 'SKU-1', barcodes: { create: [{ barcode: code }] } })), )) request.assets.sku[1].width = request.assets.sku[1].height = 800 await expect(createDesktopDelivery(account.id, request, authorize)).rejects.toThrow('同一分组中有重复文件') request.assets.sku[1].sha256 = createHash('sha256').update('y').digest('hex') const streamMock = jest.mocked(require('node:fs').createReadStream) streamMock .mockReturnValueOnce([Buffer.from('x')]) .mockReturnValueOnce([Buffer.from('x')]) .mockReturnValueOnce([Buffer.from('y')]) .mockReturnValueOnce([Buffer.from('x')]) await expect(createDesktopDelivery(account.id, request, authorize)).resolves.toMatchObject({ state: 'completed' }) request.assets.sku[1].sha256 = digest request.assets.sku[1].fileName = 'SKU-001-A.jpg' await expect(createDesktopDelivery(account.id, request, authorize)).rejects.toThrow('SKU 图的条码文件名或尺寸无效') }) test('同花色的不同规格可分别入库,元数据跟随资产 ID,同条码跨规格仍拒绝', async () => { const sku = (barcode: string, specId: string, width: number) => ({ ...file(`upload-${barcode}-${width}`, `${barcode}.jpg`), width, height: width, variantId: 'white', variantName: ' 白色 ', specId, barcodes: [barcode], }) const request = { ...input, categoryName: ' 原店铺 ', storeCategoryName: ' 平台分类 ', assets: { ...input.assets, sku: [sku('001-A', 'base', 800), sku('001-B', 'deep', 1440)] }, } mockSuccessfulUpload(Object.values(request.assets).flat()) await expect(createDesktopDelivery(account.id, request, authorize)).resolves.toMatchObject({ state: 'completed' }) const { data } = jest.mocked(prisma.material.create).mock.calls[0][0] const assets = data.assets?.create as Array<{ id: string; assetType: string }> const [base, deep] = assets.filter(asset => asset.assetType === 'sku') expect(data.categoryName).toBe('原店铺') expect(base).toMatchObject({ fileName: '001-A.jpg', barcodes: { create: [{ barcode: '001-A' }] } }) expect(deep).toMatchObject({ fileName: '001-B.jpg', barcodes: { create: [{ barcode: '001-B' }] } }) const [entry] = jest.mocked(prisma.materialLog.create).mock.calls[0] expect(entry.data).toMatchObject({ materialId: 'material', userId: 'owner', action: 'XIAOYI_DELIVERY' }) expect(JSON.parse(entry.data.changes!)).toMatchObject({ deliveryMetadata: { newValue: { storeCategoryName: '平台分类', assetSpecs: { [base.id]: { specId: 'base', variantId: 'white', variantName: '白色' }, [deep.id]: { specId: 'deep', variantId: 'white', variantName: '白色' }, }, } } }) expect(jest.mocked(prisma.materialLog.create).mock.invocationCallOrder[0]) .toBeLessThan(jest.mocked(queueXiaoyiAutoListingNotification).mock.invocationCallOrder[0]) request.assets.sku[1] = sku('001-A', 'deep', 1440) await expect(createDesktopDelivery(account.id, request, authorize)).rejects.toThrow('产品条码 001-A 不能同时绑定两张 SKU 图') expect(prisma.material.create).toHaveBeenCalledTimes(1) }) test.each([ [{}, ''], [{ categoryName: '旗舰店' }, '旗舰店'], [{ storeCategoryName: '旗舰店' }, '旗舰店'], ] as const)('旧格式上传和店铺分类别名均可入库(%j)', async (category, expectedCategory) => { mockSuccessfulUpload(Object.values(input.assets).flat()) await expect(createDesktopDelivery(account.id, { ...input, ...category }, authorize)).resolves.toMatchObject({ state: 'completed' }) expect(prisma.material.create).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ categoryName: expectedCategory }) })) expect(prisma.materialLog.create).not.toHaveBeenCalled() }) 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.each([undefined, '', ' '])('新交付缺少商品品牌时在上传前拒绝', async brandName => { await expect(createDesktopDelivery(account.id, { ...input, brandName }, authorize)) .rejects.toMatchObject({ status: 400, code: 'brand_required', message: '请填写商品品牌后再完结提交' }) expect(mkdir).not.toHaveBeenCalled() expect(findDetailMaterialMatches).not.toHaveBeenCalled() }) 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, brandName: '' }, 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(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', brandName: '', assets: { files: [file('video', '成品.mp4')] } }, { ...input, requestId: 'show-request', kind: 'buyer_show' as const, identifier: 'SPU-9', brandName: '', 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(6) }) test('完结后微调图片再次点击完结支持原位修订更新,且原素材已移除时允许重建', async () => { const { rm } = require('node:fs/promises') const detailFiles = [ ...input.assets.main, ...input.assets.detail, ...input.assets.sku, ] mockSuccessfulUpload(detailFiles) jest.mocked(getOwnedUploadSession).mockImplementation(async uploadId => ({ ...detailFiles.find(item => item.uploadId === uploadId), uploadPurpose: 'xiaoyi:project-1:request-rev-2', } as any)) jest.mocked(rm).mockResolvedValue(undefined) jest.mocked(prisma.$queryRawUnsafe as jest.Mock).mockImplementation(async (sql: string) => { if (sql.startsWith('SELECT id FROM desktop_workspace_projects')) return [{ id: 'project-1' }] if (sql.includes('FROM desktop_material_deliveries d LEFT JOIN materials m')) { return [{ materialId: 'mat-existing', materialType: '自动上架-详情', fingerprint: 'old-fp', requestId: 'request-rev-1', state: 'completed', }] } return [] }) jest.mocked(prisma.$transaction as jest.Mock).mockImplementation(async callback => callback({ $queryRawUnsafe: prisma.$queryRawUnsafe, $queryRaw: prisma.$queryRaw, $executeRawUnsafe: prisma.$executeRawUnsafe, material: prisma.material, materialAsset: prisma.materialAsset, materialLog: prisma.materialLog, deliveryRevision: prisma.deliveryRevision, xiaoyiAutoListingEvent: prisma.xiaoyiAutoListingEvent, })) jest.mocked(prisma.material.findUniqueOrThrow).mockResolvedValue({ currentRevisionId: null, authorName: '原作者', productModel: 'SPU-1', categoryName: '', productCategoryName: '', assets: [{ id: 'old-main', assetType: 'main', fileName: 'old.jpg', fileUrl: 'uploads/old.jpg', fileSize: BigInt(1), sortOrder: 0, barcodes: [] }], } as any) jest.mocked(prisma.deliveryRevision.create).mockResolvedValueOnce({ id: 'revision-baseline' } as any) jest.mocked(prisma.materialAsset.deleteMany).mockResolvedValue({ count: 3 } as any) jest.mocked(prisma.material.update).mockResolvedValue({ id: 'mat-existing' } as any) jest.mocked(prisma.materialLog.create).mockResolvedValue({} as any) ;(prisma.$queryRaw as jest.Mock).mockImplementation(async (sql, ...params) => { const query = (sql as TemplateStringsArray).join('?') if (!query.includes('FOR UPDATE')) return [] expect(query).toContain('"userId" = ? AND "deletedAt" IS NULL') expect(params).toEqual(['mat-existing', account.id]) return [{ id: 'mat-existing' }] }) const revised = await createDesktopDelivery(account.id, { ...input, requestId: 'request-rev-2' }, authorize) expect(revised).toEqual({ requestId: 'request-rev-2', materialId: 'mat-existing', materialType: '自动上架-详情', state: 'completed', revisionId: 'revision-new', }) expect(prisma.materialAsset.deleteMany).toHaveBeenCalledWith({ where: { materialId: 'mat-existing' } }) expect(prisma.material.update).toHaveBeenCalledWith(expect.objectContaining({ where: { id: 'mat-existing' } })) expect(prisma.material.create).not.toHaveBeenCalled() expect(queueXiaoyiAutoListingNotification).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ materialId: 'mat-existing', revisionId: 'revision-new', })) const [revisionSql] = jest.mocked(prisma.$executeRawUnsafe).mock.calls[0] expect(revisionSql).not.toContain('listing_status') expect(prisma.deliveryRevision.create).toHaveBeenNthCalledWith(1, expect.objectContaining({ data: expect.objectContaining({ requestId: 'request-rev-1', assets: { createMany: { data: [expect.objectContaining({ id: 'old-main', fileUrl: 'uploads/old.jpg' })] } }, }), })) expect(prisma.deliveryRevision.create).toHaveBeenNthCalledWith(2, expect.objectContaining({ data: expect.objectContaining({ requestId: 'request-rev-2', parentId: 'revision-baseline' }), })) expect(jest.mocked(prisma.deliveryRevision.create).mock.invocationCallOrder[0]) .toBeLessThan(jest.mocked(prisma.materialAsset.deleteMany).mock.invocationCallOrder[0]) // 交接发生在文件预写之后,也必须在事务里确认当前归属。 jest.mocked(prisma.$queryRaw).mockResolvedValue([]) jest.mocked(prisma.materialAsset.deleteMany).mockClear() jest.mocked(prisma.material.update).mockClear() jest.mocked(queueXiaoyiAutoListingNotification).mockClear() await expect(createDesktopDelivery(account.id, { ...input, requestId: 'request-rev-2' }, authorize)) .rejects.toMatchObject({ status: 409, code: 'delivery_ownership_conflict' }) expect(prisma.materialAsset.deleteMany).not.toHaveBeenCalled() expect(prisma.material.update).not.toHaveBeenCalled() expect(queueXiaoyiAutoListingNotification).not.toHaveBeenCalled() // 原素材已软删时允许重建新 Material 并更新 delivery 指向 jest.mocked(getOwnedUploadSession).mockImplementation(async uploadId => ({ ...detailFiles.find(item => item.uploadId === uploadId), uploadPurpose: 'xiaoyi:project-1:request-rev-3', } as any)) jest.mocked(prisma.$queryRawUnsafe as jest.Mock).mockImplementation(async (sql: string) => { if (sql.startsWith('SELECT id FROM desktop_workspace_projects')) return [{ id: 'project-1' }] if (sql.includes('FROM desktop_material_deliveries d LEFT JOIN materials m')) { return [{ materialId: 'mat-removed', materialType: '自动上架-详情', fingerprint: 'old-fp', requestId: 'request-rev-2', state: 'removed', }] } return [] }) jest.mocked(prisma.material.create).mockResolvedValue({ id: 'mat-recreated' } as any) const recreated = await createDesktopDelivery(account.id, { ...input, requestId: 'request-rev-3' }, authorize) expect(recreated).toEqual({ requestId: 'request-rev-3', materialId: 'mat-recreated', materialType: '自动上架-详情', state: 'completed', revisionId: 'revision-new', }) expect(prisma.material.create).toHaveBeenCalledTimes(1) }) test('同 requestId 但 fingerprint 不一致仍返回 409,且在跑任务预检与事务异常均不留孤儿文件', async () => { const { rm } = require('node:fs/promises') jest.mocked(prisma.$queryRawUnsafe as jest.Mock).mockImplementation(async (sql: string) => { if (sql.startsWith('SELECT id FROM desktop_workspace_projects')) return [{ id: 'project-1' }] if (sql.includes('FROM desktop_material_deliveries d LEFT JOIN materials m')) { return [{ materialId: 'mat-1', materialType: '自动上架-详情', fingerprint: 'different-fp', requestId: 'request-1', state: 'completed', }] } return [] }) await expect(createDesktopDelivery(account.id, input, authorize)) .rejects.toMatchObject({ status: 409, code: 'delivery_conflict' }) expect(mkdir).not.toHaveBeenCalled() // 在跑任务预检在拷贝文件之前拦截 jest.mocked(prisma.$queryRawUnsafe as jest.Mock).mockImplementation(async (sql: string) => { if (sql.startsWith('SELECT id FROM desktop_workspace_projects')) return [{ id: 'project-1' }] if (sql.includes('FROM desktop_creation_tasks')) return [{ id: 'running-task-1' }] return [] }) await expect(createDesktopDelivery(account.id, input, authorize)) .rejects.toMatchObject({ status: 409, code: 'task_busy' }) expect(mkdir).not.toHaveBeenCalled() // 事务失败时清理已写入的本地目录 const detailFiles = [...input.assets.main, ...input.assets.detail, ...input.assets.sku] mockSuccessfulUpload(detailFiles) jest.mocked(getOwnedUploadSession).mockImplementation(async uploadId => ({ ...detailFiles.find(item => item.uploadId === uploadId), uploadPurpose: 'xiaoyi:project-1:request-1', } as any)) jest.mocked(rm).mockResolvedValue(undefined) jest.mocked(prisma.$queryRawUnsafe as jest.Mock).mockImplementation(async (sql: string) => sql.startsWith('SELECT id FROM desktop_workspace_projects') ? [{ id: 'project-1' }] : []) jest.mocked(prisma.$transaction as jest.Mock).mockRejectedValue(new Error('tx_boom')) await expect(createDesktopDelivery(account.id, input, authorize)).rejects.toThrow('tx_boom') expect(rm).toHaveBeenCalledWith(expect.stringContaining('request-1'), { recursive: true, force: true }) }) test.each([false, true])('同请求并发提交保留胜出文件,指纹相同=%s', async (sameFingerprint) => { const fs = jest.requireActual('node:fs/promises') const root = await fs.mkdtemp(path.join(tmpdir(), 'xiaoyi-delivery-race-')) try { const source = path.join(root, 'assembled.jpg') await fs.writeFile(source, 'x') mockSuccessfulUpload(Object.values(input.assets).flat()) jest.mocked(getUploadRootDir).mockReturnValue(root) jest.mocked(inspectUploadOutput).mockResolvedValue({ existing: { filePath: source } } as any) jest.mocked(mkdir).mockImplementation(fs.mkdir) jest.mocked(copyFile).mockImplementation(fs.copyFile) jest.mocked(rm).mockImplementation(fs.rm) let receipt: { fingerprint: string; materialId: string; materialType: string; requestId: string; state: string } | undefined const transaction = { ...prisma, $queryRawUnsafe: jest.fn(async (sql: string) => { if (sql.startsWith('SELECT id FROM desktop_workspace_projects')) return [{ id: input.projectId }] if (sql.includes('FROM desktop_material_deliveries') && receipt) return [receipt] return [] }), $executeRawUnsafe: jest.fn(async (_sql, _id, _owner, _project, requestId, _kind, fingerprint, materialId, materialType) => { receipt = { requestId, materialId, materialType, fingerprint, state: 'completed' } }), } let releaseTransactions!: () => void const bothStaged = new Promise((resolve) => { releaseTransactions = resolve }) let attempts = 0 let queue: Promise = Promise.resolve() jest.mocked(prisma.$transaction).mockImplementation(async (action) => { if (++attempts === 2) releaseTransactions() const submitted = queue.then(async () => { await bothStaged return action(transaction as any) }) queue = submitted.catch(() => undefined) return submitted }) const second = sameFingerprint ? input : { ...input, brandName: '并发修订' } const outcomes = await Promise.allSettled([ createDesktopDelivery(account.id, input, authorize), createDesktopDelivery(account.id, second, authorize), ]) expect(outcomes.filter(({ status }) => status === 'fulfilled')).toHaveLength(sameFingerprint ? 2 : 1) if (!sameFingerprint) expect(outcomes).toContainEqual({ status: 'rejected', reason: expect.objectContaining({ status: 409, code: 'delivery_conflict' }), }) const assets = jest.mocked(prisma.material.create).mock.calls[0][0].data.assets?.create as Array<{ fileUrl: string }> expect(assets).toHaveLength(3) for (const asset of assets) { const fullPath = path.join(root, asset.fileUrl.slice('uploads/'.length)) expect(await fs.readFile(fullPath, 'utf-8')).toBe('x') } expect(rm).toHaveBeenCalledTimes(1) expect(prisma.material.create).toHaveBeenCalledTimes(1) expect(queueXiaoyiAutoListingNotification).toHaveBeenCalledTimes(1) } finally { await fs.rm(root, { recursive: true, force: true }) } })