fix: expose Xiaoyi listing assets by barcode and spec

This commit is contained in:
WuYongJie 2026-12-04 20:03:18 +08:00
parent 035b373264
commit dbfff0f160
9 changed files with 331 additions and 56 deletions

View File

@ -1,5 +1,6 @@
import { EXTERNAL_MATERIAL_SCOPE_WHERE, isRestrictedMaterial } from '@/lib/material-access-scope'
import { resolveStoredUploadPath } from '@/lib/upload-paths'
import { isXiaoyiDeliveryMaterial, xiaoyiSkuDimensions } from '@/lib/xiaoyi-delivery-material'
/**
* 外部接口:文件下载
* GET - 通过 Token 下载文件
@ -159,7 +160,7 @@ async function handleDownload(request: NextRequest) {
);
}
if (['自动上架-详情', '自动上架-视频', '自动上架-买家秀'].includes(material.materialType)) {
if (isXiaoyiDeliveryMaterial(material.materialType)) {
if (downloadType === 'all') {
const assets = material.assets.filter((item: any) => ['main','sku','detail','video','buyer_show'].includes(item.assetType))
if (!assets.length || assets.some((item: any) => {
@ -687,17 +688,22 @@ async function downloadAsZip(assets: any[], taskNo: string, downloadType: string
let failCount = 0;
const skuNames = new Map<string, number>();
for (const asset of assets) {
if (asset.assetType !== 'sku' || !asset.fileName) continue;
const name = asset.fileName.toLowerCase();
skuNames.set(name, (skuNames.get(name) ?? 0) + 1);
}
for (const asset of assets) {
const skuResolutions = new Set<string>();
const files = assets.map(asset => {
const fileUrl = normalizeAssetFileUrl(asset.fileUrl);
const fileName = asset.fileName || path.basename(fileUrl);
const skuResolution = /\/xiaoyi-deliveries\/[^/]+\/[^/]+\/[^/]+\/sku\/(\d+x\d+)\//.exec(fileUrl)?.[1];
const group = asset.assetType === 'sku' && (skuNames.get(fileName.toLowerCase()) ?? 0) > 1
? `sku/${skuResolution ?? asset.sortOrder}` : asset.assetType;
const { resolution } = xiaoyiSkuDimensions(asset.assetType, fileUrl);
if (resolution) skuResolutions.add(resolution);
if (asset.assetType === 'sku') {
const name = fileName.toLowerCase();
skuNames.set(name, (skuNames.get(name) ?? 0) + 1);
}
return { asset, fileUrl, fileName, resolution };
});
for (const { asset, fileUrl, fileName, resolution } of files) {
const repeatedSkuName = asset.assetType === 'sku' && (skuNames.get(fileName.toLowerCase()) ?? 0) > 1;
const group = repeatedSkuName || (resolution && skuResolutions.size > 1)
? `sku/${resolution ?? asset.sortOrder}` : asset.assetType;
const entryName = `${group}/${fileName}`;
try {

View File

@ -1,6 +1,9 @@
import { isRestrictedMaterial } from '@/lib/material-access-scope'
import { prisma } from '@/lib/prisma'
import { isXiaoyiDeliveryMaterial, XIAOYI_DELIVERY_MATERIAL_TYPES, XIAOYI_DETAIL_ASSET_GROUPS, type XiaoyiDeliveryKind } from '@/lib/xiaoyi-delivery-material'
import {
isXiaoyiDeliveryMaterial, readXiaoyiDeliveryMetadata, XIAOYI_DELIVERY_LOG_ACTION,
XIAOYI_DELIVERY_MATERIAL_TYPES, XIAOYI_DETAIL_ASSET_GROUPS, xiaoyiSkuDimensions, type XiaoyiDeliveryKind,
} from '@/lib/xiaoyi-delivery-material'
import { parseListingUpdate, pendingListingStatus, recordListingStatus, type ListingStatus } from '@/lib/xiaoyi-listing-status'
import { XIAOYI_LISTING_KEY_SCOPE } from '@/lib/external-api'
@ -170,10 +173,14 @@ export async function GET(request: NextRequest) {
brandName: string; productName: string; eventId: string | null; listingStatus: ListingStatus | null
deliveryGroupId: string; authorId: string; detailBarcode: string | null; barcodes: string[] | null
relatedMaterials: Partial<Record<XiaoyiDeliveryKind, string>> | null
metadataChanges: string | null
}>>`
SELECT d.brand_name AS "brandName", d.product_name AS "productName",
e.id AS "eventId", d.listing_status AS "listingStatus", d.project_id AS "deliveryGroupId", d.owner_id AS "authorId",
siblings."relatedMaterials", codes."detailBarcode", codes.barcodes
siblings."relatedMaterials", codes."detailBarcode", codes.barcodes,
(SELECT log.changes FROM material_logs log
WHERE log."materialId" = d.material_id AND log.action = ${XIAOYI_DELIVERY_LOG_ACTION}
ORDER BY log.timestamp DESC LIMIT 1) AS "metadataChanges"
FROM desktop_material_deliveries d
JOIN materials delivered ON delivered.id = d.material_id
LEFT JOIN xiaoyi_auto_listing_events e ON e.material_id = d.material_id
@ -196,14 +203,20 @@ export async function GET(request: NextRequest) {
WHERE d.material_id = ${material.id}
`
if (listingOnly && !delivery?.eventId) return errorResponse(API_ERROR.MATERIAL_NOT_FOUND)
const metadata = readXiaoyiDeliveryMetadata(delivery?.metadataChanges)
const groups: Record<string, any[]> = {main: [], sku: [], detail: [], video: [], buyer_show: []}
for (const asset of material.assets || []) {
if (!groups[asset.assetType]) continue
const spec = metadata?.assetSpecs?.[asset.id]
groups[asset.assetType].push({
id: asset.id,
fileName: asset.fileName || '',
fileSize: Number(asset.fileSize || 0),
sortOrder: asset.sortOrder || 0,
...xiaoyiSkuDimensions(asset.assetType, asset.fileUrl),
specId: spec?.specId ?? null,
variantId: spec?.variantId ?? null,
variantName: spec?.variantName ?? null,
...(asset.assetType === 'sku' ? {
skuCode: asset.skuCode || null,
barcodes: (asset.barcodes || []).map((entry: { barcode: string }) => entry.barcode),
@ -225,6 +238,7 @@ export async function GET(request: NextRequest) {
identifier: material.productModel,
spu: delivery || groups.sku.some(asset => asset.barcodes.length) ? material.productModel : null,
categoryName: material.categoryName, productCategoryName: material.productCategoryName,
storeCategoryName: metadata?.storeCategoryName ?? (material.categoryName || null),
authorId: delivery?.authorId ?? material.userId,
authorName: material.authorName,
detailBarcode: delivery?.detailBarcode ?? null,

View File

@ -2,6 +2,9 @@ import { EXTERNAL_MATERIAL_SCOPE_WHERE } from '@/lib/material-access-scope'
import { NextRequest } from 'next/server'
import { prisma } from '@/lib/prisma'
import { rewriteStorageUrlForClient } from '@/lib/url-rewrite'
import { generateDownloadUrl } from '@/lib/download-token'
import { getPublicAppOrigin } from '@/lib/public-app-url'
import { XIAOYI_DELIVERY_MATERIAL_TYPES, xiaoyiSkuDimensions } from '@/lib/xiaoyi-delivery-material'
import {
API_ERROR,
errorResponse,
@ -21,7 +24,14 @@ interface BarcodeImageItem {
shopName: string
sceneName: string
skuCode: string | null
barcode: string
barcodes: string[]
materialType: string
assetType: string
width: number | null
height: number | null
resolution: string | null
aspectRatio: string | null
previewUrl: string
fileName: string
sortOrder: number
@ -62,9 +72,11 @@ export async function GET(request: NextRequest) {
where: {
barcode,
asset: {
assetType: 'sku-preview',
OR: [
{ assetType: 'sku-preview', material: { materialType: '任务-详情' } },
{ assetType: 'sku', material: { materialType: XIAOYI_DELIVERY_MATERIAL_TYPES.detail } },
],
material: {
materialType: '任务-详情',
...EXTERNAL_MATERIAL_SCOPE_WHERE,
deletedAt: null,
},
@ -76,6 +88,7 @@ export async function GET(request: NextRequest) {
asset: {
select: {
id: true,
assetType: true,
fileUrl: true,
fileName: true,
sortOrder: true,
@ -90,6 +103,7 @@ export async function GET(request: NextRequest) {
material: {
select: {
id: true,
materialType: true,
taskNo: true,
productModel: true,
categoryName: true,
@ -125,10 +139,16 @@ export async function GET(request: NextRequest) {
shopName: String(material.categoryName || ''),
sceneName: String(material.sceneName || ''),
skuCode: asset.skuCode || null,
barcode: match.barcode,
barcodes: Array.from(
new Set((asset.barcodes || []).map((item: any) => String(item.barcode || '').trim()).filter(Boolean)),
new Set((asset.barcodes || []).map(item => item.barcode.trim()).filter(Boolean)),
),
previewUrl: rewriteStorageUrlForClient(asset.fileUrl, request) || String(asset.fileUrl || ''),
materialType: material.materialType,
assetType: asset.assetType,
...xiaoyiSkuDimensions(asset.assetType, asset.fileUrl),
previewUrl: material.materialType === XIAOYI_DELIVERY_MATERIAL_TYPES.detail
? generateDownloadUrl(getPublicAppOrigin(), { materialId: material.id, downloadType: 'single', assetId: asset.id })
: rewriteStorageUrlForClient(asset.fileUrl, request) || String(asset.fileUrl || ''),
fileName: String(asset.fileName || ''),
sortOrder: Number(asset.sortOrder || 0),
uploadedAt: asset.createdAt.toISOString(),
@ -187,7 +207,9 @@ export async function GET(request: NextRequest) {
userAgent: request.headers.get('user-agent') || undefined,
})
return successResponse(responseData)
const response = successResponse(responseData)
response.headers.set('Cache-Control', 'private, no-store')
return response
} catch (error) {
console.error('[external/product-barcode-images] GET error:', error)

View File

@ -11,7 +11,7 @@ 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() },
material: { create: jest.fn() }, materialLog: { create: jest.fn() },
} }))
jest.mock('@/lib/detail-generator/materials', () => ({ findDetailMaterialMatches: jest.fn() }))
jest.mock('node:fs', () => ({ createReadStream: jest.fn(() => [Buffer.from('x')]) }))
@ -57,6 +57,18 @@ beforeEach(() => {
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(rename).mockResolvedValue(undefined)
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')
@ -111,20 +123,11 @@ test('旧客户端没有 JSON 条码时沿用 JPG 文件名中的条码', async
})
test('同条码的两种尺寸入库时保留纯条码文件名并分别存放', async () => {
jest.mocked(mkdir).mockResolvedValue(undefined)
jest.mocked(lstat).mockResolvedValue({ size: 1, isFile: () => true, isSymbolicLink: () => false } as any)
jest.mocked(rename).mockResolvedValue(undefined)
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)
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',
})) } }
const uploaded = Object.values(request.assets).flat()
jest.mocked(getOwnedUploadSession).mockImplementation(async uploadId => ({
...uploaded.find(item => item.uploadId === uploadId), uploadPurpose: 'xiaoyi:project-1:request-1',
} as any))
mockSuccessfulUpload(Object.values(request.assets).flat())
await expect(createDesktopDelivery(account.id, request, authorize)).resolves.toMatchObject({ state: 'completed' })
const destinations = jest.mocked(rename).mock.calls.map(([, target]) => String(target).replaceAll('\\', '/'))
expect(destinations).toEqual(expect.arrayContaining([
@ -142,6 +145,51 @@ test('同条码的两种尺寸入库时保留纯条码文件名并分别存放',
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: [

View File

@ -1,9 +1,10 @@
/** @jest-environment node */
import { NextRequest } from 'next/server'
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { dirname, join } from 'node:path'
import AdmZip from 'adm-zip'
import { GET } from '@/app/api/external/download/route'
import { isTokenExpired, verifyDownloadToken } from '@/lib/download-token'
@ -117,6 +118,48 @@ describe('external single-file S3 download range forwarding', () => {
await rm(localTempDir, { recursive: true, force: true })
})
test.each([
[['1440x1440/001-A.jpg'], ['sku/001-A.jpg']],
[
['800x800/001-A.jpg', '1440x1920/001-A.jpg', '1440x1920/001-B.jpg'],
['sku/800x800/001-A.jpg', 'sku/1440x1920/001-A.jpg', 'sku/1440x1920/001-B.jpg'],
],
])('小壹 ZIP 按分辨率组织 SKU 并保留单分辨率的历史目录(%j)', async (paths, expected) => {
jest.mocked(verifyDownloadToken).mockReturnValue({ materialId: 'material-1', downloadType: 'all' })
const assets = await Promise.all(paths.map(async (relative, sortOrder) => {
const [resolution, fileName] = relative.split('/')
const fileUrl = join(localTempDir, 'xiaoyi-deliveries', 'owner', 'project', 'request', 'sku', resolution, 'hash', fileName)
await mkdir(dirname(fileUrl), { recursive: true })
await writeFile(fileUrl, relative)
return { assetType: 'sku', fileUrl, fileName, sortOrder }
}))
jest.mocked(prisma.material.findUnique).mockResolvedValue({
...makeMaterial(), materialType: '自动上架-详情', assets,
} as any)
const response = await GET(makeRequest())
expect(response.status).toBe(200)
const zip = new AdmZip(Buffer.from(await response.arrayBuffer()))
expect(zip.getEntries().map(entry => entry.entryName).sort()).toEqual([...expected].sort())
expected.forEach((entry, index) => expect(zip.readAsText(entry)).toBe(paths[index]))
})
test.each([{ accessScope: 'operations_g' }, { taskDetailPrivate: true }])(
'小壹成图的下载 Token 仍会核对当前素材权限(%j)', async restrictions => {
jest.mocked(prisma.material.findUnique).mockResolvedValue({
...makeMaterial(), materialType: '自动上架-详情', ...restrictions,
} as any)
const response = await GET(makeRequest())
expect(response.status).toBe(404)
expect(prisma.material.findUnique).toHaveBeenCalledWith(expect.objectContaining({
where: { id: 'material-1', accessScope: 'general', taskDetailPrivate: false, deletedAt: null },
}))
expect(global.fetch).not.toHaveBeenCalled()
},
)
test('forwards Range to S3 and preserves a 206 streaming response', async () => {
;(global.fetch as jest.Mock).mockResolvedValueOnce(
makeUpstreamResponse(206, 1024, {

View File

@ -191,6 +191,47 @@ describe('external product-assets route', () => {
})
})
test('回调拉取按资产 ID 返回 SKU 规格、分辨率及店铺分类,历史文件缺字段时返回 null', async () => {
const id = '35d8644b-1e09-4ce8-9bb0-c529b39ba52e'
const spec = { specId: 'deep', variantId: 'white', variantName: '白色加深款' }
const sku = (id: string, fileUrl: string, sortOrder: number) => ({
id, assetType: 'sku', fileName: '001-A.jpg', skuCode: 'SKU-1', barcodes: [{ barcode: '001-A' }], fileUrl, sortOrder,
})
jest.mocked(validateApiKey).mockResolvedValue({ id: 'listing-key', scope: 'xiaoyi_auto_listing' } as any)
jest.mocked(prisma.$queryRaw).mockResolvedValue([{
eventId: 'event-1', metadataChanges: JSON.stringify({ deliveryMetadata: { newValue: {
storeCategoryName: '平台店铺分类', assetSpecs: { portrait: spec, square: spec },
} } }),
}])
jest.mocked(getMaterialById).mockResolvedValue({
id, materialType: '自动上架-详情', taskStatus: TASK_STATUS.FETCHED,
categoryName: '店铺', productCategoryName: '书柜', createdAt: new Date(), updatedAt: new Date(),
assets: [
sku('square', 'uploads/xiaoyi-deliveries/owner/project/request/sku/1440x1440/hash/001-A.jpg', 5),
sku('portrait', 'https://storage.example/uploads/xiaoyi-deliveries/owner/project/request/sku/1440x1920/hash/001-A.jpg', 2),
{ ...sku('legacy', 'uploads/xiaoyi-deliveries/owner/project/request/0001-hash.jpg', 0), fileName: '001-B.jpg' },
{ id: 'main', assetType: 'main', fileName: 'main.jpg' },
],
} as any)
const response = await GET(createRequest(`https://example.com/api/external/product-assets?materialId=${id}`))
expect(response.status).toBe(200)
expect((await response.json()).data).toMatchObject({
categoryName: '店铺', storeCategoryName: '平台店铺分类', productCategoryName: '书柜',
assets: {
sku: [
{ ...spec, id: 'square', fileName: '001-A.jpg', skuCode: 'SKU-1', barcodes: ['001-A'], sortOrder: 5,
width: 1440, height: 1440, resolution: '1440x1440', aspectRatio: '1:1' },
{ ...spec, id: 'portrait', fileName: '001-A.jpg', width: 1440, height: 1920, resolution: '1440x1920', aspectRatio: '3:4' },
{ id: 'legacy', width: null, height: null, resolution: null, aspectRatio: null,
specId: null, variantId: null, variantName: null },
],
main: [{ id: 'main', width: null, height: null, resolution: null, aspectRatio: null,
specId: null, variantId: null, variantName: null }],
},
})
})
test('materialId 查询应返回任务详情正式资源,并为所有资源组补齐 sortOrder', async () => {
;(getMaterialById as jest.Mock).mockResolvedValue({
id: '35d8644b-1e09-4ce8-9bb0-c529b39ba52e',

View File

@ -3,6 +3,7 @@
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', () => ({
@ -17,6 +18,8 @@ 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 {
@ -63,6 +66,8 @@ describe('external product-barcode-images route', () => {
;(prisma.materialAssetBarcode.findMany as jest.Mock).mockResolvedValue([])
})
afterEach(() => jest.restoreAllMocks())
function createRequest(url: string) {
return {
nextUrl: new URL(url),
@ -83,16 +88,24 @@ describe('external product-barcode-images route', () => {
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: expect.objectContaining({
where: {
barcode,
asset: expect.objectContaining({ material: expect.objectContaining({ taskDetailPrivate: false }) }),
}),
asset: {
OR: [
{ assetType: 'sku-preview', material: { materialType: '任务-详情' } },
{ assetType: 'sku', material: { materialType: '自动上架-详情' } },
],
material: { accessScope: 'general', taskDetailPrivate: false, deletedAt: null },
},
},
}))
})
@ -129,6 +142,7 @@ describe('external product-barcode-images route', () => {
barcode: 'DNZ030516N717V01',
asset: {
id: 'asset-old',
assetType: 'sku-preview',
fileUrl: 'https://s3.example/old.webp',
fileName: 'old.webp',
sortOrder: 1,
@ -138,6 +152,7 @@ describe('external product-barcode-images route', () => {
barcodes: [{ barcode: 'DNZ030516N717V01' }],
material: {
id: 'material-old',
materialType: '任务-详情',
taskNo: 'TASK202604210001',
productModel: 'SPU-OLD',
categoryName: '老店铺',
@ -155,6 +170,7 @@ describe('external product-barcode-images route', () => {
barcode: 'DNZ030516N717V01',
asset: {
id: 'asset-new',
assetType: 'sku-preview',
fileUrl: 'https://s3.example/new.webp',
fileName: 'new.webp',
sortOrder: 0,
@ -164,6 +180,7 @@ describe('external product-barcode-images route', () => {
barcodes: [{ barcode: 'DNZ030516N717V01' }, { barcode: 'SG008839N1049V01' }],
material: {
id: 'material-new',
materialType: '任务-详情',
taskNo: 'TASK202604220001',
productModel: 'SPU-NEW',
categoryName: '新店铺',
@ -198,7 +215,10 @@ describe('external product-barcode-images route', () => {
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,
@ -216,7 +236,10 @@ describe('external product-barcode-images route', () => {
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,
@ -235,4 +258,32 @@ describe('external product-barcode-images route', () => {
}),
)
})
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',
})
})
})

View File

@ -16,16 +16,19 @@ import { findDetailMaterialMatches } from '@/lib/detail-generator/materials'
import { ensureExternalNotificationTables, queueXiaoyiAutoListingNotification, wakeXiaoyiAutoListingNotifications } from '@/lib/external-auto-listing'
import { desktopAssert, desktopId } from './contract.mjs'
import { pendingListingStatus, type ListingStatus } from '@/lib/xiaoyi-listing-status'
import { XIAOYI_DELIVERY_MATERIAL_TYPES as TYPES, XIAOYI_DETAIL_ASSET_GROUPS, type XiaoyiDeliveryKind } from '@/lib/xiaoyi-delivery-material'
import {
XIAOYI_DELIVERY_LOG_ACTION, XIAOYI_DELIVERY_MATERIAL_TYPES as TYPES, XIAOYI_DETAIL_ASSET_GROUPS,
type XiaoyiAssetSpec, type XiaoyiDeliveryKind, type XiaoyiDeliveryMetadata,
} from '@/lib/xiaoyi-delivery-material'
import type { DesktopAccount } from './service'
type FileInput = {
type FileInput = XiaoyiAssetSpec & {
uploadId: string; fileName: string; fileSize: number; sha256: string
skuCode?: string; barcode?: string; barcodes?: string[]; variantId?: string; width?: number; height?: number
skuCode?: string; barcode?: string; barcodes?: string[]; width?: number; height?: number
}
type Input = {
projectId: string; requestId: string; kind: XiaoyiDeliveryKind; identifier?: string; productModel?: string; deliverySpu?: string; detailBarcode?: string | null;
categoryName?: string; productCategoryName?: string; brandName?: string; productName?: string; identifierType?: string;
categoryName?: string; storeCategoryName?: string; productCategoryName?: string; brandName?: string; productName?: string; identifierType?: string;
assets: { main?: FileInput[]; sku?: FileInput[]; detail?: FileInput[]; files?: FileInput[] }
}
type DeliveryFile = Omit<FileInput, 'barcode' | 'barcodes' | 'width' | 'height'> & { group: string; barcodes: string[]; resolution?: string }
@ -51,16 +54,18 @@ function normalized(input: Input) {
desktopAssert(identifier.length > 0 && identifier.length <= 120, '请填写商品 SPU')
const detailBarcode = input.detailBarcode == null ? null : parseBarcodes([input.detailBarcode])[0]
desktopAssert(!detailBarcode || input.kind === 'detail', '详情页主条码只能随详情三件套提交')
const categoryName = typeof input.categoryName === 'string' ? input.categoryName.trim() : ''
const storeCategoryName = typeof input.storeCategoryName === 'string' ? input.storeCategoryName.trim() : ''
const categoryName = (typeof input.categoryName === 'string' ? input.categoryName.trim() : '') || storeCategoryName
const storeCategory = storeCategoryName && storeCategoryName !== categoryName ? { storeCategoryName } : {}
const productCategoryName = typeof input.productCategoryName === 'string' ? input.productCategoryName.trim() : ''
const brandName = typeof input.brandName === 'string' ? input.brandName.trim() : ''
const productName = typeof input.productName === 'string' ? input.productName.trim() : ''
const identifierType = typeof input.identifierType === 'string' ? input.identifierType.trim() : ''
desktopAssert([categoryName,productCategoryName,brandName,productName,identifierType].every(value => value.length <= 120), '商品资料过长')
desktopAssert([categoryName,storeCategoryName,productCategoryName,brandName,productName,identifierType].every(value => value.length <= 120), '商品资料过长')
desktopAssert(input.assets && typeof input.assets === 'object', '交付文件缺失')
const files: DeliveryFile[] = []
const legacyFiles: Array<Omit<DeliveryFile, 'barcodes'> & { barcode?: string }> = []
const barcodeOwners = new Map<string, { legacy: boolean; skuCode?: string; variantId?: string }>()
const barcodeOwners = new Map<string, { legacy: boolean; skuCode?: string; variantId?: string; specId?: string }>()
const filenames = new Set<string>()
const skuNames = new Map<string, boolean>()
let hasBarcodeArrays = false
@ -78,22 +83,24 @@ function normalized(input: Input) {
hasBarcodeArrays ||= file.barcodes !== undefined
const skuCode = typeof file.skuCode === 'string' ? file.skuCode.trim() : undefined
const variantId = file.variantId
const specId = typeof file.specId === 'string' ? file.specId.trim() || undefined : undefined
const variantName = typeof file.variantName === 'string' ? file.variantName.trim() || undefined : undefined
desktopAssert((group === 'sku' || (file.barcodes === undefined && !legacy && file.skuCode === undefined))
&& (file.skuCode === undefined || (skuCode && skuCode.length <= 200)), 'SKU 图资料无效')
desktopAssert(variantId === undefined || (group === 'sku' && file.barcodes !== undefined
&& typeof variantId === 'string' && uuid.test(variantId)), 'SKU 图花色编号无效')
for (const barcode of barcodes) {
const previous = barcodeOwners.get(barcode)
desktopAssert(!previous || (previous.skuCode === skuCode
&& ((legacy && previous.legacy) || (variantId && previous.variantId === variantId))),
desktopAssert(!previous || (previous.skuCode === skuCode && previous.variantId === variantId && previous.specId === specId
&& ((legacy && previous.legacy) || variantId || specId)),
'产品条码 ' + barcode + ' 不能同时绑定两张 SKU 图')
barcodeOwners.set(barcode, { legacy, skuCode, variantId })
barcodeOwners.set(barcode, { legacy, skuCode, variantId, specId })
}
const assetGroup = group === 'files' ? (input.kind === 'detail' ? 'source' : input.kind) : group
const nameKey = assetGroup + '\u0000' + name.fileName!.toLowerCase()
let resolution: string | undefined
if (file.width !== undefined || file.height !== undefined) {
desktopAssert(group === 'sku' && variantId && barcodes.length === 1
desktopAssert(group === 'sku' && (variantId || specId) && barcodes.length === 1
&& name.fileName === barcodes[0].normalize('NFC') + '.jpg'
&& Number.isSafeInteger(file.width) && file.width! > 0
&& Number.isSafeInteger(file.height) && file.height! > 0, 'SKU 图的条码文件名或尺寸无效')
@ -105,12 +112,12 @@ function normalized(input: Input) {
'同一分组中有重复文件')
skuNames.set(nameKey, Boolean(resolution))
}
const fileKey = legacy ? nameKey + '\u0000' + file.sha256 : resolution ? nameKey + '\u0000' + resolution : nameKey
const fileKey = resolution ? nameKey + '\u0000' + resolution : legacy ? nameKey + '\u0000' + file.sha256 : nameKey
desktopAssert(!filenames.has(fileKey), '同一分组中有重复文件')
filenames.add(fileKey)
const metadata = { group: assetGroup, fileName: name.fileName!, fileSize: file.fileSize, sha256: file.sha256 }
files.push({ ...metadata, uploadId: file.uploadId, barcodes, skuCode, ...(variantId !== undefined && { variantId }),
...(resolution && { resolution }) })
...(resolution && { resolution }), ...(specId && { specId }), ...(variantName && { variantName }) })
legacyFiles.push({ ...metadata, uploadId: file.uploadId, ...(file.barcode !== undefined && { barcode: barcodes[0], skuCode }) })
}
}
@ -125,10 +132,11 @@ function normalized(input: Input) {
desktopAssert(files.every(file => file.group === input.kind), '该交付类型只接收对应的结果文件')
desktopAssert(files.every(file => !/\.(?:psd|psb|pcraft)$/i.test(file.fileName)), '只接收成品文件,不接收源文件')
}
const identity = { projectId, requestId: input.requestId, kind: input.kind, identifier, categoryName, productCategoryName, brandName, productName, detailBarcode,
const identity = { projectId, requestId: input.requestId, kind: input.kind, identifier, categoryName, ...storeCategory, productCategoryName, brandName, productName, detailBarcode,
files: files.map(({ uploadId, barcodes, ...file }) => ({ ...file, barcodes: [...barcodes].sort() })) }
const fingerprint = createHash('sha256').update(JSON.stringify(identity)).digest('hex')
const legacyFingerprint = input.identifier === undefined && legacySpu === undefined && input.detailBarcode === undefined && !hasBarcodeArrays
&& !storeCategory.storeCategoryName && !files.some(file => file.specId || file.variantName)
? createHash('sha256').update(JSON.stringify({
projectId, requestId: input.requestId, kind: input.kind, productModel: identifier, categoryName, productCategoryName, brandName, productName, identifierType,
files: legacyFiles.map(({ uploadId, ...file }) => file),
@ -289,24 +297,36 @@ export async function createDesktopDelivery(ownerId: string, input: Input, reaut
const identifier = await projectDeliveryIdentifier(tx, ownerId, request.projectId, request.identifier)
const materialType = TYPES[request.kind]
const firstDetailIndex = files.findIndex(file => file.group === 'detail')
// Keep delivery metadata attached to the asset ID when assets are reordered.
const deliveryMetadata: XiaoyiDeliveryMetadata = { storeCategoryName: request.storeCategoryName, assetSpecs: {} }
const assets = files.map((file, index) => {
// The first detail image carries the package's primary barcode; SKU images carry their own lists.
const codes = index === firstDetailIndex && request.detailBarcode ? [request.detailBarcode] : file.barcodes
const id = randomUUID()
const { specId, variantId, variantName } = file
if (specId || variantId || variantName) deliveryMetadata.assetSpecs[id] = { specId, variantId, variantName }
return {
id, assetType: file.group, fileUrl: file.storedPath, fileName: file.fileName,
fileSize: BigInt(file.fileSize), sortOrder: index, skuCode: file.skuCode,
...(codes.length && { barcodes: { create: codes.map(barcode => ({ barcode })) } }),
}
})
const material = await tx.material.create({data:{
userId:ownerId, authorName:author.name, productModel:identifier,
categoryName:request.categoryName, productCategoryName:request.productCategoryName, sceneName:'',
materialType, previewUrl:'', taskStatus:'completed', isFullSet:request.kind === 'detail', isAiGenerated:true,
assets: { create: files.map((file,index) => {
// The first detail image carries the package's primary barcode; SKU images carry their own lists.
const codes = index === firstDetailIndex && request.detailBarcode ? [request.detailBarcode] : file.barcodes
return {
assetType: file.group, fileUrl: file.storedPath, fileName: file.fileName,
fileSize: BigInt(file.fileSize), sortOrder: index, skuCode: file.skuCode,
...(codes.length && { barcodes: { create: codes.map(barcode => ({ barcode })) } }),
}
}) },
assets: { create: assets },
},select:{id:true}})
await tx.$executeRawUnsafe(
'INSERT INTO desktop_material_deliveries (id,owner_id,project_id,request_id,kind,fingerprint,material_id,material_type,brand_name,product_name,identifier_type) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)',
randomUUID(),ownerId,request.projectId,request.requestId,request.kind,request.fingerprint,material.id,materialType,request.brandName,request.productName,'spu',
)
if (deliveryMetadata.storeCategoryName || Object.keys(deliveryMetadata.assetSpecs).length) {
await tx.materialLog.create({ data: {
materialId: material.id, userId: ownerId, action: XIAOYI_DELIVERY_LOG_ACTION,
changes: JSON.stringify({ deliveryMetadata: { oldValue: null, newValue: deliveryMetadata } }),
} })
}
await queueXiaoyiAutoListingNotification(tx,{materialId:material.id,materialType,outcomeKind:request.kind,projectId:request.projectId})
return {requestId:request.requestId,materialId:material.id,materialType,state:'completed' as const}
},{timeout:30000})

View File

@ -6,6 +6,36 @@ export const XIAOYI_DELIVERY_MATERIAL_TYPES = {
export type XiaoyiDeliveryKind = keyof typeof XIAOYI_DELIVERY_MATERIAL_TYPES
export const XIAOYI_DELIVERY_TYPES = Object.values(XIAOYI_DELIVERY_MATERIAL_TYPES)
export const XIAOYI_DETAIL_ASSET_GROUPS = ['main', 'sku', 'detail'] as const
export const XIAOYI_DELIVERY_LOG_ACTION = 'XIAOYI_DELIVERY'
export type XiaoyiAssetSpec = { specId?: string; variantId?: string; variantName?: string }
export type XiaoyiDeliveryMetadata = { storeCategoryName?: string; assetSpecs: Record<string, XiaoyiAssetSpec> }
export function readXiaoyiDeliveryMetadata(changes?: string | null): XiaoyiDeliveryMetadata | null {
if (!changes) return null
try {
return JSON.parse(changes)?.deliveryMetadata?.newValue ?? null
} catch {
return null
}
}
export function xiaoyiSkuDimensions(assetType: string, fileUrl?: string | null) {
const sizes = assetType === 'sku' && fileUrl
? /(?:^|\/)xiaoyi-deliveries\/[^/]+\/[^/]+\/[^/]+\/sku\/([1-9]\d*)x([1-9]\d*)\//.exec(fileUrl.replace(/\\/g, '/').split(/[?#]/, 1)[0])
: null
if (sizes) {
const width = Number(sizes[1])
const height = Number(sizes[2])
if (Number.isSafeInteger(width) && Number.isSafeInteger(height)) {
let divisor = width
let remainder = height
while (remainder) [divisor, remainder] = [remainder, divisor % remainder]
return { width, height, resolution: `${width}x${height}`, aspectRatio: `${width / divisor}:${height / divisor}` }
}
}
return { width: null, height: null, resolution: null, aspectRatio: null }
}
export function isXiaoyiDeliveryMaterial(type: string): boolean {
return (XIAOYI_DELIVERY_TYPES as readonly string[]).includes(type)