295 lines
19 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 type { Prisma } from '@prisma/client'
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'
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 type { DesktopAccount } from './service'
type FileInput = {
uploadId: string; fileName: string; fileSize: number; sha256: string
skuCode?: string; barcode?: string; barcodes?: string[]; variantId?: string
}
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;
assets: { main?: FileInput[]; sku?: FileInput[]; detail?: FileInput[]; files?: FileInput[] }
}
type DeliveryFile = Omit<FileInput, 'barcode' | 'barcodes'> & { group: string; barcodes: string[] }
type StoredFile = DeliveryFile & { storedPath: string }
type Receipt = { requestId: string; materialId: string; materialType: string; state: 'completed' | 'removed' }
const GROUPS = [...XIAOYI_DETAIL_ASSET_GROUPS, 'files'] as const
const uuid = /^[a-zA-Z0-9_-]{1,80}$/
const sha = /^[a-f0-9]{64}$/
function parseBarcodes(value: unknown): string[] {
desktopAssert(Array.isArray(value) && value.every(code => typeof code === 'string' && code.trim()), '产品条码须为非空字符串')
return Array.from(new Set((value as string[]).map(code => code.trim())))
}
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 { deliverySpu: legacySpu } = input
const identifierInput = input.identifier ?? legacySpu ?? input.productModel
const identifier = typeof identifierInput === 'string' ? identifierInput.trim() : ''
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 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: DeliveryFile[] = []
const legacyFiles: Array<Omit<DeliveryFile, 'barcodes'> & { barcode?: string }> = []
const barcodeOwners = new Map<string, { legacy: boolean; skuCode?: string; variantId?: string }>()
const filenames = new Set<string>()
let hasBarcodeArrays = false
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 legacyName = group === 'sku' && /\.jpg$/i.test(file.fileName) ? file.fileName.slice(0, -4) : undefined
const legacyBarcode = file.barcode === undefined ? legacyName : file.barcode
const legacy = file.barcodes === undefined && legacyBarcode !== undefined
const barcodes = parseBarcodes(file.barcodes === undefined ? (legacy ? [legacyBarcode] : []) : file.barcodes)
hasBarcodeArrays ||= file.barcodes !== undefined
const skuCode = typeof file.skuCode === 'string' ? file.skuCode.trim() : undefined
const variantId = file.variantId
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))),
'产品条码 ' + barcode + ' 不能同时绑定两张 SKU 图')
barcodeOwners.set(barcode, { legacy, skuCode, variantId })
}
const assetGroup = group === 'files' ? (input.kind === 'detail' ? 'source' : input.kind) : group
const nameKey = assetGroup + '\u0000' + name.fileName!.toLowerCase()
const fileKey = 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 }) })
legacyFiles.push({ ...metadata, uploadId: file.uploadId, ...(file.barcode !== undefined && { barcode: barcodes[0], skuCode }) })
}
}
desktopAssert(files.length > 0 && files.length <= 500 && new Set(files.map(file => file.uploadId)).size === files.length, '交付文件为空或重复')
if (barcodeOwners.size && !hasBarcodeArrays) {
desktopAssert(files.filter(file => file.group === 'sku').every(file => file.barcodes.length), '每张 SKU 图都须提供条码')
}
if (input.kind === 'detail') {
desktopAssert(XIAOYI_DETAIL_ASSET_GROUPS.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, identifier, categoryName, 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
? 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),
})).digest('hex')
: null
return { ...identity, files, fingerprint, legacyFingerprint }
}
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')
}
async function projectDeliveryIdentifier(db: Pick<Prisma.TransactionClient, '$queryRaw'>, ownerId: string, projectId: string, identifier: string) {
const related = await db.$queryRaw<Array<{ identifier: string }>>`
SELECT m."productModel" AS identifier
FROM desktop_material_deliveries d JOIN materials m ON m.id = d.material_id
WHERE d.project_id = ${projectId} AND d.owner_id = ${ownerId}
ORDER BY d.created_at, d.id
`
desktopAssert(related.every(item => item.identifier.toUpperCase() === identifier.toUpperCase()),
'本项目已有其他 SPU 的交付记录', 409, 'delivery_identifier_conflict')
return related[0]?.identifier ?? identifier
}
export async function getDesktopDelivery(ownerId: string, projectId: string, kind: string) {
desktopId(projectId)
desktopAssert(Object.hasOwn(TYPES, kind), '交付类型无效')
await authorizeProject(ownerId, projectId)
const rows = await prisma.$queryRawUnsafe<Array<Receipt & { listingStatus: ListingStatus | null }>>(
`SELECT d.request_id AS "requestId", d.material_id AS "materialId", d.material_type AS "materialType",
d.listing_status AS "listingStatus",
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,
)
const [receipt] = rows
return receipt ? { ...receipt, listingStatus: receipt.state === 'completed' ? receipt.listingStatus ?? pendingListingStatus : null } : null
}
export async function createDesktopDelivery(ownerId: string, input: Input, reauthorize: () => Promise<DesktopAccount>): 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 && [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}
}
await projectDeliveryIdentifier(prisma, ownerId, request.projectId, request.identifier)
const barcodeFiles = request.files.filter(file => file.barcodes.length)
const barcodes = new Set(barcodeFiles.flatMap(file => file.barcodes))
if (request.detailBarcode) barcodes.add(request.detailBarcode)
if (barcodes.size) {
const catalog = await findDetailMaterialMatches(ownerId, 'spu', request.identifier, true)
const valid = new Map<string, Set<string>>()
const knownBarcodes = new 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)
knownBarcodes.add(barcode)
}
}
desktopAssert(barcodeFiles.every(file => !file.skuCode ||
file.barcodes.every(barcode => !knownBarcodes.has(barcode) || valid.get(file.skuCode!)?.has(barcode))),
'SKU 或条码不属于该 SPU,请核对产品资料')
const unknownBarcodes = Array.from(barcodes).filter(barcode => !knownBarcodes.has(barcode))
for (let index = 0; index < unknownBarcodes.length; index += 5) {
const codes = unknownBarcodes.slice(index, index + 5)
const matches = await Promise.all(codes.map(barcode => findDetailMaterialMatches(ownerId, 'barcode', barcode, true)))
for (let offset = 0; offset < codes.length; offset++) {
desktopAssert(matches[offset].every(row => row.productModel.toUpperCase() === request.identifier.toUpperCase()),
'条码 ' + codes[offset] + ' 已登记在其他 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})
}
const author = 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 && [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)
const materialType = TYPES[request.kind]
const firstDetailIndex = files.findIndex(file => file.group === 'detail')
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 })) } }),
}
}) },
},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',
)
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
}