From c0da4bd6e8fe125f62f8d7926593b8154a2670db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B1=85=E5=B1=85?= Date: Fri, 13 Nov 2026 14:51:42 +0800 Subject: [PATCH 1/4] =?UTF-8?q?fix(clearance):=20=E8=A1=A5=E9=BD=90?= =?UTF-8?q?=E8=87=AA=E5=8A=A8=E6=8E=A8=E4=BB=B7=E5=B9=B6=E4=BF=AE=E6=AD=A3?= =?UTF-8?q?=E7=A6=81=E6=8A=98=E4=B8=8E=E8=A7=84=E5=88=99=E5=8F=96=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../清货任务制定与推送流程-20261110.md | 9 + furniture-3d-system/package.json | 1 + .../clearance/priority-rules/route.ts | 2 + .../clearance/ClearanceRuleEditor.test.tsx | 66 +++++ .../clearance/ClearanceRuleEditor.tsx | 67 ++++- .../management/clearance/clearance.module.css | 46 ++++ .../src/lib/clearance-priority-rules.test.ts | 33 +++ .../src/lib/clearance-priority-rules.ts | 38 +++ ...in-clearance-auto-price.repository.test.ts | 39 +++ .../supply-chain-clearance.repository.ts | 42 +++ ...chain-clearance-price-push.service.test.ts | 56 ++++ ...-clearance-priority-config.service.test.ts | 18 ++ ...hain-clearance-task-import.service.test.ts | 10 +- .../supply-chain-clearance.service.test.ts | 258 +++++++++++++++++- ...pply-chain-clearance-price-push.service.ts | 37 ++- ...chain-clearance-priority-config.service.ts | 13 + .../supply-chain-clearance.service.ts | 204 ++++++++++++-- 17 files changed, 899 insertions(+), 40 deletions(-) create mode 100644 furniture-3d-system/src/server/repositories/__tests__/supply-chain-clearance-auto-price.repository.test.ts diff --git a/furniture-3d-system/docs/使用说明/清货任务制定与推送流程-20261110.md b/furniture-3d-system/docs/使用说明/清货任务制定与推送流程-20261110.md index f7347e73..c95e80fc 100644 --- a/furniture-3d-system/docs/使用说明/清货任务制定与推送流程-20261110.md +++ b/furniture-3d-system/docs/使用说明/清货任务制定与推送流程-20261110.md @@ -133,6 +133,15 @@ - 清货价可留空,填写时必须为正数且不高于成本价。 - 导入任务直接进入 `APPROVED` 状态,并同步刷新清货任务及清货价推送。 +### 4.7 优先级规则自动补清货价 + +现有优先级规则可配置两个可选字段: + +- 无任务自动推送清货价:开启后,命中规则且没有正式任务的商品可自动进入清货价推送。 +- 固定清货折扣:例如填写 `7` 表示 7 折,系统按成本价 × 0.7 生成清货价。 + +自动补价不覆盖已有任务价格或人工价格;人工价格优先于任务价格,任务价格优先于自动规则。 + ## 5. 状态流转 | 状态 | 含义 | 是否进入清货任务页 | diff --git a/furniture-3d-system/package.json b/furniture-3d-system/package.json index ae718700..c6e53b0d 100644 --- a/furniture-3d-system/package.json +++ b/furniture-3d-system/package.json @@ -12,6 +12,7 @@ "test": "jest", "verify:clearance-import-dialogs": "jest --runInBand src/app/supply-chain/management/clearance/ClearancePricePushView.test.tsx src/app/supply-chain/management/clearance/ClearancePricePushFeedback.test.tsx src/app/supply-chain/management/clearance/ClearancePricePushBatchEditDialog.test.tsx src/app/supply-chain/management/clearance/ClearanceTaskManualImportDialog.test.tsx src/app/supply-chain/management/clearance/ExternalOrderCostView.test.tsx src/app/supply-chain/management/clearance/ExternalOrderCostFeedback.test.tsx", "verify:clearance-task-import": "jest --runInBand src/lib/clearance-task-manual-import.test.ts src/server/services/__tests__/supply-chain-clearance-task-import.service.test.ts src/server/services/__tests__/supply-chain-clearance.service.test.ts src/app/supply-chain/management/clearance/ClearanceTaskManualImportDialog.test.tsx", + "verify:clearance-priority-auto-price": "jest --runInBand src/lib/clearance-priority-rules.test.ts src/server/services/__tests__/supply-chain-clearance-priority-config.service.test.ts src/app/supply-chain/management/clearance/ClearanceRuleEditor.test.tsx src/server/services/__tests__/supply-chain-clearance.service.test.ts src/server/services/__tests__/supply-chain-clearance-price-push.service.test.ts", "verify:clearance-price-push": "jest --runInBand src/server/services/__tests__/supply-chain-clearance-price-push.service.test.ts src/server/repositories/__tests__/supply-chain-clearance-price-push.repository.test.ts src/lib/clearance-price-push-manual-import.test.ts src/app/supply-chain/management/clearance/ClearancePricePushView.test.tsx src/app/supply-chain/management/clearance/ClearancePricePushFeedback.test.tsx src/app/supply-chain/management/clearance/ClearancePricePushBatchEditDialog.test.tsx", "test:watch": "jest --watch", "test:coverage": "jest --coverage", diff --git a/furniture-3d-system/src/app/api/supply-chain/clearance/priority-rules/route.ts b/furniture-3d-system/src/app/api/supply-chain/clearance/priority-rules/route.ts index a8b74344..5e2b6652 100644 --- a/furniture-3d-system/src/app/api/supply-chain/clearance/priority-rules/route.ts +++ b/furniture-3d-system/src/app/api/supply-chain/clearance/priority-rules/route.ts @@ -23,6 +23,8 @@ const ruleSchema = z.object({ priority: z.string().trim().min(1).max(50), taskType: z.enum(['fixed', 'normal', 'priority']), matchMode: z.enum(['ALL', 'ANY']).default('ALL'), + autoPricePushWithoutTask: z.boolean().default(false), + fixedClearanceDiscount: z.number().positive().max(1).nullable().optional(), conditions: z.array(z.object({ field: z.string().trim().min(1).max(80), operator: operatorSchema, diff --git a/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceRuleEditor.test.tsx b/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceRuleEditor.test.tsx index 554b750e..82dd1b7d 100644 --- a/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceRuleEditor.test.tsx +++ b/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceRuleEditor.test.tsx @@ -196,4 +196,70 @@ describe('ClearanceRuleEditor condition value controls', () => { expect(taskType).toHaveValue('fixed') }) + + it('saves optional automatic price push and fixed discount on a priority rule', async () => { + let savedBody: unknown + global.fetch = jest.fn((input, init) => { + const url = String(input) + if (url.includes('/api/supply-chain/clearance/options?')) { + return jsonResponse({ values: [] }) + } + if (init?.method === 'PUT') { + savedBody = JSON.parse(String(init.body)) + return jsonResponse({ + rules: [{ + id: 'rule-gd', + priority: '广东佛山', + taskType: 'normal', + matchMode: 'ALL', + autoPricePushWithoutTask: true, + fixedClearanceDiscount: 0.7, + conditions: [{ + field: 'priority', + operator: 'equals', + value: '广东佛山', + }], + }], + fallback: '', + updatedByName: '测试用户', + updatedAt: null, + }) + } + return jsonResponse({ + rules: [{ + id: 'rule-gd', + priority: '广东佛山', + taskType: 'normal', + matchMode: 'ALL', + autoPricePushWithoutTask: false, + conditions: [{ + field: 'priority', + operator: 'equals', + value: '广东佛山', + }], + }], + fallback: '', + updatedByName: '测试用户', + updatedAt: null, + }) + }) as jest.Mock + + render() + + expect(await screen.findByLabelText('规则 1 条件 1 字段')).toHaveValue('priority') + const checkbox = await screen.findByRole('checkbox') + fireEvent.click(checkbox) + expect(screen.getByLabelText('规则 1 固定清货折扣')).toHaveValue(7) + fireEvent.click(screen.getByRole('button', { name: '保存规则' })) + + await waitFor(() => { + expect(savedBody).toMatchObject({ + rules: [{ + priority: '广东佛山', + autoPricePushWithoutTask: true, + fixedClearanceDiscount: 0.7, + }], + }) + }) + }) }) diff --git a/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceRuleEditor.tsx b/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceRuleEditor.tsx index d3296ec6..1db6fafd 100644 --- a/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceRuleEditor.tsx +++ b/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceRuleEditor.tsx @@ -43,6 +43,8 @@ type EditableRule = { output: string taskType: ClearanceScoreTaskType matchMode: ClearanceRuleMatchMode + autoPricePushWithoutTask: boolean + fixedDiscount: string conditions: ClearancePriorityRuleCondition[] } type ConfigRuleResponse = { @@ -52,6 +54,8 @@ type ConfigRuleResponse = { fixedTaskQty?: number formula?: string matchMode?: ClearanceRuleMatchMode + autoPricePushWithoutTask?: boolean + fixedClearanceDiscount?: number conditions: ClearancePriorityRuleCondition[] } type RuleConfigResponse = { @@ -292,9 +296,7 @@ export function ClearanceRuleEditor({ kind }: { kind: RuleKind }) { const [saving, setSaving] = useState(false) const [message, setMessage] = useState('') const [error, setError] = useState('') - const availableFields = isFixedTask - ? CLEARANCE_PRIORITY_FIELDS - : CLEARANCE_PRIORITY_FIELDS.filter((field) => field.key !== 'priority') + const availableFields = CLEARANCE_PRIORITY_FIELDS const load = useCallback(async () => { setLoading(true) @@ -314,6 +316,10 @@ export function ClearanceRuleEditor({ kind }: { kind: RuleKind }) { ?? mappingByPriority.get(String(rule.priority ?? '').trim()) ?? suggestClearanceTaskType(String(rule.priority ?? '')), matchMode: rule.matchMode === 'ANY' ? 'ANY' : 'ALL', + autoPricePushWithoutTask: rule.autoPricePushWithoutTask === true, + fixedDiscount: rule.fixedClearanceDiscount == null + ? '' + : String(Number((rule.fixedClearanceDiscount * 10).toFixed(2))), conditions: rule.conditions, }))) const loadedFallback = isFixedTask ? data.fallbackFormula ?? '' : data.fallback ?? '' @@ -370,6 +376,8 @@ export function ClearanceRuleEditor({ kind }: { kind: RuleKind }) { output: '', taskType: 'priority', matchMode: 'ALL', + autoPricePushWithoutTask: false, + fixedDiscount: '', conditions: [newCondition()], }, ]) @@ -423,6 +431,15 @@ export function ClearanceRuleEditor({ kind }: { kind: RuleKind }) { : '请填写每条规则的优先级,并完整填写所有条件') return } + const invalidAutoPriceRule = !isFixedTask && rules.some((rule) => { + if (!rule.autoPricePushWithoutTask) return false + const discount = Number(rule.fixedDiscount) + return !Number.isFinite(discount) || discount <= 0 || discount > 10 + }) + if (invalidAutoPriceRule) { + setError('开启无任务自动推送时,请填写大于 0 且不超过 10 的固定折扣') + return + } if (isFixedTask && fallback.trim() && !validateClearanceFixedTaskFormula(fallback).valid) { setError('固定任务兜底公式格式不正确') return @@ -444,6 +461,10 @@ export function ClearanceRuleEditor({ kind }: { kind: RuleKind }) { priority: rule.output.trim(), taskType: rule.taskType, matchMode: rule.matchMode, + autoPricePushWithoutTask: rule.autoPricePushWithoutTask, + fixedClearanceDiscount: rule.autoPricePushWithoutTask + ? Number(rule.fixedDiscount) / 10 + : null, conditions: rule.conditions, } )) @@ -471,6 +492,10 @@ export function ClearanceRuleEditor({ kind }: { kind: RuleKind }) { ?? mappingByPriority.get(String(rule.priority ?? '').trim()) ?? suggestClearanceTaskType(String(rule.priority ?? '')), matchMode: rule.matchMode === 'ANY' ? 'ANY' : 'ALL', + autoPricePushWithoutTask: rule.autoPricePushWithoutTask === true, + fixedDiscount: rule.fixedClearanceDiscount == null + ? '' + : String(Number((rule.fixedClearanceDiscount * 10).toFixed(2))), conditions: rule.conditions, }))) const savedFallback = isFixedTask ? data.fallbackFormula ?? '' : data.fallback ?? '' @@ -576,6 +601,42 @@ export function ClearanceRuleEditor({ kind }: { kind: RuleKind }) { + {!isFixedTask && ( +
+ + + 仅补充没有任务价格和人工价格的商品 +
+ )} + {isFixedTask && (
diff --git a/furniture-3d-system/src/app/supply-chain/management/clearance/clearance.module.css b/furniture-3d-system/src/app/supply-chain/management/clearance/clearance.module.css index 4d7b13dd..29ce2655 100644 --- a/furniture-3d-system/src/app/supply-chain/management/clearance/clearance.module.css +++ b/furniture-3d-system/src/app/supply-chain/management/clearance/clearance.module.css @@ -22,6 +22,12 @@ content: ""; } +.dailyUpdateNote { + margin: 7px 0 0; + color: #697274; + font-size: 12px; +} + .statGrid { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); @@ -2108,6 +2114,46 @@ white-space: nowrap; } +.priorityAutoPriceConfig { + display: flex; + align-items: center; + gap: 16px; + flex-wrap: wrap; + margin: 0 18px 14px; + padding: 10px 12px; + border: 1px solid #dbe4ea; + border-radius: 8px; + background: #f7fafc; + color: #526065; + font-size: 12px; +} + +.priorityAutoPriceConfig label { + display: flex; + align-items: center; + gap: 7px; + font-weight: 600; +} + +.priorityAutoPriceConfig label:first-child { + color: #253238; +} + +.priorityAutoPriceConfig input[type="checkbox"] { + width: 15px; + height: 15px; + accent-color: #d0442f; +} + +.priorityAutoPriceConfig .priorityValueInput { + width: 74px; + height: 32px; +} + +.priorityAutoPriceConfig em { + font-style: normal; +} + .priorityTaskTypePicker .prioritySelect { width: 108px; } diff --git a/furniture-3d-system/src/lib/clearance-priority-rules.test.ts b/furniture-3d-system/src/lib/clearance-priority-rules.test.ts index 589a0a66..b020afb8 100644 --- a/furniture-3d-system/src/lib/clearance-priority-rules.test.ts +++ b/furniture-3d-system/src/lib/clearance-priority-rules.test.ts @@ -5,6 +5,7 @@ import { isClearancePriorityConditionValueComplete, normalizeClearanceFixedTaskRules, normalizeClearancePriorityRules, + resolveClearanceAutoPriceRule, resolveClearanceFixedTask, resolveClearancePriority, type ClearanceFixedTaskRule, @@ -329,4 +330,36 @@ describe('clearance priority rules', () => { }], }])).toEqual([]) }) + + it('resolves the optional automatic price push discount from a matching priority rule', () => { + const normalized = normalizeClearancePriorityRules([{ + id: 'gd-auto', + priority: '广东佛山', + taskType: 'normal', + autoPricePushWithoutTask: true, + fixedClearanceDiscount: 0.7, + conditions: [ + { field: 'priority', operator: 'equals', value: '广东佛山' }, + { field: 'salesStatus', operator: 'not_equals', value: '销售' }, + ], + }]) + + expect(normalized[0]).toMatchObject({ + autoPricePushWithoutTask: true, + fixedClearanceDiscount: 0.7, + }) + expect(resolveClearanceAutoPriceRule({ + salesStatus: '退市', + extra: { priority: '广东佛山' }, + }, normalized)).toEqual({ + ruleId: 'gd-auto', + ruleOrder: 1, + priority: '广东佛山', + discount: 0.7, + }) + expect(resolveClearanceAutoPriceRule({ + salesStatus: '销售', + extra: { priority: '广东佛山' }, + }, normalized)).toBeNull() + }) }) diff --git a/furniture-3d-system/src/lib/clearance-priority-rules.ts b/furniture-3d-system/src/lib/clearance-priority-rules.ts index 35a9e3e0..59dafdbe 100644 --- a/furniture-3d-system/src/lib/clearance-priority-rules.ts +++ b/furniture-3d-system/src/lib/clearance-priority-rules.ts @@ -28,6 +28,8 @@ export type ClearancePriorityRule = { priority: string taskType?: ClearanceScoreTaskType matchMode?: ClearanceRuleMatchMode + autoPricePushWithoutTask?: boolean + fixedClearanceDiscount?: number conditions: ClearancePriorityRuleCondition[] } @@ -568,6 +570,11 @@ export function normalizeClearancePriorityRules(value: unknown): ClearancePriori const conditions = normalizeConditions(source.conditions) if (!conditions.length) return [] const taskType = source.taskType + const fixedClearanceDiscount = normalizedNumber(source.fixedClearanceDiscount) + const autoPricePushWithoutTask = source.autoPricePushWithoutTask === true + && fixedClearanceDiscount != null + && fixedClearanceDiscount > 0 + && fixedClearanceDiscount <= 1 return [{ id: normalizeRuleId(source.id, 'priority-rule', ruleIndex, usedIds), priority, @@ -575,6 +582,12 @@ export function normalizeClearancePriorityRules(value: unknown): ClearancePriori ? { taskType } : {}), matchMode: source.matchMode === 'ANY' ? 'ANY' : 'ALL', + ...(autoPricePushWithoutTask + ? { + autoPricePushWithoutTask: true, + fixedClearanceDiscount: fixedClearanceDiscount!, + } + : {}), conditions, }] }) @@ -637,6 +650,31 @@ export function resolveClearancePriority( } } +export function resolveClearanceAutoPriceRule( + row: Record, + rules: readonly ClearancePriorityRule[], +) { + for (let index = 0; index < rules.length; index += 1) { + const rule = rules[index] + if ( + !rule.autoPricePushWithoutTask + || rule.fixedClearanceDiscount == null + || rule.fixedClearanceDiscount <= 0 + || rule.fixedClearanceDiscount > 1 + || !matchesRuleConditions(row, rule.conditions, rule.matchMode) + ) { + continue + } + return { + ruleId: rule.id, + ruleOrder: index + 1, + priority: rule.priority, + discount: rule.fixedClearanceDiscount, + } + } + return null +} + export function resolveClearanceFixedTask( row: Record, rules: readonly ClearanceFixedTaskRule[], diff --git a/furniture-3d-system/src/server/repositories/__tests__/supply-chain-clearance-auto-price.repository.test.ts b/furniture-3d-system/src/server/repositories/__tests__/supply-chain-clearance-auto-price.repository.test.ts new file mode 100644 index 00000000..42c59558 --- /dev/null +++ b/furniture-3d-system/src/server/repositories/__tests__/supply-chain-clearance-auto-price.repository.test.ts @@ -0,0 +1,39 @@ +/** @jest-environment node */ +const mockGenerationFindUnique = jest.fn() +const mockSnapshotFindFirst = jest.fn() +const mockSnapshotFindMany = jest.fn() + +jest.mock('@/lib/prisma', () => ({ + prisma: { + supplyChainClearancePoolGeneration: { + findUnique: (...args: unknown[]) => mockGenerationFindUnique(...args), + }, + supplyChainClearancePoolSnapshot: { + findFirst: (...args: unknown[]) => mockSnapshotFindFirst(...args), + findMany: (...args: unknown[]) => mockSnapshotFindMany(...args), + }, + }, +})) + +import { supplyChainClearanceRepository } from '../supply-chain-clearance.repository' + +describe('clearance automatic pricing repository query', () => { + beforeEach(() => { + jest.clearAllMocks() + mockGenerationFindUnique.mockResolvedValue({ + statDate: new Date('2026-11-13T00:00:00.000Z'), + }) + mockSnapshotFindFirst.mockResolvedValue(null) + mockSnapshotFindMany.mockResolvedValue([]) + }) + + it('selects business creation dates for date-based automatic pricing rules', async () => { + await supplyChainClearanceRepository.listPoolRowsForAutoPricePush('2026-11') + + expect(mockSnapshotFindMany).toHaveBeenCalledWith(expect.objectContaining({ + select: expect.objectContaining({ + businessCreatedAt: true, + }), + })) + }) +}) diff --git a/furniture-3d-system/src/server/repositories/supply-chain-clearance.repository.ts b/furniture-3d-system/src/server/repositories/supply-chain-clearance.repository.ts index 37b1206a..61a2706c 100644 --- a/furniture-3d-system/src/server/repositories/supply-chain-clearance.repository.ts +++ b/furniture-3d-system/src/server/repositories/supply-chain-clearance.repository.ts @@ -1004,6 +1004,48 @@ class SupplyChainClearanceRepository { })) } + async listPoolRowsForAutoPricePush(periodKey: string) { + const generation = await this.findPoolGeneration(periodKey) + const snapshot = generation ?? await prisma.supplyChainClearancePoolSnapshot.findFirst({ + where: { periodKey }, + orderBy: [{ statDate: 'desc' }, { statTime: 'desc' }], + select: { statDate: true }, + }) + if (!snapshot) return [] + return prisma.supplyChainClearancePoolSnapshot.findMany({ + where: { + periodKey, + statDate: snapshot.statDate, + totalStock: { gt: 0 }, + costPrice: { not: null }, + }, + select: { + barcode: true, + spu: true, + sku: true, + productName: true, + brand: true, + category: true, + productStatus: true, + salesStatus: true, + supplierName: true, + packType: true, + cooperationStatus: true, + ownerName: true, + department: true, + stockJianshang: true, + stockFactory: true, + totalStock: true, + dailySales: true, + availableDays: true, + costPrice: true, + businessCreatedAt: true, + extra: true, + }, + orderBy: [{ barcode: 'asc' }], + }) + } + async listPoolSkuFamilyStatuses(periodKey: string, skus: string[]) { const variants = Array.from(new Set( skus.flatMap((sku) => clearanceSkuFamilyVariants(sku)), diff --git a/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance-price-push.service.test.ts b/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance-price-push.service.test.ts index 7a76f8cd..5189a442 100644 --- a/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance-price-push.service.test.ts +++ b/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance-price-push.service.test.ts @@ -165,6 +165,62 @@ describe('supply chain clearance price push service', () => { ) }) + it('adds priority-rule automatic prices only when the product has no task price', async () => { + const repo = repository({ + replaceSnapshot: jest.fn().mockResolvedValue({ + id: 'snapshot-1', + generatedAt: new Date('2026-11-05T02:00:00.000Z'), + }), + }) + const taskReader = { + getTasks: jest.fn().mockResolvedValue({ + tasks: [{ + barcode: 'SKU-TASK', + clearanceCode: 'SKU-TASK', + costPrice: 100, + clearancePrice: 60, + round: 1, + submittedAt: '2026-10-31T00:00:00.000Z', + }], + }), + listAutoPricePushCandidates: jest.fn().mockResolvedValue([{ + productCode: 'SKU-TASK', + clearanceCode: 'SKU-TASK', + costPrice: 100, + discount: 0.7, + ruleId: 'gd-rule', + }, { + productCode: 'SKU-AUTO', + clearanceCode: 'SKU-AUTO', + costPrice: 100, + discount: 0.7, + ruleId: 'gd-rule', + }]), + } + const service = new SupplyChainClearancePricePushService(repo, taskReader as never) + + await service.generate({ + periodKey: '2026-11', + user, + }) + + expect(repo.replaceSnapshot).toHaveBeenCalledWith(expect.objectContaining({ + items: expect.arrayContaining([ + expect.objectContaining({ + productCode: 'SKU-TASK', + historicalCostPrice: 60, + }), + expect.objectContaining({ + productCode: 'SKU-AUTO', + historicalCostPrice: 70, + }), + ]), + })) + const items = repo.replaceSnapshot.mock.calls[0][0].items + expect(items.filter((item) => item.productCode === 'SKU-TASK')).toHaveLength(1) + expect(items.filter((item) => item.productCode === 'SKU-AUTO')).toHaveLength(1) + }) + it('uses the second-round task price and lets same-date manual data override it', async () => { const repo = repository({ listProductCodesByClearanceCodes: jest.fn().mockResolvedValue([ diff --git a/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance-priority-config.service.test.ts b/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance-priority-config.service.test.ts index ce7d11a4..40f3dbb7 100644 --- a/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance-priority-config.service.test.ts +++ b/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance-priority-config.service.test.ts @@ -219,6 +219,24 @@ describe('clearance priority config service', () => { expect(repository.savePriorityRules).not.toHaveBeenCalled() }) + it('requires a valid fixed discount when automatic price push is enabled', async () => { + await expect(supplyChainClearancePriorityConfigService.saveConfig({ + user, + rules: [{ + id: 'gd-auto', + priority: '广东佛山', + taskType: 'normal', + matchMode: 'ALL', + autoPricePushWithoutTask: true, + fixedClearanceDiscount: 0, + conditions: [{ field: 'priority', operator: 'equals', value: '广东佛山' }], + }], + fallback: '', + fallbackTaskType: 'priority', + })).rejects.toThrow('固定清货折扣必须大于 0 且不超过 10 折') + expect(repository.savePriorityRules).not.toHaveBeenCalled() + }) + it('rejects conflicting task types for the same priority', async () => { await expect(supplyChainClearancePriorityConfigService.saveConfig({ user, diff --git a/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance-task-import.service.test.ts b/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance-task-import.service.test.ts index 2587ee2e..01ed1360 100644 --- a/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance-task-import.service.test.ts +++ b/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance-task-import.service.test.ts @@ -1,6 +1,9 @@ import ExcelJS from 'exceljs' import type { AuthUser } from '@/server/core/types' -import { CLEARANCE_TASK_IMPORT_HEADERS } from '@/lib/clearance-task-manual-import' +import { + CLEARANCE_TASK_IMPORT_HEADERS, + CLEARANCE_TASK_IMPORT_TEMPLATE_HEADERS, +} from '@/lib/clearance-task-manual-import' import { SupplyChainClearanceTaskImportService } from '../supply-chain-clearance-task-import.service' const user = { @@ -13,7 +16,7 @@ const user = { async function workbookBuffer(rows: unknown[][]) { const workbook = new ExcelJS.Workbook() const worksheet = workbook.addWorksheet('清货任务') - worksheet.addRow([...CLEARANCE_TASK_IMPORT_HEADERS]) + worksheet.addRow([...CLEARANCE_TASK_IMPORT_TEMPLATE_HEADERS]) for (const row of rows) worksheet.addRow(row) return Buffer.from(await workbook.xlsx.writeBuffer()) } @@ -75,7 +78,7 @@ describe('SupplyChainClearanceTaskImportService', () => { user, buffer: await workbookBuffer([ ['2026-11', 'sku-a', 60, 200, '运营中心A', '运营新', '部门新'], - ['2026-11', 'SKU-B', '', 30, '运营中心G', '运营G', '部门G'], + ['2026-11', 'SKU-B', '', 30, '运营中心G', '运营G', '部门G', '广东佛山'], ]), })).resolves.toEqual({ periodKey: '2026-11', @@ -109,6 +112,7 @@ describe('SupplyChainClearanceTaskImportService', () => { discount: '1.00', status: 'APPROVED', submittedById: user.id, + priorityOverride: '广东佛山', }, }) expect(syncPricePush).toHaveBeenCalledWith('2026-11') diff --git a/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance.service.test.ts b/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance.service.test.ts index 85854e2c..798d142d 100644 --- a/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance.service.test.ts +++ b/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance.service.test.ts @@ -9,6 +9,7 @@ import { discountLabel, netClearanceJianshangStock, previousPeriodKey, + resolveClearancePriorityForGeneration, resolveClearancePriorityWithManualOverride, resolveClearanceWorkingPeriod, shouldExcludeClearanceProduct, @@ -67,6 +68,7 @@ jest.mock('@/server/repositories/supply-chain-clearance.repository', () => ({ findPoolImagesByBarcodes: jest.fn(), findPoolItemsByBarcodes: jest.fn(), listPoolItemsForTaskPeriod: jest.fn(), + listPoolRowsForAutoPricePush: jest.fn(), listPoolSkuFamilyStatuses: jest.fn(), listProductArchiveTaskValuesByBarcodes: jest.fn(), findRepresentativePoolImagesByOwners: jest.fn(), @@ -246,6 +248,37 @@ describe('supply-chain-clearance helpers', () => { }) }) + it('uses the manual backup priority for 2026-11 and configured rules from 2026-12', () => { + expect(resolveClearancePriorityForGeneration({ + periodKey: '2026-11', + manualPriorityBackupExtra: { priority: '广东佛山' }, + systemPriority: 'A 固定任务', + fallbackPriority: '普通清货', + })).toEqual({ + priority: '广东佛山', + manual: true, + }) + expect(resolveClearancePriorityForGeneration({ + periodKey: '2026-11', + manualPriorityBackupExtra: {}, + systemPriority: 'A 固定任务', + fallbackPriority: '普通清货', + })).toEqual({ + priority: '', + manual: false, + }) + expect(resolveClearancePriorityForGeneration({ + periodKey: '2026-12', + manualPriorityBackupExtra: { priority: '广东佛山' }, + previousExtra: { priority: '上月人工优先级', priorityManual: true }, + systemPriority: 'A 固定任务', + fallbackPriority: '普通清货', + })).toEqual({ + priority: 'A 固定任务', + manual: false, + }) + }) + it('excludes blank categories, welfare products and the configured barcode', () => { expect(shouldExcludeClearanceProduct({ barcode: 'SKU001', @@ -412,6 +445,7 @@ describe('supply-chain-clearance workflow', () => { repository.supplementPoolRowsForRefresh.mockResolvedValue([]) repository.updatePoolDailyMetrics.mockResolvedValue(0) repository.listPoolFilterOptions.mockResolvedValue([]) + repository.listPoolRowsForAutoPricePush.mockResolvedValue([]) repository.poolOverview.mockResolvedValue({ stockJianshang: 0, clearanceBarcodeCount: 0, @@ -922,6 +956,14 @@ describe('supply-chain-clearance workflow', () => { createdAt: new Date(), updatedAt: new Date(), } as never) + repository.listPoolRowsForBatchCarry.mockImplementation(async (periodKey) => ( + periodKey === '2026-11' + ? [{ + barcode: 'SKU001', + extra: { priority: 'A 固定任务' }, + }] as never + : [] + )) const result = await supplyChainClearanceService.generatePool({ periodKey: '2026-11', @@ -981,9 +1023,9 @@ describe('supply-chain-clearance workflow', () => { suggestedDiscount: 1, reviewScoreVersion: '2026-11-v2', priority: 'A 固定任务', - priorityManual: false, - priorityRuleId: 'priority-a', - priorityRuleOrder: 1, + priorityManual: true, + priorityRuleId: 'manual', + priorityRuleOrder: null, fixedTaskQty: 60, fixedTaskFormula: '总库存/2', fixedTaskRuleId: 'fixed-a', @@ -2403,6 +2445,216 @@ describe('supply-chain-clearance workflow', () => { }) }) + it('includes configured priorities in the priority filter even before they appear in pool rows', async () => { + repository.findClearanceConfig.mockResolvedValue({ + priorityRules: [{ + id: 'gd-rule', + priority: '广东佛山', + taskType: 'normal', + conditions: [{ field: 'priority', operator: 'equals', value: '广东佛山' }], + }], + priorityFallback: '普通清货', + priorityTaskTypes: [], + } as never) + repository.listPoolFilterOptions.mockResolvedValue(['库存积压']) + + const result = await supplyChainClearanceService.getPoolFilterOptions({ + field: 'priority', + query: '', + limit: 200, + }) + + expect(result.values).toEqual(expect.arrayContaining(['广东佛山', '普通清货', '库存积压'])) + }) + + it('builds automatic price candidates from enabled priority rules', async () => { + repository.findClearanceConfig.mockResolvedValue({ + priorityRules: [{ + id: 'gd-rule', + priority: '广东佛山', + taskType: 'normal', + autoPricePushWithoutTask: true, + fixedClearanceDiscount: 0.7, + conditions: [{ field: 'priority', operator: 'equals', value: '广东佛山' }], + }], + } as never) + repository.listPoolRowsForAutoPricePush.mockResolvedValue([ + { + barcode: 'SKU-GD', + costPrice: '100.000', + extra: { priority: '广东佛山', clearanceCode: 'SKU-GD' }, + }, + { + barcode: 'SKU-OTHER', + costPrice: '80.000', + extra: { priority: '库存积压', clearanceCode: 'SKU-OTHER' }, + }, + ] as never) + + await expect(supplyChainClearanceService.listAutoPricePushCandidates('2026-11')) + .resolves.toEqual([{ + productCode: 'SKU-GD', + clearanceCode: 'SKU-GD', + costPrice: 100, + discount: 0.7, + ruleId: 'gd-rule', + }]) + }) + + it('skips automatic pricing for every prohibited discount scenario', async () => { + repository.findClearanceConfig.mockResolvedValue({ + priorityRules: [{ + id: 'gd-rule', + priority: '广东佛山', + taskType: 'normal', + autoPricePushWithoutTask: true, + fixedClearanceDiscount: 0.7, + conditions: [{ field: 'priority', operator: 'equals', value: '广东佛山' }], + }], + discountRestrictions: [{ type: 'barcode', value: 'SKU-RESTRICTED' }], + } as never) + repository.listPoolRowsForAutoPricePush.mockResolvedValue([ + { + barcode: 'SKU-SALES', + sku: 'SKU-SALES', + productStatus: '销售', + salesStatus: '销售', + stockJianshang: 10, + costPrice: '100', + extra: { priority: '广东佛山' }, + }, + { + barcode: 'SKU-FAMILY', + sku: 'FAMILY', + productStatus: '退市', + salesStatus: '退市', + stockJianshang: 10, + costPrice: '100', + extra: { priority: '广东佛山' }, + }, + { + barcode: 'SKU-RESTRICTED', + sku: 'SKU-RESTRICTED', + productStatus: '退市', + salesStatus: '退市', + stockJianshang: 10, + costPrice: '100', + extra: { priority: '广东佛山' }, + }, + { + barcode: 'SKU-DROPSHIP', + sku: 'SKU-DROPSHIP', + productStatus: '退市', + salesStatus: '退市', + stockJianshang: 0, + costPrice: '100', + extra: { priority: '广东佛山', dropshipStock: 10 }, + }, + { + barcode: 'SKU-VALID', + sku: 'SKU-VALID', + productStatus: '退市', + salesStatus: '退市', + stockJianshang: 10, + costPrice: '100', + extra: { priority: '广东佛山', dropshipStock: 0 }, + }, + ] as never) + repository.listPoolSkuFamilyStatuses.mockResolvedValue([{ + sku: 'FAMILY', + productStatus: '销售', + salesStatus: '销售', + }]) + + await expect(supplyChainClearanceService.listAutoPricePushCandidates('2026-11')) + .resolves.toEqual([expect.objectContaining({ + productCode: 'SKU-VALID', + discount: 0.7, + })]) + }) + + it('passes business creation dates into automatic pricing rules', async () => { + repository.findClearanceConfig.mockResolvedValue({ + priorityRules: [{ + id: 'created-rule', + priority: '新入库', + taskType: 'normal', + autoPricePushWithoutTask: true, + fixedClearanceDiscount: 0.8, + conditions: [{ + field: 'businessCreatedAt', + operator: 'gte', + value: '2026-11-01', + }], + }], + } as never) + repository.listPoolRowsForAutoPricePush.mockResolvedValue([ + { + barcode: 'SKU-NEW', + sku: 'SKU-NEW', + productStatus: '退市', + salesStatus: '退市', + stockJianshang: 10, + costPrice: '100', + businessCreatedAt: new Date('2026-11-02T00:00:00.000Z'), + extra: {}, + }, + { + barcode: 'SKU-OLD', + sku: 'SKU-OLD', + productStatus: '退市', + salesStatus: '退市', + stockJianshang: 10, + costPrice: '100', + businessCreatedAt: new Date('2026-10-02T00:00:00.000Z'), + extra: {}, + }, + ] as never) + + await expect(supplyChainClearanceService.listAutoPricePushCandidates('2026-11')) + .resolves.toEqual([expect.objectContaining({ + productCode: 'SKU-NEW', + ruleId: 'created-rule', + })]) + }) + + it('recomputes discontinued days before evaluating automatic pricing rules', async () => { + repository.findClearanceConfig.mockResolvedValue({ + priorityRules: [{ + id: 'discontinued-rule', + priority: '长期停产', + taskType: 'normal', + autoPricePushWithoutTask: true, + fixedClearanceDiscount: 0.6, + conditions: [{ + field: 'discontinuedDays', + operator: 'gte', + value: '10', + }], + }], + } as never) + repository.listPoolRowsForAutoPricePush.mockResolvedValue([{ + barcode: 'SKU-STOPPED', + sku: 'SKU-STOPPED', + productStatus: '停产', + salesStatus: '停产', + stockJianshang: 10, + costPrice: '100', + extra: { + discontinuedAt: '2026-11-01', + discontinuedDays: 1, + }, + }] as never) + + await expect(supplyChainClearanceService.listAutoPricePushCandidates( + '2026-11', + new Date('2026-11-13T01:00:00.000Z'), + )).resolves.toEqual([expect.objectContaining({ + productCode: 'SKU-STOPPED', + ruleId: 'discontinued-rule', + })]) + }) + it('blocks inline drafts outside the confirmed application window', async () => { repository.findApplicationWindows.mockResolvedValue([{ ...openWindow, diff --git a/furniture-3d-system/src/server/services/supply-chain-clearance-price-push.service.ts b/furniture-3d-system/src/server/services/supply-chain-clearance-price-push.service.ts index 1e7ce97b..10f32bf5 100644 --- a/furniture-3d-system/src/server/services/supply-chain-clearance-price-push.service.ts +++ b/furniture-3d-system/src/server/services/supply-chain-clearance-price-push.service.ts @@ -32,6 +32,7 @@ type PricePushRepository = Pick< > type ClearanceTaskReader = Pick + & Partial> function number(value: unknown) { if (value == null || value === '') return null @@ -39,6 +40,10 @@ function number(value: unknown) { return Number.isFinite(parsed) ? parsed : null } +function round(value: number, digits: number) { + return Number(value.toFixed(digits)) +} + function dateOnlyKey(value: Date) { const year = value.getFullYear() const month = String(value.getMonth() + 1).padStart(2, '0') @@ -406,9 +411,14 @@ export class SupplyChainClearancePricePushService { const startDateKey = `${periodKey}-01` const startDate = new Date(`${startDateKey}T00:00:00.000Z`) - const taskResult = await this.taskReader.getTasks(periodKey, { - includeFreight: false, - }) + const [taskResult, autoPriceCandidates] = await Promise.all([ + this.taskReader.getTasks(periodKey, { + includeFreight: false, + }), + this.taskReader.listAutoPricePushCandidates + ? this.taskReader.listAutoPricePushCandidates(periodKey) + : Promise.resolve([]), + ]) const taskByClearanceCode = new Map() const fallbackProductCodes = new Set() + const taskCodes = new Set(taskResult.tasks.flatMap((task) => [ + String(task.barcode ?? '').trim().toUpperCase(), + String(task.clearanceCode ?? '').trim().toUpperCase(), + ].filter(Boolean))) + for (const candidate of autoPriceCandidates) { + if ( + taskCodes.has(candidate.productCode.trim().toUpperCase()) + || taskCodes.has(candidate.clearanceCode.trim().toUpperCase()) + ) { + continue + } + itemByCodeAndDate.set(itemKey(candidate.productCode, startDate), { + productCode: candidate.productCode, + costPrice: candidate.costPrice, + startDate, + historicalCostPrice: round(candidate.costPrice * candidate.discount, 3), + shopId: '', + shopName: '', + profitCenter: '', + }) + } for (const task of taskByClearanceCode.values()) { const mappedProductCodes = productCodesByClearanceCode.get( task.clearanceCode.toUpperCase(), diff --git a/furniture-3d-system/src/server/services/supply-chain-clearance-priority-config.service.ts b/furniture-3d-system/src/server/services/supply-chain-clearance-priority-config.service.ts index 00b25c78..b62e0dba 100644 --- a/furniture-3d-system/src/server/services/supply-chain-clearance-priority-config.service.ts +++ b/furniture-3d-system/src/server/services/supply-chain-clearance-priority-config.service.ts @@ -74,6 +74,19 @@ class SupplyChainClearancePriorityConfigService { '优先级规则不完整,请为每条规则填写优先级,并完整填写所有条件', ) } + const invalidAutoPriceRule = inputRules.some((item) => { + if (!item || typeof item !== 'object' || Array.isArray(item)) return false + const source = item as Record + if (source.autoPricePushWithoutTask !== true) return false + const discount = Number(source.fixedClearanceDiscount) + return !Number.isFinite(discount) || discount <= 0 || discount > 1 + }) + if (invalidAutoPriceRule) { + throw new AppError( + ErrorCode.VALIDATION_INVALID_FORMAT, + '开启无任务自动推送时,固定清货折扣必须大于 0 且不超过 10 折', + ) + } if (rules.some((rule) => !rule.taskType)) { throw new AppError( ErrorCode.VALIDATION_REQUIRED_FIELD, diff --git a/furniture-3d-system/src/server/services/supply-chain-clearance.service.ts b/furniture-3d-system/src/server/services/supply-chain-clearance.service.ts index 28e0cee7..3aeca6a4 100644 --- a/furniture-3d-system/src/server/services/supply-chain-clearance.service.ts +++ b/furniture-3d-system/src/server/services/supply-chain-clearance.service.ts @@ -11,6 +11,7 @@ import { evaluateClearanceFixedTaskFormula, normalizeClearanceFixedTaskRules, normalizeClearancePriorityRules, + resolveClearanceAutoPriceRule, resolveClearanceFixedTask, resolveClearancePriority, } from '@/lib/clearance-priority-rules' @@ -97,6 +98,7 @@ const clearanceComboIndexCache = new Map | null + previousExtra?: Record | null + systemPriority: string + fallbackPriority?: string +}) { + if (input.periodKey <= MANUAL_PRIORITY_BACKUP_CUTOFF_PERIOD) { + const priority = String(input.manualPriorityBackupExtra?.priority ?? '').trim() + return { priority, manual: Boolean(priority) } + } + return resolveClearancePriorityWithManualOverride({ + previousExtra: null, + systemPriority: input.systemPriority, + fallbackPriority: input.fallbackPriority, + }) +} + type RepositoryPoolGeneration = NonNullable< Awaited> > @@ -701,23 +721,31 @@ function effectiveClearanceSalesStatus(...values: Array, + restrictions: ReturnType, + discount: number, + allowFixedTaskDiscount = false, +) { + if (discount >= 0.995 || allowFixedTaskDiscount) return '' + if ( + integer(item.stockJianshang) <= 0 + && integer(poolExtra(item).dropshipStock) > 0 + ) { + return '简尚总库存为0且库存仅在代发仓,不允许申请折扣' + } + const restriction = matchingClearanceDiscountRestriction(item, restrictions) + if (!restriction) return '' + return '该商品已命中禁止申请折扣的限制规则,请将折扣留空' +} + function assertDiscountRestrictionAllowed( item: Record, restrictions: ReturnType, discount: number, allowFixedTaskDiscount = false, ) { - if (discount >= 0.995) return - if (allowFixedTaskDiscount) return - if ( - integer(item.stockJianshang) <= 0 - && integer(poolExtra(item).dropshipStock) > 0 - ) { - throw new AppError( - ErrorCode.VALIDATION_INVALID_FORMAT, - '简尚总库存为0且库存仅在代发仓,不允许申请折扣', - ) - } - const restriction = matchingClearanceDiscountRestriction(item, restrictions) - if (!restriction) return - throw new AppError( - ErrorCode.VALIDATION_INVALID_FORMAT, - '该商品已命中禁止申请折扣的限制规则,请将折扣留空', + const message = discountRestrictionError( + item, + restrictions, + discount, + allowFixedTaskDiscount, ) + if (message) throw new AppError(ErrorCode.VALIDATION_INVALID_FORMAT, message) } function clearanceReviewOutcome(task: { @@ -965,6 +1001,17 @@ class SupplyChainClearanceService { row.barcode.trim().toUpperCase(), row, ])) + const currentPeriodPriorityBackupRows = periodKey <= MANUAL_PRIORITY_BACKUP_CUTOFF_PERIOD + ? mode === 'ROUND2_REFRESH' + ? poolRows + : await supplyChainClearanceRepository.listPoolRowsForBatchCarry(periodKey) + : [] + const currentPeriodPriorityBackupByBarcode = new Map( + currentPeriodPriorityBackupRows.map((row) => [ + row.barcode.trim().toUpperCase(), + row, + ] as const), + ) const nextBatchNumber = nextClearanceBatchNumber(previousBatchRows.map((row) => ( row.extra && typeof row.extra === 'object' && !Array.isArray(row.extra) ? (row.extra as Record).clearanceBatch @@ -1283,10 +1330,18 @@ class SupplyChainClearanceService { availableDays, costPrice: number(row.costPrice), businessCreatedAt: row.businessCreatedAt, - extra, + extra: { + ...extra, + priority: String(previousExtra.priority ?? '').trim(), + }, } const priorityMatch = resolveClearancePriority(ruleSubject, priorityRules) - const resolvedPriority = resolveClearancePriorityWithManualOverride({ + const manualPriorityBackup = poolExtra( + currentPeriodPriorityBackupByBarcode.get(barcode) ?? {}, + ) + const resolvedPriority = resolveClearancePriorityForGeneration({ + periodKey, + manualPriorityBackupExtra: manualPriorityBackup, previousExtra, systemPriority: priorityMatch.priority, fallbackPriority: priorityFallback, @@ -2014,14 +2069,107 @@ class SupplyChainClearanceService { )).slice(0, limit) return { values } } - const values = await supplyChainClearanceRepository.listPoolFilterOptions({ + const priorityConfig = field === 'priority' + ? await supplyChainClearanceRepository.findClearanceConfig() + : null + const priorityValues = field === 'priority' + ? Array.from(new Set([ + ...normalizeClearancePriorityRules(priorityConfig?.priorityRules) + .map((rule) => rule.priority.trim()), + priorityConfig?.priorityFallback.trim() ?? '', + ].filter(Boolean))) + : [] + const repositoryValues = await supplyChainClearanceRepository.listPoolFilterOptions({ key: field, query: input.query?.trim().slice(0, 300) ?? '', limit: input.limit ?? 200, }) + if (field !== 'priority') return { values: repositoryValues } + const query = input.query?.trim().toLowerCase() ?? '' + const limit = Math.min(500, Math.max(1, Math.floor(input.limit ?? 200))) + const values = Array.from(new Set([...priorityValues, ...repositoryValues])) + .filter((value) => !query || value.toLowerCase().includes(query)) + .sort((left, right) => left.localeCompare(right, 'zh-Hans-CN', { numeric: true })) + .slice(0, limit) return { values } } + async listAutoPricePushCandidates(periodKeyInput: string, currentAt = new Date()) { + const periodKey = normalizePeriodKey(periodKeyInput) + const [config, rows] = await Promise.all([ + supplyChainClearanceRepository.findClearanceConfig(), + supplyChainClearanceRepository.listPoolRowsForAutoPricePush(periodKey), + ]) + const rules = normalizeClearancePriorityRules(config?.priorityRules) + .filter((rule) => rule.autoPricePushWithoutTask) + if (!rules.length) return [] + const discountRestrictions = normalizeClearanceDiscountRestrictions( + config?.discountRestrictions, + ) + const skuFamilySalesKeys = clearanceSkuFamilySalesKeySet( + await supplyChainClearanceRepository.listPoolSkuFamilyStatuses( + periodKey, + rows.map((row) => row.sku).filter(Boolean), + ), + ) + const candidates = new Map() + for (const row of rows) { + const extra = { ...poolExtra(row) } + const discontinuedDays = clearanceDiscontinuedDays( + String(extra.discontinuedAt ?? ''), + currentAt, + ) + if (discontinuedDays == null) delete extra.discontinuedDays + else extra.discontinuedDays = discontinuedDays + const ruleRow = { + ...row, + extra, + } as unknown as Record + const match = resolveClearanceAutoPriceRule( + ruleRow, + rules, + ) + const costPrice = number(row.costPrice) + const productCode = row.barcode.trim().toUpperCase() + if (!match || costPrice == null || costPrice <= 0 || !productCode) continue + const skuFamilyHasSalesStatus = Boolean( + row.sku + && skuFamilySalesKeys.has(clearanceSkuFamilyKey(row.sku)), + ) + if ( + salesStatusDiscountError( + effectiveClearanceSalesStatus(row.salesStatus, row.productStatus), + match.discount, + skuFamilyHasSalesStatus, + ) + || discountRestrictionError( + ruleRow, + discountRestrictions, + match.discount, + ) + ) continue + const clearanceCode = String(extra.clearanceCode ?? '').trim().toUpperCase() + || productCode + const current = candidates.get(productCode) + if (!current || costPrice < current.costPrice) { + candidates.set(productCode, { + productCode, + clearanceCode, + costPrice, + discount: match.discount, + ruleId: match.ruleId, + }) + } + } + return Array.from(candidates.values()) + } + private async poolSkuFamilyHasSalesStatus(periodKey: string, sku: string) { const rows = await supplyChainClearanceRepository.listPoolSkuFamilyStatuses( periodKey, From 90f96e17c41e1dbea7dcabcd95405231fa8971dc Mon Sep 17 00:00:00 2001 From: WuYongJie Date: Mon, 16 Nov 2026 10:42:34 +0800 Subject: [PATCH 2/4] fix(diy): support scene retries, annotation review and selected replacements Allow one current image and one retry candidate per slot, with explicit selection. Keep saved scene references and editable feedback for regeneration and annotation. Improve outer-edge placement, 16px offsets and terminal task recovery. Exclude XG0268 and unrelated registered changes. --- .../diy/ai-renders/[id]/regenerate/route.ts | 13 +++ .../api/diy/ai-renders/[id]/versions/route.ts | 13 +++ .../diy/components/DiyAiProcessingResults.tsx | 30 +++-- .../app/diy/components/DiyAiResultCard.tsx | 24 +++- .../diy/components/DiyImageVersions.test.tsx | 60 ++++++++++ .../app/diy/components/DiyImageVersions.tsx | 45 ++++++++ .../components/DiySkuImageActions.test.tsx | 49 +++++++++ .../app/diy/components/DiySkuImageActions.tsx | 45 ++++++++ .../app/diy/components/DiySkuRetryDialog.tsx | 29 +++++ .../batch/DiyBatchProcessingRecord.test.tsx | 21 +++- .../batch/DiyBatchProcessingRecord.tsx | 23 ++-- .../components/batch/DiyBatchRecord.test.tsx | 26 ++++- .../diy/components/batch/DiyBatchRecord.tsx | 25 ++++- .../components/batch/DiyBatchResults.test.tsx | 15 +++ .../diy/components/batch/DiyBatchResults.tsx | 5 +- .../app/diy/hooks/useDiyReprocessing.test.tsx | 29 +++++ .../src/app/diy/hooks/useDiyReprocessing.ts | 25 +++-- furniture-3d-system/src/app/diy/lib/ai-api.ts | 10 +- .../src/app/diy/lib/failure-guidance.test.ts | 15 +++ .../src/app/diy/lib/failure-guidance.ts | 20 +++- .../src/lib/diy/door-appearance.ts | 3 +- .../src/lib/diy/image-versions.test.ts | 25 +++++ .../src/lib/diy/image-versions.ts | 39 +++++++ .../src/lib/diy/negative-prompt.ts | 7 ++ .../src/lib/diy/render-processing.ts | 27 ++++- .../lib/diy/sku/annotation-placement.test.ts | 45 +++++++- .../src/lib/diy/sku/annotation-placement.ts | 57 +++++----- .../lib/diy/sku/annotation-scene-view.test.ts | 24 +++- .../src/lib/diy/sku/annotation-scene-view.ts | 7 +- .../src/lib/diy/sku/annotation-visibility.ts | 27 +++++ .../src/lib/diy/sku/retry-review.ts | 31 ++++++ .../src/lib/diy/sku/scene-layout.ts | 2 +- .../diy-image-version.repository.test.ts | 63 +++++++++++ .../__tests__/diy-render-guard.test.ts | 7 ++ ...diy-render-regeneration.repository.test.ts | 35 ++++++ ...diy-render-reprocessing.repository.test.ts | 67 ++++++++++- .../diy-image-version.repository.ts | 40 +++++++ .../server/repositories/diy-render-guard.ts | 4 +- .../diy-render-regeneration.repository.ts | 44 ++++++++ .../diy-render-reprocessing.repository.ts | 39 +++++-- .../__tests__/diy-ai-batch.service.test.ts | 11 ++ .../__tests__/diy-ai-render.service.test.ts | 33 ++++++ .../__tests__/diy-ai-render.storage.test.ts | 20 ++++ .../diy-image-version-processing.test.ts | 104 ++++++++++++++++++ .../__tests__/diy-render-processing.test.ts | 32 ++++++ .../__tests__/diy-render-regeneration.test.ts | 82 ++++++++++++++ .../__tests__/diy-scene-outer-edge.test.ts | 17 ++- .../services/__tests__/diy-sku-image.test.ts | 10 ++ .../services/__tests__/diy-sku-render.test.ts | 6 + .../__tests__/diy-sku-retry-review.test.ts | 75 +++++++++++++ .../__tests__/diy-sku-review-vision.test.ts | 35 ++++++ .../__tests__/diy-sku-scene-image.test.ts | 43 +++++++- .../__tests__/diy-sku-scene-location.test.ts | 40 +++++++ .../server/services/diy-ai-batch.service.ts | 10 +- .../server/services/diy-ai-render.create.ts | 8 +- .../server/services/diy-ai-render.service.ts | 9 +- .../server/services/diy-ai-render.storage.ts | 17 ++- .../server/services/diy-batch-scene-lock.ts | 3 +- .../services/diy-image-version-processing.ts | 70 ++++++++++++ .../services/diy-image-version.service.ts | 14 +++ .../diy-render-negative-prompt.test.ts | 27 +++++ .../services/diy-render-negative-prompt.ts | 17 +++ .../server/services/diy-render-processing.ts | 15 ++- .../diy-render-regeneration-completion.ts | 24 ++++ .../diy-render-regeneration.service.ts | 58 ++++++++++ .../diy-render-reprocessing.service.ts | 2 +- .../services/diy-scene-placement-prompt.ts | 5 +- .../services/diy-scene-reference-prompt.ts | 2 +- .../services/diy-sku-edge-refinement.ts | 14 ++- .../src/server/services/diy-sku-image.ts | 32 ++++-- .../src/server/services/diy-sku-prompt.ts | 8 +- .../server/services/diy-sku-retry-review.ts | 49 +++++++++ .../server/services/diy-sku-review-crops.ts | 20 ++++ .../server/services/diy-sku-review-vision.ts | 38 +++++++ .../server/services/diy-sku-scene-image.ts | 24 +++- .../server/services/diy-sku-scene-location.ts | 52 ++++++++- .../server/services/diy-sku-scene-prompt.ts | 2 + .../services/native-image-generation.types.ts | 2 +- .../native-render-completion.service.ts | 10 +- 79 files changed, 2006 insertions(+), 149 deletions(-) create mode 100644 furniture-3d-system/src/app/api/diy/ai-renders/[id]/regenerate/route.ts create mode 100644 furniture-3d-system/src/app/api/diy/ai-renders/[id]/versions/route.ts create mode 100644 furniture-3d-system/src/app/diy/components/DiyImageVersions.test.tsx create mode 100644 furniture-3d-system/src/app/diy/components/DiyImageVersions.tsx create mode 100644 furniture-3d-system/src/app/diy/components/DiySkuImageActions.test.tsx create mode 100644 furniture-3d-system/src/app/diy/components/DiySkuImageActions.tsx create mode 100644 furniture-3d-system/src/app/diy/components/DiySkuRetryDialog.tsx create mode 100644 furniture-3d-system/src/app/diy/hooks/useDiyReprocessing.test.tsx create mode 100644 furniture-3d-system/src/lib/diy/image-versions.test.ts create mode 100644 furniture-3d-system/src/lib/diy/image-versions.ts create mode 100644 furniture-3d-system/src/lib/diy/negative-prompt.ts create mode 100644 furniture-3d-system/src/lib/diy/sku/annotation-visibility.ts create mode 100644 furniture-3d-system/src/lib/diy/sku/retry-review.ts create mode 100644 furniture-3d-system/src/server/repositories/__tests__/diy-image-version.repository.test.ts create mode 100644 furniture-3d-system/src/server/repositories/__tests__/diy-render-regeneration.repository.test.ts create mode 100644 furniture-3d-system/src/server/repositories/diy-image-version.repository.ts create mode 100644 furniture-3d-system/src/server/repositories/diy-render-regeneration.repository.ts create mode 100644 furniture-3d-system/src/server/services/__tests__/diy-ai-render.storage.test.ts create mode 100644 furniture-3d-system/src/server/services/__tests__/diy-image-version-processing.test.ts create mode 100644 furniture-3d-system/src/server/services/__tests__/diy-render-regeneration.test.ts create mode 100644 furniture-3d-system/src/server/services/__tests__/diy-sku-retry-review.test.ts create mode 100644 furniture-3d-system/src/server/services/__tests__/diy-sku-review-vision.test.ts create mode 100644 furniture-3d-system/src/server/services/__tests__/diy-sku-scene-location.test.ts create mode 100644 furniture-3d-system/src/server/services/diy-image-version-processing.ts create mode 100644 furniture-3d-system/src/server/services/diy-image-version.service.ts create mode 100644 furniture-3d-system/src/server/services/diy-render-negative-prompt.test.ts create mode 100644 furniture-3d-system/src/server/services/diy-render-negative-prompt.ts create mode 100644 furniture-3d-system/src/server/services/diy-render-regeneration-completion.ts create mode 100644 furniture-3d-system/src/server/services/diy-render-regeneration.service.ts create mode 100644 furniture-3d-system/src/server/services/diy-sku-retry-review.ts create mode 100644 furniture-3d-system/src/server/services/diy-sku-review-crops.ts create mode 100644 furniture-3d-system/src/server/services/diy-sku-review-vision.ts create mode 100644 furniture-3d-system/src/server/services/diy-sku-scene-prompt.ts diff --git a/furniture-3d-system/src/app/api/diy/ai-renders/[id]/regenerate/route.ts b/furniture-3d-system/src/app/api/diy/ai-renders/[id]/regenerate/route.ts new file mode 100644 index 00000000..a3f34db1 --- /dev/null +++ b/furniture-3d-system/src/app/api/diy/ai-renders/[id]/regenerate/route.ts @@ -0,0 +1,13 @@ +import type { NextRequest } from 'next/server' +import { handleRequest, jsonSuccess } from '@/server/core/response' +import { AppError, ErrorCode } from '@/server/core/errors' +import { regenerateDiyImage } from '@/server/services/diy-render-regeneration.service' + +export async function POST(request: NextRequest, context: { params: Promise<{ id: string }> }) { + return handleRequest(request, async ctx => { + let input: unknown + try { input = await request.json() } catch { throw new AppError(ErrorCode.VALIDATION_FAILED, '重新出图参数格式无效') } + const { id } = await context.params + return jsonSuccess(await regenerateDiyImage(id, input, ctx.user), 202, ctx.requestId) + }, { requireAuth: true }) +} diff --git a/furniture-3d-system/src/app/api/diy/ai-renders/[id]/versions/route.ts b/furniture-3d-system/src/app/api/diy/ai-renders/[id]/versions/route.ts new file mode 100644 index 00000000..cb8e1773 --- /dev/null +++ b/furniture-3d-system/src/app/api/diy/ai-renders/[id]/versions/route.ts @@ -0,0 +1,13 @@ +import type { NextRequest } from 'next/server' +import { handleRequest, jsonSuccess } from '@/server/core/response' +import { AppError, ErrorCode } from '@/server/core/errors' +import { chooseDiyImageVersion } from '@/server/services/diy-image-version.service' + +export async function POST(request: NextRequest, context: { params: Promise<{ id: string }> }) { + return handleRequest(request, async ctx => { + let input: unknown + try { input = await request.json() } catch { throw new AppError(ErrorCode.VALIDATION_FAILED, '图片选用参数格式无效') } + const { id } = await context.params + return jsonSuccess(await chooseDiyImageVersion(id, input, ctx.user), 200, ctx.requestId) + }, { requireAuth: true }) +} diff --git a/furniture-3d-system/src/app/diy/components/DiyAiProcessingResults.tsx b/furniture-3d-system/src/app/diy/components/DiyAiProcessingResults.tsx index 0abac7d3..7d2ee749 100644 --- a/furniture-3d-system/src/app/diy/components/DiyAiProcessingResults.tsx +++ b/furniture-3d-system/src/app/diy/components/DiyAiProcessingResults.tsx @@ -1,30 +1,36 @@ 'use client' -import { Download, RefreshCw } from 'lucide-react' +import { Download } from 'lucide-react' import Button from '@/components/ui/Button' import type { DiyAiRenderDTO } from '@/lib/diy/ai-render' import type { DiyAiRenderController } from '../hooks/useDiyAiRender' -import { useDiyReprocessing } from '../hooks/useDiyReprocessing' +import { useDiyReprocessing, type DiyReprocessingController } from '../hooks/useDiyReprocessing' import DiyAiFailureNotice from './DiyAiFailureNotice' +import DiySkuImageActions from './DiySkuImageActions' +import DiyImageVersions from './DiyImageVersions' -export default function DiyAiProcessingResults({ record, ai, onPreview }: { record: DiyAiRenderDTO; ai: DiyAiRenderController; onPreview: (url: string) => void }) { - const retry = useDiyReprocessing(ai.refresh) +export default function DiyAiProcessingResults({ record, ai, onPreview, controller }: { record: DiyAiRenderDTO; ai: DiyAiRenderController; onPreview: (url: string) => void; controller?: DiyReprocessingController }) { + const ownController = useDiyReprocessing(ai.refresh), retry = controller || ownController if (!record.processing) return null - const pending = record.processing.images.filter(image => image.status !== 'succeeded') - const failed = pending.filter(image => image.status === 'failed').length + const pending = record.processing.images.filter(image => image.status !== 'succeeded' + && !record.images.some(result => result.storageKey === image.resultStorageKey)) + const awaitingChoice = pending.filter(image => image.versions?.some(version => !version.selected && version.result)).length + const failed = pending.filter(image => image.status === 'failed' && !image.versions?.some(version => version.result)).length return
-

成功 {record.images.length}/{record.processing.expected} 张{failed ? ` · ${failed}张后处理失败` : pending.length ? ' · 正在处理原图…' : ''}

- {retry.error &&

{retry.error}

} +

已选用 {record.images.length}/{record.processing.expected} 张{record.needsReview ? ' · 任务已暂停,待核对' : awaitingChoice ? ` · ${awaitingChoice}张可对比选用` : failed ? ` · ${failed}张后处理失败` : pending.length ? ' · 正在处理原图…' : ''}

+ {!controller && retry.error &&

{retry.error}

} {pending.map(image =>
+ {image.versions && image.versions.length > 1 ? : <> {image.status === 'failed' ? - :

原图已生成,正在处理…

} + :

{record.needsReview ? '任务已暂停,待核对已有结果' : '原图已生成,正在处理…'}

} + }
- {image.status === 'failed' && record.mode === 'sku' && !record.operation && ai.access.canGenerate && } + {(!image.versions || image.versions.length < 2) && image.status === 'failed' && ai.access.canGenerate && } {ai.access.canDownload && }
diff --git a/furniture-3d-system/src/app/diy/components/DiyAiResultCard.tsx b/furniture-3d-system/src/app/diy/components/DiyAiResultCard.tsx index 422daca3..1d487464 100644 --- a/furniture-3d-system/src/app/diy/components/DiyAiResultCard.tsx +++ b/furniture-3d-system/src/app/diy/components/DiyAiResultCard.tsx @@ -10,6 +10,9 @@ import DiyDimensionActions from './dimensions/DiyDimensionActions' import { diyDisplayImageUrl, type DiyDimensionSelection } from '@/lib/diy/dimension-annotations' import DiyAiProcessingResults from './DiyAiProcessingResults' import DiyAiFailureNotice from './DiyAiFailureNotice' +import { useDiyReprocessing } from '../hooks/useDiyReprocessing' +import DiySkuImageActions from './DiySkuImageActions' +import DiyImageVersions from './DiyImageVersions' export const diyRenderLabel = (record: DiyAiRenderDTO) => record.operation === 'local-preview' ? '本地截图' : record.operation === 'text-replace' ? '文字替换' : record.operation === 'layout-replace' ? '排版图' : record.mode === 'sku' ? 'SKU 图' : record.mode === 'scene' ? '效果图' : '白底图' @@ -20,7 +23,9 @@ export default function DiyAiResultCard({ record, ai, onPreview, onEdit, onLayou onEdit: (selection: DiyImageSelection) => void; onLayout: (selection: DiyImageSelection) => void; onDimensions: (selection: DiyDimensionSelection) => void }) { const label = diyRenderLabel(record) + const replacement = useDiyReprocessing(ai.refresh) const hasProcessingFailure = record.processing?.images.some(image => image.status === 'failed') + const hasComparison = record.processing?.images.some(image => image.versions && image.versions.length > 1) return
{record.name} @@ -31,24 +36,33 @@ export default function DiyAiResultCard({ record, ai, onPreview, onEdit, onLayou
{record.needsReview &&

待核对 · 后台已暂停,不占生成名额

} - {record.status === 'PENDING' && !record.needsReview && !record.errorMessage &&

{record.processing ? '正在处理原图…' : '正在生成…'}

} + {record.status === 'PENDING' && !record.needsReview && !record.errorMessage &&

{record.processing?.images.some(image => image.operation) ? '正在重新处理,完成后对比选用…' : record.processing ? '正在处理原图…' : '正在生成…'}

} + {replacement.error &&

{replacement.error}

} {record.status === 'PENDING' && record.errorMessage &&

{record.errorMessage}

} - {record.status !== 'PENDING' && (record.status === 'FAILED' || record.errorMessage) && !hasProcessingFailure && } - + {record.status !== 'PENDING' && record.images.length > 0 && record.errorMessage?.includes('原成图已保留') &&

本次重新处理失败,原成图已保留。

} + {record.status !== 'PENDING' && (record.status === 'FAILED' || record.errorMessage) && !hasProcessingFailure && !hasComparison && } + {record.status === 'FAILED' && !record.images.length && ai.access.canDelete && } {record.images.map((image, index) => { const displayUrl = diyDisplayImageUrl(record, image) + const processing = record.processing?.images.find(item => item.resultStorageKey === image.storageKey) + const comparing = Boolean(processing?.versions && processing.versions.length > 1) const selection: DiyImageSelection = { recordId: record.id, storageKey: image.storageKey, url: image.originalUrl, name: `${record.name}-${label}-${index + 1}`, width: image.width, height: image.height } const canLayout = ai.access.canGenerate && record.mode !== 'scene' && (!record.operation || record.operation === 'local-preview') && record.status === 'SUCCEEDED' return
- + } + {!comparing && ai.access.canGenerate && processing &&
+ +
}
{canLayout && } diff --git a/furniture-3d-system/src/app/diy/components/DiyImageVersions.test.tsx b/furniture-3d-system/src/app/diy/components/DiyImageVersions.test.tsx new file mode 100644 index 00000000..1a7ab197 --- /dev/null +++ b/furniture-3d-system/src/app/diy/components/DiyImageVersions.test.tsx @@ -0,0 +1,60 @@ +import { fireEvent, render, screen, within } from '@testing-library/react' +import DiyImageVersions from './DiyImageVersions' +import type { DiyAiRenderDTO } from '@/lib/diy/ai-render' +import type { DiyProcessingImageDTO } from '@/lib/diy/render-processing' +import type { DiyReprocessingController } from '../hooks/useDiyReprocessing' + +const output = (key: string) => ({ storageKey: key, originalUrl: `/${key}.png`, thumbnailUrl: `/${key}.png`, width: 1440, height: 1440 }) +const record = { id: 'record', status: 'SUCCEEDED', mode: 'sku', sku: { template: 'gujia', background: 'scene' } } as DiyAiRenderDTO +const image: DiyProcessingImageDTO = { index: 7, status: 'succeeded', originalUrl: '/old-raw', resultStorageKey: 'old', versions: [ + { id: 'original', kind: 'original', status: 'succeeded', source: { originalUrl: '/old-raw' }, result: output('old'), selected: true, createdAt: '2026-11-14T00:00:00Z' }, + { id: 'trial', kind: 'generate', status: 'succeeded', source: { originalUrl: '/new-raw' }, result: output('new'), selected: false, createdAt: '2026-11-14T01:00:00Z' }, +] } +const controller = () => ({ busy: '', error: '', operation: 'annotate', retry: jest.fn(), regenerate: jest.fn(), choose: jest.fn() }) as DiyReprocessingController +test('current and this candidate appear together; selecting or keeping the current image is explicit', () => { + const c = controller(), preview = jest.fn() + const { container } = render() + expect(screen.getAllByRole('img')).toHaveLength(2) + expect(screen.getByText('当前选用')).toBeInTheDocument(); expect(screen.getByText('待选用')).toBeInTheDocument() + expect(c.choose).not.toHaveBeenCalled() + fireEvent.click(screen.getByRole('button', { name: '选用这张' })) + expect(c.choose).toHaveBeenCalledWith('record', 7, 'trial', 'old') + fireEvent.click(screen.getByRole('button', { name: '保留当前图' })) + expect(c.choose).toHaveBeenLastCalledWith('record', 7, 'original', 'old') + const failed = within(container.querySelector('[data-image-version="trial"]')! as HTMLElement) + fireEvent.click(failed.getByRole('button', { name: '重新标注' })) + fireEvent.click(screen.getByRole('button', { name: '开始重新标注' })) + expect(c.retry).toHaveBeenCalledWith('record', 7, 'old', 'trial') + fireEvent.click(failed.getByRole('button', { name: '重新出图' })) + fireEvent.click(screen.getByRole('button', { name: '开始重新出图' })) + expect(c.regenerate).toHaveBeenCalledWith('record', 7, 'old', 'trial') + fireEvent.click(screen.getByRole('button', { name: '放大查看本次候选' })) + expect(preview).toHaveBeenCalledWith('/new.png') +}) +test('view permission allows comparison, while all writes are blocked during processing', () => { + const c = controller(), props = { record, image, controller: c, onPreview: jest.fn() } + const { rerender } = render() + expect(screen.getAllByRole('img')).toHaveLength(2) + expect(screen.queryByRole('button', { name: '选用这张' })).not.toBeInTheDocument() + rerender() + expect(screen.getByRole('button', { name: '选用这张' })).toBeDisabled() + for (const button of screen.getAllByRole('button', { name: '重新标注' })) expect(button).toBeDisabled() +}) +test('a failed upstream generation shows no counterfeit new photo or reannotation action', () => { + const versions = [image.versions![0], { ...image.versions![1], id: 'failed', status: 'failed' as const, result: undefined, sourceReady: false }] + const { container } = render() + expect(screen.getAllByRole('img')).toHaveLength(1) + expect(screen.getByText('本次未生成新图')).toBeInTheDocument() + expect(container.querySelector('[data-image-version="failed"] button')).toBeNull() +}) +test('an unchanged retry exposes the requested correction and unresolved findings beside the candidate', () => { + const versions = [image.versions![0], { ...image.versions![1], feedback: '38 没有贴合底侧板', review: { + status: 'needs-review' as const, change: 'unchanged' as const, changedAxes: [], summary: '复核后无明显变化,请对比确认', issues: ['深度线仍需核对'], + } }] + render() + expect(screen.getByText('复核未确认改善')).toBeInTheDocument() + expect(screen.getByText('复核后无明显变化,请对比确认')).toBeInTheDocument() + expect(screen.getByText('调整要求:38 没有贴合底侧板')).toBeInTheDocument() + expect(screen.getByText('深度线仍需核对')).toBeInTheDocument() + expect(screen.queryByText('自动复核通过')).not.toBeInTheDocument() +}) diff --git a/furniture-3d-system/src/app/diy/components/DiyImageVersions.tsx b/furniture-3d-system/src/app/diy/components/DiyImageVersions.tsx new file mode 100644 index 00000000..f0c98da6 --- /dev/null +++ b/furniture-3d-system/src/app/diy/components/DiyImageVersions.tsx @@ -0,0 +1,45 @@ +'use client' +import Button from '@/components/ui/Button' +import type { DiyAiRenderDTO } from '@/lib/diy/ai-render' +import type { DiyProcessingImageDTO } from '@/lib/diy/render-processing' +import { diyDisplayImageUrl } from '@/lib/diy/dimension-annotations' +import type { DiyReprocessingController } from '../hooks/useDiyReprocessing' +import DiySkuImageActions from './DiySkuImageActions' + +export default function DiyImageVersions({ record, image, controller, onPreview, canGenerate, disabled = false }: { + record: DiyAiRenderDTO; image: DiyProcessingImageDTO; controller: DiyReprocessingController + onPreview: (url: string) => void; canGenerate: boolean; disabled?: boolean +}) { + if (!image.versions || image.versions.length < 2) return null + const busy = disabled || Boolean(controller.busy) || record.status === 'PENDING' + return
+ {image.versions.map(version => { + const label = version.selected ? '当前图' : '本次候选' + const url = version.result ? version.selected ? diyDisplayImageUrl(record, version.result) : version.result.originalUrl : version.source.originalUrl + return
+

{label} + {version.selected ? version.result ? '当前选用' : '原图未标注' : version.status === 'pending' ? record.needsReview ? '待核对' : '处理中' : version.result ? '待选用' : version.sourceReady === false ? '生图失败' : '标注未完成'}

+ {version.sourceReady === false ?
{version.status === 'pending' ? record.needsReview ? '任务已暂停,待核对' : '正在重新出图…' : '本次未生成新图'}
: + } + {version.completedAt && } + {version.errorMessage &&

{version.errorMessage}

} + {version.feedback &&

调整要求:{version.feedback}

} + {version.review &&
+

{version.review.status === 'passed' ? '自动复核通过' : version.review.status === 'needs-review' ? version.review.change === 'unchanged' ? '复核未确认改善' : '复核发现问题' : '自动复核未完成'}

+

{version.review.summary}

+ {version.review.change === 'changed' && version.review.changedAxes.length > 0 &&

位置有变化:{version.review.changedAxes.map(axis => ({ width: '长度线', height: '高度线', depth: '深度线', scene: '场景构图' })[axis]).join('、')}

} + {version.review.issues.map((issue, i) =>

{issue}

)} +
} + {canGenerate && version.result && } + {canGenerate && version.sourceReady !== false &&
+ +
} +
+ })} +
+} diff --git a/furniture-3d-system/src/app/diy/components/DiySkuImageActions.test.tsx b/furniture-3d-system/src/app/diy/components/DiySkuImageActions.test.tsx new file mode 100644 index 00000000..b38a9a7b --- /dev/null +++ b/furniture-3d-system/src/app/diy/components/DiySkuImageActions.test.tsx @@ -0,0 +1,49 @@ +import { render, screen, fireEvent } from '@testing-library/react' +import DiySkuImageActions from './DiySkuImageActions' +import type { DiyAiRenderDTO } from '@/lib/diy/ai-render' +import type { DiyReprocessingController } from '../hooks/useDiyReprocessing' +const image = { index: 7, originalUrl: '/raw', status: 'succeeded' as const, resultStorageKey: 'current-version' } +const record = { id: 'record', mode: 'sku', status: 'SUCCEEDED', sku: { template: 'gujia', background: 'scene' } } as DiyAiRenderDTO +test('successful scene outputs expose both replacement actions using the stable original index', () => { + const controller = { busy: '', operation: 'annotate', retry: jest.fn(), regenerate: jest.fn() } as unknown as DiyReprocessingController + render( ) + fireEvent.click(screen.getByRole('button', { name: '重新标注' })) + fireEvent.click(screen.getByRole('button', { name: '开始重新标注' })) + expect(controller.retry).toHaveBeenCalledWith('record', 7, 'current-version') + fireEvent.click(screen.getByRole('button', { name: '重新出图' })) + fireEvent.click(screen.getByRole('button', { name: '开始重新出图' })) + expect(controller.regenerate).toHaveBeenCalledWith('record', 7, 'current-version') +}) +test('pending work disables both actions and white SKU output exposes no scene regeneration', () => { + const controller = { busy: '', operation: 'annotate', retry: jest.fn(), regenerate: jest.fn() } as unknown as DiyReprocessingController + const { rerender } = render( ) + expect(screen.getByRole('button', { name: '重新标注' })).toBeDisabled() + expect(screen.getByRole('button', { name: '重新出图' })).toBeDisabled() + rerender( ) + expect(screen.queryByRole('button', { name: '重新出图' })).not.toBeInTheDocument() + fireEvent.click(screen.getByRole('button', { name: '重新标注' })) + expect(controller.retry).toHaveBeenCalledWith('record', 7, 'current-version') + expect(screen.queryByRole('dialog')).not.toBeInTheDocument() +}) +test('optional feedback is trimmed and sent only after submission; cancel and Esc do not submit', () => { + const controller = { busy: '', retry: jest.fn(), regenerate: jest.fn() } as unknown as DiyReprocessingController + render() + fireEvent.click(screen.getByRole('button', { name: '重新标注' })) + expect(controller.retry).not.toHaveBeenCalled() + fireEvent.change(screen.getByRole('textbox', { name: '调整要求(可选)' }), { target: { value: ' 38 的线压到了花瓶 ' } }) + fireEvent.click(screen.getByRole('button', { name: '开始重新标注' })) + expect(controller.retry).toHaveBeenCalledWith('record', 7, 'current-version', 'trial', '38 的线压到了花瓶') + fireEvent.click(screen.getByRole('button', { name: '重新出图' })) + fireEvent.keyDown(screen.getByRole('textbox'), { key: 'Escape' }) + expect(screen.queryByRole('dialog')).not.toBeInTheDocument() + expect(controller.regenerate).not.toHaveBeenCalled() +}) + +test('candidate work does not spin current-image actions, and blocked work never spins', () => { + const controller = { busy: '', operation: 'annotate', retry: jest.fn(), regenerate: jest.fn() } as unknown as DiyReprocessingController + const { container, rerender } = render() + expect(container.querySelector('.animate-spin')).toBeNull() + expect(screen.getByRole('button', { name: '重新标注' })).toBeDisabled() + rerender() + expect(container.querySelector('.animate-spin')).toBeNull() +}) diff --git a/furniture-3d-system/src/app/diy/components/DiySkuImageActions.tsx b/furniture-3d-system/src/app/diy/components/DiySkuImageActions.tsx new file mode 100644 index 00000000..7225fe47 --- /dev/null +++ b/furniture-3d-system/src/app/diy/components/DiySkuImageActions.tsx @@ -0,0 +1,45 @@ +'use client' +import { ImagePlus, RefreshCw } from 'lucide-react' +import { useState } from 'react' +import Button from '@/components/ui/Button' +import type { DiyAiRenderDTO } from '@/lib/diy/ai-render' +import type { DiyProcessingImageDTO } from '@/lib/diy/render-processing' +import type { DiyReprocessingController } from '../hooks/useDiyReprocessing' +import DiySkuRetryDialog from './DiySkuRetryDialog' + +export default function DiySkuImageActions({ record, image, controller, disabled = false, compact = false, baseVersionId }: { + record: DiyAiRenderDTO; image: DiyProcessingImageDTO; controller: DiyReprocessingController; disabled?: boolean; compact?: boolean; baseVersionId?: string +}) { + const [requested, setRequested] = useState<'generate' | 'annotate' | null>(null) + if (record.mode !== 'sku' || record.operation) return null + const scene = record.sku?.template === 'gujia' && record.sku.background === 'scene' + const busy = Boolean(controller.busy) || record.status === 'PENDING' || disabled + // Version cards use their own status. A pending candidate must never spin the current image's buttons. + const current = !baseVersionId && !record.needsReview + ? controller.busy === `${record.id}:${image.index}` ? controller.operation : image.operation : undefined + const version = image.versions?.find(version => version.id === (baseVersionId || image.versions?.find(version => version.selected)?.id)) + const imageUrl = version?.result?.originalUrl || version?.source.originalUrl || record.images?.find(result => result.storageKey === image.resultStorageKey)?.originalUrl || image.originalUrl + const submit = async (feedback: string) => { + const run = requested === 'generate' ? controller.regenerate : controller.retry + setRequested(null) + if (feedback) await run(record.id, image.index, image.resultStorageKey, baseVersionId, feedback) + else if (baseVersionId) await run(record.id, image.index, image.resultStorageKey, baseVersionId) + else await run(record.id, image.index, image.resultStorageKey) + } + const actionClass = compact ? '!h-6 !min-h-0 !min-w-0 !px-1 !py-0 !text-[10px] !whitespace-nowrap [&>span]:gap-1' + : 'min-w-0! whitespace-nowrap px-2! text-[11px]!' + return <> + + {scene && } + {requested && setRequested(null)} onSubmit={submit}/>} + +} diff --git a/furniture-3d-system/src/app/diy/components/DiySkuRetryDialog.tsx b/furniture-3d-system/src/app/diy/components/DiySkuRetryDialog.tsx new file mode 100644 index 00000000..e571859a --- /dev/null +++ b/furniture-3d-system/src/app/diy/components/DiySkuRetryDialog.tsx @@ -0,0 +1,29 @@ +'use client' +import { useState } from 'react' +import Modal from '@/components/ui/Modal' +import Button from '@/components/ui/Button' + +export default function DiySkuRetryDialog({ kind, imageUrl, busy, onClose, onSubmit }: { + kind: 'generate' | 'annotate'; imageUrl: string; busy: boolean; onClose: () => void; onSubmit: (feedback: string) => Promise +}) { + const [feedback, setFeedback] = useState('') + const label = kind === 'generate' ? '重新出图' : '重新标注' + return
{ if (event.key === 'Escape') { event.stopPropagation(); onClose() } }}> + +
{ event.preventDefault(); if (!busy) void onSubmit(feedback.trim()) }}> +

{label}

+ {/* eslint-disable-next-line @next/next/no-img-element */} + 本次调整的版本 +