fix(xiaoyi): resolve P0/P1 delivery revision, retry timezone, S3 download fallback, multi-res SKU bundle and CRLF copy
This commit is contained in:
parent
9359d836d9
commit
45b3cfdca9
90
app/api/external/download/route.ts
vendored
90
app/api/external/download/route.ts
vendored
@ -1,6 +1,7 @@
|
||||
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'
|
||||
import { getS3ObjectStream } from '@/lib/s3'
|
||||
/**
|
||||
* 外部接口:文件下载
|
||||
* GET - 通过 Token 下载文件
|
||||
@ -163,11 +164,26 @@ async function handleDownload(request: NextRequest) {
|
||||
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) => {
|
||||
const local = resolveAssetLocalPath(item.fileUrl)
|
||||
return !local || !fs.existsSync(local)
|
||||
})) return NextResponse.json({success:false,error:{code:'FILE_NOT_FOUND',message:'交付文件暂不可用'}},{status:503})
|
||||
return await downloadAsZip(assets, material.id, 'all')
|
||||
if (!assets.length) {
|
||||
return NextResponse.json({success:false,error:{code:'FILE_NOT_FOUND',message:'交付文件暂不可用'}},{status:503})
|
||||
}
|
||||
const prefetchedStreams = new Map<string, { body: Readable; contentLength?: number }>()
|
||||
for (const item of assets) {
|
||||
const normalizedUrl = normalizeAssetFileUrl(item.fileUrl)
|
||||
const local = resolveAssetLocalPath(normalizedUrl)
|
||||
if (local && fs.existsSync(local)) continue
|
||||
if (isHttpUrl(normalizedUrl)) continue
|
||||
const remote = await openRemoteFallbackStream(normalizedUrl)
|
||||
if (remote) {
|
||||
prefetchedStreams.set(item.id, remote)
|
||||
continue
|
||||
}
|
||||
for (const stream of Array.from(prefetchedStreams.values())) {
|
||||
stream.body.destroy()
|
||||
}
|
||||
return NextResponse.json({success:false,error:{code:'FILE_NOT_FOUND',message:'交付文件暂不可用'}},{status:503})
|
||||
}
|
||||
return await downloadAsZip(assets, material.id, 'all', prefetchedStreams)
|
||||
}
|
||||
if (downloadType !== 'single' || !assetId) {
|
||||
return NextResponse.json({success:false,error:{code:'INVALID_DOWNLOAD_TYPE',message:'请指定交付文件'}},{status:400})
|
||||
@ -444,9 +460,22 @@ async function downloadSingleFile(asset: any, rangeHeader: string | null = null)
|
||||
const fileName = resolveAssetFileName(asset, normalizedFileUrl);
|
||||
const localPath = resolveAssetLocalPath(asset?.fileUrl);
|
||||
|
||||
// 本地文件
|
||||
// 本地文件(缺失时自动兜底远程对象存储)
|
||||
if (localPath) {
|
||||
if (!fs.existsSync(localPath)) {
|
||||
const remote = await openRemoteFallbackStream(normalizedFileUrl);
|
||||
if (remote) {
|
||||
const contentType = getContentType(fileName);
|
||||
const stream = nodeReadableToWebStream(remote.body);
|
||||
return new NextResponse(stream as any, {
|
||||
status: 200,
|
||||
headers: {
|
||||
'Content-Type': contentType,
|
||||
'Content-Disposition': `attachment; filename="${encodeURIComponent(fileName)}"`,
|
||||
...(remote.contentLength != null ? { 'Content-Length': String(remote.contentLength) } : {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
return NextResponse.json(
|
||||
{ success: false, error: { code: 'FILE_NOT_FOUND', message: '文件不存在' } },
|
||||
{ status: 404 }
|
||||
@ -671,10 +700,43 @@ async function appendExternalAssetToArchive(
|
||||
archive.file(localPath, { name: entryName });
|
||||
}
|
||||
|
||||
async function openRemoteFallbackStream(
|
||||
fileUrl?: string | null,
|
||||
): Promise<{ body: Readable; contentLength?: number } | null> {
|
||||
if (!process.env.S3_BUCKET?.trim()) {
|
||||
return null;
|
||||
}
|
||||
const normalized = normalizeAssetFileUrl(fileUrl).replace(/^\/+/, '');
|
||||
if (!normalized || isHttpUrl(normalized) || path.isAbsolute(String(fileUrl || '')) || normalized.split('/').some((seg) => seg === '..')) {
|
||||
return null;
|
||||
}
|
||||
const s3Prefix = String(process.env.S3_FILE_PATH || '')
|
||||
.trim()
|
||||
.replace(/\\/g, '/')
|
||||
.replace(/^\/+|\/+$/g, '');
|
||||
const candidateKeys = s3Prefix ? [`${s3Prefix}/${normalized}`, normalized] : [normalized];
|
||||
for (const key of candidateKeys) {
|
||||
try {
|
||||
const result = await getS3ObjectStream(key);
|
||||
if (result?.body) {
|
||||
return result;
|
||||
}
|
||||
} catch {
|
||||
// Try next candidate key.
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 打包下载为 ZIP
|
||||
*/
|
||||
async function downloadAsZip(assets: any[], taskNo: string, downloadType: string) {
|
||||
async function downloadAsZip(
|
||||
assets: any[],
|
||||
taskNo: string,
|
||||
downloadType: string,
|
||||
prefetchedStreams?: Map<string, { body: Readable; contentLength?: number }>,
|
||||
) {
|
||||
console.log(`[downloadAsZip] ========== 开始打包下载 ==========`);
|
||||
console.log(`[downloadAsZip] taskNo: ${taskNo}, downloadType: ${downloadType}`);
|
||||
console.log(`[downloadAsZip] 待打包资产数量: ${assets.length}`);
|
||||
@ -713,8 +775,20 @@ async function downloadAsZip(assets: any[], taskNo: string, downloadType: string
|
||||
successCount++;
|
||||
continue;
|
||||
}
|
||||
const prefetched = asset?.id ? prefetchedStreams?.get(asset.id) : undefined;
|
||||
if (prefetched) {
|
||||
archive.append(archiveDownload.trackSource(prefetched.body), { name: entryName });
|
||||
successCount++;
|
||||
continue;
|
||||
}
|
||||
if (localPath) {
|
||||
console.error(`[downloadAsZip] ❌ 本地文件不存在: ${localPath}`);
|
||||
const remote = await openRemoteFallbackStream(fileUrl);
|
||||
if (remote) {
|
||||
archive.append(archiveDownload.trackSource(remote.body), { name: entryName });
|
||||
successCount++;
|
||||
continue;
|
||||
}
|
||||
console.error(`[downloadAsZip] ❌ 本地与远程文件均不存在: ${localPath}`);
|
||||
failCount++;
|
||||
continue;
|
||||
}
|
||||
|
||||
@ -154,8 +154,13 @@ export async function verifyDeliveryBundle(directory, expected = []) {
|
||||
const folder = path.posix.dirname(relativePath).slice('工程文件'.length);
|
||||
requireThat(['psd', 'psb'].some(ext => entries.get(`PSD${folder}/${name}.${ext}`)?.category === 'PSD'), `缺少分层文件 ${relativePath}`);
|
||||
for (const category of categories) {
|
||||
requireThat([...entries.values()].some(row => row.format === 'jpg' && row.category === category
|
||||
&& path.posix.dirname(row.relativePath) === category + folder), `缺少 ${category}${folder}`);
|
||||
const expectedDir = category + folder;
|
||||
requireThat([...entries.values()].some(row => {
|
||||
if (row.format !== 'jpg' || row.category !== category) return false;
|
||||
const dir = path.posix.dirname(row.relativePath);
|
||||
if (dir === expectedDir) return true;
|
||||
return category === 'SKU' && dir.startsWith(expectedDir + '/') && /^\d+x\d+$/.test(dir.slice(expectedDir.length + 1));
|
||||
}), `缺少 ${category}${folder}`);
|
||||
}
|
||||
}
|
||||
for (const entry of await readdir(root, { recursive: true, withFileTypes: true })) {
|
||||
|
||||
@ -954,7 +954,7 @@ export async function openProductionOperations(host,{target=host.productionConte
|
||||
async function registerCopy(result){
|
||||
const snapshot=await canvas.detailCopyFields({includeFilled:true});
|
||||
const after=new Map(snapshot.fields.map(field=>[field.layer,field]));
|
||||
const applied=items.filter(row=>(recordOnly||result.appliedLayers?.includes(row.layer))&&after.get(row.layer)?.currentText===row.text);
|
||||
const applied=items.filter(row=>(recordOnly||result.appliedLayers?.includes(row.layer))&&after.get(row.layer)?.currentText===String(row.text??'').replace(/\r\n?/g,'\n'));
|
||||
await update(journal=>{
|
||||
syncCopyEvidence(journal,inputPlan);
|
||||
journal.copyEvidence??={};
|
||||
|
||||
@ -2771,3 +2771,41 @@ test('plan_production compares copy fields with the selected canonical barcode e
|
||||
assert.deepEqual(plan.fieldConflicts.map(({ layer, productValue }) => [layer, productValue]),
|
||||
[[1, '125 cm'], [2, '暖白'], [3, '白蜡木'], [4, '指接板']]);
|
||||
});
|
||||
|
||||
test('write_copy_fields normalizes CRLF line endings when recording copyEvidence', async t => {
|
||||
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-pi-crlf-copy-'));
|
||||
t.after(() => cleanup(dir));
|
||||
const store = productionStore(dir);
|
||||
const currentTexts = new Map([[1, '原文本']]);
|
||||
const host = {
|
||||
store,
|
||||
productionGoal: { outputId: 'detail', variantId: 'white' },
|
||||
canvas: {
|
||||
workflowRead: async () => ({
|
||||
available: true, canvasFirst: true, outputId: 'detail', productVariantId: 'white',
|
||||
template: { contentHash: 'crlf-copy' }, totalSlots: 0, slots: [],
|
||||
}),
|
||||
detailCopyFields: async () => ({
|
||||
revision: 2,
|
||||
fields: [{ layer: 1, label: '卖点', currentText: currentTexts.get(1) }],
|
||||
}),
|
||||
commitDetailCopy: async (edits) => {
|
||||
for (const edit of edits) {
|
||||
currentTexts.set(edit.layer, String(edit.text).replace(/\r\n?/g, '\n'));
|
||||
}
|
||||
return { appliedLayers: edits.map(e => e.layer) };
|
||||
},
|
||||
delta: async () => {},
|
||||
imageRequest: async () => [],
|
||||
},
|
||||
};
|
||||
const actions = await openOperations(host);
|
||||
t.after(() => actions.close());
|
||||
const written = await actions.write_copy_fields({
|
||||
items: [{ layer: 1, text: '第一行\r\n第二行' }],
|
||||
});
|
||||
assert.deepEqual(written.appliedLayers, [1]);
|
||||
assert.equal(written.copyUpdates.total, 1);
|
||||
const journal = JSON.parse(await fs.readFile(path.join(dir, 'production-detail-white.json'), 'utf8'));
|
||||
assert.equal(journal.copyEvidence[1].text, '第一行\r\n第二行');
|
||||
});
|
||||
|
||||
@ -135,3 +135,40 @@ test('checks disk path lengths and duplicate large files using verified digests'
|
||||
assert.equal(tooLong.longestRelativePathLength, 121);
|
||||
assert.ok(tooLong.errors.some(error => error.message === '相对路径超过 120 字符'));
|
||||
});
|
||||
|
||||
test('allows multi-resolution SKU subdirectories under SKU output folder', async t => {
|
||||
const root = await fixture(t);
|
||||
const manifestPath = path.join(root, '交付清单.json');
|
||||
const manifest = JSON.parse(await fs.readFile(manifestPath, 'utf8'));
|
||||
const jpeg = Buffer.from('ffd8ffc0000b080001000101011100ffd9', 'hex');
|
||||
const sha256 = createHash('sha256').update(jpeg).digest('hex');
|
||||
const snapshot = manifest.deliveryId;
|
||||
const skuZipPath = path.join(root, '工程文件/主图.pcraft');
|
||||
const pcraftBytes = await fs.readFile(skuZipPath);
|
||||
await fs.writeFile(path.join(root, '工程文件/SKU.pcraft'), pcraftBytes);
|
||||
await fs.writeFile(path.join(root, 'PSD/SKU.psb'), await fs.readFile(path.join(root, 'PSD/主图.psb')));
|
||||
const pcraftHash = createHash('sha256').update(pcraftBytes).digest('hex');
|
||||
const psdBytes = await fs.readFile(path.join(root, 'PSD/SKU.psb'));
|
||||
const psdHash = createHash('sha256').update(psdBytes).digest('hex');
|
||||
manifest.files.push(
|
||||
{ relativePath: '工程文件/SKU.pcraft', category: '工程文件', format: 'pcraft', width: 1, height: 1, sizeBytes: pcraftBytes.length, sha256: pcraftHash, verified: true },
|
||||
{ relativePath: 'PSD/SKU.psb', category: 'PSD', format: 'psb', width: 1, height: 1, sizeBytes: psdBytes.length, sha256: psdHash, verified: true },
|
||||
);
|
||||
manifest.counts['工程文件'] += 1;
|
||||
manifest.counts['PSD'] += 1;
|
||||
manifest.completedOutputs = 2;
|
||||
manifest.totalOutputs = 2;
|
||||
for (const res of ['800x800', '1440x1440']) {
|
||||
const relativePath = `SKU/${res}/BARCODE01.jpg`;
|
||||
await fs.mkdir(path.join(root, `SKU/${res}`), { recursive: true });
|
||||
await fs.writeFile(path.join(root, relativePath), jpeg);
|
||||
manifest.files.push({
|
||||
relativePath, category: 'SKU', format: 'jpg', width: 1, height: 1,
|
||||
sizeBytes: jpeg.length, sha256, verified: true,
|
||||
});
|
||||
}
|
||||
manifest.counts['SKU'] = 2;
|
||||
await fs.writeFile(manifestPath, JSON.stringify({ ...manifest, deliveryId: snapshot }));
|
||||
const report = await verifyDeliveryBundle(root, ['main_images', 'sku_images']);
|
||||
assert.equal(report.ok, true, JSON.stringify(report.errors));
|
||||
});
|
||||
|
||||
@ -11,11 +11,11 @@ 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() }, materialLog: { create: jest.fn() },
|
||||
material: { create: jest.fn(), update: jest.fn() }, materialAsset: { deleteMany: 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')]) }))
|
||||
jest.mock('node:fs/promises', () => ({ mkdir: jest.fn(), lstat: jest.fn(), copyFile: jest.fn(), rename: jest.fn(), unlink: jest.fn() }))
|
||||
jest.mock('node:fs/promises', () => ({ mkdir: jest.fn(), lstat: jest.fn(), copyFile: jest.fn(), rename: jest.fn(), unlink: jest.fn(), rm: jest.fn() }))
|
||||
jest.mock('@/lib/material-facets-cache', () => ({ invalidateMaterialFacetsCache: jest.fn() }))
|
||||
jest.mock('@/lib/remote-upload-sync', () => ({ syncStoredUploadFileToRemote: jest.fn() }))
|
||||
jest.mock('@/lib/upload-sessions', () => ({ getOwnedUploadSession: jest.fn() }))
|
||||
@ -275,3 +275,113 @@ test('三种成品共用项目和 SPU,作者取自再次校验的会话,详
|
||||
expect(prisma.material.create).toHaveBeenCalledTimes(3)
|
||||
expect(mkdir).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
|
||||
test('完结后微调图片再次点击完结支持原位修订更新,且原素材已移除时允许重建', async () => {
|
||||
const { rm } = require('node:fs/promises')
|
||||
const detailFiles = [
|
||||
...input.assets.main,
|
||||
...input.assets.detail,
|
||||
...input.assets.sku,
|
||||
]
|
||||
mockSuccessfulUpload(detailFiles)
|
||||
jest.mocked(getOwnedUploadSession).mockImplementation(async uploadId => ({
|
||||
...detailFiles.find(item => item.uploadId === uploadId),
|
||||
uploadPurpose: 'xiaoyi:project-1:request-rev-2',
|
||||
} as any))
|
||||
jest.mocked(rm).mockResolvedValue(undefined)
|
||||
jest.mocked(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-existing', materialType: '自动上架-详情',
|
||||
fingerprint: 'old-fp', requestId: 'request-rev-1', state: 'completed',
|
||||
}]
|
||||
}
|
||||
return []
|
||||
})
|
||||
jest.mocked(prisma.$transaction as jest.Mock).mockImplementation(async callback => callback({
|
||||
$queryRawUnsafe: prisma.$queryRawUnsafe,
|
||||
$queryRaw: prisma.$queryRaw,
|
||||
$executeRawUnsafe: prisma.$executeRawUnsafe,
|
||||
material: prisma.material,
|
||||
materialAsset: prisma.materialAsset,
|
||||
materialLog: prisma.materialLog,
|
||||
}))
|
||||
jest.mocked(prisma.materialAsset.deleteMany).mockResolvedValue({ count: 3 } as any)
|
||||
jest.mocked(prisma.material.update).mockResolvedValue({ id: 'mat-existing' } as any)
|
||||
jest.mocked(prisma.materialLog.create).mockResolvedValue({} as any)
|
||||
|
||||
const revised = await createDesktopDelivery(account.id, { ...input, requestId: 'request-rev-2' }, authorize)
|
||||
expect(revised).toEqual({
|
||||
requestId: 'request-rev-2', materialId: 'mat-existing', materialType: '自动上架-详情', state: 'completed',
|
||||
})
|
||||
expect(prisma.materialAsset.deleteMany).toHaveBeenCalledWith({ where: { materialId: 'mat-existing' } })
|
||||
expect(prisma.material.update).toHaveBeenCalledWith(expect.objectContaining({ where: { id: 'mat-existing' } }))
|
||||
expect(prisma.material.create).not.toHaveBeenCalled()
|
||||
expect(queueXiaoyiAutoListingNotification).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
|
||||
materialId: 'mat-existing', replaceExisting: true,
|
||||
}))
|
||||
|
||||
// 原素材已软删时允许重建新 Material 并更新 delivery 指向
|
||||
jest.mocked(getOwnedUploadSession).mockImplementation(async uploadId => ({
|
||||
...detailFiles.find(item => item.uploadId === uploadId),
|
||||
uploadPurpose: 'xiaoyi:project-1:request-rev-3',
|
||||
} as any))
|
||||
jest.mocked(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-removed', materialType: '自动上架-详情',
|
||||
fingerprint: 'old-fp', requestId: 'request-rev-2', state: 'removed',
|
||||
}]
|
||||
}
|
||||
return []
|
||||
})
|
||||
jest.mocked(prisma.material.create).mockResolvedValue({ id: 'mat-recreated' } as any)
|
||||
const recreated = await createDesktopDelivery(account.id, { ...input, requestId: 'request-rev-3' }, authorize)
|
||||
expect(recreated).toEqual({
|
||||
requestId: 'request-rev-3', materialId: 'mat-recreated', materialType: '自动上架-详情', state: 'completed',
|
||||
})
|
||||
expect(prisma.material.create).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
test('同 requestId 但 fingerprint 不一致仍返回 409,且在跑任务预检与事务异常均不留孤儿文件', async () => {
|
||||
const { rm } = require('node:fs/promises')
|
||||
jest.mocked(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: 'different-fp', requestId: 'request-1', state: 'completed',
|
||||
}]
|
||||
}
|
||||
return []
|
||||
})
|
||||
await expect(createDesktopDelivery(account.id, input, authorize))
|
||||
.rejects.toMatchObject({ status: 409, code: 'delivery_conflict' })
|
||||
expect(mkdir).not.toHaveBeenCalled()
|
||||
|
||||
// 在跑任务预检在拷贝文件之前拦截
|
||||
jest.mocked(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_creation_tasks')) return [{ id: 'running-task-1' }]
|
||||
return []
|
||||
})
|
||||
await expect(createDesktopDelivery(account.id, input, authorize))
|
||||
.rejects.toMatchObject({ status: 409, code: 'task_busy' })
|
||||
expect(mkdir).not.toHaveBeenCalled()
|
||||
|
||||
// 事务失败时清理已写入的本地目录
|
||||
const detailFiles = [...input.assets.main, ...input.assets.detail, ...input.assets.sku]
|
||||
mockSuccessfulUpload(detailFiles)
|
||||
jest.mocked(getOwnedUploadSession).mockImplementation(async uploadId => ({
|
||||
...detailFiles.find(item => item.uploadId === uploadId),
|
||||
uploadPurpose: 'xiaoyi:project-1:request-1',
|
||||
} as any))
|
||||
jest.mocked(rm).mockResolvedValue(undefined)
|
||||
jest.mocked(prisma.$queryRawUnsafe as jest.Mock).mockImplementation(async (sql: string) =>
|
||||
sql.startsWith('SELECT id FROM desktop_workspace_projects') ? [{ id: 'project-1' }] : [])
|
||||
jest.mocked(prisma.$transaction as jest.Mock).mockRejectedValue(new Error('tx_boom'))
|
||||
await expect(createDesktopDelivery(account.id, input, authorize)).rejects.toThrow('tx_boom')
|
||||
expect(rm).toHaveBeenCalledWith(expect.stringContaining('request-1'), { recursive: true, force: true })
|
||||
})
|
||||
|
||||
@ -531,4 +531,43 @@ describe('external auto listing', () => {
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
test('重试退避时间应基于数据库 NOW() 计算间隔,避免 ::timestamp 时区偏差', async () => {
|
||||
;(prisma.$transaction as jest.Mock).mockImplementationOnce(async (callback) =>
|
||||
callback({
|
||||
$executeRawUnsafe: jest.fn().mockResolvedValue(1),
|
||||
$queryRawUnsafe: jest.fn().mockResolvedValue([
|
||||
{
|
||||
id: 'delivery-tz-1',
|
||||
status: 'retrying',
|
||||
payload: { eventId: 'evt-1' },
|
||||
attemptCount: 1,
|
||||
maxAttempts: 5,
|
||||
updatedAt: new Date('2026-03-25T10:00:00.000Z'),
|
||||
targetId: 'target-1',
|
||||
name: '自动上架平台',
|
||||
callbackUrl: 'https://auto.example.com/callback',
|
||||
isActive: true,
|
||||
authType: 'none',
|
||||
authConfig: {},
|
||||
eventTypes: [AUTO_LISTING_EVENT_TYPE],
|
||||
createdAt: new Date('2026-03-25T10:00:00.000Z'),
|
||||
targetUpdatedAt: new Date('2026-03-25T10:00:00.000Z'),
|
||||
},
|
||||
]),
|
||||
}),
|
||||
)
|
||||
jest.mocked(postAutoListingCallback).mockResolvedValueOnce(502)
|
||||
|
||||
const result = await processExternalNotificationDelivery('delivery-tz-1')
|
||||
expect(result).toEqual({
|
||||
success: false,
|
||||
status: AUTO_LISTING_DELIVERY_STATUS.RETRYING,
|
||||
})
|
||||
const updateCall = (prisma.$executeRawUnsafe as jest.Mock).mock.calls.at(-1)!
|
||||
expect(updateCall[0]).toContain("NOW() + ($6::bigint * INTERVAL '1 millisecond')")
|
||||
expect(updateCall[0]).not.toContain('::timestamp')
|
||||
expect(updateCall[6]).toBe(5 * 60 * 1000)
|
||||
expect(updateCall[7]).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@ -4,11 +4,17 @@ import { NextRequest } from 'next/server'
|
||||
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { Readable } from 'node:stream'
|
||||
import AdmZip from 'adm-zip'
|
||||
|
||||
import { GET } from '@/app/api/external/download/route'
|
||||
import { isTokenExpired, verifyDownloadToken } from '@/lib/download-token'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { getS3ObjectStream } from '@/lib/s3'
|
||||
|
||||
jest.mock('@/lib/s3', () => ({
|
||||
getS3ObjectStream: jest.fn(),
|
||||
}))
|
||||
|
||||
jest.mock('@/lib/download-token', () => ({
|
||||
isTokenExpired: jest.fn(),
|
||||
@ -379,4 +385,108 @@ describe('external single-file S3 download range forwarding', () => {
|
||||
expect(new Headers(requestInit?.headers).get('range')).toBe('bytes=0-1023')
|
||||
})
|
||||
})
|
||||
|
||||
describe('xiaoyi delivery remote S3 fallback', () => {
|
||||
const prevBucket = process.env.S3_BUCKET
|
||||
const prevPrefix = process.env.S3_FILE_PATH
|
||||
|
||||
beforeEach(() => {
|
||||
process.env.S3_BUCKET = 'gongxiangpan'
|
||||
process.env.S3_FILE_PATH = 'xiaoyi/'
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
if (prevBucket === undefined) delete process.env.S3_BUCKET
|
||||
else process.env.S3_BUCKET = prevBucket
|
||||
if (prevPrefix === undefined) delete process.env.S3_FILE_PATH
|
||||
else process.env.S3_FILE_PATH = prevPrefix
|
||||
})
|
||||
|
||||
test('falls back to S3 stream for Xiaoyi ZIP when local upload file is missing', async () => {
|
||||
;(verifyDownloadToken as jest.Mock).mockReturnValue({
|
||||
materialId: 'material-1',
|
||||
downloadType: 'all',
|
||||
})
|
||||
;(prisma.material.findUnique as jest.Mock).mockResolvedValue({
|
||||
id: 'material-1',
|
||||
materialType: '自动上架-详情',
|
||||
createdAt: new Date('2026-12-01T00:00:00.000Z'),
|
||||
assets: [
|
||||
{
|
||||
id: 'asset-main',
|
||||
assetType: 'main',
|
||||
fileUrl: 'uploads/xiaoyi-deliveries/owner/proj/req/0000-main.jpg',
|
||||
fileName: '0000-main.jpg',
|
||||
sortOrder: 0,
|
||||
},
|
||||
],
|
||||
})
|
||||
;(getS3ObjectStream as jest.Mock).mockResolvedValueOnce({
|
||||
body: Readable.from([Buffer.from('remote-main-bytes')]),
|
||||
contentLength: 17,
|
||||
})
|
||||
|
||||
const response = await GET(makeRequest())
|
||||
expect(response.status).toBe(200)
|
||||
expect(getS3ObjectStream).toHaveBeenCalledWith('xiaoyi/uploads/xiaoyi-deliveries/owner/proj/req/0000-main.jpg')
|
||||
const zip = new AdmZip(Buffer.from(await response.arrayBuffer()))
|
||||
expect(zip.readAsText('main/0000-main.jpg')).toBe('remote-main-bytes')
|
||||
})
|
||||
|
||||
test('falls back to S3 stream for Xiaoyi single file when local upload file is missing', async () => {
|
||||
;(verifyDownloadToken as jest.Mock).mockReturnValue({
|
||||
materialId: 'material-1',
|
||||
downloadType: 'single',
|
||||
assetId: 'asset-main',
|
||||
})
|
||||
;(prisma.material.findUnique as jest.Mock).mockResolvedValue({
|
||||
id: 'material-1',
|
||||
materialType: '自动上架-详情',
|
||||
createdAt: new Date('2026-12-01T00:00:00.000Z'),
|
||||
assets: [
|
||||
{
|
||||
id: 'asset-main',
|
||||
assetType: 'main',
|
||||
fileUrl: 'uploads/xiaoyi-deliveries/owner/proj/req/0000-main.jpg',
|
||||
fileName: '0000-main.jpg',
|
||||
sortOrder: 0,
|
||||
},
|
||||
],
|
||||
})
|
||||
;(getS3ObjectStream as jest.Mock).mockResolvedValueOnce({
|
||||
body: Readable.from([Buffer.from('remote-single-bytes')]),
|
||||
contentLength: 19,
|
||||
})
|
||||
|
||||
const response = await GET(makeRequest())
|
||||
expect(response.status).toBe(200)
|
||||
expect(response.headers.get('Content-Length')).toBe('19')
|
||||
expect(Buffer.from(await response.arrayBuffer()).toString()).toBe('remote-single-bytes')
|
||||
})
|
||||
|
||||
test('returns 503 when both local and S3 objects are missing for Xiaoyi ZIP', async () => {
|
||||
;(verifyDownloadToken as jest.Mock).mockReturnValue({
|
||||
materialId: 'material-1',
|
||||
downloadType: 'all',
|
||||
})
|
||||
;(prisma.material.findUnique as jest.Mock).mockResolvedValue({
|
||||
id: 'material-1',
|
||||
materialType: '自动上架-详情',
|
||||
createdAt: new Date('2026-12-01T00:00:00.000Z'),
|
||||
assets: [
|
||||
{
|
||||
id: 'asset-main',
|
||||
assetType: 'main',
|
||||
fileUrl: 'uploads/xiaoyi-deliveries/owner/proj/req/missing.jpg',
|
||||
fileName: 'missing.jpg',
|
||||
sortOrder: 0,
|
||||
},
|
||||
],
|
||||
})
|
||||
;(getS3ObjectStream as jest.Mock).mockRejectedValue(new Error('NoSuchKey'))
|
||||
|
||||
const response = await GET(makeRequest())
|
||||
expect(response.status).toBe(503)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@ -73,4 +73,22 @@ describe('小壹自动上架通知', () => {
|
||||
expect(fetch).not.toHaveBeenCalled()
|
||||
fetch.mockRestore()
|
||||
})
|
||||
|
||||
test('原位修订通知可更新事件并按新 eventId 去重投递,不被旧事件吞掉', async () => {
|
||||
const execute = jest.fn().mockResolvedValue(1)
|
||||
await queueXiaoyiAutoListingNotification({ $executeRawUnsafe: execute }, { ...event, replaceExisting: true })
|
||||
const [sql] = execute.mock.calls[0]
|
||||
expect(sql).toContain('ON CONFLICT (material_id) DO UPDATE')
|
||||
|
||||
;(prisma.$queryRawUnsafe as jest.Mock)
|
||||
.mockResolvedValueOnce([{
|
||||
eventId: 'event-rev-2', targetId: 'target-1', ...event, createdAt: new Date('2026-12-01T12:00:00Z'),
|
||||
}])
|
||||
.mockResolvedValueOnce([{ id: 'delivery-rev-2' }])
|
||||
await queueXiaoyiDeliveries()
|
||||
const [selectSql] = (prisma.$queryRawUnsafe as jest.Mock).mock.calls[0]
|
||||
expect(selectSql).toContain('d.dedupe_key=e.id OR (d.dedupe_key=e.material_id AND d.created_at>=e.created_at)')
|
||||
const insertCall = (prisma.$queryRawUnsafe as jest.Mock).mock.calls[1]
|
||||
expect(insertCall.at(-1)).toBe('event-rev-2')
|
||||
})
|
||||
})
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
|
||||
import { createHash, randomUUID } from 'node:crypto'
|
||||
import { createReadStream } from 'node:fs'
|
||||
import { copyFile, lstat, mkdir, rename, unlink } from 'node:fs/promises'
|
||||
import { copyFile, lstat, mkdir, rename, rm, unlink } from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
import type { Prisma } from '@prisma/client'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
@ -197,12 +197,17 @@ export async function createDesktopDelivery(ownerId: string, input: Input, reaut
|
||||
WHERE d.owner_id=$1 AND d.project_id=$2 AND d.kind=$3`,
|
||||
ownerId, request.projectId, request.kind,
|
||||
)
|
||||
if (previous[0]) {
|
||||
desktopAssert(previous[0].requestId === request.requestId && [request.fingerprint, request.legacyFingerprint].includes(previous[0].fingerprint), '已有不同的交付记录,请保留原素材并联系管理员', 409, 'delivery_conflict')
|
||||
if (previous[0]?.requestId === request.requestId) {
|
||||
desktopAssert([request.fingerprint, request.legacyFingerprint].includes(previous[0].fingerprint), '已有不同的交付记录,请保留原素材并联系管理员', 409, 'delivery_conflict')
|
||||
return {requestId:previous[0].requestId,materialId:previous[0].materialId,materialType:previous[0].materialType,state:previous[0].state}
|
||||
}
|
||||
desktopAssert(request.kind !== 'detail' || request.brandName, '请填写商品品牌后再完结提交', 400, 'brand_required')
|
||||
await projectDeliveryIdentifier(prisma, ownerId, request.projectId, request.identifier)
|
||||
const runningPrecheck = await prisma.$queryRawUnsafe<{id:string}[]>(
|
||||
"SELECT id FROM desktop_creation_tasks WHERE owner_id=$1 AND project_id=$2 AND (status IN ('queued','running','received','unknown') OR lease_until>NOW()) LIMIT 1",
|
||||
ownerId, request.projectId,
|
||||
)
|
||||
desktopAssert(!runningPrecheck.length, '项目仍有未完成的制作任务', 409, 'task_busy')
|
||||
|
||||
const barcodeFiles = request.files.filter(file => file.barcodes.length)
|
||||
const barcodes = new Set(barcodeFiles.flatMap(file => file.barcodes))
|
||||
@ -290,8 +295,8 @@ export async function createDesktopDelivery(ownerId: string, input: Input, reaut
|
||||
WHERE d.owner_id=$1 AND d.project_id=$2 AND d.kind=$3`,
|
||||
ownerId, request.projectId, request.kind,
|
||||
)
|
||||
if (found[0]) {
|
||||
desktopAssert(found[0].requestId === request.requestId && [request.fingerprint, request.legacyFingerprint].includes(found[0].fingerprint), '已有不同的交付记录,请保留原素材并联系管理员', 409, 'delivery_conflict')
|
||||
if (found[0]?.requestId === request.requestId) {
|
||||
desktopAssert([request.fingerprint, request.legacyFingerprint].includes(found[0].fingerprint), '已有不同的交付记录,请保留原素材并联系管理员', 409, 'delivery_conflict')
|
||||
return {requestId:found[0].requestId,materialId:found[0].materialId,materialType:found[0].materialType,state:found[0].state}
|
||||
}
|
||||
const identifier = await projectDeliveryIdentifier(tx, ownerId, request.projectId, request.identifier)
|
||||
@ -311,16 +316,51 @@ export async function createDesktopDelivery(ownerId: string, input: Input, reaut
|
||||
...(codes.length && { barcodes: { create: codes.map(barcode => ({ barcode })) } }),
|
||||
}
|
||||
})
|
||||
if (found[0] && found[0].state !== 'removed') {
|
||||
await tx.materialAsset.deleteMany({ where: { materialId: found[0].materialId } })
|
||||
await tx.material.update({
|
||||
where: { id: found[0].materialId },
|
||||
data: {
|
||||
authorName: author.name, productModel: identifier,
|
||||
categoryName: request.categoryName, productCategoryName: request.productCategoryName,
|
||||
materialType, taskStatus: 'completed', isFullSet: request.kind === 'detail', isAiGenerated: true,
|
||||
assets: { create: assets },
|
||||
},
|
||||
})
|
||||
await tx.$executeRawUnsafe(
|
||||
`UPDATE desktop_material_deliveries
|
||||
SET request_id=$1,fingerprint=$2,material_type=$3,brand_name=$4,product_name=$5,identifier_type=$6,listing_status=NULL
|
||||
WHERE owner_id=$7 AND project_id=$8 AND kind=$9`,
|
||||
request.requestId,request.fingerprint,materialType,request.brandName,request.productName,'spu',
|
||||
ownerId,request.projectId,request.kind,
|
||||
)
|
||||
await tx.materialLog.create({ data: {
|
||||
materialId: found[0].materialId, userId: ownerId, action: XIAOYI_DELIVERY_LOG_ACTION,
|
||||
changes: JSON.stringify({ deliveryMetadata: { oldValue: null, newValue: deliveryMetadata } }),
|
||||
} })
|
||||
await queueXiaoyiAutoListingNotification(tx,{materialId:found[0].materialId,materialType,outcomeKind:request.kind,projectId:request.projectId,replaceExisting:true})
|
||||
return {requestId:request.requestId,materialId:found[0].materialId,materialType,state:'completed' as const}
|
||||
}
|
||||
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: 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 (found[0]) {
|
||||
await tx.$executeRawUnsafe(
|
||||
`UPDATE desktop_material_deliveries
|
||||
SET request_id=$1,fingerprint=$2,material_id=$3,material_type=$4,brand_name=$5,product_name=$6,identifier_type=$7,listing_status=NULL
|
||||
WHERE owner_id=$8 AND project_id=$9 AND kind=$10`,
|
||||
request.requestId,request.fingerprint,material.id,materialType,request.brandName,request.productName,'spu',
|
||||
ownerId,request.projectId,request.kind,
|
||||
)
|
||||
} else {
|
||||
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,
|
||||
@ -329,7 +369,10 @@ export async function createDesktopDelivery(ownerId: string, input: Input, reaut
|
||||
}
|
||||
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})
|
||||
},{timeout:30000}).catch(async error => {
|
||||
await rm?.(folder, { recursive: true, force: true })?.catch(() => undefined)
|
||||
throw error
|
||||
})
|
||||
invalidateMaterialFacetsCache()
|
||||
wakeXiaoyiAutoListingNotifications()
|
||||
return result
|
||||
|
||||
@ -620,6 +620,7 @@ export interface XiaoyiAutoListingEvent {
|
||||
materialType: string
|
||||
outcomeKind: XiaoyiOutcomeKind
|
||||
projectId: string
|
||||
replaceExisting?: boolean
|
||||
}
|
||||
|
||||
/** Called inside the same transaction that creates the material and its files. */
|
||||
@ -630,9 +631,17 @@ export async function queueXiaoyiAutoListingNotification(
|
||||
if (!event.materialId || !event.projectId || XIAOYI_DELIVERY_MATERIAL_TYPES[event.outcomeKind] !== event.materialType) {
|
||||
throw new Error('小壹交付通知参数无效')
|
||||
}
|
||||
const conflictClause = event.replaceExisting
|
||||
? `ON CONFLICT (material_id) DO UPDATE SET
|
||||
id = EXCLUDED.id,
|
||||
material_type = EXCLUDED.material_type,
|
||||
outcome_kind = EXCLUDED.outcome_kind,
|
||||
project_id = EXCLUDED.project_id,
|
||||
created_at = CURRENT_TIMESTAMP`
|
||||
: 'ON CONFLICT (material_id) DO NOTHING'
|
||||
await tx.$executeRawUnsafe(
|
||||
`INSERT INTO "${XIAOYI_EVENT_TABLE}" (id, material_id, material_type, outcome_kind, project_id)
|
||||
VALUES ($1, $2, $3, $4, $5) ON CONFLICT (material_id) DO NOTHING`,
|
||||
VALUES ($1, $2, $3, $4, $5) ${conflictClause}`,
|
||||
randomUUID(), event.materialId, event.materialType, event.outcomeKind, event.projectId,
|
||||
)
|
||||
}
|
||||
@ -656,7 +665,8 @@ export async function queueXiaoyiDeliveries(limit = 20) {
|
||||
JOIN "${TARGET_TABLE}" t ON t.is_active = TRUE AND t.event_types ? $1
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM "${DELIVERY_TABLE}" d
|
||||
WHERE d.target_id=t.id AND d.event_type=$1 AND d.dedupe_key=e.material_id
|
||||
WHERE d.target_id=t.id AND d.event_type=$1
|
||||
AND (d.dedupe_key=e.id OR (d.dedupe_key=e.material_id AND d.created_at>=e.created_at))
|
||||
)
|
||||
ORDER BY e.created_at,t.created_at
|
||||
LIMIT $2
|
||||
@ -679,10 +689,10 @@ export async function queueXiaoyiDeliveries(limit = 20) {
|
||||
INSERT INTO "${DELIVERY_TABLE}" (
|
||||
id,target_id,event_type,material_id,material_type,dedupe_key,status,payload,
|
||||
attempt_count,max_attempts,next_retry_at,created_at,updated_at
|
||||
) VALUES ($1,$2,$3,$4,$5,$4,$6,$7::jsonb,0,$8,NOW(),NOW(),NOW())
|
||||
) VALUES ($1,$2,$3,$4,$5,$9,$6,$7::jsonb,0,$8,NOW(),NOW(),NOW())
|
||||
ON CONFLICT ("target_id","event_type","dedupe_key") DO NOTHING RETURNING id
|
||||
`, deliveryId, event.targetId, XIAOYI_AUTO_LISTING_EVENT_TYPE, event.materialId,
|
||||
event.materialType, AUTO_LISTING_DELIVERY_STATUS.PENDING, JSON.stringify(payload), DELIVERY_MAX_ATTEMPTS)
|
||||
event.materialType, AUTO_LISTING_DELIVERY_STATUS.PENDING, JSON.stringify(payload), DELIVERY_MAX_ATTEMPTS, event.eventId)
|
||||
if (inserted[0]) scheduleDeliveryProcessing(String(inserted[0].id), 0)
|
||||
}
|
||||
}
|
||||
@ -1300,7 +1310,6 @@ export async function processExternalNotificationDelivery(
|
||||
const nextAttempt = claimed.attemptCount + 1
|
||||
const isExhausted = nextAttempt >= claimed.maxAttempts
|
||||
const retryDelayMs = RETRY_DELAYS_MS[Math.min(nextAttempt, RETRY_DELAYS_MS.length - 1)]
|
||||
const nextRetryAt = new Date(Date.now() + retryDelayMs).toISOString()
|
||||
|
||||
await executeRaw(
|
||||
`
|
||||
@ -1311,8 +1320,8 @@ export async function processExternalNotificationDelivery(
|
||||
last_status_code = $3,
|
||||
last_response_body = $4,
|
||||
last_error = $5,
|
||||
next_retry_at = $6::timestamp,
|
||||
completed_at = $7::timestamp,
|
||||
next_retry_at = CASE WHEN $6::bigint IS NULL THEN NULL ELSE NOW() + ($6::bigint * INTERVAL '1 millisecond') END,
|
||||
completed_at = CASE WHEN $7::boolean THEN NOW() ELSE NULL END,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
@ -1321,8 +1330,8 @@ export async function processExternalNotificationDelivery(
|
||||
responseStatus,
|
||||
null,
|
||||
requestError,
|
||||
isExhausted ? null : nextRetryAt,
|
||||
isExhausted ? new Date().toISOString() : null,
|
||||
isExhausted ? null : retryDelayMs,
|
||||
isExhausted,
|
||||
)
|
||||
|
||||
if (!isExhausted) {
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user