feat: 完善包材模板录入与工作筛选

This commit is contained in:
Codex 2026-04-03 14:20:39 +08:00
parent 4fd184e513
commit f58a8d5d5f
3 changed files with 661 additions and 39 deletions

View File

@ -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(
<PackagingMaterialsClient
initialFamilies={[createFamily(), foamFamily]}
initialFamilies={[createFamily(), deskBoxFamily]}
initialVariants={[createVariant()]}
user={user}
/>,
@ -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(
<PackagingMaterialsClient
initialFamilies={[createFamily()]}
initialVariants={[
createVariant({
id: 'variant-missing-cost',
code: 'CTN-001',
name: 'Carton 001',
businessData: {
unit: 'piece',
templateType: 'carton',
pricingMethod: 'by_area',
pricingFormula: '计价长 × 计价宽 ÷ 1000000 × 平方米单价',
templateFields: {},
customAttributes: [],
},
}),
createVariant({
id: 'variant-ready',
code: 'TAPE-001',
name: 'Tape 001',
costPrice: 12,
businessData: {
unit: 'roll',
templateType: 'adhesiveTape',
pricingMethod: 'by_roll',
pricingFormula: '最终成本 = 单卷单价',
templateFields: { rollPrice: '12' },
customAttributes: [],
},
}),
]}
user={user}
/>,
)
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(
<PackagingMaterialsClient
initialFamilies={[createFamily()]}
initialVariants={[
createVariant({
businessData: {
unit: 'piece',
templateType: 'carton',
pricingMethod: 'by_area',
pricingFormula: '计价长 × 计价宽 ÷ 1000000 × 平方米单价',
templateFields: {},
customAttributes: [],
},
}),
]}
user={user}
/>,
)
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({

View File

@ -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<string, unknown>
const templateFields = (meta.templateFields ?? {}) as Record<string, string>
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<string, unknown>
const templateFields = (businessData.templateFields ?? {}) as Record<string, string>
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<string | null>(null)
const [searchQuery, setSearchQuery] = useState('')
const [statusFilter, setStatusFilter] = useState<string>('all')
const [workFilter, setWorkFilter] = useState<WorkFilter>('all')
const [selectedVariantId, setSelectedVariantId] = useState<string | null>(null)
const [editingMaterial, setEditingMaterial] = useState<EditingMaterial | null>(null)
const [isNew, setIsNew] = useState(false)
const [templateStarterCompleted, setTemplateStarterCompleted] = useState(false)
const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(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<PackagingTemplateDefinition | null>(
() =>
editingMaterial?.templateType
? PACKAGING_TEMPLATE_MAP.get(editingMaterial.templateType) ?? null
: null,
[editingMaterial],
)
const activeTemplateFields = useMemo<FieldTemplate[]>(
() => 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({
/>
</div>
<Select
label="状态筛选"
size="small"
value={statusFilter}
onChange={(e) => setStatusFilter(e.target.value)}
@ -729,6 +857,18 @@ export default function PackagingMaterialsClient({
{ value: 'DRAFT', label: '草稿' },
]}
/>
<Select
label="工作筛选"
size="small"
value={workFilter}
onChange={(e) => setWorkFilter(e.target.value as WorkFilter)}
options={[
{ value: 'all', label: '全部' },
{ value: 'missingCost', label: '只看缺成本' },
{ value: 'missingImage', label: '只看缺图片' },
{ value: 'draftOnly', label: '只看草稿' },
]}
/>
<span className="text-xs text-apple-label-tertiary shrink-0">{filteredVariants.length} 条</span>
</div>
@ -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<string, number>
const hasDims = dims.length || dims.width || dims.height || dims.thickness
@ -793,6 +934,11 @@ export default function PackagingMaterialsClient({
{level2Label}
</Badge>
)}
{template && (
<Badge type="info" variant="subtle" size="small">
{template.label}
</Badge>
)}
</div>
</div>
<Badge type={getStatusTone(variant.status)} variant="subtle" size="small">
@ -804,6 +950,9 @@ export default function PackagingMaterialsClient({
<span>{dims.length ?? 0} × {dims.width ?? 0} × {dims.height ?? 0} mm</span>
)}
{variant.costPrice != null && <span>¥{variant.costPrice}</span>}
{variant.costPrice == null && computedCost != null && (
<span>系统成本 ¥{computedCost.toFixed(2)}</span>
)}
{variant.weightKg != null && <span>{variant.weightKg} kg</span>}
</div>
{/* Hover 操作按钮 */}
@ -851,18 +1000,52 @@ export default function PackagingMaterialsClient({
<div
className="flex-1 min-w-0 overflow-y-auto bg-white/60"
>
{editingMaterial ? (
{showTemplateStarter && editingMaterial ? (
<TemplateStarter
family={currentFamily}
level1={currentLevel1}
templateType={editingMaterial.templateType}
error={error}
onTemplateChange={(templateType) =>
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 ? (
<DetailEditor
material={editingMaterial}
isNew={isNew}
saving={saving}
error={error}
templateFields={templateFields}
template={currentTemplate}
templateLocked={!isNew && Boolean(editingMaterial.id)}
templateFields={activeTemplateFields}
families={families}
currentLevel1={currentLevel1}
onChange={(patch) =>
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<string, number>
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<string, string>
const { template: templateDef, templateFields: templateFieldValues, computedCost } =
getVariantTemplateSnapshot(variant, family)
return (
<div className="p-4 space-y-4">
@ -1008,6 +1196,7 @@ function VariantPreview({
<div className="flex flex-wrap gap-1.5 text-xs text-apple-label-tertiary">
{level1Key && <Badge type="default" variant="subtle" size="small">{getLevel1Label(level1Key)}</Badge>}
{level2Key && <Badge type="info" variant="subtle" size="small">{getLevel2Label(level2Key)}</Badge>}
{templateDef && <Badge type="default" variant="subtle" size="small">{templateDef.label}</Badge>}
{unit && <Badge type="default" variant="subtle" size="small">{UNIT_OPTIONS.find(u => u.value === unit)?.label ?? unit}</Badge>}
</div>
</div>
@ -1042,13 +1231,16 @@ function VariantPreview({
</div>
)}
{(variant.costPrice != null || variant.weightKg != null) && (
{(variant.costPrice != null || computedCost != null || variant.weightKg != null) && (
<div>
<p className="text-[10px] font-apple-semibold text-apple-label-tertiary uppercase tracking-wider mb-2">成本</p>
<div className="grid grid-cols-2 gap-x-4 gap-y-1 text-xs">
{variant.costPrice != null && (
<div><span className="text-apple-label-tertiary">单价</span> <span className="text-apple-label-primary font-apple-medium">¥{variant.costPrice}</span></div>
)}
{variant.costPrice == null && computedCost != null && (
<div><span className="text-apple-label-tertiary">系统计算成本</span> <span className="text-apple-label-primary font-apple-medium">¥{computedCost.toFixed(2)}</span></div>
)}
{variant.weightKg != null && (
<div><span className="text-apple-label-tertiary">重量</span> <span className="text-apple-label-primary">{variant.weightKg} kg</span></div>
)}
@ -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 (
<div className="p-4 space-y-4">
<div className="flex items-center justify-between">
<h3 className="text-sm font-apple-semibold text-apple-label-primary">新增包材</h3>
<button onClick={onCancel} className="text-xs text-apple-label-tertiary hover:text-apple-label-secondary">
关闭
</button>
</div>
{error && (
<div className="rounded-apple-md border border-rose-200 bg-rose-50 px-3 py-2 text-xs text-rose-700">
{error}
</div>
)}
<div className="rounded-apple-lg border border-black/5 bg-apple-bg-secondary/60 px-4 py-4 space-y-3">
<div>
<p className="text-sm font-apple-semibold text-apple-label-primary">请选择模板类型</p>
<p className="mt-1 text-xs text-apple-label-tertiary">
先确定这条包材按哪种计价模板录入,后面字段和成本公式会跟着切换。
</p>
</div>
<div className="grid grid-cols-2 gap-2 text-xs">
<div>
<span className="text-apple-label-tertiary">一级分类</span>{' '}
<span className="text-apple-label-primary">{getLevel1Label(level1)}</span>
</div>
<div>
<span className="text-apple-label-tertiary">当前品类</span>{' '}
<span className="text-apple-label-primary">{family?.name ?? '未选择'}</span>
</div>
</div>
<Select
label="模板类型"
size="small"
value={templateType}
options={[
{ value: '', label: '请选择模板类型' },
...getTemplateOptionsForLevel1(level1),
]}
onChange={(e) => onTemplateChange(e.target.value as PackagingTemplateKey | '')}
/>
</div>
<div className="flex justify-end gap-2 pt-2 border-t border-black/5">
<Button variant="plain" size="small" onClick={onCancel}>
取消
</Button>
<Button size="small" onClick={onContinue}>
下一步:录入字段
</Button>
</div>
</div>
)
}
/* ============================================================
* DetailEditor
* ============================================================ */
@ -1094,10 +1367,14 @@ interface DetailEditorProps {
isNew: boolean
saving: boolean
error: string | null
template: PackagingTemplateDefinition | null
templateLocked: boolean
templateFields: FieldTemplate[]
families: AssetFamilyDTO[]
currentLevel1: Level1CategoryKey
onChange: (patch: Partial<EditingMaterial>) => void
onFamilyChange: (familyId: string) => void
onTemplateChange: (templateType: PackagingTemplateKey | '') => void
onTemplateFieldChange: (key: string, value: string) => void
onAddCustomAttribute: () => void
onUpdateCustomAttribute: (index: number, field: 'key' | 'value', value: string) => void
@ -1112,10 +1389,14 @@ function DetailEditor({
isNew,
saving,
error,
template,
templateLocked,
templateFields,
families,
currentLevel1,
onChange,
onFamilyChange,
onTemplateChange,
onTemplateFieldChange,
onAddCustomAttribute,
onUpdateCustomAttribute,
@ -1146,6 +1427,28 @@ function DetailEditor({
<Select label="所属品类" size="small" value={material.assetFamilyId}
options={families.map((f) => ({ value: f.id, label: f.name }))}
onChange={(e) => onFamilyChange(e.target.value)} />
{templateLocked ? (
<div className="rounded-apple-md border border-black/5 bg-apple-bg-secondary/50 px-3 py-2">
<p className="text-[10px] font-apple-semibold text-apple-label-tertiary uppercase tracking-wider">
模板类型
</p>
<p className="mt-1 text-sm text-apple-label-primary">{template?.label ?? '未设置'}</p>
<p className="mt-1 text-xs text-apple-label-tertiary">
模板类型已锁定,如选错请复制新增或删除后重建。
</p>
</div>
) : (
<Select
label="模板类型"
size="small"
value={material.templateType}
options={[
{ value: '', label: '请选择模板类型' },
...getTemplateOptionsForLevel1(currentLevel1),
]}
onChange={(e) => onTemplateChange(e.target.value as PackagingTemplateKey | '')}
/>
)}
<div className="grid grid-cols-2 gap-2">
<Input label="编码" size="small" value={material.code} onChange={(e) => onChange({ code: e.target.value })} placeholder="CTN-1200" />
<Input label="名称" size="small" value={material.name} onChange={(e) => onChange({ name: e.target.value })} placeholder="纸箱 1200" />
@ -1162,6 +1465,22 @@ function DetailEditor({
</div>
</section>
{template && (
<section className="space-y-2.5">
<p className="text-[10px] font-apple-semibold text-apple-label-tertiary uppercase tracking-wider">模板规则</p>
<div className="rounded-apple-md border border-black/5 bg-apple-bg-secondary/50 px-3 py-3 space-y-1.5">
<div className="text-xs">
<span className="text-apple-label-tertiary">模板名称</span>{' '}
<span className="text-apple-label-primary">{template.label}</span>
</div>
<div className="text-xs">
<span className="text-apple-label-tertiary">成本公式</span>{' '}
<span className="text-apple-label-primary">{template.pricingFormula}</span>
</div>
</div>
</section>
)}
<section className="space-y-2.5">
<p className="text-[10px] font-apple-semibold text-apple-label-tertiary uppercase tracking-wider">通用规格</p>
<div className="grid grid-cols-3 gap-2">

View File

@ -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
}) => (
<a href={href} {...props}>
{children}
</a>
),
}))
jest.mock('@/components/ui/Modal', () => ({
__esModule: true,
default: ({
isOpen,
title,
children,
footer,
}: {
isOpen: boolean
title?: string
children: ReactNode
footer?: ReactNode
}) =>
isOpen ? (
<div role="dialog" aria-label={title}>
<div>{children}</div>
<div>{footer}</div>
</div>
) : 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>): 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>): 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<typeof userEvent.setup>,
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(
<PackagingMaterialsClient
initialFamilies={[createFamily()]}
initialVariants={[]}
user={user}
/>,
)
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(
<PackagingMaterialsClient
initialFamilies={[createFamily()]}
initialVariants={[
createVariant({
businessData: {
unit: 'piece',
templateType: 'carton',
pricingMethod: 'by_area',
pricingFormula: '计价长 × 计价宽 ÷ 1000000 × 平方米单价',
templateFields: {
pricingLengthMm: '2000',
pricingWidthMm: '1000',
squareMeterPrice: '3',
},
customAttributes: [],
},
}),
]}
user={user}
/>,
)
await actor.dblClick(screen.getByText('Carton 001'))
expect(screen.getByText(/模板类型已锁定/)).toBeInTheDocument()
expect(screen.getAllByText('纸箱').length).toBeGreaterThan(0)
expect(screen.queryByRole('combobox', { name: '模板类型' })).not.toBeInTheDocument()
})
})