From d9b447847273bcdec56bc7fb90cd9938ea97fc7a Mon Sep 17 00:00:00 2001 From: Codex Date: Thu, 2 Apr 2026 15:30:15 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E5=8C=85=E6=9D=90=E8=B5=84=E6=96=99?= =?UTF-8?q?=E5=BA=93):=20=E5=9F=BA=E4=BA=8E=E6=96=B0=E4=B8=BB=E7=BA=BF?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=8C=85=E6=9D=90=E8=B5=84=E6=96=99=E5=BA=93?= =?UTF-8?q?=E7=8B=AC=E7=AB=8B=E9=A1=B5=E9=9D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 catalog.ts: 6个一级分类(含其他) + 20+二级品类模板 - 新增 /asset-center/packaging-materials 独立页面 - 四栏可拖拽布局: L1|L2|列表|详情 - 顶部统一工具栏: 新增/复制/启停/新建品类 - AssetCenterClient 包装tab添加"包材资料库"入口卡片 --- .../app/asset-center/AssetCenterClient.tsx | 15 + .../PackagingMaterialsClient.tsx | 1016 +++++++++++++++++ .../asset-center/packaging-materials/page.tsx | 23 + .../src/lib/packaging-materials/catalog.ts | 343 ++++++ 4 files changed, 1397 insertions(+) create mode 100644 furniture-3d-system/src/app/asset-center/packaging-materials/PackagingMaterialsClient.tsx create mode 100644 furniture-3d-system/src/app/asset-center/packaging-materials/page.tsx create mode 100644 furniture-3d-system/src/lib/packaging-materials/catalog.ts diff --git a/furniture-3d-system/src/app/asset-center/AssetCenterClient.tsx b/furniture-3d-system/src/app/asset-center/AssetCenterClient.tsx index 5b84d504..cd3de95c 100644 --- a/furniture-3d-system/src/app/asset-center/AssetCenterClient.tsx +++ b/furniture-3d-system/src/app/asset-center/AssetCenterClient.tsx @@ -571,6 +571,21 @@ export default function AssetCenterClient({ {/* 资产族列表 */}
+ {activeTab === 'PACKAGING' && ( + +
+ +
+

包材资料库

+

品类模板化管理 · 复制新增 · 启停控制

+
+
+ + + )} {currentFamilies.length === 0 ? (

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 new file mode 100644 index 00000000..30369695 --- /dev/null +++ b/furniture-3d-system/src/app/asset-center/packaging-materials/PackagingMaterialsClient.tsx @@ -0,0 +1,1016 @@ +'use client' + +import { useCallback, useMemo, useState, useRef } from 'react' +import Link from 'next/link' +import { Badge } from '@/components/ui/Badge' +import Button from '@/components/ui/Button' +import { Input, Textarea } from '@/components/ui/Input' +import Select from '@/components/ui/Select' +import { + Package2, + Plus, + Search, + ArrowLeft, + ChevronRight, + Copy, + ToggleLeft, + ToggleRight, + FolderPlus, +} from 'lucide-react' +import { cn } from '@/lib/utils' +import { + LEVEL1_CATEGORIES, + LEVEL2_CATEGORIES, + LEVEL2_MAP, + LEVEL2_BY_LEVEL1, + UNIT_OPTIONS, + MATERIAL_STATUS_OPTIONS, + getLevel1FromFamily, + getLevel2FromFamily, + getLevel1Label, + getLevel2Label, + type Level1CategoryKey, + type FieldTemplate, +} from '@/lib/packaging-materials/catalog' +import { + createAssetFamily, + createAssetVariant, + updateAssetVariant, +} from '@/lib/open-product/platform-api' +import type { AssetFamilyDTO, AssetVariantDTO } from '@/server/services' + +/* ============================================================ + * Types + * ============================================================ */ + +interface PackagingMaterialsClientProps { + initialFamilies: AssetFamilyDTO[] + initialVariants: AssetVariantDTO[] + user: { + id: string + name: string + email: string + role: string + avatar: string | null + department: { id: string; name: string } | null + } +} + +interface EditingMaterial { + id: string + assetFamilyId: string + code: string + name: string + status: string + sizeLabel: string + unit: string + length: string + width: string + height: string + thickness: string + weightKg: string + costPrice: string + materialType: string + templateFields: Record + customAttributes: { key: string; value: string }[] + notes: string + imageUrl: string +} + +/* ============================================================ + * Helpers + * ============================================================ */ + +function emptyEditingMaterial(familyId: string): EditingMaterial { + return { + id: '', + assetFamilyId: familyId, + code: '', + name: '', + status: 'DRAFT', + sizeLabel: '', + unit: 'piece', + length: '', + width: '', + height: '', + thickness: '', + weightKg: '', + costPrice: '', + materialType: '', + templateFields: {}, + customAttributes: [], + notes: '', + imageUrl: '', + } +} + +function variantToEditing(v: AssetVariantDTO): EditingMaterial { + const meta = (v.businessData ?? {}) as Record + const templateFields = (meta.templateFields ?? {}) as Record + const customAttributes = (meta.customAttributes ?? []) as { key: string; value: string }[] + const dims = (v.dimensions ?? {}) as Record + + return { + id: v.id, + assetFamilyId: v.assetFamilyId, + code: v.code, + name: v.name, + status: v.status, + sizeLabel: v.sizeLabel ?? '', + unit: (meta.unit as string) ?? 'piece', + length: String(dims.length ?? ''), + width: String(dims.width ?? ''), + height: String(dims.height ?? ''), + thickness: String(dims.thickness ?? ''), + weightKg: v.weightKg != null ? String(v.weightKg) : '', + costPrice: v.costPrice != null ? String(v.costPrice) : '', + materialType: (meta.materialType as string) ?? '', + templateFields, + customAttributes, + notes: (meta.notes as string) ?? '', + imageUrl: v.thumbnailUrl ?? '', + } +} + +function getStatusTone(status: string) { + if (status === 'AVAILABLE') return 'success' + if (status === 'DISABLED') return 'warning' + return 'default' +} + +function getStatusLabel(status: string) { + if (status === 'AVAILABLE') return '启用中' + if (status === 'DISABLED') return '停用中' + return '草稿' +} + +/* ============================================================ + * Drag-to-resize hook — supports N columns + * ============================================================ */ + +function useColumnResize(initialWidths: number[]) { + const [widths, setWidths] = useState(initialWidths) + const dragging = useRef<{ index: number; startX: number; startWidths: number[] } | null>(null) + + const onMouseDown = useCallback((index: number, e: React.MouseEvent) => { + e.preventDefault() + dragging.current = { index, startX: e.clientX, startWidths: [...widths] } + + const onMouseMove = (ev: MouseEvent) => { + if (!dragging.current) return + const dx = ev.clientX - dragging.current.startX + const i = dragging.current.index + setWidths((prev) => { + const next = [...prev] + const minW = 100 + next[i] = Math.max(minW, dragging.current!.startWidths[i] + dx) + if (i + 1 < next.length) { + next[i + 1] = Math.max(minW, dragging.current!.startWidths[i + 1] - dx) + } + return next + }) + } + + const onMouseUp = () => { + dragging.current = null + window.removeEventListener('mousemove', onMouseMove) + window.removeEventListener('mouseup', onMouseUp) + } + + window.addEventListener('mousemove', onMouseMove) + window.addEventListener('mouseup', onMouseUp) + }, [widths]) + + return { widths, onMouseDown } +} + +/* ============================================================ + * Resize Handle component + * ============================================================ */ + +function ResizeHandle({ onMouseDown }: { onMouseDown: (e: React.MouseEvent) => void }) { + return ( +

+ ) +} + +/* ============================================================ + * Main Client Component + * ============================================================ */ + +export default function PackagingMaterialsClient({ + initialFamilies, + initialVariants, + user, +}: PackagingMaterialsClientProps) { + const [families, setFamilies] = useState(initialFamilies) + const [variants, setVariants] = useState(initialVariants) + + const [selectedLevel1, setSelectedLevel1] = useState('outer') + const [selectedFamilyId, setSelectedFamilyId] = useState(null) + const [searchQuery, setSearchQuery] = useState('') + const [statusFilter, setStatusFilter] = useState('all') + const [selectedVariantId, setSelectedVariantId] = useState(null) + const [editingMaterial, setEditingMaterial] = useState(null) + const [isNew, setIsNew] = useState(false) + const [saving, setSaving] = useState(false) + const [error, setError] = useState(null) + const [showNewFamily, setShowNewFamily] = useState(false) + const [newFamilyName, setNewFamilyName] = useState('') + const [newFamilyCode, setNewFamilyCode] = useState('') + const [newFamilyLevel1, setNewFamilyLevel1] = useState('outer') + const [newFamilyLevel2, setNewFamilyLevel2] = useState('carton') + + // 4 resizable columns: [L1, L2, List, Detail] + const { widths: colWidths, onMouseDown: onColResize } = useColumnResize([140, 140, 400, 400]) + + // ---- Filtered data ---- + const filteredFamilies = useMemo(() => { + return families.filter((f) => getLevel1FromFamily(f.metadata) === selectedLevel1) + }, [families, selectedLevel1]) + + const filteredFamilyIds = useMemo( + () => new Set(filteredFamilies.map((f) => f.id)), + [filteredFamilies], + ) + + const l2Categories = useMemo( + () => LEVEL2_BY_LEVEL1[selectedLevel1] ?? [], + [selectedLevel1], + ) + + const filteredVariants = useMemo(() => { + let result = variants.filter((v) => filteredFamilyIds.has(v.assetFamilyId)) + if (selectedFamilyId) { + result = result.filter((v) => v.assetFamilyId === selectedFamilyId) + } + if (searchQuery.trim()) { + const q = searchQuery.trim().toLowerCase() + result = result.filter( + (v) => v.name.toLowerCase().includes(q) || v.code.toLowerCase().includes(q), + ) + } + if (statusFilter !== 'all') { + result = result.filter((v) => v.status === statusFilter) + } + return result + }, [variants, filteredFamilyIds, selectedFamilyId, searchQuery, statusFilter]) + + // ---- Template for current family ---- + const currentFamily = useMemo( + () => families.find((f) => f.id === editingMaterial?.assetFamilyId) ?? null, + [families, editingMaterial], + ) + + const templateFields = useMemo(() => { + const level2Key = getLevel2FromFamily(currentFamily?.metadata ?? null) + return level2Key ? (LEVEL2_MAP.get(level2Key)?.fields ?? []) : [] + }, [currentFamily]) + + // ---- Stats ---- + const stats = useMemo(() => { + const enabled = variants.filter((v) => v.status === 'AVAILABLE').length + return { total: variants.length, enabled, families: families.length } + }, [variants, families]) + + // ---- Handlers ---- + const handleNew = useCallback( + (familyId?: string) => { + const fid = familyId ?? filteredFamilies[0]?.id ?? families[0]?.id + if (!fid) return + setEditingMaterial(emptyEditingMaterial(fid)) + setIsNew(true) + setError(null) + }, + [filteredFamilies, families], + ) + + const handleEdit = useCallback((variant: AssetVariantDTO) => { + setEditingMaterial(variantToEditing(variant)) + setIsNew(false) + setError(null) + }, []) + + const handleCopyNew = useCallback((variant: AssetVariantDTO) => { + const editing = variantToEditing(variant) + editing.id = '' + editing.code = '' + editing.name = `${editing.name} (副本)` + setEditingMaterial(editing) + setIsNew(true) + setError(null) + }, []) + + const handleSave = useCallback(async () => { + if (!editingMaterial) return + if (!editingMaterial.name.trim()) { setError('包材名称不能为空'); return } + if (!editingMaterial.code.trim()) { setError('包材编码不能为空'); return } + + setSaving(true) + setError(null) + + try { + const dimensions: Record = {} + if (editingMaterial.length) dimensions.length = Number(editingMaterial.length) || 0 + if (editingMaterial.width) dimensions.width = Number(editingMaterial.width) || 0 + if (editingMaterial.height) dimensions.height = Number(editingMaterial.height) || 0 + if (editingMaterial.thickness) dimensions.thickness = Number(editingMaterial.thickness) || 0 + + const businessData = { + unit: editingMaterial.unit, + materialType: editingMaterial.materialType || undefined, + templateFields: editingMaterial.templateFields, + customAttributes: editingMaterial.customAttributes.filter( + (a) => a.key.trim() && a.value.trim(), + ), + notes: editingMaterial.notes || undefined, + } + + const weightKg = editingMaterial.weightKg ? Number(editingMaterial.weightKg) : null + const costPrice = editingMaterial.costPrice ? Number(editingMaterial.costPrice) : null + + if (isNew) { + const created = await createAssetVariant({ + assetFamilyId: editingMaterial.assetFamilyId, + code: editingMaterial.code.trim(), + name: editingMaterial.name.trim(), + status: editingMaterial.status as 'DRAFT' | 'AVAILABLE' | 'DISABLED', + sizeLabel: editingMaterial.sizeLabel || undefined, + dimensions, + modelUrl: '', + thumbnailUrl: editingMaterial.imageUrl || undefined, + mountPoints: [{ name: 'origin', position: [0, 0, 0] }], + weightKg, + costPrice, + businessData, + }) + setVariants((prev) => [created, ...prev]) + setSelectedVariantId(created.id) + } else { + const updated = await updateAssetVariant(editingMaterial.id, { + name: editingMaterial.name.trim(), + code: editingMaterial.code.trim(), + status: editingMaterial.status as 'DRAFT' | 'AVAILABLE' | 'DISABLED', + sizeLabel: editingMaterial.sizeLabel || undefined, + dimensions, + weightKg, + costPrice, + businessData, + thumbnailUrl: editingMaterial.imageUrl || undefined, + }) + setVariants((prev) => prev.map((v) => (v.id === updated.id ? updated : v))) + } + + setEditingMaterial(null) + setIsNew(false) + } catch (saveError) { + setError(saveError instanceof Error ? saveError.message : '保存失败') + } finally { + setSaving(false) + } + }, [editingMaterial, isNew]) + + const handleCreateFamily = useCallback(async () => { + if (!newFamilyName.trim() || !newFamilyCode.trim()) return + setSaving(true) + setError(null) + try { + const created = await createAssetFamily({ + type: 'PACKAGING' as const, + code: newFamilyCode.trim(), + name: newFamilyName.trim(), + metadata: { + categoryLevel1: newFamilyLevel1, + categoryLevel2: newFamilyLevel2, + }, + }) + setFamilies((prev) => [...prev, created]) + setShowNewFamily(false) + setNewFamilyName('') + setNewFamilyCode('') + } catch (err) { + setError(err instanceof Error ? err.message : '创建品类失败') + } finally { + setSaving(false) + } + }, [newFamilyName, newFamilyCode, newFamilyLevel1, newFamilyLevel2]) + + const handleToggleStatus = useCallback( + async (variant: AssetVariantDTO) => { + const newStatus = variant.status === 'AVAILABLE' ? 'DISABLED' : 'AVAILABLE' + try { + const updated = await updateAssetVariant(variant.id, { status: newStatus }) + setVariants((prev) => prev.map((v) => (v.id === updated.id ? updated : v))) + } catch { + /* ignore */ + } + }, + [], + ) + + const selectedVariant = useMemo( + () => variants.find((v) => v.id === selectedVariantId) ?? null, + [variants, selectedVariantId], + ) + + return ( +
+ {/* ====== Top Header & Toolbar ====== */} +
+
+
+ + + 资产中心 + + +
+ +

包材资料库

+
+
+ +
+
+ {stats.families} 品类 + {stats.total} 档案 + {stats.enabled} 启用 +
+ + + + +
+
+
+ + {/* ====== Four-column body ====== */} +
+ {/* Column 1: L1 */} +
+
+

+ 一级分类 +

+ {LEVEL1_CATEGORIES.map((cat) => { + const count = variants.filter((v) => { + const fam = families.find((f) => f.id === v.assetFamilyId) + return fam && getLevel1FromFamily(fam.metadata) === cat.key + }).length + return ( + + ) + })} +
+
+ + onColResize(0, e)} /> + + {/* Column 2: L2 */} +
+
+

+ 二级品类 +

+ {l2Categories.map((cat) => { + const matchingFamilies = filteredFamilies.filter( + (f) => getLevel2FromFamily(f.metadata) === cat.key, + ) + const isActive = selectedFamilyId + ? matchingFamilies.some((f) => f.id === selectedFamilyId) + : false + const count = variants.filter((v) => + matchingFamilies.some((f) => f.id === v.assetFamilyId), + ).length + + return ( + + ) + })} + {l2Categories.length === 0 && ( +

+ 请先选择一级分类 +

+ )} +
+
+ + onColResize(1, e)} /> + + {/* Column 3: Material List */} +
+ {/* Search bar */} +
+
+ + setSearchQuery(e.target.value)} + placeholder="搜索编码或名称..." + className="w-full rounded-apple-md border border-black/10 bg-white/80 pl-8 pr-3 py-1.5 text-sm placeholder:text-apple-label-tertiary focus:outline-none focus:ring-1 focus:ring-apple-blue/40" + /> +
+ ({ value: c.key, label: c.label }))} + onChange={(e) => { + const key = e.target.value as Level1CategoryKey + setNewFamilyLevel1(key) + setNewFamilyLevel2(LEVEL2_BY_LEVEL1[key]?.[0]?.key ?? 'carton') + }} + /> + setNewFamilyCode(e.target.value)} placeholder="如 CARTON" /> + setNewFamilyName(e.target.value)} placeholder="如 纸箱" /> +
+
+ + +
+
+
+ )} +
+ ) +} + +/* ============================================================ + * VariantPreview + * ============================================================ */ + +function VariantPreview({ + variant, + family, + onEdit, + onCopy, + onToggleStatus, +}: { + variant: AssetVariantDTO + family: AssetFamilyDTO | null + onEdit: () => void + onCopy: () => void + onToggleStatus: () => void +}) { + const meta = (variant.businessData ?? {}) as Record + const unit = meta.unit as string | undefined + 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 + + return ( +
+
+

包材详情

+
+ + +
+
+ +
+

{variant.name}

+
+ {variant.code} + {getStatusLabel(variant.status)} +
+
+ {level1Key && {getLevel1Label(level1Key)}} + {level2Key && {getLevel2Label(level2Key)}} + {unit && {UNIT_OPTIONS.find(u => u.value === unit)?.label ?? unit}} +
+
+ + {(dims.length || dims.width || dims.height || dims.thickness) ? ( +
+

规格

+
+ {dims.length ?
长 {dims.length} mm
: null} + {dims.width ?
宽 {dims.width} mm
: null} + {dims.height ?
高 {dims.height} mm
: null} + {dims.thickness ?
厚度 {dims.thickness} mm
: null} +
+
+ ) : null} + + {templateDef && templateDef.fields.length > 0 && ( +
+

品类属性

+
+ {templateDef.fields.map((field) => { + const val = templateFieldValues[field.key] + if (!val) return null + return ( +
+ {field.label}{' '} + {val}{field.unit ? ` ${field.unit}` : ''} +
+ ) + })} +
+
+ )} + + {(variant.costPrice != null || variant.weightKg != null) && ( +
+

成本

+
+ {variant.costPrice != null && ( +
单价 ¥{variant.costPrice}
+ )} + {variant.weightKg != null && ( +
重量 {variant.weightKg} kg
+ )} +
+
+ )} + +
+ + +
+
+ ) +} + +/* ============================================================ + * DetailEditor + * ============================================================ */ + +interface DetailEditorProps { + material: EditingMaterial + isNew: boolean + saving: boolean + error: string | null + templateFields: FieldTemplate[] + families: AssetFamilyDTO[] + onChange: (patch: Partial) => void + onTemplateFieldChange: (key: string, value: string) => void + onAddCustomAttribute: () => void + onUpdateCustomAttribute: (index: number, field: 'key' | 'value', value: string) => void + onRemoveCustomAttribute: (index: number) => void + onSave: () => void + onCancel: () => void +} + +function DetailEditor({ + material, + isNew, + saving, + error, + templateFields, + families, + onChange, + onTemplateFieldChange, + onAddCustomAttribute, + onUpdateCustomAttribute, + onRemoveCustomAttribute, + onSave, + onCancel, +}: DetailEditorProps) { + return ( +
+
+

+ {isNew ? '新增包材' : '编辑包材'} +

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

基础信息

+ onChange({ code: e.target.value })} placeholder="CTN-1200" /> + onChange({ name: e.target.value })} placeholder="纸箱 1200" /> +
+
+ ({ value: s.value, label: s.label }))} + onChange={(e) => onChange({ status: e.target.value })} /> +
+ + +
+

通用规格

+
+ onChange({ length: e.target.value })} /> + onChange({ width: e.target.value })} /> + onChange({ height: e.target.value })} /> +
+
+ onChange({ thickness: e.target.value })} /> + onChange({ weightKg: e.target.value })} /> + onChange({ materialType: e.target.value })} placeholder="瓦楞纸" /> +
+
+ + {templateFields.length > 0 && ( +
+

品类规格

+
+ {templateFields.map((field) => ( + onTemplateFieldChange(field.key, value)} /> + ))} +
+
+ )} + +
+

成本

+
+ onChange({ costPrice: e.target.value })} /> + onChange({ sizeLabel: e.target.value })} placeholder="1200x600" /> +
+
+ +
+
+

自定义属性

+ +
+ {material.customAttributes.map((attr, index) => ( +
+ onUpdateCustomAttribute(index, 'key', e.target.value)} placeholder="属性名" /> + onUpdateCustomAttribute(index, 'value', e.target.value)} placeholder="属性值" /> + +
+ ))} +
+ +