gongxiangp2/lib/__tests__/desktop-product-platform-route.test.ts

319 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 { GET, POST } from '@/app/api/desktop/[...path]/route'
import { prisma } from '@/lib/prisma'
jest.mock('@/lib/auth', () => ({ authOptions: {} }))
jest.mock('next-auth', () => ({ getServerSession: jest.fn() }))
jest.mock('@/lib/prisma', () => ({ prisma: { $queryRawUnsafe: jest.fn(), $executeRawUnsafe: jest.fn(), user: { findUnique: jest.fn() } } }))
jest.mock('@/lib/detail-generator/repository', () => ({}))
jest.mock('@/lib/detail-generator/storage', () => ({}))
jest.mock('@/lib/desktop-client/project-lifecycle', () => ({}))
const querySession = prisma.$queryRawUnsafe as jest.Mock
const findUser = prisma.user.findUnique as jest.Mock
const context = { params: { path: ['product-platform', 'spu'] } }
const origin = 'https://product-platform.test:8443'
const apiKey = 'mock-product-platform-key'
const authorization = `Bearer dcs_${'a'.repeat(64)}`
const account = { username: 'owner', isActive: true, status: 'active', archivedAt: null }
const originalEnv = process.env
let upstream: jest.SpyInstance<Promise<Response>, Parameters<typeof fetch>>
function request(spu: string | null = 'SpU01', method = 'GET') {
const url = new URL('/api/desktop/product-platform/spu', 'https://materials.test')
if (spu !== null) url.searchParams.set('spu', spu)
return new Request(url, { method, headers: { authorization, 'X-API-Key': 'mock-client-key' } })
}
beforeEach(() => {
process.env = {
...originalEnv,
DETAIL_GENERATOR_ENABLED: 'true',
PRODUCT_PLATFORM_BASE_URL: origin,
PRODUCT_PLATFORM_BY_SPU_API_KEY: apiKey,
}
querySession.mockReset().mockResolvedValue([{ id: 'test-device', ownerId: 'test-owner', expiresAt: new Date(Date.now() + 60_000) }])
jest.mocked(prisma.$executeRawUnsafe).mockReset().mockResolvedValue(1)
findUser.mockReset().mockResolvedValue(account)
upstream = jest.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('Unexpected upstream request'))
})
afterEach(() => {
process.env = originalEnv
jest.restoreAllMocks()
})
test('requires an authorized desktop session and checks revocations', async () => {
const anonymous = await GET(new Request(request().url), context)
expect(anonymous.status).toBe(401)
expect(await anonymous.json()).toHaveProperty('code', 'unauthenticated')
expect(querySession).not.toHaveBeenCalled()
querySession.mockResolvedValueOnce([])
const revoked = await GET(request(), context)
expect(revoked.status).toBe(401)
expect(await revoked.json()).toHaveProperty('code', 'session_expired')
expect(querySession.mock.calls[0][0]).toContain('revoked_at IS NULL')
expect(findUser).not.toHaveBeenCalled()
expect(upstream).not.toHaveBeenCalled()
})
test.each([{ isActive: false }, { status: 'inactive' }, { archivedAt: new Date() }])('rejects unavailable accounts (%o)', async (changes) => {
findUser.mockResolvedValueOnce({ ...account, ...changes })
const response = await GET(request(), context)
expect(response.status).toBe(403)
expect(await response.json()).toHaveProperty('code', 'account_inactive')
expect(upstream).not.toHaveBeenCalled()
})
test.each([null, ' \t '])('requires a nonempty SPU (%s)', async (spu) => {
const response = await GET(request(spu), context)
expect(response.status).toBe(400)
expect(await response.json()).toEqual({ error: '请输入商品 SPU', code: 'invalid_request' })
expect(upstream).not.toHaveBeenCalled()
})
test('does not forward other HTTP methods', async () => {
expect((await POST(request('SpU01', 'POST'), context)).status).toBe(404)
expect(upstream).not.toHaveBeenCalled()
})
test.each([
['PRODUCT_PLATFORM_BASE_URL', undefined],
['PRODUCT_PLATFORM_BASE_URL', 'ftp://product-platform.test'],
['PRODUCT_PLATFORM_BASE_URL', 'https://product-platform.test/api'],
['PRODUCT_PLATFORM_BASE_URL', 'https://product-platform.test?'],
['PRODUCT_PLATFORM_BASE_URL', 'https://product-platform.test#'],
['PRODUCT_PLATFORM_BASE_URL', 'https://user:pass@product-platform.test'],
['PRODUCT_PLATFORM_BASE_URL', 'https://product-platform.test:99999'],
['PRODUCT_PLATFORM_BY_SPU_API_KEY', undefined],
['PRODUCT_PLATFORM_BY_SPU_API_KEY', ' '],
['PRODUCT_PLATFORM_BY_SPU_API_KEY', 'invalid\r\nmock-key'],
])('rejects invalid %s configuration (%s)', async (name, value) => {
if (value === undefined) delete process.env[name]
else process.env[name] = value
const response = await GET(request(), context)
expect(response.status).toBe(503)
expect(await response.json()).toEqual({ error: '产品平台联动未配置,请联系管理员', code: 'product_platform_misconfigured' })
expect(upstream).not.toHaveBeenCalled()
})
test.each(['application/json', 'Application/JSON; charset=utf-8'])('reports a missing SPU from a JSON 404 (%s)', async (contentType) => {
const upstreamResponse = new Response(JSON.stringify({
success: false,
error: { code: 'PRODUCT_001', message: '未找到对应 SPU 的商品资料' },
}), { status: 404, headers: { 'content-type': contentType } })
upstream.mockResolvedValueOnce(upstreamResponse)
const response = await GET(request(), context)
expect(response.status).toBe(404)
expect(await response.json()).toEqual({ error: '产品平台未找到该 SPU 资料', code: 'product_not_found' })
expect(upstreamResponse.bodyUsed).toBe(true)
})
test.each([
['HTML', 'text/html; charset=utf-8', '<!DOCTYPE html><html><h1>404 Not Found</h1></html>'],
['different error code', 'application/json', '{"success":false,"error":{"code":"OTHER_404"}}'],
['malformed JSON', 'application/json', '{"success":false'],
['non-JSON content type', 'text/plain', '{"success":false,"error":{"code":"PRODUCT_001"}}'],
['missing success flag', 'application/json', '{"error":{"code":"PRODUCT_001"}}'],
])('reports an upstream error for a 404 with %s', async (_case, contentType, payload) => {
const upstreamResponse = new Response(payload, { status: 404, headers: { 'content-type': contentType } })
upstream.mockResolvedValueOnce(upstreamResponse)
const response = await GET(request(), context)
expect(response.status).toBe(502)
expect(await response.json()).toEqual({ error: '产品平台查询接口暂不可用,请联系管理员', code: 'product_platform_upstream_error' })
expect(upstreamResponse.bodyUsed).toBe(true)
})
test.each([
[401, 'AUTH_004', 502, 'product_platform_auth_failed', '产品平台鉴权失败,请联系管理员'],
[403, 'AUTH_004', 502, 'product_platform_auth_failed', '产品平台鉴权失败,请联系管理员'],
[502, 'SYSTEM_001', 502, 'product_platform_upstream_error', '产品平台响应异常,请稍后重试'],
[504, 'SYSTEM_001', 504, 'product_platform_timeout', '产品平台请求超时,请稍后重试'],
])('maps upstream %i to a desktop error', async (upstreamStatus, upstreamCode, status, code, error) => {
upstream.mockResolvedValueOnce(Response.json({
success: false,
error: { code: upstreamCode, message: 'mock-upstream-internal-details' },
meta: { timestamp: new Date().toISOString(), requestId: 'mock-upstream-request' },
}, { status: upstreamStatus }))
const response = await GET(request(), context)
expect(response.status).toBe(status)
expect(await response.json()).toEqual({ error, code })
})
test('does not follow a redirect', async () => {
upstream.mockResolvedValueOnce(Response.redirect('https://redirect.test/'))
const response = await GET(request(), context)
expect(response.status).toBe(502)
expect(await response.json()).toHaveProperty('code', 'product_platform_upstream_error')
expect(upstream).toHaveBeenCalledTimes(1)
expect(upstream.mock.calls[0][1]?.redirect).toBe('manual')
})
test('maps network failure without returning internal errors', async () => {
upstream.mockRejectedValueOnce(new TypeError('mock-upstream-internal-details'))
const response = await GET(request(), context)
expect(response.status).toBe(502)
expect(await response.json()).toEqual({ error: '产品平台暂时无法连接,请稍后重试', code: 'product_platform_unreachable' })
})
test.each(['fetch', 'body'] as const)('applies a 15-second deadline to the upstream %s', async (phase) => {
const controller = new AbortController()
const timeout = jest.spyOn(AbortSignal, 'timeout').mockReturnValue(controller.signal)
const rejectAfterDeadline = () => {
controller.abort(new DOMException('Mock timeout', 'TimeoutError'))
return Promise.reject(controller.signal.reason)
}
if (phase === 'fetch') upstream.mockImplementationOnce(rejectAfterDeadline)
else {
const response = new Response()
jest.spyOn(response, 'json').mockImplementationOnce(rejectAfterDeadline)
upstream.mockResolvedValueOnce(response)
}
const response = await GET(request(), context)
expect(timeout).toHaveBeenCalledWith(15_000)
expect(upstream.mock.calls[0][1]?.signal).toBe(controller.signal)
expect(response.status).toBe(504)
expect(await response.json()).toEqual({ error: '产品平台请求超时,请稍后重试', code: 'product_platform_timeout' })
})
test.each(['<html>mock gateway page</html>', '{"success":true,"data":{}}'])('rejects malformed success responses', async (payload) => {
upstream.mockResolvedValueOnce(new Response(payload))
const response = await GET(request(), context)
expect(response.status).toBe(502)
expect(await response.json()).toHaveProperty('code', 'product_platform_invalid_response')
})
const emptyProduct = {
spu: 'SpU01',
productName: null,
brandName: null,
categoryName: null,
shared: { dimensions: null, sizeText: null, material: null, description: null, attributes: null, sellingPoints: [] },
mainImages: [],
barcodes: [],
}
test('preserves all product and barcode fields, including signed image URLs and null values', async () => {
const spu = 'SpU01/+&甲'
const dimensions = { length: 1400, width: 800, height: null, unit: 'mm' }
const expiresAt = '2035-01-01T00:00:00.000Z'
const signedUrl = 'https://cdn.test/oak.jpg?e=2051222400&token=mock-image-signature%2F%3D'
const emptyBarcode = {
skuCode: null, skuName: null, colorName: null, dimensions: null, spec: null, sizeText: null,
attributes: null, sellingPoints: [], images: [], updatedAt: '2026-11-30T10:00:00.000Z',
}
const data = {
spu, productName: '实木餐桌', brandName: '品牌甲', categoryName: '餐桌',
shared: { dimensions, sizeText: '1400 × 800 mm', material: '实木', description: '长方形餐桌', attributes: { materialType: '木制' }, sellingPoints: ['实木桌面'] },
mainImages: [{ url: signedUrl, kind: 'main', signed: true, expiresAt }],
barcodes: [
{
...emptyBarcode, barcode: '000Ab/+甲', skuCode: 'SKU01', skuName: '长桌', colorName: '胡桃木色', dimensions,
spec: '长桌', sizeText: '1400 × 800 mm', attributes: { packageDimensions: dimensions, specCode: 'L' },
sellingPoints: ['大桌面'], images: [
{ url: signedUrl, kind: 'reference', signed: true, expiresAt },
{ url: 'https://cdn.test/white.jpg', kind: 'whiteBackground', signed: false, expiresAt: null },
],
},
{ ...emptyBarcode, barcode: '000aB/+甲', images: [{ url: 'https://cdn.test/sku.jpg?v=8', kind: 'sku', signed: null, expiresAt: null }] },
{ ...emptyBarcode, barcode: '000C' },
],
}
upstream.mockResolvedValueOnce(Response.json({ success: true, data, meta: { requestId: 'mock-upstream-request' } }))
const response = await GET(request(` ${spu} `), context)
expect(response.status).toBe(200)
expect(response.headers.get('cache-control')).toBe('private, no-store')
const result = await response.json()
expect(result).toMatchObject({ source: 'product_platform', shared: data.shared, mainImages: data.mainImages,
barcodes: data.barcodes.map(({ updatedAt, ...row }) => row) })
expect(result.barcodes[0]).not.toHaveProperty('updatedAt')
expect(result.normalizedProduct.assets).toEqual([
expect.objectContaining({ kind: 'whiteBackground', label: '白底图 · 胡桃木色', barcode: '000Ab/+甲' }),
expect.objectContaining({ kind: 'main', url: signedUrl }),
expect.objectContaining({ kind: 'sku' }),
])
expect(upstream).toHaveBeenCalledTimes(1)
const [url, init] = upstream.mock.calls[0]
const target = new URL(String(url))
expect(target.origin).toBe(origin)
expect(target.pathname).toBe('/api/external/products/by-spu')
expect(target.searchParams.toString()).toBe(new URLSearchParams({ spu }).toString())
expect(init?.method).toBe('GET')
expect(init?.cache).toBe('no-store')
expect(Object.fromEntries(new Headers(init?.headers))).toEqual({ accept: 'application/json', 'x-api-key': apiKey })
})
test('preserves empty arrays and absent values for a product with no barcodes', async () => {
process.env.PRODUCT_PLATFORM_BASE_URL = ' http://product-platform.test/ '
upstream.mockResolvedValueOnce(Response.json({ success: true, data: emptyProduct }))
const response = await GET(request(), context)
expect(response.status).toBe(200)
expect(await response.json()).toMatchObject({ source: 'product_platform', ...emptyProduct,
normalizedProduct: { identity: { spu: 'SpU01', productName: '' }, variants: [], assets: [] } })
})
test('normalizes mixed attributes, dimension units, duplicates and signed images', async () => {
const row = {
barcode: ' 0001 ', skuCode: null, skuName: ' 旧款 ', colorName: ' Oak ', dimensions: null, spec: null,
sizeText: '140 × 70 × 75 CM', attributes: { materialType: '实木', specCode: '大号', count: 0 },
sellingPoints: [' 同款结构 ', ' 大桌面 ', '暂无'], images: [], updatedAt: '2026-11-30T10:00:00Z',
}
const signed = (url: string, kind: string) => ({ url, kind, signed: true, expiresAt: null })
const data = { ...emptyProduct, spu: ' SpU01 ', productName: ' 实木餐桌 ', brandName: ' N/A ', categoryName: ' 餐桌 ',
shared: { ...emptyProduct.shared, material: ' 实木 ', description: ' - ', sellingPoints: [' 同款结构 ', '同款结构'],
dimensions: { length: 1.4000000000000004, width: 0.7, height: 0.75, unit: '米' },
attributes: { materialType: ' 实木 ', packageDimensions: '145*75*20 厘米', texts: [' A ', '-', 'A', ' B '],
assemblyRequired: false, empty: [], none: null, object: {}, updatedAt: 'ignored', seriesName: ' 森林 ' } },
mainImages: [signed('https://cdn.test/oak.jpg?v=2&token=old', 'reference')],
barcodes: [row, { ...row, barcode: '0001', skuName: ' 新款 ', updatedAt: '2026-12-01T11:00:00Z',
attributes: { specCode: '加大', assemblyRequired: false }, images: [
signed('https://cdn.test/oak.jpg?token=new&v=2#preview', 'whiteBackground'),
signed('https://cdn.test/oak.jpg?v=3&token=new', 'sku'),
] }, { ...row, barcode: '0002', colorName: 'oak' }],
}
upstream.mockImplementation(() => Promise.resolve(Response.json({ success: true, data })))
const result = await (await GET(request(), context)).json()
const product = result.normalizedProduct
expect(product.identity).toEqual({ spu: 'SpU01', productName: '实木餐桌', platformBrand: null, platformCategory: '餐桌', seriesOrModel: '森林' })
expect(product.specs.dimensions).toEqual({ length: 1400, width: 700, height: 750, unit: 'mm', display: '1400×700×750 mm' })
expect(product.specs.packageDimensions.display).toBe('1450×750×200 mm')
expect(product.specs.attributes).toContainEqual({ key: 'texts', label: 'texts', value: 'A、B', group: 'other' })
expect(product.copy).toEqual({ summary: null, sellingPoints: ['同款结构'] })
expect(product.variants).toHaveLength(1)
const [variant] = product.variants
expect(variant.id).toMatch(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/)
expect(variant.colorName).toBe('Oak')
expect(variant.barcodes[0]).toMatchObject({ barcode: '0001', skuName: '新款', dimensions: null, sellingPoints: ['大桌面'],
attributes: [{ key: 'specCode', label: '规格编码', value: '加大' }, { key: 'count', label: 'count', value: '0' }] })
expect(product.assets).toHaveLength(2)
expect(product.assets[0]).toMatchObject({ kind: 'whiteBackground', label: '白底图 · Oak', selectedForProject: true })
expect(variant.barcodes[0].imageIds).toContain(product.assets[0].id)
expect(product.trace.rawFieldWarnings).toEqual(['已合并重复条码:0001'])
expect(JSON.stringify(result.platformFacts)).not.toContain('updatedAt')
const repeated = await (await GET(request(), context)).json()
expect(repeated.normalizedProduct.variants[0].id).toBe(variant.id)
})
test('selects white background and main images before the project limit and retains remaining assets', async () => {
const image = (name: string, kind: string) => ({ url: `https://cdn.test/${name}.jpg`, kind, signed: false, expiresAt: null })
upstream.mockResolvedValueOnce(Response.json({ success: true, data: {
...emptyProduct,
mainImages: [
...Array.from({ length: 8 }, (_, index) => image(`ref-${index}`, 'reference')),
image('main', 'main'), image('white', 'whiteBackground'),
],
} }))
const result = await (await GET(request(), context)).json()
const assets = result.normalizedProduct.assets
expect(assets).toHaveLength(10)
expect(assets.filter((asset: { selectedForProject: boolean }) => asset.selectedForProject)).toHaveLength(8)
expect(assets.slice(0, 2)).toEqual([
expect.objectContaining({ kind: 'whiteBackground', selectedForProject: true }),
expect.objectContaining({ kind: 'main', selectedForProject: true }),
])
})