gongxiangp2/lib/__tests__/product-assets-route.test.ts

433 lines
17 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 { DELETE, GET } from '@/app/api/external/product-assets/route'
import { getMaterialById, getMaterialByTaskNo, softDeleteExternalMaterial, TASK_STATUS, updateTaskStatus } from '@/lib/product-package'
import { logApiCall, validateApiKey } from '@/lib/external-api'
import { prisma } from '@/lib/prisma'
import fixture from './fixtures/xiaoyi-free-barcode.json'
jest.mock('@/lib/external-api', () => {
const { NextResponse } = require('next/server')
return {
getApiKeyFromRequest: jest.fn((request: { headers: Headers }) => request.headers.get('X-API-Key')),
getClientIp: jest.fn(() => '127.0.0.1'),
logApiCall: jest.fn().mockResolvedValue(undefined),
successResponse: jest.fn((data: unknown, message?: string) =>
NextResponse.json({
success: true,
...(message ? { message } : {}),
data,
}),
),
errorResponse: jest.fn((error: { code: string; message: string; status: number }) =>
NextResponse.json(
{
success: false,
error: {
code: error.code,
message: error.message,
},
},
{ status: error.status },
),
),
validateApiKey: jest.fn(),
XIAOYI_LISTING_KEY_SCOPE: 'xiaoyi_auto_listing',
API_ERROR: {
INVALID_API_KEY: { code: 'INVALID_API_KEY', message: 'API Key 无效或缺失', status: 401 },
TASK_NOT_FOUND: { code: 'TASK_NOT_FOUND', message: '任务号不存在', status: 404 },
MATERIAL_NOT_FOUND: { code: 'MATERIAL_NOT_FOUND', message: '素材不存在', status: 404 },
MATERIAL_DELETED: { code: 'MATERIAL_DELETED', message: '素材已被删除', status: 410 },
INVALID_TASK_NO: { code: 'INVALID_TASK_NO', message: '任务号格式错误', status: 400 },
INVALID_MATERIAL_ID: { code: 'INVALID_MATERIAL_ID', message: '素材ID格式错误', status: 400 },
INVALID_QUERY: { code: 'INVALID_QUERY', message: '请提供 taskNo 或 materialId', status: 400 },
SERVER_ERROR: { code: 'SERVER_ERROR', message: '服务器内部错误', status: 500 },
},
}
})
jest.mock('@/lib/prisma', () => ({
prisma: { $queryRaw: jest.fn() },
}))
jest.mock('@/lib/product-package', () => ({
validateTaskNo: jest.fn((taskNo?: string | null) => Boolean(taskNo && taskNo.startsWith('TASK'))),
getMaterialByTaskNo: jest.fn(),
getMaterialById: jest.fn(),
updateTaskStatus: jest.fn().mockResolvedValue({ count: 1 }),
softDeleteExternalMaterial: jest.fn().mockResolvedValue({ count: 1 }),
TASK_STATUS: {
PENDING: 'pending',
COMPLETED: 'completed',
FETCHED: 'fetched',
},
ASSET_TYPE: {
MAIN: 'main',
SKU: 'sku',
DETAIL: 'detail',
PSD: 'psd',
},
}))
jest.mock('@/lib/download-token', () => ({
generateDownloadUrl: jest.fn((_baseUrl: string, { materialId }: { materialId: string }) => `https://download.example/${materialId}`),
}))
jest.mock('@/lib/public-app-url', () => ({
getPublicAppOrigin: jest.fn(() => 'https://sc.jiansun.vip'),
}))
jest.mock('@/lib/url-rewrite', () => ({
rewriteStorageUrlForClient: jest.fn((url?: string | null) => (url ? `rewritten:${url}` : null)),
}))
describe('external product-assets route', () => {
beforeEach(() => {
jest.clearAllMocks()
;(validateApiKey as jest.Mock).mockResolvedValue({
id: 'api-key-1',
name: 'auto-listing',
isActive: true,
})
})
function createRequest(url: string) {
return {
nextUrl: new URL(url),
headers: new Headers({
'X-API-Key': 'test-key',
'user-agent': 'jest',
}),
} as any
}
test('私密任务详情不向外部系统暴露资料或更新领取状态', async () => {
;(getMaterialById as jest.Mock).mockResolvedValue({ id: 'private-one', materialType: '任务-详情', taskDetailPrivate: true })
const response = await GET(createRequest('https://example.com/api/external/product-assets?materialId=35d8644b-1e09-4ce8-9bb0-c529b39ba52e'))
expect(response.status).toBe(404)
expect(updateTaskStatus).not.toHaveBeenCalled()
expect((await response.json()).data).toBeUndefined()
})
test('查询后素材转为受限时,不更新领取状态或返回资源', async () => {
const id = '35d8644b-1e09-4ce8-9bb0-c529b39ba52e'
;(getMaterialById as jest.Mock).mockResolvedValue({ id, taskStatus: TASK_STATUS.COMPLETED })
;(updateTaskStatus as jest.Mock).mockResolvedValueOnce({ count: 0 })
const response = await GET(createRequest(`https://example.com/api/external/product-assets?materialId=${id}`))
expect(response.status).toBe(404)
expect((await response.json()).data).toBeUndefined()
})
test('删除只按匹配到的素材 ID 写入,当前范围校验失败时返回 404', async () => {
;(getMaterialByTaskNo as jest.Mock).mockResolvedValue({ id: 'matched-material' })
;(softDeleteExternalMaterial as jest.Mock).mockResolvedValueOnce({ count: 0 })
const response = await DELETE(createRequest('https://example.com/api/external/product-assets?taskNo=TASK202603310001'))
expect(softDeleteExternalMaterial).toHaveBeenCalledWith('matched-material')
expect(response.status).toBe(404)
})
test('从三件套、视频或买家秀取件均返回同项目关系、SPU、详情主条码和 SKU 条码', async () => {
const ids = {
detail: '35d8644b-1e09-4ce8-9bb0-c529b39ba52e',
video: '683a77e8-c567-43df-8af3-bcbae2d0010e',
buyer_show: 'b5d39d6b-8c2d-40c2-a384-fcf5cb08601c',
}
const sku = fixture.sku.map(({ variantId, fileName, barcodes }, sortOrder) => ({
id: variantId, assetType: 'sku', fileName, barcodes: barcodes.map(barcode => ({ barcode })), sortOrder,
}))
const barcodes = fixture.sku.flatMap(file => file.barcodes)
const kinds = { detail: '详情', video: '视频', buyer_show: '买家秀' } as const
const asset = (type: string) => ({ id: type, assetType: type, fileName: type + '.jpg' })
jest.mocked(prisma.$queryRaw).mockResolvedValue([{
productName: '椅子', brandName: '测试品牌', eventId: 'event-1', deliveryGroupId: 'project-1',
authorId: 'account-1', relatedMaterials: ids, detailBarcode: fixture.detailBarcode, barcodes,
}])
jest.mocked(validateApiKey).mockResolvedValue({ id: 'listing-key', scope: 'xiaoyi_auto_listing' } as any)
const relatedMaterials = Object.fromEntries(Object.entries(ids).map(([kind, id]) => [
kind, { materialId: id, downloadUrl: 'https://download.example/' + id },
]))
for (const kind of Object.keys(kinds) as Array<keyof typeof kinds>) {
const id = ids[kind]
jest.mocked(getMaterialById).mockResolvedValue({
id, productModel: fixture.identifier, materialType: '自动上架-' + kinds[kind], authorName: '测试作者',
taskStatus: TASK_STATUS.COMPLETED, deletedAt: null, createdAt: new Date(), updatedAt: new Date(),
assets: kind === 'detail' ? [asset('main'), ...sku, asset('detail')] : [asset(kind)],
} as any)
const response = await GET(createRequest(`https://example.com/api/external/product-assets?materialId=${id}`))
expect(response.status).toBe(200)
const { data } = await response.json()
expect(data).toMatchObject({
identifier: fixture.identifier, spu: fixture.identifier, identifierType: 'spu', productName: '椅子',
authorId: 'account-1', authorName: '测试作者', detailBarcode: fixture.detailBarcode,
barcodes, relatedMaterials, deliveryGroupId: 'project-1',
isFullSet: kind === 'detail',
})
if (kind === 'detail') {
expect(data.assets.main).toHaveLength(1)
expect(data.assets.sku).toMatchObject(fixture.sku.map(({ fileName, barcodes }) => ({ fileName, barcodes, skuCode: null })))
expect(data.assets.detail).toHaveLength(1)
} else {
expect(data.files).toEqual(data.assets[kind])
expect(data.files).toHaveLength(1)
}
}
const sql = (jest.mocked(prisma.$queryRaw).mock.calls[0][0] as TemplateStringsArray).join('$1')
expect(sql).toContain('related.project_id = d.project_id AND related.owner_id = d.owner_id')
expect(sql).toContain('UPPER(rm."productModel") = UPPER(delivered."productModel")')
expect(sql).toContain("WHERE a.material_id = (siblings.\"relatedMaterials\"->>'detail')")
})
test('早期交付缺少详情页主条码时不把首个 SKU 条码当作主条码', async () => {
const id = '35d8644b-1e09-4ce8-9bb0-c529b39ba52e'
jest.mocked(prisma.$queryRaw).mockResolvedValue([{ deliveryGroupId: 'project-1', detailBarcode: null, barcodes: ['DNZ030516N717V01'] }])
jest.mocked(getMaterialById).mockResolvedValue({
id, productModel: 'SPU-001', materialType: '自动上架-详情', authorName: '测试作者',
taskStatus: TASK_STATUS.FETCHED, createdAt: new Date(), updatedAt: new Date(), assets: [],
} as any)
const response = await GET(createRequest(`https://example.com/api/external/product-assets?materialId=${id}`))
expect((await response.json()).data).toMatchObject({
detailBarcode: null, barcodes: ['DNZ030516N717V01'], relatedMaterials: { detail: null, video: null, buyer_show: null },
})
})
test('materialId 查询应返回任务详情正式资源,并为所有资源组补齐 sortOrder', async () => {
;(getMaterialById as jest.Mock).mockResolvedValue({
id: '35d8644b-1e09-4ce8-9bb0-c529b39ba52e',
taskNo: null,
productModel: 'SPU-001',
categoryName: '旗舰店',
sceneName: '客厅',
materialType: '任务-详情',
taskStatus: TASK_STATUS.COMPLETED,
isFullSet: true,
deletedAt: null,
createdAt: new Date('2026-03-25T09:00:00.000Z'),
updatedAt: new Date('2026-03-25T09:10:00.000Z'),
assets: [
{
id: 'asset-main',
assetType: 'main',
fileUrl: 'https://s3.example/main.zip',
fileName: '主图.zip',
fileSize: BigInt(10),
sortOrder: 0,
},
{
id: 'asset-sku',
assetType: 'sku',
fileUrl: 'https://s3.example/sku.zip',
fileName: 'SKU.zip',
fileSize: BigInt(20),
sortOrder: 1,
},
{
id: 'asset-detail',
assetType: 'detail',
fileUrl: 'https://s3.example/detail.zip',
fileName: '详情.zip',
fileSize: BigInt(30),
sortOrder: 2,
},
{
id: 'asset-psd',
assetType: 'psd',
fileUrl: 'https://s3.example/source.psd',
fileName: '源文件.psd',
fileSize: BigInt(40),
sortOrder: 3,
},
],
})
const response = await GET(
createRequest(
'https://example.com/api/external/product-assets?materialId=35d8644b-1e09-4ce8-9bb0-c529b39ba52e',
),
)
const body = await response.json()
expect(response.status).toBe(200)
expect(body.success).toBe(true)
expect(body.data).toEqual({
materialId: '35d8644b-1e09-4ce8-9bb0-c529b39ba52e',
taskNo: null,
productModel: 'SPU-001',
categoryName: '旗舰店',
shopName: '旗舰店',
sceneName: '客厅',
isFullSet: true,
status: TASK_STATUS.FETCHED,
createdAt: '2026-03-25T09:00:00.000Z',
updatedAt: '2026-03-25T09:10:00.000Z',
assets: {
main: [
{
id: 'asset-main',
url: 'rewritten:https://s3.example/main.zip',
fileName: '主图.zip',
fileSize: 10,
sortOrder: 0,
},
],
sku: [
{
id: 'asset-sku',
url: 'rewritten:https://s3.example/sku.zip',
fileName: 'SKU.zip',
fileSize: 20,
sortOrder: 1,
},
],
detail: [
{
id: 'asset-detail',
url: 'rewritten:https://s3.example/detail.zip',
fileName: '详情.zip',
fileSize: 30,
sortOrder: 2,
},
],
psd: [
{
id: 'asset-psd',
url: 'rewritten:https://s3.example/source.psd',
fileName: '源文件.psd',
fileSize: 40,
sortOrder: 3,
},
],
},
downloadUrl: 'https://download.example/35d8644b-1e09-4ce8-9bb0-c529b39ba52e',
downloadUrls: {
all: 'https://download.example/35d8644b-1e09-4ce8-9bb0-c529b39ba52e',
},
})
expect(updateTaskStatus).toHaveBeenCalledWith(
'35d8644b-1e09-4ce8-9bb0-c529b39ba52e',
TASK_STATUS.FETCHED,
expect.objectContaining({
taskFetchedAt: expect.any(Date),
}),
)
expect(getMaterialByTaskNo).not.toHaveBeenCalled()
expect(logApiCall).toHaveBeenCalled()
})
test.each(['materialId', 'taskNo'])('%s:已获取素材连续更新后,每次查询返回最新正式图片包', async (queryBy) => {
const id = '35d8644b-1e09-4ce8-9bb0-c529b39ba52e'
const taskNo = 'TASK202601030184'
const lookup = (queryBy === 'materialId' ? getMaterialById : getMaterialByTaskNo) as jest.Mock
for (const revision of [1, 2, 3]) {
const updatedAt = new Date(`2026-10-29T0${revision}:00:00.000Z`)
const url = `uploads/materials/sku-v${revision}.zip`
lookup.mockResolvedValue({
id, taskNo, materialType: '任务-详情', taskStatus: TASK_STATUS.FETCHED,
productModel: 'GBGJ-SZ0244', isFullSet: false, deletedAt: null,
createdAt: new Date('2026-09-15T00:00:00.000Z'), updatedAt,
assets: [{ id: 'asset-sku', assetType: 'sku', fileUrl: url,
fileName: `sku-v${revision}.zip`, fileSize: BigInt(revision * 100), sortOrder: 0 }],
})
const response = await GET(createRequest(
`https://example.com/api/external/product-assets?${queryBy}=${queryBy === 'materialId' ? id : taskNo}`,
))
const body = await response.json()
expect(response.status).toBe(200)
expect(response.headers.get('Cache-Control')).toBe('private, no-store')
expect(body.data.updatedAt).toBe(updatedAt.toISOString())
expect(body.data.assets.sku).toEqual([expect.objectContaining({
id: 'asset-sku', url: `rewritten:${url}`, fileName: `sku-v${revision}.zip`, fileSize: revision * 100,
})])
expect(body.data.downloadUrls.all).toBe(`https://download.example/${id}`)
}
expect(lookup).toHaveBeenCalledTimes(3)
expect(updateTaskStatus).not.toHaveBeenCalled()
})
test('未提供 taskNo 和 materialId 时应立即失败', async () => {
const response = await GET(createRequest('https://example.com/api/external/product-assets'))
const body = await response.json()
expect(response.status).toBe(400)
expect(body).toEqual({
success: false,
error: {
code: 'INVALID_QUERY',
message: '请提供 taskNo 或 materialId',
},
})
})
test('任务-其他应继续走老接口地址,但返回轻量 files 结构', async () => {
;(getMaterialByTaskNo as jest.Mock).mockResolvedValue({
id: 'material-task-other-1',
taskNo: 'TASK202603310001',
productModel: 'TASK202603310001',
categoryName: '通用',
sceneName: '通用',
materialType: '任务-其他',
taskStatus: TASK_STATUS.COMPLETED,
isFullSet: false,
deletedAt: null,
previewUrl: 'https://s3.example/task-other-cover.webp',
zipFileName: '任务其他源文件.zip',
zipFileSize: BigInt(52428800),
createdAt: new Date('2026-03-31T08:00:00.000Z'),
updatedAt: new Date('2026-03-31T08:05:00.000Z'),
assets: [
{
id: 'asset-preview',
assetType: 'preview',
fileUrl: 'https://s3.example/task-other-cover.webp',
fileName: 'cover.webp',
fileSize: BigInt(1024),
sortOrder: 0,
},
{
id: 'asset-zip',
assetType: 'zip',
fileUrl: 'uploads/materials/task-other.zip',
fileName: '任务其他源文件.zip',
fileSize: BigInt(52428800),
sortOrder: 0,
},
],
})
const response = await GET(
createRequest('https://example.com/api/external/product-assets?taskNo=TASK202603310001'),
)
const body = await response.json()
expect(response.status).toBe(200)
expect(body.success).toBe(true)
expect(body.data).toEqual({
materialId: 'material-task-other-1',
materialType: '任务-其他',
taskNo: 'TASK202603310001',
productModel: 'TASK202603310001',
categoryName: '通用',
shopName: '通用',
sceneName: '通用',
isFullSet: false,
status: TASK_STATUS.FETCHED,
createdAt: '2026-03-31T08:00:00.000Z',
updatedAt: '2026-03-31T08:05:00.000Z',
files: [
{
id: 'material-task-other-1',
url: 'rewritten:https://s3.example/task-other-cover.webp',
downloadUrl: 'https://download.example/material-task-other-1',
fileName: '任务其他源文件.zip',
fileSize: 52428800,
},
],
downloadUrls: {
all: 'https://download.example/material-task-other-1',
},
})
})
})