fix(materials): combine task detail image groups in one approval
This commit is contained in:
parent
705d1e28b1
commit
cb0dccf771
@ -152,6 +152,12 @@ jest.mock('@/components/detail/ProductPackageDetail', () => ({
|
||||
<button type="button" onClick={() => props.onRequestAppend?.('main')}>
|
||||
触发追加主图
|
||||
</button>
|
||||
<button type="button" onClick={() => props.onRequestGroupDelete?.('sku', ['sku-1'])}>
|
||||
触发整组删除 SKU
|
||||
</button>
|
||||
<button type="button" onClick={() => props.onRequestGroupDelete?.('main', ['main-1', 'main-2', 'main-3'])}>
|
||||
触发整组删除主图
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => props.onRequestInsert?.({ group: 'detail', afterAssetId: 'detail-1', beforeAssetId: 'detail-2' })}
|
||||
@ -296,7 +302,7 @@ describe('task detail share page change requests', () => {
|
||||
jest.restoreAllMocks()
|
||||
})
|
||||
|
||||
test('serializes all operation kinds while keeping each request inside one image group', async () => {
|
||||
test('submits operations across main, detail and SKU in one request', async () => {
|
||||
const user = userEvent.setup()
|
||||
chunkUploadMock
|
||||
.mockResolvedValueOnce({ uploadId: 'upload-replace-1' })
|
||||
@ -345,38 +351,33 @@ describe('task detail share page change requests', () => {
|
||||
],
|
||||
)
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: '提交主管确认 5 项' }))
|
||||
|
||||
await user.click(screen.getByRole('button', { name: '触发插入详情' }))
|
||||
await user.upload(
|
||||
screen.getByTestId('task-detail-batch-input'),
|
||||
new File(['insert'], 'insert-detail.jpg', { type: 'image/jpeg' }),
|
||||
)
|
||||
await user.click(await screen.findByRole('button', { name: '提交主管确认 1 项' }))
|
||||
await user.click(screen.getByRole('button', { name: '触发整组删除 SKU' }))
|
||||
expect(screen.getByText('待提交变更 7 项')).toBeInTheDocument()
|
||||
await user.click(await screen.findByRole('button', { name: '提交全部变更' }))
|
||||
|
||||
const requestCalls = fetchMock.mock.calls.filter(
|
||||
([url, init]) => String(url) === '/api/materials/material-1/assets/change-requests'
|
||||
&& init?.method === 'POST',
|
||||
)
|
||||
expect(requestCalls).toHaveLength(2)
|
||||
expect(requestCalls).toHaveLength(1)
|
||||
expect(requestCalls[0]?.[1]).toMatchObject({
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
|
||||
const mainPayload = JSON.parse(String((requestCalls[0]?.[1] as RequestInit).body))
|
||||
expect(mainPayload).toEqual({
|
||||
const payload = JSON.parse(String((requestCalls[0]?.[1] as RequestInit).body))
|
||||
expect(payload).toEqual({
|
||||
operations: [
|
||||
{ kind: 'replace', assetId: 'main-1', uploadId: 'upload-replace-1' },
|
||||
{ kind: 'rename', assetId: 'main-2', newFileName: 'detail-2-renamed' },
|
||||
{ kind: 'delete', assetId: 'main-3' },
|
||||
{ kind: 'append', group: 'main', uploadId: 'upload-append-1' },
|
||||
{ kind: 'append', group: 'main', uploadId: 'upload-append-2' },
|
||||
],
|
||||
})
|
||||
const detailPayload = JSON.parse(String((requestCalls[1]?.[1] as RequestInit).body))
|
||||
expect(detailPayload).toEqual({
|
||||
operations: [
|
||||
{
|
||||
kind: 'insert',
|
||||
group: 'detail',
|
||||
@ -384,12 +385,13 @@ describe('task detail share page change requests', () => {
|
||||
afterAssetId: 'detail-1',
|
||||
beforeAssetId: 'detail-2',
|
||||
},
|
||||
{ kind: 'group_images', group: 'sku', assetIds: ['sku-1'], uploadIds: [] },
|
||||
],
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(showToastMock).toHaveBeenCalledWith(
|
||||
'已直接应用 1 项变更,下载包已同步更新',
|
||||
'已直接应用 7 项变更,下载包已同步更新',
|
||||
{ variant: 'success' },
|
||||
)
|
||||
})
|
||||
@ -425,7 +427,7 @@ describe('task detail share page change requests', () => {
|
||||
expect(await screen.findByTestId('mock-product-package-detail')).toBeInTheDocument()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: '触发删除' }))
|
||||
await user.click(await screen.findByRole('button', { name: '提交主管确认 1 项' }))
|
||||
await user.click(await screen.findByRole('button', { name: '提交全部变更' }))
|
||||
|
||||
expect(await screen.findByText('变更已提交主管确认')).toBeInTheDocument()
|
||||
expect(screen.getByText('经理:王主管')).toBeInTheDocument()
|
||||
@ -436,7 +438,7 @@ describe('task detail share page change requests', () => {
|
||||
expect(mockPush).toHaveBeenCalledWith('/task-detail-change-requests/request-1')
|
||||
})
|
||||
|
||||
test('blocks switching image groups before opening another upload picker', async () => {
|
||||
test('blocks a conflicting whole-group change while preserving the queued edit', async () => {
|
||||
const user = userEvent.setup()
|
||||
global.fetch = jest.fn(async (input: RequestInfo | URL) => {
|
||||
const url = String(input)
|
||||
@ -451,10 +453,11 @@ describe('task detail share page change requests', () => {
|
||||
expect(await screen.findByTestId('mock-product-package-detail')).toBeInTheDocument()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: '触发删除' }))
|
||||
await user.click(screen.getByRole('button', { name: '触发插入详情' }))
|
||||
await user.click(screen.getByRole('button', { name: '触发整组删除主图' }))
|
||||
|
||||
expect(screen.getByText('待提交变更 1 项')).toBeInTheDocument()
|
||||
expect(showToastMock).toHaveBeenCalledWith(
|
||||
'待提交清单已有主图变更,请先提交或清空后再编辑详情图',
|
||||
'主图已有待提交变更,撤销该组的冲突操作后可继续编辑',
|
||||
{ variant: 'error' },
|
||||
)
|
||||
})
|
||||
|
||||
@ -31,7 +31,7 @@ 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, validateTaskDetailUploadFiles } from '@/lib/task-detail-upload-policy'
|
||||
import type { TaskDetailEditGroup } from '@/lib/task-detail-asset-edit'
|
||||
import { getTaskDetailEditGroup, type TaskDetailEditGroup } from '@/lib/task-detail-edit-groups'
|
||||
|
||||
interface Material {
|
||||
accessScope?: string
|
||||
@ -174,7 +174,6 @@ 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: {
|
||||
@ -565,7 +564,6 @@ export default function SharePage() {
|
||||
// 批量编辑攒批清单:先在前端整理一组变更,再统一提交给主管确认或直接应用。
|
||||
const [taskDetailPendingOps, setTaskDetailPendingOps] = useState<TaskDetailPendingOp[]>([])
|
||||
const pendingGroupEdits = taskDetailPendingOps.filter((op) => op.kind === 'group_images')
|
||||
const pendingGroupEdit = pendingGroupEdits.length > 0
|
||||
const [taskDetailApplying, setTaskDetailApplying] = useState(false)
|
||||
const [taskDetailChangeRequestNotice, setTaskDetailChangeRequestNotice] = useState<TaskDetailChangeRequestNotice | null>(null)
|
||||
const taskDetailPendingBarRef = useRef<HTMLDivElement | null>(null)
|
||||
@ -1192,13 +1190,8 @@ export default function SharePage() {
|
||||
|
||||
// ---- 任务-详情图片编辑 ----
|
||||
|
||||
const getTaskDetailAssetGroup = (assetId: string): 'main' | 'sku' | 'detail' | null => {
|
||||
const assetType = material?.assets?.find((asset) => asset.id === assetId)?.assetType
|
||||
if (assetType === 'main-preview') return 'main'
|
||||
if (assetType === 'sku-preview') return 'sku'
|
||||
if (assetType === 'detail-preview') return 'detail'
|
||||
return null
|
||||
}
|
||||
const getTaskDetailAssetGroup = (assetId: string) =>
|
||||
getTaskDetailEditGroup(material?.assets?.find((asset) => asset.id === assetId)?.assetType)
|
||||
|
||||
const getTaskDetailPendingOpGroup = (op: TaskDetailPendingOpInput | TaskDetailPendingOp) => {
|
||||
return 'group' in op ? op.group : getTaskDetailAssetGroup(op.assetId)
|
||||
@ -1209,24 +1202,10 @@ export default function SharePage() {
|
||||
showToast('图片分组识别失败,请刷新后重试', { variant: 'error' })
|
||||
return false
|
||||
}
|
||||
if (wholeGroup) {
|
||||
if (pendingGroupEdits.some((op) => op.group === group)) {
|
||||
showToast(`${TASK_DETAIL_GROUP_LABELS[group]}已加入待提交,撤销这组变更后可重新选择`, { variant: 'error' })
|
||||
return false
|
||||
}
|
||||
if (pendingGroupEdits.length === taskDetailPendingOps.length) return true
|
||||
showToast('请先提交或撤销单图变更,再处理整组图片', { variant: 'error' })
|
||||
return false
|
||||
}
|
||||
if (pendingGroupEdit) {
|
||||
showToast('请先提交或撤销整组变更,再编辑单张图片', { variant: 'error' })
|
||||
return false
|
||||
}
|
||||
const currentGroup = taskDetailPendingOps[0]
|
||||
? getTaskDetailPendingOpGroup(taskDetailPendingOps[0])
|
||||
: null
|
||||
if (currentGroup && currentGroup !== group) {
|
||||
showToast(`待提交清单已有${TASK_DETAIL_GROUP_LABELS[currentGroup]}变更,请先提交或清空后再编辑${TASK_DETAIL_GROUP_LABELS[group]}`, {
|
||||
if (taskDetailPendingOps.some((op) =>
|
||||
getTaskDetailPendingOpGroup(op) === group && (wholeGroup || op.kind === 'group_images'),
|
||||
)) {
|
||||
showToast(`${TASK_DETAIL_GROUP_LABELS[group]}已有待提交变更,撤销该组的冲突操作后可继续编辑`, {
|
||||
variant: 'error',
|
||||
})
|
||||
return false
|
||||
@ -1497,7 +1476,7 @@ export default function SharePage() {
|
||||
uploadId,
|
||||
})
|
||||
if (queued) {
|
||||
showToast('替换已加入待提交清单,全部操作完后点「提交主管确认」', { variant: 'success' })
|
||||
showToast('替换已加入待提交清单', { variant: 'success' })
|
||||
}
|
||||
} catch (error) {
|
||||
showToast(error instanceof Error ? error.message : '替换失败,请稍后重试', { variant: 'error' })
|
||||
@ -1617,7 +1596,7 @@ export default function SharePage() {
|
||||
expiresAt: null,
|
||||
}
|
||||
setTaskDetailChangeRequestNotice(notice)
|
||||
showToast(`已提交 ${taskDetailPendingOps.length} 项变更,等待${notice.managerName || '主管'}确认`, {
|
||||
showToast(`${taskDetailPendingOps.length} 项变更已合并提交,等待${notice.managerName || '主管'}确认`, {
|
||||
variant: 'success',
|
||||
})
|
||||
} else {
|
||||
@ -1740,9 +1719,7 @@ export default function SharePage() {
|
||||
待提交变更 {taskDetailPendingOps.length} 项
|
||||
</p>
|
||||
<p className="mt-1 text-[12px] leading-5 text-[#6b7075]">
|
||||
{pendingGroupEdit
|
||||
? '这些分组会一起提交。提交前可以撤销任意一组。'
|
||||
: '替换和插入文件先留在临时区,点击提交后再进入主管确认,不会立即覆盖正式素材。'}
|
||||
主图、详情图和 SKU 图可以一起提交,提交前可以逐项撤销。
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
@ -1761,25 +1738,24 @@ export default function SharePage() {
|
||||
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
|
||||
? '正在提交…'
|
||||
: pendingGroupEdit
|
||||
? (pendingGroupEdits.length === 1 ? '提交整组变更' : `提交 ${pendingGroupEdits.length} 组变更`)
|
||||
: `提交主管确认 ${taskDetailPendingOps.length} 项`}
|
||||
{taskDetailApplying ? '正在提交…' : '提交全部变更'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<ul className="mt-3 space-y-1.5">
|
||||
{taskDetailPendingOps.map((op) => {
|
||||
const actionLabel = op.kind === 'group_images'
|
||||
const group = 'assetId' in op ? getTaskDetailAssetGroup(op.assetId) : null
|
||||
const label = op.kind === 'group_images'
|
||||
? (op.uploadIds.length > 0 ? '替换' : '删除')
|
||||
: TASK_DETAIL_OPERATION_LABELS[op.kind]
|
||||
: group ? TASK_DETAIL_GROUP_LABELS[group] : null
|
||||
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>
|
||||
{label && (
|
||||
<span className={op.kind === 'delete' || label === '删除' ? 'mr-2 text-[#b42318]' : 'mr-2 text-[#6b7075]'}>
|
||||
{label}
|
||||
</span>
|
||||
)}
|
||||
{op.label}
|
||||
</span>
|
||||
<button
|
||||
|
||||
@ -507,7 +507,7 @@ export default function TaskDetailChangeRequestPage() {
|
||||
<ol className="mt-4 space-y-2">
|
||||
{record.operations.map((op, index) => (
|
||||
<li
|
||||
key={`${op.kind}-${op.assetId || op.afterAssetId || index}`}
|
||||
key={`${index}-${op.kind}`}
|
||||
className="rounded-[10px] border border-[#e7e8ea] bg-[#fafafa] px-4 py-3"
|
||||
>
|
||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||
@ -527,9 +527,11 @@ 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 === 'group_images' ? '整组' : op.kind}
|
||||
</span>
|
||||
{op.group && op.kind !== 'group_images' && (
|
||||
<span className="rounded-full border border-[#d7dde3] bg-white px-2 py-0.5 text-[11px] font-medium text-[#66758b]">
|
||||
{GROUP_LABELS[op.group]}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{Boolean(record.imagePreviews[index]?.before || record.imagePreviews[index]?.after) && (
|
||||
<details open={index < 3} className="mt-3 border-t border-[#e7e8ea] pt-3">
|
||||
|
||||
@ -267,7 +267,7 @@ export default function ProductPackageDetail({
|
||||
const psdFiles = material.assets.filter((a) => a.assetType === 'psd');
|
||||
const pendingIds = new Set(pendingAssetIds);
|
||||
const editsDisabled = Boolean(editingAssetId) || assetEditingDisabled;
|
||||
const singleEditsDisabled = editsDisabled || pendingGroups.length > 0;
|
||||
const singleEditsDisabled = (group: TaskDetailEditGroup) => editsDisabled || pendingGroups.includes(group);
|
||||
|
||||
useEffect(() => {
|
||||
setSelectedGroups(new Set());
|
||||
@ -480,7 +480,7 @@ export default function ProductPackageDetail({
|
||||
<AssetEditMenu
|
||||
asset={img}
|
||||
busy={editingAssetId === img.id}
|
||||
disabled={singleEditsDisabled}
|
||||
disabled={singleEditsDisabled('main')}
|
||||
onRequestReplace={onRequestReplace}
|
||||
onRequestRename={onRequestRename}
|
||||
onRequestDelete={onRequestDelete}
|
||||
@ -499,7 +499,7 @@ export default function ProductPackageDetail({
|
||||
<AddImageButton
|
||||
label="追加图片"
|
||||
hint="加入主图末尾"
|
||||
disabled={singleEditsDisabled}
|
||||
disabled={singleEditsDisabled('main')}
|
||||
onClick={() => onRequestAppend('main')}
|
||||
className="h-[84px] w-[84px] flex-shrink-0"
|
||||
/>
|
||||
@ -531,7 +531,7 @@ export default function ProductPackageDetail({
|
||||
<AssetEditMenu
|
||||
asset={img}
|
||||
busy={editingAssetId === img.id}
|
||||
disabled={singleEditsDisabled}
|
||||
disabled={singleEditsDisabled('detail')}
|
||||
onRequestReplace={onRequestReplace}
|
||||
onRequestRename={onRequestRename}
|
||||
onRequestDelete={onRequestDelete}
|
||||
@ -549,7 +549,7 @@ export default function ProductPackageDetail({
|
||||
</div>
|
||||
{canManageAssets && onRequestInsert && detailImages[index + 1] && (
|
||||
<DetailInsertButton
|
||||
disabled={singleEditsDisabled}
|
||||
disabled={singleEditsDisabled('detail')}
|
||||
afterIndex={index + 1}
|
||||
beforeIndex={index + 2}
|
||||
onClick={() => onRequestInsert({
|
||||
@ -565,7 +565,7 @@ export default function ProductPackageDetail({
|
||||
<AddImageButton
|
||||
label="添加详情图"
|
||||
hint="上传详情图原图"
|
||||
disabled={singleEditsDisabled}
|
||||
disabled={singleEditsDisabled('detail')}
|
||||
onClick={() => onRequestAppend('detail')}
|
||||
className="min-h-20 w-full"
|
||||
/>
|
||||
@ -661,7 +661,7 @@ export default function ProductPackageDetail({
|
||||
<AssetEditMenu
|
||||
asset={img}
|
||||
busy={editingAssetId === img.id}
|
||||
disabled={singleEditsDisabled}
|
||||
disabled={singleEditsDisabled('sku')}
|
||||
onRequestReplace={onRequestReplace}
|
||||
onRequestRename={onRequestRename}
|
||||
onRequestDelete={onRequestDelete}
|
||||
@ -680,7 +680,7 @@ export default function ProductPackageDetail({
|
||||
<AddImageButton
|
||||
label="追加图片"
|
||||
hint="加入 SKU 末尾"
|
||||
disabled={singleEditsDisabled}
|
||||
disabled={singleEditsDisabled('sku')}
|
||||
onClick={() => onRequestAppend('sku')}
|
||||
className="aspect-square w-full"
|
||||
/>
|
||||
|
||||
@ -347,7 +347,7 @@ describe('task-detail asset edit batch data-plane', () => {
|
||||
expect(prisma.$transaction).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('第二组替换图片无法解码时,不应用第一组或覆盖正式总包', async () => {
|
||||
test('另一组的单张替换失败时,不应用已重建的整组变更或覆盖正式总包', async () => {
|
||||
const replacement = await createSolidImage('replacement.png', 80, 80)
|
||||
const damagedPath = path.join(tempRoot, 'damaged.png')
|
||||
await writeFile(damagedPath, 'not a PNG')
|
||||
@ -362,14 +362,14 @@ describe('task-detail asset edit batch data-plane', () => {
|
||||
const zipRows = ['main', 'detail', 'all'].map((group) => ({
|
||||
id: 'zip-' + group, assetType: group, fileUrl: path.join(tempRoot, group + '.zip'), fileName: group + '.zip',
|
||||
}))
|
||||
configureAssetQueries({ previewRows, zipRows, extraFindMany: [previewRows, zipRows] })
|
||||
configureAssetQueries({ previewRows, zipRows })
|
||||
mockListZipEntries.mockResolvedValueOnce([{ name: 'main.png' }]).mockResolvedValueOnce([{ name: 'detail.png' }])
|
||||
|
||||
await expect(batchEditTaskDetailImages({
|
||||
materialId: 'material-1', operatorUserId: 'operator-1',
|
||||
operations: [
|
||||
{ kind: 'group_images', group: 'main', assetIds: ['main-1'], files: [{ uploadId: 'main' }] },
|
||||
{ kind: 'group_images', group: 'detail', assetIds: ['detail-1'], files: [{ uploadId: 'detail' }] },
|
||||
{ kind: 'replace', assetId: 'detail-1', uploadId: 'detail' },
|
||||
],
|
||||
})).rejects.toThrow('不是有效图片')
|
||||
|
||||
|
||||
@ -62,9 +62,7 @@ jest.mock('@/lib/task-detail-asset-edit', () => ({
|
||||
assertTaskDetailGroupSelection: jest.fn(),
|
||||
assertTaskDetailImageEditReady: jest.fn(),
|
||||
batchEditTaskDetailImages: jest.fn(),
|
||||
TaskDetailAssetEditError: class extends Error {
|
||||
constructor(message: string, public statusCode = 400) { super(message) }
|
||||
},
|
||||
TaskDetailAssetEditError: jest.requireActual('@/lib/task-detail-edit-groups').TaskDetailAssetEditError,
|
||||
}))
|
||||
jest.mock('@/lib/task-detail-change-notifications', () => ({
|
||||
queueTaskDetailChangeNotification: jest.fn(),
|
||||
@ -436,16 +434,43 @@ describe('任务详情图片变更主管审批', () => {
|
||||
expect(queueTaskDetailChangeNotification).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('跨主图和详情图的变更在暂存前直接拒绝', async () => {
|
||||
test('主图、详情图和 SKU 图的单张与整组变更进入同一张审批单', async () => {
|
||||
;(getEmployeeByUserId as jest.Mock).mockResolvedValue(employee('P'))
|
||||
|
||||
await expect(submitTaskDetailChange('material-1', {
|
||||
id: 'user-1',
|
||||
role: 'USER',
|
||||
}, [
|
||||
;(prisma.material.findFirst as jest.Mock).mockResolvedValue({
|
||||
...material, assets: [...material.assets, { id: 'sku-1', assetType: 'sku-preview' }],
|
||||
})
|
||||
;(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()))
|
||||
;(prisma.taskDetailChangeRequest.create as jest.Mock).mockImplementation(async ({ data }) => ({ ...data, material }))
|
||||
const operations = [
|
||||
{ kind: 'delete', assetId: 'asset-1' },
|
||||
{ kind: 'delete', assetId: 'detail-1' },
|
||||
])).rejects.toThrow('一次只能提交同一图片分组')
|
||||
{ kind: 'group_images', group: 'detail', assetIds: ['detail-1'], uploadIds: [] },
|
||||
{ kind: 'rename', assetId: 'sku-1', newFileName: 'sku-new' },
|
||||
]
|
||||
|
||||
const result = await submitTaskDetailChange('material-1', { id: 'user-1', role: 'USER' }, operations)
|
||||
|
||||
expect(result.mode).toBe('pending_approval')
|
||||
expect(prisma.taskDetailChangeRequest.create).toHaveBeenCalledTimes(1)
|
||||
const { data } = jest.mocked(prisma.taskDetailChangeRequest.create).mock.calls[0][0]
|
||||
expect(data.operations).toEqual([
|
||||
{ ...operations[0], group: 'main' },
|
||||
{ kind: 'group_images', group: 'detail', assetIds: ['detail-1'], stagedFiles: [] },
|
||||
{ ...operations[2], group: 'sku' },
|
||||
])
|
||||
expect(jest.mocked(assertTaskDetailImageEditReady).mock.calls.map(([input]) => input.group)).toEqual(['main', 'detail', 'sku'])
|
||||
expect(queueTaskDetailChangeNotification).toHaveBeenCalledTimes(1)
|
||||
expect(batchEditTaskDetailImages).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('同一组的整组和单张操作在暂存前拒绝', async () => {
|
||||
await expect(submitTaskDetailChange('material-1', { id: 'user-1', role: 'USER' }, [
|
||||
{ kind: 'group_images', group: 'main', assetIds: ['asset-1'], uploadIds: [] },
|
||||
{ kind: 'delete', assetId: 'asset-1' },
|
||||
])).rejects.toThrow('同一图片分组的整组变更不能与该组的其他变更同时提交')
|
||||
|
||||
expect(withTaskDetailStagedUploads).not.toHaveBeenCalled()
|
||||
expect(prisma.taskDetailChangeRequest.create).not.toHaveBeenCalled()
|
||||
|
||||
@ -13,6 +13,12 @@ import {
|
||||
} from '@/lib/material-upload-cross-process-lock'
|
||||
import { isProductPackageType } from '@/lib/material-type-mapper'
|
||||
import { deriveTaskDetailIsFullSet } from '@/lib/task-detail-full-set'
|
||||
import {
|
||||
groupTaskDetailImageEdits,
|
||||
TASK_DETAIL_PREVIEW_TYPES as GROUP_PREVIEW_TYPES,
|
||||
TaskDetailAssetEditError,
|
||||
type TaskDetailEditGroup,
|
||||
} from '@/lib/task-detail-edit-groups'
|
||||
import {
|
||||
canAccessMaterialPrivacy,
|
||||
TASK_DETAIL_PRIVACY_SELECT,
|
||||
@ -56,7 +62,7 @@ import { promisify } from 'util'
|
||||
* 匹配不上就拒绝编辑,并交由来源映射核对,不能悄悄改错图。
|
||||
*/
|
||||
|
||||
export type TaskDetailEditGroup = 'main' | 'sku' | 'detail'
|
||||
export { TaskDetailAssetEditError, type TaskDetailEditGroup } from '@/lib/task-detail-edit-groups'
|
||||
|
||||
const GROUP_ZIP_LABELS: Record<TaskDetailEditGroup, string> = {
|
||||
main: '主图',
|
||||
@ -64,24 +70,8 @@ const GROUP_ZIP_LABELS: Record<TaskDetailEditGroup, string> = {
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
export function assertTaskDetailGroupSelection(
|
||||
group: TaskDetailEditGroup,
|
||||
assetIds: string[],
|
||||
@ -573,7 +563,7 @@ async function assertCanManage(
|
||||
}
|
||||
}
|
||||
|
||||
async function loadEditContext(options: {
|
||||
type LoadEditContextOptions = {
|
||||
materialId: string
|
||||
assetId?: string
|
||||
operatorUserId: string
|
||||
@ -582,7 +572,9 @@ async function loadEditContext(options: {
|
||||
allowEmptyGroup?: boolean
|
||||
expectedMaterialUpdatedAt?: Date | string
|
||||
approvalRequestId?: string
|
||||
}): Promise<EditContext> {
|
||||
}
|
||||
|
||||
async function loadEditSnapshot(options: LoadEditContextOptions) {
|
||||
const material = await prisma.material.findFirst({
|
||||
where: { id: options.materialId, deletedAt: null },
|
||||
select: {
|
||||
@ -691,6 +683,14 @@ async function loadEditContext(options: {
|
||||
(previewRows as PreviewRowLike[]).filter((row) => row.assetType === GROUP_PREVIEW_TYPES[group]),
|
||||
)
|
||||
}
|
||||
return { material, rowsByGroup, groupZipAssets, allZipAsset, psdCount }
|
||||
}
|
||||
|
||||
async function loadEditContext(
|
||||
options: LoadEditContextOptions,
|
||||
snapshot?: Awaited<ReturnType<typeof loadEditSnapshot>>,
|
||||
): Promise<EditContext> {
|
||||
const { material, rowsByGroup, groupZipAssets, allZipAsset, psdCount } = snapshot ?? await loadEditSnapshot(options)
|
||||
|
||||
const targetGroup = options.assetId
|
||||
? GROUPS.find((group) => rowsByGroup[group].some((row) => row.id === options.assetId))
|
||||
@ -2964,40 +2964,88 @@ export interface BatchTaskDetailImageEditInput {
|
||||
operations: BatchTaskDetailImageEditOperation[]
|
||||
}
|
||||
|
||||
const MAX_BATCH_OPERATIONS = 100
|
||||
|
||||
async function prepareWholeGroupRebuilds(input: BatchTaskDetailImageEditInput, edits: GroupImagesEdit[]) {
|
||||
const contexts: EditContext[] = []
|
||||
for (const edit of edits) {
|
||||
const context = await loadEditContext({
|
||||
materialId: input.materialId,
|
||||
operatorUserId: input.operatorUserId,
|
||||
operatorRole: input.operatorRole,
|
||||
group: edit.group,
|
||||
expectedMaterialUpdatedAt: input.expectedMaterialUpdatedAt,
|
||||
approvalRequestId: input.approvalRequestId,
|
||||
async function prepareSingleImageEdits(
|
||||
context: EditContext,
|
||||
singleEdits: Exclude<BatchTaskDetailImageEditOperation, GroupImagesEdit>[],
|
||||
countSourceBytes: (bytes: number) => void,
|
||||
) {
|
||||
const prepared: PreparedBatchOperation[] = []
|
||||
for (const operation of singleEdits) {
|
||||
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
|
||||
}
|
||||
if (operation.kind === 'replace') {
|
||||
const source = await resolveMutationSource({
|
||||
uploadId: operation.uploadId,
|
||||
stagedFile: operation.stagedFile,
|
||||
operatorUserId: context.operatorUserId,
|
||||
actionLabel: '替换图片',
|
||||
})
|
||||
countSourceBytes(source.fileSize)
|
||||
prepared.push({
|
||||
assetId: operation.assetId,
|
||||
mutation: { kind: 'replace', source },
|
||||
})
|
||||
continue
|
||||
}
|
||||
if (operation.kind === 'append') {
|
||||
const source = await resolveMutationSource({
|
||||
uploadId: operation.uploadId,
|
||||
stagedFile: operation.stagedFile,
|
||||
operatorUserId: context.operatorUserId,
|
||||
actionLabel: '追加图片',
|
||||
})
|
||||
countSourceBytes(source.fileSize)
|
||||
prepared.push({
|
||||
mutation: {
|
||||
kind: 'append',
|
||||
group: operation.group,
|
||||
source,
|
||||
skuCode: operation.skuCode?.trim() || null,
|
||||
barcodes: Array.from(new Set((operation.barcodes || []).filter(Boolean))),
|
||||
},
|
||||
})
|
||||
continue
|
||||
}
|
||||
const source = await resolveMutationSource({
|
||||
uploadId: operation.uploadId,
|
||||
stagedFile: operation.stagedFile,
|
||||
operatorUserId: context.operatorUserId,
|
||||
actionLabel: '插入图片',
|
||||
})
|
||||
countSourceBytes(source.fileSize)
|
||||
prepared.push({
|
||||
mutation: {
|
||||
kind: 'insert',
|
||||
afterAssetId: operation.afterAssetId,
|
||||
beforeAssetId: operation.beforeAssetId,
|
||||
source,
|
||||
},
|
||||
})
|
||||
assertTaskDetailGroupSelection(edit.group, edit.assetIds, context.rowsByGroup[edit.group])
|
||||
contexts.push(context)
|
||||
}
|
||||
|
||||
let totalBytes = 0
|
||||
const countSourceBytes = (bytes: number) => {
|
||||
totalBytes += bytes
|
||||
if (totalBytes > TASK_DETAIL_UPLOAD_LIMITS.maxTotalSourceBytes) {
|
||||
throw new TaskDetailAssetEditError('本次替换图片总大小超过 1GB,请先压缩图片')
|
||||
}
|
||||
}
|
||||
const rebuilds: GroupRebuild[] = []
|
||||
try {
|
||||
for (let index = 0; index < edits.length; index += 1) {
|
||||
rebuilds.push(await executeBatchRebuild(contexts[index], [], { edit: edits[index], countSourceBytes }))
|
||||
}
|
||||
} catch (error) {
|
||||
await cleanupUnappliedRebuilds(rebuilds)
|
||||
throw error
|
||||
}
|
||||
return rebuilds
|
||||
return prepared
|
||||
}
|
||||
|
||||
async function applyBatchRebuilds(
|
||||
@ -3044,145 +3092,61 @@ async function applyBatchRebuilds(
|
||||
}
|
||||
}
|
||||
|
||||
/** 整组操作可同时修改不同组;单图操作在同组内一次应用。 */
|
||||
/** Rebuild each affected group, then publish the previews and archives in one transaction. */
|
||||
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} 项操作,请分批提交`)
|
||||
}
|
||||
const groupEdits = operations.filter((operation) => operation.kind === 'group_images')
|
||||
if (groupEdits.length > 0) {
|
||||
if (groupEdits.length !== operations.length || new Set(groupEdits.map((item) => item.group)).size !== groupEdits.length) {
|
||||
throw new TaskDetailAssetEditError('整组变更每组只提交一次,请与单图编辑分开提交')
|
||||
}
|
||||
if (groupEdits.some((item) => item.files.length > TASK_DETAIL_UPLOAD_LIMITS.maxImagesPerGroup)) {
|
||||
throw new TaskDetailAssetEditError(`每组最多替换为 ${TASK_DETAIL_UPLOAD_LIMITS.maxImagesPerGroup} 张原图`)
|
||||
}
|
||||
return runEditOperation(input.materialId, async (assertHeld) => {
|
||||
const rebuilds = await prepareWholeGroupRebuilds(input, groupEdits)
|
||||
const uploadIds = groupEdits.flatMap((edit) => edit.files.flatMap((file) => file.uploadId ? [file.uploadId.trim()] : []))
|
||||
return applyBatchRebuilds(rebuilds, uploadIds, operations.length, assertHeld, true)
|
||||
})
|
||||
if (operations.length > TASK_DETAIL_UPLOAD_LIMITS.maxTotalImageCount) {
|
||||
throw new TaskDetailAssetEditError(`一次最多提交 ${TASK_DETAIL_UPLOAD_LIMITS.maxTotalImageCount} 项图片变更`)
|
||||
}
|
||||
|
||||
const singleEdits = operations.filter((operation) => operation.kind !== 'group_images')
|
||||
return runEditOperation(input.materialId, async (assertHeld) => {
|
||||
const seed = singleEdits[0]
|
||||
const context = await loadEditContext({
|
||||
materialId: input.materialId,
|
||||
operatorUserId: input.operatorUserId,
|
||||
operatorRole: input.operatorRole,
|
||||
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,
|
||||
const snapshot = await loadEditSnapshot(input)
|
||||
const groups = groupTaskDetailImageEdits(operations, Object.values(snapshot.rowsByGroup).flat())
|
||||
const groupEdits = operations.filter((operation) => operation.kind === 'group_images')
|
||||
for (const edit of groupEdits) {
|
||||
assertTaskDetailGroupSelection(edit.group, edit.assetIds, snapshot.rowsByGroup[edit.group])
|
||||
if (edit.files.length > TASK_DETAIL_UPLOAD_LIMITS.maxImagesPerGroup) {
|
||||
throw new TaskDetailAssetEditError(`每组最多替换为 ${TASK_DETAIL_UPLOAD_LIMITS.maxImagesPerGroup} 张原图`)
|
||||
}
|
||||
}
|
||||
const uploadIds = operations.flatMap((edit) => {
|
||||
if (edit.kind === 'group_images') {
|
||||
return edit.files.flatMap((file) => file.uploadId ? [file.uploadId.trim()] : [])
|
||||
}
|
||||
return 'uploadId' in edit && edit.uploadId ? [edit.uploadId.trim()] : []
|
||||
})
|
||||
|
||||
const validAssetIds = new Set(
|
||||
context.runs.flatMap((run) => run.rows.map((row) => row.id)),
|
||||
)
|
||||
for (const operation of singleEdits) {
|
||||
if (operation.kind === 'append') {
|
||||
if (operation.group !== context.group) {
|
||||
throw new TaskDetailAssetEditError('批量操作只支持同一分组(主图/SKU/详情)内的图片')
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (operation.kind === 'insert') {
|
||||
if (
|
||||
context.group !== 'detail'
|
||||
|| !validAssetIds.has(operation.afterAssetId)
|
||||
|| !validAssetIds.has(operation.beforeAssetId)
|
||||
) {
|
||||
throw new TaskDetailAssetEditError('批量操作只支持同一分组(主图/SKU/详情)内的图片')
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (!validAssetIds.has(operation.assetId)) {
|
||||
throw new TaskDetailAssetEditError('批量操作只支持同一分组(主图/SKU/详情)内的图片')
|
||||
let totalBytes = 0
|
||||
const countSourceBytes = (bytes: number) => {
|
||||
totalBytes += bytes
|
||||
if (totalBytes > TASK_DETAIL_UPLOAD_LIMITS.maxTotalSourceBytes) {
|
||||
throw new TaskDetailAssetEditError('本次变更上传的图片总大小超过 1GB,请先压缩图片')
|
||||
}
|
||||
}
|
||||
|
||||
const prepared: PreparedBatchOperation[] = []
|
||||
const consumedUploadIds: string[] = []
|
||||
for (const operation of singleEdits) {
|
||||
if ('uploadId' in operation && operation.uploadId) consumedUploadIds.push(operation.uploadId.trim())
|
||||
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 rebuilds: GroupRebuild[] = []
|
||||
try {
|
||||
for (const [group, edits] of Array.from(groups)) {
|
||||
const firstEdit = edits[0]
|
||||
const context = await loadEditContext({
|
||||
...input,
|
||||
group,
|
||||
assetId: 'assetId' in firstEdit ? firstEdit.assetId : firstEdit.kind === 'insert' ? firstEdit.afterAssetId : undefined,
|
||||
allowEmptyGroup: firstEdit.kind === 'append',
|
||||
}, snapshot)
|
||||
if (firstEdit.kind === 'group_images') {
|
||||
rebuilds.push(await executeBatchRebuild(context, [], { edit: firstEdit, countSourceBytes }))
|
||||
} else {
|
||||
const prepared = await prepareSingleImageEdits(context, edits.filter((edit) => edit.kind !== 'group_images'), countSourceBytes)
|
||||
rebuilds.push(await executeBatchRebuild(context, prepared))
|
||||
}
|
||||
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
|
||||
}
|
||||
if (operation.kind === 'replace') {
|
||||
const source = await resolveMutationSource({
|
||||
uploadId: operation.uploadId,
|
||||
stagedFile: operation.stagedFile,
|
||||
operatorUserId: input.operatorUserId,
|
||||
actionLabel: '替换图片',
|
||||
})
|
||||
prepared.push({
|
||||
assetId: operation.assetId,
|
||||
mutation: { kind: 'replace', source },
|
||||
})
|
||||
continue
|
||||
}
|
||||
if (operation.kind === 'append') {
|
||||
const source = await resolveMutationSource({
|
||||
uploadId: operation.uploadId,
|
||||
stagedFile: operation.stagedFile,
|
||||
operatorUserId: input.operatorUserId,
|
||||
actionLabel: '追加图片',
|
||||
})
|
||||
prepared.push({
|
||||
mutation: {
|
||||
kind: 'append',
|
||||
group: operation.group,
|
||||
source,
|
||||
skuCode: operation.skuCode?.trim() || null,
|
||||
barcodes: Array.from(new Set((operation.barcodes || []).filter(Boolean))),
|
||||
},
|
||||
})
|
||||
continue
|
||||
}
|
||||
const source = await resolveMutationSource({
|
||||
uploadId: operation.uploadId,
|
||||
stagedFile: operation.stagedFile,
|
||||
operatorUserId: input.operatorUserId,
|
||||
actionLabel: '插入图片',
|
||||
})
|
||||
prepared.push({
|
||||
mutation: {
|
||||
kind: 'insert',
|
||||
afterAssetId: operation.afterAssetId,
|
||||
beforeAssetId: operation.beforeAssetId,
|
||||
source,
|
||||
},
|
||||
})
|
||||
} catch (error) {
|
||||
await cleanupUnappliedRebuilds(rebuilds)
|
||||
throw error
|
||||
}
|
||||
|
||||
const outcome = await executeBatchRebuild(context, prepared)
|
||||
return applyBatchRebuilds([outcome], consumedUploadIds, operations.length, assertHeld)
|
||||
return applyBatchRebuilds(rebuilds, uploadIds, operations.length, assertHeld, groupEdits.length > 0)
|
||||
})
|
||||
}
|
||||
|
||||
@ -12,6 +12,7 @@ import { prisma } from '@/lib/prisma'
|
||||
import { getPublicAppOrigin } from '@/lib/public-app-url'
|
||||
import { buildDingtalkEntryPath } from '@/lib/safe-redirect'
|
||||
import { isSystemAdmin } from '@/lib/department-permission'
|
||||
import { groupTaskDetailImageEdits, TASK_DETAIL_PREVIEW_TYPES } from '@/lib/task-detail-edit-groups'
|
||||
import {
|
||||
cleanupTaskDetailChangeStaging,
|
||||
resolveTaskDetailStagedFile,
|
||||
@ -45,7 +46,6 @@ const REQUEST_STATUS = {
|
||||
|
||||
const APPROVAL_WINDOW_MS = 24 * 60 * 60 * 1000
|
||||
const STALE_APPLYING_MS = 30 * 60 * 1000
|
||||
const MAX_OPERATIONS = 100
|
||||
|
||||
export class TaskDetailChangeApprovalError extends Error {
|
||||
constructor(message: string, public statusCode = 400) {
|
||||
@ -80,7 +80,7 @@ type StoreSingle<T extends SingleImageChangeOperation> =
|
||||
T extends { uploadId: string } ? Omit<T, 'uploadId'> & { stagedFile: TaskDetailStagedFile } : T
|
||||
|
||||
export type StoredTaskDetailChangeOperation =
|
||||
| StoreSingle<SingleImageChangeOperation>
|
||||
| (StoreSingle<SingleImageChangeOperation> & { group?: TaskDetailEditGroup })
|
||||
| (Omit<GroupImagesOperation, 'uploadIds'> & { stagedFiles: TaskDetailStagedFile[] })
|
||||
|
||||
type Actor = {
|
||||
@ -97,8 +97,8 @@ function clean(value: unknown) {
|
||||
function normalizeOperations(value: unknown): TaskDetailChangeOperationInput[] {
|
||||
const rows = Array.isArray(value) ? value : []
|
||||
if (rows.length === 0) throw new TaskDetailChangeApprovalError('图片变更不能为空')
|
||||
if (rows.length > MAX_OPERATIONS) {
|
||||
throw new TaskDetailChangeApprovalError(`一次最多提交 ${MAX_OPERATIONS} 项图片变更`)
|
||||
if (rows.length > TASK_DETAIL_UPLOAD_LIMITS.maxTotalImageCount) {
|
||||
throw new TaskDetailChangeApprovalError(`一次最多提交 ${TASK_DETAIL_UPLOAD_LIMITS.maxTotalImageCount} 项图片变更`)
|
||||
}
|
||||
|
||||
const operations: TaskDetailChangeOperationInput[] = []
|
||||
@ -179,60 +179,9 @@ function normalizeOperations(value: unknown): TaskDetailChangeOperationInput[] {
|
||||
}
|
||||
throw new TaskDetailChangeApprovalError(`不支持的图片变更类型:${kind || '空'}`)
|
||||
}
|
||||
const wholeGroups = operations.filter((item) => item.kind === 'group_images')
|
||||
if (wholeGroups.length > 0) {
|
||||
if (wholeGroups.length !== operations.length || new Set(wholeGroups.map((item) => item.group)).size !== wholeGroups.length) {
|
||||
throw new TaskDetailChangeApprovalError('整组变更每组只提交一次,请与单图编辑分开提交')
|
||||
}
|
||||
const uploads = wholeGroups.flatMap((item) => item.uploadIds)
|
||||
if (new Set(uploads).size !== uploads.length) {
|
||||
throw new TaskDetailChangeApprovalError('不同分组不能共用同一个上传文件')
|
||||
}
|
||||
if (uploads.length > TASK_DETAIL_UPLOAD_LIMITS.maxTotalImageCount) {
|
||||
throw new TaskDetailChangeApprovalError(`一次最多替换 ${TASK_DETAIL_UPLOAD_LIMITS.maxTotalImageCount} 张原图`)
|
||||
}
|
||||
}
|
||||
return operations
|
||||
}
|
||||
|
||||
function assertSingleOperationGroup(
|
||||
operations: SingleImageChangeOperation[],
|
||||
assets: Array<{ id: string; assetType: string }>,
|
||||
): 'main' | 'sku' | 'detail' {
|
||||
const assetGroups = new Map<string, 'main' | 'sku' | 'detail'>()
|
||||
for (const asset of assets) {
|
||||
if (asset.assetType === 'main-preview') assetGroups.set(asset.id, 'main')
|
||||
if (asset.assetType === 'sku-preview') assetGroups.set(asset.id, 'sku')
|
||||
if (asset.assetType === 'detail-preview') assetGroups.set(asset.id, 'detail')
|
||||
}
|
||||
const groups = new Set<'main' | 'sku' | 'detail'>()
|
||||
for (const operation of operations) {
|
||||
if (operation.kind === 'append') {
|
||||
groups.add(operation.group)
|
||||
continue
|
||||
}
|
||||
if (operation.kind === 'insert') {
|
||||
if (
|
||||
assetGroups.get(operation.afterAssetId) !== 'detail'
|
||||
|| assetGroups.get(operation.beforeAssetId) !== 'detail'
|
||||
) {
|
||||
throw new TaskDetailChangeApprovalError('详情图插入位置不存在或不属于该素材', 404)
|
||||
}
|
||||
groups.add('detail')
|
||||
continue
|
||||
}
|
||||
const group = assetGroups.get(operation.assetId)
|
||||
if (!group) {
|
||||
throw new TaskDetailChangeApprovalError('要修改的图片不存在或不属于该素材', 404)
|
||||
}
|
||||
groups.add(group)
|
||||
}
|
||||
if (groups.size !== 1) {
|
||||
throw new TaskDetailChangeApprovalError('一次只能提交同一图片分组(主图、SKU图或详情图)的变更,请分组提交')
|
||||
}
|
||||
return Array.from(groups)[0]
|
||||
}
|
||||
|
||||
async function loadAuthorizedContext(materialId: string, actor: Actor) {
|
||||
const [material, employee] = await Promise.all([
|
||||
prisma.material.findFirst({
|
||||
@ -248,7 +197,7 @@ async function loadAuthorizedContext(materialId: string, actor: Actor) {
|
||||
productModel: true,
|
||||
updatedAt: true,
|
||||
assets: {
|
||||
where: { assetType: { in: ['main-preview', 'sku-preview', 'detail-preview'] } },
|
||||
where: { assetType: { in: Object.values(TASK_DETAIL_PREVIEW_TYPES) } },
|
||||
select: { id: true, assetType: true },
|
||||
},
|
||||
},
|
||||
@ -399,6 +348,7 @@ async function queueRequesterResultNotification(request: any, label: string) {
|
||||
|
||||
function storeOperations(
|
||||
operations: TaskDetailChangeOperationInput[],
|
||||
groups: Map<TaskDetailEditGroup, TaskDetailChangeOperationInput[]>,
|
||||
staged: Map<string, TaskDetailStagedFile>,
|
||||
): StoredTaskDetailChangeOperation[] {
|
||||
const getStagedFile = (uploadId: string) => {
|
||||
@ -406,14 +356,22 @@ function storeOperations(
|
||||
if (!stagedFile) throw new TaskDetailChangeApprovalError('图片持久暂存结果缺失', 500)
|
||||
return stagedFile
|
||||
}
|
||||
const groupsByOperation = new Map(
|
||||
Array.from(groups, ([group, edits]) => edits.map((edit) => [edit, group] as const)).flat(),
|
||||
)
|
||||
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
|
||||
const { uploadId: _uploadId, ...rest } = operation
|
||||
return { ...rest, stagedFile: getStagedFile(operation.uploadId) }
|
||||
if ('assetId' in operation) {
|
||||
const group = groupsByOperation.get(operation)
|
||||
if (operation.kind !== 'replace') return { ...operation, group }
|
||||
const { uploadId, ...rest } = operation
|
||||
return { ...rest, group, stagedFile: getStagedFile(uploadId) }
|
||||
}
|
||||
const { uploadId, ...rest } = operation
|
||||
return { ...rest, stagedFile: getStagedFile(uploadId) }
|
||||
})
|
||||
}
|
||||
|
||||
@ -442,12 +400,20 @@ export async function submitTaskDetailChange(
|
||||
const operations = normalizeOperations(rawOperations)
|
||||
const { material, employee } = await loadAuthorizedContext(materialId, actor)
|
||||
const groupEdits = operations.filter((operation) => operation.kind === 'group_images')
|
||||
const groups = groupEdits.length > 0
|
||||
? groupEdits.map((item) => item.group)
|
||||
: [assertSingleOperationGroup(operations.filter((operation) => operation.kind !== 'group_images'), material.assets)]
|
||||
const groups = groupTaskDetailImageEdits(operations, material.assets)
|
||||
const uploadIds = operations.flatMap((item) => {
|
||||
if (item.kind === 'group_images') return item.uploadIds
|
||||
return 'uploadId' in item ? [item.uploadId] : []
|
||||
})
|
||||
if (new Set(uploadIds).size !== uploadIds.length) {
|
||||
throw new TaskDetailChangeApprovalError('同一次变更不能重复使用同一个上传文件')
|
||||
}
|
||||
if (uploadIds.length > TASK_DETAIL_UPLOAD_LIMITS.maxTotalImageCount) {
|
||||
throw new TaskDetailChangeApprovalError(`一次最多上传 ${TASK_DETAIL_UPLOAD_LIMITS.maxTotalImageCount} 张原图`)
|
||||
}
|
||||
try {
|
||||
for (const edit of groupEdits) assertTaskDetailGroupSelection(edit.group, edit.assetIds, material.assets)
|
||||
for (const group of groups) {
|
||||
for (const group of Array.from(groups.keys())) {
|
||||
await assertTaskDetailImageEditReady({
|
||||
materialId,
|
||||
operatorUserId: actor.id,
|
||||
@ -471,7 +437,7 @@ export async function submitTaskDetailChange(
|
||||
materialId,
|
||||
operatorUserId: actor.id,
|
||||
operatorRole: actor.role,
|
||||
...(groupEdits.length > 0 ? { expectedMaterialUpdatedAt: material.updatedAt } : {}),
|
||||
...(groupEdits.length > 0 || groups.size > 1 ? { expectedMaterialUpdatedAt: material.updatedAt } : {}),
|
||||
operations: operations.map((operation) => {
|
||||
if (operation.kind !== 'group_images') return operation
|
||||
const { uploadIds, ...rest } = operation
|
||||
@ -486,18 +452,13 @@ export async function submitTaskDetailChange(
|
||||
const manager = await resolveManager(employee, subAdminDingtalkUserIds)
|
||||
const requestId = randomUUID()
|
||||
const expiresAt = new Date(Date.now() + APPROVAL_WINDOW_MS)
|
||||
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,
|
||||
...(groupEdits.length > 0 ? { enforceImageLimits: true } : {}),
|
||||
enforceImageLimits: true,
|
||||
commit: async (staged) => {
|
||||
const storedOperations = storeOperations(operations, staged)
|
||||
const storedOperations = storeOperations(operations, groups, staged)
|
||||
return prisma.taskDetailChangeRequest.create({
|
||||
data: {
|
||||
id: requestId,
|
||||
|
||||
61
lib/task-detail-edit-groups.ts
Normal file
61
lib/task-detail-edit-groups.ts
Normal file
@ -0,0 +1,61 @@
|
||||
export const TASK_DETAIL_PREVIEW_TYPES = {
|
||||
main: 'main-preview',
|
||||
sku: 'sku-preview',
|
||||
detail: 'detail-preview',
|
||||
} as const
|
||||
|
||||
export type TaskDetailEditGroup = keyof typeof TASK_DETAIL_PREVIEW_TYPES
|
||||
|
||||
export function getTaskDetailEditGroup(assetType: string | undefined): TaskDetailEditGroup | null {
|
||||
if (assetType === TASK_DETAIL_PREVIEW_TYPES.main) return 'main'
|
||||
if (assetType === TASK_DETAIL_PREVIEW_TYPES.sku) return 'sku'
|
||||
if (assetType === TASK_DETAIL_PREVIEW_TYPES.detail) return 'detail'
|
||||
return null
|
||||
}
|
||||
|
||||
export class TaskDetailAssetEditError extends Error {
|
||||
constructor(message: string, readonly statusCode: 400 | 403 | 404 | 409 = 400) {
|
||||
super(message)
|
||||
this.name = 'TaskDetailAssetEditError'
|
||||
}
|
||||
}
|
||||
|
||||
type GroupableImageEdit =
|
||||
| { kind: 'group_images' | 'append'; group: TaskDetailEditGroup }
|
||||
| { kind: 'insert'; afterAssetId: string; beforeAssetId: string }
|
||||
| { kind: 'delete' | 'rename' | 'replace'; assetId: string }
|
||||
|
||||
export function groupTaskDetailImageEdits<Edit extends GroupableImageEdit>(
|
||||
edits: Edit[],
|
||||
assets: Array<{ id: string; assetType: string }>,
|
||||
) {
|
||||
const groups = new Map<TaskDetailEditGroup, Edit[]>()
|
||||
const assetGroups = new Map(assets.map((asset) => [asset.id, getTaskDetailEditGroup(asset.assetType)]))
|
||||
for (const edit of edits) {
|
||||
let group: TaskDetailEditGroup | null | undefined
|
||||
if ('assetId' in edit) {
|
||||
group = assetGroups.get(edit.assetId)
|
||||
if (!group) {
|
||||
throw new TaskDetailAssetEditError('要编辑的图片不存在或不属于该素材', 404)
|
||||
}
|
||||
} else if (edit.kind === 'insert') {
|
||||
if (assetGroups.get(edit.afterAssetId) !== 'detail' || assetGroups.get(edit.beforeAssetId) !== 'detail') {
|
||||
throw new TaskDetailAssetEditError('详情图插入位置不存在或不属于该素材', 404)
|
||||
}
|
||||
group = 'detail'
|
||||
} else {
|
||||
group = edit.group
|
||||
}
|
||||
|
||||
const current = groups.get(group)
|
||||
if (current) {
|
||||
if (edit.kind === 'group_images' || current[0].kind === 'group_images') {
|
||||
throw new TaskDetailAssetEditError('同一图片分组的整组变更不能与该组的其他变更同时提交')
|
||||
}
|
||||
current.push(edit)
|
||||
} else {
|
||||
groups.set(group, [edit])
|
||||
}
|
||||
}
|
||||
return groups
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user