587 lines
36 KiB
TypeScript
587 lines
36 KiB
TypeScript
|
||
import { createHash, randomUUID } from 'node:crypto'
|
||
import { createReadStream } from 'node:fs'
|
||
import { copyFile, lstat, mkdir, rm } 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 { isRemoteUploadSyncEnabled, 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 { queueXiaoyiAutoListingNotification, wakeXiaoyiAutoListingNotifications, XIAOYI_AUTO_LISTING_EVENT_TYPE } from '@/lib/external-auto-listing'
|
||
import { desktopAssert, desktopId } from './contract.mjs'
|
||
import { pendingListingStatus, type ListingStatus } from '@/lib/xiaoyi-listing-status'
|
||
import {
|
||
XIAOYI_DELIVERY_LOG_ACTION, XIAOYI_DELIVERY_MATERIAL_TYPES as TYPES, XIAOYI_DETAIL_ASSET_GROUPS, XIAOYI_INTERNAL_ASSET_GROUPS,
|
||
type XiaoyiAssetSpec, type XiaoyiDeliveryKind, type XiaoyiDeliveryMetadata,
|
||
} from '@/lib/xiaoyi-delivery-material'
|
||
import type { DesktopAccount } from './service'
|
||
import { acquireDeliveryAttemptLock, saveDeliveryRevision, type DeliveryReference, type DeliverySnapshot } from '@/lib/delivery-revisions'
|
||
import { readXiaoyiDeliveryMetadata } from '@/lib/xiaoyi-delivery-material'
|
||
import { acquireTaskMaterialUploadSessionLocks } from '@/lib/material-upload-cross-process-lock'
|
||
|
||
type FileInput = XiaoyiAssetSpec & {
|
||
uploadId: string; fileName: string; fileSize: number; sha256: string
|
||
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; storeCategoryName?: string; productCategoryName?: string; brandName?: string; productName?: string; identifierType?: string;
|
||
baseRevisionId?: string | null; deliveredAt?: string | number; clientRevision?: number | string;
|
||
assets: {
|
||
main?: FileInput[]; sku?: FileInput[]; detail?: FileInput[]; files?: FileInput[];
|
||
longImage?: FileInput[]; projectSource?: FileInput[]; psd?: FileInput[];
|
||
}
|
||
}
|
||
type DeliveryFile = Omit<FileInput, 'barcode' | 'barcodes' | 'width' | 'height'> & { group: string; barcodes: string[]; resolution?: string }
|
||
type StoredFile = DeliveryFile & { storedPath: string }
|
||
|
||
async function findDeliveryRequest(
|
||
db: Pick<Prisma.TransactionClient, 'deliveryRevision'>,
|
||
ownerId: string,
|
||
request: { projectId: string; requestId: string; kind: XiaoyiDeliveryKind; fingerprint: string; legacyFingerprint: string | null },
|
||
): Promise<Receipt | null> {
|
||
const existing = await db.deliveryRevision.findUnique({
|
||
where: { ownerId_requestId_kind: { ownerId, requestId: request.requestId, kind: request.kind } },
|
||
select: { id: true, fingerprint: true, projectId: true, material: { select: { id: true, deletedAt: true, currentRevisionId: true } } },
|
||
})
|
||
if (!existing) return null
|
||
desktopAssert(existing.projectId === request.projectId && [request.fingerprint, request.legacyFingerprint].includes(existing.fingerprint),
|
||
'已有不同的交付记录,请保留原素材并联系管理员', 409, 'delivery_conflict')
|
||
return { requestId: request.requestId, materialId: existing.material.id, revisionId: existing.id,
|
||
materialType: TYPES[request.kind], state: existing.material.deletedAt ? 'removed' : 'completed',
|
||
isCurrent: existing.material.currentRevisionId === existing.id }
|
||
}
|
||
|
||
async function relatedDeliveryReferences(tx: Prisma.TransactionClient, ownerId: string, projectId: string, productModel: string) {
|
||
const rows = await tx.$queryRaw<Array<DeliveryReference & { kind: XiaoyiDeliveryKind }>>`
|
||
SELECT d.kind, d.material_id AS "materialId", m.current_revision_id AS "revisionId"
|
||
FROM desktop_material_deliveries d
|
||
JOIN materials m ON m.id = d.material_id AND m."userId" = d.owner_id
|
||
WHERE d.owner_id = ${ownerId} AND d.project_id = ${projectId}
|
||
AND UPPER(m."productModel") = UPPER(${productModel})
|
||
AND m."deletedAt" IS NULL AND NOT m.is_incomplete_shell
|
||
AND m.access_scope = 'general' AND NOT m.task_detail_private
|
||
`
|
||
return Object.fromEntries(rows.map(({ kind, ...ref }) => [kind, ref])) as Partial<Record<XiaoyiDeliveryKind, DeliveryReference>>
|
||
}
|
||
type Receipt = {
|
||
requestId: string; materialId: string; materialType: string; state: 'completed' | 'removed'; revisionId: string | null; isCurrent?: boolean
|
||
}
|
||
type PreviousDelivery = Receipt & { fingerprint: string; brandName: string; productName: string }
|
||
|
||
type OutboundReceipt = {
|
||
eventId: string | null
|
||
outboundStatus: 'no_targets' | 'pending' | 'accepted' | 'exhausted'
|
||
}
|
||
|
||
export async function withDesktopDeliveryOutbound<T extends Receipt>(receipt: T): Promise<T & OutboundReceipt> {
|
||
const { materialId, revisionId } = receipt
|
||
const [outbound] = await prisma.$queryRaw<OutboundReceipt[]>`
|
||
WITH outbound_event AS (
|
||
SELECT id, expanded_at IS NULL AS awaiting_targets
|
||
FROM xiaoyi_auto_listing_outbox WHERE revision_id = ${revisionId} AND material_id = ${materialId}
|
||
UNION ALL
|
||
SELECT e.id, true
|
||
FROM xiaoyi_auto_listing_events e
|
||
WHERE e.material_id = ${materialId} AND (${revisionId}::text IS NULL OR EXISTS (
|
||
SELECT 1 FROM delivery_revisions r
|
||
WHERE r.id = ${revisionId} AND r.snapshot->>'eventId' = e.id
|
||
))
|
||
)
|
||
SELECT e.id AS "eventId", CASE
|
||
WHEN bool_or(d.status = 'succeeded') THEN 'accepted'
|
||
WHEN bool_or(d.status IN ('pending', 'processing', 'retrying') AND t.is_active AND t.event_types ? d.event_type)
|
||
OR (e.awaiting_targets AND count(d.id) = 0 AND EXISTS (
|
||
SELECT 1 FROM external_notification_targets WHERE is_active AND event_types ? ${XIAOYI_AUTO_LISTING_EVENT_TYPE}
|
||
)) THEN 'pending'
|
||
WHEN bool_or(d.status = 'exhausted') THEN 'exhausted'
|
||
ELSE 'no_targets'
|
||
END AS "outboundStatus"
|
||
FROM outbound_event e
|
||
LEFT JOIN external_notification_deliveries d ON d.material_id = ${materialId}
|
||
AND d.event_type = ${XIAOYI_AUTO_LISTING_EVENT_TYPE} AND (d.dedupe_key = e.id OR d.payload->>'eventId' = e.id)
|
||
LEFT JOIN external_notification_targets t ON t.id = d.target_id
|
||
GROUP BY e.id, e.awaiting_targets
|
||
`
|
||
return { ...receipt, ...(outbound ?? { eventId: null, outboundStatus: 'no_targets' }) }
|
||
}
|
||
|
||
const GROUPS = [...XIAOYI_DETAIL_ASSET_GROUPS, ...XIAOYI_INTERNAL_ASSET_GROUPS, 'files'] as const
|
||
const uuid = /^[a-zA-Z0-9_-]{1,80}$/
|
||
const sha = /^[a-f0-9]{64}$/
|
||
|
||
function parseDeliveredAt(value: unknown): number | undefined {
|
||
if (value === undefined || value === null || value === '') return undefined
|
||
if (typeof value === 'number') {
|
||
desktopAssert(Number.isFinite(value) && value > 0, '交付时间戳无效')
|
||
return Math.trunc(value)
|
||
}
|
||
if (typeof value === 'string') {
|
||
const trimmed = value.trim()
|
||
const asNumber = /^\d+$/.test(trimmed) ? Number(trimmed) : Date.parse(trimmed)
|
||
desktopAssert(Number.isFinite(asNumber) && asNumber > 0, '交付时间戳无效')
|
||
return Math.trunc(asNumber)
|
||
}
|
||
desktopAssert(false, '交付时间戳无效')
|
||
}
|
||
|
||
function parseClientRevision(value: unknown): number | undefined {
|
||
if (value === undefined || value === null || value === '') return undefined
|
||
const num = typeof value === 'string' && /^\d+$/.test(value.trim()) ? Number(value.trim()) : value
|
||
desktopAssert(typeof num === 'number' && Number.isSafeInteger(num) && num >= 0, '客户端修订序号无效')
|
||
return num as number
|
||
}
|
||
|
||
function assertMonotonicRevision(
|
||
request: { baseRevisionId?: string | null; deliveredAt?: number; clientRevision?: number },
|
||
currentRevisionId: string | null,
|
||
currentSnapshot?: DeliverySnapshot | null,
|
||
) {
|
||
if (request.baseRevisionId !== undefined && currentRevisionId !== request.baseRevisionId) {
|
||
desktopAssert(false, '云端已有更新的交付修订,当前请求已过时,请基于最新版本提交', 409, 'stale_delivery_revision')
|
||
}
|
||
const currentMonotonic = currentSnapshot?.clientMonotonic
|
||
if (request.deliveredAt !== undefined && currentMonotonic?.deliveredAt !== undefined && request.deliveredAt < currentMonotonic.deliveredAt) {
|
||
desktopAssert(false, '云端已有更新的交付修订,较旧的交付请求不会覆盖当前版本', 409, 'stale_delivery_revision')
|
||
}
|
||
if (request.clientRevision !== undefined && currentMonotonic?.clientRevision !== undefined && request.clientRevision < currentMonotonic.clientRevision) {
|
||
desktopAssert(false, '云端已有更新的交付修订,较旧的交付请求不会覆盖当前版本', 409, 'stale_delivery_revision')
|
||
}
|
||
}
|
||
|
||
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 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,storeCategoryName,productCategoryName,brandName,productName,identifierType].every(value => value.length <= 120), '商品资料过长')
|
||
const baseRevisionId = input.baseRevisionId === undefined ? undefined
|
||
: input.baseRevisionId === null ? null
|
||
: (desktopAssert(typeof input.baseRevisionId === 'string' && uuid.test(input.baseRevisionId), '基线修订编号无效'), input.baseRevisionId)
|
||
const deliveredAt = parseDeliveredAt(input.deliveredAt)
|
||
const clientRevision = parseClientRevision(input.clientRevision)
|
||
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; specId?: string }>()
|
||
const filenames = new Set<string>()
|
||
const skuNames = new Map<string, boolean>()
|
||
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
|
||
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 && previous.variantId === variantId && previous.specId === specId
|
||
&& ((legacy && previous.legacy) || variantId || specId)),
|
||
'产品条码 ' + barcode + ' 不能同时绑定两张 SKU 图')
|
||
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 || 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 图的条码文件名或尺寸无效')
|
||
resolution = `${file.width}x${file.height}`
|
||
}
|
||
if (group === 'sku') {
|
||
const qualified = skuNames.get(nameKey)
|
||
desktopAssert(qualified === undefined || (!qualified && !resolution) || (qualified && resolution),
|
||
'同一分组中有重复文件')
|
||
skuNames.set(nameKey, Boolean(resolution))
|
||
}
|
||
const fileKey = resolution ? nameKey + '\u0000' + resolution + '\u0000' + file.sha256 : 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 }), ...(specId && { specId }), ...(variantName && { variantName }) })
|
||
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 => {
|
||
if (file.group === 'source') return false
|
||
if (file.group === 'psd') return /\.(?:psd|psb)$/i.test(file.fileName)
|
||
if (file.group === 'projectSource') return /\.(?:psd|psb|pcraft|zip|json|png|jpe?g|webp)$/i.test(file.fileName)
|
||
return /\.(?:jpe?g|png|webp)$/i.test(file.fileName)
|
||
}), '详情交付包含不支持的文件格式')
|
||
} else {
|
||
desktopAssert(files.every(file => file.group === input.kind), '该交付类型只接收对应的结果文件')
|
||
desktopAssert(files.every(file => !/\.(?:psd|psb|pcraft)$/i.test(file.fileName)), '只接收成品文件,不接收源文件')
|
||
}
|
||
const clientMonotonic = deliveredAt !== undefined || clientRevision !== undefined
|
||
? { ...(deliveredAt !== undefined && { deliveredAt }), ...(clientRevision !== undefined && { clientRevision }) }
|
||
: undefined
|
||
const identity = { projectId, requestId: input.requestId, kind: input.kind, identifier, categoryName, ...storeCategory, productCategoryName, brandName, productName, detailBarcode,
|
||
...(baseRevisionId !== undefined && { baseRevisionId }),
|
||
...(clientMonotonic && { clientMonotonic }),
|
||
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),
|
||
})).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", m.current_revision_id AS "revisionId",
|
||
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 replay = await findDeliveryRequest(prisma, ownerId, request)
|
||
if (replay) return replay
|
||
const previous = await prisma.$queryRawUnsafe<PreviousDelivery[]>(
|
||
`SELECT d.material_id AS "materialId",d.material_type AS "materialType",d.fingerprint,d.request_id AS "requestId",d.brand_name AS "brandName",d.product_name AS "productName",m.current_revision_id AS "revisionId",
|
||
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]?.requestId === request.requestId) {
|
||
desktopAssert([request.fingerprint, request.legacyFingerprint].includes(previous[0].fingerprint), '已有不同的交付记录,请保留原素材并联系管理员', 409, 'delivery_conflict')
|
||
const { requestId, materialId, materialType, state, revisionId } = previous[0]
|
||
return { requestId, materialId, materialType, state, revisionId, isCurrent: true }
|
||
}
|
||
if (previous[0] && previous[0].state !== 'removed' && (request.baseRevisionId !== undefined || request.clientMonotonic)) {
|
||
const currentRevision = previous[0].revisionId
|
||
? await prisma.deliveryRevision.findUnique({ where: { id: previous[0].revisionId }, select: { snapshot: true } })
|
||
: null
|
||
assertMonotonicRevision(
|
||
{ baseRevisionId: request.baseRevisionId, ...request.clientMonotonic },
|
||
previous[0].revisionId,
|
||
(currentRevision?.snapshot as DeliverySnapshot | undefined) ?? null,
|
||
)
|
||
}
|
||
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))
|
||
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 attempt = `${request.requestId}-${randomUUID()}`
|
||
const projectFolder = path.join(uploadRoot, 'xiaoyi-deliveries', owner, request.projectId)
|
||
const folder = path.join(projectFolder, attempt)
|
||
await mkdir(projectFolder, { recursive: true })
|
||
const releaseAttempt = await acquireDeliveryAttemptLock(owner, request.projectId, attempt)
|
||
|
||
let result: Receipt
|
||
let keepFolder = false
|
||
try {
|
||
await mkdir(folder)
|
||
const files: StoredFile[] = []
|
||
for (let index = 0; index < request.files.length; index++) {
|
||
const file = request.files[index]
|
||
const releaseUpload = await acquireTaskMaterialUploadSessionLocks([file.uploadId])
|
||
try {
|
||
releaseUpload.assertHeld()
|
||
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 = file.resolution ? file.fileName
|
||
: String(index).padStart(4,'0') + '-' + file.sha256 + (getUploadStorageExtension(file.fileName) || '.bin')
|
||
const folders = file.resolution ? ['sku', file.resolution, file.sha256] : []
|
||
const parent = path.join(folder, ...folders)
|
||
if (file.resolution) await mkdir(parent, { recursive: true })
|
||
const target = path.join(parent, targetName)
|
||
await copyFile(source!, target)
|
||
const storedPath = buildStoredUploadPath('xiaoyi-deliveries', owner, request.projectId, attempt, ...folders, targetName)
|
||
await syncStoredUploadFileToRemote(target, storedPath, file.fileSize)
|
||
files.push({ ...file, storedPath })
|
||
} finally {
|
||
await releaseUpload()
|
||
}
|
||
}
|
||
const author = await reauthorize()
|
||
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 replay = await findDeliveryRequest(tx, ownerId, request)
|
||
if (replay) return replay
|
||
const found = await tx.$queryRawUnsafe<PreviousDelivery[]>(
|
||
`SELECT d.material_id AS "materialId",d.material_type AS "materialType",d.fingerprint,d.request_id AS "requestId",d.brand_name AS "brandName",d.product_name AS "productName",m.current_revision_id AS "revisionId",
|
||
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 FOR UPDATE OF d`,
|
||
ownerId, request.projectId, request.kind,
|
||
)
|
||
if (found[0]?.requestId === request.requestId) {
|
||
desktopAssert([request.fingerprint, request.legacyFingerprint].includes(found[0].fingerprint), '已有不同的交付记录,请保留原素材并联系管理员', 409, 'delivery_conflict')
|
||
const { requestId, materialId, materialType, state, revisionId } = found[0]
|
||
return { requestId, materialId, materialType, state, revisionId, isCurrent: true }
|
||
}
|
||
desktopAssert(found[0]?.requestId === previous[0]?.requestId,
|
||
'其他提交已更新交付,请重试本次提交', 409, 'delivery_conflict')
|
||
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 materialData = {
|
||
authorName: author.name, productModel: identifier,
|
||
categoryName: request.categoryName, productCategoryName: request.productCategoryName,
|
||
materialType, taskStatus: 'completed', isFullSet: request.kind === 'detail', isAiGenerated: true,
|
||
}
|
||
const revisionIdentity = { ownerId, projectId: request.projectId, kind: request.kind,
|
||
requestId: request.requestId, fingerprint: request.fingerprint }
|
||
const related = await relatedDeliveryReferences(tx, ownerId, request.projectId, identifier)
|
||
const revising = found[0] && found[0].state !== 'removed' ? found[0] : null
|
||
let parentId: string | null = null
|
||
let materialId: string
|
||
if (revising) {
|
||
materialId = revising.materialId
|
||
const ownedMaterial = await tx.$queryRaw<Array<{ id: string }>>`
|
||
SELECT id FROM materials
|
||
WHERE id = ${materialId} AND "userId" = ${ownerId} AND "deletedAt" IS NULL
|
||
FOR UPDATE
|
||
`
|
||
desktopAssert(ownedMaterial.length, '素材已交接或撤回,无法覆盖', 409, 'delivery_ownership_conflict')
|
||
const current = await tx.material.findUniqueOrThrow({
|
||
where: { id: materialId },
|
||
select: { currentRevisionId: true, authorName: true, productModel: true, categoryName: true,
|
||
productCategoryName: true, assets: { include: { barcodes: { select: { barcode: true } } } } },
|
||
})
|
||
parentId = current.currentRevisionId
|
||
const currentRevision = parentId
|
||
? await tx.deliveryRevision.findUnique({ where: { id: parentId }, select: { snapshot: true } })
|
||
: null
|
||
assertMonotonicRevision(
|
||
{ baseRevisionId: request.baseRevisionId, ...request.clientMonotonic },
|
||
parentId,
|
||
(currentRevision?.snapshot as DeliverySnapshot | undefined) ?? null,
|
||
)
|
||
if (!parentId) {
|
||
const lastLog = await tx.materialLog.findFirst({
|
||
where: { materialId, action: XIAOYI_DELIVERY_LOG_ACTION },
|
||
orderBy: [{ timestamp: 'desc' }, { id: 'desc' }], select: { changes: true },
|
||
})
|
||
const legacyEvent = await tx.xiaoyiAutoListingEvent.findUnique({ where: { materialId }, select: { id: true } })
|
||
const baseline = await saveDeliveryRevision(tx, {
|
||
...revisionIdentity, materialId, parentId: null,
|
||
requestId: revising.requestId, fingerprint: revising.fingerprint,
|
||
}, {
|
||
authorName: current.authorName, productModel: current.productModel, categoryName: current.categoryName,
|
||
productCategoryName: current.productCategoryName, brandName: revising.brandName, productName: revising.productName,
|
||
metadata: readXiaoyiDeliveryMetadata(lastLog?.changes), related, legacy: true, ...(legacyEvent && { eventId: legacyEvent.id }),
|
||
}, current.assets.map(({ id, assetType, fileUrl, fileName, fileSize, sortOrder, skuCode, barcodes }) => ({
|
||
id, assetType, fileUrl, fileName, fileSize, sortOrder, skuCode, barcodes: barcodes.map(({ barcode }) => barcode),
|
||
})))
|
||
parentId = baseline.id
|
||
}
|
||
// Replace the compatibility projection. The immutable records keep the exact same asset IDs and files.
|
||
await tx.materialAsset.deleteMany({ where: { materialId } })
|
||
await tx.material.update({ where: { id: materialId }, data: { ...materialData, assets: { create: assets } } })
|
||
} else {
|
||
const material = await tx.material.create({
|
||
data: { ...materialData, userId: ownerId, sceneName: '', previewUrl: '', assets: { create: assets } },
|
||
select: { id: true },
|
||
})
|
||
materialId = material.id
|
||
}
|
||
const revision = await saveDeliveryRevision(tx, { ...revisionIdentity, materialId, parentId }, {
|
||
authorName: author.name, productModel: identifier, categoryName: request.categoryName,
|
||
productCategoryName: request.productCategoryName, brandName: request.brandName, productName: request.productName,
|
||
metadata: deliveryMetadata, related, ...(request.clientMonotonic && { clientMonotonic: request.clientMonotonic }),
|
||
}, assets.map(({ barcodes, ...asset }, index) => ({
|
||
...asset, sha256: files[index].sha256, barcodes: barcodes?.create.map(({ barcode }) => barcode) ?? [],
|
||
})))
|
||
await tx.material.update({ where: { id: materialId }, data: { currentRevisionId: revision.id } })
|
||
if (revising) {
|
||
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
|
||
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,
|
||
)
|
||
} else 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,materialId,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,materialId,materialType,request.brandName,request.productName,'spu',
|
||
)
|
||
}
|
||
if (revising || deliveryMetadata.storeCategoryName || Object.keys(deliveryMetadata.assetSpecs).length) {
|
||
await tx.materialLog.create({ data: {
|
||
materialId, userId: ownerId, action: XIAOYI_DELIVERY_LOG_ACTION,
|
||
changes: JSON.stringify({ deliveryMetadata: { oldValue: null, newValue: deliveryMetadata } }),
|
||
} })
|
||
}
|
||
await queueXiaoyiAutoListingNotification(tx,{materialId,materialType,outcomeKind:request.kind,projectId:request.projectId,revisionId:revision.id})
|
||
keepFolder = true
|
||
return {requestId:request.requestId,materialId,materialType,state:'completed' as const,revisionId:revision.id}
|
||
},{timeout:30000})
|
||
} finally {
|
||
// If the transaction reached COMMIT, the database may retain these files even when the connection fails.
|
||
try {
|
||
if (!keepFolder && !isRemoteUploadSyncEnabled()) await rm(folder, { recursive: true, force: true })
|
||
} finally {
|
||
await releaseAttempt()
|
||
}
|
||
}
|
||
invalidateMaterialFacetsCache()
|
||
wakeXiaoyiAutoListingNotifications()
|
||
return result
|
||
}
|