gongxiangp2/lib/task-detail-asset-edit.ts

1757 lines
58 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

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

import { prisma } from '@/lib/prisma'
import {
canManageMaterial,
} from '@/lib/material-authorization'
import { createMaterialLog } from '@/lib/material-log'
import { deleteFileIfUnreferenced } from '@/lib/file-cleanup'
import {
acquireTaskMaterialCompletionLock,
} from '@/lib/material-upload-cross-process-lock'
import { isProductPackageType } from '@/lib/material-type-mapper'
import { deriveTaskDetailIsFullSet } from '@/lib/task-detail-full-set'
import {
queueTaskDetailBarcodeImagesUpdatedNotification,
queueTaskDetailFullSetNotification,
} from '@/lib/external-auto-listing'
import {
buildTaskDetailPublicDisplayPath,
uploadPublicDisplayToS3,
} from '@/lib/public-display'
import { TASK_DETAIL_UPLOAD_LIMITS } from '@/lib/task-detail-upload-policy'
import { withImageProcessingSlot } from '@/lib/image-processing-limiter'
import { cleanupConsumedUploadSession } from '@/lib/temp-cleanup'
import { deleteStoredUploadFileFromRemote } from '@/lib/remote-upload-sync'
import {
getOwnedUploadSession,
getUploadedFile,
isSafeUploadId,
} from '@/lib/upload-sessions'
import { createZipFromFiles, createZipFromZips } from '@/lib/task-material-processor'
import {
createTaskDetailEditWorkspace,
extractZipEntriesToDirectory,
listZipEntries,
} from '@/lib/zip-entry-reader'
import { resolveStoredUploadPath } from '@/lib/upload-paths'
import path from 'path'
/**
* 任务-详情素材的单图编辑(替换 / 改名 / 删除)。
*
* 原图只存在于分组 ZIP(主图/SKU图/详情图)里,数据库保存的是 webp
* 预览行和打包产物。所以任何单图操作都要:
* 解开对应分组 ZIP -> 改条目 -> 重打分组 ZIP 和 all.zip -> 同步预览行。
*
* 预览行与 ZIP 条目的对应关系靠"来源文件名"锚定:archiver 并发打包
* 不保证条目顺序等于上传顺序,位置映射不可靠;预览名(客户端命名或
* 本模块生成的 __srv 命名)携带来源基础名,与条目名去扩展名后匹配。
* 匹配不上就拒绝编辑,宁可让用户删除重传,也不能悄悄改错图。
*/
export type TaskDetailEditGroup = 'main' | 'sku' | 'detail'
const GROUP_ZIP_LABELS: Record<TaskDetailEditGroup, string> = {
main: '主图',
sku: 'SKU图',
detail: '详情图',
}
const GROUP_PREVIEW_TYPES: Record<TaskDetailEditGroup, string> = {
main: 'main-preview',
sku: 'sku-preview',
detail: 'detail-preview',
}
const GROUPS: TaskDetailEditGroup[] = ['main', 'sku', 'detail']
export class TaskDetailAssetEditError extends Error {
readonly statusCode: 400 | 403 | 404 | 409
constructor(message: string, statusCode: 400 | 403 | 404 | 409 = 400) {
super(message)
this.name = 'TaskDetailAssetEditError'
this.statusCode = statusCode
}
}
interface PreviewRowLike {
id: string
assetType: string
fileUrl: string
fileName: string | null
sortOrder: number
skuCode?: string | null
createdAt?: Date | null
}
interface PreviewRun {
key: string
rows: PreviewRowLike[]
/** 旧代命名的图片序号;新命名 run 为 null */
legacyIndex: number | null
}
interface EditContext {
materialId: string
materialType: string
productModel: string | null
authorName: string | null
categoryName: string | null
currentPreviewUrl: string | null
wasFullSet: boolean
operatorUserId: string
psdCount: number
group: TaskDetailEditGroup
rowsByGroup: Record<TaskDetailEditGroup, PreviewRowLike[]>
groupZipAssets: Record<TaskDetailEditGroup, { id: string; fileUrl: string; fileName: string | null } | null>
allZipAsset: { id: string; fileUrl: string; fileName: string | null } | null
entryNames: string[]
runs: PreviewRun[]
targetRunIndex: number
targetEntryIndex: number
}
type EditMutation =
| { kind: 'replace'; filePath: string; replacementFileName: string; buffer: Buffer }
| { kind: 'rename'; newBaseName: string }
| { kind: 'delete' }
// ---------- 预览名解析、run 切分与条目匹配 ----------
interface ParsedPreviewName {
/** 与 ZIP 条目名(去扩展名)对应的锚;无法解析出锚时为 null */
label: string | null
sliceIndex: number | null
}
/**
* 解析预览文件名,提取"来源文件名"锚点。
*
* ZIP 条目顺序在 archiver 并发打包下不保证等于上传顺序,位置映射不可靠,
* 所以 run ↔ 条目一律用文件名锚定:
* - 客户端命名:`{原始基础名}.webp` / 切片 `{原始基础名}-{三位序号}.webp`
* - 服务端生成:`{原始基础名}__srv-{13位时间戳}-{序号}-{随机串}.webp`
*/
export function parseTaskDetailPreviewFileName(fileName: string): ParsedPreviewName | null {
if (!/\.webp$/i.test(fileName)) {
return null
}
const withoutExtension = fileName.replace(/\.webp$/i, '')
const serverMatch = /^(.+)__srv-\d+-\d+-[a-z0-9]*$/i.exec(withoutExtension)
if (serverMatch) {
return { label: serverMatch[1], sliceIndex: null }
}
const sliceMatch = /-(\d{3})$/.exec(withoutExtension)
if (sliceMatch) {
return {
label: withoutExtension.slice(0, sliceMatch.index),
sliceIndex: Number(sliceMatch[1]),
}
}
// 历史客户端命名 `{原始基础名}-preview.webp`(如 `主图3-preview.webp`):
// 剥掉 -preview 尾巴才是与 ZIP 条目名对应的锚。误剥只会导致配不上被拒绝,
// 不会错配(锚定仍要求条目名唯一命中)。
const previewTailMatch = /^(.+)-preview$/i.exec(withoutExtension)
if (previewTailMatch) {
return { label: previewTailMatch[1], sliceIndex: null }
}
return { label: withoutExtension, sliceIndex: null }
}
/** 生成服务端预览文件名:携带来源基础名作为后续编辑的匹配锚。 */
export function buildServerPreviewFileName(
sourceBaseName: string,
entryIndex: number,
): string {
const timestamp = Date.now()
const randomSuffix = Math.random().toString(36).substring(2, 9)
return `${sourceBaseName}__srv-${timestamp}-${entryIndex}-${randomSuffix}.webp`
}
/**
* 旧代客户端预览名:`{分组}-preview-{13位时间戳}-{图片序号}[-slice{N}]-{随机串}.webp`。
* 名字不含来源文件锚,但「图片序号」是上传时的权威顺序;历史 ZIP 为顺序打包,
* 因此序号可以与 ZIP 条目位置对齐(见 alignRunsToZipEntriesByOrder)。
*/
const LEGACY_PREVIEW_PATTERN =
/^(?:main|sku|detail)-preview-\d{13}-(\d+)(?:-slice(\d+))?-([a-z0-9]+)\.webp$/i
export function parseLegacyPreviewFileName(
fileName: string,
): { imageIndex: number; sliceIndex: number | null } | null {
const match = LEGACY_PREVIEW_PATTERN.exec(String(fileName || '').trim())
if (!match) return null
return {
imageIndex: Number(match[1]),
sliceIndex: match[2] !== undefined ? Number(match[2]) : null,
}
}
/**
* 旧代对齐:有名字锚的 run 先按现有规则唯一命中;剩余未配对的 run 与剩余
* 条目按相对顺序一一对应。正确性不变量:编辑操作(替换/改名/删除)不会改变
* 剩余条目的相对顺序,也同样不会改变剩余旧代序号的相对顺序,因此两个升序
* 序列的对应关系在多次编辑后依然成立。任何前置校验失败返回 null,调用方保持拒绝。
*/
export function alignRunsToZipEntriesByOrder(
runs: PreviewRun[],
entryNames: string[],
): number[] | null {
if (runs.length !== entryNames.length) return null
const entryBases = entryNames.map((name) => stripExtension(name).toLowerCase())
const baseOccurrences = new Map<string, number>()
for (const base of entryBases) {
baseOccurrences.set(base, (baseOccurrences.get(base) || 0) + 1)
}
const assigned = new Array<number>(runs.length).fill(-1)
const usedEntries = new Set<number>()
// 1. 有名字锚的 run 按唯一命中配对(与现有规则一致)
for (let runIndex = 0; runIndex < runs.length; runIndex += 1) {
const run = runs[runIndex]
if (run.legacyIndex !== null) continue
const key = run.key
if (!key.startsWith('name:')) return null
const label = key.slice('name:'.length).toLowerCase()
if ((baseOccurrences.get(label) || 0) !== 1) return null
const entryIndex = entryBases.findIndex(
(base, index) => base === label && !usedEntries.has(index),
)
if (entryIndex < 0) return null
assigned[runIndex] = entryIndex
usedEntries.add(entryIndex)
}
// 2. 旧代序号 run:同一序号只能出现一次
const seenLegacyIndexes = new Set<number>()
for (const run of runs) {
if (run.legacyIndex === null) continue
if (seenLegacyIndexes.has(run.legacyIndex)) return null
seenLegacyIndexes.add(run.legacyIndex)
}
// 3. 剩余 run(按旧代序号升序)与剩余条目(按位置升序)一一配对
const unmatchedRunIndexes = runs
.map((run, index) => (assigned[index] < 0 ? index : -1))
.filter((index) => index >= 0)
.sort((left, right) => {
const leftIndex = runs[left].legacyIndex ?? 0
const rightIndex = runs[right].legacyIndex ?? 0
return leftIndex - rightIndex
})
const unusedEntryIndexes: number[] = []
for (let index = 0; index < entryBases.length; index += 1) {
if (!usedEntries.has(index)) unusedEntryIndexes.push(index)
}
if (unmatchedRunIndexes.length !== unusedEntryIndexes.length) return null
unmatchedRunIndexes.forEach((runIndex, order) => {
assigned[runIndex] = unusedEntryIndexes[order]
})
return assigned
}
/**
* 把有序预览行切成 run。
* 相邻同名但各自独立的单预览保持独立;切片序列只在序号连续时合并。
* 返回 null 表示存在无法解析的名字(该素材不能安全编辑)。
*/
export function groupPreviewRowsIntoRuns(
sortedRows: PreviewRowLike[],
): PreviewRun[] | null {
const runs: PreviewRun[] = []
let expectedNextSlice: number | null = null
for (const row of sortedRows) {
const parsed = parseTaskDetailPreviewFileName(String(row.fileName || ''))
if (!parsed) {
return null
}
const lastRun = runs[runs.length - 1]
const continuesSliceSequence =
parsed.sliceIndex !== null
&& parsed.label !== null
&& lastRun !== undefined
&& lastRun.key === `name:${parsed.label}`
&& expectedNextSlice === parsed.sliceIndex
if (continuesSliceSequence && lastRun) {
lastRun.rows.push(row)
expectedNextSlice = parsed.sliceIndex! + 1
continue
}
runs.push({
key: parsed.label !== null ? `name:${parsed.label}` : 'unlabeled',
rows: [row],
legacyIndex: null,
})
expectedNextSlice = parsed.sliceIndex !== null ? parsed.sliceIndex + 1 : null
}
return runs
}
/**
* 为每个 run 附带旧代序号:旧代命名的行按「图片序号」归并(切片行合并进同序号),
* 新命名行沿用现有锚 key。用于锚定失败后的顺序对齐兜底。
* 任一行既不是新命名也不是旧代命名时返回 null(与现有 parse 失败同待遇)。
*/
export function buildRunsWithLegacyIndex(
sortedRows: PreviewRowLike[],
): PreviewRun[] | null {
const runs: PreviewRun[] = []
const runByLegacyIndex = new Map<number, PreviewRun>()
for (const row of sortedRows) {
const fileName = String(row.fileName || '')
const legacy = parseLegacyPreviewFileName(fileName)
if (legacy) {
const existing = runByLegacyIndex.get(legacy.imageIndex)
if (existing) {
existing.rows.push(row)
continue
}
const run: PreviewRun = {
key: `legacy:${legacy.imageIndex}`,
rows: [row],
legacyIndex: legacy.imageIndex,
}
runByLegacyIndex.set(legacy.imageIndex, run)
runs.push(run)
continue
}
const parsed = parseTaskDetailPreviewFileName(fileName)
if (!parsed) return null
runs.push({
key: `name:${parsed.label ?? ''}`,
rows: [row],
legacyIndex: null,
})
}
return runs
}
function stripExtension(name: string): string {
const dotIndex = name.lastIndexOf('.')
return dotIndex > 0 ? name.slice(0, dotIndex) : name
}
function getExtension(name: string): string {
const dotIndex = name.lastIndexOf('.')
return dotIndex > 0 ? name.slice(dotIndex) : ''
}
/**
* 把 run 匹配到 ZIP 条目下标。
*
* 规则:
* 1. 有名字锚的 run 按"条目名去扩展名(忽略大小写)"唯一命中才分配;
* 2. 剩下未分配的 run 和未命中的条目数量相等且 ≤1 时按剩余一一配对
* (兜住个别历史服务端命名行);
* 3. 其余情况一律拒绝——宁可让用户删除重传,也不能改错图。
*/
export function matchRunsToZipEntries(
runs: Array<{ key: string; rows: PreviewRowLike[] }>,
entryNames: string[],
): number[] {
if (runs.length !== entryNames.length) {
throw new TaskDetailAssetEditError(
'该素材的图片索引与打包内容不一致,无法安全地单独编辑。请删除后重新上传。',
)
}
const entryBases = entryNames.map((name) => stripExtension(name).toLowerCase())
const assignedEntryForRun = new Array<number>(runs.length).fill(-1)
const usedEntries = new Set<number>()
const baseOccurrences = new Map<string, number>()
for (const base of entryBases) {
baseOccurrences.set(base, (baseOccurrences.get(base) || 0) + 1)
}
for (let runIndex = 0; runIndex < runs.length; runIndex += 1) {
const key = runs[runIndex].key
if (!key.startsWith('name:')) {
continue
}
const label = key.slice('name:'.length).toLowerCase()
if ((baseOccurrences.get(label) || 0) !== 1) {
// 重名或完全无命中:留到残余阶段判断
continue
}
const entryIndex = entryBases.findIndex(
(base, index) => base === label && !usedEntries.has(index),
)
if (entryIndex >= 0) {
assignedEntryForRun[runIndex] = entryIndex
usedEntries.add(entryIndex)
}
}
const unassignedRuns: number[] = []
for (let runIndex = 0; runIndex < runs.length; runIndex += 1) {
if (assignedEntryForRun[runIndex] < 0) {
unassignedRuns.push(runIndex)
}
}
const unusedEntryIndexes: number[] = []
for (let index = 0; index < entryBases.length; index += 1) {
if (!usedEntries.has(index)) {
unusedEntryIndexes.push(index)
}
}
if (unassignedRuns.length !== unusedEntryIndexes.length) {
throw new TaskDetailAssetEditError(
'该素材的图片索引与打包内容不一致,无法安全地单独编辑。请删除后重新上传。',
)
}
if (unassignedRuns.length > 1) {
throw new TaskDetailAssetEditError(
'部分图片缺少可靠的来源标识,无法确认对应关系。请删除后重新上传。',
)
}
if (unassignedRuns.length === 1) {
assignedEntryForRun[unassignedRuns[0]] = unusedEntryIndexes[0]
}
return assignedEntryForRun
}
function sortPreviewRows(rows: PreviewRowLike[]): PreviewRowLike[] {
return [...rows].sort((left, right) => {
if (left.sortOrder !== right.sortOrder) {
return left.sortOrder - right.sortOrder
}
const leftTime = left.createdAt ? new Date(left.createdAt).getTime() : 0
const rightTime = right.createdAt ? new Date(right.createdAt).getTime() : 0
if (leftTime !== rightTime) {
return leftTime - rightTime
}
return left.id.localeCompare(right.id)
})
}
// ---------- 上下文装载 ----------
async function assertCanManage(
material: { id: string; userId: string | null },
operatorUserId: string,
operatorRole?: string | null,
) {
const canManage = await canManageMaterial(
{ id: operatorUserId, role: operatorRole },
// userId 为空表示历史脏数据:不匹配任何操作者,只可能由托管/管理员放行
{ id: material.id, userId: material.userId ?? '' },
)
if (!canManage) {
throw new TaskDetailAssetEditError('您没有权限编辑此素材', 403)
}
}
async function loadEditContext(options: {
materialId: string
assetId: string
operatorUserId: string
operatorRole?: string | null
}): Promise<EditContext> {
const material = await prisma.material.findFirst({
where: { id: options.materialId, deletedAt: null },
select: {
id: true,
userId: true,
materialType: true,
taskStatus: true,
productModel: true,
authorName: true,
categoryName: true,
previewUrl: true,
isFullSet: true,
},
})
if (!material) {
throw new TaskDetailAssetEditError('素材不存在或已被删除', 404)
}
if (!isProductPackageType(material.materialType)) {
throw new TaskDetailAssetEditError('只有任务-详情类型支持单图编辑')
}
if (material.taskStatus !== 'completed') {
throw new TaskDetailAssetEditError('素材尚未完成上传,暂不能编辑图片')
}
await assertCanManage(material, options.operatorUserId, options.operatorRole)
const [previewRows, zipAssetRows, psdCount] = await Promise.all([
prisma.materialAsset.findMany({
where: {
materialId: material.id,
assetType: { in: Object.values(GROUP_PREVIEW_TYPES) },
},
select: {
id: true,
assetType: true,
fileUrl: true,
fileName: true,
sortOrder: true,
skuCode: true,
createdAt: true,
},
}),
prisma.materialAsset.findMany({
where: {
materialId: material.id,
assetType: { in: ['main', 'sku', 'detail', 'all'] },
},
select: {
id: true,
assetType: true,
fileUrl: true,
fileName: true,
},
}),
prisma.materialAsset.count({
where: { materialId: material.id, assetType: 'psd' },
}),
])
const rowsByGroup: Record<TaskDetailEditGroup, PreviewRowLike[]> = {
main: [],
sku: [],
detail: [],
}
const groupZipAssets: Record<TaskDetailEditGroup, { id: string; fileUrl: string; fileName: string | null } | null> = {
main: null,
sku: null,
detail: null,
}
let allZipAsset: EditContext['allZipAsset'] = null
for (const row of zipAssetRows) {
if ((GROUPS as string[]).includes(row.assetType)) {
groupZipAssets[row.assetType as TaskDetailEditGroup] = {
id: row.id,
fileUrl: row.fileUrl,
fileName: row.fileName,
}
} else if (row.assetType === 'all') {
allZipAsset = { id: row.id, fileUrl: row.fileUrl, fileName: row.fileName }
}
}
for (const group of GROUPS) {
rowsByGroup[group] = sortPreviewRows(
(previewRows as PreviewRowLike[]).filter((row) => row.assetType === GROUP_PREVIEW_TYPES[group]),
)
}
const targetGroup = GROUPS.find((group) =>
rowsByGroup[group].some((row) => row.id === options.assetId),
)
if (!targetGroup) {
throw new TaskDetailAssetEditError('要编辑的图片不存在或不属于该素材', 404)
}
const groupZip = groupZipAssets[targetGroup]
if (!groupZip?.fileUrl) {
throw new TaskDetailAssetEditError('该分组的压缩包缺失,无法单独编辑图片')
}
const zipAbsolutePath = path.isAbsolute(groupZip.fileUrl)
? groupZip.fileUrl
: resolveStoredUploadPath(groupZip.fileUrl)
let entryNames: string[]
try {
const entries = await listZipEntries(zipAbsolutePath)
entryNames = entries.map((entry) => entry.name)
} catch (error) {
throw new TaskDetailAssetEditError(
`分组压缩包读取失败:${error instanceof Error ? error.message : '未知错误'}`,
)
}
// 先走「来源文件名锚定」;锚定失败时回退到旧代序号命名的顺序对齐
// (历史素材的预览名 detail-preview-{时间戳}-{序号}-... 不含文件锚,
// 但历史 ZIP 为顺序打包,序号与条目位置的相对顺序在多次编辑后依然成立)。
const resolveRunsAndEntryIndexes = (): { runs: PreviewRun[]; runEntryIndexes: number[] } => {
const anchoredRuns = groupPreviewRowsIntoRuns(rowsByGroup[targetGroup])
if (anchoredRuns) {
try {
return { runs: anchoredRuns, runEntryIndexes: matchRunsToZipEntries(anchoredRuns, entryNames) }
} catch (anchorError) {
const legacyRuns = buildRunsWithLegacyIndex(rowsByGroup[targetGroup])
const aligned = legacyRuns
? alignRunsToZipEntriesByOrder(legacyRuns, entryNames)
: null
if (legacyRuns && aligned) {
return { runs: legacyRuns, runEntryIndexes: aligned }
}
throw anchorError
}
}
const legacyRuns = buildRunsWithLegacyIndex(rowsByGroup[targetGroup])
const aligned = legacyRuns
? alignRunsToZipEntriesByOrder(legacyRuns, entryNames)
: null
if (legacyRuns && aligned) {
return { runs: legacyRuns, runEntryIndexes: aligned }
}
throw new TaskDetailAssetEditError(
'该素材的图片索引与打包内容不一致,无法安全地单独编辑。请删除后重新上传。',
)
}
const { runs, runEntryIndexes } = resolveRunsAndEntryIndexes()
const targetRunIndex = runs.findIndex((run) =>
run.rows.some((row) => row.id === options.assetId),
)
if (targetRunIndex < 0) {
throw new TaskDetailAssetEditError('要编辑的图片不存在或不属于该素材', 404)
}
return {
materialId: material.id,
materialType: material.materialType,
productModel: material.productModel,
authorName: material.authorName,
categoryName: material.categoryName,
currentPreviewUrl: material.previewUrl,
wasFullSet: Boolean(material.isFullSet),
operatorUserId: options.operatorUserId,
psdCount,
group: targetGroup,
rowsByGroup,
groupZipAssets,
allZipAsset,
entryNames,
runs,
targetRunIndex,
targetEntryIndex: runEntryIndexes[targetRunIndex],
}
}
// ---------- 预览生成与替换文件校验 ----------
const SERVER_PREVIEW_SOURCE_MAX_WIDTH = 12_000
const SERVER_PREVIEW_SOURCE_MAX_HEIGHT =
TASK_DETAIL_UPLOAD_LIMITS.maxSliceHeight * TASK_DETAIL_UPLOAD_LIMITS.maxPreviewCountPerImage
const SERVER_PREVIEW_SOURCE_MAX_PIXELS = 60_000_000
async function loadSharp() {
const sharpModule = (await import('sharp')) as unknown as {
default: typeof import('sharp')
}
return sharpModule.default
}
/** 按完成链路的服务端兜底参数生成预览(800x1200 webp,长图切片)。 */
async function generateServerPreviews(
imageBuffer: Buffer,
group: TaskDetailEditGroup,
materialId: string,
sourceBaseName: string,
entryIndex: number,
): Promise<Array<{ fileName: string; fileUrl: string; size: number }>> {
const { compressImage, sliceImage } = await import('@/lib/image-processor')
const sharp = await loadSharp()
if (imageBuffer.length > 200 * 1024 * 1024) {
throw new TaskDetailAssetEditError('替换图片不能超过 200MB')
}
const metadata = await withImageProcessingSlot(() =>
sharp(imageBuffer, {
limitInputPixels: SERVER_PREVIEW_SOURCE_MAX_PIXELS,
sequentialRead: true,
failOn: 'error',
}).metadata(),
)
if (
(metadata.width || 0) > SERVER_PREVIEW_SOURCE_MAX_WIDTH
|| (metadata.height || 0) > SERVER_PREVIEW_SOURCE_MAX_HEIGHT
) {
throw new TaskDetailAssetEditError('替换图片尺寸超出限制,请先缩小后再上传')
}
const shouldSlice = group === 'detail' && (metadata.height || 0) > 1500
const buffers = shouldSlice
? await sliceImage!(
imageBuffer,
TASK_DETAIL_UPLOAD_LIMITS.maxSliceHeight,
200,
TASK_DETAIL_UPLOAD_LIMITS.maxSliceWidth,
{
allowAnimatedFirstFrame: true,
maxInputWidth: SERVER_PREVIEW_SOURCE_MAX_WIDTH,
maxInputHeight: SERVER_PREVIEW_SOURCE_MAX_HEIGHT,
maxInputPixels: SERVER_PREVIEW_SOURCE_MAX_PIXELS,
},
)
: [
await compressImage(imageBuffer, {
maxWidth: 800,
maxHeight: 1200,
maxSizeKB: 200,
format: 'webp',
allowAnimatedFirstFrame: true,
maxInputWidth: SERVER_PREVIEW_SOURCE_MAX_WIDTH,
maxInputHeight: SERVER_PREVIEW_SOURCE_MAX_HEIGHT,
maxInputPixels: SERVER_PREVIEW_SOURCE_MAX_PIXELS,
}),
]
const previews: Array<{ fileName: string; fileUrl: string; size: number }> = []
for (let sliceIndex = 0; sliceIndex < buffers.length; sliceIndex += 1) {
const fileName = buildServerPreviewFileName(sourceBaseName, entryIndex)
const fileUrl = await uploadPublicDisplayToS3(
buffers[sliceIndex],
buildTaskDetailPublicDisplayPath(materialId, group, fileName),
'image/webp',
)
previews.push({ fileName, fileUrl, size: buffers[sliceIndex].length })
}
return previews
}
async function resolveReplacementUpload(options: {
uploadId: string
operatorUserId: string
}): Promise<{ filePath: string; fileName: string; fileSize: number; buffer: Buffer }> {
const uploadId = String(options.uploadId || '').trim()
if (!uploadId || !isSafeUploadId(uploadId)) {
throw new TaskDetailAssetEditError('替换图片的上传会话无效,请重新选择文件')
}
const session = await getOwnedUploadSession(uploadId, options.operatorUserId)
if (!session) {
throw new TaskDetailAssetEditError('替换图片尚未上传完成或会话已过期,请重新上传')
}
if (session.fileSize > TASK_DETAIL_UPLOAD_LIMITS.maxSingleImageBytes) {
throw new TaskDetailAssetEditError(
`替换图片超过单图 ${Math.round(TASK_DETAIL_UPLOAD_LIMITS.maxSingleImageBytes / 1024 / 1024)}MB 限制`,
)
}
const filePath = await getUploadedFile(uploadId)
if (!filePath) {
throw new TaskDetailAssetEditError('替换图片文件缺失,请重新上传')
}
const { readFile } = await import('fs/promises')
const buffer = await readFile(filePath)
const sharp = await loadSharp()
try {
await withImageProcessingSlot(() =>
sharp(buffer, {
limitInputPixels: SERVER_PREVIEW_SOURCE_MAX_PIXELS,
failOn: 'error',
}).metadata(),
)
} catch {
throw new TaskDetailAssetEditError('替换的文件不是有效图片,请更换文件后重试')
}
return { filePath, fileName: session.fileName, fileSize: session.fileSize, buffer }
}
function buildFinalEntryName(originalName: string, replacementFileName: string): string {
const originalExtension = getExtension(originalName)
const replacementExtension = getExtension(replacementFileName)
return `${stripExtension(originalName)}${replacementExtension || originalExtension}`
}
function sanitizeNewBaseName(rawName: string): string {
const trimmed = String(rawName || '').trim()
if (!trimmed) {
throw new TaskDetailAssetEditError('文件名不能为空')
}
if (trimmed.length > 120) {
throw new TaskDetailAssetEditError('文件名不能超过 120 个字符')
}
if (/[\/\\:*?"<>|\r\n\0]/.test(trimmed)) {
throw new TaskDetailAssetEditError('文件名不能包含 \\ / : * ? " < > | 等字符')
}
return trimmed
}
// ---------- 变更计划与执行 ----------
interface PlannedDbChanges {
previewRowsToDelete: string[]
previewRowsToInsert: Array<{
assetType: string
fileUrl: string
fileName: string
fileSize: bigint
sortOrder: number
skuCode: string | null
barcodes: string[]
}>
sortOrderUpdates: Array<{ id: string; sortOrder: number }>
fileNameUpdates: Array<{ id: string; fileName: string }>
removedPreviewUrls: Array<{ url: string }>
}
interface RebuildOutcome {
nextEntryNames: string[]
newGroupZip: { filePath: string; fileName: string; fileSize: number } | null
newAllZip: { filePath: string; fileName: string; fileSize: number } | null
db: PlannedDbChanges
finalRowCountByGroup: Record<TaskDetailEditGroup, number>
firstPreviewUrlByGroup: Record<TaskDetailEditGroup, string | null>
}
async function planPreviewRowChanges(
context: EditContext,
mutation: EditMutation,
finalEntryName: string,
): Promise<PlannedDbChanges> {
const { group, runs, targetRunIndex, targetEntryIndex } = context
const targetRun = runs[targetRunIndex]
const previewType = GROUP_PREVIEW_TYPES[group]
const planned: PlannedDbChanges = {
previewRowsToDelete: [],
previewRowsToInsert: [],
sortOrderUpdates: [],
fileNameUpdates: [],
removedPreviewUrls: [],
}
if (mutation.kind === 'delete') {
for (const row of targetRun.rows) {
planned.previewRowsToDelete.push(row.id)
planned.removedPreviewUrls.push({ url: row.fileUrl })
}
} else if (mutation.kind === 'replace') {
const generated = await generateServerPreviews(
mutation.buffer,
group,
context.materialId,
stripExtension(finalEntryName),
targetEntryIndex,
)
const barcodes = await loadRunBarcodes(targetRun.rows.map((row) => row.id))
for (const row of targetRun.rows) {
planned.previewRowsToDelete.push(row.id)
planned.removedPreviewUrls.push({ url: row.fileUrl })
}
generated.forEach((preview, index) => {
planned.previewRowsToInsert.push({
assetType: previewType,
fileUrl: preview.fileUrl,
fileName: preview.fileName,
fileSize: BigInt(preview.size),
sortOrder: targetRunIndex + index,
skuCode: targetRun.rows[0]?.skuCode?.trim() || null,
barcodes: index === 0 ? barcodes : [],
})
})
} else {
// rename:同步预览标签里的来源基础名(客户端命名与 __srv 命名都要跟条目名一致)
const newBaseName = stripExtension(finalEntryName)
for (const row of targetRun.rows) {
const currentName = String(row.fileName || '')
const parsed = parseTaskDetailPreviewFileName(currentName)
if (!parsed?.label) {
continue
}
if (parsed.label.toLowerCase() === newBaseName.toLowerCase()) {
continue
}
const serverTail = /^.*(__srv-\d+-\d+-[a-z0-9]*)$/i.exec(
currentName.replace(/\.webp$/i, ''),
)
let nextName: string
if (serverTail) {
nextName = `${newBaseName}${serverTail[1]}.webp`
} else {
const sliceSuffixMatch = /-\d{3}(?=\.webp$)/i.exec(currentName)
nextName = sliceSuffixMatch
? `${newBaseName}${sliceSuffixMatch[0]}.webp`
: `${newBaseName}.webp`
}
if (nextName !== currentName) {
planned.fileNameUpdates.push({ id: row.id, fileName: nextName })
}
}
}
// 目标 run 之后的所有行统一重排编号(rename 行数不变,重排结果不变)
const rowsInFinalOrder: PreviewRowLike[] = []
for (let runIndex = 0; runIndex < runs.length; runIndex += 1) {
if (mutation.kind !== 'rename' && runIndex === targetRunIndex) {
continue
}
rowsInFinalOrder.push(...runs[runIndex].rows)
}
rowsInFinalOrder.forEach((row, index) => {
if (row.sortOrder !== index) {
planned.sortOrderUpdates.push({ id: row.id, sortOrder: index })
}
})
return planned
}
async function loadRunBarcodes(assetIds: string[]): Promise<string[]> {
if (assetIds.length === 0) {
return []
}
const rows = await prisma.materialAssetBarcode.findMany({
where: { assetId: { in: assetIds } },
select: { barcode: true },
})
return Array.from(new Set(rows.map((row) => row.barcode).filter(Boolean))).sort()
}
// ---------- 批量编辑:序列应用 + 一次重建 ----------
interface PreparedBatchOperation {
assetId: string
mutation: EditMutation
/** replace 操作消费的上传会话,提交成功后清理 */
uploadId?: string
}
/**
* 批量执行:全部操作在内存中按顺序应用完毕后,只做一次分组 ZIP 重建、
* 一次 all.zip 重建、一次数据库事务。复用 RebuildOutcome 与提交链路。
*/
async function executeBatchRebuild(
context: EditContext,
operations: PreparedBatchOperation[],
): Promise<RebuildOutcome> {
const { group, entryNames } = context
const previewType = GROUP_PREVIEW_TYPES[group]
const workspace = await createTaskDetailEditWorkspace()
try {
const groupZip = context.groupZipAssets[group]!
const groupZipAbsolute = path.isAbsolute(groupZip.fileUrl)
? groupZip.fileUrl
: resolveStoredUploadPath(groupZip.fileUrl)
const extracted = await extractZipEntriesToDirectory(groupZipAbsolute, workspace.dir)
// 存活条目与存活 run 一一对应,随操作同步增删
const entries: Array<{ path: string; name: string; size: number }> = extracted.map(
(item, index) => ({
path: item.filePath,
name: entryNames[index],
size: item.size,
}),
)
const runs: PreviewRun[] = context.runs.map((run) => ({ ...run, rows: [...run.rows] }))
const db: PlannedDbChanges = {
previewRowsToDelete: [],
previewRowsToInsert: [],
sortOrderUpdates: [],
fileNameUpdates: [],
removedPreviewUrls: [],
}
// 被替换 run(rows 清空)→ 其新插入行在 previewRowsToInsert 中的区间,最终统一重排
const replacedInsertsByRunIndex = new Map<number, { startIndex: number; count: number }>()
const handledAssetIds = new Set<string>()
for (const operation of operations) {
if (handledAssetIds.has(operation.assetId)) {
throw new TaskDetailAssetEditError('同一张图在一次批量提交中只能操作一次,请分开提交')
}
handledAssetIds.add(operation.assetId)
const runIndex = runs.findIndex((run) => run.rows.some((row) => row.id === operation.assetId))
if (runIndex < 0) {
throw new TaskDetailAssetEditError('要编辑的图片不存在或已被本次批量操作移除', 404)
}
if (operation.mutation.kind === 'delete') {
for (const row of runs[runIndex].rows) {
db.previewRowsToDelete.push(row.id)
db.removedPreviewUrls.push({ url: row.fileUrl })
}
entries.splice(runIndex, 1)
runs.splice(runIndex, 1)
continue
}
if (operation.mutation.kind === 'rename') {
const originalExtension = getExtension(entries[runIndex].name)
const finalEntryName = `${operation.mutation.newBaseName}${originalExtension}`
const conflict = entries.some((entry, index) => index !== runIndex && entry.name === finalEntryName)
if (conflict) {
throw new TaskDetailAssetEditError(`改名后的「${finalEntryName}」与包内其他文件重名,请换一个名字`, 409)
}
entries[runIndex] = { ...entries[runIndex], name: finalEntryName }
// 同步预览行文件名里的来源锚(与单张 rename 分支同一套规则)
const newBaseName = operation.mutation.newBaseName
for (const row of runs[runIndex].rows) {
const currentName = String(row.fileName || '')
const parsed = parseTaskDetailPreviewFileName(currentName)
if (!parsed?.label) continue
if (parsed.label.toLowerCase() === newBaseName.toLowerCase()) continue
const serverTail = /^.*(__srv-\d+-\d+-[a-z0-9]*)$/i.exec(
currentName.replace(/\.webp$/i, ''),
)
let nextName: string
if (serverTail) {
nextName = `${newBaseName}${serverTail[1]}.webp`
} else {
const sliceSuffixMatch = /-\d{3}(?=\.webp$)/i.exec(currentName)
nextName = sliceSuffixMatch
? `${newBaseName}${sliceSuffixMatch[0]}.webp`
: `${newBaseName}.webp`
}
if (nextName !== currentName) {
db.fileNameUpdates.push({ id: row.id, fileName: nextName })
}
}
continue
}
// replace
const finalEntryName = buildFinalEntryName(entries[runIndex].name, operation.mutation.replacementFileName)
const conflict = entries.some((entry, index) => index !== runIndex && entry.name === finalEntryName)
if (conflict) {
throw new TaskDetailAssetEditError(`替换后的「${finalEntryName}」与包内其他文件重名,请先改名再替换`, 409)
}
entries[runIndex] = {
path: operation.mutation.filePath,
name: finalEntryName,
size: 0,
}
const generated = await generateServerPreviews(
operation.mutation.buffer,
group,
context.materialId,
stripExtension(finalEntryName),
runIndex,
)
const barcodes = group === 'sku'
? await loadRunBarcodes(runs[runIndex].rows.map((row) => row.id))
: []
for (const row of runs[runIndex].rows) {
db.previewRowsToDelete.push(row.id)
db.removedPreviewUrls.push({ url: row.fileUrl })
}
const startIndex = db.previewRowsToInsert.length
generated.forEach((preview, index) => {
db.previewRowsToInsert.push({
assetType: previewType,
fileUrl: preview.fileUrl,
fileName: preview.fileName,
fileSize: BigInt(preview.size),
sortOrder: runIndex + index,
skuCode: runs[runIndex].rows[0]?.skuCode?.trim() || null,
barcodes: index === 0 ? barcodes : [],
})
})
replacedInsertsByRunIndex.set(runIndex, { startIndex, count: generated.length })
runs[runIndex] = { ...runs[runIndex], rows: [] }
}
// 最终统一重排:按 run 顺序展开"存活旧行 + 替换插入行",重写 sortOrder
const finalRowUrls: string[] = []
let cursor = 0
for (let runIndex = 0; runIndex < runs.length; runIndex += 1) {
const replaced = replacedInsertsByRunIndex.get(runIndex)
if (replaced) {
for (let offset = 0; offset < replaced.count; offset += 1) {
const row = db.previewRowsToInsert[replaced.startIndex + offset]
row.sortOrder = cursor
finalRowUrls.push(row.fileUrl)
cursor += 1
}
continue
}
for (const row of runs[runIndex].rows) {
if (row.sortOrder !== cursor) {
db.sortOrderUpdates.push({ id: row.id, sortOrder: cursor })
}
finalRowUrls.push(row.fileUrl)
cursor += 1
}
}
let newGroupZip: RebuildOutcome['newGroupZip'] = null
if (entries.length > 0) {
newGroupZip = await createZipFromFiles(
entries,
context.materialId,
context.productModel || 'product',
'任务-详情',
GROUP_ZIP_LABELS[group],
context.authorName || undefined,
context.categoryName || undefined,
)
}
const members: Array<{ path: string; name: string }> = []
for (const memberGroup of GROUPS) {
if (memberGroup === group) {
if (newGroupZip) {
members.push({
path: resolveStoredUploadPath(newGroupZip.filePath),
name: newGroupZip.fileName,
})
}
continue
}
const memberAsset = context.groupZipAssets[memberGroup]
if (memberAsset?.fileUrl) {
members.push({
path: resolveStoredUploadPath(memberAsset.fileUrl),
name: memberAsset.fileName || '',
})
}
}
let newAllZip: RebuildOutcome['newAllZip'] = null
if (members.length > 0) {
newAllZip = await createZipFromZips(
members,
context.materialId,
context.productModel || 'product',
'任务-详情',
)
}
const finalRowCountByGroup: Record<TaskDetailEditGroup, number> = {
main: context.rowsByGroup.main.length,
sku: context.rowsByGroup.sku.length,
detail: context.rowsByGroup.detail.length,
}
finalRowCountByGroup[group] = cursor
const firstPreviewUrlByGroup: Record<TaskDetailEditGroup, string | null> = {
main: null,
sku: null,
detail: null,
}
if (finalRowCountByGroup[group] > 0) {
firstPreviewUrlByGroup[group] = finalRowUrls[0] || null
}
return {
nextEntryNames: entries.map((entry) => entry.name),
newGroupZip,
newAllZip,
db,
finalRowCountByGroup,
firstPreviewUrlByGroup,
}
} finally {
await workspace.cleanup()
}
}
async function executeRebuild(
context: EditContext,
mutation: EditMutation,
): Promise<RebuildOutcome> {
const { group, entryNames, targetEntryIndex } = context
const workspace = await createTaskDetailEditWorkspace()
try {
const groupZip = context.groupZipAssets[group]!
const groupZipAbsolute = path.isAbsolute(groupZip.fileUrl)
? groupZip.fileUrl
: resolveStoredUploadPath(groupZip.fileUrl)
const extracted = await extractZipEntriesToDirectory(groupZipAbsolute, workspace.dir)
const finalEntries: Array<{ path: string; name: string; size: number }> = extracted.map(
(item, index) => ({
path: item.filePath,
name: entryNames[index],
size: item.size,
}),
)
let finalEntryName = entryNames[targetEntryIndex]
if (mutation.kind === 'delete') {
finalEntries.splice(targetEntryIndex, 1)
} else if (mutation.kind === 'rename') {
const originalExtension = getExtension(finalEntryName)
finalEntryName = `${mutation.newBaseName}${originalExtension}`
const conflict = finalEntries.some(
(entry, index) => index !== targetEntryIndex && entry.name === finalEntryName,
)
if (conflict) {
throw new TaskDetailAssetEditError('包内已存在同名文件,请换一个名字', 409)
}
finalEntries[targetEntryIndex] = { ...finalEntries[targetEntryIndex], name: finalEntryName }
} else {
finalEntryName = buildFinalEntryName(entryNames[targetEntryIndex], mutation.replacementFileName)
const conflict = finalEntries.some(
(entry, index) => index !== targetEntryIndex && entry.name === finalEntryName,
)
if (conflict) {
throw new TaskDetailAssetEditError('替换后的文件名与包内其他文件重名,请先改名再替换', 409)
}
finalEntries[targetEntryIndex] = {
path: mutation.filePath,
name: finalEntryName,
size: 0,
}
}
let newGroupZip: RebuildOutcome['newGroupZip'] = null
if (finalEntries.length > 0) {
newGroupZip = await createZipFromFiles(
finalEntries,
context.materialId,
context.productModel || 'product',
'任务-详情',
GROUP_ZIP_LABELS[group],
context.authorName || undefined,
context.categoryName || undefined,
)
}
const members: Array<{ path: string; name: string }> = []
for (const memberGroup of GROUPS) {
if (memberGroup === group) {
if (newGroupZip) {
members.push({
path: resolveStoredUploadPath(newGroupZip.filePath),
name: newGroupZip.fileName,
})
}
continue
}
const memberAsset = context.groupZipAssets[memberGroup]
if (memberAsset?.fileUrl) {
members.push({
path: resolveStoredUploadPath(memberAsset.fileUrl),
name: memberAsset.fileName || '',
})
}
}
let newAllZip: RebuildOutcome['newAllZip'] = null
if (members.length > 0) {
newAllZip = await createZipFromZips(
members,
context.materialId,
context.productModel || 'product',
'任务-详情',
)
}
const db = await planPreviewRowChanges(context, mutation, finalEntryName)
// 计算各组最终预览行数与首图地址(用于封面回退和整套判定)
const finalRowCountByGroup: Record<TaskDetailEditGroup, number> = {
main: context.rowsByGroup.main.length,
sku: context.rowsByGroup.sku.length,
detail: context.rowsByGroup.detail.length,
}
finalRowCountByGroup[group] =
context.rowsByGroup[group].length
- db.previewRowsToDelete.length
+ db.previewRowsToInsert.length
const firstPreviewUrlByGroup: Record<TaskDetailEditGroup, string | null> = {
main: null,
sku: null,
detail: null,
}
if (finalRowCountByGroup[group] > 0) {
const candidates = [
...context.rowsByGroup[group]
.filter((row) => !db.previewRowsToDelete.includes(row.id))
.map((row) => ({ url: row.fileUrl, sortOrder: row.sortOrder })),
...db.previewRowsToInsert.map((row) => ({
url: row.fileUrl,
sortOrder: row.sortOrder,
})),
].sort((left, right) => left.sortOrder - right.sortOrder)
firstPreviewUrlByGroup[group] = candidates[0]?.url || null
}
return {
nextEntryNames: finalEntries.map((entry) => entry.name),
newGroupZip,
newAllZip,
db,
finalRowCountByGroup,
firstPreviewUrlByGroup,
}
} finally {
await workspace.cleanup()
}
}
// ---------- 落库与清理 ----------
function computeNextAssetTypes(context: EditContext, outcome: RebuildOutcome): Array<{ assetType: string }> {
const types: Array<{ assetType: string }> = []
for (const group of GROUPS) {
if (outcome.finalRowCountByGroup[group] > 0) {
types.push({ assetType: GROUP_PREVIEW_TYPES[group] }, { assetType: group })
}
}
if (context.psdCount > 0) {
types.push({ assetType: 'psd' })
}
return types
}
async function commitRebuild(
context: EditContext,
outcome: RebuildOutcome,
operationLabel: 'REPLACE_IMAGE' | 'RENAME_IMAGE' | 'DELETE_IMAGE' | 'BATCH_IMAGE_EDITS',
): Promise<{ nextIsFullSet: boolean }> {
const { group } = context
const previewType = GROUP_PREVIEW_TYPES[group]
const insertedBarcodeLinks: Array<{ assetId: string; barcode: string }> = []
const result = await prisma.$transaction(async (tx) => {
const groupZipAsset = context.groupZipAssets[group]!
if (outcome.newGroupZip) {
await tx.materialAsset.update({
where: { id: groupZipAsset.id },
data: {
fileUrl: outcome.newGroupZip.filePath,
fileName: outcome.newGroupZip.fileName,
fileSize: BigInt(outcome.newGroupZip.fileSize),
},
})
} else {
await tx.materialAsset.delete({ where: { id: groupZipAsset.id } })
}
if (outcome.newAllZip) {
const allData = {
fileUrl: outcome.newAllZip.filePath,
fileName: outcome.newAllZip.fileName,
fileSize: BigInt(outcome.newAllZip.fileSize),
}
if (context.allZipAsset) {
await tx.materialAsset.update({ where: { id: context.allZipAsset.id }, data: allData })
} else {
await tx.materialAsset.create({
data: {
materialId: context.materialId,
assetType: 'all',
sortOrder: 0,
...allData,
},
})
}
} else if (context.allZipAsset) {
await tx.materialAsset.delete({ where: { id: context.allZipAsset.id } })
}
if (outcome.db.previewRowsToDelete.length > 0) {
await tx.materialAsset.deleteMany({
where: { id: { in: outcome.db.previewRowsToDelete } },
})
}
if (outcome.db.previewRowsToInsert.length > 0) {
await tx.materialAsset.createMany({
data: outcome.db.previewRowsToInsert.map((row) => ({
materialId: context.materialId,
assetType: row.assetType,
fileUrl: row.fileUrl,
fileName: row.fileName,
fileSize: row.fileSize,
sortOrder: row.sortOrder,
skuCode: row.skuCode,
})),
})
if (group === 'sku') {
const insertedRows = await tx.materialAsset.findMany({
where: {
materialId: context.materialId,
assetType: previewType,
fileUrl: { in: outcome.db.previewRowsToInsert.map((row) => row.fileUrl) },
},
select: { id: true, fileUrl: true },
})
const urlToId = new Map(insertedRows.map((row) => [row.fileUrl, row.id]))
for (const row of outcome.db.previewRowsToInsert) {
const assetId = urlToId.get(row.fileUrl)
for (const barcode of row.barcodes) {
if (assetId) {
insertedBarcodeLinks.push({ assetId, barcode })
}
}
}
if (insertedBarcodeLinks.length > 0) {
await tx.materialAssetBarcode.createMany({
data: insertedBarcodeLinks,
skipDuplicates: true,
})
}
}
}
for (const update of outcome.db.sortOrderUpdates) {
await tx.materialAsset.update({
where: { id: update.id },
data: { sortOrder: update.sortOrder },
})
}
for (const update of outcome.db.fileNameUpdates) {
await tx.materialAsset.update({
where: { id: update.id },
data: { fileName: update.fileName },
})
}
const nextIsFullSet = deriveTaskDetailIsFullSet(
context.materialType,
computeNextAssetTypes(context, outcome),
false,
)
const removedUrls = new Set(outcome.db.removedPreviewUrls.map((item) => item.url))
let nextPreviewUrl = context.currentPreviewUrl
if (nextPreviewUrl && removedUrls.has(nextPreviewUrl)) {
nextPreviewUrl =
outcome.firstPreviewUrlByGroup.main
|| outcome.firstPreviewUrlByGroup.sku
|| outcome.firstPreviewUrlByGroup.detail
|| ''
}
await tx.material.update({
where: { id: context.materialId },
data: {
previewUrl: nextPreviewUrl || '',
zipFilePath: outcome.newAllZip?.filePath || '',
zipFileName: outcome.newAllZip?.fileName || '',
zipFileSize: BigInt(outcome.newAllZip?.fileSize || 0),
isFullSet: nextIsFullSet,
},
})
return { nextIsFullSet }
})
// 数据与文件都已提交,流水写失败只记告警,不能让用户误以为编辑没生效。
await createMaterialLog({
materialId: context.materialId,
userId: context.operatorUserId,
action: 'UPDATE',
changes: {
assetOperation: { oldValue: null, newValue: operationLabel },
group: { oldValue: null, newValue: group },
entryName: {
oldValue: context.entryNames[context.targetEntryIndex],
newValue: outcome.nextEntryNames[context.targetEntryIndex] ?? null,
},
entryCount: {
oldValue: context.entryNames.length,
newValue: outcome.nextEntryNames.length,
},
},
}).catch((error) => {
console.error('[task-detail-asset-edit] 素材日志写入失败:', error)
})
return result
}
async function cleanupAfterCommit(context: EditContext, outcome: RebuildOutcome) {
const tasks: Array<Promise<unknown>> = []
const staleStoredPaths: string[] = []
const groupZip = context.groupZipAssets[context.group]
if (groupZip && (!outcome.newGroupZip || groupZip.fileUrl !== outcome.newGroupZip.filePath)) {
staleStoredPaths.push(groupZip.fileUrl)
}
if (
context.allZipAsset
&& (!outcome.newAllZip || context.allZipAsset.fileUrl !== outcome.newAllZip.filePath)
) {
staleStoredPaths.push(context.allZipAsset.fileUrl)
}
for (const storedPath of staleStoredPaths) {
tasks.push(deleteStoredUploadFileFromRemote(storedPath).catch(() => undefined))
}
for (const removed of outcome.db.removedPreviewUrls) {
tasks.push(
deleteFileIfUnreferenced(removed.url, {
excludeMaterialIds: [context.materialId],
}).catch(() => undefined),
)
}
await Promise.allSettled(tasks)
}
async function runEditOperation<T>(materialId: string, operation: () => Promise<T>): Promise<T> {
const release = await acquireTaskMaterialCompletionLock(materialId)
try {
release.assertHeld()
return await operation()
} finally {
await release()
}
}
// ---------- 对外入口 ----------
export interface ReplaceTaskDetailImageInput {
materialId: string
assetId: string
operatorUserId: string
operatorRole?: string | null
uploadId: string
}
export async function replaceTaskDetailImage(input: ReplaceTaskDetailImageInput) {
return runEditOperation(input.materialId, async () => {
const context = await loadEditContext(input)
const upload = await resolveReplacementUpload({
uploadId: input.uploadId,
operatorUserId: input.operatorUserId,
})
const outcome = await executeRebuild(context, {
kind: 'replace',
filePath: upload.filePath,
replacementFileName: upload.fileName,
buffer: upload.buffer,
})
const { nextIsFullSet } = await commitRebuild(context, outcome, 'REPLACE_IMAGE')
await cleanupAfterCommit(context, outcome)
await cleanupConsumedUploadSession(input.uploadId.trim()).catch(() => undefined)
if (!context.wasFullSet && nextIsFullSet) {
void queueTaskDetailFullSetNotification(context.materialId)
}
if (context.group === 'sku' && outcome.db.previewRowsToInsert.length > 0) {
const insertedAssets = await prisma.materialAsset.findMany({
where: {
materialId: context.materialId,
assetType: GROUP_PREVIEW_TYPES.sku,
fileUrl: { in: outcome.db.previewRowsToInsert.map((row) => row.fileUrl) },
},
select: { id: true },
})
void queueTaskDetailBarcodeImagesUpdatedNotification(
context.materialId,
insertedAssets.map((row) => row.id),
)
}
return {
success: true,
entryName: outcome.nextEntryNames[context.targetRunIndex],
}
})
}
export interface RenameTaskDetailImageInput {
materialId: string
assetId: string
operatorUserId: string
operatorRole?: string | null
newFileName: string
}
export async function renameTaskDetailImage(input: RenameTaskDetailImageInput) {
return runEditOperation(input.materialId, async () => {
const context = await loadEditContext(input)
const rawName = String(input.newFileName || '').trim()
const baseName = sanitizeNewBaseName(stripExtension(rawName))
const requestedExtension = getExtension(rawName)
const originalExtension = getExtension(context.entryNames[context.targetRunIndex])
if (requestedExtension && requestedExtension.toLowerCase() !== originalExtension.toLowerCase()) {
throw new TaskDetailAssetEditError('只能修改文件名,不能更改扩展名')
}
const outcome = await executeRebuild(context, { kind: 'rename', newBaseName: baseName })
await commitRebuild(context, outcome, 'RENAME_IMAGE')
await cleanupAfterCommit(context, outcome)
return {
success: true,
entryName: outcome.nextEntryNames[context.targetRunIndex],
}
})
}
export interface DeleteTaskDetailImageInput {
materialId: string
assetId: string
operatorUserId: string
operatorRole?: string | null
}
export async function deleteTaskDetailImage(input: DeleteTaskDetailImageInput) {
return runEditOperation(input.materialId, async () => {
const context = await loadEditContext(input)
const outcome = await executeRebuild(context, { kind: 'delete' })
await commitRebuild(context, outcome, 'DELETE_IMAGE')
await cleanupAfterCommit(context, outcome)
if (!context.wasFullSet) {
const nextIsFullSet = deriveTaskDetailIsFullSet(
context.materialType,
computeNextAssetTypes(context, outcome),
false,
)
if (nextIsFullSet) {
void queueTaskDetailFullSetNotification(context.materialId)
}
}
return { success: true }
})
}
// ---------- 批量编辑对外入口 ----------
export type BatchTaskDetailImageEditOperation =
| { kind: 'delete'; assetId: string }
| { kind: 'rename'; assetId: string; newFileName: string }
| { kind: 'replace'; assetId: string; uploadId: string }
export interface BatchTaskDetailImageEditInput {
materialId: string
operatorUserId: string
operatorRole?: string | null
operations: BatchTaskDetailImageEditOperation[]
}
const MAX_BATCH_OPERATIONS = 100
/**
* 批量单图编辑:一次提交一组删除/改名/替换操作。
* 限制:所有操作必须落在同一分组(主图/SKU/详情)内;同一张图只能出现一次。
* 全部操作要么整体成功,要么整体不变。
*/
export async function batchEditTaskDetailImages(input: BatchTaskDetailImageEditInput) {
const operations = Array.isArray(input.operations) ? input.operations : []
if (operations.length === 0) {
throw new TaskDetailAssetEditError('批量操作不能为空')
}
if (operations.length > MAX_BATCH_OPERATIONS) {
throw new TaskDetailAssetEditError(`一次最多提交 ${MAX_BATCH_OPERATIONS} 项操作,请分批提交`)
}
return runEditOperation(input.materialId, async () => {
const context = await loadEditContext({
materialId: input.materialId,
assetId: operations[0].assetId,
operatorUserId: input.operatorUserId,
operatorRole: input.operatorRole,
})
const validAssetIds = new Set(
context.runs.flatMap((run) => run.rows.map((row) => row.id)),
)
for (const operation of operations) {
if (!validAssetIds.has(operation.assetId)) {
throw new TaskDetailAssetEditError('批量操作只支持同一分组(主图/SKU/详情)内的图片')
}
}
const prepared: PreparedBatchOperation[] = []
for (const operation of operations) {
if (operation.kind === 'delete') {
prepared.push({ assetId: operation.assetId, mutation: { kind: 'delete' } })
continue
}
if (operation.kind === 'rename') {
const rawName = String(operation.newFileName || '').trim()
const baseName = sanitizeNewBaseName(stripExtension(rawName))
if (!baseName) {
throw new TaskDetailAssetEditError('文件名不能为空')
}
const runIndex = context.runs.findIndex((run) =>
run.rows.some((row) => row.id === operation.assetId),
)
const requestedExtension = getExtension(rawName)
const originalExtension = getExtension(context.entryNames[runIndex])
if (requestedExtension && requestedExtension.toLowerCase() !== originalExtension.toLowerCase()) {
throw new TaskDetailAssetEditError('只能修改文件名,不能更改扩展名')
}
prepared.push({
assetId: operation.assetId,
mutation: { kind: 'rename', newBaseName: baseName },
})
continue
}
const upload = await resolveReplacementUpload({
uploadId: operation.uploadId,
operatorUserId: input.operatorUserId,
})
prepared.push({
assetId: operation.assetId,
mutation: {
kind: 'replace',
filePath: upload.filePath,
replacementFileName: upload.fileName,
buffer: upload.buffer,
},
uploadId: operation.uploadId.trim(),
})
}
const outcome = await executeBatchRebuild(context, prepared)
const { nextIsFullSet } = await commitRebuild(context, outcome, 'BATCH_IMAGE_EDITS')
await cleanupAfterCommit(context, outcome)
for (const operation of prepared) {
if (operation.uploadId) {
await cleanupConsumedUploadSession(operation.uploadId).catch(() => undefined)
}
}
if (!context.wasFullSet && nextIsFullSet) {
void queueTaskDetailFullSetNotification(context.materialId)
}
if (context.group === 'sku' && outcome.db.previewRowsToInsert.length > 0) {
const insertedAssets = await prisma.materialAsset.findMany({
where: {
materialId: context.materialId,
assetType: GROUP_PREVIEW_TYPES.sku,
fileUrl: { in: outcome.db.previewRowsToInsert.map((row) => row.fileUrl) },
},
select: { id: true },
})
void queueTaskDetailBarcodeImagesUpdatedNotification(
context.materialId,
insertedAssets.map((row) => row.id),
)
}
return {
success: true,
appliedCount: prepared.length,
entryCount: outcome.nextEntryNames.length,
}
})
}