gongxiangp2/lib/__tests__/product-barcode-images-route.test.ts

290 lines
10 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 { GET } from '@/app/api/external/product-barcode-images/route'
import { logApiCall, validateApiKey } from '@/lib/external-api'
import { prisma } from '@/lib/prisma'
import { verifyDownloadToken } from '@/lib/download-token'
import fixture from './fixtures/xiaoyi-free-barcode.json'
jest.mock('@/lib/prisma', () => ({
prisma: {
materialAssetBarcode: {
findMany: jest.fn(),
},
},
}))
jest.mock('@/lib/url-rewrite', () => ({
rewriteStorageUrlForClient: jest.fn((url?: string | null) => (url ? `rewritten:${url}` : null)),
}))
jest.mock('@/lib/public-app-url', () => ({ getPublicAppOrigin: () => 'https://download.example' }))
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(),
API_ERROR: {
INVALID_API_KEY: { code: 'INVALID_API_KEY', message: 'API Key 无效或缺失', status: 401 },
INVALID_BARCODE: { code: 'INVALID_BARCODE', message: '产品条码不能为空', status: 400 },
BARCODE_NOT_FOUND: { code: 'BARCODE_NOT_FOUND', message: '未找到对应的产品条码图片', status: 404 },
SERVER_ERROR: { code: 'SERVER_ERROR', message: '服务器内部错误', status: 500 },
},
}
})
describe('external product-barcode-images route', () => {
beforeEach(() => {
jest.clearAllMocks()
;(validateApiKey as jest.Mock).mockResolvedValue({
id: 'api-key-1',
name: 'product-platform',
isActive: true,
})
;(prisma.materialAssetBarcode.findMany as jest.Mock).mockResolvedValue([])
})
afterEach(() => jest.restoreAllMocks())
function createRequest(url: string) {
return {
nextUrl: new URL(url),
headers: new Headers({
'X-API-Key': 'test-key',
'user-agent': 'jest',
}),
} as any
}
test('API Key 无效时应返回 401', async () => {
;(validateApiKey as jest.Mock).mockResolvedValue(null)
const response = await GET(
createRequest('https://example.com/api/external/product-barcode-images?barcode=DNZ030516N717V01'),
)
const body = await response.json()
expect(response.status).toBe(401)
expect(body.error.code).toBe('INVALID_API_KEY')
expect(validateApiKey).toHaveBeenCalledWith('test-key')
expect(prisma.materialAssetBarcode.findMany).not.toHaveBeenCalled()
})
test.each(fixture.sku.flatMap(file => file.barcodes))('按原值精确查询条码 %s,并过滤私密任务详情', async barcode => {
const query = new URLSearchParams({ barcode: ' ' + barcode + ' ' })
await GET(createRequest('https://example.com/api/external/product-barcode-images?' + query))
expect(prisma.materialAssetBarcode.findMany).toHaveBeenCalledWith(expect.objectContaining({
where: {
barcode,
asset: {
OR: [
{ assetType: 'sku-preview', material: { materialType: '任务-详情' } },
{ assetType: 'sku', material: { materialType: '自动上架-详情' } },
],
material: { accessScope: 'general', taskDetailPrivate: false, deletedAt: null },
},
},
}))
})
test('barcode 为空时应返回 400', async () => {
const response = await GET(
createRequest('https://example.com/api/external/product-barcode-images?barcode='),
)
const body = await response.json()
expect(response.status).toBe(400)
expect(body.error.code).toBe('INVALID_BARCODE')
expect(logApiCall).toHaveBeenCalledWith(
expect.objectContaining({
queryType: 'barcode',
statusCode: 400,
}),
)
})
test('找不到条码时应返回 404', async () => {
const response = await GET(
createRequest('https://example.com/api/external/product-barcode-images?barcode=DNZ030516N717V01'),
)
const body = await response.json()
expect(response.status).toBe(404)
expect(body.error.code).toBe('BARCODE_NOT_FOUND')
})
test('命中多条历史记录时应按最新优先返回并标记 isLatest', async () => {
;(prisma.materialAssetBarcode.findMany as jest.Mock).mockResolvedValue([
{
assetId: 'asset-old',
barcode: 'DNZ030516N717V01',
asset: {
id: 'asset-old',
assetType: 'sku-preview',
fileUrl: 'https://s3.example/old.webp',
fileName: 'old.webp',
sortOrder: 1,
skuCode: 'SKU-OLD',
createdAt: new Date('2026-04-21T09:00:00.000Z'),
updatedAt: new Date('2026-04-21T09:05:00.000Z'),
barcodes: [{ barcode: 'DNZ030516N717V01' }],
material: {
id: 'material-old',
materialType: '任务-详情',
taskNo: 'TASK202604210001',
productModel: 'SPU-OLD',
categoryName: '老店铺',
sceneName: '卧室',
authorName: '旧作者',
user: {
realName: '李四',
username: 'lisi',
},
},
},
},
{
assetId: 'asset-new',
barcode: 'DNZ030516N717V01',
asset: {
id: 'asset-new',
assetType: 'sku-preview',
fileUrl: 'https://s3.example/new.webp',
fileName: 'new.webp',
sortOrder: 0,
skuCode: 'SKU-NEW',
createdAt: new Date('2026-04-22T09:00:00.000Z'),
updatedAt: new Date('2026-04-22T09:05:00.000Z'),
barcodes: [{ barcode: 'DNZ030516N717V01' }, { barcode: 'SG008839N1049V01' }],
material: {
id: 'material-new',
materialType: '任务-详情',
taskNo: 'TASK202604220001',
productModel: 'SPU-NEW',
categoryName: '新店铺',
sceneName: '客厅',
authorName: '新作者',
user: {
realName: '张三',
username: 'zhangsan',
},
},
},
},
])
const response = await GET(
createRequest('https://example.com/api/external/product-barcode-images?barcode=DNZ030516N717V01'),
)
const body = await response.json()
expect(response.status).toBe(200)
expect(body.success).toBe(true)
expect(body.data).toEqual({
barcode: 'DNZ030516N717V01',
total: 2,
items: [
{
materialId: 'material-new',
assetId: 'asset-new',
taskNo: 'TASK202604220001',
productModel: 'SPU-NEW',
categoryName: '新店铺',
shopName: '新店铺',
sceneName: '客厅',
skuCode: 'SKU-NEW',
barcode: 'DNZ030516N717V01',
barcodes: ['DNZ030516N717V01', 'SG008839N1049V01'],
materialType: '任务-详情', assetType: 'sku-preview',
width: null, height: null, resolution: null, aspectRatio: null,
previewUrl: 'rewritten:https://s3.example/new.webp',
fileName: 'new.webp',
sortOrder: 0,
uploadedAt: '2026-04-22T09:00:00.000Z',
updatedAt: '2026-04-22T09:05:00.000Z',
uploaderName: '张三',
isLatest: true,
},
{
materialId: 'material-old',
assetId: 'asset-old',
taskNo: 'TASK202604210001',
productModel: 'SPU-OLD',
categoryName: '老店铺',
shopName: '老店铺',
sceneName: '卧室',
skuCode: 'SKU-OLD',
barcode: 'DNZ030516N717V01',
barcodes: ['DNZ030516N717V01'],
materialType: '任务-详情', assetType: 'sku-preview',
width: null, height: null, resolution: null, aspectRatio: null,
previewUrl: 'rewritten:https://s3.example/old.webp',
fileName: 'old.webp',
sortOrder: 1,
uploadedAt: '2026-04-21T09:00:00.000Z',
updatedAt: '2026-04-21T09:05:00.000Z',
uploaderName: '李四',
isLatest: false,
},
],
})
expect(logApiCall).toHaveBeenCalledWith(
expect.objectContaining({
queryType: 'barcode',
queryValue: 'DNZ030516N717V01',
statusCode: 200,
}),
)
})
test('旧条码入口优先返回最新的小壹成图及可下载链接,同时保留旧图', async () => {
jest.replaceProperty(process, 'env', { ...process.env, DOWNLOAD_TOKEN_SECRET: 'test-download-key' })
const barcode = '001-A'
const date = new Date('2026-12-04T09:00:00.000Z')
const material = { id: 'delivery', materialType: '自动上架-详情', productModel: 'SPU', categoryName: '旗舰店' }
const asset = { id: 'xiaoyi-sku', assetType: 'sku', fileName: '001-A.jpg', sortOrder: 0,
createdAt: date, updatedAt: date, barcodes: [{ barcode }], material }
jest.mocked(prisma.materialAssetBarcode.findMany).mockResolvedValue([
{ barcode, asset: { ...asset, id: 'old-sku', assetType: 'sku-preview', fileUrl: 'https://s3.example/old.webp',
createdAt: new Date('2026-01-01'), material: { ...material, id: 'old', materialType: '任务-详情' } } },
{ barcode, asset: { ...asset, fileUrl: 'uploads/xiaoyi-deliveries/owner/project/request/sku/1440x1920/hash/001-A.jpg' } },
] as any)
const response = await GET(createRequest(`https://example.com/api/external/product-barcode-images?barcode=${barcode}`))
const { data } = await response.json()
expect(response.status).toBe(200)
expect(data.items).toMatchObject([
{ assetId: 'xiaoyi-sku', barcode, materialType: '自动上架-详情', assetType: 'sku', isLatest: true,
width: 1440, height: 1920, resolution: '1440x1920', aspectRatio: '3:4', fileName: '001-A.jpg' },
{ assetId: 'old-sku', assetType: 'sku-preview', resolution: null, isLatest: false },
])
const preview = new URL(data.items[0].previewUrl)
expect(preview.origin + preview.pathname).toBe('https://download.example/api/external/download')
expect(verifyDownloadToken(preview.searchParams.get('token')!)).toMatchObject({
materialId: 'delivery', assetId: 'xiaoyi-sku', downloadType: 'single',
})
})
})