diff --git a/furniture-3d-system/src/app/asset-center/packaging-materials/PackagingMaterialsClient.test.tsx b/furniture-3d-system/src/app/asset-center/packaging-materials/PackagingMaterialsClient.test.tsx index 95ce726d..ec06373e 100644 --- a/furniture-3d-system/src/app/asset-center/packaging-materials/PackagingMaterialsClient.test.tsx +++ b/furniture-3d-system/src/app/asset-center/packaging-materials/PackagingMaterialsClient.test.tsx @@ -318,10 +318,11 @@ describe('PackagingMaterialsClient', () => { ) await actor.click(screen.getByRole('button', { name: /新增包材/ })) + await chooseOption(actor, '模板类型', '纸箱') + await actor.click(screen.getByRole('button', { name: /下一步:录入字段/ })) - const textInputs = document.querySelectorAll('input:not([type]), input[type="text"]') - await actor.type(textInputs[1] as HTMLInputElement, 'CTN-1200') - await actor.type(textInputs[2] as HTMLInputElement, 'Carton 1200') + await actor.type(screen.getByPlaceholderText('CTN-1200'), 'CTN-1200') + await actor.type(screen.getByPlaceholderText('纸箱 1200'), 'Carton 1200') await actor.click(screen.getByRole('button', { name: /^保存$/ })) await waitFor(() => expect(createAssetVariant).toHaveBeenCalledTimes(1)) @@ -370,33 +371,34 @@ describe('PackagingMaterialsClient', () => { await waitFor(() => expect(createAssetFamily).toHaveBeenCalledTimes(1)) expect(screen.getByRole('heading', { name: '新增包材' })).toBeInTheDocument() + await chooseOption(actor, '模板类型', '纸箱') + await actor.click(screen.getByRole('button', { name: /下一步:录入字段/ })) expect(screen.getByRole('combobox', { name: '所属品类' })).toHaveTextContent('大桌外箱') }) it('编辑包材切换所属品类后,保存会带上 assetFamilyId 并切换到新分类', async () => { const actor = userEvent.setup() - const foamFamily = createFamily({ - id: 'family-foam', - code: 'PACK-FOAM', - name: '泡沫业务类', + const deskBoxFamily = createFamily({ + id: 'family-desk-box', + code: 'PACK-DESK-BOX', + name: '大桌外箱', metadata: { - categoryLevel1: 'cushion', - categoryLevel2: 'foam', + categoryLevel1: 'outer', }, }) updateAssetVariant.mockResolvedValue( createVariant({ id: 'variant-1', - assetFamilyId: 'family-foam', - assetFamilyCode: 'PACK-FOAM', - assetFamilyName: '泡沫业务类', + assetFamilyId: 'family-desk-box', + assetFamilyCode: 'PACK-DESK-BOX', + assetFamilyName: '大桌外箱', }), ) render( , @@ -404,7 +406,7 @@ describe('PackagingMaterialsClient', () => { await actor.dblClick(screen.getByText('Carton 001')) - await chooseOption(actor, '所属品类', '泡沫业务类') + await chooseOption(actor, '所属品类', '大桌外箱') await actor.click(screen.getByRole('button', { name: /^保存$/ })) await waitFor(() => expect(updateAssetVariant).toHaveBeenCalledTimes(1)) @@ -412,16 +414,92 @@ describe('PackagingMaterialsClient', () => { expect(updateAssetVariant).toHaveBeenCalledWith( 'variant-1', expect.objectContaining({ - assetFamilyId: 'family-foam', + assetFamilyId: 'family-desk-box', }), ) - expect(screen.getByRole('button', { name: /内缓冲防护类/ }).className).toContain( + expect(screen.getByRole('button', { name: /外包装类/ }).className).toContain( 'bg-apple-blue/12', ) - expect(screen.getByRole('button', { name: /泡沫业务类/ }).className).toContain( + expect(screen.getByRole('button', { name: /大桌外箱/ }).className).toContain( 'bg-apple-blue/12', ) }) + + it('工作筛选可以只看缺成本的包材', async () => { + const actor = userEvent.setup() + + render( + , + ) + + await chooseOption(actor, '工作筛选', '只看缺成本') + + expect(screen.getByText('Carton 001')).toBeInTheDocument() + expect(screen.queryByText('Tape 001')).not.toBeInTheDocument() + expect(screen.getAllByText('纸箱').length).toBeGreaterThan(0) + }) + + it('启用前缺少成本时会在编辑区顶部显示明确错误', async () => { + const actor = userEvent.setup() + + render( + , + ) + + await actor.dblClick(screen.getByText('Carton 001')) + await chooseOption(actor, '状态', '启用中') + await actor.click(screen.getByRole('button', { name: /^保存$/ })) + + expect(await screen.findByText('启用前必须补齐成本')).toBeInTheDocument() + }) + it('选中空的二级分类时,右上角删除按钮可用并会删除该分类', async () => { const actor = userEvent.setup() const emptyFamily = createFamily({ diff --git a/furniture-3d-system/src/app/asset-center/packaging-materials/PackagingMaterialsClient.tsx b/furniture-3d-system/src/app/asset-center/packaging-materials/PackagingMaterialsClient.tsx index 9ec5bbe2..2305cc5f 100644 --- a/furniture-3d-system/src/app/asset-center/packaging-materials/PackagingMaterialsClient.tsx +++ b/furniture-3d-system/src/app/asset-center/packaging-materials/PackagingMaterialsClient.tsx @@ -25,7 +25,8 @@ import { import { cn } from '@/lib/utils' import { LEVEL1_CATEGORIES, - LEVEL2_MAP, + PACKAGING_TEMPLATE_MAP, + PACKAGING_TEMPLATES, UNIT_OPTIONS, MATERIAL_STATUS_OPTIONS, getLevel1FromFamily, @@ -34,12 +35,19 @@ import { getLevel2Label, type Level1CategoryKey, type FieldTemplate, + type PackagingTemplateDefinition, + type PackagingTemplateKey, } from '@/lib/packaging-materials/catalog' import { buildPackagingVariantCreateInput, getSelectionAfterFamilyCreate, getSelectionForFamilyId, + readPackagingTemplateType, } from '@/lib/packaging-materials/client-helpers' +import { + computePackagingMaterialCost, + validatePackagingMaterialDraft, +} from '@/lib/packaging-materials/pricing' import { createAssetFamily, createAssetVariant, @@ -69,6 +77,7 @@ interface PackagingMaterialsClientProps { interface EditingMaterial { id: string assetFamilyId: string + templateType: PackagingTemplateKey | '' code: string name: string status: string @@ -89,6 +98,7 @@ interface EditingMaterial { type SortField = 'name' | 'code' | 'costPrice' | 'updatedAt' type SortDir = 'asc' | 'desc' +type WorkFilter = 'all' | 'missingCost' | 'missingImage' | 'draftOnly' type DeleteTarget = | { type: 'family'; id: string; name: string } | { type: 'variant'; id: string; name: string } @@ -101,6 +111,7 @@ function emptyEditingMaterial(familyId: string): EditingMaterial { return { id: '', assetFamilyId: familyId, + templateType: '', code: '', name: '', status: 'DRAFT', @@ -120,7 +131,7 @@ function emptyEditingMaterial(familyId: string): EditingMaterial { } } -function variantToEditing(v: AssetVariantDTO): EditingMaterial { +function variantToEditing(v: AssetVariantDTO, family: AssetFamilyDTO | null): EditingMaterial { const meta = (v.businessData ?? {}) as Record const templateFields = (meta.templateFields ?? {}) as Record const customAttributes = (meta.customAttributes ?? []) as { key: string; value: string }[] @@ -129,6 +140,7 @@ function variantToEditing(v: AssetVariantDTO): EditingMaterial { return { id: v.id, assetFamilyId: v.assetFamilyId, + templateType: readPackagingTemplateType(v, family), code: v.code, name: v.name, status: v.status, @@ -148,6 +160,28 @@ function variantToEditing(v: AssetVariantDTO): EditingMaterial { } } +function getTemplateOptionsForLevel1(level1: Level1CategoryKey) { + return PACKAGING_TEMPLATES.filter((template) => template.level1 === level1).map((template) => ({ + value: template.key, + label: template.label, + })) +} + +function getVariantTemplateSnapshot(variant: AssetVariantDTO, family: AssetFamilyDTO | null) { + const businessData = (variant.businessData ?? {}) as Record + const templateFields = (businessData.templateFields ?? {}) as Record + const templateType = readPackagingTemplateType(variant, family) + const template = templateType ? PACKAGING_TEMPLATE_MAP.get(templateType) ?? null : null + const computedCost = templateType ? computePackagingMaterialCost(templateType, templateFields) : null + + return { + templateType, + template, + templateFields, + computedCost, + } +} + function getStatusTone(status: string) { if (status === 'AVAILABLE') return 'success' if (status === 'DISABLED') return 'warning' @@ -235,9 +269,11 @@ export default function PackagingMaterialsClient({ const [selectedFamilyId, setSelectedFamilyId] = useState(null) const [searchQuery, setSearchQuery] = useState('') const [statusFilter, setStatusFilter] = useState('all') + const [workFilter, setWorkFilter] = useState('all') const [selectedVariantId, setSelectedVariantId] = useState(null) const [editingMaterial, setEditingMaterial] = useState(null) const [isNew, setIsNew] = useState(false) + const [templateStarterCompleted, setTemplateStarterCompleted] = useState(false) const [saving, setSaving] = useState(false) const [error, setError] = useState(null) @@ -287,6 +323,28 @@ export default function PackagingMaterialsClient({ if (statusFilter !== 'all') { result = result.filter((v) => v.status === statusFilter) } + + if (workFilter !== 'all') { + result = result.filter((variant) => { + const family = families.find((item) => item.id === variant.assetFamilyId) ?? null + const { computedCost } = getVariantTemplateSnapshot(variant, family) + + if (workFilter === 'missingCost') { + return variant.costPrice == null && computedCost == null + } + + if (workFilter === 'missingImage') { + return !variant.thumbnailUrl + } + + if (workFilter === 'draftOnly') { + return variant.status === 'DRAFT' + } + + return true + }) + } + // sort result.sort((a, b) => { let cmp = 0 @@ -301,7 +359,7 @@ export default function PackagingMaterialsClient({ return sortDir === 'asc' ? cmp : -cmp }) return result - }, [variants, filteredFamilyIds, selectedFamilyId, searchQuery, statusFilter, sortField, sortDir]) + }, [variants, filteredFamilyIds, selectedFamilyId, searchQuery, statusFilter, sortField, sortDir, workFilter, families]) // ---- Template for current family ---- const currentFamily = useMemo( @@ -309,10 +367,25 @@ export default function PackagingMaterialsClient({ [families, editingMaterial], ) - const templateFields = useMemo(() => { - const level2Key = getLevel2FromFamily(currentFamily?.metadata ?? null) - return level2Key ? (LEVEL2_MAP.get(level2Key)?.fields ?? []) : [] - }, [currentFamily]) + const currentLevel1 = useMemo( + () => getLevel1FromFamily(currentFamily?.metadata ?? null) ?? selectedLevel1, + [currentFamily, selectedLevel1], + ) + + const currentTemplate = useMemo( + () => + editingMaterial?.templateType + ? PACKAGING_TEMPLATE_MAP.get(editingMaterial.templateType) ?? null + : null, + [editingMaterial], + ) + + const activeTemplateFields = useMemo( + () => currentTemplate?.fields ?? [], + [currentTemplate], + ) + + const showTemplateStarter = Boolean(editingMaterial && isNew && !templateStarterCompleted) // ---- Stats ---- const stats = useMemo(() => { @@ -344,6 +417,7 @@ export default function PackagingMaterialsClient({ setSelectedVariantId(null) setEditingMaterial(emptyEditingMaterial(fid)) setIsNew(true) + setTemplateStarterCompleted(false) setError(null) }, [selectedFamilyId, filteredFamilies, families, syncSelectionToFamily], @@ -352,10 +426,12 @@ export default function PackagingMaterialsClient({ const handleEdit = useCallback((variant: AssetVariantDTO) => { syncSelectionToFamily(variant.assetFamilyId) setSelectedVariantId(variant.id) - setEditingMaterial(variantToEditing(variant)) + const family = families.find((item) => item.id === variant.assetFamilyId) ?? null + setEditingMaterial(variantToEditing(variant, family)) setIsNew(false) + setTemplateStarterCompleted(true) setError(null) - }, [syncSelectionToFamily]) + }, [families, syncSelectionToFamily]) const openCreateFamilyModal = useCallback(() => { setNewFamilyLevel1(selectedLevel1) @@ -366,7 +442,8 @@ export default function PackagingMaterialsClient({ }, [selectedLevel1]) const handleCopyNew = useCallback((variant: AssetVariantDTO) => { - const editing = variantToEditing(variant) + const family = families.find((item) => item.id === variant.assetFamilyId) ?? null + const editing = variantToEditing(variant, family) editing.id = '' editing.code = '' editing.status = 'DRAFT' @@ -375,13 +452,36 @@ export default function PackagingMaterialsClient({ setSelectedVariantId(null) setEditingMaterial(editing) setIsNew(true) + setTemplateStarterCompleted(Boolean(editing.templateType)) setError(null) - }, [syncSelectionToFamily]) + }, [families, syncSelectionToFamily]) const handleSave = useCallback(async () => { if (!editingMaterial) return - if (!editingMaterial.name.trim()) { setError('包材名称不能为空'); return } - if (!editingMaterial.code.trim()) { setError('包材编码不能为空'); return } + + const family = + families.find((item) => item.id === editingMaterial.assetFamilyId) ?? currentFamily ?? null + const level1 = getLevel1FromFamily(family?.metadata ?? null) ?? selectedLevel1 + const validation = validatePackagingMaterialDraft({ + code: editingMaterial.code, + name: editingMaterial.name, + level1, + templateType: editingMaterial.templateType, + status: isNew ? 'DRAFT' : editingMaterial.status, + dimensions: { + length: editingMaterial.length, + width: editingMaterial.width, + height: editingMaterial.height, + thickness: editingMaterial.thickness, + }, + templateFields: editingMaterial.templateFields, + costPrice: editingMaterial.costPrice, + }) + + if (validation.errors.length > 0) { + setError(validation.errors[0]) + return + } setSaving(true) setError(null) @@ -393,8 +493,16 @@ export default function PackagingMaterialsClient({ if (editingMaterial.height) dimensions.height = Number(editingMaterial.height) || 0 if (editingMaterial.thickness) dimensions.thickness = Number(editingMaterial.thickness) || 0 + const template = + editingMaterial.templateType + ? PACKAGING_TEMPLATE_MAP.get(editingMaterial.templateType) ?? null + : null + const businessData = { unit: editingMaterial.unit, + templateType: editingMaterial.templateType || undefined, + pricingMethod: template?.pricingMethod, + pricingFormula: template?.pricingFormula, materialType: editingMaterial.materialType || undefined, templateFields: editingMaterial.templateFields, customAttributes: editingMaterial.customAttributes.filter( @@ -436,12 +544,13 @@ export default function PackagingMaterialsClient({ setEditingMaterial(null) setIsNew(false) + setTemplateStarterCompleted(false) } catch (saveError) { setError(saveError instanceof Error ? saveError.message : '保存失败') } finally { setSaving(false) } - }, [editingMaterial, isNew, syncSelectionToFamily]) + }, [currentFamily, editingMaterial, families, isNew, selectedLevel1, syncSelectionToFamily]) const handleCreateFamily = useCallback(async () => { if (!newFamilyName.trim() || !newFamilyCode.trim()) return @@ -463,6 +572,7 @@ export default function PackagingMaterialsClient({ setSelectedVariantId(null) setEditingMaterial(emptyEditingMaterial(created.id)) setIsNew(true) + setTemplateStarterCompleted(false) setFamilyModalOpen(false) setNewFamilyName('') setNewFamilyCode('') @@ -521,9 +631,26 @@ export default function PackagingMaterialsClient({ const handleFamilyChange = useCallback((newFamilyId: string) => { setEditingMaterial((cur) => { if (!cur) return cur - return { ...cur, assetFamilyId: newFamilyId, templateFields: {} } + + if (!isNew) { + return { ...cur, assetFamilyId: newFamilyId } + } + + const nextFamily = families.find((family) => family.id === newFamilyId) ?? null + const nextLevel1 = getLevel1FromFamily(nextFamily?.metadata ?? null) + const shouldKeepTemplate = + nextLevel1 && cur.templateType + ? PACKAGING_TEMPLATE_MAP.get(cur.templateType)?.level1 === nextLevel1 + : false + + return { + ...cur, + assetFamilyId: newFamilyId, + templateType: shouldKeepTemplate ? cur.templateType : '', + templateFields: shouldKeepTemplate ? cur.templateFields : {}, + } }) - }, []) + }, [families, isNew]) const SORT_OPTIONS: { field: SortField; label: string }[] = [ { field: 'name', label: '名称' }, @@ -719,6 +846,7 @@ export default function PackagingMaterialsClient({ /> setWorkFilter(e.target.value as WorkFilter)} + options={[ + { value: 'all', label: '全部' }, + { value: 'missingCost', label: '只看缺成本' }, + { value: 'missingImage', label: '只看缺图片' }, + { value: 'draftOnly', label: '只看草稿' }, + ]} + /> {filteredVariants.length} 条 @@ -766,6 +906,7 @@ export default function PackagingMaterialsClient({ const family = families.find((f) => f.id === variant.assetFamilyId) const level2Key = getLevel2FromFamily(family?.metadata ?? null) const level2Label = getLevel2Label(level2Key) + const { template, computedCost } = getVariantTemplateSnapshot(variant, family ?? null) const dims = (variant.dimensions ?? {}) as Record const hasDims = dims.length || dims.width || dims.height || dims.thickness @@ -793,6 +934,11 @@ export default function PackagingMaterialsClient({ {level2Label} )} + {template && ( + + {template.label} + + )} @@ -804,6 +950,9 @@ export default function PackagingMaterialsClient({ {dims.length ?? 0} × {dims.width ?? 0} × {dims.height ?? 0} mm )} {variant.costPrice != null && ¥{variant.costPrice}} + {variant.costPrice == null && computedCost != null && ( + 系统成本 ¥{computedCost.toFixed(2)} + )} {variant.weightKg != null && {variant.weightKg} kg} {/* Hover 操作按钮 */} @@ -851,18 +1000,52 @@ export default function PackagingMaterialsClient({
- {editingMaterial ? ( + {showTemplateStarter && editingMaterial ? ( + + setEditingMaterial((cur) => + cur ? { ...cur, templateType, templateFields: {} } : cur, + ) + } + onContinue={() => { + if (!editingMaterial.templateType) { + setError('请选择模板类型') + return + } + setError(null) + setTemplateStarterCompleted(true) + }} + onCancel={() => { + setEditingMaterial(null) + setIsNew(false) + setTemplateStarterCompleted(false) + setError(null) + }} + /> + ) : editingMaterial ? ( setEditingMaterial((cur) => (cur ? { ...cur, ...patch } : cur)) } onFamilyChange={handleFamilyChange} + onTemplateChange={(templateType) => + setEditingMaterial((cur) => + cur ? { ...cur, templateType, templateFields: {} } : cur, + ) + } onTemplateFieldChange={(key, value) => setEditingMaterial((cur) => cur @@ -892,7 +1075,12 @@ export default function PackagingMaterialsClient({ }) } onSave={handleSave} - onCancel={() => { setEditingMaterial(null); setIsNew(false); setError(null) }} + onCancel={() => { + setEditingMaterial(null) + setIsNew(false) + setTemplateStarterCompleted(false) + setError(null) + }} onDelete={editingMaterial.id ? () => setDeleteTarget({ type: 'variant', id: editingMaterial.id, name: editingMaterial.name }) : undefined} /> ) : selectedVariant ? ( @@ -986,8 +1174,8 @@ function VariantPreview({ const dims = (variant.dimensions ?? {}) as Record const level2Key = getLevel2FromFamily(family?.metadata ?? null) const level1Key = getLevel1FromFamily(family?.metadata ?? null) - const templateDef = level2Key ? LEVEL2_MAP.get(level2Key) : null - const templateFieldValues = (meta.templateFields ?? {}) as Record + const { template: templateDef, templateFields: templateFieldValues, computedCost } = + getVariantTemplateSnapshot(variant, family) return (
@@ -1008,6 +1196,7 @@ function VariantPreview({
{level1Key && {getLevel1Label(level1Key)}} {level2Key && {getLevel2Label(level2Key)}} + {templateDef && {templateDef.label}} {unit && {UNIT_OPTIONS.find(u => u.value === unit)?.label ?? unit}}
@@ -1042,13 +1231,16 @@ function VariantPreview({
)} - {(variant.costPrice != null || variant.weightKg != null) && ( + {(variant.costPrice != null || computedCost != null || variant.weightKg != null) && (

成本

{variant.costPrice != null && (
单价 ¥{variant.costPrice}
)} + {variant.costPrice == null && computedCost != null && ( +
系统计算成本 ¥{computedCost.toFixed(2)}
+ )} {variant.weightKg != null && (
重量 {variant.weightKg} kg
)} @@ -1085,6 +1277,87 @@ function VariantPreview({ ) } +/* ============================================================ + * TemplateStarter + * ============================================================ */ + +interface TemplateStarterProps { + family: AssetFamilyDTO | null + level1: Level1CategoryKey + templateType: PackagingTemplateKey | '' + error: string | null + onTemplateChange: (templateType: PackagingTemplateKey | '') => void + onContinue: () => void + onCancel: () => void +} + +function TemplateStarter({ + family, + level1, + templateType, + error, + onTemplateChange, + onContinue, + onCancel, +}: TemplateStarterProps) { + return ( +
+
+

新增包材

+ +
+ + {error && ( +
+ {error} +
+ )} + +
+
+

请选择模板类型

+

+ 先确定这条包材按哪种计价模板录入,后面字段和成本公式会跟着切换。 +

+
+ +
+
+ 一级分类{' '} + {getLevel1Label(level1)} +
+
+ 当前品类{' '} + {family?.name ?? '未选择'} +
+
+ + ({ value: f.id, label: f.name }))} onChange={(e) => onFamilyChange(e.target.value)} /> + {templateLocked ? ( +
+

+ 模板类型 +

+

{template?.label ?? '未设置'}

+

+ 模板类型已锁定,如选错请复制新增或删除后重建。 +

+
+ ) : ( + onChange({ code: e.target.value })} placeholder="CTN-1200" /> onChange({ name: e.target.value })} placeholder="纸箱 1200" /> @@ -1162,6 +1465,22 @@ function DetailEditor({
+ {template && ( +
+

模板规则

+
+
+ 模板名称{' '} + {template.label} +
+
+ 成本公式{' '} + {template.pricingFormula} +
+
+
+ )} +

通用规格

diff --git a/furniture-3d-system/src/app/asset-center/packaging-materials/PackagingMaterialsClient.workflow.test.tsx b/furniture-3d-system/src/app/asset-center/packaging-materials/PackagingMaterialsClient.workflow.test.tsx new file mode 100644 index 00000000..f2bfa5e9 --- /dev/null +++ b/furniture-3d-system/src/app/asset-center/packaging-materials/PackagingMaterialsClient.workflow.test.tsx @@ -0,0 +1,225 @@ +import { render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import type { ReactNode } from 'react' +import PackagingMaterialsClient from './PackagingMaterialsClient' +import { PACKAGING_PLACEHOLDER_MODEL_URL } from '@/lib/packaging-materials/client-helpers' +import type { AssetFamilyDTO, AssetVariantDTO } from '@/server/services' + +jest.mock('next/link', () => ({ + __esModule: true, + default: ({ + href, + children, + ...props + }: { + href: string + children: ReactNode + }) => ( + + {children} + + ), +})) + +jest.mock('@/components/ui/Modal', () => ({ + __esModule: true, + default: ({ + isOpen, + title, + children, + footer, + }: { + isOpen: boolean + title?: string + children: ReactNode + footer?: ReactNode + }) => + isOpen ? ( +
+
{children}
+
{footer}
+
+ ) : null, +})) + +jest.mock('@/components/ui/DeleteConfirmDialog', () => ({ + __esModule: true, + DeleteConfirmDialog: () => null, +})) + +jest.mock('@/lib/open-product/platform-api', () => ({ + __esModule: true, + createAssetFamily: jest.fn(), + createAssetVariant: jest.fn(), + updateAssetVariant: jest.fn(), + deleteAssetFamily: jest.fn(), + deleteAssetVariant: jest.fn(), +})) + +function createFamily(overrides?: Partial): AssetFamilyDTO { + return { + id: 'family-carton', + type: 'PACKAGING', + code: 'PACK-CARTON', + name: '纸箱业务类', + description: null, + productCategoryId: null, + productCategoryName: null, + applicableSeriesCodes: [], + connectionRoles: [], + metadata: { + categoryLevel1: 'outer', + categoryLevel2: 'carton', + }, + status: 'DRAFT', + createdBy: 'user-1', + creatorName: 'Test User', + workflow: { + submittedAt: null, + submittedById: null, + submittedByName: null, + reviewedAt: null, + reviewedById: null, + reviewedByName: null, + rejectedAt: null, + rejectedById: null, + rejectedByName: null, + rejectionReason: null, + lastModifiedById: null, + lastModifiedByName: null, + }, + createdAt: new Date('2026-04-02T10:00:00.000Z'), + updatedAt: new Date('2026-04-02T10:00:00.000Z'), + ...overrides, + } +} + +function createVariant(overrides?: Partial): AssetVariantDTO { + return { + id: 'variant-1', + assetFamilyId: 'family-carton', + assetFamilyCode: 'PACK-CARTON', + assetFamilyName: '纸箱业务类', + assetType: 'PACKAGING', + code: 'CTN-001', + name: 'Carton 001', + identityKey: 'packaging::variant-1', + status: 'DRAFT', + sizeLabel: null, + substrateId: null, + substrateCode: null, + substrateName: null, + finishId: null, + finishName: null, + dimensions: {}, + modelUrl: PACKAGING_PLACEHOLDER_MODEL_URL, + thumbnailUrl: null, + mountPoints: [{ name: 'origin', position: [0, 0, 0] }], + assemblyBasis: null, + compatibilityRules: null, + namingFields: null, + businessData: { + unit: 'piece', + templateFields: {}, + customAttributes: [], + }, + weightKg: null, + costPrice: null, + inheritedFromVariantId: null, + createdBy: 'user-1', + creatorName: 'Test User', + workflow: { + submittedAt: null, + submittedById: null, + submittedByName: null, + reviewedAt: null, + reviewedById: null, + reviewedByName: null, + rejectedAt: null, + rejectedById: null, + rejectedByName: null, + rejectionReason: null, + lastModifiedById: null, + lastModifiedByName: null, + }, + createdAt: new Date('2026-04-02T10:00:00.000Z'), + updatedAt: new Date('2026-04-02T10:00:00.000Z'), + ...overrides, + } +} + +const user = { + id: 'user-1', + name: 'Test User', + email: 'test@example.com', + role: 'SUPER_ADMIN', + avatar: null, + department: null, +} + +async function chooseOption( + actor: ReturnType, + label: string, + option: string, +) { + await actor.click(screen.getByRole('combobox', { name: label })) + await actor.click(screen.getByRole('option', { name: option })) +} + +describe('PackagingMaterialsClient workflow', () => { + it('新增包材时会先选择模板类型,再进入正式录入', async () => { + const actor = userEvent.setup() + + render( + , + ) + + await actor.click(screen.getByRole('button', { name: /新增包材/ })) + + expect(screen.getByText('请选择模板类型')).toBeInTheDocument() + expect(screen.queryByLabelText('编码')).not.toBeInTheDocument() + + await chooseOption(actor, '模板类型', '纸箱') + await actor.click(screen.getByRole('button', { name: /下一步:录入字段/ })) + + expect(screen.getByPlaceholderText('CTN-1200')).toBeInTheDocument() + expect(screen.getByText('计价长 × 计价宽 ÷ 1000000 × 平方米单价')).toBeInTheDocument() + }) + + it('已保存包材进入编辑后,模板类型会锁定展示', async () => { + const actor = userEvent.setup() + + render( + , + ) + + await actor.dblClick(screen.getByText('Carton 001')) + + expect(screen.getByText(/模板类型已锁定/)).toBeInTheDocument() + expect(screen.getAllByText('纸箱').length).toBeGreaterThan(0) + expect(screen.queryByRole('combobox', { name: '模板类型' })).not.toBeInTheDocument() + }) +})