feat(materials): edit entire task detail image groups
This commit is contained in:
parent
cfc1452f8b
commit
2d8e3df626
@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from 'next/server'
|
||||
import { getServerSession } from 'next-auth'
|
||||
|
||||
import { authOptions } from '@/lib/auth'
|
||||
import { TaskDetailAssetEditError } from '@/lib/task-detail-asset-edit'
|
||||
import {
|
||||
listTaskDetailChanges,
|
||||
submitTaskDetailChange,
|
||||
@ -22,7 +23,7 @@ function actor(session: unknown) {
|
||||
}
|
||||
|
||||
function errorResponse(error: unknown) {
|
||||
if (error instanceof TaskDetailChangeApprovalError) {
|
||||
if (error instanceof TaskDetailChangeApprovalError || error instanceof TaskDetailAssetEditError) {
|
||||
return NextResponse.json({ success: false, error: error.message }, { status: error.statusCode })
|
||||
}
|
||||
console.error('[task-detail-change] request error:', error)
|
||||
|
||||
@ -30,7 +30,8 @@ import { getCertificateReportDisplayTitle, isCertificateReportMaterialType } fro
|
||||
import { isVideoMaterialType } from '@/lib/video-material-types'
|
||||
import { buildPublicMaterialShareUrl } from '@/lib/public-app-url'
|
||||
import { chunkUpload } from '@/lib/chunk-upload'
|
||||
import { TASK_DETAIL_UPLOAD_LIMITS } from '@/lib/task-detail-upload-policy'
|
||||
import { TASK_DETAIL_UPLOAD_LIMITS, validateTaskDetailUploadFiles } from '@/lib/task-detail-upload-policy'
|
||||
import type { TaskDetailEditGroup } from '@/lib/task-detail-asset-edit'
|
||||
|
||||
interface Material {
|
||||
accessScope?: string
|
||||
@ -101,8 +102,6 @@ interface Material {
|
||||
}>
|
||||
}
|
||||
|
||||
type TaskDetailAppendGroup = 'main' | 'sku'
|
||||
|
||||
type TaskDetailInsertIntent = {
|
||||
kind: 'insert'
|
||||
group: 'detail'
|
||||
@ -110,14 +109,17 @@ type TaskDetailInsertIntent = {
|
||||
beforeAssetId: string
|
||||
}
|
||||
|
||||
type TaskDetailBatchIntent =
|
||||
| { kind: 'append'; group: TaskDetailAppendGroup }
|
||||
type TaskDetailUploadIntent =
|
||||
| { kind: 'append'; group: TaskDetailEditGroup }
|
||||
| TaskDetailInsertIntent
|
||||
|
||||
type TaskDetailGroupIntent = { kind: 'group_images'; group: TaskDetailEditGroup; assetIds: string[] }
|
||||
type TaskDetailBatchIntent = TaskDetailUploadIntent | TaskDetailGroupIntent
|
||||
|
||||
type TaskDetailPendingOpInput =
|
||||
| {
|
||||
kind: 'append'
|
||||
group: TaskDetailAppendGroup
|
||||
group: TaskDetailEditGroup
|
||||
label: string
|
||||
uploadId: string
|
||||
}
|
||||
@ -146,6 +148,7 @@ type TaskDetailPendingOpInput =
|
||||
assetId: string
|
||||
label: string
|
||||
}
|
||||
| (TaskDetailGroupIntent & { uploadIds: string[]; label: string })
|
||||
|
||||
type TaskDetailPendingOp = TaskDetailPendingOpInput & { key: string }
|
||||
|
||||
@ -171,6 +174,8 @@ const TASK_DETAIL_GROUP_LABELS: Record<'main' | 'sku' | 'detail', string> = {
|
||||
detail: '详情图',
|
||||
}
|
||||
|
||||
const TASK_DETAIL_OPERATION_LABELS = { delete: '删除', rename: '改名', replace: '替换', append: '追加', insert: '插入' } as const
|
||||
|
||||
const TASK_DETAIL_CHANGE_REQUEST_STATUS_META: Record<string, { label: string; className: string }> = {
|
||||
pending_approval: {
|
||||
label: '待主管确认',
|
||||
@ -559,6 +564,7 @@ export default function SharePage() {
|
||||
} | null>(null)
|
||||
// 批量编辑攒批清单:先在前端整理一组变更,再统一提交给主管确认或直接应用。
|
||||
const [taskDetailPendingOps, setTaskDetailPendingOps] = useState<TaskDetailPendingOp[]>([])
|
||||
const pendingGroupEdit = taskDetailPendingOps.some((op) => op.kind === 'group_images')
|
||||
const [taskDetailApplying, setTaskDetailApplying] = useState(false)
|
||||
const [taskDetailChangeRequestNotice, setTaskDetailChangeRequestNotice] = useState<TaskDetailChangeRequestNotice | null>(null)
|
||||
const taskDetailPendingBarRef = useRef<HTMLDivElement | null>(null)
|
||||
@ -1183,7 +1189,7 @@ export default function SharePage() {
|
||||
})
|
||||
}
|
||||
|
||||
// ---- 任务-详情单图编辑 ----
|
||||
// ---- 任务-详情图片编辑 ----
|
||||
|
||||
const getTaskDetailAssetGroup = (assetId: string): 'main' | 'sku' | 'detail' | null => {
|
||||
const assetType = material?.assets?.find((asset) => asset.id === assetId)?.assetType
|
||||
@ -1194,16 +1200,18 @@ export default function SharePage() {
|
||||
}
|
||||
|
||||
const getTaskDetailPendingOpGroup = (op: TaskDetailPendingOpInput | TaskDetailPendingOp) => {
|
||||
if (op.kind === 'append') return op.group
|
||||
if (op.kind === 'insert') return 'detail' as const
|
||||
return getTaskDetailAssetGroup(op.assetId)
|
||||
return 'group' in op ? op.group : getTaskDetailAssetGroup(op.assetId)
|
||||
}
|
||||
|
||||
const canStartTaskDetailGroup = (group: 'main' | 'sku' | 'detail' | null) => {
|
||||
const canStartTaskDetailGroup = (group: TaskDetailEditGroup | null, wholeGroup = false) => {
|
||||
if (!group) {
|
||||
showToast('图片分组识别失败,请刷新后重试', { variant: 'error' })
|
||||
return false
|
||||
}
|
||||
if (pendingGroupEdit || (wholeGroup && taskDetailPendingOps.length > 0)) {
|
||||
showToast('请先提交或撤销待提交变更,再处理整组图片', { variant: 'error' })
|
||||
return false
|
||||
}
|
||||
const currentGroup = taskDetailPendingOps[0]
|
||||
? getTaskDetailPendingOpGroup(taskDetailPendingOps[0])
|
||||
: null
|
||||
@ -1229,7 +1237,7 @@ export default function SharePage() {
|
||||
const queueTaskDetailPendingOp = (
|
||||
nextOp: TaskDetailPendingOpInput,
|
||||
) => {
|
||||
if (!canStartTaskDetailGroup(getTaskDetailPendingOpGroup(nextOp))) return false
|
||||
if (!canStartTaskDetailGroup(getTaskDetailPendingOpGroup(nextOp), nextOp.kind === 'group_images')) return false
|
||||
setTaskDetailPendingOps((prev) => {
|
||||
const withKey: TaskDetailPendingOp = {
|
||||
...nextOp,
|
||||
@ -1248,7 +1256,7 @@ export default function SharePage() {
|
||||
return true
|
||||
}
|
||||
|
||||
const openTaskDetailAppendPicker = (group: TaskDetailAppendGroup) => {
|
||||
const openTaskDetailAppendPicker = (group: TaskDetailEditGroup) => {
|
||||
if (!canStartTaskDetailGroup(group)) return
|
||||
const input = taskDetailBatchInputRef.current
|
||||
taskDetailBatchIntentRef.current = { kind: 'append', group }
|
||||
@ -1268,7 +1276,92 @@ export default function SharePage() {
|
||||
}
|
||||
}
|
||||
|
||||
const queueTaskDetailUploads = async (files: File[], intent: TaskDetailBatchIntent) => {
|
||||
const openTaskDetailGroupReplacePicker = (group: TaskDetailEditGroup, assetIds: string[]) => {
|
||||
if (!canStartTaskDetailGroup(group, true)) return
|
||||
const input = taskDetailBatchInputRef.current
|
||||
if (!input) return
|
||||
taskDetailBatchIntentRef.current = { kind: 'group_images', group, assetIds }
|
||||
input.value = ''
|
||||
input.click()
|
||||
}
|
||||
|
||||
const queueTaskDetailGroupDelete = (group: TaskDetailEditGroup, assetIds: string[]) => {
|
||||
if (queueTaskDetailPendingOp({
|
||||
kind: 'group_images',
|
||||
group,
|
||||
assetIds,
|
||||
uploadIds: [],
|
||||
label: `${TASK_DETAIL_GROUP_LABELS[group]}全部 ${assetIds.length} 张`,
|
||||
})) {
|
||||
showToast('整组删除已加入待提交清单,可以撤销', { variant: 'success' })
|
||||
}
|
||||
}
|
||||
|
||||
const queueTaskDetailGroupReplacement = async (files: File[], intent: TaskDetailGroupIntent) => {
|
||||
if (!material || !canStartTaskDetailGroup(intent.group, true)) return
|
||||
const { group, assetIds } = intent
|
||||
const label = TASK_DETAIL_GROUP_LABELS[group]
|
||||
if (group === 'sku' && files.length !== assetIds.length) {
|
||||
showToast(`整组替换 SKU 图需要选择 ${assetIds.length} 张新图,当前选择了 ${files.length} 张`, { variant: 'error' })
|
||||
return
|
||||
}
|
||||
const validation = validateTaskDetailUploadFiles({ main: [], sku: [], detail: [], [group]: files })
|
||||
if (validation) {
|
||||
showToast(validation, { variant: 'error' })
|
||||
return
|
||||
}
|
||||
const assetsById = new Map((material.assets || []).map((asset) => [asset.id, asset]))
|
||||
const { confirmed } = await confirmAction({
|
||||
title: `确认替换全部${label}`,
|
||||
description: (
|
||||
<>
|
||||
<p>用 {files.length} 张新原图替换本组全部 {assetIds.length} 张预览。请核对图片顺序。</p>
|
||||
{group === 'sku' && <p className="mt-1">每个位置保留原 SKU 编号和条码。</p>}
|
||||
<ol aria-label="新图片替换顺序" tabIndex={0} className="mt-3 max-h-48 list-decimal space-y-1 overflow-y-auto pl-5 pr-2 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#1a1c1d]">
|
||||
{files.map((file, index) => (
|
||||
<li key={index} className="[overflow-wrap:anywhere]">
|
||||
{group === 'sku' && `${assetsById.get(assetIds[index])?.fileName || `SKU 图 ${index + 1}`} → `}
|
||||
{file.name}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</>
|
||||
),
|
||||
confirmLabel: '上传并加入待提交',
|
||||
})
|
||||
if (!confirmed) return
|
||||
|
||||
setTaskDetailEditingAssetId(`group-${group}`)
|
||||
try {
|
||||
const uploadIds: string[] = []
|
||||
for (let index = 0; index < files.length; index += 1) {
|
||||
const file = files[index]
|
||||
const progressLabel = `正在上传${label}替换文件 ${index + 1}/${files.length}`
|
||||
setTaskDetailUploadProgress({ label: progressLabel, progress: 0 })
|
||||
const result = await chunkUpload(file, {}, {
|
||||
skipComplete: true,
|
||||
onProgress: (progress) => setTaskDetailUploadProgress({ label: progressLabel, progress }),
|
||||
})
|
||||
const uploadId = (result as { uploadId?: string } | null)?.uploadId
|
||||
if (!uploadId) throw new Error(`${file.name} 上传未完成,请重新选择图片`)
|
||||
uploadIds.push(uploadId)
|
||||
}
|
||||
if (queueTaskDetailPendingOp({
|
||||
...intent,
|
||||
uploadIds,
|
||||
label: `${label}全部 ${assetIds.length} 张预览,换为 ${files.length} 张原图`,
|
||||
})) {
|
||||
showToast('整组替换已加入待提交清单', { variant: 'success' })
|
||||
}
|
||||
} catch (error) {
|
||||
showToast(error instanceof Error ? error.message : '整组替换上传失败,请重新选择图片', { variant: 'error' })
|
||||
} finally {
|
||||
setTaskDetailEditingAssetId(null)
|
||||
setTaskDetailUploadProgress(null)
|
||||
}
|
||||
}
|
||||
|
||||
const queueTaskDetailUploads = async (files: File[], intent: TaskDetailUploadIntent) => {
|
||||
if (!material || files.length === 0) return
|
||||
|
||||
const uploadLabel = intent.kind === 'append'
|
||||
@ -1455,7 +1548,7 @@ export default function SharePage() {
|
||||
}
|
||||
|
||||
const applyTaskDetailPendingOps = async () => {
|
||||
if (!material || taskDetailPendingOps.length === 0 || taskDetailApplying) return
|
||||
if (!material || taskDetailPendingOps.length === 0 || taskDetailApplying || taskDetailEditingAssetId) return
|
||||
setTaskDetailApplying(true)
|
||||
try {
|
||||
const response = await fetch(`/api/materials/${material.id}/assets/change-requests`, {
|
||||
@ -1464,6 +1557,8 @@ export default function SharePage() {
|
||||
body: JSON.stringify({
|
||||
operations: taskDetailPendingOps.map((op) => {
|
||||
switch (op.kind) {
|
||||
case 'group_images':
|
||||
return { kind: op.kind, group: op.group, assetIds: op.assetIds, uploadIds: op.uploadIds }
|
||||
case 'append':
|
||||
return { kind: 'append', group: op.group, uploadId: op.uploadId }
|
||||
case 'insert':
|
||||
@ -1625,13 +1720,15 @@ export default function SharePage() {
|
||||
待提交变更 {taskDetailPendingOps.length} 项
|
||||
</p>
|
||||
<p className="mt-1 text-[12px] leading-5 text-[#6b7075]">
|
||||
替换和插入文件先留在临时区,点击提交后再进入主管确认,不会立即覆盖正式素材。
|
||||
{pendingGroupEdit
|
||||
? '整组变更可以撤销。提交后按权限直接应用或交主管确认。'
|
||||
: '替换和插入文件先留在临时区,点击提交后再进入主管确认,不会立即覆盖正式素材。'}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
disabled={taskDetailApplying}
|
||||
disabled={taskDetailApplying || Boolean(taskDetailEditingAssetId)}
|
||||
onClick={() => setTaskDetailPendingOps([])}
|
||||
className="rounded-lg border border-[#e7e8ea] px-3 py-1.5 text-[12px] text-[#6b7075] transition-colors hover:bg-[#fafafa] disabled:opacity-50"
|
||||
>
|
||||
@ -1639,47 +1736,40 @@ export default function SharePage() {
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={taskDetailApplying}
|
||||
disabled={taskDetailApplying || Boolean(taskDetailEditingAssetId)}
|
||||
data-apply-btn
|
||||
onClick={() => void applyTaskDetailPendingOps()}
|
||||
className="min-h-10 rounded-lg bg-[#1a1c1d] px-4 py-1.5 text-[12px] font-medium text-white transition-all hover:opacity-80 active:scale-[0.99] disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
{taskDetailApplying ? '正在提交…' : `提交主管确认 ${taskDetailPendingOps.length} 项`}
|
||||
{taskDetailApplying ? '正在提交…' : pendingGroupEdit ? '提交整组变更' : `提交主管确认 ${taskDetailPendingOps.length} 项`}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<ul className="mt-3 space-y-1.5">
|
||||
{taskDetailPendingOps.map((op) => (
|
||||
<li key={op.key} data-pending-op className="flex items-center justify-between gap-3 rounded-lg bg-[#fafafa] px-3 py-1.5">
|
||||
<span className="min-w-0 flex-1 truncate text-[12px] text-[#1a1c1d]">
|
||||
<span className={
|
||||
op.kind === 'delete'
|
||||
? 'mr-2 text-[#b42318]'
|
||||
: 'mr-2 text-[#6b7075]'
|
||||
}>
|
||||
{op.kind === 'delete'
|
||||
? '删除'
|
||||
: op.kind === 'rename'
|
||||
? '改名'
|
||||
: op.kind === 'replace'
|
||||
? '替换'
|
||||
: op.kind === 'append'
|
||||
? '追加'
|
||||
: '插入'}
|
||||
{taskDetailPendingOps.map((op) => {
|
||||
const actionLabel = op.kind === 'group_images'
|
||||
? (op.uploadIds.length > 0 ? '替换' : '删除')
|
||||
: TASK_DETAIL_OPERATION_LABELS[op.kind]
|
||||
return (
|
||||
<li key={op.key} data-pending-op className="flex items-center justify-between gap-3 rounded-lg bg-[#fafafa] px-3 py-1.5">
|
||||
<span className={`min-w-0 flex-1 text-[12px] text-[#1a1c1d] ${op.kind === 'group_images' ? 'break-words' : 'truncate'}`}>
|
||||
<span className={actionLabel === '删除' ? 'mr-2 text-[#b42318]' : 'mr-2 text-[#6b7075]'}>
|
||||
{actionLabel}
|
||||
</span>
|
||||
{op.label}
|
||||
</span>
|
||||
{op.label}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
disabled={taskDetailApplying}
|
||||
onClick={() => setTaskDetailPendingOps((prev) => prev.filter((item) => item.key !== op.key))}
|
||||
className="text-[12px] text-[#86898e] transition-colors hover:text-[#b42318] disabled:opacity-50"
|
||||
aria-label="撤销这项操作"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
disabled={taskDetailApplying || Boolean(taskDetailEditingAssetId)}
|
||||
onClick={() => setTaskDetailPendingOps((prev) => prev.filter((item) => item.key !== op.key))}
|
||||
className="text-[12px] text-[#86898e] transition-colors hover:text-[#b42318] disabled:opacity-50"
|
||||
aria-label="撤销这项操作"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
@ -1700,12 +1790,18 @@ export default function SharePage() {
|
||||
showToast={showToast}
|
||||
canManageAssets={Boolean(material.canManageTaskDetailAssets)}
|
||||
editingAssetId={taskDetailEditingAssetId}
|
||||
pendingAssetIds={taskDetailPendingOps.flatMap((op) => ('assetId' in op ? [op.assetId] : []))}
|
||||
assetEditingDisabled={taskDetailApplying || pendingGroupEdit}
|
||||
pendingAssetIds={taskDetailPendingOps.flatMap((op) => {
|
||||
if (op.kind === 'group_images') return op.assetIds
|
||||
return 'assetId' in op ? [op.assetId] : []
|
||||
})}
|
||||
onRequestReplace={handleTaskDetailReplaceRequest}
|
||||
onRequestRename={openTaskDetailRenameDialog}
|
||||
onRequestDelete={(asset) => void handleTaskDetailDeleteRequest(asset)}
|
||||
onRequestAppend={(group) => openTaskDetailAppendPicker(group)}
|
||||
onRequestInsert={(position) => openTaskDetailInsertPicker(position)}
|
||||
onRequestGroupDelete={queueTaskDetailGroupDelete}
|
||||
onRequestGroupReplace={openTaskDetailGroupReplacePicker}
|
||||
onDownload={async (type, assetId) => {
|
||||
try {
|
||||
let directDownloadUrl = `/api/materials/download?id=${material.id}&type=${type}`
|
||||
@ -2339,8 +2435,10 @@ export default function SharePage() {
|
||||
onChange={(event) => {
|
||||
const files = Array.from(event.target.files || [])
|
||||
const intent = taskDetailBatchIntentRef.current
|
||||
taskDetailBatchIntentRef.current = null
|
||||
if (intent && files.length > 0) {
|
||||
void queueTaskDetailUploads(files, intent)
|
||||
if (intent.kind === 'group_images') void queueTaskDetailGroupReplacement(files, intent)
|
||||
else void queueTaskDetailUploads(files, intent)
|
||||
}
|
||||
event.target.value = ''
|
||||
}}
|
||||
|
||||
@ -16,6 +16,8 @@ type TaskDetailChangeRequestOperation = {
|
||||
afterAssetId?: string | null
|
||||
beforeAssetId?: string | null
|
||||
newFileName?: string | null
|
||||
affectedCount?: number
|
||||
fileNames?: string[]
|
||||
}
|
||||
|
||||
type TaskDetailChangeRequestViewModel = {
|
||||
@ -126,6 +128,10 @@ function normalizeChangeRequestPayload(payload: unknown): TaskDetailChangeReques
|
||||
afterAssetId: readText(op.afterAssetId),
|
||||
beforeAssetId: readText(op.beforeAssetId),
|
||||
newFileName: readText(op.newFileName),
|
||||
affectedCount: typeof op.affectedCount === 'number' ? op.affectedCount : undefined,
|
||||
fileNames: Array.isArray(op.fileNames)
|
||||
? op.fileNames.filter((name): name is string => typeof name === 'string')
|
||||
: undefined,
|
||||
}
|
||||
})
|
||||
: []
|
||||
@ -166,6 +172,13 @@ function normalizeChangeRequestPayload(payload: unknown): TaskDetailChangeReques
|
||||
function describeOperation(op: TaskDetailChangeRequestOperation, index: number) {
|
||||
if (op.label) return op.label
|
||||
|
||||
if (op.kind === 'group_images') {
|
||||
const groupLabel = op.group ? GROUP_LABELS[op.group] : '图片'
|
||||
const count = op.affectedCount ?? 0
|
||||
return op.fileNames?.length
|
||||
? `替换${groupLabel}全部 ${count} 张预览,换为 ${op.fileNames.length} 张原图`
|
||||
: `删除${groupLabel}全部 ${count} 张`
|
||||
}
|
||||
if (op.kind === 'append') {
|
||||
const groupLabel = GROUP_LABELS[op.group || 'main']
|
||||
return `追加到${groupLabel}末尾`
|
||||
@ -439,7 +452,9 @@ export default function TaskDetailChangeRequestPage() {
|
||||
<div className="min-w-0">
|
||||
<p className="break-all text-[13px] font-medium text-[#1a1c1d]">{describeOperation(op, index)}</p>
|
||||
<p className="mt-1 text-[12px] text-[#86898e]">
|
||||
{op.kind === 'append'
|
||||
{op.kind === 'group_images'
|
||||
? '通过后将同步更新这组图片的预览与下载包'
|
||||
: op.kind === 'append'
|
||||
? '追加图片会在主管通过后追加到分组末尾'
|
||||
: op.kind === 'insert'
|
||||
? '插入图片会按当前接缝位置进入待处理链路'
|
||||
@ -451,9 +466,21 @@ export default function TaskDetailChangeRequestPage() {
|
||||
</p>
|
||||
</div>
|
||||
<span className="rounded-full border border-[#d7dde3] bg-white px-2 py-0.5 text-[11px] font-medium text-[#66758b]">
|
||||
{op.kind}
|
||||
{op.kind === 'group_images' ? '整组' : op.kind}
|
||||
</span>
|
||||
</div>
|
||||
{op.kind === 'group_images' && Boolean(op.fileNames?.length) && (
|
||||
<details className="mt-2 text-[13px] text-[#4f6077]">
|
||||
<summary className="cursor-pointer rounded focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#1a1c1d]/70">
|
||||
查看替换顺序
|
||||
</summary>
|
||||
<ol className="mt-2 list-decimal space-y-1 pl-5">
|
||||
{op.fileNames?.map((fileName, fileIndex) => (
|
||||
<li key={fileIndex} className="break-all">{fileName}</li>
|
||||
))}
|
||||
</ol>
|
||||
</details>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
|
||||
@ -7,6 +7,7 @@
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { parseDownloadError } from '@/lib/download-errors';
|
||||
import { getTaskDetailSourceTypeLabel } from '@/lib/task-detail-source-type';
|
||||
import type { TaskDetailEditGroup } from '@/lib/task-detail-asset-edit';
|
||||
import {
|
||||
detailInkButtonClass,
|
||||
detailOutlineButtonClass,
|
||||
@ -27,8 +28,6 @@ interface Asset {
|
||||
sortOrder: number;
|
||||
}
|
||||
|
||||
type AppendableGroup = 'main' | 'sku';
|
||||
|
||||
type DetailInsertPosition = {
|
||||
group: 'detail';
|
||||
afterAssetId: string;
|
||||
@ -59,15 +58,31 @@ interface ProductPackageDetailProps {
|
||||
canManageAssets?: boolean;
|
||||
/** 正在编辑处理的资产 id,用于禁用与遮罩 */
|
||||
editingAssetId?: string | null;
|
||||
assetEditingDisabled?: boolean;
|
||||
onRequestReplace?: (asset: Asset) => void;
|
||||
onRequestRename?: (asset: Asset) => void;
|
||||
onRequestDelete?: (asset: Asset) => void;
|
||||
onRequestAppend?: (group: AppendableGroup) => void;
|
||||
onRequestAppend?: (group: TaskDetailEditGroup) => void;
|
||||
onRequestInsert?: (position: DetailInsertPosition) => void;
|
||||
onRequestGroupDelete?: (group: TaskDetailEditGroup, assetIds: string[]) => void;
|
||||
onRequestGroupReplace?: (group: TaskDetailEditGroup, assetIds: string[]) => void;
|
||||
/** 已加入待提交清单的资产 id,缩略图上显示待提交标记 */
|
||||
pendingAssetIds?: string[];
|
||||
}
|
||||
|
||||
const groupActionClass =
|
||||
'min-h-10 rounded-[8px] px-2.5 text-sm font-medium transition-colors hover:bg-[#f1f3f5] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#1a1c1d]/70 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50'
|
||||
|
||||
function GroupSelectionMark() {
|
||||
return (
|
||||
<span aria-hidden="true" className="pointer-events-none absolute bottom-1 left-1 z-10 flex h-5 w-5 items-center justify-center rounded bg-[#1a1c1d] text-white">
|
||||
<svg viewBox="0 0 16 16" className="h-3.5 w-3.5" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
|
||||
<path d="m3.5 8 3 3 6-6" />
|
||||
</svg>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function AddImageButton({
|
||||
label,
|
||||
hint,
|
||||
@ -222,11 +237,14 @@ export default function ProductPackageDetail({
|
||||
showToast,
|
||||
canManageAssets = false,
|
||||
editingAssetId = null,
|
||||
assetEditingDisabled = false,
|
||||
onRequestReplace,
|
||||
onRequestRename,
|
||||
onRequestDelete,
|
||||
onRequestAppend,
|
||||
onRequestInsert,
|
||||
onRequestGroupDelete,
|
||||
onRequestGroupReplace,
|
||||
pendingAssetIds = [],
|
||||
}: ProductPackageDetailProps) {
|
||||
// 当前预览的图片类型和索引
|
||||
@ -235,6 +253,7 @@ export default function ProductPackageDetail({
|
||||
const [currentSkuIndex, setCurrentSkuIndex] = useState(0);
|
||||
const [downloading, setDownloading] = useState(false);
|
||||
const [downloadType, setDownloadType] = useState<string>('');
|
||||
const [selectedGroup, setSelectedGroup] = useState<TaskDetailEditGroup | null>(null);
|
||||
|
||||
// 轮播相关状态
|
||||
const [autoPlayEnabled, setAutoPlayEnabled] = useState(true);
|
||||
@ -244,6 +263,66 @@ export default function ProductPackageDetail({
|
||||
const skuImages = material.assets.filter((a) => a.assetType === 'sku-preview').sort((a, b) => a.sortOrder - b.sortOrder);
|
||||
const detailImages = material.assets.filter((a) => a.assetType === 'detail-preview').sort((a, b) => a.sortOrder - b.sortOrder);
|
||||
const psdFiles = material.assets.filter((a) => a.assetType === 'psd');
|
||||
const pendingIds = new Set(pendingAssetIds);
|
||||
const editsDisabled = Boolean(editingAssetId) || assetEditingDisabled;
|
||||
|
||||
useEffect(() => {
|
||||
setSelectedGroup(null);
|
||||
setCurrentMainIndex((index) => Math.min(index, Math.max(0, mainImages.length - 1)));
|
||||
setCurrentSkuIndex((index) => Math.min(index, Math.max(0, skuImages.length - 1)));
|
||||
setPreviewType((group) => {
|
||||
if (group === 'main' && mainImages.length === 0 && skuImages.length > 0) return 'sku';
|
||||
if (group === 'sku' && skuImages.length === 0 && mainImages.length > 0) return 'main';
|
||||
return group;
|
||||
});
|
||||
}, [material.id, material.assets, mainImages.length, skuImages.length]);
|
||||
|
||||
const renderImageGroupHeading = (group: TaskDetailEditGroup, label: string, images: Asset[]) => {
|
||||
const heading = <h4 className={detailSectionTitleClass}>{label} ({images.length})</h4>;
|
||||
if (!canManageAssets || images.length === 0 || !onRequestGroupDelete || !onRequestGroupReplace) {
|
||||
return heading;
|
||||
}
|
||||
const selected = selectedGroup === group;
|
||||
return (
|
||||
<div className="mb-2 flex flex-wrap items-baseline justify-between gap-x-2">
|
||||
{heading}
|
||||
<div className="flex flex-wrap items-center gap-x-1">
|
||||
<button
|
||||
type="button"
|
||||
className={`${groupActionClass} text-[#1a1c1d]`}
|
||||
aria-label={`${selected ? '取消全选' : '全选'}${label}`}
|
||||
aria-pressed={selected}
|
||||
disabled={editsDisabled}
|
||||
onClick={() => setSelectedGroup(selected ? null : group)}
|
||||
>
|
||||
{selected ? '取消全选' : '全选'}
|
||||
</button>
|
||||
{selected && (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
className={`${groupActionClass} text-[#1a1c1d]`}
|
||||
aria-label={`替换全部${label}`}
|
||||
disabled={editsDisabled}
|
||||
onClick={() => onRequestGroupReplace(group, images.map((image) => image.id))}
|
||||
>
|
||||
替换全部
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`${groupActionClass} text-[#b42318]`}
|
||||
aria-label={`删除全部${label}`}
|
||||
disabled={editsDisabled}
|
||||
onClick={() => onRequestGroupDelete(group, images.map((image) => image.id))}
|
||||
>
|
||||
删除全部
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// 轮播逻辑
|
||||
const autoPlayTimerRef = useRef<NodeJS.Timeout | null>(null);
|
||||
@ -338,7 +417,7 @@ export default function ProductPackageDetail({
|
||||
{/* 主图小卡片展示区 */}
|
||||
{(mainImages.length > 0 || (canManageAssets && onRequestAppend)) && (
|
||||
<div className={`${detailPanelClass} p-4`}>
|
||||
<h4 className={detailSectionTitleClass}>主图 ({mainImages.length})</h4>
|
||||
{renderImageGroupHeading('main', '主图', mainImages)}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{mainImages.map((img, index) => (
|
||||
<div
|
||||
@ -376,7 +455,7 @@ export default function ProductPackageDetail({
|
||||
alt={`主图 ${index + 1}`}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
{previewType === 'main' && index === currentMainIndex && (
|
||||
{selectedGroup !== 'main' && previewType === 'main' && index === currentMainIndex && (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-[#1a1c1d]/20">
|
||||
<svg className="h-6 w-6 text-white" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
|
||||
@ -384,12 +463,13 @@ export default function ProductPackageDetail({
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
{selectedGroup === 'main' && <GroupSelectionMark />}
|
||||
{canManageAssets && onRequestReplace && onRequestRename && onRequestDelete && (
|
||||
<>
|
||||
<AssetEditMenu
|
||||
asset={img}
|
||||
busy={editingAssetId === img.id}
|
||||
disabled={Boolean(editingAssetId)}
|
||||
disabled={editsDisabled}
|
||||
onRequestReplace={onRequestReplace}
|
||||
onRequestRename={onRequestRename}
|
||||
onRequestDelete={onRequestDelete}
|
||||
@ -397,7 +477,7 @@ export default function ProductPackageDetail({
|
||||
{editingAssetId === img.id && (
|
||||
<span className="pointer-events-none absolute inset-0 z-0 animate-pulse rounded-[8px] border border-[#1a1c1d]/30 bg-white/60" />
|
||||
)}
|
||||
{pendingAssetIds.includes(img.id) && (
|
||||
{pendingIds.has(img.id) && (
|
||||
<span className="pointer-events-none absolute left-1 top-1 z-10 rounded bg-[#1a1c1d]/80 px-1.5 py-0.5 text-[10px] font-medium text-white">待提交</span>
|
||||
)}
|
||||
</>
|
||||
@ -408,7 +488,7 @@ export default function ProductPackageDetail({
|
||||
<AddImageButton
|
||||
label="追加图片"
|
||||
hint="加入主图末尾"
|
||||
disabled={Boolean(editingAssetId)}
|
||||
disabled={editsDisabled}
|
||||
onClick={() => onRequestAppend('main')}
|
||||
className="h-[84px] w-[84px] flex-shrink-0"
|
||||
/>
|
||||
@ -418,9 +498,9 @@ export default function ProductPackageDetail({
|
||||
)}
|
||||
|
||||
{/* 详情图区域(使用页面整体滚动,图片无缝拼接) */}
|
||||
{detailImages.length > 0 && (
|
||||
{(detailImages.length > 0 || (canManageAssets && onRequestAppend)) && (
|
||||
<div className={`${detailPanelClass} p-4`}>
|
||||
<h4 className={detailSectionTitleClass}>详情图 ({detailImages.length})</h4>
|
||||
{renderImageGroupHeading('detail', '详情图', detailImages)}
|
||||
<div className="space-y-0">
|
||||
{detailImages.map((img, index) => (
|
||||
<div key={img.id}>
|
||||
@ -434,12 +514,13 @@ export default function ProductPackageDetail({
|
||||
<div className="absolute left-2 top-2 bg-[#1a1c1d] px-2 py-1 text-[11px] text-white">
|
||||
{index + 1}
|
||||
</div>
|
||||
{selectedGroup === 'detail' && <GroupSelectionMark />}
|
||||
{canManageAssets && onRequestReplace && onRequestRename && onRequestDelete && (
|
||||
<>
|
||||
<AssetEditMenu
|
||||
asset={img}
|
||||
busy={editingAssetId === img.id}
|
||||
disabled={Boolean(editingAssetId)}
|
||||
disabled={editsDisabled}
|
||||
onRequestReplace={onRequestReplace}
|
||||
onRequestRename={onRequestRename}
|
||||
onRequestDelete={onRequestDelete}
|
||||
@ -449,7 +530,7 @@ export default function ProductPackageDetail({
|
||||
正在上传临时图片,请稍候…
|
||||
</span>
|
||||
)}
|
||||
{pendingAssetIds.includes(img.id) && (
|
||||
{pendingIds.has(img.id) && (
|
||||
<span className="pointer-events-none absolute left-1 top-1 z-10 rounded bg-[#1a1c1d]/80 px-1.5 py-0.5 text-[10px] font-medium text-white">待提交</span>
|
||||
)}
|
||||
</>
|
||||
@ -457,7 +538,7 @@ export default function ProductPackageDetail({
|
||||
</div>
|
||||
{canManageAssets && onRequestInsert && detailImages[index + 1] && (
|
||||
<DetailInsertButton
|
||||
disabled={Boolean(editingAssetId)}
|
||||
disabled={editsDisabled}
|
||||
afterIndex={index + 1}
|
||||
beforeIndex={index + 2}
|
||||
onClick={() => onRequestInsert({
|
||||
@ -469,6 +550,15 @@ export default function ProductPackageDetail({
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{detailImages.length === 0 && canManageAssets && onRequestAppend && (
|
||||
<AddImageButton
|
||||
label="添加详情图"
|
||||
hint="上传详情图原图"
|
||||
disabled={editsDisabled}
|
||||
onClick={() => onRequestAppend('detail')}
|
||||
className="min-h-20 w-full"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
@ -522,7 +612,7 @@ export default function ProductPackageDetail({
|
||||
{/* SKU图小卡片展示区 */}
|
||||
{(skuImages.length > 0 || (canManageAssets && onRequestAppend)) && (
|
||||
<div className={`${detailPanelClass} p-4`}>
|
||||
<h4 className={detailSectionTitleClass}>SKU图 ({skuImages.length})</h4>
|
||||
{renderImageGroupHeading('sku', 'SKU图', skuImages)}
|
||||
<div className="grid grid-cols-4 gap-2">
|
||||
{skuImages.map((img, index) => (
|
||||
<div key={img.id} className="group relative aspect-square w-full">
|
||||
@ -546,7 +636,7 @@ export default function ProductPackageDetail({
|
||||
alt={`SKU图 ${index + 1}`}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
{previewType === 'sku' && index === currentSkuIndex && (
|
||||
{selectedGroup !== 'sku' && previewType === 'sku' && index === currentSkuIndex && (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-[#1a1c1d]/20">
|
||||
<svg className="h-6 w-6 text-white" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
|
||||
@ -554,12 +644,13 @@ export default function ProductPackageDetail({
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
{selectedGroup === 'sku' && <GroupSelectionMark />}
|
||||
{canManageAssets && onRequestReplace && onRequestRename && onRequestDelete && (
|
||||
<>
|
||||
<AssetEditMenu
|
||||
asset={img}
|
||||
busy={editingAssetId === img.id}
|
||||
disabled={Boolean(editingAssetId)}
|
||||
disabled={editsDisabled}
|
||||
onRequestReplace={onRequestReplace}
|
||||
onRequestRename={onRequestRename}
|
||||
onRequestDelete={onRequestDelete}
|
||||
@ -567,7 +658,7 @@ export default function ProductPackageDetail({
|
||||
{editingAssetId === img.id && (
|
||||
<span className="pointer-events-none absolute inset-0 z-0 animate-pulse rounded-[8px] border border-[#1a1c1d]/30 bg-white/60" />
|
||||
)}
|
||||
{pendingAssetIds.includes(img.id) && (
|
||||
{pendingIds.has(img.id) && (
|
||||
<span className="pointer-events-none absolute left-1 top-1 z-10 rounded bg-[#1a1c1d]/80 px-1.5 py-0.5 text-[10px] font-medium text-white">待提交</span>
|
||||
)}
|
||||
</>
|
||||
@ -578,7 +669,7 @@ export default function ProductPackageDetail({
|
||||
<AddImageButton
|
||||
label="追加图片"
|
||||
hint="加入 SKU 末尾"
|
||||
disabled={Boolean(editingAssetId)}
|
||||
disabled={editsDisabled}
|
||||
onClick={() => onRequestAppend('sku')}
|
||||
className="aspect-square w-full"
|
||||
/>
|
||||
|
||||
@ -7,7 +7,7 @@ import os from 'os'
|
||||
import path from 'path'
|
||||
import sharp from 'sharp'
|
||||
|
||||
jest.mock('child_process', () => ({ execFile: jest.fn() }))
|
||||
jest.mock('child_process', () => ({ ...jest.requireActual('child_process'), execFile: jest.fn() }))
|
||||
jest.mock('@/lib/material-authorization', () => ({ canManageMaterial: jest.fn() }))
|
||||
jest.mock('@/lib/material-log', () => ({ createMaterialLog: jest.fn().mockResolvedValue(undefined) }))
|
||||
jest.mock('@/lib/file-cleanup', () => ({ deleteFileIfUnreferenced: jest.fn().mockResolvedValue(undefined) }))
|
||||
@ -45,6 +45,7 @@ jest.mock('@/lib/zip-entry-reader', () => ({
|
||||
jest.mock('@/lib/upload-paths', () => ({ resolveStoredUploadPath: jest.fn((value: string) => value) }))
|
||||
jest.mock('@/lib/prisma', () => ({
|
||||
prisma: {
|
||||
user: { findUnique: jest.fn().mockResolvedValue({ isSuperAdmin: false }) },
|
||||
material: {
|
||||
findFirst: jest.fn(),
|
||||
update: jest.fn(),
|
||||
@ -264,6 +265,57 @@ describe('task-detail asset edit batch data-plane', () => {
|
||||
}
|
||||
}
|
||||
|
||||
test('整组删除可一次清除超过 100 张主图,保留其他组和封面', async () => {
|
||||
const mainRows = Array.from({ length: 110 }, (_, index) => ({
|
||||
id: `main-${index}`,
|
||||
assetType: 'main-preview',
|
||||
fileUrl: `https://preview/main-${index}.webp`,
|
||||
fileName: `main-${index}-preview.webp`,
|
||||
sortOrder: index,
|
||||
}))
|
||||
const sku = { id: 'sku-1', assetType: 'sku-preview', fileUrl: 'https://preview/sku.webp', fileName: 'sku.webp', sortOrder: 0 }
|
||||
;(prisma.material.findFirst as jest.Mock).mockResolvedValue({ ...material, previewUrl: mainRows[0].fileUrl })
|
||||
configureAssetQueries({
|
||||
previewRows: [...mainRows, sku],
|
||||
zipRows: ['main', 'sku', 'all'].map((group) => ({
|
||||
id: `zip-${group}`, assetType: group, fileUrl: path.join(tempRoot, `${group}.zip`), fileName: `${group}.zip`,
|
||||
})),
|
||||
})
|
||||
mockListZipEntries.mockResolvedValue(mainRows.map(({ id }) => ({ name: `${id}.png` })))
|
||||
const assetIds = mainRows.map(({ id }) => id)
|
||||
|
||||
await expect(batchEditTaskDetailImages({
|
||||
materialId: 'material-1', operatorUserId: 'operator-1',
|
||||
operations: [{ kind: 'group_images', group: 'main', assetIds, files: [] }],
|
||||
})).resolves.toMatchObject({ appliedCount: 1, entryCount: 0 })
|
||||
|
||||
expect(mockExtractZipEntries).not.toHaveBeenCalled()
|
||||
expect(mockCreateZipFromFiles).not.toHaveBeenCalled()
|
||||
expect(mockCreateZipFromZips.mock.calls[0][0]).toEqual([{ path: path.join(tempRoot, 'sku.zip'), name: 'sku.zip' }])
|
||||
expect(prisma.materialAsset.deleteMany).toHaveBeenCalledWith({ where: { id: { in: assetIds } } })
|
||||
expect(prisma.material.update).toHaveBeenCalledWith(expect.objectContaining({
|
||||
data: expect.objectContaining({ previewUrl: sku.fileUrl }),
|
||||
}))
|
||||
})
|
||||
|
||||
test('全选后分组发生变化,整组删除不更新正式素材', async () => {
|
||||
configureAssetQueries({
|
||||
previewRows: [1, 2].map((index) => ({
|
||||
id: `current-${index}`, assetType: 'main-preview', fileUrl: `https://preview/main-${index}.webp`,
|
||||
fileName: `main-${index}-preview.webp`, sortOrder: index - 1,
|
||||
})),
|
||||
zipRows: [{ id: 'zip-main', assetType: 'main', fileUrl: path.join(tempRoot, 'main.zip'), fileName: 'main.zip' }],
|
||||
})
|
||||
mockListZipEntries.mockResolvedValue([{ name: 'main-1.png' }, { name: 'main-2.png' }])
|
||||
|
||||
await expect(batchEditTaskDetailImages({
|
||||
materialId: 'material-1', operatorUserId: 'operator-1',
|
||||
operations: [{ kind: 'group_images', group: 'main', assetIds: ['current-1', 'removed-2'], files: [] }],
|
||||
})).rejects.toMatchObject({ statusCode: 409, message: '图片分组已变化,请刷新后重新全选' })
|
||||
expect(mockCreateZipFromZips).not.toHaveBeenCalled()
|
||||
expect(prisma.$transaction).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test.each(['completed', 'fetched'])('%s:sku 追加支持多张按顺序提交,并保留 skuCode/barcodes', async (taskStatus) => {
|
||||
;(prisma.material.findFirst as jest.Mock).mockResolvedValue({ ...material, taskStatus })
|
||||
const existingSource = await createSolidImage('sku-old.png', 80, 80)
|
||||
|
||||
@ -14,6 +14,7 @@ import { queueTaskDetailChangeNotification } from '@/lib/task-detail-change-noti
|
||||
import {
|
||||
decideTaskDetailChange,
|
||||
expireDueTaskDetailChanges,
|
||||
getTaskDetailChangeRequest,
|
||||
recoverMissingTaskDetailChangeRequestNotifications,
|
||||
recoverStaleApplyingTaskDetailChanges,
|
||||
submitTaskDetailChange,
|
||||
@ -57,11 +58,13 @@ jest.mock('@/lib/user-permission-inherit', () => ({
|
||||
}))
|
||||
jest.mock('@/lib/department-permission', () => ({
|
||||
isSystemAdmin: jest.fn((role: string) => role === 'ADMIN' || role === 'SYSTEM_ADMIN'),
|
||||
isSuperAdmin: jest.fn().mockResolvedValue(false),
|
||||
}))
|
||||
jest.mock('@/lib/material-type-mapper', () => ({ isProductPackageType: jest.fn(() => true) }))
|
||||
jest.mock('@/lib/public-app-url', () => ({ getPublicAppOrigin: () => 'https://sc.example.com' }))
|
||||
jest.mock('@/lib/safe-redirect', () => ({ buildDingtalkEntryPath: (path: string) => path }))
|
||||
jest.mock('@/lib/task-detail-asset-edit', () => ({
|
||||
assertTaskDetailGroupSelection: jest.fn(),
|
||||
assertTaskDetailImageEditReady: jest.fn(),
|
||||
batchEditTaskDetailImages: jest.fn(),
|
||||
TaskDetailAssetEditError: class extends Error {
|
||||
@ -225,6 +228,74 @@ describe('任务详情图片变更主管审批', () => {
|
||||
expect(queueTaskDetailChangeNotification).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
test('整组替换按用户确认的顺序暂存,主管查看后可作为一项变更应用', async () => {
|
||||
const skuAssets = ['sku-a', 'sku-b'].map((id) => ({ id, assetType: 'sku-preview' }))
|
||||
const uploadIds = ['upload-b', 'upload-a']
|
||||
const assetIds = skuAssets.map(({ id }) => id)
|
||||
const files = ['second.png', 'first.png'].map((fileName) => ({
|
||||
relativePath: `task-detail-change-requests/request-group/${fileName}`,
|
||||
fileName,
|
||||
fileSize: 10,
|
||||
}))
|
||||
;(prisma.material.findFirst as jest.Mock).mockResolvedValue({ ...material, assets: skuAssets })
|
||||
;(getEmployeeByUserId as jest.Mock).mockResolvedValue(employee('P'))
|
||||
;(prisma.performanceSurveyEmployeeProfile.findUnique as jest.Mock).mockResolvedValue({
|
||||
id: 'manager-employee',
|
||||
displayName: '直属主管',
|
||||
employmentState: 'ACTIVE',
|
||||
dingtalkUserId: 'manager-ding',
|
||||
userBindings: [{ userId: 'manager-user' }],
|
||||
})
|
||||
;(withTaskDetailStagedUploads as jest.Mock).mockImplementation(async ({ commit }) => commit(new Map([
|
||||
['upload-a', files[1]], ['upload-b', files[0]],
|
||||
])))
|
||||
;(prisma.taskDetailChangeRequest.create as jest.Mock).mockImplementation(async ({ data }) => ({ ...data, material }))
|
||||
|
||||
const result = await submitTaskDetailChange('material-1', { id: 'user-1', role: 'USER' }, [
|
||||
{ kind: 'group_images', group: 'sku', assetIds, uploadIds },
|
||||
])
|
||||
expect(result.mode).toBe('pending_approval')
|
||||
expect(batchEditTaskDetailImages).not.toHaveBeenCalled()
|
||||
expect(withTaskDetailStagedUploads).toHaveBeenCalledWith(expect.objectContaining({
|
||||
uploadIds, enforceImageLimits: true,
|
||||
}))
|
||||
const pending = { ...(prisma.taskDetailChangeRequest.create as jest.Mock).mock.calls[0][0].data, material }
|
||||
expect(pending.operations).toEqual([{ kind: 'group_images', group: 'sku', assetIds, stagedFiles: files }])
|
||||
|
||||
const manager = { id: 'manager-user', role: 'USER' }
|
||||
;(getEmployeeByUserId as jest.Mock).mockResolvedValue(employee('M', 'manager-ding'))
|
||||
;(prisma.taskDetailChangeRequest.findUnique as jest.Mock)
|
||||
.mockResolvedValueOnce(pending)
|
||||
.mockResolvedValueOnce(pending)
|
||||
.mockResolvedValueOnce({ ...pending, status: 'applied' })
|
||||
;(prisma.taskDetailChangeRequest.updateMany as jest.Mock).mockResolvedValue({ count: 1 })
|
||||
;(prisma.material.findUnique as jest.Mock).mockResolvedValue({ updatedAt: material.updatedAt })
|
||||
;(resolveTaskDetailStagedFile as jest.Mock).mockImplementation((_requestId, file) => ({
|
||||
trusted: true, filePath: `/uploads/staged/${file.fileName}`, fileName: file.fileName, fileSize: file.fileSize,
|
||||
}))
|
||||
const review = await getTaskDetailChangeRequest(pending.id, manager)
|
||||
expect(review.operations).toEqual([{
|
||||
kind: 'group_images', group: 'sku', affectedCount: 2, fileNames: ['second.png', 'first.png'],
|
||||
}])
|
||||
await expect(decideTaskDetailChange(pending.id, manager, 'approve')).resolves.toMatchObject({ status: 'applied' })
|
||||
expect(batchEditTaskDetailImages).toHaveBeenCalledWith(expect.objectContaining({
|
||||
operatorUserId: 'user-1',
|
||||
expectedMaterialUpdatedAt: material.updatedAt,
|
||||
approvalRequestId: pending.id,
|
||||
operations: [{ kind: 'group_images', group: 'sku', assetIds, files: files.map(({ fileName }) => ({
|
||||
stagedFile: expect.objectContaining({ trusted: true, fileName }),
|
||||
})) }],
|
||||
}))
|
||||
})
|
||||
|
||||
test('整组替换 SKU 图的数量不符时不暂存文件或发起审批', async () => {
|
||||
await expect(submitTaskDetailChange('material-1', { id: 'user-1' }, [
|
||||
{ kind: 'group_images', group: 'sku', assetIds: ['sku-a', 'sku-b'], uploadIds: ['upload-a'] },
|
||||
])).rejects.toThrow('新图数量必须与原图数量一致')
|
||||
expect(withTaskDetailStagedUploads).not.toHaveBeenCalled()
|
||||
expect(prisma.taskDetailChangeRequest.create).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test.each([
|
||||
{ taskStatus: 'pending', isIncompleteShell: false },
|
||||
{ taskStatus: 'queued', isIncompleteShell: false },
|
||||
|
||||
@ -79,6 +79,23 @@ export class TaskDetailAssetEditError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export function assertTaskDetailGroupSelection(
|
||||
group: TaskDetailEditGroup,
|
||||
assetIds: string[],
|
||||
assets: Array<{ id: string; assetType: string }>,
|
||||
) {
|
||||
const current = assets.filter((asset) => asset.assetType === GROUP_PREVIEW_TYPES[group])
|
||||
const selected = new Set(assetIds)
|
||||
if (
|
||||
current.length === 0
|
||||
|| selected.size !== assetIds.length
|
||||
|| current.length !== selected.size
|
||||
|| current.some((asset) => !selected.has(asset.id))
|
||||
) {
|
||||
throw new TaskDetailAssetEditError('图片分组已变化,请刷新后重新全选', 409)
|
||||
}
|
||||
}
|
||||
|
||||
interface PreviewRowLike {
|
||||
id: string
|
||||
assetType: string
|
||||
@ -1693,14 +1710,19 @@ type PreparedBatchMutation =
|
||||
| { kind: 'delete' }
|
||||
| { kind: 'rename'; newBaseName: string }
|
||||
| { kind: 'replace'; source: ResolvedMutationSource }
|
||||
| { kind: 'append'; group: 'main' | 'sku'; source: ResolvedMutationSource; skuCode: string | null; barcodes: string[] }
|
||||
| { kind: 'append'; group: TaskDetailEditGroup; source: ResolvedMutationSource; skuCode: string | null; barcodes: string[] }
|
||||
| { kind: 'insert'; afterAssetId: string; beforeAssetId: string; source: ResolvedMutationSource }
|
||||
|
||||
interface PreparedBatchOperation {
|
||||
assetId?: string
|
||||
mutation: PreparedBatchMutation
|
||||
/** 上传会话来源的操作在提交成功后清理 */
|
||||
cleanupUploadId?: string
|
||||
}
|
||||
|
||||
interface GroupImagesEdit {
|
||||
kind: 'group_images'
|
||||
group: TaskDetailEditGroup
|
||||
assetIds: string[]
|
||||
files: MutationSourceInput[]
|
||||
}
|
||||
|
||||
function createExistingBatchRowState(row: PreviewRowLike): ExistingBatchRowState {
|
||||
@ -1762,6 +1784,67 @@ async function buildNewBatchRunState(options: {
|
||||
}
|
||||
}
|
||||
|
||||
async function buildWholeGroupRuns(
|
||||
context: EditContext,
|
||||
edit: GroupImagesEdit,
|
||||
workspaceDir: string,
|
||||
generatedPreviewLocations: string[],
|
||||
): Promise<BatchRunState[]> {
|
||||
const { group, runs, runEntryIndexes, entryNames } = context
|
||||
if (edit.files.length === 0) return []
|
||||
|
||||
// SKU 图沿用户确认的旧图顺序匹配,保留对应编号和条码。
|
||||
const skuRunIndexByAssetId = group === 'sku'
|
||||
? new Map(runs.map((run, index) => [run.rows[0].id, index]))
|
||||
: null
|
||||
if (skuRunIndexByAssetId && (
|
||||
edit.files.length !== runs.length
|
||||
|| edit.assetIds.length !== runs.length
|
||||
|| edit.assetIds.some((id) => !skuRunIndexByAssetId.has(id))
|
||||
)) {
|
||||
throw new TaskDetailAssetEditError('整组替换 SKU 图时,新图数量必须与原图数量一致')
|
||||
}
|
||||
|
||||
const usedNames = new Set<string>()
|
||||
const finalRuns: BatchRunState[] = []
|
||||
let totalBytes = 0
|
||||
for (let entryIndex = 0; entryIndex < edit.files.length; entryIndex += 1) {
|
||||
const file = edit.files[entryIndex]
|
||||
const source = await resolveMutationSource({
|
||||
...file,
|
||||
operatorUserId: context.operatorUserId,
|
||||
actionLabel: '整组替换图片',
|
||||
})
|
||||
totalBytes += source.fileSize
|
||||
if (totalBytes > TASK_DETAIL_UPLOAD_LIMITS.maxTotalSourceBytes) {
|
||||
throw new TaskDetailAssetEditError('替换图片总大小超过 1GB,请先压缩图片')
|
||||
}
|
||||
const oldIndex = skuRunIndexByAssetId?.get(edit.assetIds[entryIndex])
|
||||
const oldRun = oldIndex === undefined ? undefined : runs[oldIndex]
|
||||
const entryName = oldIndex === undefined
|
||||
? normalizeEntryFileName(source.fileName, '替换')
|
||||
: buildFinalEntryName(entryNames[runEntryIndexes[oldIndex]], source.fileName)
|
||||
const anchor = stripExtension(entryName).toLowerCase()
|
||||
if (usedNames.has(anchor)) {
|
||||
throw new TaskDetailAssetEditError(`「${entryName}」与本组其他图片的文件名重复,请改名后重试`, 409)
|
||||
}
|
||||
usedNames.add(anchor)
|
||||
finalRuns.push(await buildNewBatchRunState({
|
||||
source,
|
||||
entryName,
|
||||
group,
|
||||
materialId: context.materialId,
|
||||
isPrivate: isRestrictedMaterial(context),
|
||||
entryIndex,
|
||||
workspaceDir,
|
||||
generatedPreviewLocations,
|
||||
skuCode: oldRun?.rows[0].skuCode,
|
||||
barcodes: oldRun ? await loadRunBarcodes(oldRun.rows.map((row) => row.id)) : [],
|
||||
}))
|
||||
}
|
||||
return finalRuns
|
||||
}
|
||||
|
||||
function flattenBatchRows(runs: BatchRunState[]): Array<{ runIndex: number; rowIndex: number; row: BatchRowState }> {
|
||||
const flattened: Array<{ runIndex: number; rowIndex: number; row: BatchRowState }> = []
|
||||
for (let runIndex = 0; runIndex < runs.length; runIndex += 1) {
|
||||
@ -2058,13 +2141,14 @@ function resolveInsertSeam(
|
||||
async function executeBatchRebuild(
|
||||
context: EditContext,
|
||||
operations: PreparedBatchOperation[],
|
||||
groupEdit?: GroupImagesEdit,
|
||||
): Promise<RebuildOutcome> {
|
||||
const { group, entryNames } = context
|
||||
const workspace = await createTaskDetailEditWorkspace()
|
||||
const generatedPreviewLocations: string[] = []
|
||||
|
||||
try {
|
||||
const extracted = context.groupZipAssets[group]?.fileUrl
|
||||
const extracted = !groupEdit && context.groupZipAssets[group]?.fileUrl
|
||||
? await extractZipEntriesToDirectory(
|
||||
path.isAbsolute(context.groupZipAssets[group]!.fileUrl)
|
||||
? context.groupZipAssets[group]!.fileUrl
|
||||
@ -2073,18 +2157,20 @@ async function executeBatchRebuild(
|
||||
)
|
||||
: []
|
||||
|
||||
let finalRuns: BatchRunState[] = context.runs.map((run, index) => {
|
||||
const entryIndex = context.runEntryIndexes[index]
|
||||
return {
|
||||
sourceRunIndex: index,
|
||||
entry: {
|
||||
path: extracted[entryIndex]?.filePath || '',
|
||||
name: entryNames[entryIndex],
|
||||
size: extracted[entryIndex]?.size || 0,
|
||||
},
|
||||
rows: run.rows.map((row) => createExistingBatchRowState(row)),
|
||||
}
|
||||
})
|
||||
let finalRuns: BatchRunState[] = groupEdit
|
||||
? await buildWholeGroupRuns(context, groupEdit, workspace.dir, generatedPreviewLocations)
|
||||
: context.runs.map((run, index) => {
|
||||
const entryIndex = context.runEntryIndexes[index]
|
||||
return {
|
||||
sourceRunIndex: index,
|
||||
entry: {
|
||||
path: extracted[entryIndex]?.filePath || '',
|
||||
name: entryNames[entryIndex],
|
||||
size: extracted[entryIndex]?.size || 0,
|
||||
},
|
||||
rows: run.rows.map((row) => createExistingBatchRowState(row)),
|
||||
}
|
||||
})
|
||||
|
||||
const handledAssetIds = new Set<string>()
|
||||
const repeatedInsertBoundaries = new Map<string, BatchRunState>()
|
||||
@ -2359,6 +2445,8 @@ async function executeBatchRebuild(
|
||||
assertFinalBatchLimits(context, group, finalRuns)
|
||||
const { db, finalRowUrls } = buildBatchDbChanges(context, group, finalRuns)
|
||||
|
||||
// 与任务详情上传使用相同的快速压缩级别,避免大批原图重复重压缩。
|
||||
const zipOptions = groupEdit ? [undefined, 1] as const : [] as const
|
||||
let newGroupZip: RebuildOutcome['newGroupZip'] = null
|
||||
if (finalRuns.length > 0) {
|
||||
newGroupZip = await createZipFromFiles(
|
||||
@ -2369,6 +2457,7 @@ async function executeBatchRebuild(
|
||||
GROUP_ZIP_LABELS[group],
|
||||
context.authorName || undefined,
|
||||
context.categoryName || undefined,
|
||||
...zipOptions,
|
||||
)
|
||||
}
|
||||
|
||||
@ -2399,6 +2488,7 @@ async function executeBatchRebuild(
|
||||
context.materialId,
|
||||
context.productModel || 'product',
|
||||
'任务-详情',
|
||||
...zipOptions,
|
||||
)
|
||||
}
|
||||
|
||||
@ -2410,13 +2500,11 @@ async function executeBatchRebuild(
|
||||
finalRowCountByGroup[group] = finalRowUrls.length
|
||||
|
||||
const firstPreviewUrlByGroup: Record<TaskDetailEditGroup, string | null> = {
|
||||
main: null,
|
||||
sku: null,
|
||||
detail: null,
|
||||
}
|
||||
if (finalRowUrls.length > 0) {
|
||||
firstPreviewUrlByGroup[group] = finalRowUrls[0]
|
||||
main: context.rowsByGroup.main[0]?.fileUrl || null,
|
||||
sku: context.rowsByGroup.sku[0]?.fileUrl || null,
|
||||
detail: context.rowsByGroup.detail[0]?.fileUrl || null,
|
||||
}
|
||||
firstPreviewUrlByGroup[group] = finalRowUrls[0] || null
|
||||
|
||||
return {
|
||||
nextEntryNames: finalRuns.map((run) => run.entry.name),
|
||||
@ -2727,7 +2815,7 @@ async function commitRebuild(
|
||||
|
||||
const removedUrls = new Set(outcome.db.removedPreviewUrls.map((item) => item.url))
|
||||
let nextPreviewUrl = context.currentPreviewUrl
|
||||
if (nextPreviewUrl && removedUrls.has(nextPreviewUrl)) {
|
||||
if (!nextPreviewUrl || removedUrls.has(nextPreviewUrl)) {
|
||||
nextPreviewUrl =
|
||||
outcome.firstPreviewUrlByGroup.main
|
||||
|| outcome.firstPreviewUrlByGroup.sku
|
||||
@ -2994,7 +3082,7 @@ export type BatchTaskDetailImageEditOperation =
|
||||
| { kind: 'replace'; assetId: string; uploadId?: string; stagedFile?: ServerTrustedTaskDetailStagedFile }
|
||||
| {
|
||||
kind: 'append'
|
||||
group: 'main' | 'sku'
|
||||
group: TaskDetailEditGroup
|
||||
uploadId?: string
|
||||
stagedFile?: ServerTrustedTaskDetailStagedFile
|
||||
skuCode?: string | null
|
||||
@ -3007,6 +3095,7 @@ export type BatchTaskDetailImageEditOperation =
|
||||
uploadId?: string
|
||||
stagedFile?: ServerTrustedTaskDetailStagedFile
|
||||
}
|
||||
| GroupImagesEdit
|
||||
|
||||
export interface BatchTaskDetailImageEditInput {
|
||||
materialId: string
|
||||
@ -3033,6 +3122,13 @@ export async function batchEditTaskDetailImages(input: BatchTaskDetailImageEditI
|
||||
if (operations.length > MAX_BATCH_OPERATIONS) {
|
||||
throw new TaskDetailAssetEditError(`一次最多提交 ${MAX_BATCH_OPERATIONS} 项操作,请分批提交`)
|
||||
}
|
||||
const groupEdit = operations.find((operation) => operation.kind === 'group_images')
|
||||
if (groupEdit && operations.length !== 1) {
|
||||
throw new TaskDetailAssetEditError('整组变更请单独提交')
|
||||
}
|
||||
if (groupEdit && groupEdit.files.length > TASK_DETAIL_UPLOAD_LIMITS.maxImagesPerGroup) {
|
||||
throw new TaskDetailAssetEditError(`每组最多替换为 ${TASK_DETAIL_UPLOAD_LIMITS.maxImagesPerGroup} 张原图`)
|
||||
}
|
||||
|
||||
return runEditOperation(input.materialId, async () => {
|
||||
const seed = operations[0]
|
||||
@ -3040,13 +3136,8 @@ export async function batchEditTaskDetailImages(input: BatchTaskDetailImageEditI
|
||||
materialId: input.materialId,
|
||||
operatorUserId: input.operatorUserId,
|
||||
operatorRole: input.operatorRole,
|
||||
assetId:
|
||||
seed.kind === 'insert'
|
||||
? seed.afterAssetId
|
||||
: seed.kind === 'append'
|
||||
? undefined
|
||||
: seed.assetId,
|
||||
group: seed.kind === 'append' ? seed.group : seed.kind === 'insert' ? 'detail' : undefined,
|
||||
assetId: 'assetId' in seed ? seed.assetId : seed.kind === 'insert' ? seed.afterAssetId : undefined,
|
||||
group: 'group' in seed ? seed.group : seed.kind === 'insert' ? 'detail' : undefined,
|
||||
allowEmptyGroup: seed.kind === 'append',
|
||||
expectedMaterialUpdatedAt: input.expectedMaterialUpdatedAt,
|
||||
approvalRequestId: input.approvalRequestId,
|
||||
@ -3056,6 +3147,10 @@ export async function batchEditTaskDetailImages(input: BatchTaskDetailImageEditI
|
||||
context.runs.flatMap((run) => run.rows.map((row) => row.id)),
|
||||
)
|
||||
for (const operation of operations) {
|
||||
if (operation.kind === 'group_images') {
|
||||
assertTaskDetailGroupSelection(operation.group, operation.assetIds, context.rowsByGroup[context.group])
|
||||
continue
|
||||
}
|
||||
if (operation.kind === 'append') {
|
||||
if (operation.group !== context.group) {
|
||||
throw new TaskDetailAssetEditError('批量操作只支持同一分组(主图/SKU/详情)内的图片')
|
||||
@ -3078,7 +3173,15 @@ export async function batchEditTaskDetailImages(input: BatchTaskDetailImageEditI
|
||||
}
|
||||
|
||||
const prepared: PreparedBatchOperation[] = []
|
||||
const consumedUploadIds: string[] = []
|
||||
for (const operation of operations) {
|
||||
if (operation.kind === 'group_images') {
|
||||
for (const file of operation.files) {
|
||||
if (file.uploadId) consumedUploadIds.push(file.uploadId.trim())
|
||||
}
|
||||
continue
|
||||
}
|
||||
if ('uploadId' in operation && operation.uploadId) consumedUploadIds.push(operation.uploadId.trim())
|
||||
if (operation.kind === 'delete') {
|
||||
prepared.push({ assetId: operation.assetId, mutation: { kind: 'delete' } })
|
||||
continue
|
||||
@ -3113,7 +3216,6 @@ export async function batchEditTaskDetailImages(input: BatchTaskDetailImageEditI
|
||||
prepared.push({
|
||||
assetId: operation.assetId,
|
||||
mutation: { kind: 'replace', source },
|
||||
cleanupUploadId: operation.uploadId?.trim() || undefined,
|
||||
})
|
||||
continue
|
||||
}
|
||||
@ -3132,7 +3234,6 @@ export async function batchEditTaskDetailImages(input: BatchTaskDetailImageEditI
|
||||
skuCode: operation.skuCode?.trim() || null,
|
||||
barcodes: Array.from(new Set((operation.barcodes || []).filter(Boolean))),
|
||||
},
|
||||
cleanupUploadId: operation.uploadId?.trim() || undefined,
|
||||
})
|
||||
continue
|
||||
}
|
||||
@ -3149,18 +3250,15 @@ export async function batchEditTaskDetailImages(input: BatchTaskDetailImageEditI
|
||||
beforeAssetId: operation.beforeAssetId,
|
||||
source,
|
||||
},
|
||||
cleanupUploadId: operation.uploadId?.trim() || undefined,
|
||||
})
|
||||
}
|
||||
|
||||
const outcome = await executeBatchRebuild(context, prepared)
|
||||
const outcome = await executeBatchRebuild(context, prepared, groupEdit)
|
||||
const { nextIsFullSet } = await commitRebuildWithCleanup(context, outcome, 'BATCH_IMAGE_EDITS')
|
||||
await cleanupAfterCommit(context, outcome)
|
||||
|
||||
for (const operation of prepared) {
|
||||
if (operation.cleanupUploadId) {
|
||||
await cleanupConsumedUploadSession(operation.cleanupUploadId).catch(() => undefined)
|
||||
}
|
||||
for (const uploadId of consumedUploadIds) {
|
||||
await cleanupConsumedUploadSession(uploadId).catch(() => undefined)
|
||||
}
|
||||
|
||||
if (!context.wasFullSet && nextIsFullSet) {
|
||||
@ -3188,7 +3286,7 @@ export async function batchEditTaskDetailImages(input: BatchTaskDetailImageEditI
|
||||
|
||||
return {
|
||||
success: true,
|
||||
appliedCount: prepared.length,
|
||||
appliedCount: operations.length,
|
||||
entryCount: outcome.nextEntryNames.length,
|
||||
}
|
||||
})
|
||||
|
||||
@ -19,7 +19,14 @@ import {
|
||||
type TaskDetailStagedFile,
|
||||
} from '@/lib/task-detail-change-staging'
|
||||
import { queueTaskDetailChangeNotification } from '@/lib/task-detail-change-notifications'
|
||||
import { assertTaskDetailImageEditReady, batchEditTaskDetailImages, TaskDetailAssetEditError } from '@/lib/task-detail-asset-edit'
|
||||
import {
|
||||
assertTaskDetailGroupSelection,
|
||||
assertTaskDetailImageEditReady,
|
||||
batchEditTaskDetailImages,
|
||||
TaskDetailAssetEditError,
|
||||
type TaskDetailEditGroup,
|
||||
} from '@/lib/task-detail-asset-edit'
|
||||
import { TASK_DETAIL_UPLOAD_LIMITS } from '@/lib/task-detail-upload-policy'
|
||||
|
||||
const REQUEST_STATUS = {
|
||||
PENDING: 'pending_manager_approval',
|
||||
@ -41,11 +48,11 @@ export class TaskDetailChangeApprovalError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export type TaskDetailChangeOperationInput =
|
||||
type SingleImageChangeOperation =
|
||||
| { kind: 'delete'; assetId: string }
|
||||
| { kind: 'rename'; assetId: string; newFileName: string }
|
||||
| { kind: 'replace'; assetId: string; uploadId: string }
|
||||
| { kind: 'append'; group: 'main' | 'sku'; uploadId: string }
|
||||
| { kind: 'append'; group: TaskDetailEditGroup; uploadId: string }
|
||||
| {
|
||||
kind: 'insert'
|
||||
group: 'detail'
|
||||
@ -54,10 +61,19 @@ export type TaskDetailChangeOperationInput =
|
||||
beforeAssetId: string
|
||||
}
|
||||
|
||||
type StoredOperation = Omit<TaskDetailChangeOperationInput, 'uploadId'> & {
|
||||
stagedFile?: TaskDetailStagedFile
|
||||
type GroupImagesOperation = {
|
||||
kind: 'group_images'
|
||||
group: TaskDetailEditGroup
|
||||
assetIds: string[]
|
||||
uploadIds: string[]
|
||||
}
|
||||
|
||||
export type TaskDetailChangeOperationInput = SingleImageChangeOperation | GroupImagesOperation
|
||||
|
||||
type StoredOperation = (Omit<SingleImageChangeOperation, 'uploadId'> & {
|
||||
stagedFile?: TaskDetailStagedFile
|
||||
}) | (Omit<GroupImagesOperation, 'uploadIds'> & { stagedFiles: TaskDetailStagedFile[] })
|
||||
|
||||
type Actor = {
|
||||
id: string
|
||||
role?: string | null
|
||||
@ -79,8 +95,34 @@ function normalizeOperations(value: unknown): TaskDetailChangeOperationInput[] {
|
||||
const operations: TaskDetailChangeOperationInput[] = []
|
||||
const targetAssetIds = new Set<string>()
|
||||
for (const raw of rows) {
|
||||
const row = raw as Record<string, unknown>
|
||||
const row = (raw || {}) as Record<string, unknown>
|
||||
const kind = clean(row.kind)
|
||||
if (kind === 'group_images') {
|
||||
if (rows.length !== 1) throw new TaskDetailChangeApprovalError('整组变更请单独提交')
|
||||
const group = clean(row.group)
|
||||
if (group !== 'main' && group !== 'sku' && group !== 'detail') {
|
||||
throw new TaskDetailChangeApprovalError('整组变更的图片分组无效')
|
||||
}
|
||||
if (
|
||||
!Array.isArray(row.assetIds)
|
||||
|| row.assetIds.length === 0
|
||||
|| row.assetIds.length > TASK_DETAIL_UPLOAD_LIMITS.maxTotalPreviewCount
|
||||
|| !Array.isArray(row.uploadIds)
|
||||
|| row.uploadIds.length > TASK_DETAIL_UPLOAD_LIMITS.maxImagesPerGroup
|
||||
) {
|
||||
throw new TaskDetailChangeApprovalError('整组变更的图片数量或参数无效')
|
||||
}
|
||||
const assetIds = row.assetIds.map((id) => typeof id === 'string' ? id.trim() : '')
|
||||
const uploadIds = row.uploadIds.map((id) => typeof id === 'string' ? id.trim() : '')
|
||||
if (assetIds.includes('') || uploadIds.includes('') || new Set(uploadIds).size !== uploadIds.length) {
|
||||
throw new TaskDetailChangeApprovalError('整组变更包含无效或重复的上传会话')
|
||||
}
|
||||
if (group === 'sku' && uploadIds.length > 0 && uploadIds.length !== assetIds.length) {
|
||||
throw new TaskDetailChangeApprovalError('整组替换 SKU 图时,新图数量必须与原图数量一致')
|
||||
}
|
||||
operations.push({ kind, group, assetIds, uploadIds })
|
||||
continue
|
||||
}
|
||||
if (kind === 'delete') {
|
||||
const assetId = clean(row.assetId)
|
||||
if (!assetId) throw new TaskDetailChangeApprovalError('删除操作缺少图片标识')
|
||||
@ -110,7 +152,7 @@ function normalizeOperations(value: unknown): TaskDetailChangeOperationInput[] {
|
||||
if (kind === 'append') {
|
||||
const group = clean(row.group)
|
||||
const uploadId = clean(row.uploadId)
|
||||
if ((group !== 'main' && group !== 'sku') || !uploadId) {
|
||||
if ((group !== 'main' && group !== 'sku' && group !== 'detail') || !uploadId) {
|
||||
throw new TaskDetailChangeApprovalError('追加图片操作参数不完整')
|
||||
}
|
||||
operations.push({ kind, group, uploadId })
|
||||
@ -144,7 +186,7 @@ function assertSingleOperationGroup(
|
||||
}
|
||||
const groups = new Set<'main' | 'sku' | 'detail'>()
|
||||
for (const operation of operations) {
|
||||
if (operation.kind === 'append') {
|
||||
if (operation.kind === 'append' || operation.kind === 'group_images') {
|
||||
groups.add(operation.group)
|
||||
continue
|
||||
}
|
||||
@ -339,17 +381,31 @@ function storeOperations(
|
||||
operations: TaskDetailChangeOperationInput[],
|
||||
staged: Map<string, TaskDetailStagedFile>,
|
||||
): StoredOperation[] {
|
||||
return operations.map((operation) => {
|
||||
if (!('uploadId' in operation)) return operation as StoredOperation
|
||||
const stagedFile = staged.get(operation.uploadId)
|
||||
const getStagedFile = (uploadId: string) => {
|
||||
const stagedFile = staged.get(uploadId)
|
||||
if (!stagedFile) throw new TaskDetailChangeApprovalError('图片持久暂存结果缺失', 500)
|
||||
return stagedFile
|
||||
}
|
||||
return operations.map((operation) => {
|
||||
if (operation.kind === 'group_images') {
|
||||
const { uploadIds, ...rest } = operation
|
||||
return { ...rest, stagedFiles: uploadIds.map(getStagedFile) }
|
||||
}
|
||||
if (!('uploadId' in operation)) return operation as StoredOperation
|
||||
const { uploadId: _uploadId, ...rest } = operation
|
||||
return { ...rest, stagedFile } as StoredOperation
|
||||
return { ...rest, stagedFile: getStagedFile(operation.uploadId) } as StoredOperation
|
||||
})
|
||||
}
|
||||
|
||||
function applyOperations(requestId: string, operations: StoredOperation[]) {
|
||||
return operations.map((operation) => {
|
||||
if (operation.kind === 'group_images') {
|
||||
const { stagedFiles, ...rest } = operation
|
||||
return {
|
||||
...rest,
|
||||
files: stagedFiles.map((file) => ({ stagedFile: resolveTaskDetailStagedFile(requestId, file) })),
|
||||
}
|
||||
}
|
||||
if (!operation.stagedFile) return operation
|
||||
return {
|
||||
...operation,
|
||||
@ -366,7 +422,9 @@ export async function submitTaskDetailChange(
|
||||
const operations = normalizeOperations(rawOperations)
|
||||
const { material, employee } = await loadAuthorizedContext(materialId, actor)
|
||||
const group = assertSingleOperationGroup(operations, material.assets)
|
||||
const groupEdit = operations.find((operation) => operation.kind === 'group_images')
|
||||
try {
|
||||
if (groupEdit) assertTaskDetailGroupSelection(group, groupEdit.assetIds, material.assets)
|
||||
await assertTaskDetailImageEditReady({
|
||||
materialId,
|
||||
operatorUserId: actor.id,
|
||||
@ -383,7 +441,12 @@ export async function submitTaskDetailChange(
|
||||
materialId,
|
||||
operatorUserId: actor.id,
|
||||
operatorRole: actor.role,
|
||||
operations: operations as any,
|
||||
...(groupEdit ? { expectedMaterialUpdatedAt: material.updatedAt } : {}),
|
||||
operations: operations.map((operation) => {
|
||||
if (operation.kind !== 'group_images') return operation
|
||||
const { uploadIds, ...rest } = operation
|
||||
return { ...rest, files: uploadIds.map((uploadId) => ({ uploadId })) }
|
||||
}),
|
||||
})
|
||||
return { mode: 'applied' as const, data }
|
||||
}
|
||||
@ -393,14 +456,16 @@ export async function submitTaskDetailChange(
|
||||
const manager = await resolveManager(employee)
|
||||
const requestId = randomUUID()
|
||||
const expiresAt = new Date(Date.now() + APPROVAL_WINDOW_MS)
|
||||
const uploadIds = operations.filter((item): item is Extract<TaskDetailChangeOperationInput, { uploadId: string }> => (
|
||||
'uploadId' in item
|
||||
)).map((item) => item.uploadId)
|
||||
const uploadIds = operations.flatMap((item) => {
|
||||
if (item.kind === 'group_images') return item.uploadIds
|
||||
return 'uploadId' in item ? [item.uploadId] : []
|
||||
})
|
||||
|
||||
const request = await withTaskDetailStagedUploads({
|
||||
requestId,
|
||||
ownerUserId: actor.id,
|
||||
uploadIds,
|
||||
...(groupEdit ? { enforceImageLimits: true } : {}),
|
||||
commit: async (staged) => {
|
||||
const storedOperations = storeOperations(operations, staged)
|
||||
return prisma.taskDetailChangeRequest.create({
|
||||
@ -492,10 +557,18 @@ export async function getTaskDetailChangeRequest(id: string, actor: Actor) {
|
||||
requesterName: request.requesterName,
|
||||
managerName: request.managerName,
|
||||
material: request.material,
|
||||
operations: operations.map(({ stagedFile, ...operation }) => ({
|
||||
...operation,
|
||||
fileName: stagedFile?.fileName || null,
|
||||
})),
|
||||
operations: operations.map((item) => {
|
||||
if (item.kind === 'group_images') {
|
||||
return {
|
||||
kind: item.kind,
|
||||
group: item.group,
|
||||
affectedCount: item.assetIds.length,
|
||||
fileNames: item.stagedFiles.map((file) => file.fileName),
|
||||
}
|
||||
}
|
||||
const { stagedFile, ...operation } = item
|
||||
return { ...operation, fileName: stagedFile?.fileName || null }
|
||||
}),
|
||||
submittedAt: request.submittedAt,
|
||||
expiresAt: request.expiresAt,
|
||||
decidedAt: request.decidedAt,
|
||||
|
||||
@ -4,6 +4,8 @@ import path from 'path'
|
||||
|
||||
import { acquireTaskMaterialUploadSessionLocks } from '@/lib/material-upload-cross-process-lock'
|
||||
import { normalizeSafeFileName, resolveStrictChildPath } from '@/lib/path-security'
|
||||
import { TaskDetailAssetEditError } from '@/lib/task-detail-asset-edit'
|
||||
import { TASK_DETAIL_UPLOAD_LIMITS } from '@/lib/task-detail-upload-policy'
|
||||
import { cleanupConsumedUploadSession } from '@/lib/temp-cleanup'
|
||||
import { getUploadRootDir } from '@/lib/upload-paths'
|
||||
import {
|
||||
@ -38,6 +40,7 @@ export async function withTaskDetailStagedUploads<T>(input: {
|
||||
requestId: string
|
||||
ownerUserId: string
|
||||
uploadIds: string[]
|
||||
enforceImageLimits?: boolean
|
||||
commit: (files: Map<string, TaskDetailStagedFile>) => Promise<T>
|
||||
}): Promise<T> {
|
||||
const uploadIds = Array.from(new Set(
|
||||
@ -57,6 +60,7 @@ export async function withTaskDetailStagedUploads<T>(input: {
|
||||
release?.assertHeld()
|
||||
await mkdir(requestDirectory, { recursive: false })
|
||||
const staged = new Map<string, TaskDetailStagedFile>()
|
||||
let totalBytes = 0
|
||||
|
||||
for (let index = 0; index < uploadIds.length; index += 1) {
|
||||
release?.assertHeld()
|
||||
@ -69,6 +73,15 @@ export async function withTaskDetailStagedUploads<T>(input: {
|
||||
if (!sourceStats.isFile() || sourceStats.isSymbolicLink() || sourceStats.size <= 0) {
|
||||
throw new Error('已上传图片文件状态异常,请重新选择图片')
|
||||
}
|
||||
if (input.enforceImageLimits) {
|
||||
totalBytes += sourceStats.size
|
||||
if (sourceStats.size > TASK_DETAIL_UPLOAD_LIMITS.maxSingleImageBytes) {
|
||||
throw new TaskDetailAssetEditError('单张替换图片不能超过 100MB,请先压缩图片')
|
||||
}
|
||||
if (totalBytes > TASK_DETAIL_UPLOAD_LIMITS.maxTotalSourceBytes) {
|
||||
throw new TaskDetailAssetEditError('替换图片总大小超过 1GB,请先压缩图片')
|
||||
}
|
||||
}
|
||||
|
||||
const safeName = normalizeSafeFileName(session.fileName)
|
||||
if (!safeName) throw new Error('图片文件名无效')
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user