235 lines
15 KiB
TypeScript
235 lines
15 KiB
TypeScript
|
||
import { createHash, randomUUID } from 'node:crypto'
|
||
import { createReadStream } from 'node:fs'
|
||
import { copyFile, lstat, mkdir, rename, unlink } from 'node:fs/promises'
|
||
import path from 'node:path'
|
||
import { prisma } from '@/lib/prisma'
|
||
import { invalidateMaterialFacetsCache } from '@/lib/material-facets-cache'
|
||
import { syncStoredUploadFileToRemote } from '@/lib/remote-upload-sync'
|
||
import { getOwnedUploadSession } from '@/lib/upload-sessions'
|
||
import { buildStoredUploadPath, getUploadRootDir, getUploadStorageExtension, inspectUploadOutput } from '@/lib/upload-paths'
|
||
import { resolveStrictChildPath } from '@/lib/path-security'
|
||
import { validateUploadFileName } from '@/lib/upload-file-name'
|
||
import { detailTransactionLock } from '@/lib/detail-generator/repository'
|
||
import { findDetailMaterialMatches } from '@/lib/detail-generator/materials'
|
||
import { ensureExternalNotificationTables, queueXiaoyiAutoListingNotification, wakeXiaoyiAutoListingNotifications } from '@/lib/external-auto-listing'
|
||
import { desktopAssert, desktopId } from './contract.mjs'
|
||
|
||
type DeliveryKind = 'detail' | 'video' | 'buyer_show'
|
||
type FileInput = { uploadId: string; fileName: string; fileSize: number; sha256: string; skuCode?: string; barcode?: string }
|
||
type Input = {
|
||
projectId: string; requestId: string; kind: DeliveryKind; productModel: string;
|
||
categoryName?: string; productCategoryName?: string; brandName?: string; productName?: string; identifierType?: string;
|
||
assets: { main?: FileInput[]; sku?: FileInput[]; detail?: FileInput[]; files?: FileInput[] }
|
||
}
|
||
type StoredFile = FileInput & { group: string; storedPath: string }
|
||
type Receipt = { requestId: string; materialId: string; materialType: string; state: 'completed' | 'removed' }
|
||
const TYPES: Record<DeliveryKind, string> = {
|
||
detail: '自动上架-详情', video: '自动上架-视频', buyer_show: '自动上架-买家秀',
|
||
}
|
||
const GROUPS = ['main', 'sku', 'detail', 'files'] as const
|
||
const uuid = /^[a-zA-Z0-9_-]{1,80}$/
|
||
const sha = /^[a-f0-9]{64}$/
|
||
|
||
function normalized(input: Input) {
|
||
desktopAssert(input && typeof input === 'object', '交付信息无效')
|
||
const projectId = desktopId(input.projectId)
|
||
desktopAssert(typeof input.requestId === 'string' && uuid.test(input.requestId), '交付请求编号无效')
|
||
desktopAssert(Object.hasOwn(TYPES, input.kind), '交付类型无效')
|
||
const productModel = typeof input.productModel === 'string' ? input.productModel.trim() : ''
|
||
desktopAssert(productModel.length > 0 && productModel.length <= 120, '请填写商品型号')
|
||
const categoryName = typeof input.categoryName === 'string' ? input.categoryName.trim() : ''
|
||
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(input.assets && typeof input.assets === 'object', '交付文件缺失')
|
||
const files: Array<FileInput & { group: string }> = []
|
||
for (const group of GROUPS) {
|
||
const list = input.assets[group] ?? []
|
||
desktopAssert(Array.isArray(list) && list.length <= 200, '交付文件列表无效')
|
||
for (const file of list) {
|
||
const name = validateUploadFileName(file?.fileName)
|
||
desktopAssert(name.fileName && typeof file.uploadId === 'string' && uuid.test(file.uploadId)
|
||
&& Number.isSafeInteger(file.fileSize) && file.fileSize > 0 && sha.test(file.sha256), '交付文件信息无效')
|
||
const identity = file.barcode === undefined && file.skuCode === undefined ? {} : {
|
||
barcode: typeof file.barcode === 'string' ? file.barcode.trim() : '',
|
||
skuCode: typeof file.skuCode === 'string' ? file.skuCode.trim() : '',
|
||
}
|
||
if ('barcode' in identity) {
|
||
desktopAssert(group === 'sku' && identity.skuCode && identity.skuCode.length <= 200 &&
|
||
identity.barcode && /^[a-zA-Z0-9_-]{1,120}$/.test(identity.barcode) &&
|
||
name.fileName === identity.barcode + '.jpg', 'SKU 图文件名须为条码.jpg,并提供 SKU 编号')
|
||
}
|
||
files.push({ group: group === 'files' ? (input.kind === 'detail' ? 'source' : input.kind) : group,
|
||
uploadId: file.uploadId, fileName: name.fileName!, fileSize: file.fileSize, sha256: file.sha256, ...identity })
|
||
}
|
||
}
|
||
desktopAssert(files.length > 0 && files.length <= 500 && new Set(files.map(file => file.uploadId)).size === files.length, '交付文件为空或重复')
|
||
const skuFiles = files.filter(file => file.group === 'sku')
|
||
const barcodeOwners = new Map<string, string>()
|
||
const filenames = new Set<string>()
|
||
for (const file of files) {
|
||
const name = file.group + '\\0' + file.fileName.toLowerCase()
|
||
if (file.barcode) {
|
||
const sku = file.skuCode!
|
||
const previous = barcodeOwners.get(name)
|
||
desktopAssert(!previous || previous === sku, '同一条码不能绑定到多个 SKU')
|
||
barcodeOwners.set(name, sku)
|
||
}
|
||
const identity = file.barcode ? name + '\\0' + file.sha256 : name
|
||
desktopAssert(!filenames.has(identity), '同一分组中有重复文件')
|
||
filenames.add(identity)
|
||
}
|
||
if (barcodeOwners.size) {
|
||
desktopAssert(skuFiles.every(file => file.barcode), '每张 SKU 图都须提供条码')
|
||
}
|
||
if (input.kind === 'detail') {
|
||
desktopAssert(['main','sku','detail'].every(group => files.some(file => file.group === group)), '详情三件套需要主图、SKU 和详情图')
|
||
desktopAssert(files.every(file => file.group !== 'source' && /\.(?:jpe?g|png|webp)$/i.test(file.fileName)), '详情三件套只接收主图、SKU 和详情成品图')
|
||
} else {
|
||
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, productModel, categoryName, productCategoryName, brandName, productName, identifierType,
|
||
files: files.map(({group,fileName,fileSize,sha256,barcode,skuCode}) => ({group,fileName,fileSize,sha256,...(barcode ? {barcode,skuCode} : {})})) }
|
||
return { ...identity, files, fingerprint: createHash('sha256').update(JSON.stringify(identity)).digest('hex') }
|
||
}
|
||
|
||
async function digestFile(file: string) {
|
||
const hash = createHash('sha256')
|
||
for await (const bytes of createReadStream(file)) hash.update(bytes)
|
||
return hash.digest('hex')
|
||
}
|
||
|
||
async function authorizeProject(ownerId: string, projectId: string) {
|
||
const rows = await prisma.$queryRawUnsafe<{id:string}[]>(
|
||
'SELECT id FROM desktop_workspace_projects WHERE id=$1 AND owner_id=$2 AND deleted_at IS NULL', projectId, ownerId,
|
||
)
|
||
desktopAssert(rows.length, '项目不存在或无权访问', 404, 'not_found')
|
||
}
|
||
|
||
export async function getDesktopDelivery(ownerId: string, projectId: string, kind: string): Promise<Receipt | null> {
|
||
desktopId(projectId)
|
||
desktopAssert(Object.hasOwn(TYPES, kind), '交付类型无效')
|
||
await authorizeProject(ownerId, projectId)
|
||
const rows = await prisma.$queryRawUnsafe<Array<Receipt>>(
|
||
`SELECT d.request_id AS "requestId", d.material_id AS "materialId", d.material_type AS "materialType",
|
||
CASE WHEN m.id IS NULL OR m."deletedAt" IS NOT NULL THEN 'removed' ELSE 'completed' END AS state
|
||
FROM desktop_material_deliveries d LEFT JOIN materials m ON m.id=d.material_id
|
||
WHERE d.owner_id=$1 AND d.project_id=$2 AND d.kind=$3`,
|
||
ownerId, projectId, kind,
|
||
)
|
||
return rows[0] || null
|
||
}
|
||
|
||
export async function createDesktopDelivery(ownerId: string, input: Input, reauthorize: () => Promise<unknown>): Promise<Receipt> {
|
||
const request = normalized(input)
|
||
await reauthorize()
|
||
await authorizeProject(ownerId, request.projectId)
|
||
const previous = await prisma.$queryRawUnsafe<Array<Receipt & {fingerprint:string}>>(
|
||
`SELECT d.material_id AS "materialId",d.material_type AS "materialType",d.fingerprint,d.request_id AS "requestId",
|
||
CASE WHEN m.id IS NULL OR m."deletedAt" IS NOT NULL THEN 'removed' ELSE 'completed' END AS state
|
||
FROM desktop_material_deliveries d LEFT JOIN materials m ON m.id=d.material_id
|
||
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 && previous[0].fingerprint === request.fingerprint, '已有不同的交付记录,请保留原素材并联系管理员', 409, 'delivery_conflict')
|
||
return {requestId:previous[0].requestId,materialId:previous[0].materialId,materialType:previous[0].materialType,state:previous[0].state}
|
||
}
|
||
|
||
const skuFiles = request.files.filter(file => file.barcode)
|
||
if (skuFiles.length) {
|
||
const catalog = await findDetailMaterialMatches(ownerId, 'spu', request.productModel, true)
|
||
const valid = new Map<string, Set<string>>()
|
||
for (const row of catalog) {
|
||
if (!valid.has(row.skuCode)) valid.set(row.skuCode, new Set())
|
||
for (const barcode of row.barcodes) valid.get(row.skuCode)!.add(barcode)
|
||
}
|
||
desktopAssert(skuFiles.every(file => valid.get(file.skuCode!)?.has(file.barcode!)), 'SKU 或条码不属于该 SPU,请核对产品资料')
|
||
}
|
||
|
||
const uploadRoot = getUploadRootDir()
|
||
const owner = createHash('sha256').update(ownerId).digest('hex')
|
||
const folder = path.join(uploadRoot, 'xiaoyi-deliveries', owner, request.projectId, request.requestId)
|
||
await mkdir(folder, {recursive:true})
|
||
const files: StoredFile[] = []
|
||
for (let index = 0; index < request.files.length; index++) {
|
||
const file = request.files[index]
|
||
const session = await getOwnedUploadSession(file.uploadId, ownerId)
|
||
desktopAssert(session?.uploadPurpose === 'xiaoyi:' + request.projectId + ':' + request.requestId
|
||
&& session.fileSize === file.fileSize && session.fileName === file.fileName, '交付文件不属于本次上传或已过期', 409, 'upload_mismatch')
|
||
const tempDir = resolveStrictChildPath(uploadRoot, 'temp', file.uploadId)
|
||
desktopAssert(tempDir, '上传会话路径无效', 409, 'upload_mismatch')
|
||
const { existing } = await inspectUploadOutput(tempDir!, 'merged-file', 'merged-', file.fileName)
|
||
const source = existing?.filePath
|
||
desktopAssert(source, '上传文件不存在或尚未合并', 409, 'upload_incomplete')
|
||
const stat = await lstat(source!)
|
||
desktopAssert(stat.isFile() && !stat.isSymbolicLink() && stat.size === file.fileSize && await digestFile(source!) === file.sha256, '上传文件内容与交付清单不一致', 409, 'file_mismatch')
|
||
const targetName = String(index).padStart(4,'0') + '-' + file.sha256 + (getUploadStorageExtension(file.fileName) || '.bin')
|
||
const target = path.join(folder, targetName)
|
||
const temporary = target + '.' + randomUUID() + '.tmp'
|
||
await copyFile(source!, temporary)
|
||
await rename(temporary, target).catch(async error => {
|
||
await unlink(temporary).catch(() => undefined)
|
||
if (error?.code !== 'EPERM' && error?.code !== 'EEXIST') throw error
|
||
const existing = await lstat(target).catch(() => null)
|
||
if (!existing?.isFile() || existing.size !== file.fileSize || await digestFile(target) !== file.sha256) throw error
|
||
})
|
||
const storedPath = buildStoredUploadPath('xiaoyi-deliveries', owner, request.projectId, request.requestId, targetName)
|
||
await syncStoredUploadFileToRemote(target, storedPath, file.fileSize)
|
||
files.push({...file, storedPath})
|
||
}
|
||
await reauthorize()
|
||
await ensureExternalNotificationTables()
|
||
const result = await prisma.$transaction(async tx => {
|
||
await detailTransactionLock(tx, 'desktop-tasks:' + ownerId)
|
||
await detailTransactionLock(tx, 'desktop:' + request.projectId)
|
||
const project = await tx.$queryRawUnsafe<{id:string}[]>(
|
||
'SELECT id FROM desktop_workspace_projects WHERE id=$1 AND owner_id=$2 AND deleted_at IS NULL FOR UPDATE',
|
||
request.projectId, ownerId,
|
||
)
|
||
desktopAssert(project.length, '项目不存在或无权访问', 404, 'not_found')
|
||
const running = await tx.$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(!running.length, '项目仍有未完成的制作任务', 409, 'task_busy')
|
||
const found = await tx.$queryRawUnsafe<Array<Receipt & {fingerprint:string}>>(
|
||
`SELECT d.material_id AS "materialId",d.material_type AS "materialType",d.fingerprint,d.request_id AS "requestId",
|
||
CASE WHEN m.id IS NULL OR m."deletedAt" IS NOT NULL THEN 'removed' ELSE 'completed' END AS state
|
||
FROM desktop_material_deliveries d LEFT JOIN materials m ON m.id=d.material_id
|
||
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 && found[0].fingerprint === request.fingerprint, '已有不同的交付记录,请保留原素材并联系管理员', 409, 'delivery_conflict')
|
||
return {requestId:found[0].requestId,materialId:found[0].materialId,materialType:found[0].materialType,state:found[0].state}
|
||
}
|
||
const user = await tx.user.findUnique({where:{id:ownerId},select:{username:true,realName:true}})
|
||
desktopAssert(user, '账户不存在', 401)
|
||
const materialType = TYPES[request.kind]
|
||
const material = await tx.material.create({data:{
|
||
userId:ownerId, authorName:user!.realName || user!.username, productModel:request.productModel,
|
||
categoryName:request.categoryName, productCategoryName:request.productCategoryName, sceneName:'',
|
||
materialType, previewUrl:'', taskStatus:'completed', isFullSet:request.kind === 'detail', isAiGenerated:true,
|
||
assets: { create: files.map((file,index) => ({
|
||
assetType: file.group, fileUrl: file.storedPath, fileName: file.fileName,
|
||
fileSize: BigInt(file.fileSize), sortOrder: index, skuCode: file.skuCode,
|
||
...(file.barcode ? { barcodes: { create: { barcode: file.barcode } } } : {}),
|
||
})) },
|
||
},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,request.identifierType,
|
||
)
|
||
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})
|
||
invalidateMaterialFacetsCache()
|
||
wakeXiaoyiAutoListingNotifications()
|
||
return result
|
||
}
|