feat: add barcode white background external APIs

This commit is contained in:
chenpei 2026-06-08 17:51:33 +08:00
parent 8280124681
commit 8fd571b823
9 changed files with 1720 additions and 272 deletions

View File

@ -0,0 +1,222 @@
import { randomUUID } from 'crypto'
import { NextRequest, NextResponse } from 'next/server'
import {
getApiKeyFromRequest,
getClientIp,
logApiCall,
validateApiKey,
} from '@/lib/external-api'
import {
completeExternalApiIdempotencyRecord,
ExternalWhiteBackgroundBarcodeError,
failExternalApiIdempotencyRecord,
normalizeExternalBarcode,
resolveStandardModelSkuByBarcode,
stableHashPayload,
STANDARD_MODEL_WHITE_BACKGROUND_BARCODE_OPERATION,
startExternalApiIdempotencyRecord,
} from '@/lib/external-standard-model-white-background-by-barcode'
import { cleanupStandardModelWhiteBackgroundForSku } from '@/lib/standard-model-white-background-service'
export const runtime = 'nodejs'
const ENDPOINT = '/api/external/standard-model-white-background/by-barcode/cleanup'
type TraceContext = {
traceId: string
startTime: number
barcode: string
ipAddress?: string
apiKeyName?: string
userAgent?: string
}
function buildErrorBody(code: string, message: string) {
return {
success: false,
error: {
code,
message,
},
}
}
function buildErrorResponse(status: number, code: string, message: string) {
return NextResponse.json(buildErrorBody(code, message), { status })
}
function buildSuccessBody<T>(data: T) {
return {
success: true,
data,
}
}
function getElapsedMs(startTime: number) {
return Math.max(0, Date.now() - startTime)
}
function finalizeResponse(response: NextResponse, trace: TraceContext) {
const duration = getElapsedMs(trace.startTime)
response.headers.set('X-Trace-Id', trace.traceId)
response.headers.set('X-Server-Duration-Ms', String(duration))
response.headers.set('Server-Timing', `app;dur=${duration}`)
if (trace.barcode) {
response.headers.set('X-Request-Barcode', trace.barcode)
}
return response
}
async function writeApiLog(params: {
apiKeyId: string
trace: TraceContext
statusCode: number
}) {
await logApiCall({
apiKeyId: params.apiKeyId,
endpoint: ENDPOINT,
method: 'POST',
queryType: 'barcode',
queryValue: params.trace.barcode || undefined,
statusCode: params.statusCode,
duration: getElapsedMs(params.trace.startTime),
ipAddress: params.trace.ipAddress,
userAgent: params.trace.userAgent,
})
}
function normalizeBarcodeList(value: unknown) {
if (!Array.isArray(value)) {
return []
}
return Array.from(
new Set(value.map((item) => normalizeExternalBarcode(item)).filter(Boolean)),
)
}
export async function POST(request: NextRequest) {
const trace: TraceContext = {
traceId: randomUUID(),
startTime: Date.now(),
barcode: '',
ipAddress: getClientIp(request),
userAgent: request.headers.get('user-agent') || undefined,
}
const apiKey = getApiKeyFromRequest(request)
const keyRecord = await validateApiKey(apiKey)
if (!keyRecord) {
return finalizeResponse(
buildErrorResponse(401, 'INVALID_API_KEY', 'API Key 无效或缺失'),
trace,
)
}
trace.apiKeyName = keyRecord.name
let idempotencyRecordId: string | null = null
try {
const body = await request.json()
const clientRequestId = String(body?.clientRequestId || '').trim()
const reason = String(body?.reason || '').trim()
const mode = String(body?.mode || 'soft').trim() || 'soft'
const skuBatchNo = body?.skuBatchNo ?? null
const barcodes = normalizeBarcodeList(body?.barcodes)
trace.barcode = barcodes.join(',')
if (!clientRequestId) {
await writeApiLog({ apiKeyId: keyRecord.id, trace, statusCode: 400 })
return finalizeResponse(
buildErrorResponse(400, 'INVALID_CLIENT_REQUEST_ID', 'clientRequestId 不能为空'),
trace,
)
}
if (barcodes.length === 0) {
await writeApiLog({ apiKeyId: keyRecord.id, trace, statusCode: 400 })
return finalizeResponse(buildErrorResponse(400, 'INVALID_BARCODE', 'barcodes 不能为空'), trace)
}
const requestHash = stableHashPayload({
clientRequestId,
reason,
mode,
skuBatchNo,
barcodes,
})
const idempotency = await startExternalApiIdempotencyRecord({
apiKeyId: keyRecord.id,
operationType: STANDARD_MODEL_WHITE_BACKGROUND_BARCODE_OPERATION.CLEANUP,
clientRequestId,
requestHash,
})
if (idempotency.mode === 'replay') {
await writeApiLog({ apiKeyId: keyRecord.id, trace, statusCode: idempotency.record.responseStatus || 200 })
return finalizeResponse(
NextResponse.json(idempotency.record.responseBody, {
status: idempotency.record.responseStatus || 200,
}),
trace,
)
}
const activeIdempotencyRecordId = String(idempotency.record.id)
idempotencyRecordId = activeIdempotencyRecordId
const results = []
for (const barcode of barcodes) {
const resolved = await resolveStandardModelSkuByBarcode(barcode)
const cleanup = await cleanupStandardModelWhiteBackgroundForSku({
materialId: resolved.materialId,
skuId: resolved.skuId,
operatorUserId: keyRecord.createdBy,
reason,
})
results.push({
barcode,
materialId: resolved.materialId,
skuId: resolved.skuId,
resolvedSpu: resolved.resolvedSpu,
resolvedSkuName: resolved.resolvedSkuName,
...cleanup,
})
}
const responseBody = buildSuccessBody({
traceId: trace.traceId,
cleanedCount: results.length,
mode,
reason,
results,
})
await completeExternalApiIdempotencyRecord({
recordId: activeIdempotencyRecordId,
responseStatus: 200,
responseBody,
})
await writeApiLog({ apiKeyId: keyRecord.id, trace, statusCode: 200 })
return finalizeResponse(NextResponse.json(responseBody), trace)
} catch (error) {
if (idempotencyRecordId) {
await failExternalApiIdempotencyRecord(idempotencyRecordId)
}
if (error instanceof ExternalWhiteBackgroundBarcodeError) {
await writeApiLog({ apiKeyId: keyRecord.id, trace, statusCode: error.status })
return finalizeResponse(buildErrorResponse(error.status, error.code, error.message), trace)
}
const message = error instanceof Error ? error.message : '清理白底图失败'
console.error('[external/standard-model-white-background/by-barcode/cleanup] POST error:', error)
await writeApiLog({ apiKeyId: keyRecord.id, trace, statusCode: 500 })
return finalizeResponse(buildErrorResponse(500, 'CLEANUP_FAILED', message || '清理白底图失败'), trace)
}
}

View File

@ -0,0 +1,306 @@
import { randomUUID } from 'crypto'
import { NextRequest, NextResponse } from 'next/server'
import {
getApiKeyFromRequest,
getClientIp,
logApiCall,
validateApiKey,
} from '@/lib/external-api'
import {
completeExternalApiIdempotencyRecord,
ExternalWhiteBackgroundBarcodeError,
failExternalApiIdempotencyRecord,
resolveStandardModelSkuByBarcode,
stableHashPayload,
STANDARD_MODEL_WHITE_BACKGROUND_BARCODE_OPERATION,
startExternalApiIdempotencyRecord,
} from '@/lib/external-standard-model-white-background-by-barcode'
import {
STANDARD_MODEL_WHITE_BG_OTHER_FIELD_NAME,
STANDARD_MODEL_WHITE_BG_VIEWS,
type StandardModelWhiteBgKey,
} from '@/lib/standard-model-white-background'
import { normalizeStandardModelWhiteBackgroundSourceType } from '@/lib/standard-model-white-background-metadata'
import { uploadStandardModelWhiteBackground } from '@/lib/standard-model-white-background-service'
export const runtime = 'nodejs'
const ENDPOINT = '/api/external/standard-model-white-background/by-barcode'
type TraceContext = {
traceId: string
startTime: number
barcode: string
ipAddress?: string
apiKeyName?: string
userAgent?: string
}
function buildErrorBody(code: string, message: string) {
return {
success: false,
error: {
code,
message,
},
}
}
function buildErrorResponse(status: number, code: string, message: string) {
return NextResponse.json(buildErrorBody(code, message), { status })
}
function buildSuccessBody<T>(data: T) {
return {
success: true,
data,
}
}
function getElapsedMs(startTime: number) {
return Math.max(0, Date.now() - startTime)
}
function finalizeResponse(response: NextResponse, trace: TraceContext) {
const duration = getElapsedMs(trace.startTime)
response.headers.set('X-Trace-Id', trace.traceId)
response.headers.set('X-Server-Duration-Ms', String(duration))
response.headers.set('Server-Timing', `app;dur=${duration}`)
if (trace.barcode) {
response.headers.set('X-Request-Barcode', trace.barcode)
}
return response
}
function isUsableFile(file: File | null | undefined): file is File {
return (
!!file &&
typeof file.name === 'string' &&
typeof file.arrayBuffer === 'function' &&
Number(file.size || 0) > 0
)
}
function collectFixedImages(formData: FormData) {
return STANDARD_MODEL_WHITE_BG_VIEWS.reduce((acc, view) => {
const file = formData.get(view.fieldName) as File | null
acc[view.key] = isUsableFile(file) ? file : null
return acc
}, {} as Partial<Record<StandardModelWhiteBgKey, File | null>>)
}
function collectOtherImages(formData: FormData) {
return formData
.getAll(STANDARD_MODEL_WHITE_BG_OTHER_FIELD_NAME)
.filter((file): file is File => isUsableFile(file as File | null))
}
function countFixedImages(images: Partial<Record<StandardModelWhiteBgKey, File | null>>) {
return STANDARD_MODEL_WHITE_BG_VIEWS.filter((view) => isUsableFile(images[view.key])).length
}
function buildUploadRequestHashPayload(params: {
clientRequestId: string
barcode: string
sourceType: string
sourceSystem: string
productId: string
skuBatchNo: string
fixedImages: Partial<Record<StandardModelWhiteBgKey, File | null>>
otherImages: File[]
}) {
return {
clientRequestId: params.clientRequestId,
barcode: params.barcode,
sourceType: params.sourceType,
sourceSystem: params.sourceSystem,
productId: params.productId,
skuBatchNo: params.skuBatchNo,
fixed: STANDARD_MODEL_WHITE_BG_VIEWS
.map((view) => {
const file = params.fixedImages[view.key]
return file
? {
key: view.key,
name: file.name,
size: Number(file.size || 0),
type: file.type || '',
}
: null
})
.filter(Boolean),
other: params.otherImages.map((file) => ({
name: file.name,
size: Number(file.size || 0),
type: file.type || '',
})),
}
}
async function writeApiLog(params: {
apiKeyId: string
trace: TraceContext
statusCode: number
}) {
await logApiCall({
apiKeyId: params.apiKeyId,
endpoint: ENDPOINT,
method: 'POST',
queryType: 'barcode',
queryValue: params.trace.barcode || undefined,
statusCode: params.statusCode,
duration: getElapsedMs(params.trace.startTime),
ipAddress: params.trace.ipAddress,
userAgent: params.trace.userAgent,
})
}
export async function POST(request: NextRequest) {
const trace: TraceContext = {
traceId: randomUUID(),
startTime: Date.now(),
barcode: '',
ipAddress: getClientIp(request),
userAgent: request.headers.get('user-agent') || undefined,
}
const apiKey = getApiKeyFromRequest(request)
const keyRecord = await validateApiKey(apiKey)
if (!keyRecord) {
return finalizeResponse(
buildErrorResponse(401, 'INVALID_API_KEY', 'API Key 无效或缺失'),
trace,
)
}
trace.apiKeyName = keyRecord.name
let idempotencyRecordId: string | null = null
try {
const formData = await request.formData()
const clientRequestId = String(formData.get('clientRequestId') || '').trim()
const barcode = String(formData.get('barcode') || '').trim()
const sourceTypeRaw = String(formData.get('sourceType') || '').trim()
const sourceSystem = String(formData.get('sourceSystem') || '').trim()
const productId = String(formData.get('productId') || '').trim()
const skuBatchNo = String(formData.get('skuBatchNo') || '').trim()
trace.barcode = barcode
if (!clientRequestId) {
await writeApiLog({ apiKeyId: keyRecord.id, trace, statusCode: 400 })
return finalizeResponse(
buildErrorResponse(400, 'INVALID_CLIENT_REQUEST_ID', 'clientRequestId 不能为空'),
trace,
)
}
if (!barcode) {
await writeApiLog({ apiKeyId: keyRecord.id, trace, statusCode: 400 })
return finalizeResponse(buildErrorResponse(400, 'INVALID_BARCODE', 'barcode 不能为空'), trace)
}
const sourceType = normalizeStandardModelWhiteBackgroundSourceType(sourceTypeRaw)
if (!sourceType) {
await writeApiLog({ apiKeyId: keyRecord.id, trace, statusCode: 400 })
return finalizeResponse(
buildErrorResponse(400, 'INVALID_SOURCE_TYPE', 'sourceType 只能是 实拍、渲染、AI'),
trace,
)
}
const fixedImages = collectFixedImages(formData)
const otherImages = collectOtherImages(formData)
if (countFixedImages(fixedImages) === 0 && otherImages.length === 0) {
await writeApiLog({ apiKeyId: keyRecord.id, trace, statusCode: 400 })
return finalizeResponse(
buildErrorResponse(400, 'MISSING_REQUIRED_VIEWS', '请至少上传 1 张白底图'),
trace,
)
}
const requestHash = stableHashPayload(
buildUploadRequestHashPayload({
clientRequestId,
barcode,
sourceType: sourceTypeRaw,
sourceSystem,
productId,
skuBatchNo,
fixedImages,
otherImages,
}),
)
const idempotency = await startExternalApiIdempotencyRecord({
apiKeyId: keyRecord.id,
operationType: STANDARD_MODEL_WHITE_BACKGROUND_BARCODE_OPERATION.UPLOAD,
clientRequestId,
requestHash,
})
if (idempotency.mode === 'replay') {
await writeApiLog({ apiKeyId: keyRecord.id, trace, statusCode: idempotency.record.responseStatus || 200 })
return finalizeResponse(
NextResponse.json(idempotency.record.responseBody, {
status: idempotency.record.responseStatus || 200,
}),
trace,
)
}
const activeIdempotencyRecordId = String(idempotency.record.id)
idempotencyRecordId = activeIdempotencyRecordId
const resolved = await resolveStandardModelSkuByBarcode(barcode)
const uploadResult = await uploadStandardModelWhiteBackground({
materialId: resolved.materialId,
skuId: resolved.skuId,
skuName: resolved.skuName,
sourceType,
operatorUserId: keyRecord.createdBy,
fixedImages,
otherImages,
})
const responseBody = buildSuccessBody({
materialId: resolved.materialId,
skuId: resolved.skuId,
resolvedSpu: resolved.resolvedSpu,
resolvedSkuName: resolved.resolvedSkuName,
uploadedAt: uploadResult.whiteBackgroundUploadedAt,
traceId: trace.traceId,
whiteBackgroundUploaded: uploadResult.whiteBackgroundUploaded,
uploadedFixedCount: uploadResult.uploadedFixedCount,
fixedCount: uploadResult.fixedCount,
otherCount: uploadResult.otherCount,
whiteBackgroundCount: uploadResult.whiteBackgroundCount,
isComplete: uploadResult.isComplete,
})
await completeExternalApiIdempotencyRecord({
recordId: activeIdempotencyRecordId,
responseStatus: 200,
responseBody,
})
await writeApiLog({ apiKeyId: keyRecord.id, trace, statusCode: 200 })
return finalizeResponse(NextResponse.json(responseBody), trace)
} catch (error) {
if (idempotencyRecordId) {
await failExternalApiIdempotencyRecord(idempotencyRecordId)
}
if (error instanceof ExternalWhiteBackgroundBarcodeError) {
await writeApiLog({ apiKeyId: keyRecord.id, trace, statusCode: error.status })
return finalizeResponse(buildErrorResponse(error.status, error.code, error.message), trace)
}
const message = error instanceof Error ? error.message : '上传白底图失败'
console.error('[external/standard-model-white-background/by-barcode] POST error:', error)
await writeApiLog({ apiKeyId: keyRecord.id, trace, statusCode: 500 })
return finalizeResponse(buildErrorResponse(500, 'UPLOAD_FAILED', message || '上传白底图失败'), trace)
}
}

View File

@ -1,61 +1,21 @@
import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { promises as fs } from 'fs'
import path from 'path'
import { authOptions } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
import { sanitizeFileName } from '@/lib/image-processor'
import { deleteFileIfUnreferenced } from '@/lib/file-cleanup'
import {
buildPublicDisplayUrl,
buildWhiteBackgroundPublicDisplayPath,
buildWhiteBackgroundPublicDisplayPathFromAssetPath,
uploadPublicDisplayToS3,
} from '@/lib/public-display'
import { deleteFromS3 } from '@/lib/s3'
import {
buildWhiteBackgroundFixedFileName,
countWhiteBackgroundFixedViews,
getAllWhiteBackgroundAssetTypesForSku,
getNextWhiteBackgroundOtherIndex,
getWhiteBackgroundAssetWhereForSku,
getWhiteBackgroundOtherAssetType,
getWhiteBackgroundPreviewRelativePathFromAssetPath,
getWhiteBackgroundRelativeDirectory,
getWhiteBackgroundRelativeFilePath,
getWhiteBackgroundViewAssetType,
getWhiteBackgroundZipFileName,
groupWhiteBackgroundAssetsBySku,
hasCompleteWhiteBackgroundAssetGroup,
normalizeWhiteBackgroundSkuName,
STANDARD_MODEL_WHITE_BG_OTHER_FIELD_NAME,
STANDARD_MODEL_WHITE_BG_VIEWS,
type StandardModelWhiteBgKey,
} from '@/lib/standard-model-white-background'
import { normalizeStandardModelWhiteBackgroundSourceType } from '@/lib/standard-model-white-background-metadata'
import { createMaterialLog } from '@/lib/material-log'
import { buildWhiteBackgroundWebpVariants } from '@/lib/white-background-preview'
import { uploadStandardModelWhiteBackground } from '@/lib/standard-model-white-background-service'
export const runtime = 'nodejs'
function resolveSafeOtherBaseName(file: File, index: number): string {
const ext = path.extname(file.name)
const originalBaseName = path.basename(file.name, ext)
return (
sanitizeFileName(originalBaseName || `other-${index}`)
.replace(/\s+/g, '-')
.toLowerCase() || `other-${index}`
)
}
export async function POST(
request: NextRequest,
{ params }: { params: { id: string } },
) {
const writtenFilePaths: string[] = []
const uploadedPreviewUrls: string[] = []
let assetsPersisted = false
try {
const session = await getServerSession(authOptions)
if (!session?.user || !(session.user as any).id) {
@ -136,243 +96,21 @@ export async function POST(
)
}
const existingAssets = await prisma.materialAsset.findMany({
where: {
materialId,
...getWhiteBackgroundAssetWhereForSku(skuId),
},
select: {
id: true,
fileUrl: true,
assetType: true,
sortOrder: true,
},
const result = await uploadStandardModelWhiteBackground({
materialId,
skuId,
skuName: skuName || sku.skuName,
sourceType,
operatorUserId: userId,
fixedImages: whiteBackgroundImages,
otherImages,
})
const existingWhiteBackgroundGroup = groupWhiteBackgroundAssetsBySku(existingAssets).get(skuId)
const nextOtherIndex = getNextWhiteBackgroundOtherIndex(existingWhiteBackgroundGroup)
const assetTypesToReplace = new Set<string>(getAllWhiteBackgroundAssetTypesForSku(skuId))
const normalizedSkuName = normalizeWhiteBackgroundSkuName(skuName || sku.skuName)
const whiteBackgroundCategoryName =
String(material.productCategoryName || '').trim() ||
String(material.categoryName || '').trim()
const uploadDir = path.join(
process.cwd(),
...getWhiteBackgroundRelativeDirectory(materialId, skuId).split('/'),
)
await fs.mkdir(path.join(uploadDir, 'other'), { recursive: true })
const assetsToCreate: Array<{
materialId: string
assetType: string
fileUrl: string
fileName: string
fileSize: bigint
sortOrder: number
}> = []
for (let index = 0; index < STANDARD_MODEL_WHITE_BG_VIEWS.length; index++) {
const view = STANDARD_MODEL_WHITE_BG_VIEWS[index]
const imageFile = whiteBackgroundImages[view.key]
if (!imageFile) {
continue
}
const displayFileName = buildWhiteBackgroundFixedFileName(
normalizedSkuName,
whiteBackgroundCategoryName,
view.label,
'.webp',
)
const diskFileName = displayFileName
const relativePath = getWhiteBackgroundRelativeFilePath(materialId, skuId, diskFileName)
const absolutePath = path.join(process.cwd(), ...relativePath.split('/'))
const sourceBuffer = Buffer.from(await imageFile.arrayBuffer())
const { original, preview } = await buildWhiteBackgroundWebpVariants(sourceBuffer)
assetTypesToReplace.add(getWhiteBackgroundViewAssetType(skuId, view.key))
await fs.mkdir(path.dirname(absolutePath), { recursive: true })
await fs.writeFile(absolutePath, original)
writtenFilePaths.push(relativePath)
const previewUrl = await uploadPublicDisplayToS3(
preview,
buildWhiteBackgroundPublicDisplayPath(materialId, skuId, diskFileName),
'image/webp',
)
uploadedPreviewUrls.push(previewUrl)
assetsToCreate.push({
materialId,
assetType: getWhiteBackgroundViewAssetType(skuId, view.key),
fileUrl: relativePath,
fileName: displayFileName,
fileSize: BigInt(original.length),
sortOrder: index,
})
}
for (let index = 0; index < otherImages.length; index++) {
const imageFile = otherImages[index]
const otherIndex = nextOtherIndex + index
const safeBaseName = resolveSafeOtherBaseName(imageFile, otherIndex)
const displayFileName = `${String(otherIndex).padStart(2, '0')}-${safeBaseName}.webp`
const diskFileName = `other/${displayFileName}`
const relativePath = getWhiteBackgroundRelativeFilePath(materialId, skuId, diskFileName)
const absolutePath = path.join(process.cwd(), ...relativePath.split('/'))
const sourceBuffer = Buffer.from(await imageFile.arrayBuffer())
const { original, preview } = await buildWhiteBackgroundWebpVariants(sourceBuffer)
await fs.mkdir(path.dirname(absolutePath), { recursive: true })
await fs.writeFile(absolutePath, original)
writtenFilePaths.push(relativePath)
const previewUrl = await uploadPublicDisplayToS3(
preview,
buildWhiteBackgroundPublicDisplayPath(materialId, skuId, diskFileName),
'image/webp',
)
uploadedPreviewUrls.push(previewUrl)
assetsToCreate.push({
materialId,
assetType: getWhiteBackgroundOtherAssetType(skuId, otherIndex),
fileUrl: relativePath,
fileName: displayFileName,
fileSize: BigInt(original.length),
sortOrder: 1000 + otherIndex - 1,
})
}
const assetTypeListToReplace = Array.from(assetTypesToReplace)
const replacedAssets = existingAssets.filter((asset) => assetTypeListToReplace.includes(asset.assetType))
const nextFixed: Partial<Record<StandardModelWhiteBgKey, { assetType: string }>> = {
...(existingWhiteBackgroundGroup?.fixed || {}),
}
uploadedFixedViews.forEach((view) => {
nextFixed[view.key] = {
assetType: getWhiteBackgroundViewAssetType(skuId, view.key),
}
})
const nextFixedCount = countWhiteBackgroundFixedViews({ fixed: nextFixed })
const nextOtherCount = (existingWhiteBackgroundGroup?.other.length || 0) + otherImages.length
const whiteBackgroundCount = nextFixedCount + nextOtherCount
const isComplete =
hasCompleteWhiteBackgroundAssetGroup({ fixed: nextFixed }) && nextFixedCount === STANDARD_MODEL_WHITE_BG_VIEWS.length
const uploadedAt = new Date()
await prisma.$transaction(async (tx) => {
if (assetTypeListToReplace.length > 0) {
await tx.materialAsset.deleteMany({
where: {
materialId,
assetType: {
in: assetTypeListToReplace,
},
},
})
}
if (assetsToCreate.length > 0) {
await tx.materialAsset.createMany({
data: assetsToCreate,
})
}
await tx.materialSku.update({
where: { id: skuId },
data: {
whiteBackgroundSourceType: sourceType,
whiteBackgroundUploadedBy: userId,
whiteBackgroundUploadedAt: uploadedAt,
},
})
})
assetsPersisted = true
for (const asset of replacedAssets) {
if (!asset.fileUrl) {
continue
}
await deleteFileIfUnreferenced(asset.fileUrl)
const previewRelativePath = getWhiteBackgroundPreviewRelativePathFromAssetPath(asset.fileUrl)
if (previewRelativePath) {
await deleteFileIfUnreferenced(previewRelativePath)
}
const publicDisplayPath = buildWhiteBackgroundPublicDisplayPathFromAssetPath(asset.fileUrl)
const publicDisplayUrl = publicDisplayPath ? buildPublicDisplayUrl(publicDisplayPath) : null
if (publicDisplayUrl) {
await deleteFileIfUnreferenced(publicDisplayUrl)
}
}
try {
await createMaterialLog({
materialId,
userId,
action: 'UPDATE',
changes: {
whiteBackgroundStorageMode: {
oldValue: existingAssets.length > 0 ? 'replace' : null,
newValue: 'per-image-assets',
},
whiteBackgroundSummary: {
oldValue: null,
newValue: {
uploadedFixedCount: uploadedFixedViews.length,
fixedCount: nextFixedCount,
otherCount: nextOtherCount,
skuId,
skuName: normalizedSkuName,
sourceType,
whiteBackgroundUploadedBy: userId,
whiteBackgroundUploadedAt: uploadedAt.toISOString(),
zipFileName: getWhiteBackgroundZipFileName(normalizedSkuName),
},
},
},
})
} catch (logError) {
console.error('记录白底图上传日志失败:', logError)
}
return NextResponse.json({
success: true,
whiteBackgroundUploaded: whiteBackgroundCount > 0,
uploadedFixedCount: uploadedFixedViews.length,
fixedCount: nextFixedCount,
otherCount: nextOtherCount,
whiteBackgroundCount,
isComplete,
sourceType,
whiteBackgroundUploadedBy: userId,
whiteBackgroundUploadedAt: uploadedAt.toISOString(),
downloadFileName: getWhiteBackgroundZipFileName(normalizedSkuName),
...result,
})
} catch (error) {
if (!assetsPersisted) {
for (const relativePath of writtenFilePaths) {
const absolutePath = path.join(process.cwd(), ...relativePath.split('/'))
try {
await fs.unlink(absolutePath)
} catch {
// ignore cleanup failure
}
}
for (const previewUrl of uploadedPreviewUrls) {
try {
await deleteFromS3(previewUrl)
} catch {
// ignore cleanup failure
}
}
}
console.error('上传白底图失败:', error)
return NextResponse.json({ error: '上传白底图失败' }, { status: 500 })
}

View File

@ -0,0 +1,182 @@
/** @jest-environment node */
import { POST as uploadByBarcode } from '@/app/api/external/standard-model-white-background/by-barcode/route'
import { POST as cleanupByBarcode } from '@/app/api/external/standard-model-white-background/by-barcode/cleanup/route'
import { logApiCall, validateApiKey } from '@/lib/external-api'
import {
completeExternalApiIdempotencyRecord,
resolveStandardModelSkuByBarcode,
startExternalApiIdempotencyRecord,
} from '@/lib/external-standard-model-white-background-by-barcode'
import {
cleanupStandardModelWhiteBackgroundForSku,
uploadStandardModelWhiteBackground,
} from '@/lib/standard-model-white-background-service'
jest.mock('@/lib/external-api', () => ({
getApiKeyFromRequest: jest.fn((request: { headers: Headers }) => request.headers.get('X-API-Key')),
getClientIp: jest.fn(() => '127.0.0.1'),
logApiCall: jest.fn().mockResolvedValue(undefined),
validateApiKey: jest.fn(),
}))
jest.mock('@/lib/external-standard-model-white-background-by-barcode', () => {
const actual = jest.requireActual('@/lib/external-standard-model-white-background-by-barcode')
return {
...actual,
completeExternalApiIdempotencyRecord: jest.fn().mockResolvedValue(undefined),
failExternalApiIdempotencyRecord: jest.fn().mockResolvedValue(undefined),
resolveStandardModelSkuByBarcode: jest.fn(),
startExternalApiIdempotencyRecord: jest.fn(),
}
})
jest.mock('@/lib/standard-model-white-background-service', () => ({
cleanupStandardModelWhiteBackgroundForSku: jest.fn(),
uploadStandardModelWhiteBackground: jest.fn(),
}))
describe('external standard-model-white-background by barcode routes', () => {
beforeEach(() => {
jest.clearAllMocks()
;(validateApiKey as jest.Mock).mockResolvedValue({
id: 'api-1',
name: 'fixture-key',
createdBy: 'user-1',
isActive: true,
})
;(startExternalApiIdempotencyRecord as jest.Mock).mockResolvedValue({
mode: 'created',
record: { id: 'idem-1' },
})
;(resolveStandardModelSkuByBarcode as jest.Mock).mockResolvedValue({
barcode: '690000000001',
materialId: 'material-1',
skuId: 'sku-1',
skuName: 'XG014799',
resolvedSpu: 'XG0147',
resolvedSkuName: 'XG014799',
})
;(uploadStandardModelWhiteBackground as jest.Mock).mockResolvedValue({
whiteBackgroundUploaded: true,
uploadedFixedCount: 1,
fixedCount: 1,
otherCount: 0,
whiteBackgroundCount: 1,
isComplete: false,
sourceType: 'AI',
whiteBackgroundUploadedBy: 'user-1',
whiteBackgroundUploadedAt: '2026-06-08T12:00:00.000Z',
downloadFileName: 'XG014799_白底图.zip',
})
;(cleanupStandardModelWhiteBackgroundForSku as jest.Mock).mockResolvedValue({
deletedAssetCount: 1,
deletedFileCount: 2,
failedFileCount: 0,
clearedMetadata: true,
})
})
function createUploadRequest(formData: FormData) {
return {
headers: new Headers({
'X-API-Key': 'test-key',
'user-agent': 'jest',
}),
formData: jest.fn().mockResolvedValue(formData),
} as any
}
function createCleanupRequest(body: unknown) {
return {
headers: new Headers({
'X-API-Key': 'test-key',
'user-agent': 'jest',
}),
json: jest.fn().mockResolvedValue(body),
} as any
}
test('少于 8 张固定视图也应按现有白底图规则上传', async () => {
const formData = new FormData()
formData.append('clientRequestId', 'req-001')
formData.append('barcode', '690000000001')
formData.append('sourceType', 'AI')
formData.append('sourceSystem', 'furniture-3d-system')
formData.append('productId', 'product-1')
formData.append('skuBatchNo', '1')
formData.append(
'whiteBgRightFront45',
new File([Buffer.from('png-source')], 'right-front-45.png', { type: 'image/png' }),
)
const response = await uploadByBarcode(createUploadRequest(formData))
const body = await response.json()
expect(response.status).toBe(200)
expect(body.success).toBe(true)
expect(body.data).toMatchObject({
materialId: 'material-1',
skuId: 'sku-1',
traceId: expect.any(String),
uploadedFixedCount: 1,
isComplete: false,
})
expect(uploadStandardModelWhiteBackground).toHaveBeenCalledWith(
expect.objectContaining({
materialId: 'material-1',
skuId: 'sku-1',
sourceType: 'AI',
operatorUserId: 'user-1',
}),
)
expect(completeExternalApiIdempotencyRecord).toHaveBeenCalled()
expect(logApiCall).toHaveBeenCalledWith(expect.objectContaining({ statusCode: 200 }))
})
test('没有任何有效白底图时才返回 MISSING_REQUIRED_VIEWS', async () => {
const formData = new FormData()
formData.append('clientRequestId', 'req-002')
formData.append('barcode', '690000000001')
formData.append('sourceType', 'AI')
const response = await uploadByBarcode(createUploadRequest(formData))
const body = await response.json()
expect(response.status).toBe(400)
expect(body).toEqual({
success: false,
error: {
code: 'MISSING_REQUIRED_VIEWS',
message: '请至少上传 1 张白底图',
},
})
expect(uploadStandardModelWhiteBackground).not.toHaveBeenCalled()
})
test('cleanup 只按条码解析到的 SKU 调用 SKU 范围清理', async () => {
const response = await cleanupByBarcode(
createCleanupRequest({
clientRequestId: 'cleanup-001',
reason: 'replace-upload',
mode: 'soft',
skuBatchNo: 1,
barcodes: ['690000000001'],
}),
)
const body = await response.json()
expect(response.status).toBe(200)
expect(body.success).toBe(true)
expect(body.data).toMatchObject({
traceId: expect.any(String),
cleanedCount: 1,
})
expect(cleanupStandardModelWhiteBackgroundForSku).toHaveBeenCalledWith({
materialId: 'material-1',
skuId: 'sku-1',
operatorUserId: 'user-1',
reason: 'replace-upload',
})
})
})

View File

@ -87,6 +87,7 @@ export async function validateApiKey(apiKey: string | null) {
id: true,
name: true,
isActive: true,
createdBy: true,
},
});

View File

@ -0,0 +1,421 @@
import crypto from 'crypto'
import { Prisma } from '@prisma/client'
import { prisma } from '@/lib/prisma'
export const STANDARD_MODEL_WHITE_BACKGROUND_BARCODE_OPERATION = {
UPLOAD: 'standard-model-white-background.by-barcode.upload',
CLEANUP: 'standard-model-white-background.by-barcode.cleanup',
} as const
export type BarcodeOperationType =
typeof STANDARD_MODEL_WHITE_BACKGROUND_BARCODE_OPERATION[keyof typeof STANDARD_MODEL_WHITE_BACKGROUND_BARCODE_OPERATION]
export class ExternalWhiteBackgroundBarcodeError extends Error {
status: number
code: string
constructor(status: number, code: string, message: string) {
super(message)
this.status = status
this.code = code
}
}
export type ResolvedStandardModelSkuByBarcode = {
barcode: string
materialId: string
skuId: string
skuName: string
resolvedSpu: string
resolvedSkuName: string
}
let supportTablesInitialized = false
async function executeRaw(sql: string) {
try {
await prisma.$executeRawUnsafe(sql)
} catch (error) {
console.error('[external-white-background-by-barcode] 执行 SQL 失败:', error)
}
}
export async function ensureStandardModelWhiteBackgroundBarcodeSupportTables() {
if (supportTablesInitialized) {
return
}
await executeRaw(`
CREATE TABLE IF NOT EXISTS "material_sku_barcodes" (
"id" TEXT PRIMARY KEY,
"sku_id" TEXT NOT NULL,
"barcode" TEXT NOT NULL,
"deleted_at" TIMESTAMP(3),
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP
)
`)
await executeRaw(`
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1
FROM pg_constraint
WHERE conname = 'material_sku_barcodes_sku_id_fkey'
) THEN
ALTER TABLE "material_sku_barcodes"
ADD CONSTRAINT "material_sku_barcodes_sku_id_fkey"
FOREIGN KEY ("sku_id") REFERENCES "material_skus"("id")
ON DELETE CASCADE ON UPDATE CASCADE;
END IF;
END
$$;
`)
await executeRaw(`
CREATE UNIQUE INDEX IF NOT EXISTS "material_sku_barcodes_barcode_active_key"
ON "material_sku_barcodes" ("barcode")
WHERE "deleted_at" IS NULL
`)
await executeRaw(`CREATE INDEX IF NOT EXISTS "material_sku_barcodes_barcode_idx" ON "material_sku_barcodes" ("barcode")`)
await executeRaw(`CREATE INDEX IF NOT EXISTS "material_sku_barcodes_sku_id_idx" ON "material_sku_barcodes" ("sku_id")`)
await executeRaw(`CREATE INDEX IF NOT EXISTS "material_sku_barcodes_deleted_at_idx" ON "material_sku_barcodes" ("deleted_at")`)
await executeRaw(`
CREATE TABLE IF NOT EXISTS "external_api_idempotency_records" (
"id" TEXT PRIMARY KEY,
"api_key_id" TEXT NOT NULL,
"operation_type" TEXT NOT NULL,
"client_request_id" TEXT NOT NULL,
"request_hash" TEXT NOT NULL,
"status" TEXT NOT NULL,
"response_status" INTEGER,
"response_body" JSONB,
"completed_at" TIMESTAMP(3),
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP
)
`)
await executeRaw(`
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1
FROM pg_constraint
WHERE conname = 'external_api_idempotency_records_api_key_id_fkey'
) THEN
ALTER TABLE "external_api_idempotency_records"
ADD CONSTRAINT "external_api_idempotency_records_api_key_id_fkey"
FOREIGN KEY ("api_key_id") REFERENCES "api_keys"("id")
ON DELETE CASCADE ON UPDATE CASCADE;
END IF;
END
$$;
`)
await executeRaw(`
CREATE UNIQUE INDEX IF NOT EXISTS "external_api_idempotency_records_api_key_operation_client_key"
ON "external_api_idempotency_records" ("api_key_id", "operation_type", "client_request_id")
`)
await executeRaw(`CREATE INDEX IF NOT EXISTS "external_api_idempotency_records_api_key_id_idx" ON "external_api_idempotency_records" ("api_key_id")`)
await executeRaw(`CREATE INDEX IF NOT EXISTS "external_api_idempotency_records_operation_type_idx" ON "external_api_idempotency_records" ("operation_type")`)
await executeRaw(`CREATE INDEX IF NOT EXISTS "external_api_idempotency_records_client_request_id_idx" ON "external_api_idempotency_records" ("client_request_id")`)
await executeRaw(`CREATE INDEX IF NOT EXISTS "external_api_idempotency_records_status_idx" ON "external_api_idempotency_records" ("status")`)
await executeRaw(`CREATE INDEX IF NOT EXISTS "external_api_idempotency_records_created_at_idx" ON "external_api_idempotency_records" ("created_at")`)
supportTablesInitialized = true
}
export function normalizeExternalBarcode(value: unknown) {
return String(value || '').trim()
}
export function stableHashPayload(payload: unknown) {
return crypto
.createHash('sha256')
.update(JSON.stringify(sortPayload(payload)))
.digest('hex')
}
function sortPayload(payload: unknown): unknown {
if (Array.isArray(payload)) {
return payload.map(sortPayload)
}
if (payload && typeof payload === 'object') {
return Object.keys(payload as Record<string, unknown>)
.sort()
.reduce((acc, key) => {
acc[key] = sortPayload((payload as Record<string, unknown>)[key])
return acc
}, {} as Record<string, unknown>)
}
return payload
}
export async function startExternalApiIdempotencyRecord(input: {
apiKeyId: string
operationType: BarcodeOperationType
clientRequestId: string
requestHash: string
}) {
await ensureStandardModelWhiteBackgroundBarcodeSupportTables()
if (!input.clientRequestId.trim()) {
throw new ExternalWhiteBackgroundBarcodeError(400, 'INVALID_CLIENT_REQUEST_ID', 'clientRequestId 不能为空')
}
try {
const result = await prisma.$transaction(
async (tx: any) => {
const existing = await tx.externalApiIdempotencyRecord.findUnique({
where: {
apiKeyId_operationType_clientRequestId: {
apiKeyId: input.apiKeyId,
operationType: input.operationType,
clientRequestId: input.clientRequestId,
},
},
})
if (existing) {
if (existing.requestHash !== input.requestHash) {
throw new ExternalWhiteBackgroundBarcodeError(
409,
'IDEMPOTENCY_CONFLICT',
'同一个 clientRequestId 已用于不同请求,请更换 clientRequestId',
)
}
if (existing.status === 'succeeded' && existing.responseBody && existing.responseStatus) {
return {
mode: 'replay' as const,
record: existing,
}
}
if (existing.status === 'failed') {
const record = await tx.externalApiIdempotencyRecord.update({
where: { id: existing.id },
data: {
status: 'processing',
responseStatus: null,
responseBody: Prisma.JsonNull,
completedAt: null,
},
})
return {
mode: 'created' as const,
record,
}
}
throw new ExternalWhiteBackgroundBarcodeError(
409,
'IDEMPOTENCY_CONFLICT',
'同一个 clientRequestId 的请求仍在处理中,请稍后重试',
)
}
const record = await tx.externalApiIdempotencyRecord.create({
data: {
apiKeyId: input.apiKeyId,
operationType: input.operationType,
clientRequestId: input.clientRequestId,
requestHash: input.requestHash,
status: 'processing',
},
})
return {
mode: 'created' as const,
record,
}
},
{
isolationLevel: Prisma.TransactionIsolationLevel.Serializable,
},
)
return result
} catch (error: any) {
if (error instanceof ExternalWhiteBackgroundBarcodeError) {
throw error
}
if (error?.code === 'P2002') {
const existing = await (prisma as any).externalApiIdempotencyRecord.findUnique({
where: {
apiKeyId_operationType_clientRequestId: {
apiKeyId: input.apiKeyId,
operationType: input.operationType,
clientRequestId: input.clientRequestId,
},
},
})
if (existing?.requestHash !== input.requestHash) {
throw new ExternalWhiteBackgroundBarcodeError(
409,
'IDEMPOTENCY_CONFLICT',
'同一个 clientRequestId 已用于不同请求,请更换 clientRequestId',
)
}
if (existing?.status === 'succeeded' && existing.responseBody && existing.responseStatus) {
return {
mode: 'replay' as const,
record: existing,
}
}
if (existing?.status === 'failed') {
const record = await (prisma as any).externalApiIdempotencyRecord.update({
where: { id: existing.id },
data: {
status: 'processing',
responseStatus: null,
responseBody: Prisma.JsonNull,
completedAt: null,
},
})
return {
mode: 'created' as const,
record,
}
}
throw new ExternalWhiteBackgroundBarcodeError(
409,
'IDEMPOTENCY_CONFLICT',
'同一个 clientRequestId 的请求仍在处理中,请稍后重试',
)
}
throw error
}
}
export async function completeExternalApiIdempotencyRecord(input: {
recordId: string
responseStatus: number
responseBody: unknown
}) {
await (prisma as any).externalApiIdempotencyRecord.update({
where: { id: input.recordId },
data: {
status: 'succeeded',
responseStatus: input.responseStatus,
responseBody: input.responseBody,
completedAt: new Date(),
},
})
}
export async function failExternalApiIdempotencyRecord(recordId: string) {
try {
await (prisma as any).externalApiIdempotencyRecord.update({
where: { id: recordId },
data: {
status: 'failed',
},
})
} catch (error) {
console.error('[external-white-background-by-barcode] 更新幂等失败状态失败:', error)
}
}
export async function resolveStandardModelSkuByBarcode(
barcode: string,
): Promise<ResolvedStandardModelSkuByBarcode> {
await ensureStandardModelWhiteBackgroundBarcodeSupportTables()
const normalizedBarcode = normalizeExternalBarcode(barcode)
if (!normalizedBarcode) {
throw new ExternalWhiteBackgroundBarcodeError(400, 'INVALID_BARCODE', 'barcode 不能为空')
}
const matches = await (prisma as any).materialSkuBarcode.findMany({
where: {
barcode: normalizedBarcode,
deletedAt: null,
},
select: {
id: true,
barcode: true,
sku: {
select: {
id: true,
skuName: true,
deletedAt: true,
materialId: true,
material: {
select: {
id: true,
productModel: true,
materialType: true,
deletedAt: true,
},
},
},
},
},
take: 3,
})
if (matches.length === 0) {
throw new ExternalWhiteBackgroundBarcodeError(404, 'BARCODE_NOT_FOUND', '未找到对应的标准模型 SKU 条码绑定')
}
const validTargets = matches.filter((match: any) => match.sku)
const activeSkuIds = Array.from(new Set(validTargets.map((match: any) => String(match.sku.id))))
if (activeSkuIds.length > 1 || matches.length > 1) {
throw new ExternalWhiteBackgroundBarcodeError(409, 'BARCODE_AMBIGUOUS', '该 barcode 绑定了多个 SKU,无法确定唯一标准模型 SKU')
}
const match = validTargets[0]
const sku = match?.sku
const material = sku?.material
if (!sku) {
throw new ExternalWhiteBackgroundBarcodeError(404, 'BARCODE_NOT_FOUND', '未找到对应的标准模型 SKU 条码绑定')
}
if (sku.deletedAt) {
throw new ExternalWhiteBackgroundBarcodeError(410, 'SKU_DELETED', '该 barcode 绑定的 SKU 已被删除')
}
if (!material) {
throw new ExternalWhiteBackgroundBarcodeError(
404,
'BARCODE_NOT_BOUND_TO_STANDARD_MODEL_SKU',
'该 barcode 未绑定到有效标准模型素材',
)
}
if (material.deletedAt) {
throw new ExternalWhiteBackgroundBarcodeError(410, 'MATERIAL_DELETED', '该 barcode 绑定的素材已被删除')
}
if (material.materialType !== '标准模型') {
throw new ExternalWhiteBackgroundBarcodeError(
400,
'BARCODE_NOT_BOUND_TO_STANDARD_MODEL_SKU',
'该 barcode 绑定的不是标准模型 SKU',
)
}
return {
barcode: normalizedBarcode,
materialId: sku.materialId,
skuId: sku.id,
skuName: sku.skuName,
resolvedSpu: material.productModel,
resolvedSkuName: sku.skuName,
}
}

View File

@ -0,0 +1,479 @@
import { promises as fs } from 'fs'
import path from 'path'
import { prisma } from '@/lib/prisma'
import { sanitizeFileName } from '@/lib/image-processor'
import { deleteFileIfUnreferenced } from '@/lib/file-cleanup'
import { createMaterialLog } from '@/lib/material-log'
import {
buildPublicDisplayUrl,
buildWhiteBackgroundPublicDisplayPath,
buildWhiteBackgroundPublicDisplayPathFromAssetPath,
uploadPublicDisplayToS3,
} from '@/lib/public-display'
import { deleteFromS3 } from '@/lib/s3'
import {
buildWhiteBackgroundFixedFileName,
countWhiteBackgroundFixedViews,
getAllWhiteBackgroundAssetTypesForSku,
getCurrentWhiteBackgroundAssetType,
LEGACY_STANDARD_MODEL_WHITE_BG_ASSET_TYPE_PREFIX,
getNextWhiteBackgroundOtherIndex,
getWhiteBackgroundAssetWhereForSku,
getWhiteBackgroundOtherAssetPrefixForSku,
getWhiteBackgroundOtherAssetType,
getWhiteBackgroundPreviewRelativePathFromAssetPath,
getWhiteBackgroundRelativeDirectory,
getWhiteBackgroundRelativeFilePath,
getWhiteBackgroundViewAssetPrefixForSku,
getWhiteBackgroundViewAssetType,
getWhiteBackgroundZipFileName,
groupWhiteBackgroundAssetsBySku,
hasCompleteWhiteBackgroundAssetGroup,
normalizeWhiteBackgroundSkuName,
STANDARD_MODEL_WHITE_BG_VIEWS,
type GroupedWhiteBackgroundAssets,
type StandardModelWhiteBgKey,
type WhiteBackgroundAssetLike,
} from '@/lib/standard-model-white-background'
import type { StandardModelWhiteBackgroundSourceType } from '@/lib/standard-model-white-background-metadata'
import { buildWhiteBackgroundWebpVariants } from '@/lib/white-background-preview'
type WhiteBackgroundAssetRecord = WhiteBackgroundAssetLike & {
id: string
fileUrl: string
assetType: string
sortOrder: number
}
export type WhiteBackgroundUploadInput = {
materialId: string
skuId: string
skuName: string
sourceType: StandardModelWhiteBackgroundSourceType
operatorUserId: string
fixedImages: Partial<Record<StandardModelWhiteBgKey, File | null>>
otherImages?: File[]
}
export type WhiteBackgroundUploadResult = {
whiteBackgroundUploaded: boolean
uploadedFixedCount: number
fixedCount: number
otherCount: number
whiteBackgroundCount: number
isComplete: boolean
sourceType: StandardModelWhiteBackgroundSourceType
whiteBackgroundUploadedBy: string
whiteBackgroundUploadedAt: string
downloadFileName: string
}
export type WhiteBackgroundCleanupResult = {
deletedAssetCount: number
deletedFileCount: number
failedFileCount: number
clearedMetadata: boolean
}
function resolveSafeOtherBaseName(file: File, index: number): string {
const ext = path.extname(file.name)
const originalBaseName = path.basename(file.name, ext)
return (
sanitizeFileName(originalBaseName || `other-${index}`)
.replace(/\s+/g, '-')
.toLowerCase() || `other-${index}`
)
}
function isUsableFile(file: File | null | undefined): file is File {
return (
!!file &&
typeof file.name === 'string' &&
typeof file.arrayBuffer === 'function' &&
Number(file.size || 0) > 0
)
}
function getUploadedFixedViews(fixedImages: Partial<Record<StandardModelWhiteBgKey, File | null>>) {
return STANDARD_MODEL_WHITE_BG_VIEWS.filter((view) => isUsableFile(fixedImages[view.key]))
}
async function deleteReplacedAssetFiles(assets: Array<{ id?: string; fileUrl?: string | null }>) {
let deletedFileCount = 0
let failedFileCount = 0
for (const asset of assets) {
if (!asset.fileUrl) {
continue
}
const targets = [
asset.fileUrl,
getWhiteBackgroundPreviewRelativePathFromAssetPath(asset.fileUrl),
(() => {
const publicDisplayPath = buildWhiteBackgroundPublicDisplayPathFromAssetPath(asset.fileUrl)
return publicDisplayPath ? buildPublicDisplayUrl(publicDisplayPath) : null
})(),
].filter((value): value is string => Boolean(value))
for (const target of targets) {
const result = await deleteFileIfUnreferenced(target, asset.id ? { excludeAssetIds: [asset.id] } : undefined)
if (result.success) {
if (!result.skipped) {
deletedFileCount += 1
}
} else {
failedFileCount += 1
}
}
}
return { deletedFileCount, failedFileCount }
}
function getScopedWhiteBackgroundAssetWhereForSku(skuId: string) {
return {
OR: [
{ assetType: getCurrentWhiteBackgroundAssetType(skuId) },
{ assetType: `${LEGACY_STANDARD_MODEL_WHITE_BG_ASSET_TYPE_PREFIX}${skuId}` },
{ assetType: { startsWith: getWhiteBackgroundViewAssetPrefixForSku(skuId) } },
{ assetType: { startsWith: getWhiteBackgroundOtherAssetPrefixForSku(skuId) } },
],
}
}
export async function uploadStandardModelWhiteBackground(
input: WhiteBackgroundUploadInput,
): Promise<WhiteBackgroundUploadResult> {
const writtenFilePaths: string[] = []
const uploadedPreviewUrls: string[] = []
let assetsPersisted = false
try {
const material = await prisma.material.findUnique({
where: { id: input.materialId },
select: {
id: true,
materialType: true,
productCategoryName: true,
categoryName: true,
},
})
if (!material) {
throw new Error('素材不存在')
}
if (material.materialType !== '标准模型') {
throw new Error('只有标准模型类型支持上传白底图')
}
const sku = await prisma.materialSku.findFirst({
where: {
id: input.skuId,
materialId: input.materialId,
deletedAt: null,
},
select: { id: true, skuName: true },
})
if (!sku) {
throw new Error('SKU不存在或已被删除')
}
const otherImages = (input.otherImages || []).filter(isUsableFile)
const uploadedFixedViews = getUploadedFixedViews(input.fixedImages)
if (uploadedFixedViews.length === 0 && otherImages.length === 0) {
throw new Error('请至少上传 1 张白底图')
}
const existingAssets = await prisma.materialAsset.findMany({
where: {
materialId: input.materialId,
...getWhiteBackgroundAssetWhereForSku(input.skuId),
},
select: {
id: true,
fileUrl: true,
assetType: true,
sortOrder: true,
},
})
const existingWhiteBackgroundGroup = groupWhiteBackgroundAssetsBySku(existingAssets).get(input.skuId)
const nextOtherIndex = getNextWhiteBackgroundOtherIndex(existingWhiteBackgroundGroup)
const assetTypesToReplace = new Set<string>(getAllWhiteBackgroundAssetTypesForSku(input.skuId))
const normalizedSkuName = normalizeWhiteBackgroundSkuName(input.skuName || sku.skuName)
const whiteBackgroundCategoryName =
String(material.productCategoryName || '').trim() ||
String(material.categoryName || '').trim()
const uploadDir = path.join(
process.cwd(),
...getWhiteBackgroundRelativeDirectory(input.materialId, input.skuId).split('/'),
)
await fs.mkdir(path.join(uploadDir, 'other'), { recursive: true })
const assetsToCreate: Array<{
materialId: string
assetType: string
fileUrl: string
fileName: string
fileSize: bigint
sortOrder: number
}> = []
for (let index = 0; index < STANDARD_MODEL_WHITE_BG_VIEWS.length; index++) {
const view = STANDARD_MODEL_WHITE_BG_VIEWS[index]
const imageFile = input.fixedImages[view.key]
if (!isUsableFile(imageFile)) {
continue
}
const displayFileName = buildWhiteBackgroundFixedFileName(
normalizedSkuName,
whiteBackgroundCategoryName,
view.label,
'.webp',
)
const diskFileName = displayFileName
const relativePath = getWhiteBackgroundRelativeFilePath(input.materialId, input.skuId, diskFileName)
const absolutePath = path.join(process.cwd(), ...relativePath.split('/'))
const sourceBuffer = Buffer.from(await imageFile.arrayBuffer())
const { original, preview } = await buildWhiteBackgroundWebpVariants(sourceBuffer)
assetTypesToReplace.add(getWhiteBackgroundViewAssetType(input.skuId, view.key))
await fs.mkdir(path.dirname(absolutePath), { recursive: true })
await fs.writeFile(absolutePath, original)
writtenFilePaths.push(relativePath)
const previewUrl = await uploadPublicDisplayToS3(
preview,
buildWhiteBackgroundPublicDisplayPath(input.materialId, input.skuId, diskFileName),
'image/webp',
)
uploadedPreviewUrls.push(previewUrl)
assetsToCreate.push({
materialId: input.materialId,
assetType: getWhiteBackgroundViewAssetType(input.skuId, view.key),
fileUrl: relativePath,
fileName: displayFileName,
fileSize: BigInt(original.length),
sortOrder: index,
})
}
for (let index = 0; index < otherImages.length; index++) {
const imageFile = otherImages[index]
const otherIndex = nextOtherIndex + index
const safeBaseName = resolveSafeOtherBaseName(imageFile, otherIndex)
const displayFileName = `${String(otherIndex).padStart(2, '0')}-${safeBaseName}.webp`
const diskFileName = `other/${displayFileName}`
const relativePath = getWhiteBackgroundRelativeFilePath(input.materialId, input.skuId, diskFileName)
const absolutePath = path.join(process.cwd(), ...relativePath.split('/'))
const sourceBuffer = Buffer.from(await imageFile.arrayBuffer())
const { original, preview } = await buildWhiteBackgroundWebpVariants(sourceBuffer)
await fs.mkdir(path.dirname(absolutePath), { recursive: true })
await fs.writeFile(absolutePath, original)
writtenFilePaths.push(relativePath)
const previewUrl = await uploadPublicDisplayToS3(
preview,
buildWhiteBackgroundPublicDisplayPath(input.materialId, input.skuId, diskFileName),
'image/webp',
)
uploadedPreviewUrls.push(previewUrl)
assetsToCreate.push({
materialId: input.materialId,
assetType: getWhiteBackgroundOtherAssetType(input.skuId, otherIndex),
fileUrl: relativePath,
fileName: displayFileName,
fileSize: BigInt(original.length),
sortOrder: 1000 + otherIndex - 1,
})
}
const assetTypeListToReplace = Array.from(assetTypesToReplace)
const replacedAssets = existingAssets.filter((asset) => assetTypeListToReplace.includes(asset.assetType))
const nextFixed: Partial<Record<StandardModelWhiteBgKey, { assetType: string }>> = {
...(existingWhiteBackgroundGroup?.fixed || {}),
}
uploadedFixedViews.forEach((view) => {
nextFixed[view.key] = {
assetType: getWhiteBackgroundViewAssetType(input.skuId, view.key),
}
})
const nextFixedCount = countWhiteBackgroundFixedViews({ fixed: nextFixed })
const nextOtherCount = (existingWhiteBackgroundGroup?.other.length || 0) + otherImages.length
const whiteBackgroundCount = nextFixedCount + nextOtherCount
const isComplete =
hasCompleteWhiteBackgroundAssetGroup({ fixed: nextFixed }) && nextFixedCount === STANDARD_MODEL_WHITE_BG_VIEWS.length
const uploadedAt = new Date()
await prisma.$transaction(async (tx) => {
if (assetTypeListToReplace.length > 0) {
await tx.materialAsset.deleteMany({
where: {
materialId: input.materialId,
assetType: {
in: assetTypeListToReplace,
},
},
})
}
if (assetsToCreate.length > 0) {
await tx.materialAsset.createMany({
data: assetsToCreate,
})
}
await tx.materialSku.update({
where: { id: input.skuId },
data: {
whiteBackgroundSourceType: input.sourceType,
whiteBackgroundUploadedBy: input.operatorUserId,
whiteBackgroundUploadedAt: uploadedAt,
},
})
})
assetsPersisted = true
await deleteReplacedAssetFiles(replacedAssets)
try {
await createMaterialLog({
materialId: input.materialId,
userId: input.operatorUserId,
action: 'UPDATE',
changes: {
whiteBackgroundStorageMode: {
oldValue: existingAssets.length > 0 ? 'replace' : null,
newValue: 'per-image-assets',
},
whiteBackgroundSummary: {
oldValue: null,
newValue: {
uploadedFixedCount: uploadedFixedViews.length,
fixedCount: nextFixedCount,
otherCount: nextOtherCount,
skuId: input.skuId,
skuName: normalizedSkuName,
sourceType: input.sourceType,
whiteBackgroundUploadedBy: input.operatorUserId,
whiteBackgroundUploadedAt: uploadedAt.toISOString(),
zipFileName: getWhiteBackgroundZipFileName(normalizedSkuName),
},
},
},
})
} catch (logError) {
console.error('记录白底图上传日志失败:', logError)
}
return {
whiteBackgroundUploaded: whiteBackgroundCount > 0,
uploadedFixedCount: uploadedFixedViews.length,
fixedCount: nextFixedCount,
otherCount: nextOtherCount,
whiteBackgroundCount,
isComplete,
sourceType: input.sourceType,
whiteBackgroundUploadedBy: input.operatorUserId,
whiteBackgroundUploadedAt: uploadedAt.toISOString(),
downloadFileName: getWhiteBackgroundZipFileName(normalizedSkuName),
}
} catch (error) {
if (!assetsPersisted) {
for (const relativePath of writtenFilePaths) {
const absolutePath = path.join(process.cwd(), ...relativePath.split('/'))
try {
await fs.unlink(absolutePath)
} catch {
// ignore cleanup failure
}
}
for (const previewUrl of uploadedPreviewUrls) {
try {
await deleteFromS3(previewUrl)
} catch {
// ignore cleanup failure
}
}
}
throw error
}
}
export async function cleanupStandardModelWhiteBackgroundForSku(input: {
materialId: string
skuId: string
operatorUserId: string
reason?: string
}): Promise<WhiteBackgroundCleanupResult> {
const assets = await prisma.materialAsset.findMany({
where: {
materialId: input.materialId,
...getScopedWhiteBackgroundAssetWhereForSku(input.skuId),
},
select: {
id: true,
fileUrl: true,
assetType: true,
sortOrder: true,
},
})
await prisma.$transaction(async (tx) => {
await tx.materialAsset.deleteMany({
where: {
materialId: input.materialId,
...getScopedWhiteBackgroundAssetWhereForSku(input.skuId),
},
})
await tx.materialSku.update({
where: { id: input.skuId },
data: {
whiteBackgroundSourceType: null,
whiteBackgroundUploadedBy: null,
whiteBackgroundUploadedAt: null,
},
})
})
const fileResult = await deleteReplacedAssetFiles(assets)
try {
await createMaterialLog({
materialId: input.materialId,
userId: input.operatorUserId,
action: 'UPDATE',
changes: {
whiteBackgroundCleanup: {
oldValue: null,
newValue: {
skuId: input.skuId,
reason: input.reason || '',
deletedAssetCount: assets.length,
},
},
},
})
} catch (logError) {
console.error('记录白底图清理日志失败:', logError)
}
return {
deletedAssetCount: assets.length,
deletedFileCount: fileResult.deletedFileCount,
failedFileCount: fileResult.failedFileCount,
clearedMetadata: true,
}
}

View File

@ -0,0 +1,59 @@
CREATE TABLE IF NOT EXISTS "material_sku_barcodes" (
"id" TEXT PRIMARY KEY,
"sku_id" TEXT NOT NULL,
"barcode" TEXT NOT NULL,
"deleted_at" TIMESTAMP(3),
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "material_sku_barcodes_sku_id_fkey"
FOREIGN KEY ("sku_id") REFERENCES "material_skus"("id")
ON DELETE CASCADE ON UPDATE CASCADE
);
CREATE UNIQUE INDEX IF NOT EXISTS "material_sku_barcodes_barcode_active_key"
ON "material_sku_barcodes" ("barcode")
WHERE "deleted_at" IS NULL;
CREATE INDEX IF NOT EXISTS "material_sku_barcodes_barcode_idx"
ON "material_sku_barcodes" ("barcode");
CREATE INDEX IF NOT EXISTS "material_sku_barcodes_sku_id_idx"
ON "material_sku_barcodes" ("sku_id");
CREATE INDEX IF NOT EXISTS "material_sku_barcodes_deleted_at_idx"
ON "material_sku_barcodes" ("deleted_at");
CREATE TABLE IF NOT EXISTS "external_api_idempotency_records" (
"id" TEXT PRIMARY KEY,
"api_key_id" TEXT NOT NULL,
"operation_type" TEXT NOT NULL,
"client_request_id" TEXT NOT NULL,
"request_hash" TEXT NOT NULL,
"status" TEXT NOT NULL,
"response_status" INTEGER,
"response_body" JSONB,
"completed_at" TIMESTAMP(3),
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "external_api_idempotency_records_api_key_id_fkey"
FOREIGN KEY ("api_key_id") REFERENCES "api_keys"("id")
ON DELETE CASCADE ON UPDATE CASCADE
);
CREATE UNIQUE INDEX IF NOT EXISTS "external_api_idempotency_records_api_key_operation_client_key"
ON "external_api_idempotency_records" ("api_key_id", "operation_type", "client_request_id");
CREATE INDEX IF NOT EXISTS "external_api_idempotency_records_api_key_id_idx"
ON "external_api_idempotency_records" ("api_key_id");
CREATE INDEX IF NOT EXISTS "external_api_idempotency_records_operation_type_idx"
ON "external_api_idempotency_records" ("operation_type");
CREATE INDEX IF NOT EXISTS "external_api_idempotency_records_client_request_id_idx"
ON "external_api_idempotency_records" ("client_request_id");
CREATE INDEX IF NOT EXISTS "external_api_idempotency_records_status_idx"
ON "external_api_idempotency_records" ("status");
CREATE INDEX IF NOT EXISTS "external_api_idempotency_records_created_at_idx"
ON "external_api_idempotency_records" ("created_at");

View File

@ -207,6 +207,7 @@ model MaterialSku {
whiteBackgroundSourceType String? @map("white_background_source_type")
whiteBackgroundUploadedBy String? @map("white_background_uploaded_by")
whiteBackgroundUploadedAt DateTime? @map("white_background_uploaded_at")
barcodes MaterialSkuBarcode[]
material Material @relation(fields: [materialId], references: [id], onDelete: Cascade)
@@index([materialId])
@ -382,6 +383,21 @@ model MaterialAssetBarcode {
@@map("material_asset_barcodes")
}
model MaterialSkuBarcode {
id String @id @default(uuid())
skuId String @map("sku_id")
barcode String
deletedAt DateTime? @map("deleted_at")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
sku MaterialSku @relation(fields: [skuId], references: [id], onDelete: Cascade)
@@index([barcode])
@@index([skuId])
@@index([deletedAt])
@@map("material_sku_barcodes")
}
model ApiKey {
id String @id @default(uuid())
name String
@ -393,12 +409,36 @@ model ApiKey {
updatedAt DateTime @updatedAt @map("updated_at")
callLogs ApiCallLog[]
externalMaterialImportJobs ExternalMaterialImportJob[]
idempotencyRecords ExternalApiIdempotencyRecord[]
@@index([key])
@@index([isActive])
@@map("api_keys")
}
model ExternalApiIdempotencyRecord {
id String @id @default(uuid())
apiKeyId String @map("api_key_id")
operationType String @map("operation_type")
clientRequestId String @map("client_request_id")
requestHash String @map("request_hash")
status String
responseStatus Int? @map("response_status")
responseBody Json? @map("response_body")
completedAt DateTime? @map("completed_at")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
apiKey ApiKey @relation(fields: [apiKeyId], references: [id], onDelete: Cascade)
@@unique([apiKeyId, operationType, clientRequestId])
@@index([apiKeyId])
@@index([operationType])
@@index([clientRequestId])
@@index([status])
@@index([createdAt])
@@map("external_api_idempotency_records")
}
model ApiCallLog {
id String @id @default(uuid())
apiKeyId String @map("api_key_id")