- 新增任务-详情全套入库后的自动上架通知与重试补发能力 - 扩展 product-assets 支持按 materialId 拉取正式资源 - 补充后台通知目标管理、投递记录和对接文档
426 lines
13 KiB
TypeScript
426 lines
13 KiB
TypeScript
import { prisma } from '@/lib/prisma'
|
|
import { assignTaskNoOnComplete, validateTaskNo } from '@/lib/product-package'
|
|
import {
|
|
cleanupOnError,
|
|
cleanupTempFiles,
|
|
createZipFromFiles,
|
|
createZipFromZips,
|
|
saveProductPackageAssets,
|
|
} from '@/lib/task-material-processor'
|
|
import { getUploadedFile } from '@/lib/upload-sessions'
|
|
import { createMaterialLog } from '@/lib/material-log'
|
|
import { isTaskDetailFullSetFromUploadGroups } from '@/lib/task-detail-full-set'
|
|
import {
|
|
buildTaskDetailPublicDisplayPath,
|
|
uploadPublicDisplayToS3,
|
|
} from '@/lib/public-display'
|
|
import { queueTaskDetailFullSetNotification } from '@/lib/external-auto-listing'
|
|
import path from 'path'
|
|
import { mkdir, readFile, writeFile } from 'fs/promises'
|
|
|
|
export interface ProductPackageImageInput {
|
|
uploadId?: string
|
|
fileUrl?: string
|
|
fileName: string
|
|
fileSize: number
|
|
sortOrder?: number
|
|
}
|
|
|
|
export interface ProductPackageSourceInput {
|
|
uploadId?: string
|
|
fileUrl?: string
|
|
fileName: string
|
|
fileSize: number
|
|
}
|
|
|
|
export interface CompleteProductPackageUploadInput {
|
|
materialId: string
|
|
taskNo?: string | null
|
|
operatorUserId: string
|
|
assets: {
|
|
main?: ProductPackageImageInput[]
|
|
sku?: ProductPackageImageInput[]
|
|
detail?: ProductPackageImageInput[]
|
|
psd?: ProductPackageSourceInput[]
|
|
}
|
|
}
|
|
|
|
async function downloadToTempFile(prefix: string, asset: ProductPackageImageInput | ProductPackageSourceInput) {
|
|
if (!asset.fileUrl) {
|
|
throw new Error(`缺少文件地址: ${asset.fileName}`)
|
|
}
|
|
|
|
const tempPath = path.join(
|
|
process.cwd(),
|
|
'uploads',
|
|
'temp',
|
|
`${prefix}-${Date.now()}-${Math.random().toString(36).substring(2, 9)}-${asset.fileName}`,
|
|
)
|
|
|
|
await mkdir(path.dirname(tempPath), { recursive: true })
|
|
|
|
const response = await fetch(asset.fileUrl)
|
|
if (!response.ok) {
|
|
throw new Error(`下载文件失败: ${asset.fileName}`)
|
|
}
|
|
|
|
const buffer = Buffer.from(await response.arrayBuffer())
|
|
await writeFile(tempPath, buffer)
|
|
return tempPath
|
|
}
|
|
|
|
async function collectAssetFiles(
|
|
assets: ProductPackageImageInput[] | undefined,
|
|
prefix: string,
|
|
tempFiles: string[],
|
|
uploadIds: string[],
|
|
) {
|
|
const files: Array<{ path: string; name: string; size: number }> = []
|
|
|
|
if (!assets || assets.length === 0) {
|
|
return files
|
|
}
|
|
|
|
for (const asset of assets) {
|
|
if (asset.uploadId) {
|
|
const filePath = await getUploadedFile(asset.uploadId)
|
|
if (!filePath) {
|
|
throw new Error(`文件缺失或未上传完成: ${asset.fileName} (${asset.uploadId})`)
|
|
}
|
|
files.push({
|
|
path: filePath,
|
|
name: asset.fileName,
|
|
size: asset.fileSize,
|
|
})
|
|
tempFiles.push(filePath)
|
|
uploadIds.push(asset.uploadId)
|
|
continue
|
|
}
|
|
|
|
if (!asset.fileUrl) {
|
|
throw new Error(`资产参数无效: ${asset.fileName}`)
|
|
}
|
|
|
|
const filePath = await downloadToTempFile(prefix, asset)
|
|
files.push({
|
|
path: filePath,
|
|
name: asset.fileName,
|
|
size: asset.fileSize,
|
|
})
|
|
tempFiles.push(filePath)
|
|
}
|
|
|
|
return files
|
|
}
|
|
|
|
async function generatePreviewsFromAssets(
|
|
materialId: string,
|
|
assets: ProductPackageImageInput[] | undefined,
|
|
type: 'main' | 'sku' | 'detail',
|
|
uploadedPreviewUrls: string[],
|
|
) {
|
|
if (!assets || assets.length === 0) {
|
|
return []
|
|
}
|
|
|
|
const previews: string[] = []
|
|
const { compressImage, sliceImage } = await import('@/lib/image-processor')
|
|
const sharp = await import('sharp')
|
|
|
|
for (let index = 0; index < assets.length; index += 1) {
|
|
const asset = assets[index]
|
|
let buffer: Buffer
|
|
|
|
if (asset.fileUrl) {
|
|
const response = await fetch(asset.fileUrl)
|
|
if (!response.ok) {
|
|
throw new Error(`下载${type}预览原图失败: ${asset.fileName}`)
|
|
}
|
|
buffer = Buffer.from(await response.arrayBuffer())
|
|
} else if (asset.uploadId) {
|
|
const filePath = await getUploadedFile(asset.uploadId)
|
|
if (!filePath) {
|
|
throw new Error(`文件不存在: ${asset.fileName} (${asset.uploadId})`)
|
|
}
|
|
buffer = await readFile(filePath)
|
|
} else {
|
|
throw new Error(`无效的${type}资产: ${asset.fileName}`)
|
|
}
|
|
|
|
const metadata = await sharp.default(buffer).metadata()
|
|
const shouldSlice = type === 'detail' && metadata.height && metadata.height > 1500
|
|
const buffers = shouldSlice
|
|
? await sliceImage(buffer, 1500, 200)
|
|
: [
|
|
await compressImage(buffer, {
|
|
maxWidth: 800,
|
|
maxHeight: 1200,
|
|
maxSizeKB: 200,
|
|
format: 'webp',
|
|
}),
|
|
]
|
|
|
|
for (let sliceIndex = 0; sliceIndex < buffers.length; sliceIndex += 1) {
|
|
const timestamp = Date.now()
|
|
const randomSuffix = Math.random().toString(36).substring(2, 9)
|
|
const sliceSuffix = buffers.length > 1 ? `-slice${sliceIndex}` : ''
|
|
const fileName = `${type}-preview-${timestamp}-${index}${sliceSuffix}-${randomSuffix}.webp`
|
|
const previewUrl = await uploadPublicDisplayToS3(
|
|
buffers[sliceIndex],
|
|
buildTaskDetailPublicDisplayPath(materialId, type, fileName),
|
|
'image/webp',
|
|
)
|
|
previews.push(previewUrl)
|
|
uploadedPreviewUrls.push(previewUrl)
|
|
}
|
|
}
|
|
|
|
return previews
|
|
}
|
|
|
|
async function movePsdFilesToPermanentDir(
|
|
materialId: string,
|
|
assets: ProductPackageSourceInput[] | undefined,
|
|
tempFiles: string[],
|
|
) {
|
|
const psdPermanentPaths: Array<{ filePath: string; fileName: string; fileSize: number }> = []
|
|
|
|
if (!assets || assets.length === 0) {
|
|
return psdPermanentPaths
|
|
}
|
|
|
|
const { rename, copyFile } = await import('fs/promises')
|
|
const psdDir = path.join(process.cwd(), 'uploads', 'materials')
|
|
await mkdir(psdDir, { recursive: true })
|
|
|
|
for (const psd of assets) {
|
|
if (!psd.uploadId) {
|
|
if (!psd.fileUrl) {
|
|
throw new Error(`PSD 资产参数无效: ${psd.fileName}`)
|
|
}
|
|
|
|
const tempFilePath = await downloadToTempFile('psd', psd)
|
|
const timestamp = Date.now()
|
|
const sanitizedFileName = psd.fileName.replace(/[\/\\:*?"<>|]/g, '_')
|
|
const permanentFileName = `psd-${materialId}-${timestamp}-${sanitizedFileName}`
|
|
const permanentFilePath = path.join(psdDir, permanentFileName)
|
|
await copyFile(tempFilePath, permanentFilePath)
|
|
tempFiles.push(tempFilePath)
|
|
psdPermanentPaths.push({
|
|
filePath: path.join('uploads', 'materials', permanentFileName),
|
|
fileName: psd.fileName,
|
|
fileSize: psd.fileSize,
|
|
})
|
|
continue
|
|
}
|
|
|
|
const tempFilePath = await getUploadedFile(psd.uploadId)
|
|
if (!tempFilePath) {
|
|
throw new Error(`PSD 文件缺失或未上传完成: ${psd.fileName} (${psd.uploadId})`)
|
|
}
|
|
|
|
const timestamp = Date.now()
|
|
const sanitizedFileName = psd.fileName.replace(/[\/\\:*?"<>|]/g, '_')
|
|
const permanentFileName = `psd-${materialId}-${timestamp}-${sanitizedFileName}`
|
|
const permanentFilePath = path.join(psdDir, permanentFileName)
|
|
const relativePath = path.join('uploads', 'materials', permanentFileName)
|
|
|
|
try {
|
|
await rename(tempFilePath, permanentFilePath)
|
|
} catch {
|
|
await copyFile(tempFilePath, permanentFilePath)
|
|
tempFiles.push(tempFilePath)
|
|
}
|
|
|
|
psdPermanentPaths.push({
|
|
filePath: relativePath,
|
|
fileName: psd.fileName,
|
|
fileSize: psd.fileSize,
|
|
})
|
|
}
|
|
|
|
return psdPermanentPaths
|
|
}
|
|
|
|
export async function completeProductPackageUpload(input: CompleteProductPackageUploadInput) {
|
|
const { materialId, taskNo, assets, operatorUserId } = input
|
|
const tempFiles: string[] = []
|
|
const uploadIds: string[] = []
|
|
const uploadedPreviewUrls: string[] = []
|
|
const createdZipPaths: string[] = []
|
|
const derivedIsFullSet = isTaskDetailFullSetFromUploadGroups(assets)
|
|
|
|
if (!materialId || !assets) {
|
|
throw new Error('缺少必填参数')
|
|
}
|
|
|
|
const totalImages = (assets.main?.length || 0) + (assets.sku?.length || 0) + (assets.detail?.length || 0)
|
|
if (totalImages === 0) {
|
|
throw new Error('请至少上传一张图片')
|
|
}
|
|
|
|
const normalizedTaskNo = taskNo?.trim() || null
|
|
if (normalizedTaskNo && !validateTaskNo(normalizedTaskNo)) {
|
|
throw new Error('任务号格式错误')
|
|
}
|
|
|
|
try {
|
|
const material: any = await prisma.material.findUnique({
|
|
where: { id: materialId },
|
|
include: {
|
|
user: {
|
|
select: {
|
|
realName: true,
|
|
username: true,
|
|
},
|
|
},
|
|
},
|
|
})
|
|
|
|
if (!material) {
|
|
throw new Error('素材不存在')
|
|
}
|
|
|
|
const authorName = material.user?.realName || material.user?.username || '未知作者'
|
|
const categoryName = material.categoryName || '未知店铺'
|
|
|
|
const mainFiles = await collectAssetFiles(assets.main, 'main', tempFiles, uploadIds)
|
|
const skuFiles = await collectAssetFiles(assets.sku, 'sku', tempFiles, uploadIds)
|
|
const detailFiles = await collectAssetFiles(assets.detail, 'detail', tempFiles, uploadIds)
|
|
|
|
const previewUrls = {
|
|
main: await generatePreviewsFromAssets(materialId, assets.main, 'main', uploadedPreviewUrls),
|
|
sku: await generatePreviewsFromAssets(materialId, assets.sku, 'sku', uploadedPreviewUrls),
|
|
detail: await generatePreviewsFromAssets(materialId, assets.detail, 'detail', uploadedPreviewUrls),
|
|
}
|
|
|
|
const zipInfos: {
|
|
main?: { filePath: string; fileName: string; fileSize: number }
|
|
sku?: { filePath: string; fileName: string; fileSize: number }
|
|
detail?: { filePath: string; fileName: string; fileSize: number }
|
|
all: { filePath: string; fileName: string; fileSize: number }
|
|
} = {} as any
|
|
|
|
const zipFilesForAll: Array<{ path: string; name: string }> = []
|
|
|
|
if (mainFiles.length > 0) {
|
|
zipInfos.main = await createZipFromFiles(
|
|
mainFiles,
|
|
materialId,
|
|
material.productModel || 'product',
|
|
'任务-详情',
|
|
'主图',
|
|
authorName,
|
|
categoryName,
|
|
)
|
|
createdZipPaths.push(zipInfos.main.filePath)
|
|
zipFilesForAll.push({ path: zipInfos.main.filePath, name: zipInfos.main.fileName })
|
|
}
|
|
|
|
if (skuFiles.length > 0) {
|
|
zipInfos.sku = await createZipFromFiles(
|
|
skuFiles,
|
|
materialId,
|
|
material.productModel || 'product',
|
|
'任务-详情',
|
|
'SKU图',
|
|
authorName,
|
|
categoryName,
|
|
)
|
|
createdZipPaths.push(zipInfos.sku.filePath)
|
|
zipFilesForAll.push({ path: zipInfos.sku.filePath, name: zipInfos.sku.fileName })
|
|
}
|
|
|
|
if (detailFiles.length > 0) {
|
|
zipInfos.detail = await createZipFromFiles(
|
|
detailFiles,
|
|
materialId,
|
|
material.productModel || 'product',
|
|
'任务-详情',
|
|
'详情图',
|
|
authorName,
|
|
categoryName,
|
|
)
|
|
createdZipPaths.push(zipInfos.detail.filePath)
|
|
zipFilesForAll.push({ path: zipInfos.detail.filePath, name: zipInfos.detail.fileName })
|
|
}
|
|
|
|
zipInfos.all = await createZipFromZips(
|
|
zipFilesForAll,
|
|
materialId,
|
|
material.productModel || 'product',
|
|
'任务-详情',
|
|
)
|
|
createdZipPaths.push(zipInfos.all.filePath)
|
|
|
|
const psdPermanentPaths = await movePsdFilesToPermanentDir(materialId, assets.psd, tempFiles)
|
|
|
|
await saveProductPackageAssets(materialId, previewUrls, zipInfos, psdPermanentPaths)
|
|
|
|
const cardPreviewUrl =
|
|
previewUrls.main[0] || previewUrls.sku[0] || previewUrls.detail[0] || material.previewUrl
|
|
|
|
await assignTaskNoOnComplete(materialId, normalizedTaskNo)
|
|
await prisma.material.update({
|
|
where: { id: materialId },
|
|
data: {
|
|
previewUrl: cardPreviewUrl,
|
|
isFullSet: derivedIsFullSet,
|
|
},
|
|
})
|
|
|
|
await cleanupTempFiles(tempFiles, uploadIds)
|
|
|
|
await createMaterialLog({
|
|
materialId,
|
|
userId: operatorUserId,
|
|
action: 'UPLOAD',
|
|
changes: {
|
|
uploadType: {
|
|
oldValue: null,
|
|
newValue: '任务-详情',
|
|
},
|
|
taskNo: {
|
|
oldValue: null,
|
|
newValue: normalizedTaskNo,
|
|
},
|
|
isFullSet: {
|
|
oldValue: false,
|
|
newValue: derivedIsFullSet,
|
|
},
|
|
assetCounts: {
|
|
oldValue: null,
|
|
newValue: {
|
|
main: mainFiles.length,
|
|
sku: skuFiles.length,
|
|
detail: detailFiles.length,
|
|
psd: assets.psd?.length || 0,
|
|
},
|
|
},
|
|
zipSizes: {
|
|
oldValue: null,
|
|
newValue: {
|
|
main: zipInfos.main?.fileSize || 0,
|
|
sku: zipInfos.sku?.fileSize || 0,
|
|
detail: zipInfos.detail?.fileSize || 0,
|
|
all: zipInfos.all.fileSize,
|
|
},
|
|
},
|
|
},
|
|
})
|
|
|
|
if (derivedIsFullSet) {
|
|
void queueTaskDetailFullSetNotification(materialId)
|
|
}
|
|
|
|
return {
|
|
materialId,
|
|
taskNo: normalizedTaskNo,
|
|
isFullSet: derivedIsFullSet,
|
|
}
|
|
} catch (error) {
|
|
await cleanupOnError(uploadedPreviewUrls, createdZipPaths, tempFiles, materialId)
|
|
throw error
|
|
}
|
|
}
|