513 lines
22 KiB
TypeScript
513 lines
22 KiB
TypeScript
import { randomUUID } from 'crypto'
|
|
import { link, lstat, rename, unlink, writeFile } from 'fs/promises'
|
|
import path from 'path'
|
|
import { lookup as lookupMimeType } from 'mime-types'
|
|
import { getServerSession } from 'next-auth'
|
|
import { NextResponse } from 'next/server'
|
|
import { authOptions } from '@/lib/auth'
|
|
import { assertBrandCenterDashboardAccess, BrandCenterDashboardAccessError } from '@/lib/brand-center-dashboard-access'
|
|
import { prisma } from '@/lib/prisma'
|
|
import { isSuperAdmin } from '@/lib/department-permission'
|
|
import { getUploadRootDir } from '@/lib/upload-paths'
|
|
import { ensureSafeDirectoryWithinRoot, isPathFreeOfSymbolicLinks, normalizeSafeFileName, resolveStrictChildPath } from '@/lib/path-security'
|
|
import { normalizeUploadFileName } from '@/lib/upload-file-name'
|
|
import { assertBoundedMultipartHeaders, assertMultipartFiles } from '@/lib/multipart-request-guard'
|
|
import { boundedMultipartRequestLimiter, getBoundedMultipartFailure } from '@/lib/multipart-route-limits'
|
|
import { prepareBrandKnowledgePreview, validateBrandKnowledgeUploadedPreviewSlices } from '@/lib/brand-knowledge-preview'
|
|
import { isWebFileLike } from '@/lib/web-file'
|
|
import { isSafeUploadId, resolveOwnedMergedUpload } from '@/lib/upload-sessions'
|
|
import {
|
|
acquireTaskMaterialUploadSessionLocks,
|
|
type MaterialUploadStorageLockRelease,
|
|
} from '@/lib/material-upload-cross-process-lock'
|
|
import { readUploadSessionSeal } from '@/lib/material-upload-session-seal'
|
|
import { cleanupConsumedUploadSession } from '@/lib/temp-cleanup'
|
|
import {
|
|
BRAND_KNOWLEDGE_MAIN_FILE_EXTENSIONS,
|
|
BRAND_KNOWLEDGE_MAX_MAIN_FILE_BYTES,
|
|
BRAND_KNOWLEDGE_MAX_PREVIEW_IMAGE_BYTES,
|
|
BRAND_KNOWLEDGE_MAX_PREVIEW_SLICE_BYTES,
|
|
BRAND_KNOWLEDGE_MAX_PREVIEW_SLICE_COUNT,
|
|
BRAND_KNOWLEDGE_MAX_REQUEST_BYTES,
|
|
BRAND_KNOWLEDGE_TYPE_OPTIONS,
|
|
} from '@/lib/brand-knowledge-file-types'
|
|
|
|
export const runtime = 'nodejs'
|
|
export const dynamic = 'force-dynamic'
|
|
export const revalidate = 0
|
|
|
|
const MAX_FILE_SIZE = BRAND_KNOWLEDGE_MAX_MAIN_FILE_BYTES
|
|
const MAX_REQUEST_SIZE = BRAND_KNOWLEDGE_MAX_REQUEST_BYTES
|
|
const MAX_PREVIEW_IMAGE_SIZE = BRAND_KNOWLEDGE_MAX_PREVIEW_IMAGE_BYTES
|
|
const KNOWLEDGE_TYPES: ReadonlySet<string> = new Set(BRAND_KNOWLEDGE_TYPE_OPTIONS)
|
|
// The source file stays independent from Material/MaterialAsset rows.
|
|
const ALLOWED_EXTENSIONS: ReadonlySet<string> = new Set(BRAND_KNOWLEDGE_MAIN_FILE_EXTENSIONS)
|
|
const PRIVATE_HEADERS = { 'Cache-Control': 'private, no-store, max-age=0' }
|
|
|
|
class BrandKnowledgePersistenceUnknownError extends Error {
|
|
constructor() {
|
|
super('品牌知识保存状态暂时无法确认,服务器已保留上传文件,请勿重新上传')
|
|
this.name = 'BrandKnowledgePersistenceUnknownError'
|
|
}
|
|
}
|
|
|
|
function accessErrorResponse(error: unknown) {
|
|
if (error instanceof BrandCenterDashboardAccessError) {
|
|
return NextResponse.json({ success: false, error: error.message }, { status: error.status, headers: PRIVATE_HEADERS })
|
|
}
|
|
return null
|
|
}
|
|
|
|
function normalizeText(value: FormDataEntryValue | null, maxLength: number) {
|
|
return typeof value === 'string' ? value.trim().slice(0, maxLength) : ''
|
|
}
|
|
|
|
function getKnowledgeResponseSelect(userId: string) {
|
|
return {
|
|
id: true,
|
|
title: true,
|
|
knowledgeType: true,
|
|
brand: true,
|
|
productCategoryName: true,
|
|
fileName: true,
|
|
filePath: true,
|
|
mimeType: true,
|
|
fileSize: true,
|
|
downloadCount: true,
|
|
previewImageName: true,
|
|
previewImagePath: true,
|
|
previewImageMimeType: true,
|
|
previewImageSize: true,
|
|
createdAt: true,
|
|
uploadedBy: true,
|
|
uploader: { select: { realName: true, username: true } },
|
|
likes: { where: { userId }, select: { id: true } },
|
|
favorites: { where: { userId }, select: { id: true } },
|
|
_count: { select: { likes: true } },
|
|
} as const
|
|
}
|
|
|
|
async function publishMergedUploadByHardLink(input: {
|
|
sourcePath: string
|
|
destination: string
|
|
expectedBytes: number
|
|
}) {
|
|
try {
|
|
await link(input.sourcePath, input.destination)
|
|
return
|
|
} catch (error: any) {
|
|
if (error?.code !== 'EEXIST') throw error
|
|
}
|
|
|
|
const [sourceStats, destinationStats] = await Promise.all([
|
|
lstat(input.sourcePath),
|
|
lstat(input.destination),
|
|
])
|
|
if (
|
|
sourceStats.isSymbolicLink()
|
|
|| destinationStats.isSymbolicLink()
|
|
|| !sourceStats.isFile()
|
|
|| !destinationStats.isFile()
|
|
|| sourceStats.size !== input.expectedBytes
|
|
|| destinationStats.size !== input.expectedBytes
|
|
|| sourceStats.dev !== destinationStats.dev
|
|
|| sourceStats.ino !== destinationStats.ino
|
|
) {
|
|
throw new Error('品牌知识主文件目标路径已存在且与上传会话不一致')
|
|
}
|
|
}
|
|
|
|
function serializeKnowledge(item: {
|
|
id: string
|
|
title: string
|
|
knowledgeType: string
|
|
brand: string
|
|
productCategoryName: string
|
|
fileName: string
|
|
mimeType: string
|
|
fileSize: bigint
|
|
downloadCount: number
|
|
previewImageName: string | null
|
|
previewImagePath: string | null
|
|
previewImageMimeType: string | null
|
|
previewImageSize: bigint | null
|
|
createdAt: Date
|
|
uploader: { realName: string | null; username: string }
|
|
likes: { id: string }[]
|
|
favorites: { id: string }[]
|
|
_count: { likes: number }
|
|
}) {
|
|
return {
|
|
id: item.id,
|
|
title: item.title,
|
|
knowledgeType: item.knowledgeType,
|
|
brand: item.brand,
|
|
productCategoryName: item.productCategoryName,
|
|
fileName: item.fileName,
|
|
mimeType: item.mimeType,
|
|
fileSize: Number(item.fileSize),
|
|
downloadCount: item.downloadCount,
|
|
createdAt: item.createdAt.toISOString(),
|
|
uploadedBy: item.uploader.realName || item.uploader.username,
|
|
downloadUrl: `/api/department-dashboard/brand-knowledge/${item.id}/file`,
|
|
previewUrl: item.previewImagePath ? `/api/department-dashboard/brand-knowledge/${item.id}/preview` : null,
|
|
previewImageName: item.previewImageName,
|
|
likeCount: item._count.likes,
|
|
isLiked: item.likes.length > 0,
|
|
isFavorited: item.favorites.length > 0,
|
|
}
|
|
}
|
|
|
|
export async function GET(request: Request) {
|
|
try {
|
|
const session = await getServerSession(authOptions)
|
|
await assertBrandCenterDashboardAccess(session)
|
|
const userId = session?.user?.id
|
|
if (!userId) return NextResponse.json({ success: false, error: '请先登录' }, { status: 401, headers: PRIVATE_HEADERS })
|
|
const params = new URL(request.url).searchParams
|
|
const type = params.get('type')?.trim() || ''
|
|
const query = params.get('q')?.trim() || ''
|
|
const [items, total, canManage] = await Promise.all([
|
|
prisma.brandKnowledge.findMany({
|
|
where: {
|
|
deletedAt: null,
|
|
...(KNOWLEDGE_TYPES.has(type) ? { knowledgeType: type } : {}),
|
|
...(query ? {
|
|
OR: [
|
|
{ title: { contains: query, mode: 'insensitive' } },
|
|
{ knowledgeType: { contains: query, mode: 'insensitive' } },
|
|
{ fileName: { contains: query, mode: 'insensitive' } },
|
|
{ brand: { contains: query, mode: 'insensitive' } },
|
|
{ productCategoryName: { contains: query, mode: 'insensitive' } },
|
|
],
|
|
} : {}),
|
|
},
|
|
orderBy: { createdAt: 'desc' },
|
|
take: 200,
|
|
select: {
|
|
id: true,
|
|
title: true,
|
|
knowledgeType: true,
|
|
brand: true,
|
|
productCategoryName: true,
|
|
fileName: true,
|
|
mimeType: true,
|
|
fileSize: true,
|
|
downloadCount: true,
|
|
previewImageName: true,
|
|
previewImagePath: true,
|
|
previewImageMimeType: true,
|
|
previewImageSize: true,
|
|
createdAt: true,
|
|
uploader: { select: { realName: true, username: true } },
|
|
likes: { where: { userId }, select: { id: true } },
|
|
favorites: { where: { userId }, select: { id: true } },
|
|
_count: { select: { likes: true } },
|
|
},
|
|
}),
|
|
prisma.brandKnowledge.count({
|
|
where: {
|
|
deletedAt: null,
|
|
...(KNOWLEDGE_TYPES.has(type) ? { knowledgeType: type } : {}),
|
|
...(query ? {
|
|
OR: [
|
|
{ title: { contains: query, mode: 'insensitive' } },
|
|
{ knowledgeType: { contains: query, mode: 'insensitive' } },
|
|
{ fileName: { contains: query, mode: 'insensitive' } },
|
|
{ brand: { contains: query, mode: 'insensitive' } },
|
|
{ productCategoryName: { contains: query, mode: 'insensitive' } },
|
|
],
|
|
} : {}),
|
|
},
|
|
}),
|
|
isSuperAdmin(userId),
|
|
])
|
|
return NextResponse.json(
|
|
{ success: true, data: items.map(serializeKnowledge), total, permissions: { canManage } },
|
|
{ headers: PRIVATE_HEADERS },
|
|
)
|
|
} catch (error) {
|
|
const response = accessErrorResponse(error)
|
|
if (response) return response
|
|
console.error('[department-dashboard] 品牌知识列表读取失败:', error)
|
|
return NextResponse.json({ success: false, error: '品牌知识列表读取失败,请稍后重试' }, { status: 500, headers: PRIVATE_HEADERS })
|
|
}
|
|
}
|
|
|
|
export async function POST(request: Request) {
|
|
let uploadId = ''
|
|
let publishedMainPath: string | null = null
|
|
const storedPreviewPaths: string[] = []
|
|
const temporaryPreviewPaths: string[] = []
|
|
let releaseRequestSlot: (() => void) | null = null
|
|
let releaseUploadSessionLock: MaterialUploadStorageLockRelease | null = null
|
|
const persistence: {
|
|
outcome: 'not_attempted' | 'not_committed' | 'committed' | 'unknown'
|
|
} = { outcome: 'not_attempted' }
|
|
try {
|
|
const session = await getServerSession(authOptions)
|
|
await assertBrandCenterDashboardAccess(session)
|
|
const userId = session?.user?.id
|
|
if (!userId) return NextResponse.json({ success: false, error: '请先登录' }, { status: 401, headers: PRIVATE_HEADERS })
|
|
|
|
assertBoundedMultipartHeaders(request.headers, MAX_REQUEST_SIZE)
|
|
releaseRequestSlot = await boundedMultipartRequestLimiter.acquire()
|
|
const formData = await request.formData()
|
|
assertMultipartFiles(formData, {
|
|
fields: {
|
|
previewImage: {
|
|
maxCount: 1,
|
|
maxFileBytes: MAX_PREVIEW_IMAGE_SIZE,
|
|
allowedMimeTypes: ['image/jpeg', 'image/png', 'image/webp'],
|
|
},
|
|
previewImageSlices: {
|
|
maxCount: BRAND_KNOWLEDGE_MAX_PREVIEW_SLICE_COUNT,
|
|
maxFileBytes: BRAND_KNOWLEDGE_MAX_PREVIEW_SLICE_BYTES,
|
|
maxTotalBytes: MAX_PREVIEW_IMAGE_SIZE,
|
|
allowedMimeTypes: ['image/webp'],
|
|
},
|
|
},
|
|
maxFiles: BRAND_KNOWLEDGE_MAX_PREVIEW_SLICE_COUNT,
|
|
maxTotalBytes: MAX_PREVIEW_IMAGE_SIZE,
|
|
})
|
|
const previewImage = formData.get('previewImage')
|
|
const uploadedPreviewSlices = formData.getAll('previewImageSlices')
|
|
if (previewImage !== null && !isWebFileLike(previewImage)) {
|
|
return NextResponse.json({ success: false, error: '预览图文件无效' }, { status: 400, headers: PRIVATE_HEADERS })
|
|
}
|
|
if (isWebFileLike(previewImage) && uploadedPreviewSlices.length > 0) {
|
|
return NextResponse.json({ success: false, error: '预览图不能同时提交原图和切片' }, { status: 400, headers: PRIVATE_HEADERS })
|
|
}
|
|
if (uploadedPreviewSlices.some((slice) => !isWebFileLike(slice))) {
|
|
return NextResponse.json({ success: false, error: '预览图切片文件无效' }, { status: 400, headers: PRIVATE_HEADERS })
|
|
}
|
|
const title = normalizeText(formData.get('title'), 200)
|
|
const knowledgeType = normalizeText(formData.get('knowledgeType'), 30)
|
|
const brand = normalizeText(formData.get('brand'), 40)
|
|
const productCategoryName = normalizeText(formData.get('productCategoryName'), 80)
|
|
uploadId = normalizeText(formData.get('uploadId'), 128)
|
|
const existingFilePath = normalizeText(formData.get('existingFilePath'), 4096)
|
|
const safeOriginalName = normalizeUploadFileName(formData.get('originalFileName'))
|
|
const declaredFileSize = Number(normalizeText(formData.get('fileSize'), 20))
|
|
if (!title) return NextResponse.json({ success: false, error: '请填写知识标题' }, { status: 400, headers: PRIVATE_HEADERS })
|
|
if (!KNOWLEDGE_TYPES.has(knowledgeType)) return NextResponse.json({ success: false, error: '知识类型不合法' }, { status: 400, headers: PRIVATE_HEADERS })
|
|
if (!isSafeUploadId(uploadId) || !existingFilePath) {
|
|
return NextResponse.json({ success: false, error: '请先完成知识主文件的分片上传' }, { status: 400, headers: PRIVATE_HEADERS })
|
|
}
|
|
if (!safeOriginalName) return NextResponse.json({ success: false, error: '文件名不合法' }, { status: 400, headers: PRIVATE_HEADERS })
|
|
if (!Number.isSafeInteger(declaredFileSize) || declaredFileSize <= 0 || declaredFileSize > MAX_FILE_SIZE) {
|
|
return NextResponse.json({ success: false, error: '主文件大小需在 1B 至 1GB 之间' }, { status: 400, headers: PRIVATE_HEADERS })
|
|
}
|
|
const extension = path.extname(safeOriginalName).toLowerCase()
|
|
if (!ALLOWED_EXTENSIONS.has(extension)) return NextResponse.json({ success: false, error: '文件格式不支持,请参考素材资产库支持的格式' }, { status: 400, headers: PRIVATE_HEADERS })
|
|
|
|
releaseUploadSessionLock = await acquireTaskMaterialUploadSessionLocks([uploadId])
|
|
releaseUploadSessionLock.assertHeld()
|
|
|
|
const uploadRoot = getUploadRootDir()
|
|
const knowledgeDirectory = await ensureSafeDirectoryWithinRoot(uploadRoot, 'brand-knowledge')
|
|
if (!knowledgeDirectory) throw new Error('品牌知识存储目录不可用')
|
|
const storageName = `source-${uploadId}${extension}`
|
|
const destination = resolveStrictChildPath(knowledgeDirectory, storageName)
|
|
if (!destination) throw new Error('品牌知识文件路径不可用')
|
|
if (!(await isPathFreeOfSymbolicLinks(uploadRoot, destination, { allowMissingLeaf: true }))) throw new Error('品牌知识存储目录不安全')
|
|
const storedPath = `uploads/brand-knowledge/${storageName}`
|
|
const responseSelect = getKnowledgeResponseSelect(userId)
|
|
const replayed = await prisma.brandKnowledge.findFirst({
|
|
where: { filePath: storedPath },
|
|
select: responseSelect,
|
|
})
|
|
if (replayed) {
|
|
if (
|
|
replayed.uploadedBy !== userId
|
|
|| replayed.fileName !== safeOriginalName
|
|
|| replayed.fileSize !== BigInt(declaredFileSize)
|
|
) {
|
|
return NextResponse.json(
|
|
{ success: false, error: '该上传会话已被其它品牌知识记录使用' },
|
|
{ status: 409, headers: PRIVATE_HEADERS },
|
|
)
|
|
}
|
|
await cleanupConsumedUploadSession(uploadId).catch((error) => {
|
|
console.warn('[department-dashboard] 品牌知识重放请求清理上传会话失败:', { uploadId, error })
|
|
})
|
|
return NextResponse.json(
|
|
{ success: true, data: serializeKnowledge(replayed), replayed: true },
|
|
{ status: 201, headers: PRIVATE_HEADERS },
|
|
)
|
|
}
|
|
|
|
const ownedMergedUpload = await resolveOwnedMergedUpload({
|
|
existingFilePath,
|
|
uploadId,
|
|
userId,
|
|
})
|
|
if (!ownedMergedUpload) {
|
|
return NextResponse.json(
|
|
{ success: false, error: '上传会话不存在、已失效或不属于当前用户' },
|
|
{ status: 403, headers: PRIVATE_HEADERS },
|
|
)
|
|
}
|
|
const seal = await readUploadSessionSeal(uploadId)
|
|
if (seal?.state !== 'completed') {
|
|
return NextResponse.json(
|
|
{ success: false, error: '知识主文件尚未完成分片合并' },
|
|
{ status: 409, headers: PRIVATE_HEADERS },
|
|
)
|
|
}
|
|
if (
|
|
normalizeUploadFileName(ownedMergedUpload.session.fileName) !== safeOriginalName
|
|
|| ownedMergedUpload.session.fileSize !== declaredFileSize
|
|
|| ownedMergedUpload.session.uploadPurpose !== 'brand-knowledge'
|
|
) {
|
|
return NextResponse.json(
|
|
{ success: false, error: '知识主文件信息或上传用途与会话不一致' },
|
|
{ status: 409, headers: PRIVATE_HEADERS },
|
|
)
|
|
}
|
|
|
|
let preparedPreview: Awaited<ReturnType<typeof prepareBrandKnowledgePreview>> | null = null
|
|
let preparedUploadedSlices: Awaited<ReturnType<typeof validateBrandKnowledgeUploadedPreviewSlices>> | null = null
|
|
let previewImageName: string | null = null
|
|
if (isWebFileLike(previewImage)) {
|
|
if (previewImage.size <= 0 || previewImage.size > MAX_PREVIEW_IMAGE_SIZE) {
|
|
return NextResponse.json({ success: false, error: '预览图需为 1B 至 50MB 之间的 PNG、JPEG 或 WebP 图片' }, { status: 400, headers: PRIVATE_HEADERS })
|
|
}
|
|
try {
|
|
preparedPreview = await prepareBrandKnowledgePreview(Buffer.from(await previewImage.arrayBuffer()), previewImage.type)
|
|
} catch (error) {
|
|
return NextResponse.json(
|
|
{ success: false, error: error instanceof Error ? error.message : '预览图无效,请上传 PNG、JPEG 或 WebP 图片' },
|
|
{ status: 400, headers: PRIVATE_HEADERS },
|
|
)
|
|
}
|
|
previewImageName = normalizeSafeFileName(previewImage.name) || `preview.${preparedPreview.source.extension}`
|
|
} else if (uploadedPreviewSlices.length > 0) {
|
|
const declaredSliceCount = Number(normalizeText(formData.get('previewImageSliceCount'), 4))
|
|
if (!Number.isSafeInteger(declaredSliceCount) || declaredSliceCount !== uploadedPreviewSlices.length) {
|
|
return NextResponse.json({ success: false, error: '预览图切片数量不一致,请重新选择图片' }, { status: 400, headers: PRIVATE_HEADERS })
|
|
}
|
|
try {
|
|
preparedUploadedSlices = await validateBrandKnowledgeUploadedPreviewSlices(
|
|
await Promise.all(uploadedPreviewSlices.map(async (slice) => {
|
|
const fileSlice = slice as File
|
|
return { buffer: Buffer.from(await fileSlice.arrayBuffer()), declaredContentType: fileSlice.type }
|
|
})),
|
|
)
|
|
} catch (error) {
|
|
return NextResponse.json(
|
|
{ success: false, error: error instanceof Error ? error.message : '预览图切片无效' },
|
|
{ status: 400, headers: PRIVATE_HEADERS },
|
|
)
|
|
}
|
|
previewImageName = normalizeSafeFileName(normalizeText(formData.get('previewImageName'), 255)) || 'preview.webp'
|
|
}
|
|
|
|
await publishMergedUploadByHardLink({
|
|
sourcePath: ownedMergedUpload.filePath,
|
|
destination,
|
|
expectedBytes: declaredFileSize,
|
|
})
|
|
publishedMainPath = destination
|
|
|
|
const previewSlices = preparedUploadedSlices
|
|
? preparedUploadedSlices.slices.map((slice) => slice.buffer)
|
|
: preparedPreview?.slices || []
|
|
if (previewSlices.length > 0) {
|
|
for (let index = 0; index < previewSlices.length; index += 1) {
|
|
const previewStorageName = `${uploadId}-preview-part-${String(index + 1).padStart(3, '0')}.webp`
|
|
const previewDestination = resolveStrictChildPath(knowledgeDirectory, previewStorageName)
|
|
if (!previewDestination || !(await isPathFreeOfSymbolicLinks(uploadRoot, previewDestination, { allowMissingLeaf: true }))) {
|
|
throw new Error('品牌知识预览图路径不可用')
|
|
}
|
|
const temporaryPreviewPath = `${previewDestination}.uploading-${randomUUID()}`
|
|
temporaryPreviewPaths.push(temporaryPreviewPath)
|
|
await writeFile(temporaryPreviewPath, previewSlices[index], { flag: 'wx' })
|
|
await rename(temporaryPreviewPath, previewDestination)
|
|
temporaryPreviewPaths.splice(temporaryPreviewPaths.indexOf(temporaryPreviewPath), 1)
|
|
storedPreviewPaths.push(`uploads/brand-knowledge/${previewStorageName}`)
|
|
}
|
|
}
|
|
|
|
let created
|
|
persistence.outcome = 'not_committed'
|
|
try {
|
|
created = await prisma.brandKnowledge.create({
|
|
data: {
|
|
title,
|
|
knowledgeType,
|
|
brand,
|
|
productCategoryName,
|
|
fileName: safeOriginalName,
|
|
filePath: storedPath,
|
|
mimeType: String(lookupMimeType(safeOriginalName) || 'application/octet-stream'),
|
|
fileSize: BigInt(declaredFileSize),
|
|
previewImageName,
|
|
previewImagePath: storedPreviewPaths[0] || null,
|
|
previewImageSlices: [...storedPreviewPaths],
|
|
previewImageMimeType: previewSlices.length > 0 ? 'image/webp' : null,
|
|
previewImageSize: previewSlices.length > 0 ? BigInt(previewSlices[0].length) : null,
|
|
uploadedBy: userId,
|
|
},
|
|
select: responseSelect,
|
|
})
|
|
persistence.outcome = 'committed'
|
|
} catch (persistenceError) {
|
|
let confirmed
|
|
try {
|
|
confirmed = await prisma.brandKnowledge.findFirst({
|
|
where: { filePath: storedPath, uploadedBy: userId },
|
|
select: responseSelect,
|
|
})
|
|
} catch (inspectionError) {
|
|
persistence.outcome = 'unknown'
|
|
console.error('[department-dashboard] 品牌知识保存异常后无法确认数据库状态:', {
|
|
uploadId,
|
|
persistenceError,
|
|
inspectionError,
|
|
})
|
|
throw new BrandKnowledgePersistenceUnknownError()
|
|
}
|
|
if (!confirmed) throw persistenceError
|
|
created = confirmed
|
|
persistence.outcome = 'committed'
|
|
}
|
|
|
|
publishedMainPath = null
|
|
storedPreviewPaths.length = 0
|
|
await cleanupConsumedUploadSession(uploadId).catch((error) => {
|
|
console.warn('[department-dashboard] 品牌知识已保存但上传会话清理失败:', { uploadId, error })
|
|
})
|
|
return NextResponse.json({ success: true, data: serializeKnowledge(created) }, { status: 201, headers: PRIVATE_HEADERS })
|
|
} catch (error) {
|
|
if (persistence.outcome !== 'committed' && persistence.outcome !== 'unknown') {
|
|
await Promise.all(temporaryPreviewPaths.map((previewPath) => unlink(previewPath).catch(() => undefined)))
|
|
if (publishedMainPath) await unlink(publishedMainPath).catch(() => undefined)
|
|
await Promise.all(storedPreviewPaths.map(async (previewPath) => {
|
|
const absolute = path.join(getUploadRootDir(), previewPath.replace(/^uploads\//, ''))
|
|
await unlink(absolute).catch(() => undefined)
|
|
}))
|
|
}
|
|
const response = accessErrorResponse(error)
|
|
if (response) return response
|
|
if (error instanceof BrandKnowledgePersistenceUnknownError) {
|
|
return NextResponse.json(
|
|
{ success: false, error: error.message, code: 'BRAND_KNOWLEDGE_PERSISTENCE_UNKNOWN' },
|
|
{ status: 503, headers: PRIVATE_HEADERS },
|
|
)
|
|
}
|
|
const boundedFailure = getBoundedMultipartFailure(error)
|
|
if (boundedFailure) {
|
|
return NextResponse.json(
|
|
{ success: false, error: boundedFailure.message, code: boundedFailure.code },
|
|
{ status: boundedFailure.status, headers: { ...PRIVATE_HEADERS, ...(boundedFailure.retryAfterSeconds ? { 'Retry-After': String(boundedFailure.retryAfterSeconds) } : {}) } },
|
|
)
|
|
}
|
|
console.error('[department-dashboard] 品牌知识上传失败:', error)
|
|
return NextResponse.json({ success: false, error: '品牌知识上传失败,请稍后重试' }, { status: 500, headers: PRIVATE_HEADERS })
|
|
} finally {
|
|
await releaseUploadSessionLock?.()
|
|
releaseRequestSlot?.()
|
|
}
|
|
}
|