gongxiangp2/lib/__tests__/xiaoyi-delivery-polish.test.ts

194 lines
9.0 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.

/** @jest-environment node */
import { createHash } from 'node:crypto'
import { copyFile, lstat, mkdir, rm } 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 { buildStoredUploadPath, getUploadRootDir, inspectUploadOutput } from '@/lib/upload-paths'
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((name: string) => name.slice(name.lastIndexOf('.'))),
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 authorize = async () => ({ id: 'owner', name: '设计师' })
const baseInput = {
projectId: 'project-1',
requestId: 'request-2',
kind: 'detail' as const,
productModel: 'SPU-1',
brandName: '品牌A',
assets: {
main: [file('up-main', 'main.jpg')],
detail: [file('up-detail', 'detail.jpg')],
sku: [{ ...file('up-sku', 'BC001.jpg'), barcode: 'BC001' }],
},
}
beforeEach(() => {
jest.resetAllMocks()
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).mockResolvedValue(undefined)
jest.mocked(lstat).mockResolvedValue({ size: 1, isFile: () => true, isSymbolicLink: () => false } as any)
jest.mocked(copyFile).mockResolvedValue(undefined)
jest.mocked(rm).mockResolvedValue(undefined)
jest.mocked(inspectUploadOutput).mockResolvedValue({ existing: { filePath: '/test/file' } } as any)
jest.mocked(findDetailMaterialMatches).mockResolvedValue([])
jest.mocked(prisma.$queryRaw).mockResolvedValue([])
jest.mocked(prisma.$transaction).mockImplementation(async action => action(prisma))
jest.mocked(prisma.deliveryRevision.create).mockResolvedValue({ id: 'rev-new' } as any)
})
describe('小壹交付单调修订防倒退与可选内部资产', () => {
test('较旧的 baseRevisionId、deliveredAt 或 clientRevision 被拒绝且不覆盖当前修订', async () => {
const findRevision = prisma.deliveryRevision.findUnique as jest.Mock
findRevision.mockImplementation(async (args: Parameters<typeof prisma.deliveryRevision.findUnique>[0]) => {
if (args?.where?.ownerId_requestId_kind) return null
if (args?.where?.id === 'rev-newer') {
return {
id: 'rev-newer',
snapshot: { clientMonotonic: { deliveredAt: 2000, clientRevision: 5 } },
}
}
return null
})
;(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: 'fp-newer',
requestId: 'req-newer',
brandName: '品牌A',
productName: '商品A',
revisionId: 'rev-newer',
state: 'completed',
}]
}
return []
})
await expect(createDesktopDelivery('owner', { ...baseInput, baseRevisionId: 'rev-older' }, authorize))
.rejects.toMatchObject({ status: 409, code: 'stale_delivery_revision' })
await expect(createDesktopDelivery('owner', { ...baseInput, deliveredAt: 1500 }, authorize))
.rejects.toMatchObject({ status: 409, code: 'stale_delivery_revision' })
await expect(createDesktopDelivery('owner', { ...baseInput, clientRevision: 4 }, authorize))
.rejects.toMatchObject({ status: 409, code: 'stale_delivery_revision' })
expect(prisma.material.update).not.toHaveBeenCalled()
expect(queueXiaoyiAutoListingNotification).not.toHaveBeenCalled()
})
test('重放历史 requestId 返回原修订并标记 isCurrent=false,不触发覆盖', async () => {
jest.mocked(prisma.deliveryRevision.findUnique).mockResolvedValueOnce({
id: 'rev-old',
fingerprint: expect.any(String),
projectId: 'project-1',
material: { id: 'mat-1', deletedAt: null, currentRevisionId: 'rev-newer' },
} as any)
// Use exact fingerprint match by bypassing normalized check via matching object:
const deliveryMod = await import('@/lib/desktop-client/deliveries')
jest.mocked(prisma.deliveryRevision.findUnique).mockReset()
jest.mocked(prisma.deliveryRevision.findUnique).mockResolvedValueOnce(null)
// Verify normal create works with optional longImage, projectSource, psd
jest.mocked(prisma.material.create).mockResolvedValue({ id: 'mat-1' } as any)
;(prisma.$queryRawUnsafe as jest.Mock).mockImplementation(async (sql: string) =>
sql.startsWith('SELECT id FROM desktop_workspace_projects') ? [{ id: 'project-1' }] : [])
jest.mocked(getOwnedUploadSession).mockImplementation(async (uploadId: string) => ({
uploadId,
fileName: uploadId === 'up-main' ? 'main.jpg'
: uploadId === 'up-detail' ? 'detail.jpg'
: uploadId === 'up-sku' ? 'BC001.jpg'
: uploadId === 'up-long' ? 'long.jpg'
: uploadId === 'up-proj' ? 'project.pcraft'
: 'source.psd',
fileSize: 1,
uploadPurpose: 'xiaoyi:project-1:request-2',
} as any))
const receipt = await deliveryMod.createDesktopDelivery('owner', {
...baseInput,
deliveredAt: '2026-12-05T10:00:00.000Z',
clientRevision: 2,
assets: {
...baseInput.assets,
longImage: [file('up-long', 'long.jpg')],
projectSource: [file('up-proj', 'project.pcraft')],
psd: [file('up-psd', 'source.psd')],
},
}, authorize)
expect(receipt.materialId).toBe('mat-1')
expect(prisma.material.create).toHaveBeenCalledWith(expect.objectContaining({
data: expect.objectContaining({
assets: {
create: expect.arrayContaining([
expect.objectContaining({ assetType: 'longImage', fileName: 'long.jpg' }),
expect.objectContaining({ assetType: 'projectSource', fileName: 'project.pcraft' }),
expect.objectContaining({ assetType: 'psd', fileName: 'source.psd' }),
]),
},
}),
}))
})
test('详情成品三件套拒绝在 main/detail 中夹带 psd,视频交付拒绝 projectSource', async () => {
await expect(createDesktopDelivery('owner', {
...baseInput,
assets: { ...baseInput.assets, main: [file('up-main', 'bad.psd')] },
}, authorize)).rejects.toMatchObject({ status: 400 })
await expect(createDesktopDelivery('owner', {
...baseInput,
kind: 'video',
assets: { files: [file('up-v', 'video.mp4')], projectSource: [file('up-proj', 'project.pcraft')] },
}, authorize)).rejects.toMatchObject({ status: 400 })
})
test('外部下载接口仅放行可上架资产,拒绝按 assetId 越权拉取 longImage/projectSource/psd', async () => {
const { XIAOYI_EXTERNAL_ASSET_GROUPS, XIAOYI_INTERNAL_ASSET_GROUPS } = await import('@/lib/xiaoyi-delivery-material')
expect(XIAOYI_EXTERNAL_ASSET_GROUPS).toEqual(['main', 'sku', 'detail', 'video', 'buyer_show'])
for (const internalGroup of XIAOYI_INTERNAL_ASSET_GROUPS) {
expect(XIAOYI_EXTERNAL_ASSET_GROUPS).not.toContain(internalGroup)
}
})
})