diff --git a/furniture-3d-system/src/app/api/asset-center/packaging-variants/route.ts b/furniture-3d-system/src/app/api/asset-center/packaging-variants/route.ts new file mode 100644 index 00000000..514648ba --- /dev/null +++ b/furniture-3d-system/src/app/api/asset-center/packaging-variants/route.ts @@ -0,0 +1,46 @@ +import { NextRequest } from 'next/server' +import { AppError, ErrorCode } from '@/server/core/errors' +import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' +import { assetCenterService } from '@/server/services' +import { packagingAssetVariantCreateSchema } from '../../platform/schemas' + +export async function POST(request: NextRequest) { + return handleRequest( + request, + async (ctx) => { + const rawBody = await request.json().catch(() => null) + const parsed = packagingAssetVariantCreateSchema.safeParse(rawBody) + if (!parsed.success) { + return jsonError( + ErrorCode.VALIDATION_FAILED, + `包材货号参数不正确: ${parsed.error.message}`, + 400, + ctx.requestId, + ) + } + + try { + const packagingFamilies = await assetCenterService.listFamilies({ + type: 'PACKAGING', + }) + if (!packagingFamilies.some((family) => family.id === parsed.data.assetFamilyId)) { + throw new AppError(ErrorCode.VALIDATION_FAILED, '包材货号只能创建在包装资产族下') + } + + const result = await assetCenterService.createVariantWithSimilarity({ + ...parsed.data, + createdBy: ctx.user.id, + }, { + skipThumbnail: true, + }) + return jsonSuccess(result, 201, ctx.requestId) + } catch (error) { + if (error instanceof AppError) { + return jsonError(error.code, error.message, error.statusCode, ctx.requestId) + } + throw error + } + }, + { requireAuth: true, requireDesignWorkspaceWrite: true }, + ) +} diff --git a/furniture-3d-system/src/app/api/asset-center/series/[id]/component-detail/route.ts b/furniture-3d-system/src/app/api/asset-center/series/[id]/component-detail/route.ts new file mode 100644 index 00000000..84907e1d --- /dev/null +++ b/furniture-3d-system/src/app/api/asset-center/series/[id]/component-detail/route.ts @@ -0,0 +1,29 @@ +import { NextRequest } from 'next/server' +import { AppError } from '@/server/core/errors' +import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' +import { assetCenterService } from '@/server/services' + +export async function POST( + request: NextRequest, + context: { params: Promise<{ id: string }> }, +) { + return handleRequest( + request, + async (ctx) => { + const { id } = await context.params + + try { + const componentDetail = + await assetCenterService.ensureSeriesComponentDetailProduct(id, ctx.user) + + return jsonSuccess({ componentDetail }, 200, ctx.requestId) + } catch (error) { + if (error instanceof AppError) { + return jsonError(error.code, error.message, error.statusCode, ctx.requestId) + } + throw error + } + }, + { requireAuth: true, requireDesignWorkspaceWrite: true }, + ) +} diff --git a/furniture-3d-system/src/app/api/intake/non-integrated/route.ts b/furniture-3d-system/src/app/api/intake/non-integrated/route.ts index 21641e68..9004d172 100644 --- a/furniture-3d-system/src/app/api/intake/non-integrated/route.ts +++ b/furniture-3d-system/src/app/api/intake/non-integrated/route.ts @@ -31,6 +31,7 @@ function readListParams(request: NextRequest): IntakeNonIntegratedProductListPar : searchParams.get('quickScope') === 'pending' ? 'pending' : 'all', + seriesName: searchParams.get('seriesName') ?? '', spu: searchParams.get('spu') ?? '', appearanceDesigner: searchParams.get('appearanceDesigner') ?? '', structureDesigner: searchParams.get('structureDesigner') ?? '', diff --git a/furniture-3d-system/src/app/api/platform/schemas.test.ts b/furniture-3d-system/src/app/api/platform/schemas.test.ts new file mode 100644 index 00000000..c286bcb6 --- /dev/null +++ b/furniture-3d-system/src/app/api/platform/schemas.test.ts @@ -0,0 +1,33 @@ +import { + assetVariantCreateSchema, + packagingAssetVariantCreateSchema, +} from './schemas' + +describe('asset variant API schemas', () => { + const basePayload = { + assetFamilyId: 'family-packaging', + name: '纸箱 60/40/20 黑色', + status: 'DRAFT', + dimensions: {}, + modelUrl: '', + mountPoints: [], + businessData: { + materialMode: 'PACKAGING', + }, + } as const + + it('普通规格款创建仍要求模型地址', () => { + expect(assetVariantCreateSchema.safeParse(basePayload).success).toBe(false) + }) + + it('包材货号创建允许无模型和空挂载点', () => { + const parsed = packagingAssetVariantCreateSchema.safeParse(basePayload) + + expect(parsed.success).toBe(true) + if (parsed.success) { + expect(parsed.data.modelUrl).toBe('') + expect(parsed.data.mountPoints).toEqual([]) + expect(parsed.data.lossFactor).toBeNull() + } + }) +}) diff --git a/furniture-3d-system/src/app/api/platform/schemas.ts b/furniture-3d-system/src/app/api/platform/schemas.ts index 85ebcc32..744af71a 100644 --- a/furniture-3d-system/src/app/api/platform/schemas.ts +++ b/furniture-3d-system/src/app/api/platform/schemas.ts @@ -38,6 +38,11 @@ const assetVariantUvConfigSchema = z.object({ version: z.literal(1), nodes: z.record(z.string(), assetVariantNodeUvConfigSchema), }) satisfies z.ZodType +const assetVariantMountPointSchema = z.object({ + name: z.string().trim().min(1), + position: vector3Schema, + rotation: vector3Schema.optional(), +}) export const assetFamilyCreateSchema = z.object({ type: z.enum(['BOARD', 'COMPONENT', 'HARDWARE', 'PACKAGING']), @@ -97,13 +102,7 @@ export const assetVariantCreateSchema = z.object({ supplierCode: z.string().trim().optional().nullable(), versionNo: z.string().trim().optional().nullable(), barcode: z.string().trim().optional().nullable(), - mountPoints: z.array( - z.object({ - name: z.string().trim().min(1), - position: vector3Schema, - rotation: vector3Schema.optional(), - }), - ), + mountPoints: z.array(assetVariantMountPointSchema), assemblyBasis: z.record(z.string(), z.unknown()).optional().nullable(), compatibilityRules: z.record(z.string(), z.unknown()).optional().nullable(), namingFields: z.record(z.string(), z.unknown()).optional().nullable(), @@ -116,6 +115,12 @@ export const assetVariantCreateSchema = z.object({ inheritedFromVariantId: z.string().trim().min(1).optional().nullable(), }) +export const packagingAssetVariantCreateSchema = assetVariantCreateSchema.extend({ + modelUrl: z.string().trim().optional().default(''), + mountPoints: z.array(assetVariantMountPointSchema).optional().default([]), + lossFactor: z.number().positive().optional().nullable().default(null), +}) + export const assetVariantUpdateSchema = z.object({ assetFamilyId: z.string().trim().min(1).optional(), code: z.string().trim().min(1).optional(), @@ -132,13 +137,7 @@ export const assetVariantUpdateSchema = z.object({ versionNo: z.string().trim().optional().nullable(), barcode: z.string().trim().optional().nullable(), mountPoints: z - .array( - z.object({ - name: z.string().trim().min(1), - position: vector3Schema, - rotation: vector3Schema.optional(), - }), - ) + .array(assetVariantMountPointSchema) .optional(), assemblyBasis: z.record(z.string(), z.unknown()).optional().nullable(), compatibilityRules: z.record(z.string(), z.unknown()).optional().nullable(), diff --git a/furniture-3d-system/src/app/asset-center/AssetCenterClient.test.tsx b/furniture-3d-system/src/app/asset-center/AssetCenterClient.test.tsx index b5ad068f..bec90fce 100644 --- a/furniture-3d-system/src/app/asset-center/AssetCenterClient.test.tsx +++ b/furniture-3d-system/src/app/asset-center/AssetCenterClient.test.tsx @@ -11,6 +11,7 @@ import type { } from '@/server/services' import { createAssetVariantWithSimilarity, + createPackagingAssetVariant, regenerateAssetVariantThumbnail, updateAssetVariant, } from '@/lib/open-product/platform-api' @@ -31,6 +32,10 @@ jest.mock('next/link', () => ({ ), })) +jest.mock('next/navigation', () => ({ + useRouter: () => ({ push: jest.fn() }), +})) + jest.mock('@/components/ui/Modal', () => ({ __esModule: true, default: ({ @@ -205,6 +210,7 @@ jest.mock('@/lib/open-product/platform-api', () => ({ createAssetFamily: jest.fn(), createAssetVariant: jest.fn(), createAssetVariantWithSimilarity: jest.fn(), + createPackagingAssetVariant: jest.fn(), createSubstrate: jest.fn(), deleteAssetFamily: jest.fn(), deleteAssetVariant: jest.fn(), @@ -227,6 +233,10 @@ const mockedCreateAssetVariantWithSimilarity = createAssetVariantWithSimilarity as jest.MockedFunction< typeof createAssetVariantWithSimilarity > +const mockedCreatePackagingAssetVariant = + createPackagingAssetVariant as jest.MockedFunction< + typeof createPackagingAssetVariant + > function createFamily(overrides?: Partial): AssetFamilyDTO { return { @@ -378,6 +388,7 @@ describe('AssetCenterClient', () => { mockedRegenerateAssetVariantThumbnail.mockReset() mockedUpdateAssetVariant.mockReset() mockedCreateAssetVariantWithSimilarity.mockReset() + mockedCreatePackagingAssetVariant.mockReset() }) it('草稿资产在列表里不显示草稿状态,但仍保留提审操作', () => { @@ -539,7 +550,7 @@ describe('AssetCenterClient', () => { expect(screen.getByRole('button', { name: '提审' })).toBeInTheDocument() }) - it('包装页保留包材资料库入口,但不重复展示包材资料库里的业务分类卡片', async () => { + it('包装页不展示包材资料库入口,也不重复展示包材资料库里的业务分类卡片', async () => { const actor = userEvent.setup() render( @@ -567,11 +578,137 @@ describe('AssetCenterClient', () => { await actor.click(screen.getByRole('button', { name: /包装/ })) - expect(screen.getByText('包材资料库')).toBeInTheDocument() + expect(screen.queryByText('包材资料库')).not.toBeInTheDocument() expect(screen.getByText('运输包装族')).toBeInTheDocument() expect(screen.queryByText('大桌外箱')).not.toBeInTheDocument() }) + it('包装资产族新增规格款时允许无模型创建包材货号', async () => { + const actor = userEvent.setup() + + mockedCreatePackagingAssetVariant.mockResolvedValue({ + variant: createBoardVariant({ + id: 'variant-packaging-new', + assetFamilyId: 'family-packaging', + assetFamilyCode: 'DBZ-SPJK04', + assetFamilyName: '纸箱资产族', + assetType: 'PACKAGING', + code: 'DBZ-SPJ01', + name: '款式四 120/120/6 纸箱', + identityKey: 'PACKAGING|code=DBZ-SPJ01', + status: 'DRAFT', + sizeLabel: null, + substrateId: null, + substrateCode: null, + substrateName: null, + finishId: null, + finishName: null, + dimensions: {}, + modelUrl: '', + thumbnailUrl: null, + mountPoints: [], + businessData: { + materialMode: 'PACKAGING', + skuContentFields: { + specName: '款式四 120/120/6 纸箱', + material: '瓦楞纸', + }, + }, + }), + similarCandidates: [], + similarityNotice: null, + }) + + render( + , + ) + + await actor.click(screen.getByRole('button', { name: /包装/ })) + await actor.click(screen.getByText('纸箱资产族')) + await actor.click(screen.getByRole('button', { name: /新增包材货号/ })) + + expect(screen.getByRole('dialog', { name: '新增包材货号' })).toBeInTheDocument() + expect(screen.getByDisplayValue('DBZ-SPJ01')).toBeInTheDocument() + await actor.type(screen.getByLabelText('供应商名称'), '兰考华兰家具') + await waitFor(() => { + expect(screen.getByDisplayValue('N1280')).toBeInTheDocument() + expect(screen.getByDisplayValue('DBZ-SPJ01N1280V01')).toBeInTheDocument() + }) + expect(screen.queryByText('ModelUploader')).not.toBeInTheDocument() + expect(screen.queryByText('模型与装配参数')).not.toBeInTheDocument() + expect(screen.queryByText('3D 模型')).not.toBeInTheDocument() + expect(screen.queryByText('板材类型')).not.toBeInTheDocument() + expect(screen.getByText('包材资料')).toBeInTheDocument() + expect(screen.getByLabelText('颜色')).not.toHaveAttribute('readonly') + expect(screen.getByLabelText('材质')).not.toHaveAttribute('readonly') + + await actor.type(screen.getByLabelText('长度'), '1200') + await actor.type(screen.getByLabelText('宽度'), '1200') + await actor.type(screen.getByLabelText('厚度'), '60') + await actor.type(screen.getByLabelText('颜色'), '纸箱') + await actor.type(screen.getByLabelText('材质'), '瓦楞纸') + await waitFor(() => { + expect(screen.getByLabelText('规格名称')).toHaveValue('款式四 120/120/6 纸箱') + }) + await actor.click(screen.getByRole('button', { name: '创建包材货号' })) + + await waitFor(() => { + expect(mockedCreatePackagingAssetVariant).toHaveBeenCalled() + }) + + const payload = mockedCreatePackagingAssetVariant.mock.calls[0]?.[0] + expect(payload).toEqual(expect.objectContaining({ + code: 'DBZ-SPJ01', + supplierName: '兰考华兰家具', + supplierCode: 'N1280', + barcode: 'DBZ-SPJ01N1280V01', + })) + expect(payload).toEqual( + expect.objectContaining({ + assetFamilyId: 'family-packaging', + name: '款式四 120/120/6 纸箱', + status: 'DRAFT', + dimensions: { + length: 1200, + width: 1200, + thickness: 60, + }, + modelUrl: '', + mountPoints: [], + lossFactor: null, + }), + ) + expect(payload?.businessData).toEqual( + expect.objectContaining({ + materialMode: 'PACKAGING', + skuContentFields: expect.objectContaining({ + model: 'DBZ-SPJK04', + skuCode: 'DBZ-SPJ01', + barcode: 'DBZ-SPJ01N1280V01', + specName: '款式四 120/120/6 纸箱', + color: '纸箱', + material: '瓦楞纸', + }), + }), + ) + }) + it('提供待审核筛选,提审后的资产可以集中查看', async () => { const actor = userEvent.setup() @@ -978,16 +1115,13 @@ describe('AssetCenterClient', () => { await actor.click(screen.getByRole('button', { name: '保存' })) const duplicateDialog = within(screen.getByRole('dialog', { name: '另存为新规格款' })) - expect(duplicateDialog.getByLabelText('编码')).toHaveValue('BOARD-030-A') - expect(duplicateDialog.getByPlaceholderText('例如 桌面板 1200 白橡')).toHaveValue('UV 桌面板 A') - expect(duplicateDialog.getByLabelText('尺寸标签')).toHaveValue('1200x600x18') - expect(duplicateDialog.getByLabelText('尺寸标签')).toBeDisabled() + expect(duplicateDialog.getByLabelText('货号')).toHaveValue('') + expect(duplicateDialog.getByLabelText('规格名称')).toHaveValue('UV 桌面板 A 120/60/1.8 胡桃木纹') + expect(duplicateDialog.getByLabelText('尺寸')).toHaveValue('120/60/1.8') expect(duplicateDialog.getByLabelText('长度')).toBeDisabled() expect(duplicateDialog.getByLabelText('宽度')).toBeDisabled() expect(duplicateDialog.getByLabelText('厚度')).toBeDisabled() - await actor.clear(duplicateDialog.getByLabelText('编码')) - await actor.type(duplicateDialog.getByLabelText('编码'), 'BOARD-030-B') await actor.click(screen.getByRole('button', { name: '另存为新规格款' })) expect(mockedCreateAssetVariantWithSimilarity).toHaveBeenCalledWith( @@ -1019,6 +1153,7 @@ describe('AssetCenterClient', () => { operationId: expect.stringMatching(/^variant-save-/), }), ) + expect(mockedCreateAssetVariantWithSimilarity.mock.calls[0]?.[0]).not.toHaveProperty('code') await waitFor(() => { expect(screen.getByText(/UV 桌面板 B/)).toBeInTheDocument() diff --git a/furniture-3d-system/src/app/asset-center/AssetCenterClient.tsx b/furniture-3d-system/src/app/asset-center/AssetCenterClient.tsx index e612732a..97cd16de 100644 --- a/furniture-3d-system/src/app/asset-center/AssetCenterClient.tsx +++ b/furniture-3d-system/src/app/asset-center/AssetCenterClient.tsx @@ -1,7 +1,18 @@ 'use client' -import { startTransition, useState, useMemo, useCallback, useEffect, useRef } from 'react' +import { + startTransition, + useState, + useMemo, + useCallback, + useEffect, + useRef, + type PointerEvent as ReactPointerEvent, + type ReactNode, +} from 'react' +import { createPortal } from 'react-dom' import Link from 'next/link' +import { useRouter } from 'next/navigation' import { ArrowRight, ChevronDown, @@ -25,6 +36,21 @@ import Checkbox from '@/components/ui/Checkbox' import Input, { Textarea } from '@/components/ui/Input' import Modal from '@/components/ui/Modal' import Select from '@/components/ui/Select' +import type { SeriesDraftSkuFields } from '@/app/intake/seriesComponentDetails' +import { EXECUTION_STANDARD_OPTIONS } from '@/app/intake/non-integrated/executionStandardDirectory' +import { + buildNonIntegratedBomSteelFrameOptions, + type NonIntegratedBomSteelFrameOption, +} from '@/lib/non-integrated-bom-steel-materials' +import { + buildNonIntegratedBomPackagingMaterialOptions, + PACKAGING_MATERIAL_LIBRARY_CHANGED_EVENT, + type NonIntegratedBomPackagingMaterialOption, +} from '@/lib/packaging-material-library' +import { + SUPPLIER_CODE_BY_NAME, + SUPPLIER_DIRECTORY, +} from '@/app/intake/non-integrated/supplierDirectory' import { calculateMenuPosition, ContextMenu, @@ -64,6 +90,12 @@ import { normalizeAssetVariantWithUv, normalizeAssetVariantsWithUv, } from '@/lib/open-product/asset-variant-uv' +import { + buildAssetVariantCode, + buildAssetVariantBarcode, + DEFAULT_SKU_VERSION_NO, + normalizeSkuVersionNo, +} from '@/lib/open-product/asset-coding' import { calculateEstimatedCost } from '@/lib/open-product/substrate-rules' import { getLevel1FromFamily } from '@/lib/packaging-materials/catalog' import { canOperateDesignWorkspace as canOperateDesignWorkspaceForUser } from '@/lib/role-scope' @@ -71,10 +103,13 @@ import { cn } from '@/lib/utils' import { createAssetFamily, createAssetVariantWithSimilarity, + createPackagingAssetVariant, deleteAssetFamily, deleteAssetVariant, + ensureAssetSeriesComponentDetail, getAssetOperationProgress, importAssetCad, + listAssetFamilies, regenerateAssetVariantThumbnail, reviewAssetFamily, reviewAssetVariant, @@ -90,7 +125,9 @@ import type { AssetCadImportResult, AssetFamilyDTO, AssetOperationProgressDTO, + AssetSeriesComponentDetailSummaryDTO, AssetSeriesDTO, + MaterialLikeDTO, SimilarAssetVariantCandidateDTO, AssetVariantDTO, SubstrateDTO, @@ -105,6 +142,7 @@ interface AssetCenterClientProps { initialSubstrates: SubstrateDTO[] initialSubstrateDictionaries?: SubstrateDictionaryBundleDTO initialAssetSeries: AssetSeriesDTO[] + initialSeriesComponentDetails?: AssetSeriesComponentDetailSummaryDTO[] finishes: MaterialDTO[] materialCategories: MaterialCategoryDTO[] metrics: PlatformMetricItem[] @@ -169,6 +207,28 @@ function sortByName(items: T[]): T[] { return [...items].sort((left, right) => left.name.localeCompare(right.name, 'zh-CN')) } +function getSortableTime(value: Date | string | null | undefined): number { + if (!value) return 0 + const time = value instanceof Date ? value.getTime() : new Date(value).getTime() + return Number.isFinite(time) ? time : 0 +} + +function sortByCreatedDesc(items: T[]): T[] { + return [...items].sort((left, right) => { + const createdDiff = getSortableTime(right.createdAt) - getSortableTime(left.createdAt) + if (createdDiff !== 0) return createdDiff + return (right.code ?? '').localeCompare(left.code ?? '', 'zh-CN', { numeric: true }) + }) +} + +function sortAssetFamiliesByCreatedTime(items: AssetFamilyDTO[]): AssetFamilyDTO[] { + return sortByCreatedDesc(items) +} + +function sortAssetVariantsByCreatedTime(items: AssetVariantDTO[]): AssetVariantDTO[] { + return sortByCreatedDesc(items) +} + function createAssetOperationId(prefix: string): string { const cryptoApi = globalThis.crypto if (typeof cryptoApi?.randomUUID === 'function') { @@ -256,6 +316,214 @@ function renderVariantSaveProgress(progress: AssetOperationProgressDTO) { ) } +function AssetVariantSkuColumnResizableFrame({ + columnWidth, + minWidth, + onColumnResize, + children, +}: { + columnWidth: number + minWidth: number + onColumnResize: (width: number) => void + children: ReactNode +}) { + function handlePointerDown(event: ReactPointerEvent) { + event.preventDefault() + event.stopPropagation() + + const startX = event.clientX + const startWidth = columnWidth + document.body.style.cursor = 'ew-resize' + document.body.style.userSelect = 'none' + + const handlePointerMove = (moveEvent: PointerEvent) => { + onColumnResize(startWidth + moveEvent.clientX - startX) + } + const handlePointerUp = () => { + document.body.style.cursor = '' + document.body.style.userSelect = '' + window.removeEventListener('pointermove', handlePointerMove) + window.removeEventListener('pointerup', handlePointerUp) + } + + window.addEventListener('pointermove', handlePointerMove) + window.addEventListener('pointerup', handlePointerUp, { once: true }) + } + + return ( +
+ {children} +
+ +
+
+ ) +} + +function AssetVariantSupplierCombobox({ + ariaLabel, + value, + options, + placeholder, + readOnly, + dropdownId, + onChange, +}: { + ariaLabel: string + value: string + options: readonly string[] + placeholder?: string + readOnly?: boolean + dropdownId: string + onChange: (value: string) => void +}) { + const inputRef = useRef(null) + const dropdownRef = useRef(null) + const [open, setOpen] = useState(false) + const [dropdownRect, setDropdownRect] = useState({ + left: 0, + top: 0, + width: 220, + }) + const normalizedQuery = value.trim().toLowerCase() + const filteredOptions = useMemo(() => { + if (!normalizedQuery) return options.slice(0, 80) + return options + .filter((option) => option.toLowerCase().includes(normalizedQuery)) + .slice(0, 80) + }, [normalizedQuery, options]) + const updateDropdownPosition = useCallback(() => { + const input = inputRef.current + if (!input) return + + const rect = input.getBoundingClientRect() + const width = Math.max(rect.width, 220) + + setDropdownRect({ + left: rect.left, + top: rect.bottom + 4, + width, + }) + }, []) + + useEffect(() => { + if (!open) return + + updateDropdownPosition() + window.addEventListener('resize', updateDropdownPosition) + window.addEventListener('scroll', updateDropdownPosition, true) + return () => { + window.removeEventListener('resize', updateDropdownPosition) + window.removeEventListener('scroll', updateDropdownPosition, true) + } + }, [open, updateDropdownPosition]) + + useEffect(() => { + if (!open) return + + function handlePointerDown(event: PointerEvent) { + const target = event.target + if (!(target instanceof Node)) return + if (inputRef.current?.contains(target)) return + if (dropdownRef.current?.contains(target)) return + setOpen(false) + } + + document.addEventListener('pointerdown', handlePointerDown, true) + return () => document.removeEventListener('pointerdown', handlePointerDown, true) + }, [open]) + + return ( + <> + + { + if (readOnly) return + setOpen(true) + updateDropdownPosition() + }} + onClick={() => { + if (readOnly) return + setOpen(true) + updateDropdownPosition() + }} + onChange={(event) => { + onChange(event.target.value) + setOpen(true) + updateDropdownPosition() + }} + onKeyDown={(event) => { + if (event.key === 'Escape') setOpen(false) + }} + className={cn( + 'h-9 w-full min-w-0 rounded-[5px] border border-[#dbe3e5] bg-white px-2 pr-7 text-[13px] font-black text-[#2d3335] outline-none placeholder:text-[#8a9498]', + readOnly && 'bg-[#f7f9f9] text-[#5a6062]/70', + )} + /> + + ▼ + + + {open && !readOnly && typeof document !== 'undefined' ? createPortal( +
+ {filteredOptions.length > 0 ? ( + filteredOptions.map((option) => ( + + )) + ) : ( +
+ 无匹配供应商,可继续手动输入 +
+ )} +
, + document.body, + ) : null} + + ) +} + function formatUvNumber(value: number | null | undefined) { return typeof value === 'number' && Number.isFinite(value) ? String(value) : '' } @@ -458,6 +726,225 @@ function toOptionalNumber(value: string): number | null { return Number.isFinite(parsed) ? parsed : null } +function formatCompactNumber(value: number) { + return Number.isInteger(value) ? String(value) : String(Number(value.toFixed(2))) +} + +function formatDimensionCmValue(value: string) { + const parsed = Number(value) + if (!Number.isFinite(parsed) || parsed <= 0) return '' + return formatCompactNumber(parsed / 10) +} + +function formatVariantSizeCmLabel(input: { + length: string + width: string + thickness: string +}) { + const parts = [ + formatDimensionCmValue(input.length), + formatDimensionCmValue(input.width), + formatDimensionCmValue(input.thickness), + ] + return parts.every(Boolean) ? parts.join('/') : '' +} + +function formatVariantSizeMmLabel(input: { + length: string + width: string + thickness: string +}) { + const parts = [input.length, input.width, input.thickness] + .map((value) => { + const parsed = Number(value) + return Number.isFinite(parsed) && parsed > 0 ? formatCompactNumber(parsed) : '' + }) + return parts.every(Boolean) ? parts.join('x') : '' +} + +function getSubstrateFinishName(substrate: SubstrateDTO | null | undefined) { + return substrate?.finishes?.[0]?.name?.trim() ?? '' +} + +function getSubstrateMaterialName(substrate: SubstrateDTO | null | undefined) { + if (!substrate) return '' + + const thickness = typeof substrate.thicknessMm === 'number' + ? formatCompactNumber(substrate.thicknessMm) + : '' + return [ + thickness, + substrate.environmentGradeName?.trim() ?? '', + substrate.categoryName?.trim() ?? '', + ].filter(Boolean).join('') +} + +function isSteelLikeSubstrate(substrate: SubstrateDTO | null | undefined) { + if (!substrate) return false + return [substrate.categoryName, substrate.name, substrate.systemNameOptionName] + .filter(Boolean) + .some((value) => /金属|钢/.test(value ?? '')) +} + +function isMetalLikeFinish(finish: MaterialDTO | MaterialLikeDTO | null | undefined) { + if (!finish) return false + return [finish.categoryName, finish.name] + .filter(Boolean) + .some((value) => /金属|钢/.test(value ?? '')) +} + +function getSteelMaterialName(substrate: SubstrateDTO | null | undefined) { + if (!substrate) return '' + + let name = (substrate.systemNameOptionName ?? substrate.name).trim() + const removableParts = [ + substrate.environmentGradeName, + substrate.surfaceOptionName, + ...substrate.finishes.map((finish) => finish.name), + ] + removableParts + .filter(Boolean) + .forEach((part) => { + name = name.replace(new RegExp(escapeRegExp(part ?? ''), 'g'), ' ') + }) + + return name.replace(/\s+/g, '').trim() || substrate.categoryName.trim() +} + +function escapeRegExp(value: string) { + return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') +} + +function stripVariantSpecNameGeneratedParts(input: { + specName: string + sizeCmLabel: string + sizeMmLabel: string + color: string +}) { + let styleName = input.specName.trim() + ;[input.sizeCmLabel, input.sizeMmLabel, input.color] + .filter(Boolean) + .forEach((part) => { + styleName = styleName.replace(new RegExp(escapeRegExp(part), 'g'), ' ') + }) + styleName = styleName.replace(/\b\d+(?:\.\d+)?[xX×/]\d+(?:\.\d+)?(?:[xX×/]\d+(?:\.\d+)?)?\b/g, ' ') + return styleName.replace(/\s+/g, ' ').trim() +} + +const CHINESE_NUMBER_DIGITS = ['', '一', '二', '三', '四', '五', '六', '七', '八', '九'] as const +const CHINESE_NUMBER_UNITS = ['', '十', '百', '千'] as const + +function formatChineseNumberUnder10000(value: number) { + const digits = String(value).split('').map((item) => Number(item)) + const parts: string[] = [] + let pendingZero = false + + digits.forEach((digit, index) => { + const unitIndex = digits.length - index - 1 + if (!digit) { + pendingZero = parts.length > 0 && unitIndex > 0 + return + } + + if (pendingZero) { + parts.push('零') + pendingZero = false + } + + if (!(digit === 1 && unitIndex === 1 && parts.length === 0)) { + parts.push(CHINESE_NUMBER_DIGITS[digit] ?? String(digit)) + } + parts.push(CHINESE_NUMBER_UNITS[unitIndex] ?? '') + }) + + return parts.join('') +} + +function formatChineseSequence(value: number) { + if (!Number.isFinite(value) || value <= 0) return '' + const integerValue = Math.floor(value) + if (integerValue < 10000) return formatChineseNumberUnder10000(integerValue) + if (integerValue < 100000000) { + const high = Math.floor(integerValue / 10000) + const low = integerValue % 10000 + return `${formatChineseSequence(high)}万${low ? formatChineseNumberUnder10000(low) : ''}` + } + return String(integerValue) +} + +function getVariantStyleNameFromModel(model: string) { + const matched = model.trim().toUpperCase().match(/SPJK(\d+)$/) + const sequence = matched ? Number.parseInt(matched[1] ?? '', 10) : NaN + const chineseSequence = formatChineseSequence(sequence) + return chineseSequence ? `款式${chineseSequence}` : '' +} + +function buildVariantSpecName(input: { + model?: string + specName: string + sizeCmLabel: string + sizeMmLabel: string + color: string +}) { + const styleName = getVariantStyleNameFromModel(input.model ?? '') || + stripVariantSpecNameGeneratedParts(input) + return [styleName, input.sizeCmLabel, input.color].filter(Boolean).join(' ') +} + +function clampNumber(value: number, min: number, max: number) { + return Math.min(Math.max(value, min), Math.max(min, max)) +} + +function getAssetVariantSkuFieldDefaultWidth(field: AssetVariantSkuFieldDefinition) { + return field.defaultWidth ?? 112 +} + +function getAssetVariantSkuFieldMinWidth(field: AssetVariantSkuFieldDefinition) { + return field.minWidth ?? Math.min(getAssetVariantSkuFieldDefaultWidth(field), 96) +} + +function normalizeAssetVariantSkuColumnWidth( + field: AssetVariantSkuFieldDefinition, + width: number, +) { + return clampNumber( + Math.round(width), + getAssetVariantSkuFieldMinWidth(field), + ASSET_VARIANT_SKU_TABLE_COLUMN_MAX_WIDTH, + ) +} + +function createDefaultAssetVariantSkuColumnWidths() { + return ASSET_VARIANT_SKU_FIELD_DEFINITIONS.reduce( + (widths, field) => ({ + ...widths, + [field.key]: getAssetVariantSkuFieldDefaultWidth(field), + }), + {} as Partial>, + ) +} + +function getAssetVariantSkuFieldWidth( + widths: Partial>, + field: AssetVariantSkuFieldDefinition, +) { + return widths[field.key] ?? getAssetVariantSkuFieldDefaultWidth(field) +} + +function getAssetVariantSkuTableMinWidth( + widths: Partial>, +) { + return ( + ASSET_VARIANT_SKU_TABLE_INDEX_WIDTH + + ASSET_VARIANT_SKU_TABLE_IMAGE_WIDTH + + ASSET_VARIANT_SKU_FIELD_DEFINITIONS.reduce( + (total, field) => + total + getAssetVariantSkuFieldWidth(widths, field) + ASSET_VARIANT_SKU_TABLE_CELL_PADDING_WIDTH, + 0, + ) + ) +} + function getStatusLabel(status: string) { if (status === 'AVAILABLE') return '可用' if (status === 'DISABLED') return '停用' @@ -536,6 +1023,44 @@ function readStringValue(value: unknown): string | null { return typeof value === 'string' && value.trim().length > 0 ? value.trim() : null } +function readAssetVariantSkuContentFields( + businessData: Record | null | undefined, +): Partial> { + if (!isObjectRecord(businessData)) return {} + const rawFields = businessData[ASSET_VARIANT_SKU_CONTENT_BUSINESS_DATA_KEY] + if (!isObjectRecord(rawFields)) return {} + + return ASSET_VARIANT_SKU_FIELD_DEFINITIONS.reduce( + (fields, definition) => { + const value = rawFields[definition.key] + if (typeof value === 'string') { + fields[definition.key] = value + } else if (typeof value === 'number' && Number.isFinite(value)) { + fields[definition.key] = String(value) + } + return fields + }, + {} as Partial>, + ) +} + +function readAssetVariantMaterialMode( + businessData: Record | null | undefined, +): VariantMaterialMode | null { + if (!isObjectRecord(businessData)) return null + const mode = businessData[ASSET_VARIANT_MATERIAL_MODE_BUSINESS_DATA_KEY] + return mode === 'BOARD' || mode === 'STEEL' || mode === 'PACKAGING' ? mode : null +} + +function readAssetVariantMaterialSourceId( + businessData: Record | null | undefined, + key: typeof ASSET_VARIANT_STEEL_FRAME_ITEM_ID_BUSINESS_DATA_KEY | typeof ASSET_VARIANT_PACKAGING_VARIANT_ID_BUSINESS_DATA_KEY, +) { + if (!isObjectRecord(businessData)) return '' + const value = businessData[key] + return typeof value === 'string' ? value.trim() : '' +} + function readNumberValue(value: unknown): number | null { return typeof value === 'number' && Number.isFinite(value) ? value : null } @@ -753,6 +1278,99 @@ const TYPE_TABS: { type: AssetTypeFilter; label: string; icon: React.ReactNode } { type: 'PACKAGING', label: '包装', icon: }, ] +type AssetVariantSkuFieldKey = Extract< + keyof SeriesDraftSkuFields, + | 'model' + | 'skuCode' + | 'barcode' + | 'setCount' + | 'specName' + | 'size' + | 'color' + | 'material' + | 'boardMaterialType' + | 'versionNo' + | 'attributeCode' + | 'drawingId' + | 'installMethod' + | 'executeStandard' + | 'nationalStandardCompliant' + | 'manufacturer' + | 'manufacturerCode' + | 'salesStatus' + | 'batchNo' + | 'dingTalkFlowNo' +> + +interface AssetVariantSkuFieldDefinition { + label: string + key: AssetVariantSkuFieldKey + placeholder: string + control?: 'input' | 'select' | 'readonly' | 'combobox' + options?: readonly string[] + defaultWidth?: number + minWidth?: number +} + +const ASSET_VARIANT_BOARD_MATERIAL_TYPE_OPTIONS = ['ENF级', '非ENF级', '清货板材'] as const +const NON_BOARD_ASSET_VARIANT_BOARD_MATERIAL_TYPE = '非ENF级' +const DEFAULT_ASSET_VARIANT_ATTRIBUTE_CODE = 'A' +const DEFAULT_ASSET_VARIANT_INSTALL_METHOD = '拆装' +const DEFAULT_ASSET_VARIANT_EXECUTE_STANDARD = 'GB/T3324-2024' +const DEFAULT_STEEL_ASSET_VARIANT_EXECUTE_STANDARD = 'GB/T3325-2024' +const DEFAULT_ASSET_VARIANT_NATIONAL_STANDARD_COMPLIANT = '是' +const DEFAULT_ASSET_VARIANT_SALES_STATUS = '销售' +const ASSET_VARIANT_SALES_STATUS_OPTIONS = ['销售', '停产', '退市'] as const +const ASSET_VARIANT_INSTALL_METHOD_OPTIONS = ['整装', '拆装'] as const +const ASSET_VARIANT_NATIONAL_STANDARD_OPTIONS = ['是', '否'] as const +const ASSET_VARIANT_SUPPLIER_NAME_OPTIONS = SUPPLIER_DIRECTORY.map((entry) => entry.name) +const ASSET_VARIANT_SKU_CONTENT_BUSINESS_DATA_KEY = 'skuContentFields' +const ASSET_VARIANT_MATERIAL_MODE_BUSINESS_DATA_KEY = 'materialMode' +const ASSET_VARIANT_STEEL_FRAME_ITEM_ID_BUSINESS_DATA_KEY = 'steelFrameItemId' +const ASSET_VARIANT_PACKAGING_VARIANT_ID_BUSINESS_DATA_KEY = 'packagingMaterialVariantId' + +type VariantMaterialMode = 'BOARD' | 'STEEL' | 'PACKAGING' + +const ASSET_VARIANT_SKU_FIELD_DEFINITIONS: AssetVariantSkuFieldDefinition[] = [ + { label: '型号', key: 'model', placeholder: '系统带出', control: 'readonly', defaultWidth: 112 }, + { label: '货号', key: 'skuCode', placeholder: '系统自动生成', control: 'readonly', defaultWidth: 112 }, + { label: '条码', key: 'barcode', placeholder: '自动带出,可修改', defaultWidth: 168, minWidth: 150 }, + { label: '套件量', key: 'setCount', placeholder: '1', defaultWidth: 72, minWidth: 64 }, + { label: '规格名称', key: 'specName', placeholder: '款式 尺寸 颜色', defaultWidth: 168 }, + { label: '尺寸', key: 'size', placeholder: '长/宽/厚,单位 cm', control: 'readonly', defaultWidth: 108 }, + { label: '颜色', key: 'color', placeholder: '基材颜色', control: 'readonly', defaultWidth: 96 }, + { label: '材质', key: 'material', placeholder: '基材材质', control: 'readonly', defaultWidth: 132 }, + { label: '板材类型', key: 'boardMaterialType', placeholder: '请选择', control: 'select', options: ASSET_VARIANT_BOARD_MATERIAL_TYPE_OPTIONS, defaultWidth: 108 }, + { label: '版本号', key: 'versionNo', placeholder: 'V01', defaultWidth: 68, minWidth: 56 }, + { label: '属性代码', key: 'attributeCode', placeholder: '请填写', defaultWidth: 96 }, + { label: '图纸ID', key: 'drawingId', placeholder: '自动带出,可修改', defaultWidth: 144 }, + { label: '安装方式', key: 'installMethod', placeholder: '请选择', control: 'select', options: ASSET_VARIANT_INSTALL_METHOD_OPTIONS, defaultWidth: 96 }, + { label: '执行标准', key: 'executeStandard', placeholder: '请填写或选择', control: 'select', options: EXECUTION_STANDARD_OPTIONS, defaultWidth: 140 }, + { label: '符合国标', key: 'nationalStandardCompliant', placeholder: '是 / 否', control: 'select', options: ASSET_VARIANT_NATIONAL_STANDARD_OPTIONS, defaultWidth: 96 }, + { label: '供应商名称', key: 'manufacturer', placeholder: '输入供应商名称筛选', control: 'combobox', options: ASSET_VARIANT_SUPPLIER_NAME_OPTIONS, defaultWidth: 152, minWidth: 132 }, + { label: '供应商代码', key: 'manufacturerCode', placeholder: '自动带出', control: 'readonly', defaultWidth: 96 }, + { label: '销售状态', key: 'salesStatus', placeholder: '销售 / 停产 / 退市', control: 'select', options: ASSET_VARIANT_SALES_STATUS_OPTIONS, defaultWidth: 96 }, + { label: '创建批次', key: 'batchNo', placeholder: '批次1', control: 'readonly', defaultWidth: 76, minWidth: 64 }, + { label: '钉钉流程号', key: 'dingTalkFlowNo', placeholder: '批次信息维护', defaultWidth: 132 }, +] + +const ASSET_VARIANT_SKU_TABLE_INDEX_WIDTH = 48 +const ASSET_VARIANT_SKU_TABLE_IMAGE_WIDTH = 74 +const ASSET_VARIANT_SKU_TABLE_CELL_PADDING_WIDTH = 16 +const ASSET_VARIANT_SKU_TABLE_COLUMN_MAX_WIDTH = 420 +const ASSET_VARIANT_SKU_AUTO_SAVE_DEBOUNCE_MS = 800 +type VariantMaterialModeOption = readonly [VariantMaterialMode, string] +const ASSET_VARIANT_MATERIAL_MODE_OPTIONS: ReadonlyArray = [ + ['BOARD', '板材'], + ['STEEL', '钢材'], + ['PACKAGING', '包材'], +] as const +const ASSET_VARIANT_PACKAGING_MATERIAL_MODE_OPTIONS: ReadonlyArray = [ + ['PACKAGING', '包材'], +] as const + +type VariantSkuAutoSaveStatus = 'idle' | 'pending' | 'saving' | 'saved' | 'failed' + // ---- 空表单模板 ---- function buildVariantIdentityPrefix(familyCode: string): string { @@ -761,17 +1379,76 @@ function buildVariantIdentityPrefix(familyCode: string): string { return normalizedCode.endsWith('-') ? normalizedCode : `${normalizedCode}-` } -function emptyVariantForm(assetFamilyId: string, identityPrefix = '') { +function resolveSeriesCodeFromAssetFamily(family: AssetFamilyDTO): string { + const directSeriesCode = family.assetSeriesCode?.trim().toUpperCase() + if (directSeriesCode) return directSeriesCode + + const matched = family.code.trim().toUpperCase().match(/^([A-Z][A-Z0-9]*)-SPJK\d+$/) + return matched?.[1] ?? '' +} + +function readAssetVariantSequence(code: string, seriesCode: string): number | null { + if (!seriesCode) return null + const matched = code + .trim() + .toUpperCase() + .match(new RegExp(`^${escapeRegExp(seriesCode)}-SPJ(\\d+)$`)) + if (!matched) return null + + const sequence = Number.parseInt(matched[1] ?? '', 10) + return Number.isFinite(sequence) && sequence > 0 ? sequence : null +} + +function buildNextAssetVariantCodeForFamily( + family: AssetFamilyDTO, + variants: AssetVariantDTO[], +): string { + const seriesCode = resolveSeriesCodeFromAssetFamily(family) + if (!seriesCode) return '' + + const maxSequence = variants.reduce((max, variant) => { + const sequence = readAssetVariantSequence(variant.code, seriesCode) + return sequence === null ? max : Math.max(max, sequence) + }, 0) + + return buildAssetVariantCode(seriesCode, maxSequence + 1) +} + +function emptyVariantForm( + assetFamilyId: string, + identityPrefix = '', + materialMode: VariantMaterialMode = 'BOARD', +) { return { assetFamilyId, + materialMode, + model: identityPrefix.endsWith('-') ? identityPrefix.slice(0, -1) : identityPrefix, code: '', - name: identityPrefix, + name: materialMode === 'PACKAGING' ? '' : identityPrefix, + setCount: '1', sizeLabel: '', + color: '', + material: '', + boardMaterialType: + NON_BOARD_ASSET_VARIANT_BOARD_MATERIAL_TYPE, + attributeCode: DEFAULT_ASSET_VARIANT_ATTRIBUTE_CODE, + drawingId: '', + installMethod: DEFAULT_ASSET_VARIANT_INSTALL_METHOD, + executeStandard: + materialMode === 'STEEL' + ? DEFAULT_STEEL_ASSET_VARIANT_EXECUTE_STANDARD + : DEFAULT_ASSET_VARIANT_EXECUTE_STANDARD, + nationalStandardCompliant: DEFAULT_ASSET_VARIANT_NATIONAL_STANDARD_COMPLIANT, + salesStatus: DEFAULT_ASSET_VARIANT_SALES_STATUS, + batchNo: '批次1', + dingTalkFlowNo: '', substrateId: '', finishId: '', + steelFrameItemId: '', + packagingMaterialVariantId: '', supplierName: '', supplierCode: '', - versionNo: '', + versionNo: DEFAULT_SKU_VERSION_NO, barcode: '', length: '', width: '', @@ -789,6 +1466,95 @@ function emptyVariantForm(assetFamilyId: string, identityPrefix = '') { type VariantForm = ReturnType +function resolveVariantBoardMaterialTypeForSku(form: VariantForm) { + return form.boardMaterialType.trim() +} + +function hasVariantSkuContentField( + fields: Partial>, + key: AssetVariantSkuFieldKey, +) { + return Object.prototype.hasOwnProperty.call(fields, key) +} + +function readVariantSkuContentFieldWithDefault( + fields: Partial>, + key: AssetVariantSkuFieldKey, + defaultValue: string, +) { + return hasVariantSkuContentField(fields, key) ? fields[key] ?? '' : defaultValue +} + +function getDefaultVariantExecuteStandard(materialMode: VariantMaterialMode) { + return materialMode === 'STEEL' + ? DEFAULT_STEEL_ASSET_VARIANT_EXECUTE_STANDARD + : DEFAULT_ASSET_VARIANT_EXECUTE_STANDARD +} + +function resolveSupplierCodeByName(name: string) { + return SUPPLIER_CODE_BY_NAME.get(name.trim())?.trim().toUpperCase() ?? '' +} + +function resolveVariantSkuVersionNo(form: VariantForm) { + const currentValue = form.versionNo.trim() + return currentValue ? normalizeSkuVersionNo(currentValue) : '' +} + +function resolveVariantBarcode(form: VariantForm) { + if (!form.supplierCode.trim()) return '' + const versionNo = resolveVariantSkuVersionNo(form) + if (!versionNo) return '' + const generatedBarcode = buildAssetVariantBarcode({ + variantCode: form.code, + supplierCode: form.supplierCode, + versionNo, + }) + return generatedBarcode +} + +function resolveVariantDrawingId(form: VariantForm) { + const model = form.model.trim().toUpperCase() + if (!model) return form.drawingId.trim().toUpperCase() + return `${model}${form.attributeCode.trim().toUpperCase()}${resolveVariantSkuVersionNo(form)}` +} + +function buildVariantSkuContentBusinessData( + form: VariantForm, + existingBusinessData?: Record | null, +): Record { + const base = isObjectRecord(existingBusinessData) ? { ...existingBusinessData } : {} + const versionNo = resolveVariantSkuVersionNo(form) + base[ASSET_VARIANT_MATERIAL_MODE_BUSINESS_DATA_KEY] = form.materialMode + base[ASSET_VARIANT_STEEL_FRAME_ITEM_ID_BUSINESS_DATA_KEY] = + form.materialMode === 'STEEL' ? form.steelFrameItemId.trim() : '' + base[ASSET_VARIANT_PACKAGING_VARIANT_ID_BUSINESS_DATA_KEY] = + form.materialMode === 'PACKAGING' ? form.packagingMaterialVariantId.trim() : '' + base[ASSET_VARIANT_SKU_CONTENT_BUSINESS_DATA_KEY] = { + model: form.model.trim(), + skuCode: form.code.trim(), + barcode: resolveVariantBarcode(form), + setCount: form.setCount.trim(), + specName: form.name.trim(), + size: form.sizeLabel.trim(), + color: form.color.trim(), + material: form.material.trim(), + boardMaterialType: resolveVariantBoardMaterialTypeForSku(form), + versionNo, + attributeCode: form.attributeCode.trim().toUpperCase(), + drawingId: resolveVariantDrawingId(form), + installMethod: form.installMethod.trim(), + executeStandard: form.executeStandard.trim(), + nationalStandardCompliant: form.nationalStandardCompliant.trim(), + manufacturer: form.supplierName.trim(), + manufacturerCode: form.supplierCode.trim().toUpperCase(), + salesStatus: form.salesStatus.trim(), + batchNo: form.batchNo.trim() || '批次1', + dingTalkFlowNo: form.dingTalkFlowNo.trim(), + } satisfies Partial> + + return base +} + type ImportableAssetType = Exclude function isImportableAssetType(type: AssetFamilyDTO['type']): type is ImportableAssetType { @@ -952,29 +1718,48 @@ export default function AssetCenterClient({ initialSubstrates, initialSubstrateDictionaries: _initialSubstrateDictionaries, initialAssetSeries, + initialSeriesComponentDetails = [], finishes: initialFinishes, materialCategories: _initialMaterialCategories, metrics, user, }: AssetCenterClientProps) { + const router = useRouter() // Toast const toast = useToast() // 数据状态 - const [families, setFamilies] = useState(sortByName(initialFamilies)) - const [variants, setVariants] = useState(() => normalizeAssetVariantsWithUv(initialVariants)) + const [families, setFamilies] = useState(() => sortAssetFamiliesByCreatedTime(initialFamilies)) + const [variants, setVariants] = useState(() => + sortAssetVariantsByCreatedTime(normalizeAssetVariantsWithUv(initialVariants)), + ) const [substrates, setSubstrates] = useState(sortByName(initialSubstrates)) + const [steelFrameMaterialOptions, setSteelFrameMaterialOptions] = useState([]) + const [packagingMaterialOptions, setPackagingMaterialOptions] = useState([]) const finishes = initialFinishes const [selectedVariantId, setSelectedVariantId] = useState(null) const [submitting, setSubmitting] = useState(false) // 系列与分类筛选状态 - const [selectedSeriesId, setSelectedSeriesId] = useState( - initialAssetSeries[0]?.id ?? null, - ) + const [selectedSeriesId, setSelectedSeriesId] = useState(() => { + const fallbackSeriesId = initialAssetSeries[0]?.id ?? null + if (typeof window === 'undefined') return fallbackSeriesId + + const savedSeriesId = window.localStorage.getItem(ASSET_CENTER_SELECTED_SERIES_STORAGE_KEY) + return savedSeriesId && initialAssetSeries.some((series) => series.id === savedSeriesId) + ? savedSeriesId + : fallbackSeriesId + }) const [seriesPickerOpen, setSeriesPickerOpen] = useState(false) const [seriesSearchText, setSeriesSearchText] = useState('') const seriesPickerRef = useRef(null) + const [seriesComponentDetails, setSeriesComponentDetails] = useState( + initialSeriesComponentDetails, + ) + const [ + creatingSeriesComponentDetailSeriesId, + setCreatingSeriesComponentDetailSeriesId, + ] = useState(null) const [activeTab, setActiveTab] = useState('BOARD') const [assemblySelectedFamilyIds, setAssemblySelectedFamilyIds] = useState>(new Set()) @@ -1013,10 +1798,16 @@ export default function AssetCenterClient({ // 规格款弹窗 const [variantModalOpen, setVariantModalOpen] = useState(false) + const [packagingVariantModalOpen, setPackagingVariantModalOpen] = useState(false) const [variantModalMode, setVariantModalMode] = useState<'create' | 'edit'>('create') const [variantForm, setVariantForm] = useState(emptyVariantForm('')) const [editingVariantId, setEditingVariantId] = useState(null) + const [variantSkuColumnWidths, setVariantSkuColumnWidths] = useState( + createDefaultAssetVariantSkuColumnWidths, + ) const [variantSaveProgress, setVariantSaveProgress] = useState(null) + const [variantSkuAutoSaveStatus, setVariantSkuAutoSaveStatus] = + useState('idle') const [reviewDialogState, setReviewDialogState] = useState(null) const [reviewRejectReason, setReviewRejectReason] = useState('') const [cadImportModalOpen, setCadImportModalOpen] = useState(false) @@ -1065,6 +1856,9 @@ export default function AssetCenterClient({ const [draftVariantSubstrateId, setDraftVariantSubstrateId] = useState(null) const variantUvEditorFormRef = useRef(variantUvEditorForm) const variantSaveProgressPollerRef = useRef(null) + const variantSkuAutoSaveTimerRef = useRef(null) + const variantSkuAutoSaveRequestRef = useRef(0) + const lastVariantSkuAutoSaveSignatureRef = useRef('') const [draftVariantUvConfig, setDraftVariantUvConfig] = useState(null) const draftVariantUvConfigRef = useRef(null) const activeVariantUvNodeNameRef = useRef(null) @@ -1075,7 +1869,66 @@ export default function AssetCenterClient({ const showReadOnlyWarning = useCallback(() => { toast.warning('当前账号只能查看设计工作区,不能新增、编辑或保存') }, [toast]) + useEffect(() => { + const loadSteelFrameMaterialOptions = () => { + setSteelFrameMaterialOptions(buildNonIntegratedBomSteelFrameOptions()) + } + const loadPackagingMaterialOptions = () => { + setPackagingMaterialOptions(buildNonIntegratedBomPackagingMaterialOptions()) + } + + loadSteelFrameMaterialOptions() + loadPackagingMaterialOptions() + window.addEventListener('focus', loadSteelFrameMaterialOptions) + window.addEventListener('storage', loadSteelFrameMaterialOptions) + window.addEventListener('focus', loadPackagingMaterialOptions) + window.addEventListener('storage', loadPackagingMaterialOptions) + window.addEventListener(PACKAGING_MATERIAL_LIBRARY_CHANGED_EVENT, loadPackagingMaterialOptions) + return () => { + window.removeEventListener('focus', loadSteelFrameMaterialOptions) + window.removeEventListener('storage', loadSteelFrameMaterialOptions) + window.removeEventListener('focus', loadPackagingMaterialOptions) + window.removeEventListener('storage', loadPackagingMaterialOptions) + window.removeEventListener(PACKAGING_MATERIAL_LIBRARY_CHANGED_EVENT, loadPackagingMaterialOptions) + } + }, []) const selectedVariant = variants.find((v) => v.id === selectedVariantId) ?? null + const inferVariantMaterialMode = useCallback(( + variant: AssetVariantDTO, + substrateIdOverride?: string | null, + ): VariantMaterialMode => { + const savedMode = readAssetVariantMaterialMode(variant.businessData) + if (savedMode) return savedMode + + if ( + variant.assetType === 'PACKAGING' || + readAssetVariantMaterialSourceId( + variant.businessData, + ASSET_VARIANT_PACKAGING_VARIANT_ID_BUSINESS_DATA_KEY, + ) + ) { + return 'PACKAGING' + } + + if ( + readAssetVariantMaterialSourceId( + variant.businessData, + ASSET_VARIANT_STEEL_FRAME_ITEM_ID_BUSINESS_DATA_KEY, + ) + ) { + return 'STEEL' + } + + const substrateId = substrateIdOverride !== undefined ? substrateIdOverride : variant.substrateId + const substrate = substrateId + ? substrates.find((item) => item.id === substrateId) ?? null + : null + if (isSteelLikeSubstrate(substrate) || isMetalLikeFinish(variant.finish)) { + return 'STEEL' + } + + return variant.assetType === 'BOARD' ? 'BOARD' : 'STEEL' + }, [substrates]) const currentUserCanReviewAssets = useMemo(() => canReviewAssets(user.role), [user.role]) const variantSubstrateDirty = Boolean( selectedVariant && @@ -1241,12 +2094,6 @@ export default function AssetCenterClient({ useEffect(() => { const availableIds = new Set(initialAssetSeries.map((series) => series.id)) - const savedSeriesId = window.localStorage.getItem(ASSET_CENTER_SELECTED_SERIES_STORAGE_KEY) - if (savedSeriesId && availableIds.has(savedSeriesId)) { - setSelectedSeriesId(savedSeriesId) - return - } - setSelectedSeriesId((current) => current && availableIds.has(current) ? current : initialAssetSeries[0]?.id ?? null, ) @@ -1302,6 +2149,9 @@ export default function AssetCenterClient({ current.push(variant) map.set(variant.assetFamilyId, current) }) + map.forEach((familyVariants, familyId) => { + map.set(familyId, sortAssetVariantsByCreatedTime(familyVariants)) + }) return map }, [variants]) @@ -1309,6 +2159,90 @@ export default function AssetCenterClient({ () => initialAssetSeries.find((series) => series.id === selectedSeriesId) ?? null, [initialAssetSeries, selectedSeriesId], ) + const seriesComponentDetailByCode = useMemo(() => { + const map = new Map() + seriesComponentDetails.forEach((detail) => { + const sourceSeriesCode = detail.sourceSeriesCode.trim().toUpperCase() + if (sourceSeriesCode) { + map.set(sourceSeriesCode, detail) + } + const spuSeriesCode = detail.spu.trim().toUpperCase().replace(/-SPJ$/, '') + if (spuSeriesCode) { + map.set(spuSeriesCode, detail) + } + }) + return map + }, [seriesComponentDetails]) + const getSeriesComponentDetail = useCallback( + (series: AssetSeriesDTO) => + seriesComponentDetailByCode.get(series.code.trim().toUpperCase()) ?? null, + [seriesComponentDetailByCode], + ) + const selectedSeriesComponentDetail = selectedSeries + ? getSeriesComponentDetail(selectedSeries) + : null + const openSeriesComponentDetail = useCallback( + (detail: AssetSeriesComponentDetailSummaryDTO) => { + router.push( + `/intake?openProductId=${encodeURIComponent(detail.productId)}&workspace=basic-info`, + ) + }, + [router], + ) + const handleEnsureSeriesComponentDetail = useCallback( + async (series: AssetSeriesDTO) => { + const existingDetail = getSeriesComponentDetail(series) + if (existingDetail) { + openSeriesComponentDetail(existingDetail) + return + } + + setCreatingSeriesComponentDetailSeriesId(series.id) + try { + const componentDetail = await ensureAssetSeriesComponentDetail(series.id) + setSeriesComponentDetails((current) => { + const nextCode = componentDetail.sourceSeriesCode.trim().toUpperCase() + const nextSpuSeriesCode = componentDetail.spu + .trim() + .toUpperCase() + .replace(/-SPJ$/, '') + const exists = current.some((item) => { + const itemCode = item.sourceSeriesCode.trim().toUpperCase() + const itemSpuSeriesCode = item.spu + .trim() + .toUpperCase() + .replace(/-SPJ$/, '') + return ( + item.productId === componentDetail.productId || + (!!nextCode && itemCode === nextCode) || + (!!nextSpuSeriesCode && itemSpuSeriesCode === nextSpuSeriesCode) + ) + }) + return exists + ? current.map((item) => + item.productId === componentDetail.productId || + item.sourceSeriesCode.trim().toUpperCase() === nextCode + ? componentDetail + : item, + ) + : [...current, componentDetail] + }) + toast.success( + componentDetail.created ? '部件开发明细已创建' : '已进入部件开发明细', + ) + openSeriesComponentDetail(componentDetail) + } catch (error) { + toast.error( + error instanceof Error + ? error.message + : '部件开发明细创建失败,请稍后再试', + ) + } finally { + setCreatingSeriesComponentDetailSeriesId(null) + } + }, + [getSeriesComponentDetail, openSeriesComponentDetail, toast], + ) const seriesAssetCounts = useMemo(() => { const map = new Map() @@ -1440,21 +2374,223 @@ export default function AssetCenterClient({ () => selectedVariantSubstrate?.finishes?.[0]?.id ?? null, [selectedVariantSubstrate], ) + const selectedVariantFinish = useMemo(() => { + if (!variantForm.finishId) return null + return finishes.find((finish) => finish.id === variantForm.finishId) + ?? selectedVariantSubstrate?.finishes.find((finish) => finish.id === variantForm.finishId) + ?? null + }, [finishes, selectedVariantSubstrate, variantForm.finishId]) + const boardSubstrateOptions = useMemo( + () => substrates.filter((substrate) => !isSteelLikeSubstrate(substrate)), + [substrates], + ) + const variantMaterialSubstrateOptions = useMemo(() => { + const baseOptions = boardSubstrateOptions + if ( + variantForm.materialMode === 'BOARD' && + selectedVariantSubstrate && + !baseOptions.some((substrate) => substrate.id === selectedVariantSubstrate.id) + ) { + return [selectedVariantSubstrate, ...baseOptions] + } + return baseOptions + }, [ + boardSubstrateOptions, + selectedVariantSubstrate, + variantForm.materialMode, + ]) + const selectedSteelFrameMaterialOption = useMemo( + () => steelFrameMaterialOptions.find((option) => option.id === variantForm.steelFrameItemId) ?? null, + [steelFrameMaterialOptions, variantForm.steelFrameItemId], + ) + const selectedPackagingMaterialOption = useMemo( + () => packagingMaterialOptions.find((variant) => variant.id === variantForm.packagingMaterialVariantId) ?? null, + [packagingMaterialOptions, variantForm.packagingMaterialVariantId], + ) + const variantMaterialFinishOptions = useMemo(() => { + const baseOptions = finishes + if ( + selectedVariantFinish && + !baseOptions.some((finish) => finish.id === selectedVariantFinish.id) + ) { + return [selectedVariantFinish, ...baseOptions] + } + return baseOptions + }, [finishes, selectedVariantFinish]) + const resolvedVariantSubstrateId = useMemo(() => { + if (variantForm.materialMode === 'BOARD') { + return variantForm.substrateId || null + } + if ( + variantForm.materialMode === 'STEEL' && + !variantForm.steelFrameItemId && + variantForm.substrateId + ) { + return variantForm.substrateId + } + return null + }, [ + variantForm.materialMode, + variantForm.steelFrameItemId, + variantForm.substrateId, + ]) + const resolvedVariantFinishId = useMemo( + () => { + if (variantForm.materialMode === 'STEEL' || variantForm.materialMode === 'PACKAGING') return variantForm.finishId || null + if (variantForm.materialMode === 'BOARD') return selectedVariantSubstrateFinishId + return null + }, + [ + selectedVariantSubstrateFinishId, + variantForm.finishId, + variantForm.materialMode, + ], + ) const isDuplicateVariantMode = variantModalMode === 'create' && Boolean(variantForm.inheritedFromVariantId) - const variantEstimatedCostPrice = useMemo( - () => - calculateEstimatedCost({ - lengthMm: toOptionalNumber(variantForm.length), - widthMm: toOptionalNumber(variantForm.width), - sheetLengthMm: selectedVariantSubstrate?.sheetLengthMm, - sheetWidthMm: selectedVariantSubstrate?.sheetWidthMm, - suggestedPrice: selectedVariantSubstrate?.suggestedPrice, - lossFactor: toOptionalNumber(variantForm.lossFactor), - }), - [selectedVariantSubstrate, variantForm.length, variantForm.width, variantForm.lossFactor], + const variantSkuTableMinWidth = useMemo( + () => getAssetVariantSkuTableMinWidth(variantSkuColumnWidths), + [variantSkuColumnWidths], ) + const derivedVariantSizeCmLabel = useMemo( + () => formatVariantSizeCmLabel({ + length: variantForm.length, + width: variantForm.width, + thickness: variantForm.thickness, + }), + [variantForm.length, variantForm.width, variantForm.thickness], + ) + const derivedVariantSizeMmLabel = useMemo( + () => formatVariantSizeMmLabel({ + length: variantForm.length, + width: variantForm.width, + thickness: variantForm.thickness, + }), + [variantForm.length, variantForm.width, variantForm.thickness], + ) + const derivedVariantColor = useMemo( + () => { + if (variantForm.materialMode === 'STEEL' || variantForm.materialMode === 'PACKAGING') { + return selectedVariantFinish?.name.trim() ?? '' + } + if (variantForm.materialMode === 'BOARD') return getSubstrateFinishName(selectedVariantSubstrate) + return '' + }, + [selectedVariantFinish, selectedVariantSubstrate, variantForm.materialMode], + ) + const derivedVariantMaterial = useMemo( + () => { + if (variantForm.materialMode === 'STEEL') { + return selectedSteelFrameMaterialOption?.displayName.trim() || + getSteelMaterialName(selectedVariantSubstrate) + } + if (variantForm.materialMode === 'PACKAGING') { + return selectedPackagingMaterialOption?.name.trim() || variantForm.material + } + return getSubstrateMaterialName(selectedVariantSubstrate) + }, + [ + selectedPackagingMaterialOption, + selectedSteelFrameMaterialOption, + selectedVariantSubstrate, + variantForm.material, + variantForm.materialMode, + ], + ) + const variantFormModalOpen = variantModalOpen || packagingVariantModalOpen + + useEffect(() => { + if (!variantFormModalOpen) return + + setVariantForm((current) => { + const nextSizeLabel = derivedVariantSizeCmLabel || current.sizeLabel + const nextColor = current.color || derivedVariantColor + const nextMaterial = current.material || derivedVariantMaterial + const nextBoardMaterialType = resolveVariantBoardMaterialTypeForSku(current) + const nextName = buildVariantSpecName({ + model: current.model, + specName: current.name, + sizeCmLabel: nextSizeLabel, + sizeMmLabel: derivedVariantSizeMmLabel, + color: nextColor, + }) || current.name + const nextVersionNo = resolveVariantSkuVersionNo(current) + const nextBarcode = resolveVariantBarcode({ + ...current, + versionNo: nextVersionNo, + }) + const nextDrawingId = resolveVariantDrawingId(current) + + if ( + current.sizeLabel === nextSizeLabel && + current.color === nextColor && + current.material === nextMaterial && + current.boardMaterialType === nextBoardMaterialType && + current.name === nextName && + current.versionNo === nextVersionNo && + current.barcode === nextBarcode && + current.drawingId === nextDrawingId + ) { + return current + } + + return { + ...current, + sizeLabel: nextSizeLabel, + color: nextColor, + material: nextMaterial, + boardMaterialType: nextBoardMaterialType, + name: nextName, + versionNo: nextVersionNo, + barcode: nextBarcode, + drawingId: nextDrawingId, + } + }) + }, [ + derivedVariantColor, + derivedVariantMaterial, + derivedVariantSizeCmLabel, + derivedVariantSizeMmLabel, + variantForm.color, + variantForm.materialMode, + variantFormModalOpen, + ]) + + useEffect(() => { + if (!variantFormModalOpen) return + + setVariantForm((current) => { + const nextVersionNo = resolveVariantSkuVersionNo(current) + const nextBarcode = resolveVariantBarcode({ + ...current, + versionNo: nextVersionNo, + }) + const nextDrawingId = resolveVariantDrawingId(current) + + if ( + current.versionNo === nextVersionNo && + current.barcode === nextBarcode && + current.drawingId === nextDrawingId + ) { + return current + } + + return { + ...current, + versionNo: nextVersionNo, + barcode: nextBarcode, + drawingId: nextDrawingId, + } + }) + }, [ + variantForm.attributeCode, + variantForm.code, + variantForm.model, + variantForm.supplierCode, + variantForm.versionNo, + variantFormModalOpen, + ]) const selectedCadSubstrate = useMemo( () => substrates.find((item) => item.id === cadImportForm.substrateId) ?? null, @@ -1854,7 +2990,6 @@ export default function AssetCenterClient({ if (familyModalMode === 'create') { const created = await createAssetFamily({ type: familyForm.type, - code: familyForm.code.trim() || undefined, name: familyForm.name, description: familyForm.description || null, assetSeriesId: submittedAssetSeriesId, @@ -1864,14 +2999,13 @@ export default function AssetCenterClient({ status: 'DRAFT', }) startTransition(() => { - setFamilies((current) => sortByName([...current, created])) + setFamilies((current) => sortAssetFamiliesByCreatedTime([...current, created])) closeFamilyModal() toast.success('资产族已创建') }) } else { if (!editingFamilyId) return const updated = await updateAssetFamily(editingFamilyId, { - code: familyForm.code.trim() || undefined, name: familyForm.name, description: familyForm.description || null, assetSeriesId: submittedAssetSeriesId, @@ -1894,19 +3028,59 @@ export default function AssetCenterClient({ // ---- 规格款弹窗操作 ---- + function resetVariantSkuAutoSaveState() { + clearVariantSkuAutoSaveTimer() + variantSkuAutoSaveRequestRef.current += 1 + lastVariantSkuAutoSaveSignatureRef.current = '' + setVariantSkuAutoSaveStatus('idle') + } + function openCreateVariantModal(family: AssetFamilyDTO) { if (!canOperateDesignWorkspace) { showReadOnlyWarning() return } + if (family.type === 'PACKAGING') { + openCreatePackagingVariantModal(family) + return + } + resetVariantSkuAutoSaveState() setVariantModalMode('create') setEditingVariantId(null) setVariantCreateUvConfig(null) - setVariantForm(emptyVariantForm(family.id, buildVariantIdentityPrefix(family.code))) + setVariantForm(emptyVariantForm( + family.id, + buildVariantIdentityPrefix(family.code), + family.type === 'BOARD' + ? 'BOARD' + : 'STEEL', + )) setExpandedFamilyIds((prev) => new Set(prev).add(family.id)) setVariantModalOpen(true) } + function openCreatePackagingVariantModal(family: AssetFamilyDTO) { + if (!canOperateDesignWorkspace) { + showReadOnlyWarning() + return + } + const nextForm = emptyVariantForm( + family.id, + buildVariantIdentityPrefix(family.code), + 'PACKAGING', + ) + nextForm.code = buildNextAssetVariantCodeForFamily(family, variants) + + resetVariantSkuAutoSaveState() + setVariantModalMode('create') + setEditingVariantId(null) + setVariantCreateUvConfig(null) + setVariantSaveProgress(null) + setVariantForm(nextForm) + setExpandedFamilyIds((prev) => new Set(prev).add(family.id)) + setPackagingVariantModalOpen(true) + } + function openDuplicateVariantModal( variant: AssetVariantDTO, draft?: { @@ -1921,20 +3095,75 @@ export default function AssetCenterClient({ const dims = variant.dimensions ?? {} const mp = variant.mountPoints?.[0] const nextUvConfig = normalizeAssetVariantUvConfig(draft?.uvConfig ?? variant.uvConfig ?? null) + const skuContentFields = readAssetVariantSkuContentFields(variant.businessData) + resetVariantSkuAutoSaveState() setVariantModalMode('create') setEditingVariantId(null) setVariantCreateUvConfig(nextUvConfig) + const materialMode = inferVariantMaterialMode(variant, draft?.substrateId ?? variant.substrateId) setVariantForm({ assetFamilyId: variant.assetFamilyId, - code: variant.code, + materialMode, + model: skuContentFields.model ?? variant.assetFamilyCode, + code: '', name: variant.name, + setCount: skuContentFields.setCount ?? '1', sizeLabel: variant.sizeLabel ?? '', + color: skuContentFields.color ?? '', + material: skuContentFields.material ?? '', + boardMaterialType: readVariantSkuContentFieldWithDefault( + skuContentFields, + 'boardMaterialType', + NON_BOARD_ASSET_VARIANT_BOARD_MATERIAL_TYPE, + ), + attributeCode: readVariantSkuContentFieldWithDefault( + skuContentFields, + 'attributeCode', + DEFAULT_ASSET_VARIANT_ATTRIBUTE_CODE, + ), + drawingId: skuContentFields.drawingId ?? '', + installMethod: readVariantSkuContentFieldWithDefault( + skuContentFields, + 'installMethod', + DEFAULT_ASSET_VARIANT_INSTALL_METHOD, + ), + executeStandard: readVariantSkuContentFieldWithDefault( + skuContentFields, + 'executeStandard', + getDefaultVariantExecuteStandard(materialMode), + ), + nationalStandardCompliant: readVariantSkuContentFieldWithDefault( + skuContentFields, + 'nationalStandardCompliant', + DEFAULT_ASSET_VARIANT_NATIONAL_STANDARD_COMPLIANT, + ), + salesStatus: readVariantSkuContentFieldWithDefault( + skuContentFields, + 'salesStatus', + DEFAULT_ASSET_VARIANT_SALES_STATUS, + ), + batchNo: skuContentFields.batchNo ?? '批次1', + dingTalkFlowNo: skuContentFields.dingTalkFlowNo ?? '', substrateId: draft?.substrateId ?? variant.substrateId ?? '', finishId: variant.finishId ?? '', - supplierName: variant.supplierName ?? '', - supplierCode: variant.supplierCode ?? '', - versionNo: variant.versionNo ?? '', - barcode: variant.barcode ?? '', + steelFrameItemId: readAssetVariantMaterialSourceId( + variant.businessData, + ASSET_VARIANT_STEEL_FRAME_ITEM_ID_BUSINESS_DATA_KEY, + ), + packagingMaterialVariantId: readAssetVariantMaterialSourceId( + variant.businessData, + ASSET_VARIANT_PACKAGING_VARIANT_ID_BUSINESS_DATA_KEY, + ), + supplierName: variant.supplierName ?? skuContentFields.manufacturer ?? '', + supplierCode: variant.supplierCode ?? skuContentFields.manufacturerCode ?? '', + versionNo: + variant.versionNo ?? + readVariantSkuContentFieldWithDefault( + skuContentFields, + 'versionNo', + DEFAULT_SKU_VERSION_NO, + ), + barcode: variant.barcode ?? skuContentFields.barcode ?? '', length: String(dims.length ?? ''), width: String(dims.width ?? ''), thickness: String(dims.thickness ?? ''), @@ -1955,22 +3184,77 @@ export default function AssetCenterClient({ showReadOnlyWarning() return } + resetVariantSkuAutoSaveState() setVariantModalMode('edit') setEditingVariantId(variant.id) setVariantCreateUvConfig(null) const dims = variant.dimensions ?? {} const mp = variant.mountPoints?.[0] + const skuContentFields = readAssetVariantSkuContentFields(variant.businessData) + const materialMode = inferVariantMaterialMode(variant) setVariantForm({ assetFamilyId: variant.assetFamilyId, + materialMode, + model: skuContentFields.model ?? variant.assetFamilyCode, code: variant.code, name: variant.name, - sizeLabel: variant.sizeLabel ?? '', + setCount: skuContentFields.setCount ?? '1', + sizeLabel: variant.sizeLabel ?? skuContentFields.size ?? '', + color: skuContentFields.color ?? '', + material: skuContentFields.material ?? '', + boardMaterialType: readVariantSkuContentFieldWithDefault( + skuContentFields, + 'boardMaterialType', + NON_BOARD_ASSET_VARIANT_BOARD_MATERIAL_TYPE, + ), + attributeCode: readVariantSkuContentFieldWithDefault( + skuContentFields, + 'attributeCode', + DEFAULT_ASSET_VARIANT_ATTRIBUTE_CODE, + ), + drawingId: skuContentFields.drawingId ?? '', + installMethod: readVariantSkuContentFieldWithDefault( + skuContentFields, + 'installMethod', + DEFAULT_ASSET_VARIANT_INSTALL_METHOD, + ), + executeStandard: readVariantSkuContentFieldWithDefault( + skuContentFields, + 'executeStandard', + getDefaultVariantExecuteStandard(materialMode), + ), + nationalStandardCompliant: readVariantSkuContentFieldWithDefault( + skuContentFields, + 'nationalStandardCompliant', + DEFAULT_ASSET_VARIANT_NATIONAL_STANDARD_COMPLIANT, + ), + salesStatus: readVariantSkuContentFieldWithDefault( + skuContentFields, + 'salesStatus', + DEFAULT_ASSET_VARIANT_SALES_STATUS, + ), + batchNo: skuContentFields.batchNo ?? '批次1', + dingTalkFlowNo: skuContentFields.dingTalkFlowNo ?? '', substrateId: variant.substrateId ?? '', finishId: variant.finishId ?? '', - supplierName: variant.supplierName ?? '', - supplierCode: variant.supplierCode ?? '', - versionNo: variant.versionNo ?? '', - barcode: variant.barcode ?? '', + steelFrameItemId: readAssetVariantMaterialSourceId( + variant.businessData, + ASSET_VARIANT_STEEL_FRAME_ITEM_ID_BUSINESS_DATA_KEY, + ), + packagingMaterialVariantId: readAssetVariantMaterialSourceId( + variant.businessData, + ASSET_VARIANT_PACKAGING_VARIANT_ID_BUSINESS_DATA_KEY, + ), + supplierName: variant.supplierName ?? skuContentFields.manufacturer ?? '', + supplierCode: variant.supplierCode ?? skuContentFields.manufacturerCode ?? '', + versionNo: + variant.versionNo ?? + readVariantSkuContentFieldWithDefault( + skuContentFields, + 'versionNo', + DEFAULT_SKU_VERSION_NO, + ), + barcode: variant.barcode ?? skuContentFields.barcode ?? '', modelUrl: variant.modelUrl ?? '', length: String(dims.length ?? ''), width: String(dims.width ?? ''), @@ -1988,12 +3272,26 @@ export default function AssetCenterClient({ function closeVariantModal() { clearVariantSaveProgressPolling() + clearVariantSkuAutoSaveTimer() + variantSkuAutoSaveRequestRef.current += 1 setVariantSaveProgress(null) + setVariantSkuAutoSaveStatus('idle') setVariantModalOpen(false) setEditingVariantId(null) setVariantCreateUvConfig(null) } + function closePackagingVariantModal() { + clearVariantSaveProgressPolling() + clearVariantSkuAutoSaveTimer() + variantSkuAutoSaveRequestRef.current += 1 + setVariantSaveProgress(null) + setVariantSkuAutoSaveStatus('idle') + setPackagingVariantModalOpen(false) + setEditingVariantId(null) + setVariantCreateUvConfig(null) + } + function clearVariantSaveProgressPolling() { if (variantSaveProgressPollerRef.current != null) { window.clearInterval(variantSaveProgressPollerRef.current) @@ -2025,15 +3323,156 @@ export default function AssetCenterClient({ }, 700) } + function clearVariantSkuAutoSaveTimer() { + if (variantSkuAutoSaveTimerRef.current != null) { + window.clearTimeout(variantSkuAutoSaveTimerRef.current) + variantSkuAutoSaveTimerRef.current = null + } + } + + function buildVariantSkuUpdatePayload( + existingBusinessData?: Record | null, + ) { + const versionNo = resolveVariantSkuVersionNo(variantForm) + const barcode = resolveVariantBarcode({ + ...variantForm, + versionNo, + }) + const drawingId = resolveVariantDrawingId(variantForm) + const normalizedForm = { + ...variantForm, + versionNo, + barcode, + drawingId, + } + + return { + name: normalizedForm.name, + sizeLabel: normalizedForm.sizeLabel || null, + supplierName: normalizedForm.supplierName || null, + supplierCode: normalizedForm.supplierCode || null, + versionNo, + barcode: barcode || null, + businessData: buildVariantSkuContentBusinessData( + normalizedForm, + existingBusinessData, + ), + } + } + + useEffect(() => { + if ( + !variantModalOpen || + variantModalMode !== 'edit' || + !editingVariantId || + submitting || + !canOperateDesignWorkspace + ) { + return + } + + const editingVariant = variants.find((item) => item.id === editingVariantId) ?? null + if (!editingVariant) return + + const payload = { + ...buildVariantSkuUpdatePayload(editingVariant.businessData), + substrateId: resolvedVariantSubstrateId, + finishId: resolvedVariantFinishId, + } + const signature = JSON.stringify({ + variantId: editingVariantId, + payload, + }) + + if (signature === lastVariantSkuAutoSaveSignatureRef.current) { + return + } + + clearVariantSkuAutoSaveTimer() + setVariantSkuAutoSaveStatus('pending') + const requestId = variantSkuAutoSaveRequestRef.current + 1 + variantSkuAutoSaveRequestRef.current = requestId + + variantSkuAutoSaveTimerRef.current = window.setTimeout(() => { + setVariantSkuAutoSaveStatus('saving') + + void updateAssetVariant(editingVariantId, payload, { skipThumbnail: true }) + .then((updatedResult) => { + if (variantSkuAutoSaveRequestRef.current !== requestId) return + const updated = normalizeAssetVariantWithUv(updatedResult) + lastVariantSkuAutoSaveSignatureRef.current = signature + startTransition(() => { + setVariants((current) => + current.map((item) => (item.id === editingVariantId ? updated : item)), + ) + if (selectedVariantId === editingVariantId) { + setSelectedVariantId(updated.id) + } + }) + setVariantSkuAutoSaveStatus('saved') + }) + .catch(() => { + if (variantSkuAutoSaveRequestRef.current !== requestId) return + setVariantSkuAutoSaveStatus('failed') + }) + }, ASSET_VARIANT_SKU_AUTO_SAVE_DEBOUNCE_MS) + + return clearVariantSkuAutoSaveTimer + }, [ + canOperateDesignWorkspace, + editingVariantId, + resolvedVariantFinishId, + resolvedVariantSubstrateId, + selectedVariantId, + submitting, + variantForm, + variantModalMode, + variantModalOpen, + variants, + ]) + function applyInheritedVariant(variantId: string) { const inheritedVariant = variants.find((v) => v.id === variantId) if (!inheritedVariant) return + const skuContentFields = readAssetVariantSkuContentFields(inheritedVariant.businessData) + const materialMode = inferVariantMaterialMode(inheritedVariant) setVariantForm((current) => ({ ...current, inheritedFromVariantId: inheritedVariant.id, + materialMode, + model: current.model || skuContentFields.model || inheritedVariant.assetFamilyCode, + setCount: current.setCount || skuContentFields.setCount || '1', + color: current.color || skuContentFields.color || '', + material: current.material || skuContentFields.material || '', + boardMaterialType: materialMode === 'BOARD' + ? current.boardMaterialType || skuContentFields.boardMaterialType || '' + : current.boardMaterialType || + skuContentFields.boardMaterialType || + NON_BOARD_ASSET_VARIANT_BOARD_MATERIAL_TYPE, + attributeCode: current.attributeCode || skuContentFields.attributeCode || '', + drawingId: current.drawingId || skuContentFields.drawingId || '', + installMethod: current.installMethod || skuContentFields.installMethod || '', + executeStandard: current.executeStandard || skuContentFields.executeStandard || '', + nationalStandardCompliant: current.nationalStandardCompliant || skuContentFields.nationalStandardCompliant || '', + salesStatus: current.salesStatus || skuContentFields.salesStatus || '', + batchNo: current.batchNo || skuContentFields.batchNo || '批次1', + dingTalkFlowNo: current.dingTalkFlowNo || skuContentFields.dingTalkFlowNo || '', + supplierName: current.supplierName || inheritedVariant.supplierName || skuContentFields.manufacturer || '', + supplierCode: current.supplierCode || inheritedVariant.supplierCode || skuContentFields.manufacturerCode || '', + versionNo: current.versionNo || inheritedVariant.versionNo || skuContentFields.versionNo || '', + barcode: current.barcode || inheritedVariant.barcode || skuContentFields.barcode || '', + sizeLabel: current.sizeLabel || inheritedVariant.sizeLabel || skuContentFields.size || '', modelUrl: current.modelUrl || inheritedVariant.modelUrl, substrateId: current.substrateId || inheritedVariant.substrateId || '', finishId: current.finishId || inheritedVariant.finishId || '', + steelFrameItemId: current.steelFrameItemId || readAssetVariantMaterialSourceId( + inheritedVariant.businessData, + ASSET_VARIANT_STEEL_FRAME_ITEM_ID_BUSINESS_DATA_KEY, + ), + packagingMaterialVariantId: current.packagingMaterialVariantId || readAssetVariantMaterialSourceId( + inheritedVariant.businessData, + ASSET_VARIANT_PACKAGING_VARIANT_ID_BUSINESS_DATA_KEY, + ), mountPointName: inheritedVariant.mountPoints[0]?.name || current.mountPointName, mountX: String(inheritedVariant.mountPoints[0]?.position?.[0] ?? current.mountX), mountY: String(inheritedVariant.mountPoints[0]?.position?.[1] ?? current.mountY), @@ -2041,6 +3480,275 @@ export default function AssetCenterClient({ })) } + function updateVariantMaterialMode(materialMode: VariantMaterialMode) { + setVariantForm((current) => { + if (current.materialMode === materialMode) return current + return { + ...current, + materialMode, + substrateId: '', + finishId: '', + steelFrameItemId: '', + packagingMaterialVariantId: '', + color: '', + material: '', + boardMaterialType: + materialMode === 'BOARD' + ? current.boardMaterialType + : NON_BOARD_ASSET_VARIANT_BOARD_MATERIAL_TYPE, + executeStandard: getDefaultVariantExecuteStandard(materialMode), + } + }) + } + + function getVariantSkuFieldValue(key: AssetVariantSkuFieldKey) { + switch (key) { + case 'model': + return variantForm.model + case 'skuCode': + return variantForm.code + case 'barcode': + return variantForm.barcode || resolveVariantBarcode(variantForm) + case 'setCount': + return variantForm.setCount + case 'specName': + return variantForm.name + case 'size': + return variantForm.sizeLabel + case 'color': + return variantForm.color + case 'material': + return variantForm.material + case 'boardMaterialType': + return resolveVariantBoardMaterialTypeForSku(variantForm) + case 'versionNo': + return resolveVariantSkuVersionNo(variantForm) + case 'attributeCode': + return variantForm.attributeCode + case 'drawingId': + return variantForm.drawingId || resolveVariantDrawingId(variantForm) + case 'installMethod': + return variantForm.installMethod + case 'executeStandard': + return variantForm.executeStandard + case 'nationalStandardCompliant': + return variantForm.nationalStandardCompliant + case 'manufacturer': + return variantForm.supplierName + case 'manufacturerCode': + return variantForm.supplierCode + case 'salesStatus': + return variantForm.salesStatus + case 'batchNo': + return variantForm.batchNo + case 'dingTalkFlowNo': + return variantForm.dingTalkFlowNo + } + } + + function updateVariantSkuFieldValue(key: AssetVariantSkuFieldKey, value: string) { + setVariantForm((current) => { + switch (key) { + case 'barcode': + return { ...current, barcode: value.toUpperCase() } + case 'setCount': + return { ...current, setCount: value } + case 'specName': + return { ...current, name: value } + case 'size': + return { ...current, sizeLabel: value } + case 'color': + return { ...current, color: value } + case 'material': + return { ...current, material: value } + case 'boardMaterialType': + if (current.materialMode !== 'BOARD') return current + return { ...current, boardMaterialType: value } + case 'versionNo': + return { ...current, versionNo: value } + case 'attributeCode': + return { ...current, attributeCode: value.toUpperCase() } + case 'drawingId': + return { ...current, drawingId: value.toUpperCase() } + case 'installMethod': + return { ...current, installMethod: value } + case 'executeStandard': + return { ...current, executeStandard: value } + case 'nationalStandardCompliant': + return { ...current, nationalStandardCompliant: value } + case 'manufacturer': { + const supplierCode = resolveSupplierCodeByName(value) + return { ...current, supplierName: value, supplierCode } + } + case 'salesStatus': + return { ...current, salesStatus: value } + case 'dingTalkFlowNo': + return { ...current, dingTalkFlowNo: value } + case 'model': + case 'skuCode': + case 'manufacturerCode': + case 'batchNo': + return current + } + }) + } + + function renderVariantSkuContentTable() { + const editingVariant = editingVariantId + ? variants.find((item) => item.id === editingVariantId) ?? null + : null + const skuFieldDefinitions = isPackagingVariantForm + ? ASSET_VARIANT_SKU_FIELD_DEFINITIONS.filter((field) => field.key !== 'boardMaterialType') + : ASSET_VARIANT_SKU_FIELD_DEFINITIONS + + return ( +
+
+
+

SKU CONTENT

+

产品信息

+
+ + 1 行 + +
+
+ + + + + + {skuFieldDefinitions.map((field) => { + const columnWidth = getAssetVariantSkuFieldWidth(variantSkuColumnWidths, field) + return ( + + ) + })} + + + + + + + {skuFieldDefinitions.map((field) => { + const value = getVariantSkuFieldValue(field.key) + const isEditableDerivedField = + field.key === 'color' || field.key === 'material' + const isReadonly = field.control === 'readonly' && !isEditableDerivedField + const isFieldDisabled = + isReadonly || + (variantForm.materialMode !== 'BOARD' && field.key === 'boardMaterialType') + const columnWidth = getAssetVariantSkuFieldWidth(variantSkuColumnWidths, field) + const columnMinWidth = getAssetVariantSkuFieldMinWidth(field) + const selectOptions = + field.control === 'select' + ? Array.from(new Set([ + ...(value && !(field.options ?? []).includes(value) ? [value] : []), + ...(field.options ?? []), + ])) + : [] + + return ( + + ) + })} + + +
+ 序号 + + 图片 + + {field.label} +
+ 1 + +
+ {editingVariant?.thumbnailUrl ? ( + {`${variantForm.model + ) : ( + '暂无图片' + )} +
+
+ + setVariantSkuColumnWidths((current) => ({ + ...current, + [field.key]: normalizeAssetVariantSkuColumnWidth(field, nextWidth), + })) + } + > +
+ {field.control === 'select' ? ( + + ) : field.control === 'combobox' ? ( + updateVariantSkuFieldValue(field.key, nextValue)} + /> + ) : ( + updateVariantSkuFieldValue(field.key, event.target.value)} + className={cn( + 'h-9 min-w-0 flex-1 rounded-[5px] border border-[#dbe3e5] bg-white px-2 text-[13px] font-black text-[#2d3335] outline-none placeholder:text-[#8a9498]', + isReadonly && 'bg-[#f7f9f9] text-[#5a6062]/70', + )} + /> + )} +
+
+
+
+
+ ) + } + const refreshVariantThumbnailAfterCreate = useCallback(async (variant: AssetVariantDTO) => { if (!variant.modelUrl) return @@ -2091,27 +3799,9 @@ export default function AssetCenterClient({ width: variantForm.width, thickness: variantForm.thickness, }) - - if (variantModalMode === 'create') { - const progress = buildInitialVariantSaveProgress(isDuplicateVariantMode) - setVariantSaveProgress(progress) - startVariantSaveProgressPolling(progress.operationId) - - const createdResult = await createAssetVariantWithSimilarity({ - assetFamilyId: variantForm.assetFamilyId, - code: variantForm.code.trim() || undefined, - name: variantForm.name, - status: 'DRAFT', - sizeLabel: variantForm.sizeLabel || undefined, - substrateId: variantForm.substrateId || null, - finishId: selectedVariantSubstrateFinishId, - supplierName: variantForm.supplierName || null, - supplierCode: variantForm.supplierCode || null, - versionNo: variantForm.versionNo || null, - barcode: variantForm.barcode || null, - dimensions, - modelUrl: variantForm.modelUrl, - mountPoints: [ + const variantMountPoints: AssetVariantDTO['mountPoints'] = isPackagingVariantForm + ? [] + : [ { name: variantForm.mountPointName || 'origin', position: [ @@ -2120,8 +3810,33 @@ export default function AssetCenterClient({ Number(variantForm.mountZ) || 0, ], }, - ], - lossFactor: toOptionalNumber(variantForm.lossFactor), + ] + const variantLossFactor = isPackagingVariantForm + ? null + : toOptionalNumber(variantForm.lossFactor) + + if (variantModalMode === 'create') { + const skuPayload = buildVariantSkuUpdatePayload() + const progress = buildInitialVariantSaveProgress(isDuplicateVariantMode) + setVariantSaveProgress(progress) + startVariantSaveProgressPolling(progress.operationId) + + const createdResult = await createAssetVariantWithSimilarity({ + assetFamilyId: variantForm.assetFamilyId, + name: skuPayload.name, + status: 'DRAFT', + sizeLabel: skuPayload.sizeLabel || undefined, + substrateId: resolvedVariantSubstrateId, + finishId: resolvedVariantFinishId, + supplierName: skuPayload.supplierName, + supplierCode: skuPayload.supplierCode, + versionNo: skuPayload.versionNo, + barcode: skuPayload.barcode, + dimensions, + modelUrl: isPackagingVariantForm ? '' : variantForm.modelUrl, + mountPoints: variantMountPoints, + lossFactor: variantLossFactor, + businessData: skuPayload.businessData, inheritedFromVariantId: variantForm.inheritedFromVariantId || null, ...(variantCreateUvConfig ? { uvConfig: variantCreateUvConfig } : {}), }, { @@ -2146,7 +3861,7 @@ export default function AssetCenterClient({ void refreshVariantThumbnailAfterCreate(created) startTransition(() => { - setVariants((current) => [created, ...current]) + setVariants((current) => sortAssetVariantsByCreatedTime([created, ...current])) setExpandedFamilyIds((prev) => new Set(prev).add(created.assetFamilyId)) draftVariantUvConfigRef.current = createdUvConfig setDraftVariantUvConfig(createdUvConfig) @@ -2172,29 +3887,16 @@ export default function AssetCenterClient({ } } else { if (!editingVariantId) return + const editingVariant = variants.find((item) => item.id === editingVariantId) ?? null + const skuPayload = buildVariantSkuUpdatePayload(editingVariant?.businessData) const updated = normalizeAssetVariantWithUv(await updateAssetVariant(editingVariantId, { - code: variantForm.code.trim() || undefined, - name: variantForm.name, - sizeLabel: variantForm.sizeLabel || null, - substrateId: variantForm.substrateId || null, - finishId: selectedVariantSubstrateFinishId, - supplierName: variantForm.supplierName || null, - supplierCode: variantForm.supplierCode || null, - versionNo: variantForm.versionNo || null, - barcode: variantForm.barcode || null, - modelUrl: variantForm.modelUrl || undefined, + ...skuPayload, + substrateId: resolvedVariantSubstrateId, + finishId: resolvedVariantFinishId, dimensions, - mountPoints: [ - { - name: variantForm.mountPointName || 'origin', - position: [ - Number(variantForm.mountX) || 0, - Number(variantForm.mountY) || 0, - Number(variantForm.mountZ) || 0, - ], - }, - ], - lossFactor: toOptionalNumber(variantForm.lossFactor), + modelUrl: isPackagingVariantForm ? undefined : variantForm.modelUrl || undefined, + mountPoints: isPackagingVariantForm ? undefined : variantMountPoints, + lossFactor: isPackagingVariantForm ? undefined : variantLossFactor, })) startTransition(() => { setVariants((current) => @@ -2226,6 +3928,59 @@ export default function AssetCenterClient({ } } + async function handleCreatePackagingVariant() { + if (!canOperateDesignWorkspace) { + showReadOnlyWarning() + return + } + if (!variantForm.name.trim()) { + toast.error('请填写规格名称') + return + } + + setSubmitting(true) + try { + const dimensions = toNumberRecord({ + length: variantForm.length, + width: variantForm.width, + thickness: variantForm.thickness, + }) + const skuPayload = buildVariantSkuUpdatePayload() + const createdResult = await createPackagingAssetVariant({ + assetFamilyId: variantForm.assetFamilyId, + code: variantForm.code || undefined, + name: skuPayload.name, + status: 'DRAFT', + sizeLabel: skuPayload.sizeLabel || undefined, + substrateId: null, + finishId: resolvedVariantFinishId, + supplierName: skuPayload.supplierName, + supplierCode: skuPayload.supplierCode, + versionNo: skuPayload.versionNo, + barcode: skuPayload.barcode, + dimensions, + modelUrl: '', + mountPoints: [], + lossFactor: null, + businessData: skuPayload.businessData, + inheritedFromVariantId: null, + }) + const created = normalizeAssetVariantWithUv(createdResult.variant) + + startTransition(() => { + setVariants((current) => sortAssetVariantsByCreatedTime([created, ...current])) + setExpandedFamilyIds((prev) => new Set(prev).add(created.assetFamilyId)) + setSelectedVariantId(created.id) + closePackagingVariantModal() + toast.success('包材货号已创建') + }) + } catch (error) { + toast.error(error instanceof Error ? error.message : '包材货号创建失败,请稍后再试') + } finally { + setSubmitting(false) + } + } + function openRejectReviewDialog(targetType: ReviewDialogState['targetType'], targetId: string, targetName: string) { setReviewDialogState({ targetType, @@ -2797,6 +4552,12 @@ export default function AssetCenterClient({ const familyVariantOptions = variants.filter( (v) => v.assetFamilyId === variantForm.assetFamilyId, ) + const variantFormFamily = families.find((family) => family.id === variantForm.assetFamilyId) ?? null + const isPackagingVariantForm = variantForm.materialMode === 'PACKAGING' + const variantMaterialModeOptions = + variantFormFamily?.type === 'PACKAGING' + ? ASSET_VARIANT_PACKAGING_MATERIAL_MODE_OPTIONS + : ASSET_VARIANT_MATERIAL_MODE_OPTIONS async function handleImportCadAsset() { if (!canOperateDesignWorkspace) { @@ -2844,15 +4605,17 @@ export default function AssetCenterClient({ startTransition(() => { setFamilies((current) => - sortByName([ + sortAssetFamiliesByCreatedTime([ ...current.filter((family) => family.id !== result.family.id), result.family, ]), ) - setVariants((current) => [ - normalizeAssetVariantWithUv(result.variant), - ...current.filter((variant) => variant.id !== result.variant.id), - ]) + setVariants((current) => + sortAssetVariantsByCreatedTime([ + normalizeAssetVariantWithUv(result.variant), + ...current.filter((variant) => variant.id !== result.variant.id), + ]), + ) setExpandedFamilyIds((prev) => new Set(prev).add(result.family.id)) setSelectedVariantId(result.variant.id) }) @@ -3269,12 +5032,13 @@ export default function AssetCenterClient({ 共 {initialAssetSeries.length} 个 +
+ {selectedSeries ? ( + + ) : null} +
{seriesPickerOpen && (
@@ -3315,6 +5118,7 @@ export default function AssetCenterClient({ filteredAssetSeries.map((series) => { const active = selectedSeriesId === series.id const count = seriesAssetCounts.get(series.id) ?? 0 + const componentDetail = getSeriesComponentDetail(series) return ( ) @@ -3475,20 +5293,6 @@ export default function AssetCenterClient({ {/* 资产族列表 */}
- {activeTab === 'PACKAGING' && ( - -
- -
-

包材资料库

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

@@ -3760,11 +5564,17 @@ export default function AssetCenterClient({ {isImportableAssetType(family.type) ? ( + +

+ } + > +
+ {renderVariantSkuContentTable()} +
+
+

PACKAGING

+

包材资料

+
+
+
+

材料类型

+
+ 包材 +
+
+ { + const nextFinishId = e.target.value + const nextFinish = + variantMaterialFinishOptions.find((finish) => finish.id === nextFinishId) ?? null + setVariantForm((c) => ({ + ...c, + finishId: nextFinishId, + color: nextFinish?.name.trim() || c.color, + })) + }} + options={variantMaterialFinishOptions.map((finish) => ({ + value: finish.id, + label: `${finish.categoryName ?? '花色'} · ${finish.name} · ${finish.code}`, + }))} + /> +
+
+

尺寸参数 (mm)

+
+ setVariantForm((c) => ({ ...c, length: e.target.value }))} placeholder="1200" /> + setVariantForm((c) => ({ ...c, width: e.target.value }))} placeholder="600" /> + setVariantForm((c) => ({ ...c, thickness: e.target.value }))} placeholder="25" /> +
+
+
+
+ + {/* 规格款弹窗 —— 放在资产中心工作台外部,避免被父级 overflow/transform 裁切 */} {variantModalMode === 'edit' && editingVariantId && ( @@ -4335,6 +6233,17 @@ export default function AssetCenterClient({
)}
+ {variantModalMode === 'edit' && variantSkuAutoSaveStatus !== 'idle' ? ( + + {({ + pending: '待自动保存', + saving: '自动保存中', + saved: '已自动保存', + failed: '自动保存失败', + idle: '', + } satisfies Record)[variantSkuAutoSaveStatus]} + + ) : null} - ) : null} +
+
+

材料类型

+
+ {variantMaterialModeOptions.map(([mode, label]) => ( + + ))} +
+
+ {variantForm.materialMode === 'BOARD' ? ( + setVariantForm((c) => ({ + ...c, + steelFrameItemId: e.target.value, + substrateId: e.target.value ? '' : c.substrateId, + }))} + options={[ + { value: '', label: '未设置' }, + ...steelFrameMaterialOptions.map((option) => ({ + value: option.id, + label: option.displayName, + })), + ]} + /> + ) : null} + {variantForm.materialMode === 'PACKAGING' ? ( + { + const nextFinishId = e.target.value + const nextFinish = + variantMaterialFinishOptions.find((finish) => finish.id === nextFinishId) ?? null + setVariantForm((c) => ({ + ...c, + finishId: nextFinishId, + color: nextFinish?.name.trim() || c.color, + })) + }} + options={[ + { value: '', label: '未设置' }, + ...variantMaterialFinishOptions.map((finish) => ({ + value: finish.id, + label: `${finish.categoryName ?? '花色'} · ${finish.name} · ${finish.code}`, + })), + ]} + /> + ) : null} + {variantModalMode === 'create' ? ( + setVariantForm((c) => ({ ...c, length: e.target.value }))} placeholder="1200" disabled={isDuplicateVariantMode} /> - setVariantForm((c) => ({ ...c, width: e.target.value }))} placeholder="600" disabled={isDuplicateVariantMode} /> - setVariantForm((c) => ({ ...c, thickness: e.target.value }))} placeholder="25" disabled={isDuplicateVariantMode} /> - setVariantForm((c) => ({ ...c, lossFactor: e.target.value }))} placeholder="例如 1.15" /> +
+

尺寸参数 (mm)

+
+ setVariantForm((c) => ({ ...c, length: e.target.value }))} placeholder="1200" disabled={isDuplicateVariantMode} /> + setVariantForm((c) => ({ ...c, width: e.target.value }))} placeholder="600" disabled={isDuplicateVariantMode} /> + setVariantForm((c) => ({ ...c, thickness: e.target.value }))} placeholder="25" disabled={isDuplicateVariantMode} /> +
-
-
-

挂载点

-
- setVariantForm((c) => ({ ...c, mountPointName: e.target.value }))} /> - setVariantForm((c) => ({ ...c, mountX: e.target.value }))} /> - setVariantForm((c) => ({ ...c, mountY: e.target.value }))} /> - setVariantForm((c) => ({ ...c, mountZ: e.target.value }))} /> -
-
-
- - -
+ {!isPackagingVariantForm ? ( +
+

挂载点

+
+ setVariantForm((c) => ({ ...c, mountPointName: e.target.value }))} /> + setVariantForm((c) => ({ ...c, mountX: e.target.value }))} /> + setVariantForm((c) => ({ ...c, mountY: e.target.value }))} /> + setVariantForm((c) => ({ ...c, mountZ: e.target.value }))} /> +
+
+ ) : null} +
@@ -4543,8 +6520,9 @@ export default function AssetCenterClient({ setFamilyForm((c) => ({ ...c, code: e.target.value }))} - placeholder="留空由系统自动生成" + placeholder="系统自动生成" + disabled + readOnly />
{familyForm.type !== 'HARDWARE' ? ( -
-

归属系列

-
- {initialAssetSeries.map((series) => { - const checked = familyForm.assetSeriesId === series.id - return ( - - ) - })} -
-
+ setSelectedMaterialId(event.target.value)} + className="h-8 min-w-0 flex-1 rounded-[5px] border border-[#dbe3e5] bg-white px-2 text-[12px] font-black text-[#2d3335] outline-none disabled:bg-[#f7f9f9] disabled:text-[#5a6062]/55" + > + + {availableMaterialOptions.map((option) => ( + + ))} + + + + + {materialOptionsError ? ( +

+ {materialOptionsError} +

+ ) : null} + + {selectedMaterials.length > 0 ? ( +
+ {selectedMaterials.map((material) => { + const option = materialOptionById.get(material.assetVariantId) + const displayCode = material.code || option?.code || material.assetVariantId + const displayName = material.name || option?.name || '包装SKU' + + return ( +
+
+

+ {displayCode} +

+

+ {displayName} +

+
+ + onMaterialQuantityChange( + packageKey, + material.assetVariantId, + normalizePackageMaterialQuantity(event.target.value), + ) + } + className="h-7 w-full rounded-[5px] border border-[#dbe3e5] bg-white px-2 text-[11px] font-black text-[#2d3335] outline-none disabled:bg-[#eef2f3] disabled:text-[#5a6062]/55" + /> + +
+ ) + })} +
+ ) : ( +
+ 当前包还没有选择纸箱、泡沫、护角等包装 SKU。 +
+ )} + ) } @@ -1613,6 +1970,168 @@ function assignComponentToSinglePackage( }, {} as PackageComponentAssignments) } +function parsePackageItemQuantity(value: string | number | null | undefined) { + const numericValue = + typeof value === 'number' + ? value + : Number.parseInt(value?.trim() ?? '', 10) + return Number.isFinite(numericValue) && numericValue > 0 ? numericValue : 1 +} + +function mapComponentAssetTypeToPackagingItemType(assetType: string | null | undefined) { + const normalizedAssetType = assetType?.trim().toUpperCase() ?? '' + if (normalizedAssetType === 'BOARD') return 'panel' as const + if (normalizedAssetType === 'HARDWARE') return 'hardware' as const + if (normalizedAssetType === 'PACKAGING') return 'accessory' as const + return 'component' as const +} + +function normalizePackagingBoxDimension(value: number | null | undefined) { + return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 1 +} + +function normalizePackagingBoxOuterSizeMm( + box: PreSkuPackagingPlanDTO['boxes'][number] | undefined, +) { + return { + length: normalizePackagingBoxDimension(box?.outerSizeMm.length), + width: normalizePackagingBoxDimension(box?.outerSizeMm.width), + height: normalizePackagingBoxDimension(box?.outerSizeMm.height), + } +} + +function findPackagingInputItemForComponent( + preSku: DraftGroupPreSkuDTO, + component: NonIntegratedSkuComponentDetail, +) { + const componentCode = getComponentDetailCode(component) + const componentName = normalizeComponentCode(component.name) + const componentRole = normalizeComponentCode(component.role) + + return preSku.packagingInput.items.find((item) => { + const candidates = [ + item.refCode, + item.name, + item.role, + item.slotKey, + item.selectionKey, + ].map(normalizeComponentCode) + return candidates.some((candidate) => + candidate && + (candidate === componentCode || + candidate === componentName || + candidate === componentRole), + ) + }) +} + +function buildPackagingPlanItemsForComponents( + preSku: DraftGroupPreSkuDTO, + components: NonIntegratedSkuComponentDetail[], +): SavePreSkuPackagingPlanInput['boxes'][number]['items'] { + return components.flatMap((component) => { + const componentCode = getComponentDetailCode(component) + const inputItem = findPackagingInputItemForComponent(preSku, component) + const refId = inputItem?.refId || componentCode + const refCode = inputItem?.refCode || component.code || componentCode + const name = + inputItem?.name || + component.name || + component.role || + component.code || + componentCode + + if (!refId || !refCode || !name) return [] + + return [ + { + itemType: + inputItem?.itemType ?? + mapComponentAssetTypeToPackagingItemType(component.assetType), + refId, + refCode, + name, + slotKey: inputItem?.slotKey ?? null, + role: inputItem?.role || component.role || null, + selectionKey: inputItem?.selectionKey ?? null, + quantity: inputItem?.quantity ?? parsePackageItemQuantity(component.quantity), + notes: null, + }, + ] + }) +} + +function buildSavePackagingPlanInput({ + preSku, + packageRows, + packageAssignments, + packageMaterialAssignments, +}: { + preSku: DraftGroupPreSkuDTO + packageRows: SkuContentPreviewRow[] + packageAssignments: PackageComponentAssignments + packageMaterialAssignments: PackageMaterialAssignments +}): SavePreSkuPackagingPlanInput { + const allComponentDetails = readPreSkuComponentDetails(preSku) + const resolvedPackageAssignments = buildResolvedPackageComponentAssignments( + packageRows, + packageAssignments, + allComponentDetails, + ) + const existingBoxes = preSku.packagingPlan?.boxes ?? [] + const normalizedMaterialAssignments = Object.entries(packageMaterialAssignments).reduce( + (next, [packageKey, assignments]) => { + next[getPackageKey(packageKey)] = normalizePackageMaterialAssignments(assignments) + return next + }, + {} as PackageMaterialAssignments, + ) + + return { + sourceType: 'DRAFT_GROUP', + sourceRefId: preSku.draftGroupId, + status: 'DRAFT', + boxes: packageRows.map((row, index) => { + const packageKey = getPackageKey(row.packageSuffix) + const assignedComponentCodes = resolvedPackageAssignments[packageKey] ?? [] + const selectedComponents = + packageRows.length <= 1 && assignedComponentCodes.length === 0 + ? allComponentDetails + : getComponentDetailsByCodes( + allComponentDetails, + assignedComponentCodes, + ) + const existingBox = existingBoxes[index] + + return { + boxNumber: index + 1, + name: getPackageLabel(packageKey), + outerSizeMm: normalizePackagingBoxOuterSizeMm(existingBox), + items: buildPackagingPlanItemsForComponents(preSku, selectedComponents), + materials: normalizePackageMaterialAssignments( + normalizedMaterialAssignments[packageKey] ?? [], + ).map((material) => ({ + assetVariantId: material.assetVariantId, + assetFamilyId: material.assetFamilyId ?? null, + code: material.code ?? null, + name: material.name ?? null, + quantity: material.quantity, + notes: material.notes ?? null, + })), + estimatedWeightKg: existingBox?.estimatedWeightKg ?? null, + estimatedCost: existingBox?.estimatedCost ?? null, + notes: existingBox?.notes ?? null, + } + }), + costSummary: null, + processDraft: { + packageComponentAssignments: resolvedPackageAssignments, + packageMaterialAssignments: normalizedMaterialAssignments, + }, + notes: preSku.packagingPlan?.notes ?? null, + } +} + function buildPushedSkuItem({ preSku, sequence, @@ -1787,7 +2306,12 @@ function SkuContentPreview({ saveState, activePackageKey, packageAssignments, + packageMaterialAssignments, + packagingMaterialOptions, + packagingMaterialOptionsLoading, + packagingMaterialOptionsError, packageComponentSaving, + packagingPlanSaving, formalSeriesSpu, formalSkuCode, pushDisabledReason, @@ -1797,6 +2321,9 @@ function SkuContentPreview({ actionError, onFieldChange, onTogglePackage, + onPackageMaterialAdd, + onPackageMaterialRemove, + onPackageMaterialQuantityChange, onPush, onDeleteDraftGroup, }: { @@ -1809,7 +2336,12 @@ function SkuContentPreview({ saveState: SkuContentAutoSaveState | null activePackageKey: string | null packageAssignments: PackageComponentAssignments + packageMaterialAssignments: PackageMaterialAssignments + packagingMaterialOptions: PackagingMaterialOption[] + packagingMaterialOptionsLoading: boolean + packagingMaterialOptionsError: string | null packageComponentSaving: boolean + packagingPlanSaving: boolean formalSeriesSpu: string formalSkuCode: string pushDisabledReason: string @@ -1819,6 +2351,9 @@ function SkuContentPreview({ actionError: string | null onFieldChange: (key: SkuContentFieldKey, value: string) => void onTogglePackage: (packageKey: string) => void + onPackageMaterialAdd: (packageKey: string, material: PackagingMaterialOption) => void + onPackageMaterialRemove: (packageKey: string, assetVariantId: string) => void + onPackageMaterialQuantityChange: (packageKey: string, assetVariantId: string, quantity: number) => void onPush: () => void onDeleteDraftGroup: () => void }) { @@ -1995,7 +2530,7 @@ function SkuContentPreview({ onChange={(event) => onFieldChange(field.key, event.target.value)} className="h-8 min-w-0 flex-1 rounded-[5px] border border-[#dbe3e5] bg-white px-2 text-[12px] font-black text-[#2d3335] outline-none disabled:bg-[#f7f9f9] disabled:text-[#5a6062]/55" > - + ))} @@ -2005,7 +2540,7 @@ function SkuContentPreview({ ariaLabel={field.label} value={value} options={field.options ?? []} - placeholder={field.placeholder} + placeholder="" readOnly={pushed || pushing} dropdownId={`supplier-options-${preSku.id}-${row.key}`} onChange={(nextValue) => onFieldChange(field.key, nextValue)} @@ -2015,7 +2550,7 @@ function SkuContentPreview({ readOnly={Boolean(isReadonly)} aria-label={field.label} value={value} - placeholder={field.placeholder} + placeholder="" onChange={(event) => onFieldChange(field.key, event.target.value)} className={cn( 'h-8 min-w-0 flex-1 rounded-[5px] border border-[#dbe3e5] bg-white px-2 text-[12px] font-black text-[#2d3335] outline-none placeholder:text-[#8a9498]', @@ -2053,7 +2588,14 @@ function SkuContentPreview({ rows={previewRows} componentDetails={allComponentDetails} packageAssignments={packageAssignments} - saving={packageComponentSaving} + packageMaterialAssignments={packageMaterialAssignments} + materialOptions={packagingMaterialOptions} + materialOptionsLoading={packagingMaterialOptionsLoading} + materialOptionsError={packagingMaterialOptionsError} + saving={packageComponentSaving || packagingPlanSaving} + onMaterialAdd={onPackageMaterialAdd} + onMaterialRemove={onPackageMaterialRemove} + onMaterialQuantityChange={onPackageMaterialQuantityChange} /> @@ -2140,7 +2682,14 @@ export default function DraftGroupsFormalClient({ const [packageComponentAssignmentsByPreSkuId, setPackageComponentAssignmentsByPreSkuId] = useState< Record >(() => readStoredPackageComponentAssignments()) + const [packageMaterialAssignmentsByPreSkuId, setPackageMaterialAssignmentsByPreSkuId] = useState< + Record + >(() => readStoredPackageMaterialAssignments()) + const [packagingMaterialOptionsByPreSkuId, setPackagingMaterialOptionsByPreSkuId] = useState< + Record + >({}) const [savingPackageComponentKey, setSavingPackageComponentKey] = useState(null) + const [savingPackagingPlanKey, setSavingPackagingPlanKey] = useState(null) const [pushingPreSkuId, setPushingPreSkuId] = useState(null) const [deletingDraftGroupId, setDeletingDraftGroupId] = useState(null) const [leftPaneWidth, setLeftPaneWidth] = useState(() => @@ -2241,6 +2790,21 @@ export default function DraftGroupsFormalClient({ const selectedPackageComponentAssignments = selectedPreSku ? packageComponentAssignmentsByPreSkuId[selectedPreSku.id] ?? {} : {} + const selectedPackageMaterialAssignments = selectedPreSku + ? packageMaterialAssignmentsByPreSkuId[selectedPreSku.id] ?? + buildPackageMaterialAssignmentsFromPackagingPlan(selectedPreSku.packagingPlan) + : {} + const selectedPackagingMaterialOptionsState = selectedPreSku + ? packagingMaterialOptionsByPreSkuId[selectedPreSku.id] ?? { + loading: false, + error: null, + options: [], + } + : { + loading: false, + error: null, + options: [], + } const selectedSkuContentSaveState = selectedPreSku ? skuContentSaveStateByPreSkuId[selectedPreSku.id] ?? null : null @@ -2486,6 +3050,78 @@ export default function DraftGroupsFormalClient({ }) } + function savePackageMaterialAssignmentsForPreSku( + preSkuId: string, + assignments: PackageMaterialAssignments, + ) { + const normalizedAssignments = Object.entries(assignments).reduce( + (next, [packageKey, materials]) => { + next[getPackageKey(packageKey)] = normalizePackageMaterialAssignments(materials) + return next + }, + {} as PackageMaterialAssignments, + ) + + setPackageMaterialAssignmentsByPreSkuId((current) => { + const next = { + ...current, + [preSkuId]: normalizedAssignments, + } + writeStoredPackageMaterialAssignments(next) + return next + }) + } + + function replacePreSkuPackagingPlan(preSkuId: string, packagingPlan: PreSkuPackagingPlanDTO) { + setDetailById((current) => { + const nextEntries = Object.entries(current).map(([draftGroupId, detail]) => [ + draftGroupId, + { + ...detail, + preSkus: detail.preSkus.map((preSku) => + preSku.id === preSkuId + ? { + ...preSku, + packagingPlan, + } + : preSku, + ), + }, + ] as const) + return Object.fromEntries(nextEntries) + }) + } + + async function syncPreSkuPackagingPlan( + packageAssignments: PackageComponentAssignments, + packageMaterialAssignments: PackageMaterialAssignments, + activePackageKey: string, + ) { + if (!selectedPreSku || selectedPackageRows.length === 0) return + + const normalizedActivePackageKey = getPackageKey(activePackageKey) + const savingKey = `${selectedPreSku.id}:${normalizedActivePackageKey}` + setSavingPackagingPlanKey(savingKey) + setActionError(null) + + try { + const packagingPlan = await savePreSkuPackagingPlan( + selectedPreSku.id, + buildSavePackagingPlanInput({ + preSku: selectedPreSku, + packageRows: selectedPackageRows, + packageAssignments, + packageMaterialAssignments, + }), + ) + replacePreSkuPackagingPlan(selectedPreSku.id, packagingPlan) + } catch (error) { + setActionError(error instanceof Error ? error.message : '包装结构保存失败') + } finally { + setSavingPackagingPlanKey((current) => current === savingKey ? null : current) + } + } + async function syncPushedPackageAssignments( assignments: PackageComponentAssignments, activePackageKey: string, @@ -2587,6 +3223,91 @@ export default function DraftGroupsFormalClient({ if (selectedSkuPushed) { void syncPushedPackageAssignments(nextAssignments, packageKey ?? packageKeys[0] ?? 'single') } + + void syncPreSkuPackagingPlan( + nextAssignments, + selectedPackageMaterialAssignments, + packageKey ?? packageKeys[0] ?? 'single', + ) + } + + function handlePackageMaterialAdd(packageKey: string, material: PackagingMaterialOption) { + if (!selectedPreSku) return + const normalizedPackageKey = getPackageKey(packageKey) + const currentMaterials = selectedPackageMaterialAssignments[normalizedPackageKey] ?? [] + const nextMaterials = normalizePackageMaterialAssignments([ + ...currentMaterials, + { + assetVariantId: material.assetVariantId, + assetFamilyId: material.assetFamilyId, + code: material.code, + name: material.name, + quantity: 1, + notes: null, + }, + ]) + const nextAssignments = { + ...selectedPackageMaterialAssignments, + [normalizedPackageKey]: nextMaterials, + } + + savePackageMaterialAssignmentsForPreSku(selectedPreSku.id, nextAssignments) + void syncPreSkuPackagingPlan( + selectedPackageComponentAssignments, + nextAssignments, + normalizedPackageKey, + ) + } + + function handlePackageMaterialRemove(packageKey: string, assetVariantId: string) { + if (!selectedPreSku) return + const normalizedPackageKey = getPackageKey(packageKey) + const nextMaterials = normalizePackageMaterialAssignments( + (selectedPackageMaterialAssignments[normalizedPackageKey] ?? []).filter( + (material) => material.assetVariantId !== assetVariantId, + ), + ) + const nextAssignments = { + ...selectedPackageMaterialAssignments, + [normalizedPackageKey]: nextMaterials, + } + + savePackageMaterialAssignmentsForPreSku(selectedPreSku.id, nextAssignments) + void syncPreSkuPackagingPlan( + selectedPackageComponentAssignments, + nextAssignments, + normalizedPackageKey, + ) + } + + function handlePackageMaterialQuantityChange( + packageKey: string, + assetVariantId: string, + quantity: number, + ) { + if (!selectedPreSku) return + const normalizedPackageKey = getPackageKey(packageKey) + const nextMaterials = normalizePackageMaterialAssignments( + (selectedPackageMaterialAssignments[normalizedPackageKey] ?? []).map((material) => + material.assetVariantId === assetVariantId + ? { + ...material, + quantity: normalizePackageMaterialQuantity(quantity), + } + : material, + ), + ) + const nextAssignments = { + ...selectedPackageMaterialAssignments, + [normalizedPackageKey]: nextMaterials, + } + + savePackageMaterialAssignmentsForPreSku(selectedPreSku.id, nextAssignments) + void syncPreSkuPackagingPlan( + selectedPackageComponentAssignments, + nextAssignments, + normalizedPackageKey, + ) } async function handlePushSelectedSku() { @@ -2705,6 +3426,52 @@ export default function DraftGroupsFormalClient({ } } + useEffect(() => { + if (!selectedPreSku) return + const preSkuId = selectedPreSku.id + const existingState = packagingMaterialOptionsByPreSkuId[preSkuId] + if (existingState) return + + let cancelled = false + setPackagingMaterialOptionsByPreSkuId((current) => ({ + ...current, + [preSkuId]: { + loading: true, + error: null, + options: [], + }, + })) + + void (async () => { + try { + const result = await getPreSkuPackagingMaterialOptions(preSkuId) + if (cancelled) return + setPackagingMaterialOptionsByPreSkuId((current) => ({ + ...current, + [preSkuId]: { + loading: false, + error: null, + options: flattenPackagingMaterialOptions(result), + }, + })) + } catch (error) { + if (cancelled) return + setPackagingMaterialOptionsByPreSkuId((current) => ({ + ...current, + [preSkuId]: { + loading: false, + error: error instanceof Error ? error.message : '包装SKU读取失败', + options: [], + }, + })) + } + })() + + return () => { + cancelled = true + } + }, [packagingMaterialOptionsByPreSkuId, selectedPreSku]) + useEffect(() => { return () => { Object.values(skuContentAutoSaveTimersRef.current).forEach((timer) => { @@ -3156,6 +3923,10 @@ export default function DraftGroupsFormalClient({ saveState={selectedSkuContentSaveState} activePackageKey={activePackageKey} packageAssignments={selectedPackageComponentAssignments} + packageMaterialAssignments={selectedPackageMaterialAssignments} + packagingMaterialOptions={selectedPackagingMaterialOptionsState.options} + packagingMaterialOptionsLoading={selectedPackagingMaterialOptionsState.loading} + packagingMaterialOptionsError={selectedPackagingMaterialOptionsState.error} packageComponentSaving={ Boolean( selectedPreSku && @@ -3163,6 +3934,13 @@ export default function DraftGroupsFormalClient({ savingPackageComponentKey === `${selectedPreSku.id}:${activePackageKey}`, ) } + packagingPlanSaving={ + Boolean( + selectedPreSku && + activePackageKey && + savingPackagingPlanKey === `${selectedPreSku.id}:${activePackageKey}`, + ) + } formalSeriesSpu={selectedFormalSeriesProduct?.spu ?? ''} formalSkuCode={selectedFormalSkuCode} pushDisabledReason={pushDisabledReason} @@ -3174,6 +3952,9 @@ export default function DraftGroupsFormalClient({ onTogglePackage={(packageKey) => setActivePackageKey((current) => current === packageKey ? null : packageKey) } + onPackageMaterialAdd={handlePackageMaterialAdd} + onPackageMaterialRemove={handlePackageMaterialRemove} + onPackageMaterialQuantityChange={handlePackageMaterialQuantityChange} onPush={handlePushSelectedSku} onDeleteDraftGroup={() => handleDeleteDraftGroup(selectedDraftGroup, selectedDraftSkuName, selectedSkuPushed) @@ -3191,6 +3972,7 @@ export default function DraftGroupsFormalClient({ preSku={selectedPreSku} packageRows={selectedPackageRows} packageAssignments={selectedPackageComponentAssignments} + packageMaterialAssignments={selectedPackageMaterialAssignments} saving={Boolean( selectedPreSku && savingPackageComponentKey?.startsWith(`${selectedPreSku.id}:`), diff --git a/furniture-3d-system/src/app/intake/AccessoryLibraryPanel.tsx b/furniture-3d-system/src/app/intake/AccessoryLibraryPanel.tsx index 09e5776a..899ee394 100644 --- a/furniture-3d-system/src/app/intake/AccessoryLibraryPanel.tsx +++ b/furniture-3d-system/src/app/intake/AccessoryLibraryPanel.tsx @@ -80,12 +80,20 @@ const LETTER_CATEGORY_LABELS: Partial> = E: '预埋螺母', F: '合页/铰链', G: '滑轨', + H: '螺母/螺帽', I: '脚轮/万向轮', J: '拉手', K: '层板托', L: '角码/连接片', - M: '门吸/反弹器', + M: '门吸/反弹器/移门轮', N: '孔塞/孔贴', + O: '木榫/木销', + P: '翻门/支撑配件', + Q: '线盒/透气孔', + R: '挂钩', + S: '卡扣/挡块', + T: '垫片/脚垫', + U: '辅助固定件', } const A_HEAD_TYPES: HeadType[] = [ @@ -202,6 +210,14 @@ const G_SCREW_CATEGORIES = [ '骑马抽滑轨', '二节滑轨', ] +const H_SCREW_CATEGORIES = [ + '六角螺母', + '法兰螺母', + '防松螺母', + '盖形螺母', + '蝶形螺母', + '套筒螺母', +] const I_CASTER_CATEGORIES = ['万向轮', '定向轮'] const I_FURNITURE_LEG_CATEGORIES = ['家具脚', '调节脚'] const I_SCREW_CATEGORIES = [ @@ -211,8 +227,57 @@ const I_SCREW_CATEGORIES = [ const J_SCREW_CATEGORIES = ['拉手'] const K_SCREW_CATEGORIES = ['层板托'] const L_SCREW_CATEGORIES = ['角码', '连接片'] -const M_SCREW_CATEGORIES = ['门吸', '反弹器'] +const M_SCREW_CATEGORIES = ['门吸', '反弹器', '移门轮'] +const M_STANDARD_TAIL_OPTIONS = ['明装', '暗装', '嵌入式', '螺丝固定', '免打孔'] +const M_STANDARD_MATERIAL_OPTIONS = ['铁', '锌合金', '不锈钢', '304不锈钢', '塑料', '尼龙'] +const M_STANDARD_TOOTH_OPTIONS = ['普通', '强磁', '按压反弹', '可调节', '缓冲'] +const M_STANDARD_DIAMETER_OPTIONS = ['小号', '中号', '大号', '短款', '长款'] +const M_STANDARD_COLOR_OPTIONS = ['银色', '黑色', '灰色', '白色', '本色'] +const M_SLIDING_WHEEL_TAIL_OPTIONS = ['上轮', '下轮', '导轮', '定位片'] +const M_SLIDING_WHEEL_DIAMETER_OPTIONS = ['25mm', '30mm', '35mm', '40mm'] +const M_SLIDING_WHEEL_MATERIAL_OPTIONS = ['塑料', '尼龙', '铁', '不锈钢'] +const M_SLIDING_WHEEL_COLOR_OPTIONS = ['黑色', '白色', '银色', '灰色'] const N_SCREW_CATEGORIES = ['孔塞', '孔贴'] +const O_SCREW_CATEGORIES = ['圆木榫'] +const P_SCREW_CATEGORIES = ['液压杆', '翻折配件', '翻斗铰链'] +const P_HYDRAULIC_FORCE_OPTIONS = ['50N', '80N', '100N', '120N', '150N'] +const P_HYDRAULIC_LENGTH_OPTIONS = ['245mm', '270mm', '300mm', '350mm'] +const P_HYDRAULIC_TAIL_OPTIONS = ['上翻门', '下翻门', '通用'] +const P_FOLDING_MODEL_OPTIONS = ['小号', '中号', '大号', '左', '右', '左右套装'] +const P_FOLDING_FUNCTION_OPTIONS = ['普通', '缓冲', '可停'] +const P_FLIP_HINGE_LAYER_OPTIONS = ['单层', '双层', '三层'] +const P_FLIP_HINGE_SIZE_OPTIONS = ['240*310mm', '260*320mm', '280*340mm'] +const P_FLIP_HINGE_TAIL_OPTIONS = ['单只', '左右套装'] +const P_MATERIAL_OPTIONS = ['铁', '塑料', '不锈钢', '冷轧钢', '锌合金', '尼龙'] +const P_COLOR_OPTIONS = ['银色', '白色', '黑色', '灰色'] +const Q_SCREW_CATEGORIES = ['穿线盒', '透气孔', '无线充电盒'] +const Q_SHAPE_OPTIONS = ['圆形', '方形', '长方形'] +const Q_SIZE_OPTIONS = ['40mm', '50mm', '60mm', '80mm', '100mm'] +const Q_MATERIAL_OPTIONS = ['塑料', '铁', '铝合金'] +const Q_COLOR_OPTIONS = ['黑色', '白色', '银色', '灰色'] +const R_SCREW_CATEGORIES = ['挂钩'] +const R_STYLE_OPTIONS = ['普通', 'S型', '耳机', '圆形', '异形'] +const R_SIZE_OPTIONS = ['小号', '中号', '大号'] +const R_TAIL_OPTIONS = ['螺丝固定', '免钉', '卡扣', '挂入'] +const R_MATERIAL_OPTIONS = ['塑料', '铁', '不锈钢', '实木'] +const R_COLOR_OPTIONS = ['黑色', '白色', '银色', '原木色', '金色'] +const S_SCREW_CATEGORIES = ['卡扣', '挡块'] +const S_USAGE_OPTIONS = ['背板', '子母', '防倒', '门挡', '限位', '通用'] +const S_SIZE_OPTIONS = ['小号', '中号', '大号', '30*20mm', '40*20mm'] +const S_MATERIAL_OPTIONS = ['塑料', '铁', '不锈钢'] +const S_COLOR_OPTIONS = ['白色', '黑色', '银色', '灰色'] +const T_SCREW_CATEGORIES = ['垫片', '脚垫'] +const T_USAGE_OPTIONS = ['普通', '毛毡', '防滑', '螺丝', '弹簧', '脚套', '吸盘'] +const T_SHAPE_OPTIONS = ['圆形', '方形', '长方形', '异形'] +const T_SIZE_OPTIONS = ['φ18', 'φ25', 'φ28', 'φ32', 'M6', 'M8', '12*4mm', '20*20mm'] +const T_THICKNESS_OPTIONS = ['1mm', '2mm', '3mm', '4mm', '5mm'] +const T_MATERIAL_OPTIONS = ['塑料', '橡胶', '毛毡', '铁', '不锈钢'] +const T_COLOR_OPTIONS = ['黑色', '白色', '灰色', '透明', '银色'] +const U_SCREW_CATEGORIES = ['扎带', '粘贴件', '钉类'] +const U_USAGE_OPTIONS = ['固定', '粘贴', '装饰', '安装'] +const U_SIZE_OPTIONS = ['3M', '小号', '中号', '大号', '100mm', '150mm', '200mm'] +const U_MATERIAL_OPTIONS = ['尼龙', '塑料', '铁', '不锈钢', '胶'] +const U_COLOR_OPTIONS = ['黑色', '白色', '透明', '银色', '彩色'] const CATEGORY_SHORTCUTS_BY_LETTER: Partial< Record @@ -222,12 +287,20 @@ const CATEGORY_SHORTCUTS_BY_LETTER: Partial< E: E_SCREW_CATEGORIES, F: F_SCREW_CATEGORIES, G: G_SCREW_CATEGORIES, + H: H_SCREW_CATEGORIES, I: I_SCREW_CATEGORIES, J: J_SCREW_CATEGORIES, K: K_SCREW_CATEGORIES, L: L_SCREW_CATEGORIES, M: M_SCREW_CATEGORIES, N: N_SCREW_CATEGORIES, + O: O_SCREW_CATEGORIES, + P: P_SCREW_CATEGORIES, + Q: Q_SCREW_CATEGORIES, + R: R_SCREW_CATEGORIES, + S: S_SCREW_CATEGORIES, + T: T_SCREW_CATEGORIES, + U: U_SCREW_CATEGORIES, } const SELECT_FIELDS = [ @@ -659,6 +732,58 @@ const G_SELECT_FIELD_OVERRIDES: Partial< }, } +const H_SELECT_FIELD_OVERRIDES: Partial< + Record>> +> = { + screwCategory: { + options: H_SCREW_CATEGORIES, + }, + material: { + label: '材质', + options: [ + '碳钢', + '不锈钢', + '304不锈钢', + '201不锈钢', + '铜', + '黄铜', + '尼龙', + '塑料', + ], + }, + finish: { + label: '表面处理', + options: ['镀锌', '镀白锌', '镀镍', '发黑', '本色', '彩锌', '黄锌', '镀铬'], + }, + diameter: { + label: '规格', + options: ['M3', 'M4', 'M5', 'M6', 'M8', 'M10', 'M12'], + }, + length: { + label: '高度/长度', + options: [ + '普通', + '薄型', + '加厚', + '6mm', + '8mm', + '10mm', + '12mm', + '15mm', + '20mm', + '25mm', + '30mm', + '35mm', + '40mm', + '50mm', + ], + }, + color: { + label: '颜色', + options: ['银色', '黑色', '金色', '本色', '白色', '彩锌色'], + }, +} + const J_SELECT_FIELD_OVERRIDES: Partial< Record>> > = { @@ -931,22 +1056,22 @@ const M_SELECT_FIELD_OVERRIDES: Partial< }, tail: { label: '安装方式', - options: ['明装', '暗装', '嵌入式', '螺丝固定', '免打孔'], + options: M_STANDARD_TAIL_OPTIONS, }, material: { label: '材质', - options: ['铁', '锌合金', '不锈钢', '304不锈钢', '塑料', '尼龙'], + options: M_STANDARD_MATERIAL_OPTIONS, }, tooth: { label: '功能', - options: ['普通', '强磁', '按压反弹', '可调节', '缓冲'], + options: M_STANDARD_TOOTH_OPTIONS, }, diameter: { label: '规格', - options: ['小号', '中号', '大号', '短款', '长款'], + options: M_STANDARD_DIAMETER_OPTIONS, }, color: { - options: ['银色', '黑色', '灰色', '白色', '本色'], + options: M_STANDARD_COLOR_OPTIONS, }, } @@ -982,6 +1107,194 @@ const N_SELECT_FIELD_OVERRIDES: Partial< }, } +const O_SELECT_FIELD_OVERRIDES: Partial< + Record>> +> = { + screwCategory: { + options: O_SCREW_CATEGORIES, + }, + drive: { + label: '纹路', + options: ['斜纹', '直纹', '光面'], + }, + material: { + label: '材质', + options: ['桦木', '榉木', '橡胶木', '杂木', '松木', '杨木'], + }, + diameter: { + label: '规格/直径', + options: ['6mm', '8mm', '10mm', '12mm'], + }, + length: { + label: '长度', + options: ['20mm', '25mm', '30mm', '35mm', '40mm', '50mm'], + }, +} + +const P_SELECT_FIELD_OVERRIDES: Partial< + Record>> +> = { + screwCategory: { + options: P_SCREW_CATEGORIES, + }, + tail: { + label: '安装方式', + options: P_HYDRAULIC_TAIL_OPTIONS, + }, + material: { + label: '材质', + options: P_MATERIAL_OPTIONS, + }, + tooth: { + label: '功能', + options: P_FOLDING_FUNCTION_OPTIONS, + }, + diameter: { + label: '规格/力度', + options: P_HYDRAULIC_FORCE_OPTIONS, + }, + length: { + label: '长度', + options: P_HYDRAULIC_LENGTH_OPTIONS, + }, + color: { + label: '颜色', + options: P_COLOR_OPTIONS, + }, +} + +const Q_SELECT_FIELD_OVERRIDES: Partial< + Record>> +> = { + screwCategory: { + options: Q_SCREW_CATEGORIES, + }, + drive: { + label: '形状', + options: Q_SHAPE_OPTIONS, + }, + material: { + label: '材质', + options: Q_MATERIAL_OPTIONS, + }, + diameter: { + label: '规格/尺寸', + options: Q_SIZE_OPTIONS, + }, + color: { + label: '颜色', + options: Q_COLOR_OPTIONS, + }, +} + +const R_SELECT_FIELD_OVERRIDES: Partial< + Record>> +> = { + screwCategory: { + options: R_SCREW_CATEGORIES, + }, + drive: { + label: '款式/形状', + options: R_STYLE_OPTIONS, + }, + tail: { + label: '安装方式', + options: R_TAIL_OPTIONS, + }, + material: { + label: '材质', + options: R_MATERIAL_OPTIONS, + }, + diameter: { + label: '规格/尺寸', + options: R_SIZE_OPTIONS, + }, + color: { + label: '颜色', + options: R_COLOR_OPTIONS, + }, +} + +const S_SELECT_FIELD_OVERRIDES: Partial< + Record>> +> = { + screwCategory: { + options: S_SCREW_CATEGORIES, + }, + drive: { + label: '款式/用途', + options: S_USAGE_OPTIONS, + }, + material: { + label: '材质', + options: S_MATERIAL_OPTIONS, + }, + diameter: { + label: '规格/尺寸', + options: S_SIZE_OPTIONS, + }, + color: { + label: '颜色', + options: S_COLOR_OPTIONS, + }, +} + +const T_SELECT_FIELD_OVERRIDES: Partial< + Record>> +> = { + screwCategory: { + options: T_SCREW_CATEGORIES, + }, + drive: { + label: '款式/用途', + options: T_USAGE_OPTIONS, + }, + tail: { + label: '形状', + options: T_SHAPE_OPTIONS, + }, + material: { + label: '材质', + options: T_MATERIAL_OPTIONS, + }, + diameter: { + label: '规格/尺寸', + options: T_SIZE_OPTIONS, + }, + length: { + label: '厚度', + options: T_THICKNESS_OPTIONS, + }, + color: { + label: '颜色', + options: T_COLOR_OPTIONS, + }, +} + +const U_SELECT_FIELD_OVERRIDES: Partial< + Record>> +> = { + screwCategory: { + options: U_SCREW_CATEGORIES, + }, + drive: { + label: '款式/用途', + options: U_USAGE_OPTIONS, + }, + material: { + label: '材质', + options: U_MATERIAL_OPTIONS, + }, + diameter: { + label: '规格/尺寸', + options: U_SIZE_OPTIONS, + }, + color: { + label: '颜色', + options: U_COLOR_OPTIONS, + }, +} + const HIDDEN_SELECT_FIELD_KEYS_BY_LETTER: Partial< Record > = { @@ -990,13 +1303,20 @@ const HIDDEN_SELECT_FIELD_KEYS_BY_LETTER: Partial< E: ['finish', 'color'], F: ['drive', 'finish', 'preDrill'], G: ['drive', 'tail', 'finish', 'length', 'preDrill'], - H: ['drive', 'tail', 'finish', 'tooth', 'preDrill'], + H: ['drive', 'tail', 'tooth', 'preDrill'], I: ['drive', 'finish', 'preDrill'], J: ['drive', 'tail', 'finish', 'tooth', 'preDrill'], K: ['drive', 'tail', 'finish', 'tooth', 'preDrill'], L: ['drive', 'finish', 'tooth', 'preDrill'], M: ['drive', 'finish', 'length', 'preDrill'], N: ['tail', 'finish', 'tooth'], + O: ['tail', 'finish', 'tooth', 'color', 'preDrill'], + P: ['drive', 'finish', 'preDrill'], + Q: ['tail', 'finish', 'tooth', 'length', 'preDrill'], + R: ['finish', 'tooth', 'length', 'preDrill'], + S: ['tail', 'finish', 'tooth', 'length', 'preDrill'], + T: ['finish', 'tooth', 'preDrill'], + U: ['tail', 'finish', 'tooth', 'length', 'preDrill'], } const CUSTOM_SELECT_FIELD_KEYS_BY_LETTER: Partial< @@ -1004,6 +1324,12 @@ const CUSTOM_SELECT_FIELD_KEYS_BY_LETTER: Partial< > = { L: ['diameter', 'length'], N: ['drive', 'material', 'diameter', 'length', 'color', 'preDrill'], + P: ['length'], + Q: ['diameter'], + R: ['diameter'], + S: ['diameter'], + T: ['diameter', 'length'], + U: ['diameter'], } const EMPTY_FILTERS: ScrewFilterState = { @@ -1050,6 +1376,22 @@ const USAGE_TAGS = [ '防腐木', '孔塞', '孔贴', + '木榫', + '木销', + '液压杆', + '翻折配件', + '翻斗铰链', + '穿线盒', + '透气孔', + '无线充电盒', + '挂钩', + '卡扣', + '挡块', + '垫片', + '脚垫', + '扎带', + '粘贴件', + '钉类', '螺丝孔', '线孔', '装饰孔', @@ -1127,6 +1469,7 @@ function getTableColumns(letter: AccessoryLibraryLetter, shouldShowHeadType: boo if (letter === 'F' && column === '材质') return '材质/表面处理' if (letter === 'G' && column === '牙型') return '功能' if (letter === 'G' && column === '材质') return '材质/表面处理' + if (letter === 'H' && column === '长度') return '高度/长度' if (letter === 'I' && column === '规格') return '规格/轮径' if (letter === 'I' && column === '尾型') return '安装方式' if (letter === 'I' && column === '牙型') return '功能' @@ -1146,6 +1489,25 @@ function getTableColumns(letter: AccessoryLibraryLetter, shouldShowHeadType: boo if (letter === 'N' && column === '长度') return '厚度' if (letter === 'N' && column === '颜色') return '颜色' if (letter === 'N' && column === '是否预开孔') return '背胶' + if (letter === 'O' && column === '槽型') return '纹路' + if (letter === 'O' && column === '规格') return '规格/直径' + if (letter === 'P' && column === '尾型') return '安装/套装' + if (letter === 'P' && column === '牙型') return '功能' + if (letter === 'P' && column === '规格') return '规格/力度/层数' + if (letter === 'P' && column === '长度') return '长度/尺寸' + if (letter === 'Q' && column === '槽型') return '形状' + if (letter === 'Q' && column === '规格') return '规格/尺寸' + if (letter === 'R' && column === '槽型') return '款式/形状' + if (letter === 'R' && column === '尾型') return '安装方式' + if (letter === 'R' && column === '规格') return '规格/尺寸' + if (letter === 'S' && column === '槽型') return '款式/用途' + if (letter === 'S' && column === '规格') return '规格/尺寸' + if (letter === 'T' && column === '槽型') return '款式/用途' + if (letter === 'T' && column === '尾型') return '形状' + if (letter === 'T' && column === '规格') return '规格/尺寸' + if (letter === 'T' && column === '长度') return '厚度' + if (letter === 'U' && column === '槽型') return '款式/用途' + if (letter === 'U' && column === '规格') return '规格/尺寸' return column }) } @@ -1288,6 +1650,21 @@ const DEFAULT_SCREW_FIELDS_BY_LETTER: Partial< preDrill: '', environments: ['室内', '防锈'], }, + H: { + screwCategory: '六角螺母', + headType: '', + drive: '', + tail: '', + material: '碳钢', + finish: '镀锌', + tooth: '', + diameter: 'M6', + length: '', + usages: ['板式家具', '五金件', '床架'], + color: '银色', + preDrill: '', + environments: ['室内', '防锈'], + }, I: { screwCategory: '万向轮', headType: '', @@ -1378,6 +1755,111 @@ const DEFAULT_SCREW_FIELDS_BY_LETTER: Partial< preDrill: '无胶', environments: ['室内'], }, + O: { + screwCategory: '圆木榫', + headType: '', + drive: '斜纹', + tail: '', + material: '桦木', + finish: '', + tooth: '', + diameter: '8mm', + length: '40mm', + usages: ['实木', '板式家具', '木榫', '木销'], + color: '', + preDrill: '', + environments: ['室内'], + }, + P: { + screwCategory: '液压杆', + headType: '', + drive: '', + tail: '上翻门', + material: '铁', + finish: '', + tooth: '', + diameter: '100N', + length: '245mm', + usages: ['板式家具', '柜体', '门板', '液压杆'], + color: '银色', + preDrill: '', + environments: ['室内'], + }, + Q: { + screwCategory: '穿线盒', + headType: '', + drive: '圆形', + tail: '', + material: '塑料', + finish: '', + tooth: '', + diameter: '50mm', + length: '', + usages: ['板式家具', '柜体', '穿线盒', '线孔'], + color: '黑色', + preDrill: '', + environments: ['室内'], + }, + R: { + screwCategory: '挂钩', + headType: '', + drive: '普通', + tail: '螺丝固定', + material: '塑料', + finish: '', + tooth: '', + diameter: '小号', + length: '', + usages: ['板式家具', '柜体', '挂钩'], + color: '黑色', + preDrill: '', + environments: ['室内'], + }, + S: { + screwCategory: '卡扣', + headType: '', + drive: '背板', + tail: '', + material: '塑料', + finish: '', + tooth: '', + diameter: '', + length: '', + usages: ['板式家具', '柜体', '卡扣'], + color: '白色', + preDrill: '', + environments: ['室内'], + }, + T: { + screwCategory: '垫片', + headType: '', + drive: '普通', + tail: '圆形', + material: '塑料', + finish: '', + tooth: '', + diameter: 'φ32', + length: '', + usages: ['板式家具', '五金件', '垫片'], + color: '', + preDrill: '', + environments: ['室内'], + }, + U: { + screwCategory: '扎带', + headType: '', + drive: '固定', + tail: '', + material: '尼龙', + finish: '', + tooth: '', + diameter: '150mm', + length: '', + usages: ['板式家具', '辅助固定件', '扎带'], + color: '黑色', + preDrill: '', + environments: ['室内'], + }, } const PRIMARY_BUTTON_CLASS = @@ -1437,6 +1919,22 @@ function isICasterCategory(category: string) { return I_CASTER_CATEGORIES.includes(category) } +function isPHydraulicCategory(category: string) { + return category === '液压杆' +} + +function isPFoldingCategory(category: string) { + return category === '翻折配件' +} + +function isPFlipHingeCategory(category: string) { + return category === '翻斗铰链' +} + +function isMSlidingDoorWheelCategory(category: string) { + return category === '移门轮' +} + function getSelectFields(letter: AccessoryLibraryLetter) { const overrides = letter === 'B' @@ -1452,7 +1950,7 @@ function getSelectFields(letter: AccessoryLibraryLetter) { : letter === 'G' ? G_SELECT_FIELD_OVERRIDES : letter === 'H' - ? {} + ? H_SELECT_FIELD_OVERRIDES : letter === 'I' ? I_SELECT_FIELD_OVERRIDES : letter === 'J' @@ -1465,7 +1963,21 @@ function getSelectFields(letter: AccessoryLibraryLetter) { ? M_SELECT_FIELD_OVERRIDES : letter === 'N' ? N_SELECT_FIELD_OVERRIDES - : {} + : letter === 'O' + ? O_SELECT_FIELD_OVERRIDES + : letter === 'P' + ? P_SELECT_FIELD_OVERRIDES + : letter === 'Q' + ? Q_SELECT_FIELD_OVERRIDES + : letter === 'R' + ? R_SELECT_FIELD_OVERRIDES + : letter === 'S' + ? S_SELECT_FIELD_OVERRIDES + : letter === 'T' + ? T_SELECT_FIELD_OVERRIDES + : letter === 'U' + ? U_SELECT_FIELD_OVERRIDES + : {} const hiddenKeys = HIDDEN_SELECT_FIELD_KEYS_BY_LETTER[letter] ?? [] return SELECT_FIELDS.filter((field) => !hiddenKeys.includes(field.key)).map( @@ -1513,6 +2025,31 @@ function shouldShowSelectFieldForItem( return false } + if ( + item.letter === 'M' && + isMSlidingDoorWheelCategory(item.screwCategory) && + fieldKey === 'tooth' + ) { + return false + } + + if (item.letter === 'P') { + if (isPHydraulicCategory(item.screwCategory) && fieldKey === 'tooth') { + return false + } + + if ( + isPFoldingCategory(item.screwCategory) && + (fieldKey === 'tail' || fieldKey === 'length') + ) { + return false + } + + if (isPFlipHingeCategory(item.screwCategory) && fieldKey === 'tooth') { + return false + } + } + return true } @@ -1520,6 +2057,110 @@ function getSelectFieldsForItem(item: Pick shouldShowSelectFieldForItem(item, field.key), ).map((field) => { + if (item.letter === 'M' && isMSlidingDoorWheelCategory(item.screwCategory)) { + if (field.key === 'tail') { + return { + ...field, + label: '位置/款式', + options: M_SLIDING_WHEEL_TAIL_OPTIONS, + } + } + + if (field.key === 'diameter') { + return { + ...field, + label: '规格/尺寸', + options: M_SLIDING_WHEEL_DIAMETER_OPTIONS, + } + } + + if (field.key === 'material') { + return { + ...field, + options: M_SLIDING_WHEEL_MATERIAL_OPTIONS, + } + } + + if (field.key === 'color') { + return { + ...field, + options: M_SLIDING_WHEEL_COLOR_OPTIONS, + } + } + } + + if (item.letter === 'P') { + if (isPHydraulicCategory(item.screwCategory)) { + if (field.key === 'diameter') { + return { + ...field, + label: '规格/力度', + options: P_HYDRAULIC_FORCE_OPTIONS, + } + } + + if (field.key === 'length') { + return { + ...field, + label: '长度', + options: P_HYDRAULIC_LENGTH_OPTIONS, + } + } + + if (field.key === 'tail') { + return { + ...field, + label: '安装方式', + options: P_HYDRAULIC_TAIL_OPTIONS, + } + } + } + + if (isPFoldingCategory(item.screwCategory)) { + if (field.key === 'diameter') { + return { + ...field, + label: '规格/型号', + options: P_FOLDING_MODEL_OPTIONS, + } + } + + if (field.key === 'tooth') { + return { + ...field, + label: '功能', + options: P_FOLDING_FUNCTION_OPTIONS, + } + } + } + + if (isPFlipHingeCategory(item.screwCategory)) { + if (field.key === 'diameter') { + return { + ...field, + label: '层数', + options: P_FLIP_HINGE_LAYER_OPTIONS, + } + } + + if (field.key === 'length') { + return { + ...field, + label: '尺寸', + options: P_FLIP_HINGE_SIZE_OPTIONS, + } + } + + if (field.key === 'tail') { + return { + ...field, + label: '套装方式', + options: P_FLIP_HINGE_TAIL_OPTIONS, + } + } + } + } + if (item.letter !== 'I' || !isIFurnitureLegCategory(item.screwCategory)) { return field } @@ -1840,6 +2481,19 @@ function buildScrewName( .join(' ') } + if (item.letter === 'H') { + return [ + item.diameter, + item.length, + item.finish, + item.material, + item.screwCategory, + ] + .map((value) => value.trim()) + .filter(Boolean) + .join(' ') + } + if ( item.letter === 'I' && isIFurnitureLegCategory(item.screwCategory) @@ -1857,7 +2511,7 @@ function buildScrewName( .join(' ') } - if (item.letter === 'H' || item.letter === 'J' || item.letter === 'K') { + if (item.letter === 'J' || item.letter === 'K') { const materialOrFinish = item.material.trim() || item.finish.trim() return [ item.diameter, @@ -1901,6 +2555,13 @@ function buildScrewName( } if (item.letter === 'M') { + if (isMSlidingDoorWheelCategory(item.screwCategory)) { + return [item.tail, item.diameter, item.color, item.material, item.screwCategory] + .map((value) => value.trim()) + .filter(Boolean) + .join(' ') + } + const materialOrFinish = item.material.trim() || item.finish.trim() return [item.diameter, item.color, materialOrFinish, item.screwCategory] .map((value) => value.trim()) @@ -1922,6 +2583,97 @@ function buildScrewName( .join(' ') } + if (item.letter === 'O') { + const spec = + diameter && item.length.trim() + ? `${diameter}*${item.length.trim()}` + : diameter || item.length.trim() + return [spec, item.material, item.drive, item.screwCategory] + .map((value) => value.trim()) + .filter(Boolean) + .join(' ') + } + + if (item.letter === 'P') { + if (isPHydraulicCategory(item.screwCategory)) { + return [item.diameter, item.length, item.tail, item.color, item.screwCategory] + .map((value) => value.trim()) + .filter(Boolean) + .join(' ') + } + + if (isPFoldingCategory(item.screwCategory)) { + return [item.diameter, item.tooth, item.color, item.screwCategory] + .map((value) => value.trim()) + .filter(Boolean) + .join(' ') + } + + if (isPFlipHingeCategory(item.screwCategory)) { + return [ + item.diameter, + item.length, + item.color, + item.material, + item.screwCategory, + ] + .map((value) => value.trim()) + .filter(Boolean) + .join(' ') + } + } + + if (item.letter === 'Q') { + return [item.diameter, item.color, item.material, item.drive, item.screwCategory] + .map((value) => value.trim()) + .filter(Boolean) + .join(' ') + } + + if (item.letter === 'R') { + return [ + item.diameter, + item.drive, + item.color, + item.material, + item.tail, + item.screwCategory, + ] + .map((value) => value.trim()) + .filter(Boolean) + .join(' ') + } + + if (item.letter === 'S') { + return [item.drive, item.diameter, item.color, item.material, item.screwCategory] + .map((value) => value.trim()) + .filter(Boolean) + .join(' ') + } + + if (item.letter === 'T') { + const usage = item.drive === '普通' ? '' : item.drive + return [ + usage, + item.tail, + item.diameter, + item.length, + item.color, + item.material, + item.screwCategory, + ] + .map((value) => value.trim()) + .filter(Boolean) + .join(' ') + } + + if (item.letter === 'U') { + return [item.drive, item.diameter, item.color, item.material, item.screwCategory] + .map((value) => value.trim()) + .filter(Boolean) + .join(' ') + } + return [specSize, item.drive, item.headType, item.tail, item.screwCategory] .map((value) => value.trim()) .filter(Boolean) @@ -2034,6 +2786,54 @@ function normalizeScrewDraftForCategory(draft: ScrewItem): ScrewItem { } } + if (draft.letter === 'M') { + if (isMSlidingDoorWheelCategory(draft.screwCategory)) { + return { + ...draft, + headType: '', + drive: '', + tail: M_SLIDING_WHEEL_TAIL_OPTIONS.includes(draft.tail) + ? draft.tail + : '下轮', + material: M_SLIDING_WHEEL_MATERIAL_OPTIONS.includes(draft.material) + ? draft.material + : '塑料', + finish: '', + tooth: '', + diameter: draft.diameter || '30mm', + length: '', + color: M_SLIDING_WHEEL_COLOR_OPTIONS.includes(draft.color) + ? draft.color + : '黑色', + preDrill: '', + usages: ['板式家具', '柜体', '移门轮'], + } + } + + return { + ...draft, + headType: '', + drive: '', + tail: M_STANDARD_TAIL_OPTIONS.includes(draft.tail) ? draft.tail : '明装', + material: M_STANDARD_MATERIAL_OPTIONS.includes(draft.material) + ? draft.material + : '铁', + finish: '', + tooth: M_STANDARD_TOOTH_OPTIONS.includes(draft.tooth) + ? draft.tooth + : draft.screwCategory === '反弹器' + ? '按压反弹' + : '强磁', + diameter: M_STANDARD_DIAMETER_OPTIONS.includes(draft.diameter) + ? draft.diameter + : '小号', + length: '', + color: M_STANDARD_COLOR_OPTIONS.includes(draft.color) ? draft.color : '银色', + preDrill: '', + usages: ['板式家具', '柜体', draft.screwCategory].filter(Boolean), + } + } + if (draft.letter === 'N') { const isHoleSticker = draft.screwCategory === '孔贴' return { @@ -2046,6 +2846,172 @@ function normalizeScrewDraftForCategory(draft: ScrewItem): ScrewItem { } } + if (draft.letter === 'P') { + if (isPHydraulicCategory(draft.screwCategory)) { + return { + ...draft, + headType: '', + drive: '', + tail: P_HYDRAULIC_TAIL_OPTIONS.includes(draft.tail) + ? draft.tail + : '上翻门', + material: P_MATERIAL_OPTIONS.includes(draft.material) + ? draft.material + : '铁', + finish: '', + tooth: '', + diameter: P_HYDRAULIC_FORCE_OPTIONS.includes(draft.diameter) + ? draft.diameter + : '100N', + length: draft.length || '245mm', + color: P_COLOR_OPTIONS.includes(draft.color) ? draft.color : '银色', + preDrill: '', + usages: ['板式家具', '柜体', '门板', '液压杆'], + } + } + + if (isPFoldingCategory(draft.screwCategory)) { + return { + ...draft, + headType: '', + drive: '', + tail: '', + material: P_MATERIAL_OPTIONS.includes(draft.material) + ? draft.material + : '铁', + finish: '', + tooth: P_FOLDING_FUNCTION_OPTIONS.includes(draft.tooth) + ? draft.tooth + : '缓冲', + diameter: P_FOLDING_MODEL_OPTIONS.includes(draft.diameter) + ? draft.diameter + : '中号', + length: '', + color: P_COLOR_OPTIONS.includes(draft.color) ? draft.color : '银色', + preDrill: '', + usages: ['板式家具', '柜体', '门板', '翻折配件'], + } + } + + if (isPFlipHingeCategory(draft.screwCategory)) { + return { + ...draft, + headType: '', + drive: '', + tail: P_FLIP_HINGE_TAIL_OPTIONS.includes(draft.tail) + ? draft.tail + : '左右套装', + material: ['塑料', '铁', '不锈钢'].includes(draft.material) + ? draft.material + : '塑料', + finish: '', + tooth: '', + diameter: P_FLIP_HINGE_LAYER_OPTIONS.includes(draft.diameter) + ? draft.diameter + : '双层', + length: draft.length || '240*310mm', + color: P_COLOR_OPTIONS.includes(draft.color) ? draft.color : '白色', + preDrill: '', + usages: ['板式家具', '鞋柜', '柜体', '翻斗铰链'], + } + } + } + + if (draft.letter === 'Q') { + return { + ...draft, + headType: '', + drive: Q_SHAPE_OPTIONS.includes(draft.drive) ? draft.drive : '圆形', + tail: '', + material: Q_MATERIAL_OPTIONS.includes(draft.material) + ? draft.material + : '塑料', + finish: '', + tooth: '', + diameter: draft.diameter || '50mm', + length: '', + color: Q_COLOR_OPTIONS.includes(draft.color) ? draft.color : '黑色', + preDrill: '', + usages: ['板式家具', '柜体', draft.screwCategory, '线孔'].filter(Boolean), + } + } + + if (draft.letter === 'R') { + return { + ...draft, + headType: '', + drive: R_STYLE_OPTIONS.includes(draft.drive) ? draft.drive : '普通', + tail: R_TAIL_OPTIONS.includes(draft.tail) ? draft.tail : '螺丝固定', + material: R_MATERIAL_OPTIONS.includes(draft.material) + ? draft.material + : '塑料', + finish: '', + tooth: '', + diameter: draft.diameter || '小号', + length: '', + color: R_COLOR_OPTIONS.includes(draft.color) ? draft.color : '黑色', + preDrill: '', + usages: ['板式家具', '柜体', '挂钩'], + } + } + + if (draft.letter === 'S') { + return { + ...draft, + headType: '', + drive: S_USAGE_OPTIONS.includes(draft.drive) ? draft.drive : '背板', + tail: '', + material: S_MATERIAL_OPTIONS.includes(draft.material) + ? draft.material + : '塑料', + finish: '', + tooth: '', + diameter: draft.diameter, + length: '', + color: S_COLOR_OPTIONS.includes(draft.color) ? draft.color : '白色', + preDrill: '', + usages: ['板式家具', '柜体', draft.screwCategory].filter(Boolean), + } + } + + if (draft.letter === 'T') { + return { + ...draft, + headType: '', + drive: T_USAGE_OPTIONS.includes(draft.drive) ? draft.drive : '普通', + tail: T_SHAPE_OPTIONS.includes(draft.tail) ? draft.tail : '圆形', + material: T_MATERIAL_OPTIONS.includes(draft.material) + ? draft.material + : '塑料', + finish: '', + tooth: '', + diameter: draft.diameter || 'φ32', + length: draft.length, + color: T_COLOR_OPTIONS.includes(draft.color) ? draft.color : '', + preDrill: '', + usages: ['板式家具', '五金件', draft.screwCategory].filter(Boolean), + } + } + + if (draft.letter === 'U') { + return { + ...draft, + headType: '', + drive: U_USAGE_OPTIONS.includes(draft.drive) ? draft.drive : '固定', + tail: '', + material: U_MATERIAL_OPTIONS.includes(draft.material) + ? draft.material + : '尼龙', + finish: '', + tooth: '', + diameter: draft.diameter || '150mm', + length: '', + color: U_COLOR_OPTIONS.includes(draft.color) ? draft.color : '黑色', + preDrill: '', + usages: ['板式家具', '辅助固定件', draft.screwCategory].filter(Boolean), + } + } + if (draft.letter !== 'E' || draft.screwCategory === '内外牙螺母') { return draft } @@ -2440,7 +3406,20 @@ export default function AccessoryLibraryPanel({ setDraft((current) => { if (!current) return current - const nextDraft = normalizeScrewDraftForCategory({ ...current, [key]: value }) + const candidateDraft = + key === 'screwCategory' && (current.letter === 'P' || current.letter === 'M') + ? { + ...current, + [key]: value, + tail: '', + material: '', + tooth: '', + diameter: '', + length: '', + color: '', + } + : { ...current, [key]: value } + const nextDraft = normalizeScrewDraftForCategory(candidateDraft) if ( [ 'diameter', diff --git a/furniture-3d-system/src/app/intake/AlphabetLibraryPanel.test.tsx b/furniture-3d-system/src/app/intake/AlphabetLibraryPanel.test.tsx index 3431ed71..357de782 100644 --- a/furniture-3d-system/src/app/intake/AlphabetLibraryPanel.test.tsx +++ b/furniture-3d-system/src/app/intake/AlphabetLibraryPanel.test.tsx @@ -66,10 +66,10 @@ describe('alphabet library panels', () => { render() - await actor.click(screen.getByRole('button', { name: 'O 0 条' })) + await actor.click(screen.getByRole('button', { name: 'V 0 条' })) - expect(screen.getByText('O 组配件')).toBeInTheDocument() - expect(screen.getByText('O 组暂未配置配件分类')).toBeInTheDocument() + expect(screen.getByText('V 组配件')).toBeInTheDocument() + expect(screen.getByText('V 组暂未配置配件分类')).toBeInTheDocument() expect(screen.queryByRole('button', { name: '新增 A 组' })).not.toBeInTheDocument() await actor.click(screen.getByRole('button', { name: 'A 自攻螺丝 0 条' })) @@ -351,16 +351,76 @@ describe('alphabet library panels', () => { }) }) - it('leaves H unconfigured before nut rules are confirmed', async () => { + it('uses nut and cap nut rules for H accessories', async () => { const actor = userEvent.setup() render() - await actor.click(screen.getByRole('button', { name: 'H 0 条' })) + await actor.click(screen.getByRole('button', { name: 'H 螺母/螺帽 0 条' })) - expect(screen.getByText('H 组配件')).toBeInTheDocument() - expect(screen.getByText('H 组暂未配置配件分类')).toBeInTheDocument() - expect(screen.queryByRole('button', { name: '新增 H 组' })).not.toBeInTheDocument() + expect(screen.getByText('H 组配件 · 螺母/螺帽')).toBeInTheDocument() + expect(screen.queryByRole('button', { name: '全部头型' })).not.toBeInTheDocument() + expect(screen.getByRole('button', { name: '全部分类' })).toBeInTheDocument() + expect(screen.getByRole('button', { name: '六角螺母' })).toBeInTheDocument() + expect(screen.getByRole('button', { name: '法兰螺母' })).toBeInTheDocument() + expect(screen.getByRole('button', { name: '防松螺母' })).toBeInTheDocument() + expect(screen.getByRole('button', { name: '盖形螺母' })).toBeInTheDocument() + expect(screen.getByRole('button', { name: '蝶形螺母' })).toBeInTheDocument() + expect(screen.getByRole('button', { name: '套筒螺母' })).toBeInTheDocument() + + await actor.click(screen.getByRole('button', { name: '新增 H 组' })) + + const dialog = await screen.findByRole('dialog', { name: '新增H组配件' }) + expect(within(dialog).getByLabelText('配件名称')).toHaveValue( + 'M6 镀锌 碳钢 六角螺母', + ) + expect(within(dialog).queryByLabelText('头型')).not.toBeInTheDocument() + expect(within(dialog).queryByLabelText('槽型')).not.toBeInTheDocument() + expect(within(dialog).queryByLabelText('尾型')).not.toBeInTheDocument() + expect(within(dialog).queryByLabelText('牙型')).not.toBeInTheDocument() + expect(within(dialog).queryByLabelText('是否预开孔')).not.toBeInTheDocument() + expect(within(dialog).getByLabelText('规格')).toHaveValue('M6') + expect(within(dialog).getByLabelText('高度/长度')).toHaveValue('') + expect(within(dialog).getByLabelText('材质')).toHaveValue('碳钢') + expect(within(dialog).getByLabelText('表面处理')).toHaveValue('镀锌') + expect(within(dialog).getByLabelText('颜色')).toHaveValue('银色') + + fireEvent.change(within(dialog).getByLabelText('分类'), { + target: { value: '套筒螺母' }, + }) + fireEvent.change(within(dialog).getByLabelText('高度/长度'), { + target: { value: '20mm' }, + }) + + expect(within(dialog).getByLabelText('配件名称')).toHaveValue( + 'M6 20mm 镀锌 碳钢 套筒螺母', + ) + + await actor.click(within(dialog).getByRole('button', { name: '保存' })) + + await waitFor(() => { + expect(screen.getByText('M6 20mm 镀锌 碳钢 套筒螺母')).toBeInTheDocument() + }) + + const savedItems = JSON.parse( + window.localStorage.getItem(ACCESSORY_LIBRARY_STORAGE_KEY) ?? '[]', + ) + expect(savedItems[0]).toMatchObject({ + letter: 'H', + code: 'H0', + name: 'M6 20mm 镀锌 碳钢 套筒螺母', + screwCategory: '套筒螺母', + headType: '', + drive: '', + tail: '', + material: '碳钢', + finish: '镀锌', + tooth: '', + diameter: 'M6', + length: '20mm', + color: '银色', + preDrill: '', + }) }) it('uses caster wheel rules for I accessories', async () => { @@ -734,13 +794,14 @@ describe('alphabet library panels', () => { render() - await actor.click(screen.getByRole('button', { name: 'M 门吸/反弹器 0 条' })) + await actor.click(screen.getByRole('button', { name: 'M 门吸/反弹器/移门轮 0 条' })) - expect(screen.getByText('M 组配件 · 门吸/反弹器')).toBeInTheDocument() + expect(screen.getByText('M 组配件 · 门吸/反弹器/移门轮')).toBeInTheDocument() expect(screen.queryByRole('button', { name: '全部头型' })).not.toBeInTheDocument() expect(screen.getByRole('button', { name: '全部分类' })).toBeInTheDocument() expect(screen.getByRole('button', { name: '门吸' })).toBeInTheDocument() expect(screen.getByRole('button', { name: '反弹器' })).toBeInTheDocument() + expect(screen.getByRole('button', { name: '移门轮' })).toBeInTheDocument() await actor.click(screen.getByRole('button', { name: '新增 M 组' })) @@ -808,6 +869,68 @@ describe('alphabet library panels', () => { }) }) + it('uses sliding door wheel rules inside M accessories', async () => { + const actor = userEvent.setup() + + render() + + await actor.click(screen.getByRole('button', { name: 'M 门吸/反弹器/移门轮 0 条' })) + await actor.click(screen.getByRole('button', { name: '新增 M 组' })) + + const dialog = await screen.findByRole('dialog', { name: '新增M组配件' }) + fireEvent.change(within(dialog).getByLabelText('分类'), { + target: { value: '移门轮' }, + }) + + expect(within(dialog).getByLabelText('配件名称')).toHaveValue( + '下轮 30mm 黑色 塑料 移门轮', + ) + expect(within(dialog).getByLabelText('位置/款式')).toHaveValue('下轮') + expect(within(dialog).getByLabelText('规格/尺寸')).toHaveValue('30mm') + expect(within(dialog).getByLabelText('材质')).toHaveValue('塑料') + expect(within(dialog).getByLabelText('颜色')).toHaveValue('黑色') + expect(within(dialog).queryByLabelText('功能')).not.toBeInTheDocument() + + fireEvent.change(within(dialog).getByLabelText('位置/款式'), { + target: { value: '上轮' }, + }) + fireEvent.change(within(dialog).getByLabelText('规格/尺寸'), { + target: { value: '25mm' }, + }) + fireEvent.change(within(dialog).getByLabelText('颜色'), { + target: { value: '白色' }, + }) + + expect(within(dialog).getByLabelText('配件名称')).toHaveValue( + '上轮 25mm 白色 塑料 移门轮', + ) + + await actor.click(within(dialog).getByRole('button', { name: '保存' })) + + await waitFor(() => { + expect(screen.getByText('上轮 25mm 白色 塑料 移门轮')).toBeInTheDocument() + }) + + const savedItems = JSON.parse( + window.localStorage.getItem(ACCESSORY_LIBRARY_STORAGE_KEY) ?? '[]', + ) + expect(savedItems[0]).toMatchObject({ + letter: 'M', + code: 'M0', + name: '上轮 25mm 白色 塑料 移门轮', + screwCategory: '移门轮', + diameter: '25mm', + tail: '上轮', + tooth: '', + color: '白色', + material: '塑料', + drive: '', + finish: '', + length: '', + preDrill: '', + }) + }) + it('uses plug and sticker rules for N accessories', async () => { const actor = userEvent.setup() @@ -889,6 +1012,575 @@ describe('alphabet library panels', () => { }) }) + it('uses wooden dowel rules for O accessories', async () => { + const actor = userEvent.setup() + + render() + + await actor.click(screen.getByRole('button', { name: 'O 木榫/木销 0 条' })) + + expect(screen.getByText('O 组配件 · 木榫/木销')).toBeInTheDocument() + expect(screen.queryByRole('button', { name: '全部头型' })).not.toBeInTheDocument() + expect(screen.getByRole('button', { name: '全部分类' })).toBeInTheDocument() + expect(screen.getByRole('button', { name: '圆木榫' })).toBeInTheDocument() + + await actor.click(screen.getByRole('button', { name: '新增 O 组' })) + + const dialog = await screen.findByRole('dialog', { name: '新增O组配件' }) + expect(within(dialog).getByLabelText('配件名称')).toHaveValue( + '8mm*40mm 桦木 斜纹 圆木榫', + ) + expect(within(dialog).getByLabelText('分类')).toHaveValue('圆木榫') + expect(within(dialog).getByLabelText('规格/直径')).toHaveValue('8mm') + expect(within(dialog).getByLabelText('长度')).toHaveValue('40mm') + expect(within(dialog).getByLabelText('材质')).toHaveValue('桦木') + expect(within(dialog).getByLabelText('纹路')).toHaveValue('斜纹') + expect(within(dialog).queryByLabelText('头型')).not.toBeInTheDocument() + expect(within(dialog).queryByLabelText('尾型')).not.toBeInTheDocument() + expect(within(dialog).queryByLabelText('表面处理')).not.toBeInTheDocument() + expect(within(dialog).queryByLabelText('牙型')).not.toBeInTheDocument() + expect(within(dialog).queryByLabelText('颜色')).not.toBeInTheDocument() + expect(within(dialog).queryByLabelText('是否预开孔')).not.toBeInTheDocument() + + fireEvent.change(within(dialog).getByLabelText('规格/直径'), { + target: { value: '10mm' }, + }) + fireEvent.change(within(dialog).getByLabelText('长度'), { + target: { value: '50mm' }, + }) + fireEvent.change(within(dialog).getByLabelText('材质'), { + target: { value: '榉木' }, + }) + fireEvent.change(within(dialog).getByLabelText('纹路'), { + target: { value: '直纹' }, + }) + + expect(within(dialog).getByLabelText('配件名称')).toHaveValue( + '10mm*50mm 榉木 直纹 圆木榫', + ) + + await actor.click(within(dialog).getByRole('button', { name: '保存' })) + + await waitFor(() => { + expect(screen.getByText('10mm*50mm 榉木 直纹 圆木榫')).toBeInTheDocument() + }) + + const savedItems = JSON.parse( + window.localStorage.getItem(ACCESSORY_LIBRARY_STORAGE_KEY) ?? '[]', + ) + expect(savedItems[0]).toMatchObject({ + letter: 'O', + code: 'O0', + name: '10mm*50mm 榉木 直纹 圆木榫', + screwCategory: '圆木榫', + headType: '', + drive: '直纹', + tail: '', + material: '榉木', + finish: '', + tooth: '', + diameter: '10mm', + length: '50mm', + color: '', + preDrill: '', + }) + }) + + it('uses flap door and support rules for P accessories', async () => { + const actor = userEvent.setup() + + render() + + await actor.click(screen.getByRole('button', { name: 'P 翻门/支撑配件 0 条' })) + + expect(screen.getByText('P 组配件 · 翻门/支撑配件')).toBeInTheDocument() + expect(screen.queryByRole('button', { name: '全部头型' })).not.toBeInTheDocument() + expect(screen.getByRole('button', { name: '全部分类' })).toBeInTheDocument() + expect(screen.getByRole('button', { name: '液压杆' })).toBeInTheDocument() + expect(screen.getByRole('button', { name: '翻折配件' })).toBeInTheDocument() + expect(screen.getByRole('button', { name: '翻斗铰链' })).toBeInTheDocument() + + await actor.click(screen.getByRole('button', { name: '新增 P 组' })) + + const dialog = await screen.findByRole('dialog', { name: '新增P组配件' }) + expect(within(dialog).getByLabelText('配件名称')).toHaveValue( + '100N 245mm 上翻门 银色 液压杆', + ) + expect(within(dialog).getByLabelText('分类')).toHaveValue('液压杆') + expect(within(dialog).getByLabelText('规格/力度')).toHaveValue('100N') + expect(within(dialog).getByLabelText('长度')).toHaveValue('245mm') + expect(within(dialog).getByLabelText('安装方式')).toHaveValue('上翻门') + expect(within(dialog).getByLabelText('材质')).toHaveValue('铁') + expect(within(dialog).getByLabelText('颜色')).toHaveValue('银色') + expect(within(dialog).queryByLabelText('头型')).not.toBeInTheDocument() + expect(within(dialog).queryByLabelText('槽型')).not.toBeInTheDocument() + expect(within(dialog).queryByLabelText('表面处理')).not.toBeInTheDocument() + expect(within(dialog).queryByLabelText('牙型')).not.toBeInTheDocument() + expect(within(dialog).queryByLabelText('是否预开孔')).not.toBeInTheDocument() + + fireEvent.change(within(dialog).getByLabelText('分类'), { + target: { value: '翻折配件' }, + }) + + expect(within(dialog).getByLabelText('配件名称')).toHaveValue( + '中号 缓冲 银色 翻折配件', + ) + expect(within(dialog).getByLabelText('规格/型号')).toHaveValue('中号') + expect(within(dialog).getByLabelText('功能')).toHaveValue('缓冲') + expect(within(dialog).queryByLabelText('安装方式')).not.toBeInTheDocument() + expect(within(dialog).queryByLabelText('长度')).not.toBeInTheDocument() + + fireEvent.change(within(dialog).getByLabelText('分类'), { + target: { value: '翻斗铰链' }, + }) + + expect(within(dialog).getByLabelText('配件名称')).toHaveValue( + '双层 240*310mm 白色 塑料 翻斗铰链', + ) + expect(within(dialog).getByLabelText('层数')).toHaveValue('双层') + expect(within(dialog).getByLabelText('尺寸')).toHaveValue('240*310mm') + expect(within(dialog).getByLabelText('套装方式')).toHaveValue('左右套装') + expect(within(dialog).getByLabelText('材质')).toHaveValue('塑料') + expect(within(dialog).getByLabelText('颜色')).toHaveValue('白色') + expect(within(dialog).queryByLabelText('功能')).not.toBeInTheDocument() + + fireEvent.change(within(dialog).getByLabelText('尺寸'), { + target: { value: '260*320mm' }, + }) + fireEvent.change(within(dialog).getByLabelText('材质'), { + target: { value: '铁' }, + }) + fireEvent.change(within(dialog).getByLabelText('颜色'), { + target: { value: '黑色' }, + }) + + expect(within(dialog).getByLabelText('配件名称')).toHaveValue( + '双层 260*320mm 黑色 铁 翻斗铰链', + ) + + await actor.click(within(dialog).getByRole('button', { name: '保存' })) + + await waitFor(() => { + expect(screen.getByText('双层 260*320mm 黑色 铁 翻斗铰链')).toBeInTheDocument() + }) + + const savedItems = JSON.parse( + window.localStorage.getItem(ACCESSORY_LIBRARY_STORAGE_KEY) ?? '[]', + ) + expect(savedItems[0]).toMatchObject({ + letter: 'P', + code: 'P0', + name: '双层 260*320mm 黑色 铁 翻斗铰链', + screwCategory: '翻斗铰链', + headType: '', + drive: '', + tail: '左右套装', + material: '铁', + finish: '', + tooth: '', + diameter: '双层', + length: '260*320mm', + color: '黑色', + preDrill: '', + }) + }) + + it('uses cable box and vent hole rules for Q accessories', async () => { + const actor = userEvent.setup() + + render() + + await actor.click(screen.getByRole('button', { name: 'Q 线盒/透气孔 0 条' })) + + expect(screen.getByText('Q 组配件 · 线盒/透气孔')).toBeInTheDocument() + expect(screen.queryByRole('button', { name: '全部头型' })).not.toBeInTheDocument() + expect(screen.getByRole('button', { name: '全部分类' })).toBeInTheDocument() + expect(screen.getByRole('button', { name: '穿线盒' })).toBeInTheDocument() + expect(screen.getByRole('button', { name: '透气孔' })).toBeInTheDocument() + expect(screen.getByRole('button', { name: '无线充电盒' })).toBeInTheDocument() + + await actor.click(screen.getByRole('button', { name: '新增 Q 组' })) + + const dialog = await screen.findByRole('dialog', { name: '新增Q组配件' }) + expect(within(dialog).getByLabelText('配件名称')).toHaveValue( + '50mm 黑色 塑料 圆形 穿线盒', + ) + expect(within(dialog).getByLabelText('分类')).toHaveValue('穿线盒') + expect(within(dialog).getByLabelText('形状')).toHaveValue('圆形') + expect(within(dialog).getByLabelText('规格/尺寸')).toHaveValue('50mm') + expect(within(dialog).getByLabelText('材质')).toHaveValue('塑料') + expect(within(dialog).getByLabelText('颜色')).toHaveValue('黑色') + expect(within(dialog).queryByLabelText('头型')).not.toBeInTheDocument() + expect(within(dialog).queryByLabelText('尾型')).not.toBeInTheDocument() + expect(within(dialog).queryByLabelText('表面处理')).not.toBeInTheDocument() + expect(within(dialog).queryByLabelText('牙型')).not.toBeInTheDocument() + expect(within(dialog).queryByLabelText('长度')).not.toBeInTheDocument() + expect(within(dialog).queryByLabelText('是否预开孔')).not.toBeInTheDocument() + + fireEvent.change(within(dialog).getByLabelText('分类'), { + target: { value: '透气孔' }, + }) + fireEvent.change(within(dialog).getByLabelText('规格/尺寸'), { + target: { value: '60mm' }, + }) + fireEvent.change(within(dialog).getByLabelText('材质'), { + target: { value: '铁' }, + }) + fireEvent.change(within(dialog).getByLabelText('颜色'), { + target: { value: '银色' }, + }) + + expect(within(dialog).getByLabelText('配件名称')).toHaveValue( + '60mm 银色 铁 圆形 透气孔', + ) + + await actor.click(within(dialog).getByRole('button', { name: '保存' })) + + await waitFor(() => { + expect(screen.getByText('60mm 银色 铁 圆形 透气孔')).toBeInTheDocument() + }) + + const savedItems = JSON.parse( + window.localStorage.getItem(ACCESSORY_LIBRARY_STORAGE_KEY) ?? '[]', + ) + expect(savedItems[0]).toMatchObject({ + letter: 'Q', + code: 'Q0', + name: '60mm 银色 铁 圆形 透气孔', + screwCategory: '透气孔', + headType: '', + drive: '圆形', + tail: '', + material: '铁', + finish: '', + tooth: '', + diameter: '60mm', + length: '', + color: '银色', + preDrill: '', + }) + }) + + it('uses hook rules for R accessories', async () => { + const actor = userEvent.setup() + + render() + + await actor.click(screen.getByRole('button', { name: 'R 挂钩 0 条' })) + + expect(screen.getByText('R 组配件 · 挂钩')).toBeInTheDocument() + expect(screen.queryByRole('button', { name: '全部头型' })).not.toBeInTheDocument() + expect(screen.getByRole('button', { name: '全部分类' })).toBeInTheDocument() + expect(screen.getByRole('button', { name: '挂钩' })).toBeInTheDocument() + + await actor.click(screen.getByRole('button', { name: '新增 R 组' })) + + const dialog = await screen.findByRole('dialog', { name: '新增R组配件' }) + expect(within(dialog).getByLabelText('配件名称')).toHaveValue( + '小号 普通 黑色 塑料 螺丝固定 挂钩', + ) + expect(within(dialog).getByLabelText('分类')).toHaveValue('挂钩') + expect(within(dialog).getByLabelText('款式/形状')).toHaveValue('普通') + expect(within(dialog).getByLabelText('规格/尺寸')).toHaveValue('小号') + expect(within(dialog).getByLabelText('安装方式')).toHaveValue('螺丝固定') + expect(within(dialog).getByLabelText('材质')).toHaveValue('塑料') + expect(within(dialog).getByLabelText('颜色')).toHaveValue('黑色') + expect(within(dialog).queryByLabelText('头型')).not.toBeInTheDocument() + expect(within(dialog).queryByLabelText('表面处理')).not.toBeInTheDocument() + expect(within(dialog).queryByLabelText('牙型')).not.toBeInTheDocument() + expect(within(dialog).queryByLabelText('长度')).not.toBeInTheDocument() + expect(within(dialog).queryByLabelText('是否预开孔')).not.toBeInTheDocument() + + fireEvent.change(within(dialog).getByLabelText('款式/形状'), { + target: { value: 'S型' }, + }) + fireEvent.change(within(dialog).getByLabelText('规格/尺寸'), { + target: { value: '中号' }, + }) + fireEvent.change(within(dialog).getByLabelText('安装方式'), { + target: { value: '挂入' }, + }) + fireEvent.change(within(dialog).getByLabelText('材质'), { + target: { value: '铁' }, + }) + + expect(within(dialog).getByLabelText('配件名称')).toHaveValue( + '中号 S型 黑色 铁 挂入 挂钩', + ) + + await actor.click(within(dialog).getByRole('button', { name: '保存' })) + + await waitFor(() => { + expect(screen.getByText('中号 S型 黑色 铁 挂入 挂钩')).toBeInTheDocument() + }) + + const savedItems = JSON.parse( + window.localStorage.getItem(ACCESSORY_LIBRARY_STORAGE_KEY) ?? '[]', + ) + expect(savedItems[0]).toMatchObject({ + letter: 'R', + code: 'R0', + name: '中号 S型 黑色 铁 挂入 挂钩', + screwCategory: '挂钩', + headType: '', + drive: 'S型', + tail: '挂入', + material: '铁', + finish: '', + tooth: '', + diameter: '中号', + length: '', + color: '黑色', + preDrill: '', + }) + }) + + it('uses clip and block rules for S accessories', async () => { + const actor = userEvent.setup() + + render() + + await actor.click(screen.getByRole('button', { name: 'S 卡扣/挡块 0 条' })) + + expect(screen.getByText('S 组配件 · 卡扣/挡块')).toBeInTheDocument() + expect(screen.queryByRole('button', { name: '全部头型' })).not.toBeInTheDocument() + expect(screen.getByRole('button', { name: '全部分类' })).toBeInTheDocument() + expect(screen.getByRole('button', { name: '卡扣' })).toBeInTheDocument() + expect(screen.getByRole('button', { name: '挡块' })).toBeInTheDocument() + + await actor.click(screen.getByRole('button', { name: '新增 S 组' })) + + const dialog = await screen.findByRole('dialog', { name: '新增S组配件' }) + expect(within(dialog).getByLabelText('配件名称')).toHaveValue( + '背板 白色 塑料 卡扣', + ) + expect(within(dialog).getByLabelText('分类')).toHaveValue('卡扣') + expect(within(dialog).getByLabelText('款式/用途')).toHaveValue('背板') + expect(within(dialog).getByLabelText('规格/尺寸')).toHaveValue('') + expect(within(dialog).getByLabelText('材质')).toHaveValue('塑料') + expect(within(dialog).getByLabelText('颜色')).toHaveValue('白色') + expect(within(dialog).queryByLabelText('头型')).not.toBeInTheDocument() + expect(within(dialog).queryByLabelText('尾型')).not.toBeInTheDocument() + expect(within(dialog).queryByLabelText('表面处理')).not.toBeInTheDocument() + expect(within(dialog).queryByLabelText('牙型')).not.toBeInTheDocument() + expect(within(dialog).queryByLabelText('长度')).not.toBeInTheDocument() + expect(within(dialog).queryByLabelText('是否预开孔')).not.toBeInTheDocument() + + fireEvent.change(within(dialog).getByLabelText('款式/用途'), { + target: { value: '防倒' }, + }) + fireEvent.change(within(dialog).getByLabelText('规格/尺寸'), { + target: { value: '30*20mm' }, + }) + fireEvent.change(within(dialog).getByLabelText('材质'), { + target: { value: '铁' }, + }) + fireEvent.change(within(dialog).getByLabelText('颜色'), { + target: { value: '黑色' }, + }) + + expect(within(dialog).getByLabelText('配件名称')).toHaveValue( + '防倒 30*20mm 黑色 铁 卡扣', + ) + + fireEvent.change(within(dialog).getByLabelText('分类'), { + target: { value: '挡块' }, + }) + fireEvent.change(within(dialog).getByLabelText('款式/用途'), { + target: { value: '门挡' }, + }) + fireEvent.change(within(dialog).getByLabelText('规格/尺寸'), { + target: { value: '小号' }, + }) + + expect(within(dialog).getByLabelText('配件名称')).toHaveValue( + '门挡 小号 黑色 铁 挡块', + ) + + await actor.click(within(dialog).getByRole('button', { name: '保存' })) + + await waitFor(() => { + expect(screen.getByText('门挡 小号 黑色 铁 挡块')).toBeInTheDocument() + }) + + const savedItems = JSON.parse( + window.localStorage.getItem(ACCESSORY_LIBRARY_STORAGE_KEY) ?? '[]', + ) + expect(savedItems[0]).toMatchObject({ + letter: 'S', + code: 'S0', + name: '门挡 小号 黑色 铁 挡块', + screwCategory: '挡块', + headType: '', + drive: '门挡', + tail: '', + material: '铁', + finish: '', + tooth: '', + diameter: '小号', + length: '', + color: '黑色', + preDrill: '', + }) + }) + + it('uses gasket and foot pad rules for T accessories', async () => { + const actor = userEvent.setup() + + render() + + await actor.click(screen.getByRole('button', { name: 'T 垫片/脚垫 0 条' })) + + expect(screen.getByText('T 组配件 · 垫片/脚垫')).toBeInTheDocument() + expect(screen.queryByRole('button', { name: '全部头型' })).not.toBeInTheDocument() + expect(screen.getByRole('button', { name: '全部分类' })).toBeInTheDocument() + expect(screen.getByRole('button', { name: '垫片' })).toBeInTheDocument() + expect(screen.getByRole('button', { name: '脚垫' })).toBeInTheDocument() + + await actor.click(screen.getByRole('button', { name: '新增 T 组' })) + + const dialog = await screen.findByRole('dialog', { name: '新增T组配件' }) + expect(within(dialog).getByLabelText('配件名称')).toHaveValue( + '圆形 φ32 塑料 垫片', + ) + expect(within(dialog).getByLabelText('分类')).toHaveValue('垫片') + expect(within(dialog).getByLabelText('款式/用途')).toHaveValue('普通') + expect(within(dialog).getByLabelText('形状')).toHaveValue('圆形') + expect(within(dialog).getByLabelText('规格/尺寸')).toHaveValue('φ32') + expect(within(dialog).getByLabelText('厚度')).toHaveValue('') + expect(within(dialog).getByLabelText('材质')).toHaveValue('塑料') + expect(within(dialog).getByLabelText('颜色')).toHaveValue('') + expect(within(dialog).queryByLabelText('头型')).not.toBeInTheDocument() + expect(within(dialog).queryByLabelText('表面处理')).not.toBeInTheDocument() + expect(within(dialog).queryByLabelText('牙型')).not.toBeInTheDocument() + expect(within(dialog).queryByLabelText('是否预开孔')).not.toBeInTheDocument() + + fireEvent.change(within(dialog).getByLabelText('分类'), { + target: { value: '脚垫' }, + }) + fireEvent.change(within(dialog).getByLabelText('款式/用途'), { + target: { value: '防滑' }, + }) + fireEvent.change(within(dialog).getByLabelText('规格/尺寸'), { + target: { value: '12*4mm' }, + }) + fireEvent.change(within(dialog).getByLabelText('材质'), { + target: { value: '橡胶' }, + }) + fireEvent.change(within(dialog).getByLabelText('颜色'), { + target: { value: '黑色' }, + }) + + expect(within(dialog).getByLabelText('配件名称')).toHaveValue( + '防滑 圆形 12*4mm 黑色 橡胶 脚垫', + ) + + await actor.click(within(dialog).getByRole('button', { name: '保存' })) + + await waitFor(() => { + expect(screen.getByText('防滑 圆形 12*4mm 黑色 橡胶 脚垫')).toBeInTheDocument() + }) + + const savedItems = JSON.parse( + window.localStorage.getItem(ACCESSORY_LIBRARY_STORAGE_KEY) ?? '[]', + ) + expect(savedItems[0]).toMatchObject({ + letter: 'T', + code: 'T0', + name: '防滑 圆形 12*4mm 黑色 橡胶 脚垫', + screwCategory: '脚垫', + headType: '', + drive: '防滑', + tail: '圆形', + material: '橡胶', + finish: '', + tooth: '', + diameter: '12*4mm', + length: '', + color: '黑色', + preDrill: '', + }) + }) + + it('uses auxiliary fastener rules for U accessories', async () => { + const actor = userEvent.setup() + + render() + + await actor.click(screen.getByRole('button', { name: 'U 辅助固定件 0 条' })) + + expect(screen.getByText('U 组配件 · 辅助固定件')).toBeInTheDocument() + expect(screen.queryByRole('button', { name: '全部头型' })).not.toBeInTheDocument() + expect(screen.getByRole('button', { name: '全部分类' })).toBeInTheDocument() + expect(screen.getByRole('button', { name: '扎带' })).toBeInTheDocument() + expect(screen.getByRole('button', { name: '粘贴件' })).toBeInTheDocument() + expect(screen.getByRole('button', { name: '钉类' })).toBeInTheDocument() + + await actor.click(screen.getByRole('button', { name: '新增 U 组' })) + + const dialog = await screen.findByRole('dialog', { name: '新增U组配件' }) + expect(within(dialog).getByLabelText('配件名称')).toHaveValue( + '固定 150mm 黑色 尼龙 扎带', + ) + expect(within(dialog).getByLabelText('分类')).toHaveValue('扎带') + expect(within(dialog).getByLabelText('款式/用途')).toHaveValue('固定') + expect(within(dialog).getByLabelText('规格/尺寸')).toHaveValue('150mm') + expect(within(dialog).getByLabelText('材质')).toHaveValue('尼龙') + expect(within(dialog).getByLabelText('颜色')).toHaveValue('黑色') + expect(within(dialog).queryByLabelText('头型')).not.toBeInTheDocument() + expect(within(dialog).queryByLabelText('尾型')).not.toBeInTheDocument() + expect(within(dialog).queryByLabelText('表面处理')).not.toBeInTheDocument() + expect(within(dialog).queryByLabelText('牙型')).not.toBeInTheDocument() + expect(within(dialog).queryByLabelText('长度')).not.toBeInTheDocument() + expect(within(dialog).queryByLabelText('是否预开孔')).not.toBeInTheDocument() + + fireEvent.change(within(dialog).getByLabelText('分类'), { + target: { value: '粘贴件' }, + }) + fireEvent.change(within(dialog).getByLabelText('款式/用途'), { + target: { value: '粘贴' }, + }) + fireEvent.change(within(dialog).getByLabelText('规格/尺寸'), { + target: { value: '3M' }, + }) + fireEvent.change(within(dialog).getByLabelText('材质'), { + target: { value: '胶' }, + }) + fireEvent.change(within(dialog).getByLabelText('颜色'), { + target: { value: '透明' }, + }) + + expect(within(dialog).getByLabelText('配件名称')).toHaveValue( + '粘贴 3M 透明 胶 粘贴件', + ) + + await actor.click(within(dialog).getByRole('button', { name: '保存' })) + + await waitFor(() => { + expect(screen.getByText('粘贴 3M 透明 胶 粘贴件')).toBeInTheDocument() + }) + + const savedItems = JSON.parse( + window.localStorage.getItem(ACCESSORY_LIBRARY_STORAGE_KEY) ?? '[]', + ) + expect(savedItems[0]).toMatchObject({ + letter: 'U', + code: 'U0', + name: '粘贴 3M 透明 胶 粘贴件', + screwCategory: '粘贴件', + headType: '', + drive: '粘贴', + tail: '', + material: '胶', + finish: '', + tooth: '', + diameter: '3M', + length: '', + color: '透明', + preDrill: '', + }) + }) + it('filters C and D accessory groups by category shortcuts', async () => { const actor = userEvent.setup() diff --git a/furniture-3d-system/src/app/intake/IntakeClient.tsx b/furniture-3d-system/src/app/intake/IntakeClient.tsx index 31e6e5d1..cf23c2ab 100644 --- a/furniture-3d-system/src/app/intake/IntakeClient.tsx +++ b/furniture-3d-system/src/app/intake/IntakeClient.tsx @@ -340,7 +340,7 @@ type IntakeEntryTab = "integrated" | "nonIntegrated" | "stock"; type ProductDevelopmentKind = NonNullable< NonIntegratedProductRecord["productDevelopmentKind"] >; -type NewNonIntegratedCreateKind = "new" | "stock"; +type NewNonIntegratedCreateKind = "new" | "stock" | "seriesComponents"; type BomLibraryKey = | "materialLibrary" | "finishLibrary" @@ -1231,6 +1231,7 @@ type NonIntegratedQuickScope = "all" | "created" | "pending"; type NonIntegratedProductKindFilter = "all" | "new" | "stock"; type NonIntegratedListQuery = { productKind: NonIntegratedProductKindFilter; + seriesName: string; spu: string; appearanceDesigner: string; structureDesigner: string; @@ -1261,6 +1262,7 @@ function createDefaultNonIntegratedListQuery( ): NonIntegratedListQuery { return { productKind, + seriesName: "", spu: "", appearanceDesigner: "", structureDesigner: "", @@ -1607,12 +1609,42 @@ function getPendingEntryTabFromNewProductTab(tab: { return "nonIntegrated"; } +function readSeriesComponentDetailMetadata(product: Record) { + const metadata = product.metadata; + if (!metadata || typeof metadata !== "object") return null; + + const record = metadata as Record; + return record.componentDetailType === "asset-series-components" + ? record + : null; +} + +function isSeriesComponentDetail(product: Record) { + return Boolean(readSeriesComponentDetailMetadata(product)); +} + +function readSeriesComponentDetailSourceSeriesName( + product: NonIntegratedProductRecord, +) { + const metadata = readSeriesComponentDetailMetadata( + product as unknown as Record, + ); + const sourceSeriesName = + typeof metadata?.sourceSeriesName === "string" + ? metadata.sourceSeriesName.trim() + : ""; + + return sourceSeriesName || product.openingReference.productName.trim(); +} + function getProductDevelopmentDetailLabel( product: NonIntegratedProductRecord, ) { const suffix = getProductDevelopmentKind(product) === "series" - ? "系列产品开发明细" + ? isSeriesComponentDetail(product as unknown as Record) + ? "部件开发明细" + : "系列产品开发明细" : isJstSkuImportedStockProduct(product) ? "存量商品明细" : "产品开发明细"; @@ -1651,16 +1683,19 @@ function createPendingEntryWorkspaceTab( function createNewNonIntegratedProductWorkspaceTab( id = "new-non-integrated:default", productDevelopmentKind: ProductDevelopmentKind = "product", + initialCreateProductKind: NewNonIntegratedCreateKind = "new", ): IntakeWorkspaceTab { return { id, kind: "newNonIntegratedProduct", label: - productDevelopmentKind === "series" - ? "新增系列产品" - : "新增产品", + initialCreateProductKind === "seriesComponents" + ? "新增部件" + : productDevelopmentKind === "series" + ? "新增系列产品" + : "新增产品", productDevelopmentKind, - initialCreateProductKind: "new", + initialCreateProductKind, }; } @@ -1930,6 +1965,11 @@ function restoreIntakeWorkspaceTab( return createNewNonIntegratedProductWorkspaceTab( tab.id, productDevelopmentKind, + tab.initialCreateProductKind === "seriesComponents" + ? "seriesComponents" + : tab.initialCreateProductKind === "stock" + ? "stock" + : "new", ); } if (tab.kind === "bomLibrary") { @@ -2565,6 +2605,10 @@ function getExistingSeriesDevelopmentNames( return getUniqueNonEmptyValues( products .filter((product) => getProductDevelopmentKind(product) === "series") + .filter( + (product) => + !isSeriesComponentDetail(product as unknown as Record), + ) .map( (product) => product.openingReference.productName || @@ -2573,6 +2617,19 @@ function getExistingSeriesDevelopmentNames( ); } +function getExistingSeriesComponentDetailNames( + products: NonIntegratedProductRecord[], +) { + return getUniqueNonEmptyValues( + products + .filter((product) => getProductDevelopmentKind(product) === "series") + .filter((product) => + isSeriesComponentDetail(product as unknown as Record), + ) + .map(readSeriesComponentDetailSourceSeriesName), + ); +} + function toggleSection( current: IntakeSection, section: Exclude, @@ -3735,10 +3792,12 @@ function NonIntegratedPendingDetail({ productDevelopmentKind = "product", fixedProductKind, createButtonLabel = "新增产品", + secondaryCreateButtonLabel, emptyMessage = "当前还没有非集成产品,点击右上角“新增产品”开始维护资料。", onProductsChange, onOpenProductWorkspace, onOpenNewNonIntegratedProductWorkspace, + onOpenSecondaryNewNonIntegratedProductWorkspace, }: { initialProducts: NonIntegratedProductRecord[]; canDeleteProducts: boolean; @@ -3746,6 +3805,7 @@ function NonIntegratedPendingDetail({ productDevelopmentKind?: ProductDevelopmentKind; fixedProductKind?: NonIntegratedProductKindFilter; createButtonLabel?: string; + secondaryCreateButtonLabel?: string; emptyMessage?: string; onProductsChange?: (products: NonIntegratedProductRecord[]) => void; onOpenProductWorkspace?: ( @@ -3753,6 +3813,7 @@ function NonIntegratedPendingDetail({ mode: WorkspaceProductMode, ) => void; onOpenNewNonIntegratedProductWorkspace?: () => void; + onOpenSecondaryNewNonIntegratedProductWorkspace?: () => void; }) { const router = useRouter(); const initialProductKind = fixedProductKind ?? "all"; @@ -3811,7 +3872,10 @@ function NonIntegratedPendingDetail({ const skipNextListStatePersistRef = useRef(false); const shouldUseSharedNonIntegratedApi = process.env.NODE_ENV !== "test"; const effectiveProductKind = fixedProductKind ?? appliedQuery.productKind; - const hasCreateAction = Boolean(onOpenNewNonIntegratedProductWorkspace); + const hasCreateAction = Boolean( + onOpenNewNonIntegratedProductWorkspace || + onOpenSecondaryNewNonIntegratedProductWorkspace, + ); function scopeProductsByDevelopmentKind( nextProducts: NonIntegratedProductRecord[], @@ -4160,6 +4224,22 @@ function NonIntegratedPendingDetail({ const stockSourceMatched = effectiveProductKind !== "stock" || stockSourceMatchesQuery(product, appliedQuery); + const seriesNameMatched = + productDevelopmentKind !== "series" || + productMatchesText( + [ + readSeriesComponentDetailSourceSeriesName(product), + readOptionalNestedString(product.metadata, "sourceSeriesName"), + readOptionalNestedString(product.metadata, "sourceSeriesCode"), + product.openingReference.productName, + getNonIntegratedProductDisplayName(product), + product.spu, + readOptionalRecordString( + (product as unknown as Record).spuBase, + ), + ].join(" "), + appliedQuery.seriesName, + ); const peopleMatched = productMatchesText( people.appearanceDesigner, @@ -4190,11 +4270,19 @@ function NonIntegratedPendingDetail({ productKindMatched && spuMatched && stockSourceMatched && + seriesNameMatched && peopleMatched && quickScopeMatched ); }); - }, [activeQuickScope, appliedQuery, currentUser, effectiveProductKind, products]); + }, [ + activeQuickScope, + appliedQuery, + currentUser, + effectiveProductKind, + productDevelopmentKind, + products, + ]); const totalRows = shouldUseSharedNonIntegratedApi ? (pageInfo?.total ?? filteredProducts.length) : filteredProducts.length; @@ -4401,9 +4489,29 @@ function NonIntegratedPendingDetail({ ], }, ]; + const seriesProductFilterFields: typeof productFilterFields = + isSeriesDevelopmentList + ? [ + { + key: "seriesName", + label: "系列名称", + ariaLabel: "系列名称", + placeholder: "搜索系列名称", + }, + ...productFilterFields, + ] + : productFilterFields; const filterFields = isStockDevelopmentList ? stockFilterFields - : productFilterFields; + : seriesProductFilterFields; + const filterGridColumnClass = + filterFields.length === 8 + ? hasCreateAction + ? "md:grid-cols-[repeat(8,minmax(0,1fr))_72px_216px]" + : "md:grid-cols-[repeat(8,minmax(0,1fr))_72px]" + : hasCreateAction + ? "md:grid-cols-[repeat(7,minmax(0,1fr))_72px_216px]" + : "md:grid-cols-[repeat(7,minmax(0,1fr))_72px]"; const quickScopes: Array<{ key: NonIntegratedQuickScope; label: string }> = [ { key: "all", label: "全部" }, { key: "created", label: "我负责的" }, @@ -4439,11 +4547,7 @@ function NonIntegratedPendingDetail({ ))}
{filterFields.map((filter) => (
{hasCreateAction ? ( -
- +
+ {onOpenNewNonIntegratedProductWorkspace ? ( + + ) : null} + {onOpenSecondaryNewNonIntegratedProductWorkspace && + secondaryCreateButtonLabel ? ( + + ) : null}
) : null}
@@ -10080,6 +10197,8 @@ export default function IntakeClient(props: IntakeClientProps) { const seriesDraftSkuOptions = getDraftGroupSeriesSkuOptions(props); const existingSeriesNames = getExistingSeriesDevelopmentNames(nonIntegratedProducts); + const existingSeriesComponentDetailNames = + getExistingSeriesComponentDetailNames(nonIntegratedProducts); const canViewProductDevelopmentList = canViewIntakeFormalWorkspace( nodePermissionOverrides, "productDevelopmentList", @@ -10665,6 +10784,7 @@ export default function IntakeClient(props: IntakeClientProps) { function openNewNonIntegratedProductWorkspace( productDevelopmentKind: ProductDevelopmentKind = "product", + initialCreateProductKind: NewNonIntegratedCreateKind = "new", ) { if (!canUseDesignControlledProductData) { return; @@ -10673,7 +10793,8 @@ export default function IntakeClient(props: IntakeClientProps) { const existingTab = workspaceTabs.find( (tab) => tab.kind === "newNonIntegratedProduct" && - tab.productDevelopmentKind === productDevelopmentKind, + tab.productDevelopmentKind === productDevelopmentKind && + (tab.initialCreateProductKind ?? "new") === initialCreateProductKind, ); if (existingTab) { syncWorkspaceState(existingTab); @@ -10681,8 +10802,12 @@ export default function IntakeClient(props: IntakeClientProps) { } const nextTab = createNewNonIntegratedProductWorkspaceTab( - createWorkspaceTabId("new-non-integrated", productDevelopmentKind), + createWorkspaceTabId( + "new-non-integrated", + `${productDevelopmentKind}:${initialCreateProductKind}`, + ), productDevelopmentKind, + initialCreateProductKind, ); openWorkspaceTab(nextTab); } @@ -10913,6 +11038,7 @@ export default function IntakeClient(props: IntakeClientProps) { productDevelopmentKind={activeWorkspaceTab.productDevelopmentKind} seriesNameOptions={seriesNameOptions} existingSeriesNames={existingSeriesNames} + existingSeriesComponentDetailNames={existingSeriesComponentDetailNames} seriesDraftSkuOptions={seriesDraftSkuOptions} materialLibraryFinishes={materialLibraryFinishes} initialDocumentWorkspaceView={activeWorkspaceTab.detailState?.view} @@ -11003,9 +11129,12 @@ export default function IntakeClient(props: IntakeClientProps) { key={activeWorkspaceTab.id} mode="create" productDevelopmentKind={activeWorkspaceTab.productDevelopmentKind} - initialCreateProductKind="new" + initialCreateProductKind={ + activeWorkspaceTab.initialCreateProductKind ?? "new" + } seriesNameOptions={seriesNameOptions} existingSeriesNames={existingSeriesNames} + existingSeriesComponentDetailNames={existingSeriesComponentDetailNames} seriesDraftSkuOptions={seriesDraftSkuOptions} materialLibraryFinishes={materialLibraryFinishes} currentUserRole={props.user.role} @@ -11103,14 +11232,12 @@ export default function IntakeClient(props: IntakeClientProps) { }); const { activeTab } = resolveWorkspaceTabsForOpen(workspaceTabs, nextTab); - setWorkspaceTabs((current) => - resolveWorkspaceTabsForOpen(current, nextTab).tabs, - ); + setWorkspaceTabs((current) => { + return resolveWorkspaceTabsForOpen(current, nextTab).tabs; + }); syncWorkspaceState(activeTab); - markProductWorkspaceTabLoaded(activeTab.id); }, [ canViewFormalWorkspaceByTarget, - markProductWorkspaceTabLoaded, props.initialOpenProductWorkspace, props.user, workspaceStateReady, @@ -11177,7 +11304,17 @@ export default function IntakeClient(props: IntakeClientProps) { onOpenNewNonIntegratedProductWorkspace={ canUseDesignControlledProductData ? () => openNewNonIntegratedProductWorkspace("series") - : undefined + : undefined + } + secondaryCreateButtonLabel="新增部件" + onOpenSecondaryNewNonIntegratedProductWorkspace={ + canUseDesignControlledProductData + ? () => + openNewNonIntegratedProductWorkspace( + "series", + "seriesComponents", + ) + : undefined } /> ) : pendingEntryTab === "stock" && canViewStockDevelopmentList ? ( @@ -11370,7 +11507,17 @@ export default function IntakeClient(props: IntakeClientProps) { onOpenNewNonIntegratedProductWorkspace={ canUseDesignControlledProductData ? () => openNewNonIntegratedProductWorkspace("series") - : undefined + : undefined + } + secondaryCreateButtonLabel="新增部件" + onOpenSecondaryNewNonIntegratedProductWorkspace={ + canUseDesignControlledProductData + ? () => + openNewNonIntegratedProductWorkspace( + "series", + "seriesComponents", + ) + : undefined } /> ) : pendingEntryTab === "stock" && canViewStockDevelopmentList ? ( diff --git a/furniture-3d-system/src/app/intake/non-integrated/NonIntegratedDetailClient.test.tsx b/furniture-3d-system/src/app/intake/non-integrated/NonIntegratedDetailClient.test.tsx index 431439a8..680922b4 100644 --- a/furniture-3d-system/src/app/intake/non-integrated/NonIntegratedDetailClient.test.tsx +++ b/furniture-3d-system/src/app/intake/non-integrated/NonIntegratedDetailClient.test.tsx @@ -39,7 +39,12 @@ import type { MaterialDTO } from "@/server/services"; import { SPU_RULE_LIBRARY_STORAGE_KEY } from "../spuRuleLibraryLogic"; import { parseZipFile } from "@/lib/zip-parser"; import { extractPreviewModelFromZip } from "../../../lib/model-preview-zip"; -import { fetchSubstrates } from "@/lib/open-product/platform-api"; +import { + fetchSubstrates, + listAssetFamilies, + listAssetSeries, + listAssetVariantsByFamilyIds, +} from "@/lib/open-product/platform-api"; import { createApprovalWorkflow } from "@/app/approval-workflows/approvalWorkflowApi"; import { buildIntakeNodePermissionOverrideKey } from "@/lib/intake-node-permission-settings"; @@ -169,6 +174,9 @@ jest.mock("./nonIntegratedApi", () => ({ jest.mock("@/lib/open-product/platform-api", () => ({ fetchSubstrates: jest.fn(), + listAssetFamilies: jest.fn(), + listAssetSeries: jest.fn(), + listAssetVariantsByFamilyIds: jest.fn(), })); jest.mock("@/app/approval-workflows/approvalWorkflowApi", () => ({ @@ -194,6 +202,11 @@ const mockedUploadSharedNonIntegratedFile = jest.mocked( uploadSharedNonIntegratedFile, ); const mockedFetchSubstrates = jest.mocked(fetchSubstrates); +const mockedListAssetFamilies = jest.mocked(listAssetFamilies); +const mockedListAssetSeries = jest.mocked(listAssetSeries); +const mockedListAssetVariantsByFamilyIds = jest.mocked( + listAssetVariantsByFamilyIds, +); const mockedCreateApprovalWorkflow = jest.mocked(createApprovalWorkflow); async function selectInlineOption( @@ -491,6 +504,9 @@ describe("NonIntegratedDetailClient", () => { })); mockedUploadSharedNonIntegratedFile.mockReset(); mockedFetchSubstrates.mockReset(); + mockedListAssetFamilies.mockReset(); + mockedListAssetSeries.mockReset(); + mockedListAssetVariantsByFamilyIds.mockReset(); mockedCreateApprovalWorkflow.mockClear(); mockedFetchSubstrates.mockResolvedValue([ createSubstrateOption({ @@ -515,6 +531,9 @@ describe("NonIntegratedDetailClient", () => { systemName: "20ENF级橡胶木", }), ]); + mockedListAssetSeries.mockResolvedValue([]); + mockedListAssetFamilies.mockResolvedValue([]); + mockedListAssetVariantsByFamilyIds.mockResolvedValue([]); Object.defineProperty(navigator, "clipboard", { value: { writeText: jest.fn(async () => undefined), @@ -862,6 +881,139 @@ describe("NonIntegratedDetailClient", () => { expect(within(dialog).getAllByText("2").length).toBeGreaterThan(0); }); + it("keeps PACKAGING asset variants in series component detail sku content", async () => { + const now = new Date("2026-06-02T08:00:00.000Z"); + mockedListAssetSeries.mockResolvedValue([ + { + id: "series-dbz", + code: "DBZ", + name: "DBZ", + displayName: "DBZ", + description: null, + sortOrder: 0, + isActive: true, + createdAt: now, + updatedAt: now, + }, + ]); + mockedListAssetFamilies.mockResolvedValue([ + { + id: "family-board", + type: "BOARD", + code: "DBZ-SPJK01", + name: "Board family", + status: "AVAILABLE", + }, + { + id: "family-packaging", + type: "PACKAGING", + code: "DBZ-SPJK06", + name: "Packaging family", + status: "AVAILABLE", + }, + ] as never); + mockedListAssetVariantsByFamilyIds.mockImplementation(async (familyIds) => + [ + { + id: "variant-board-1", + assetFamilyId: "family-board", + assetFamilyCode: "DBZ-SPJK01", + assetFamilyName: "Board family", + assetType: "BOARD", + code: "DBZ-SPJ01", + name: "Board 01", + sizeLabel: "140/60/2.5", + modelUrl: "/models/board.glb", + thumbnailUrl: "", + barcode: "DBZ-SPJ01N1280V01", + supplierName: "Supplier", + supplierCode: "N1280", + versionNo: "V01", + businessData: { + skuContentFields: { + model: "DBZ-SPJK01", + skuCode: "DBZ-SPJ01", + barcode: "DBZ-SPJ01N1280V01", + specName: "Board 01", + size: "140/60/2.5", + }, + }, + }, + { + id: "variant-packaging-11", + assetFamilyId: "family-packaging", + assetFamilyCode: "DBZ-SPJK06", + assetFamilyName: "Packaging family", + assetType: "PACKAGING", + code: "DBZ-SPJ11", + name: "Packaging 11", + sizeLabel: "120/120/0.3", + modelUrl: "", + thumbnailUrl: "", + barcode: "DBZ-SPJ11N12V01", + supplierName: "Carton supplier", + supplierCode: "N12", + versionNo: "V01", + businessData: { + skuContentFields: { + model: "DBZ-SPJK06", + skuCode: "DBZ-SPJ11", + barcode: "DBZ-SPJ11N12V01", + specName: "Packaging 11", + size: "120/120/0.3", + material: "Carton", + }, + }, + }, + ].filter((variant) => familyIds.includes(variant.assetFamilyId)) as never, + ); + + saveNonIntegratedProduct( + createProductRecord({ + id: "DBZ-SPJ-component-detail", + spu: "DBZ-SPJ", + productDevelopmentKind: "series", + metadata: { + componentDetailType: "asset-series-components", + sourceSeriesCode: "DBZ", + sourceSeriesName: "DBZ", + }, + openingReference: { + ...createEmptyNonIntegratedOpeningReference(), + productName: "DBZ", + }, + skuItems: [ + createSkuItem({ + id: "asset-variant-variant-board-1", + skuSequence: 1, + model: "DBZ-SPJK01", + skuCode: "DBZ-SPJ01", + barcode: "DBZ-SPJ01N1280V01", + source: "asset_series_component", + sourceTable: "asset_variant", + sourceSkuId: "variant-board-1", + }), + ], + }), + ); + + render( + , + ); + + await waitFor(() => + expect(mockedListAssetVariantsByFamilyIds).toHaveBeenCalledWith([ + "family-board", + "family-packaging", + ]), + ); + expect(await screen.findByDisplayValue("DBZ-SPJ11")).toBeInTheDocument(); + expect(screen.getAllByDisplayValue("DBZ-SPJK06").length).toBeGreaterThan(0); + }); + it("hides already created series names from the create selector", async () => { const actor = userEvent.setup(); diff --git a/furniture-3d-system/src/app/intake/non-integrated/NonIntegratedDetailClient.tsx b/furniture-3d-system/src/app/intake/non-integrated/NonIntegratedDetailClient.tsx index 74a3a817..146b6a57 100644 --- a/furniture-3d-system/src/app/intake/non-integrated/NonIntegratedDetailClient.tsx +++ b/furniture-3d-system/src/app/intake/non-integrated/NonIntegratedDetailClient.tsx @@ -152,8 +152,18 @@ import { parseNonIntegratedSkuWorkbook, type NonIntegratedSkuExportRow, } from "@/lib/non-integrated-sku-export"; -import { fetchSubstrates } from "@/lib/open-product/platform-api"; -import type { MaterialDTO } from "@/server/services"; +import { + fetchSubstrates, + listAssetFamilies, + listAssetSeries, + listAssetVariantsByFamilyIds, +} from "@/lib/open-product/platform-api"; +import type { + AssetFamilyDTO, + AssetSeriesDTO, + AssetVariantDTO, + MaterialDTO, +} from "@/server/services"; import RawMaterialLibraryPanel from "@/app/intake/RawMaterialLibraryPanel"; import { SPU_RULE_LIBRARY_UPDATED_EVENT, @@ -402,6 +412,13 @@ const SKU_BATCH_CHANGE_TYPE_OPTIONS: SkuBatchChangeType[] = [ ]; const NATIONAL_STANDARD_COMPLIANCE_OPTIONS = ["是", "否"] as const; const SKU_BOARD_MATERIAL_TYPE_OPTIONS = ["ENF级", "非ENF级", "清货板材"] as const; +const NON_BOARD_SKU_BOARD_MATERIAL_TYPE = "非ENF级"; +const DEFAULT_ASSET_SKU_ATTRIBUTE_CODE = "A"; +const DEFAULT_ASSET_SKU_INSTALL_METHOD = "拆装"; +const DEFAULT_ASSET_SKU_EXECUTE_STANDARD = "GB/T3324-2024"; +const DEFAULT_STEEL_ASSET_SKU_EXECUTE_STANDARD = "GB/T3325-2024"; +const DEFAULT_ASSET_SKU_NATIONAL_STANDARD_COMPLIANT = "是"; +const DEFAULT_ASSET_SKU_SALES_STATUS = "销售"; const SKU_SALES_STATUS_OPTIONS = ["销售", "停产", "退市"] as const; const SKU_COLUMN_DEFAULT_WIDTHS: Record = { @@ -694,10 +711,17 @@ type ReviewImageManagerState = { target: ReviewIssueImageTarget; }; -type CreateProductKind = "new" | "stock"; +type CreateProductKind = "new" | "stock" | "seriesComponents"; type ProductDevelopmentKind = NonNullable< NonIntegratedProductRecord["productDevelopmentKind"] >; +const SERIES_COMPONENT_DETAIL_METADATA_TYPE = "asset-series-components"; +const SERIES_COMPONENT_SECONDARY_CATEGORY = "家具辅料"; +const SERIES_COMPONENT_PRODUCT_CATEGORY = "其它家具配件"; +const SERIES_COMPONENT_ASSET_SKU_SOURCE = "asset_series_component"; +const ASSET_VARIANT_SOURCE_TABLE = "asset_variant"; +const ASSET_VARIANT_SKU_CONTENT_BUSINESS_DATA_KEY = "skuContentFields"; + type SeriesDraftSkuOption = { id: string; draftGroupId?: string; @@ -767,6 +791,47 @@ type FormValues = { craftDetail: string; }; +function readSeriesComponentDetailMetadata( + product: NonIntegratedProductRecord | null | undefined, +) { + const metadata = product?.metadata; + if (!metadata || typeof metadata !== "object") return null; + + return metadata.componentDetailType === SERIES_COMPONENT_DETAIL_METADATA_TYPE + ? metadata + : null; +} + +function isSeriesComponentCreateKind(kind: CreateProductKind) { + return kind === "seriesComponents"; +} + +function getSeriesComponentSourceSeriesName( + product: NonIntegratedProductRecord | null | undefined, +) { + const metadata = readSeriesComponentDetailMetadata(product); + return typeof metadata?.sourceSeriesName === "string" + ? metadata.sourceSeriesName.trim() + : ""; +} + +function getAssetSeriesCodeFromSeriesName(seriesName: string) { + const normalizedName = seriesName.trim(); + const codeMatch = normalizedName.match(/([A-Za-z][A-Za-z0-9]*)(?:\s*)$/); + return codeMatch?.[1]?.toUpperCase() ?? ""; +} + +function getSeriesComponentSpuFromSeriesName(seriesName: string) { + const seriesCode = getAssetSeriesCodeFromSeriesName(seriesName); + return seriesCode ? `${seriesCode}-SPJ` : ""; +} + +function getSeriesComponentProductName(seriesName: string) { + const normalizedName = seriesName.trim(); + if (!normalizedName) return ""; + return normalizedName.endsWith("部件") ? normalizedName : `${normalizedName} 部件`; +} + type FieldDefinition = { key: keyof FormValues; label: string; @@ -3483,6 +3548,127 @@ function normalizeSeriesDraftSkuSequence( return fallbackIndex + 1; } +type SkuPreviewImageCandidate = { + image: string; + imageName: string; +}; + +function isRecordLike(value: unknown): value is Record { + return Boolean(value && typeof value === "object" && !Array.isArray(value)); +} + +function readRecordString(value: Record, key: string) { + const rawValue = value[key]; + return typeof rawValue === "string" ? rawValue.trim() : ""; +} + +function readRecordStringIfPresent(value: Record, key: string) { + if (!Object.prototype.hasOwnProperty.call(value, key)) return undefined; + const rawValue = value[key]; + if (typeof rawValue === "string") return rawValue.trim(); + if (typeof rawValue === "number" && Number.isFinite(rawValue)) { + return String(rawValue); + } + return ""; +} + +function readAssetVariantSkuContentFields( + variant: AssetVariantDTO, +): Partial { + const rawFields = isRecordLike(variant.businessData) + ? variant.businessData[ASSET_VARIANT_SKU_CONTENT_BUSINESS_DATA_KEY] + : null; + if (!isRecordLike(rawFields)) return {}; + + return [ + "model", + "skuCode", + "barcode", + "setCount", + "specName", + "size", + "color", + "material", + "boardMaterialType", + "versionNo", + "attributeCode", + "drawingId", + "installMethod", + "executeStandard", + "nationalStandardCompliant", + "manufacturer", + "manufacturerCode", + "salesStatus", + "batchNo", + "tagMaterial", + "model3dFileName", + ].reduce>((fields, key) => { + const value = readRecordStringIfPresent(rawFields, key); + if (value !== undefined) { + fields[key as keyof SeriesDraftSkuFields] = value; + } + return fields; + }, {}); +} + +function normalizeAssetVariantCodeForPreviewLookup(code: string) { + return code + .trim() + .toUpperCase() + .replace(/-SPJ0+(\d+)$/, (_match, sequence: string) => { + const numericSequence = Number.parseInt(sequence, 10); + return `-SPJ${String(numericSequence).padStart(2, "0")}`; + }); +} + +function resolveSeriesDraftSkuPreviewImage( + option: SeriesDraftSkuOption, +): SkuPreviewImageCandidate | null { + const skuFieldImage = option.skuFields?.image?.trim() ?? ""; + if (skuFieldImage) { + return { + image: skuFieldImage, + imageName: + option.skuFields?.imageName?.trim() || + `${option.code.trim() || option.name.trim() || option.id}-preview`, + }; + } + + const previewNodes = Array.isArray(option.model3dPreviewNodes) + ? option.model3dPreviewNodes + : []; + const nodeWithThumbnail = previewNodes + .filter(isRecordLike) + .find((node) => readRecordString(node, "thumbnailUrl").length > 0); + if (!nodeWithThumbnail) return null; + + const image = readRecordString(nodeWithThumbnail, "thumbnailUrl"); + const imageName = + readRecordString(nodeWithThumbnail, "code") || + readRecordString(nodeWithThumbnail, "name") || + readRecordString(nodeWithThumbnail, "label") || + option.code.trim() || + option.name.trim() || + option.id; + + return { + image, + imageName: `${imageName}-thumb`, + }; +} + +function createAssetVariantPreviewImageCandidate( + variant: AssetVariantDTO, +): SkuPreviewImageCandidate | null { + const image = variant.thumbnailUrl?.trim() ?? ""; + if (!image) return null; + + return { + image, + imageName: `${variant.code.trim() || variant.id}-thumb`, + }; +} + function createSkuItemFromSeriesDraftSku( option: SeriesDraftSkuOption, index: number, @@ -3504,14 +3690,15 @@ function createSkuItemFromSeriesDraftSku( ] .filter(Boolean) .join(" / "); + const previewImage = resolveSeriesDraftSkuPreviewImage(option); return { ...createEmptySkuItem(), id: option.id ? `series-${option.id}` : buildNonIntegratedSkuId(), skuSequence: sequence, batchNo: parseImportedSkuBatchNo(skuFields?.batchNo ?? "", 1), - image: skuFields?.image?.trim() ?? "", - imageName: skuFields?.imageName?.trim() ?? "", + image: previewImage?.image ?? "", + imageName: previewImage?.imageName ?? "", model: skuFields?.model.trim() || normalizedCode, setCount: skuFields?.setCount.trim() || "1", specName: skuFields?.specName.trim() || "", @@ -3547,6 +3734,303 @@ function buildSeriesSkuItemsFromDraftSkus(options: SeriesDraftSkuOption[]) { ); } +function getAssetCodeSequence(code: string) { + const matched = code.trim().toUpperCase().match(/(\d+)$/); + const value = matched ? Number.parseInt(matched[1] ?? "", 10) : 0; + return Number.isFinite(value) ? value : 0; +} + +function sortAssetVariantsForSeriesComponent( + variants: AssetVariantDTO[], + familyOrderById: ReadonlyMap, +) { + return [...variants].sort((left, right) => { + const familyOrderDelta = + (familyOrderById.get(left.assetFamilyId) ?? Number.MAX_SAFE_INTEGER) - + (familyOrderById.get(right.assetFamilyId) ?? Number.MAX_SAFE_INTEGER); + if (familyOrderDelta !== 0) return familyOrderDelta; + + const leftFamilyCode = left.assetFamilyCode.trim(); + const rightFamilyCode = right.assetFamilyCode.trim(); + const familyCodeCompare = leftFamilyCode.localeCompare( + rightFamilyCode, + "zh-CN", + { numeric: true }, + ); + if (familyCodeCompare !== 0) return familyCodeCompare; + + const codeSequenceDelta = + getAssetCodeSequence(left.code) - getAssetCodeSequence(right.code); + if (codeSequenceDelta !== 0) return codeSequenceDelta; + + return left.code.localeCompare(right.code, "zh-CN", { numeric: true }); + }); +} + +function hasAssetVariantSkuField( + fields: Partial>, + key: string, +) { + return Object.prototype.hasOwnProperty.call(fields, key); +} + +function readAssetVariantSkuFieldWithDefault( + fields: Partial>, + key: string, + defaultValue: string, +) { + return hasAssetVariantSkuField(fields, key) ? fields[key] ?? "" : defaultValue; +} + +function getDefaultAssetVariantExecuteStandard(assetType: string) { + return assetType === "COMPONENT" || assetType === "HARDWARE" + ? DEFAULT_STEEL_ASSET_SKU_EXECUTE_STANDARD + : DEFAULT_ASSET_SKU_EXECUTE_STANDARD; +} + +function createSkuItemFromAssetVariant( + variant: AssetVariantDTO, + index: number, +): NonIntegratedSkuItem { + const skuFields = readAssetVariantSkuContentFields(variant); + const skuCode = variant.code.trim().toUpperCase(); + const manufacturerCode = + skuFields.manufacturerCode?.trim().toUpperCase() || + variant.supplierCode?.trim().toUpperCase() || + ""; + const rawVersionNo = hasAssetVariantSkuField(skuFields, "versionNo") + ? skuFields.versionNo ?? "" + : variant.versionNo ?? "V01"; + const versionNo = rawVersionNo.trim() ? normalizeSkuVersionNo(rawVersionNo) : ""; + const barcode = + skuFields.barcode?.trim().toUpperCase() || + variant.barcode?.trim().toUpperCase() || + (manufacturerCode && versionNo ? buildAutoBarcode(skuCode, manufacturerCode, versionNo) : ""); + const model = skuFields.model?.trim() || variant.assetFamilyCode.trim().toUpperCase(); + const attributeCode = readAssetVariantSkuFieldWithDefault( + skuFields, + "attributeCode", + DEFAULT_ASSET_SKU_ATTRIBUTE_CODE, + ).trim().toUpperCase(); + const drawingId = + skuFields.drawingId?.trim().toUpperCase() || + (model ? `${model}${attributeCode}${versionNo}` : ""); + const boardMaterialType = readAssetVariantSkuFieldWithDefault( + skuFields, + "boardMaterialType", + NON_BOARD_SKU_BOARD_MATERIAL_TYPE, + ).trim(); + + return { + ...createEmptySkuItem(), + id: `asset-variant-${variant.id}`, + skuSequence: index + 1, + batchNo: parseImportedSkuBatchNo(skuFields.batchNo ?? "", 1), + model, + skuCode, + setCount: skuFields.setCount?.trim() || "1", + specName: skuFields.specName?.trim() || variant.name.trim(), + barcode, + size: skuFields.size?.trim() || variant.sizeLabel?.trim() || "", + color: skuFields.color?.trim() || "", + material: skuFields.material?.trim() || "", + boardMaterialType, + image: variant.thumbnailUrl?.trim() ?? "", + imageName: variant.thumbnailUrl ? `${variant.code}-thumb` : "", + versionNo, + attributeCode, + drawingId, + installMethod: readAssetVariantSkuFieldWithDefault( + skuFields, + "installMethod", + DEFAULT_ASSET_SKU_INSTALL_METHOD, + ).trim(), + executeStandard: readAssetVariantSkuFieldWithDefault( + skuFields, + "executeStandard", + getDefaultAssetVariantExecuteStandard(variant.assetType), + ).trim(), + nationalStandardCompliant: + readAssetVariantSkuFieldWithDefault( + skuFields, + "nationalStandardCompliant", + DEFAULT_ASSET_SKU_NATIONAL_STANDARD_COMPLIANT, + ).trim(), + manufacturer: + skuFields.manufacturer?.trim() || variant.supplierName?.trim() || "", + manufacturerCode, + salesStatus: readAssetVariantSkuFieldWithDefault( + skuFields, + "salesStatus", + DEFAULT_ASSET_SKU_SALES_STATUS, + ).trim(), + tagMaterial: skuFields.tagMaterial?.trim() ?? "", + model3dFileName: + skuFields.model3dFileName?.trim() || + (variant.modelUrl.trim() ? `${variant.code}-model.glb` : ""), + model3dDataUrl: variant.modelUrl.trim(), + model3dUvConfig: variant.uvConfig ?? null, + source: SERIES_COMPONENT_ASSET_SKU_SOURCE, + sourceTable: ASSET_VARIANT_SOURCE_TABLE, + sourceSkuId: variant.id, + }; +} + +function buildSeriesComponentSkuItemsFromAssetVariants( + variants: AssetVariantDTO[], + families: AssetFamilyDTO[], +) { + const familyOrderById = new Map( + [...families] + .sort((left, right) => + left.code.localeCompare(right.code, "zh-CN", { numeric: true }), + ) + .map((family, index) => [family.id, index]), + ); + + return sortAssetVariantsForSeriesComponent(variants, familyOrderById).map( + (variant, index) => createSkuItemFromAssetVariant(variant, index), + ); +} + +function findAssetSeriesByCode(series: AssetSeriesDTO[], seriesCode: string) { + const normalizedSeriesCode = seriesCode.trim().toUpperCase(); + if (!normalizedSeriesCode) return null; + + return ( + series.find( + (item) => item.code.trim().toUpperCase() === normalizedSeriesCode, + ) ?? null + ); +} + +function hasSkuContentForSeriesComponentSync(item: NonIntegratedSkuItem) { + return [ + item.image, + item.model, + item.skuCode, + item.specName, + item.barcode, + item.size, + item.color, + item.material, + item.boardMaterialType ?? "", + item.attributeCode, + item.drawingId, + item.installMethod, + item.executeStandard, + item.nationalStandardCompliant, + item.manufacturer, + item.manufacturerCode, + item.salesStatus, + item.model3dDataUrl, + ].some((value) => value.trim().length > 0); +} + +function isSeriesComponentAssetSkuItem(item: NonIntegratedSkuItem) { + const source = normalizeSkuSourceMarker(item.source); + const sourceTable = normalizeSkuSourceMarker(item.sourceTable); + return ( + source === SERIES_COMPONENT_ASSET_SKU_SOURCE || + sourceTable === ASSET_VARIANT_SOURCE_TABLE + ); +} + +function getSeriesComponentAssetSkuSignature(items: NonIntegratedSkuItem[]) { + return items + .map((item) => + [ + item.sourceSkuId?.trim() ?? "", + item.model.trim().toUpperCase(), + item.skuCode.trim().toUpperCase(), + item.image.trim(), + item.imageName.trim(), + item.barcode.trim().toUpperCase(), + item.setCount.trim(), + item.specName.trim(), + item.size.trim(), + item.color.trim(), + item.material.trim(), + item.boardMaterialType?.trim() ?? "", + item.versionNo.trim().toUpperCase(), + item.attributeCode.trim().toUpperCase(), + item.drawingId.trim().toUpperCase(), + item.installMethod.trim(), + item.executeStandard.trim(), + item.nationalStandardCompliant.trim(), + item.manufacturer.trim(), + item.manufacturerCode.trim().toUpperCase(), + item.salesStatus.trim(), + String(item.batchNo), + item.model3dDataUrl.trim(), + ].join(":"), + ) + .join("|"); +} + +function mergeSeriesComponentAssetSkuItems( + currentItems: NonIntegratedSkuItem[], + assetItems: NonIntegratedSkuItem[], +) { + if (assetItems.length === 0) return currentItems; + const currentHasOnlyPlaceholder = + currentItems.length <= 1 && + currentItems.every((item) => !hasSkuContentForSeriesComponentSync(item)); + if (currentHasOnlyPlaceholder) return assetItems; + + const currentBySourceSkuId = new Map( + currentItems + .map((item) => [item.sourceSkuId?.trim() ?? "", item] as const) + .filter(([sourceSkuId]) => sourceSkuId.length > 0), + ); + const currentBySkuCode = new Map( + currentItems + .map((item) => [item.skuCode.trim().toUpperCase(), item] as const) + .filter(([skuCode]) => skuCode.length > 0), + ); + + return assetItems.map((assetItem, index) => { + const matchedCurrent = + currentBySourceSkuId.get(assetItem.sourceSkuId?.trim() ?? "") ?? + currentBySkuCode.get(assetItem.skuCode.trim().toUpperCase()); + if (!matchedCurrent) return assetItem; + + return { + ...matchedCurrent, + id: matchedCurrent.id || assetItem.id, + skuSequence: index + 1, + batchNo: assetItem.batchNo, + model: assetItem.model, + skuCode: assetItem.skuCode, + setCount: assetItem.setCount, + specName: assetItem.specName, + barcode: assetItem.barcode, + size: assetItem.size, + color: assetItem.color, + material: assetItem.material, + boardMaterialType: assetItem.boardMaterialType, + versionNo: assetItem.versionNo, + attributeCode: assetItem.attributeCode, + drawingId: assetItem.drawingId, + installMethod: assetItem.installMethod, + executeStandard: assetItem.executeStandard, + nationalStandardCompliant: assetItem.nationalStandardCompliant, + manufacturer: assetItem.manufacturer, + manufacturerCode: assetItem.manufacturerCode, + salesStatus: assetItem.salesStatus, + tagMaterial: assetItem.tagMaterial, + image: assetItem.image || matchedCurrent.image, + imageName: assetItem.imageName || matchedCurrent.imageName, + model3dFileName: assetItem.model3dFileName, + model3dDataUrl: assetItem.model3dDataUrl, + model3dUvConfig: assetItem.model3dUvConfig, + source: SERIES_COMPONENT_ASSET_SKU_SOURCE, + sourceTable: ASSET_VARIANT_SOURCE_TABLE, + sourceSkuId: assetItem.sourceSkuId, + }; + }); +} + function extractLegacySeriesComponentCodes(value: string | undefined | null) { const normalizedValue = value?.trim().toUpperCase() ?? ""; if (!normalizedValue.includes("/")) return []; @@ -5465,8 +5949,9 @@ function deriveSkuItem( const versionNo = normalizeSkuVersionNo(item.versionNo); const normalizedItem = { ...item, versionNo }; const importedContentLocked = isImportedSkuContentLocked(item); + const seriesComponentAssetSku = isSeriesComponentAssetSkuItem(item); const resolvedSkuCode = - importedContentLocked && item.skuCode.trim() + (importedContentLocked || seriesComponentAssetSku) && item.skuCode.trim() ? item.skuCode.trim().toUpperCase() : finalSkuCode; const autoDrawingId = buildAutoDrawingId({ @@ -5481,6 +5966,29 @@ function deriveSkuItem( const importedLockedBarcode = importedContentLocked ? item.barcode.trim().toUpperCase() : ""; + const resolvedSpecName = seriesComponentAssetSku + ? item.specName.trim() + : importedContentLocked && item.specName.trim() + ? item.specName.trim() + : autoSpecName; + const resolvedBarcode = seriesComponentAssetSku + ? item.barcode.trim().toUpperCase() + : importedLockedBarcode || + (shouldKeepCustomBarcode( + item.barcode, + resolvedSkuCode, + item.manufacturerCode, + versionNo, + ) + ? item.barcode.trim() + : autoBarcode); + const resolvedDrawingId = seriesComponentAssetSku + ? item.drawingId.trim().toUpperCase() + : importedContentLocked && item.drawingId.trim() + ? item.drawingId.trim().toUpperCase() + : shouldKeepCustomDrawingId(item.drawingId, normalizedItem) + ? item.drawingId.trim() + : autoDrawingId; return { ...item, @@ -5489,27 +5997,10 @@ function deriveSkuItem( ? Math.floor(item.batchNo) : 1, skuCode: resolvedSkuCode, - specName: - importedContentLocked && item.specName.trim() - ? item.specName.trim() - : autoSpecName, - barcode: - importedLockedBarcode || - (shouldKeepCustomBarcode( - item.barcode, - resolvedSkuCode, - item.manufacturerCode, - versionNo, - ) - ? item.barcode.trim() - : autoBarcode), + specName: resolvedSpecName, + barcode: resolvedBarcode, versionNo, - drawingId: - importedContentLocked && item.drawingId.trim() - ? item.drawingId.trim().toUpperCase() - : shouldKeepCustomDrawingId(item.drawingId, normalizedItem) - ? item.drawingId.trim() - : autoDrawingId, + drawingId: resolvedDrawingId, installMethod: item.installMethod.trim(), executeStandard: item.executeStandard.trim(), nationalStandardCompliant: normalizeNationalStandardCompliance( @@ -5535,6 +6026,17 @@ function parseImportedSkuBatchNo(value: string, fallbackBatchNo = 1) { return Math.floor(parsedBatchNo); } +function getSkuBatchCountFromSkuItems(items: NonIntegratedSkuItem[]) { + return Math.max( + 1, + ...items.map((item) => + Number.isFinite(item.batchNo) && item.batchNo > 0 + ? Math.floor(item.batchNo) + : 1, + ), + ); +} + function buildSkuItemFromImportedRow( row: NonIntegratedSkuExportRow, existingItem: NonIntegratedSkuItem | undefined, @@ -10463,6 +10965,7 @@ function buildProductPayload( createdBy?: string, updatedBy?: string, productDevelopmentKind: ProductDevelopmentKind = "product", + metadata?: Record, ): NonIntegratedProductRecord { const now = new Date().toISOString(); const derivedSkuItemsForPayload = skuItems.map((item, index) => { @@ -10707,6 +11210,7 @@ function buildProductPayload( return { id, productDevelopmentKind, + ...(metadata && Object.keys(metadata).length > 0 ? { metadata } : {}), projectStatus, projectReview: normalizeNonIntegratedProjectReview(projectReview), openingReference: normalizedOpeningReference, @@ -10863,8 +11367,10 @@ export default function NonIntegratedDetailClient({ onOpenRawMaterialProcessConfig, onReturnToList, productDevelopmentKind = "product", + initialCreateProductKind = "new", seriesNameOptions = [], existingSeriesNames = [], + existingSeriesComponentDetailNames = [], seriesDraftSkuOptions = [], materialLibraryFinishes = [], }: { @@ -10897,6 +11403,7 @@ export default function NonIntegratedDetailClient({ productDevelopmentKind?: ProductDevelopmentKind; seriesNameOptions?: string[]; existingSeriesNames?: string[]; + existingSeriesComponentDetailNames?: string[]; seriesDraftSkuOptions?: SeriesDraftSkuOption[]; materialLibraryFinishes?: MaterialDTO[]; }) { @@ -10979,7 +11486,9 @@ export default function NonIntegratedDetailClient({ const [activeSkuTab, setActiveSkuTab] = useState("skuInfo"); const [activeComponentSkuCategory, setActiveComponentSkuCategory] = useState("all"); - const [createProductKind] = useState("new"); + const [createProductKind] = useState( + initialCreateProductKind, + ); const [stockProductSpu, setStockProductSpu] = useState(""); const [formValues, setFormValues] = useState(() => createFormValuesFromProduct(existingProduct), @@ -11040,6 +11549,16 @@ export default function NonIntegratedDetailClient({ const [seriesComponentDialogSkuId, setSeriesComponentDialogSkuId] = useState< string | null >(null); + const [seriesComponentAssetFamilies, setSeriesComponentAssetFamilies] = + useState([]); + const [seriesComponentAssetVariants, setSeriesComponentAssetVariants] = + useState([]); + const [ + isSeriesComponentAssetsLoading, + setIsSeriesComponentAssetsLoading, + ] = useState(false); + const [seriesComponentAssetsError, setSeriesComponentAssetsError] = + useState(""); const [factoryRows, setFactoryRows] = useState( existingProduct?.factoryRows ?? [], ); @@ -12122,9 +12641,62 @@ export default function NonIntegratedDetailClient({ ? "series" : productDevelopmentKind; const isSeriesDevelopment = effectiveProductDevelopmentKind === "series"; + const isSeriesComponentCreate = + mode === "create" && + isSeriesDevelopment && + isSeriesComponentCreateKind(createProductKind); + const isSeriesComponentDetailProduct = Boolean( + readSeriesComponentDetailMetadata(existingProduct), + ); + const selectedSourceSeriesName = isSeriesComponentCreate + ? openingReference.productName.trim() + : getSeriesComponentSourceSeriesName(existingProduct); + const assetSeriesNameForSkuAssets = + selectedSourceSeriesName || + openingReference.productName.trim() || + existingProduct?.openingReference?.productName?.trim() || + ""; + const seriesComponentSpu = + getSeriesComponentSpuFromSeriesName(selectedSourceSeriesName); + const seriesComponentProductName = + getSeriesComponentProductName(selectedSourceSeriesName); + const selectedAssetSeriesCode = + getAssetSeriesCodeFromSeriesName(assetSeriesNameForSkuAssets); + const shouldLoadSeriesComponentAssets = + isSeriesDevelopment && + (isSeriesComponentCreate || isSeriesComponentDetailProduct || mode === "edit") && + selectedAssetSeriesCode.length > 0; + const seriesComponentAssetSkuItems = useMemo( + () => + buildSeriesComponentSkuItemsFromAssetVariants( + seriesComponentAssetVariants, + seriesComponentAssetFamilies, + ), + [seriesComponentAssetFamilies, seriesComponentAssetVariants], + ); + const seriesAssetVariantPreviewImageByCode = useMemo(() => { + const lookup = new Map(); + + seriesComponentAssetVariants.forEach((variant) => { + const previewImage = createAssetVariantPreviewImageCandidate(variant); + if (!previewImage) return; + + const code = variant.code.trim().toUpperCase(); + const normalizedCode = normalizeAssetVariantCodeForPreviewLookup(code); + [code, normalizedCode] + .filter(Boolean) + .forEach((key) => lookup.set(key, previewImage)); + }); + + return lookup; + }, [seriesComponentAssetVariants]); const isStockSeriesProductCreate = isStockProductCreate && isSeriesDevelopment; - const developmentCreateTitle = isSeriesDevelopment ? "新增系列产品" : "新增产品"; + const developmentCreateTitle = isSeriesComponentCreate + ? "新增部件" + : isSeriesDevelopment + ? "新增系列产品" + : "新增产品"; const developmentNameLabel = isSeriesDevelopment ? "系列名称" : "名称"; const developmentNamePlaceholder = isSeriesDevelopment ? "请选择系列名称" @@ -12136,11 +12708,15 @@ export default function NonIntegratedDetailClient({ ? "如:单板桌系列" : "如:胡桃木色窄边书桌"; const developmentDetailSuffix = isSeriesDevelopment - ? "系列产品开发明细" + ? isSeriesComponentDetailProduct + ? "部件开发明细" + : "系列产品开发明细" : "产品开发明细"; - const developmentCreateButtonLabel = isSeriesDevelopment - ? "创建系列产品" - : "创建开品单"; + const developmentCreateButtonLabel = isSeriesComponentCreate + ? "创建部件" + : isSeriesDevelopment + ? "创建系列产品" + : "创建开品单"; const existingSeriesNameKeys = useMemo( () => new Set( @@ -12150,13 +12726,38 @@ export default function NonIntegratedDetailClient({ ), [existingSeriesNames], ); + const existingSeriesComponentDetailNameKeys = useMemo( + () => + new Set( + existingSeriesComponentDetailNames + .map((name) => normalizeSeriesNameKey(name)) + .filter((name) => name.length > 0), + ), + [existingSeriesComponentDetailNames], + ); const availableSeriesNameOptions = useMemo(() => { if (!isSeriesDevelopment) return []; - return getUniqueNonEmptyStrings(seriesNameOptions).filter( - (name) => !existingSeriesNameKeys.has(normalizeSeriesNameKey(name)), + const blockedSeriesNameKeys = isSeriesComponentCreate + ? existingSeriesComponentDetailNameKeys + : existingSeriesNameKeys; + const sourceSeriesNames = isSeriesComponentCreate + ? [...existingSeriesNames, ...seriesNameOptions] + : seriesNameOptions; + + return getUniqueNonEmptyStrings(sourceSeriesNames).filter( + (name) => + !blockedSeriesNameKeys.has(normalizeSeriesNameKey(name)) && + (!isSeriesComponentCreate || + getSeriesComponentSpuFromSeriesName(name).length > 0), ); - }, [existingSeriesNameKeys, isSeriesDevelopment, seriesNameOptions]); + }, [ + existingSeriesComponentDetailNameKeys, + existingSeriesNameKeys, + isSeriesComponentCreate, + isSeriesDevelopment, + seriesNameOptions, + ]); const selectedSeriesNameKey = normalizeSeriesNameKey( openingReference.productName, ); @@ -12196,10 +12797,163 @@ export default function NonIntegratedDetailClient({ return lookup; }, [selectedSeriesDraftSkuOptions]); const selectedSeriesDraftSkuCount = selectedSeriesDraftSkuOptions.length; + const selectedSeriesDraftSkuPreviewImageByKey = useMemo(() => { + const lookup = new Map(); + + selectedSeriesDraftSkuOptions.forEach((option, index) => { + const previewImage = resolveSeriesDraftSkuPreviewImage(option); + if (!previewImage) return; + + const sequence = normalizeSeriesDraftSkuSequence(option, index); + [ + option.id, + `series-${option.id}`, + option.code.trim(), + String(sequence).padStart(2, "0"), + String(sequence), + ] + .map((key) => key.trim()) + .filter(Boolean) + .forEach((key) => lookup.set(key, previewImage)); + }); + + return lookup; + }, [selectedSeriesDraftSkuOptions]); + useEffect(() => { + if (!shouldLoadSeriesComponentAssets) { + setSeriesComponentAssetFamilies([]); + setSeriesComponentAssetVariants([]); + setSeriesComponentAssetsError(""); + setIsSeriesComponentAssetsLoading(false); + return; + } + + let isCancelled = false; + setIsSeriesComponentAssetsLoading(true); + setSeriesComponentAssetsError(""); + + void (async () => { + try { + const assetSeries = await listAssetSeries(); + if (isCancelled) return; + + const matchedSeries = findAssetSeriesByCode( + assetSeries, + selectedAssetSeriesCode, + ); + if (!matchedSeries) { + setSeriesComponentAssetFamilies([]); + setSeriesComponentAssetVariants([]); + setSeriesComponentAssetsError( + `资产中心未找到系列 ${selectedAssetSeriesCode}`, + ); + return; + } + + const families = await listAssetFamilies({ + assetSeriesId: matchedSeries.id, + }); + if (isCancelled) return; + + const variants = await listAssetVariantsByFamilyIds( + families.map((family) => family.id), + ); + if (isCancelled) return; + + setSeriesComponentAssetFamilies(families); + setSeriesComponentAssetVariants(variants); + } catch (error) { + if (isCancelled) return; + setSeriesComponentAssetFamilies([]); + setSeriesComponentAssetVariants([]); + setSeriesComponentAssetsError( + error instanceof Error + ? error.message + : "读取资产中心部件失败,请稍后再试", + ); + } finally { + if (!isCancelled) { + setIsSeriesComponentAssetsLoading(false); + } + } + })(); + + return () => { + isCancelled = true; + }; + }, [selectedAssetSeriesCode, shouldLoadSeriesComponentAssets]); + useEffect(() => { + if ( + mode !== "edit" || + !isSeriesDevelopment || + isSeriesComponentDetailProduct || + (selectedSeriesDraftSkuPreviewImageByKey.size === 0 && + seriesAssetVariantPreviewImageByCode.size === 0) + ) { + return; + } + + let hasChanged = false; + const nextSkuItems = skuItems.map((item) => { + if (item.image.trim()) return item; + + const componentPreviewImage = normalizeNonIntegratedSkuComponentDetails( + item.componentDetails, + ) + .map((detail) => + seriesAssetVariantPreviewImageByCode.get( + normalizeAssetVariantCodeForPreviewLookup(detail.code), + ), + ) + .find(Boolean); + if (componentPreviewImage) { + hasChanged = true; + return { + ...item, + image: componentPreviewImage.image, + imageName: componentPreviewImage.imageName, + }; + } + + const lookupKeys = [ + item.sourceSkuId?.trim() ?? "", + item.id.trim(), + item.id.startsWith("series-") ? item.id.slice("series-".length) : "", + String(item.skuSequence).padStart(2, "0"), + String(item.skuSequence), + ].filter(Boolean); + const previewImage = lookupKeys + .map((key) => selectedSeriesDraftSkuPreviewImageByKey.get(key)) + .find(Boolean); + if (!previewImage) return item; + + hasChanged = true; + return { + ...item, + image: previewImage.image, + imageName: previewImage.imageName, + }; + }); + + if (!hasChanged) return; + + setSkuItems(nextSkuItems); + }, [ + isSeriesComponentDetailProduct, + isSeriesDevelopment, + mode, + selectedSeriesDraftSkuPreviewImageByKey, + seriesAssetVariantPreviewImageByCode, + skuItems, + ]); const canUseSelectedSeriesName = !isSeriesDevelopment || (selectedSeriesNameKey.length > 0 && - !existingSeriesNameKeys.has(selectedSeriesNameKey) && + !(isSeriesComponentCreate + ? existingSeriesComponentDetailNameKeys + : existingSeriesNameKeys + ).has(selectedSeriesNameKey) && + (!isSeriesComponentCreate || seriesComponentSpu.length > 0) && availableSeriesNameOptions.some( (name) => normalizeSeriesNameKey(name) === selectedSeriesNameKey, )); @@ -12365,21 +13119,25 @@ export default function NonIntegratedDetailClient({ : spuRuleProductCategory ? "未配置SPU规则" : "选择类目后自动预估"; - const seriesCreateEstimatedSpuLabel = hasFormalSpu - ? formalSpuValue - : estimatedSpuAssignment - ? `预计SPU:${estimatedFormalSpu}` - : createProductCategory - ? "当前类目未配置SPU规则" - : "选择类目后自动预估"; + const seriesCreateEstimatedSpuLabel = isSeriesComponentCreate + ? seriesComponentSpu || "选择系列后自动生成" + : hasFormalSpu + ? formalSpuValue + : estimatedSpuAssignment + ? `预计SPU:${estimatedFormalSpu}` + : createProductCategory + ? "当前类目未配置SPU规则" + : "选择类目后自动预估"; const canConfirmCreateSpu = mode !== "create" || isStockProductCreate || - Boolean( - createSalesCategory && - createProductCategory && - estimatedSpuAssignment, - ); + (isSeriesComponentCreate + ? Boolean(selectedSourceSeriesName && seriesComponentSpu) + : Boolean( + createSalesCategory && + createProductCategory && + estimatedSpuAssignment, + )); const isSpuCategoryLocked = hasFormalSpu && !isStockProductRecord; const skuCodePreviewSpu = formalSpuValue || estimatedFormalSpu; const derivedSkuItems = useMemo( @@ -12389,6 +13147,53 @@ export default function NonIntegratedDetailClient({ ), [formValues.tagMaterial, skuCodePreviewSpu, skuItems], ); + useEffect(() => { + if ( + !isSeriesComponentDetailProduct || + isSeriesComponentAssetsLoading || + seriesComponentAssetsError || + seriesComponentAssetSkuItems.length === 0 + ) { + return; + } + + const mergedSkuItems = mergeSeriesComponentAssetSkuItems( + skuItems, + seriesComponentAssetSkuItems, + ); + const mergedSkuBatchCount = getSkuBatchCountFromSkuItems(mergedSkuItems); + const hasChanged = + mergedSkuItems.length !== skuItems.length || + getSeriesComponentAssetSkuSignature(mergedSkuItems) !== + getSeriesComponentAssetSkuSignature(skuItems); + const hasBatchCountChanged = mergedSkuBatchCount !== skuBatchCount; + + if (!hasChanged && !hasBatchCountChanged) return; + + if (hasChanged) { + setSkuItems(mergedSkuItems); + } + if (hasBatchCountChanged) { + setSkuBatchCount(mergedSkuBatchCount); + setActiveSkuBatch((current) => + current === "all" || current <= mergedSkuBatchCount + ? current + : mergedSkuBatchCount, + ); + setActiveDownstreamSkuBatch((current) => + current === "all" || current <= mergedSkuBatchCount + ? current + : mergedSkuBatchCount, + ); + } + }, [ + isSeriesComponentAssetsLoading, + isSeriesComponentDetailProduct, + seriesComponentAssetSkuItems, + seriesComponentAssetsError, + skuBatchCount, + skuItems, + ]); const getSeriesSkuComponentDetails = useCallback( (item: NonIntegratedSkuItem): NonIntegratedSkuComponentDetail[] => { const storedDetails = normalizeNonIntegratedSkuComponentDetails( @@ -15010,20 +15815,27 @@ export default function NonIntegratedDetailClient({ : activeDocumentWorkspaceCopy.emptyDescription; const canSubmitCreate = mode === "create" - ? isStockProductCreate - ? sharedProductImage.length > 0 && - normalizedStockProductSpu.length > 0 && - (!isStockSeriesProductCreate || canUseSelectedSeriesName) && - openingReference.designer.trim().length > 0 && - formValues.brand.trim().length > 0 - : sharedProductImage.length > 0 && - (isSeriesDevelopment - ? canUseSelectedSeriesName - : openingReference.productName.trim().length > 0) && - canConfirmCreateSpu && - openingReference.designer.trim().length > 0 && - openingReference.planningOwner.trim().length > 0 && - formValues.brand.trim().length > 0 + ? isSeriesComponentCreate + ? canUseSelectedSeriesName && + seriesComponentSpu.length > 0 && + formValues.brand.trim().length > 0 && + !isSeriesComponentAssetsLoading && + !seriesComponentAssetsError && + seriesComponentAssetSkuItems.length > 0 + : isStockProductCreate + ? sharedProductImage.length > 0 && + normalizedStockProductSpu.length > 0 && + (!isStockSeriesProductCreate || canUseSelectedSeriesName) && + openingReference.designer.trim().length > 0 && + formValues.brand.trim().length > 0 + : sharedProductImage.length > 0 && + (isSeriesDevelopment + ? canUseSelectedSeriesName + : openingReference.productName.trim().length > 0) && + canConfirmCreateSpu && + openingReference.designer.trim().length > 0 && + openingReference.planningOwner.trim().length > 0 && + formValues.brand.trim().length > 0 : formValues.spu.trim().length > 0 && sharedProductImage.length > 0; const uploadAssetSourceToServer = useCallback( async ( @@ -15316,10 +16128,12 @@ export default function NonIntegratedDetailClient({ successMessage, errorFallbackMessage, overrides, + suppressSuccessMessage = false, }: { successMessage: string; errorFallbackMessage: string; overrides?: PersistEditedProductOverrides; + suppressSuccessMessage?: boolean; }) => { const nextDocumentWorkspaceConfirmations = overrides?.documentWorkspaceConfirmations ?? @@ -15390,6 +16204,7 @@ export default function NonIntegratedDetailClient({ existingProduct?.createdBy, currentUserNameNormalized || currentUserIdNormalized || undefined, effectiveProductDevelopmentKind, + existingProduct?.metadata, ), ); @@ -15415,8 +16230,10 @@ export default function NonIntegratedDetailClient({ onProductSavedRef.current?.(savedProduct); clearNonIntegratedBomDraftSnapshot(productId); lastPersistErrorMessageRef.current = ""; - setSaveMessage(successMessage); - setSaveMessageType("success"); + if (!suppressSuccessMessage) { + setSaveMessage(successMessage); + setSaveMessageType("success"); + } return true; } catch (error) { const errorMessage = @@ -15437,10 +16254,12 @@ export default function NonIntegratedDetailClient({ existingProduct?.copiedFromProductId, existingProduct?.copiedFromSpu, existingProduct?.createdBy, + existingProduct?.metadata, isStockProductRecord, currentUserIdNormalized, currentUserNameNormalized, activePermissionWorkspaceCategory, + isSeriesComponentDetailProduct, isReadOnly, mode, normalizeProductAssetsForStorage, @@ -15516,6 +16335,7 @@ export default function NonIntegratedDetailClient({ successMessage: "已自动保存最新修改", errorFallbackMessage: "自动保存失败,请稍后再试", overrides: pendingOverrides, + suppressSuccessMessage: true, }).then((saved) => { if (saved && showNotice) { showAutoSaveNoticeRef.current(); @@ -15605,13 +16425,14 @@ export default function NonIntegratedDetailClient({ autoSaveTimeoutRef.current = window.setTimeout(() => { const pendingOverrides = pendingAutoSaveOverridesRef.current ?? undefined; pendingAutoSaveOverridesRef.current = null; - void persistEditedProduct({ + void persistEditedProductRef.current({ successMessage: "已自动保存最新修改", errorFallbackMessage: "自动保存失败,请稍后再试", overrides: pendingOverrides, + suppressSuccessMessage: true, }).then((saved) => { if (saved) { - showAutoSaveNotice(); + showAutoSaveNoticeRef.current(); } }); autoSaveTimeoutRef.current = null; @@ -15917,7 +16738,6 @@ export default function NonIntegratedDetailClient({ mode, openingReference, patentApplication, - persistEditedProduct, planningLayoutRows, productFactoryRows, productFinishedSampleShipmentRows, @@ -15930,7 +16750,6 @@ export default function NonIntegratedDetailClient({ projectStatus, qualityInspectionSheet, reviewRounds, - showAutoSaveNotice, skuBatchChangeTypes, skuBatchConfirmedAt, skuBatchCount, @@ -17123,6 +17942,34 @@ export default function NonIntegratedDetailClient({ function assignFormalSpuForSku() { const currentSpu = formValuesRef.current.spu.trim(); + if ( + (isSeriesComponentCreate || isSeriesComponentDetailProduct) && + seriesComponentSpu + ) { + const componentSpu = seriesComponentSpu.trim().toUpperCase(); + if (currentSpu === componentSpu) return currentSpu; + + setFormValuesAndRef((current) => ({ + ...current, + spu: componentSpu, + productCode: current.productCode || componentSpu, + salesCategory: + current.salesCategory || SERIES_COMPONENT_SECONDARY_CATEGORY, + productCategory: + current.productCategory || SERIES_COMPONENT_PRODUCT_CATEGORY, + })); + setOpeningReferenceAndRef((current) => ({ + ...current, + salesCategory: + current.salesCategory || SERIES_COMPONENT_SECONDARY_CATEGORY, + productCategory: + current.productCategory || SERIES_COMPONENT_PRODUCT_CATEGORY, + })); + setSaveMessage(`SPU已生效:${componentSpu}`); + setSaveMessageType("success"); + return componentSpu; + } + if (currentSpu) return currentSpu; const productCategory = @@ -22601,12 +23448,24 @@ export default function NonIntegratedDetailClient({ createBrand, ) : normalizedStockProductSpu; + const seriesComponentMetadata = isSeriesComponentCreate + ? { + componentDetailType: SERIES_COMPONENT_DETAIL_METADATA_TYPE, + sourceSeriesName: selectedSourceSeriesName, + sourceSeriesCode: + getAssetSeriesCodeFromSeriesName(selectedSourceSeriesName), + } + : undefined; const draftProductName = - isStockProductCreate + isSeriesComponentCreate + ? seriesComponentProductName + : isStockProductCreate ? openingReference.productName.trim() || stockSpu : openingReference.productName.trim() || "待补充开品资料"; const draftTemporaryCode = - isStockProductCreate + isSeriesComponentCreate + ? seriesComponentSpu + : isStockProductCreate ? stockSpu : openingReference.temporaryCode.trim(); const createAdaptableBrands = normalizeNonIntegratedBrandList([ @@ -22614,9 +23473,13 @@ export default function NonIntegratedDetailClient({ ...openingReference.adaptableBrands, ...formValues.adaptableBrands, ]).filter((brand) => BRAND_OPTIONS.includes(brand)); - let createFormalSpu = isStockProductCreate ? stockSpu : ""; + let createFormalSpu = isSeriesComponentCreate + ? seriesComponentSpu + : isStockProductCreate + ? stockSpu + : ""; - if (!isStockProductCreate) { + if (!isStockProductCreate && !isSeriesComponentCreate) { const productCategory = formValues.productCategory.trim() || openingReference.productCategory.trim(); @@ -22643,10 +23506,18 @@ export default function NonIntegratedDetailClient({ const nextOpeningReference = normalizeNonIntegratedOpeningReference({ ...openingReference, - productName: openingReference.productName.trim() || draftProductName, + productName: isSeriesComponentCreate + ? seriesComponentProductName + : openingReference.productName.trim() || draftProductName, temporaryCode: draftTemporaryCode, brand: createBrand, adaptableBrands: createAdaptableBrands, + productCategory: isSeriesComponentCreate + ? SERIES_COMPONENT_PRODUCT_CATEGORY + : openingReference.productCategory, + salesCategory: isSeriesComponentCreate + ? SERIES_COMPONENT_SECONDARY_CATEGORY + : openingReference.salesCategory, currentStage: isStockProductCreate ? "存量商品" : getOpeningReferenceStageFromStatus(projectStatus), @@ -22661,14 +23532,24 @@ export default function NonIntegratedDetailClient({ : formValues.processTemplate, brand: createBrand, adaptableBrands: createAdaptableBrands, + productCategory: isSeriesComponentCreate + ? SERIES_COMPONENT_PRODUCT_CATEGORY + : formValues.productCategory, + salesCategory: isSeriesComponentCreate + ? SERIES_COMPONENT_SECONDARY_CATEGORY + : formValues.salesCategory, }, nextOpeningReference, createFormalSpu, ); const createSkuItems = - isSeriesDevelopment && selectedSeriesDraftSkuOptions.length > 0 - ? buildSeriesSkuItemsFromDraftSkus(selectedSeriesDraftSkuOptions) - : skuItems; + isSeriesComponentCreate + ? seriesComponentAssetSkuItems + : isSeriesDevelopment && + !isSeriesComponentCreate && + selectedSeriesDraftSkuOptions.length > 0 + ? buildSeriesSkuItemsFromDraftSkus(selectedSeriesDraftSkuOptions) + : skuItems; const nextProductId = buildNonIntegratedProductId( nextFormValues.spu || nextOpeningReference.temporaryCode || @@ -22712,6 +23593,7 @@ export default function NonIntegratedDetailClient({ currentUserNameNormalized || currentUserIdNormalized || undefined, currentUserNameNormalized || currentUserIdNormalized || undefined, effectiveProductDevelopmentKind, + seriesComponentMetadata, ), { attachToExistingProduct: false }, ); @@ -22722,7 +23604,7 @@ export default function NonIntegratedDetailClient({ savedProduct.id, )}`; const nextProductDetailUrl = nextProductUrl; - if (!isStockProductCreate) { + if (!isStockProductCreate && !isSeriesComponentCreate) { try { await createApprovalWorkflow({ productId: savedProduct.id, @@ -28965,7 +29847,9 @@ function renderFactoryQualityWorkspace() { placeholder={ availableSeriesNameOptions.length > 0 ? "请选择系列名称" - : "暂无可选系列" + : isSeriesComponentCreate + ? "可选系列都已创建部件明细" + : "暂无可选系列" } value={openingReference.productName} readOnly={isReadOnly} @@ -29010,7 +29894,7 @@ function renderFactoryQualityWorkspace() {
- updateField("salesCategory", value) + isSeriesComponentCreate + ? undefined + : updateField("salesCategory", value) } /> - updateField("productCategory", value) + isSeriesComponentCreate + ? undefined + : updateField("productCategory", value) } /> {isSeriesDevelopment ? ( @@ -29139,7 +30037,7 @@ function renderFactoryQualityWorkspace() { /> ; spu: string; projectStatus: NonIntegratedProjectStatus; projectReview: NonIntegratedProjectReview; @@ -1054,6 +1055,22 @@ function normalizeStringRecord(value: unknown) { ); } +function normalizeMetadataRecord(value: unknown) { + if (!value || typeof value !== "object" || Array.isArray(value)) { + return undefined; + } + + const entries = Object.entries(value as Record).filter( + ([, item]) => + item === null || + typeof item === "string" || + typeof item === "number" || + typeof item === "boolean", + ); + + return entries.length > 0 ? Object.fromEntries(entries) : undefined; +} + function normalizeTupleMap( value: unknown, tupleLength: TLength, @@ -2087,6 +2104,7 @@ function toProductRecord( id: item.id, productDevelopmentKind: item.productDevelopmentKind === "series" ? "series" : "product", + metadata: normalizeMetadataRecord(item.metadata), spu: item.spu, projectStatus: normalizeNonIntegratedProjectStatus(item.projectStatus), projectReview: normalizeNonIntegratedProjectReview(item.projectReview), diff --git a/furniture-3d-system/src/app/intake/page.tsx b/furniture-3d-system/src/app/intake/page.tsx index 8f48e35e..35d988be 100644 --- a/furniture-3d-system/src/app/intake/page.tsx +++ b/furniture-3d-system/src/app/intake/page.tsx @@ -188,6 +188,18 @@ function appendInitialOpenProduct( return [product, ...products] } +function mergeInitialNonIntegratedProducts( + ...productGroups: NonIntegratedProductRecord[][] +) { + const productMap = new Map() + + productGroups.flat().forEach((product) => { + productMap.set(product.id, product) + }) + + return Array.from(productMap.values()) +} + export default async function IntakePage({ searchParams, }: { @@ -218,6 +230,7 @@ export default async function IntakePage({ materialLibraryCategories, materialLibraryDictionaries, initialNonIntegratedProductPage, + initialSeriesNonIntegratedProductPage, nodePermissionSettings, initialOpenProduct, ] = await Promise.all([ @@ -232,6 +245,11 @@ export default async function IntakePage({ pageSize: 50, productDevelopmentKind: 'product', }), + intakeNonIntegratedProductService.listPage(authUser, { + page: 1, + pageSize: 500, + productDevelopmentKind: 'series', + }), intakeNodePermissionSettingsService.getSettings(), initialOpenProductId ? intakeNonIntegratedProductService @@ -240,7 +258,10 @@ export default async function IntakePage({ : Promise.resolve(null), ]) const initialNonIntegratedProducts = appendInitialOpenProduct( - initialNonIntegratedProductPage.products, + mergeInitialNonIntegratedProducts( + initialNonIntegratedProductPage.products, + initialSeriesNonIntegratedProductPage.products, + ), initialOpenProduct, ) const initialOpenProductWorkspace = initialOpenProduct diff --git a/furniture-3d-system/src/app/intake/seriesComponentDetails.test.ts b/furniture-3d-system/src/app/intake/seriesComponentDetails.test.ts new file mode 100644 index 00000000..05bd37bc --- /dev/null +++ b/furniture-3d-system/src/app/intake/seriesComponentDetails.test.ts @@ -0,0 +1,33 @@ +import { readPreSkuSkuFields } from './seriesComponentDetails' + +describe('readPreSkuSkuFields', () => { + it('keeps whole-product centimeter size values', () => { + expect( + readPreSkuSkuFields({ + displaySummary: { + size: '140 / 60 / 75', + }, + }).size, + ).toBe('140 / 60 / 75') + }) + + it('converts labeled whole-product millimeter size values to centimeters', () => { + expect( + readPreSkuSkuFields({ + displaySummary: { + size: '长1400mm / 宽600mm / 高750mm', + }, + }).size, + ).toBe('140 / 60 / 75') + }) + + it('drops legacy board-only thickness size values', () => { + expect( + readPreSkuSkuFields({ + displaySummary: { + size: '长1400mm / 宽600mm / 厚25mm', + }, + }).size, + ).toBe('') + }) +}) diff --git a/furniture-3d-system/src/app/intake/seriesComponentDetails.ts b/furniture-3d-system/src/app/intake/seriesComponentDetails.ts index 3d8e7c5b..5f60a869 100644 --- a/furniture-3d-system/src/app/intake/seriesComponentDetails.ts +++ b/furniture-3d-system/src/app/intake/seriesComponentDetails.ts @@ -104,6 +104,37 @@ function readPreSkuFirstStringField( return ""; } +function normalizePreSkuOverallSize(value: string) { + if (!value) return ""; + if (/厚\s*\d|thickness/i.test(value)) return ""; + + const labeledMillimeterSize = { + length: value.match(/长\s*(\d+(?:\.\d+)?)\s*mm/i)?.[1], + width: value.match(/宽\s*(\d+(?:\.\d+)?)\s*mm/i)?.[1], + height: value.match(/高\s*(\d+(?:\.\d+)?)\s*mm/i)?.[1], + }; + if ( + labeledMillimeterSize.length && + labeledMillimeterSize.width && + labeledMillimeterSize.height + ) { + return [ + labeledMillimeterSize.length, + labeledMillimeterSize.width, + labeledMillimeterSize.height, + ] + .map((item) => { + const centimeters = Math.round((Number(item) / 10) * 10) / 10; + return Number.isInteger(centimeters) + ? String(centimeters) + : centimeters.toFixed(1); + }) + .join(" / "); + } + + return value; +} + export function readPreSkuSkuFields( preSku: PreSkuComponentDetailSource, ): SeriesDraftSkuFields { @@ -115,7 +146,7 @@ export function readPreSkuSkuFields( barcode: readPreSkuStringField(preSku, "barcode"), setCount: readPreSkuStringField(preSku, "setCount"), specName: readPreSkuStringField(preSku, "specName"), - size: readPreSkuStringField(preSku, "size"), + size: normalizePreSkuOverallSize(readPreSkuStringField(preSku, "size")), color: readPreSkuStringField(preSku, "color"), material: readPreSkuStringField(preSku, "material"), boardMaterialType: readPreSkuStringField(preSku, "boardMaterialType"), diff --git a/furniture-3d-system/src/lib/open-product/__tests__/asset-coding.test.ts b/furniture-3d-system/src/lib/open-product/__tests__/asset-coding.test.ts index 87c353d5..48744534 100644 --- a/furniture-3d-system/src/lib/open-product/__tests__/asset-coding.test.ts +++ b/furniture-3d-system/src/lib/open-product/__tests__/asset-coding.test.ts @@ -25,12 +25,12 @@ describe('asset-coding', () => { const familyCode = buildAssetFamilyCode('DBZ', 1) const variantCode = buildAssetVariantCode('DBZ', 1) - expect(familyCode).toBe('DBZ-SPJK001') - expect(variantCode).toBe('DBZ-SPJ00001') + expect(familyCode).toBe('DBZ-SPJK01') + expect(variantCode).toBe('DBZ-SPJ01') expect(validateAssetFamilyCode(familyCode)).toBeNull() expect(validateAssetVariantCode(variantCode)).toBeNull() - expect(validateAssetFamilyCode('BOARD-TOP')).toBe('资产族编码格式应为 系列编码-SPJK001') - expect(validateAssetVariantCode('BOARD-TOP-1200')).toBe('规格款编码格式应为 系列编码-SPJ00001') + expect(validateAssetFamilyCode('BOARD-TOP')).toBe('资产组型号格式应为 系列编码-SPJK01') + expect(validateAssetVariantCode('BOARD-TOP-1200')).toBe('规格款货号格式应为 系列编码-SPJ01') expect(normalizeSkuVersionNo(null)).toBe('V01') expect(normalizeSkuVersionNo('1')).toBe('V01') }) @@ -38,14 +38,14 @@ describe('asset-coding', () => { it('按规格款编码、供应商编码和版本号生成条码,并校验供应商编码', () => { expect(validateSupplierCode('K001')).toBeNull() expect(buildAssetVariantBarcode({ - variantCode: 'DBZ-SPJ00001', + variantCode: 'DBZ-SPJ01', supplierCode: 'K001', - })).toBe('DBZ-SPJ00001K001V01') + })).toBe('DBZ-SPJ01K001V01') expect(buildAssetVariantBarcode({ - variantCode: 'dbz-spj00001', + variantCode: 'dbz-spj01', supplierCode: 'k001', versionNo: '2', - })).toBe('DBZ-SPJ00001K001V02') + })).toBe('DBZ-SPJ01K001V02') expect(validateSupplierCode('K')).toBe('供应商代码必须为 2-12 位大写字母或数字') }) }) diff --git a/furniture-3d-system/src/lib/open-product/__tests__/asset-validation.test.ts b/furniture-3d-system/src/lib/open-product/__tests__/asset-validation.test.ts index fcd8cac8..8d099bcf 100644 --- a/furniture-3d-system/src/lib/open-product/__tests__/asset-validation.test.ts +++ b/furniture-3d-system/src/lib/open-product/__tests__/asset-validation.test.ts @@ -1,4 +1,7 @@ -import { validateAssetFamilyForReview } from '../asset-validation' +import { + validateAssetFamilyForReview, + validateAssetVariantForReview, +} from '../asset-validation' describe('validateAssetFamilyForReview', () => { it('组件和五金资产族提交审核时不再强制要求连接角色', () => { @@ -31,4 +34,46 @@ describe('validateAssetFamilyForReview', () => { }), ).toEqual(['资产族编码不能为空', '资产族名称不能为空']) }) + + it('包装规格款提交审核时不强制要求模型、挂载点、尺寸和成本', () => { + expect( + validateAssetVariantForReview({ + assetType: 'PACKAGING', + code: 'DBZ-SPJ01', + name: '纸箱 1 号', + dimensions: {}, + modelUrl: '', + mountPoints: [], + lossFactor: null, + estimatedCostPrice: null, + }), + ).toEqual([]) + }) + + it('组件和五金规格款提交审核时不强制要求预估成本价', () => { + const baseInput = { + code: 'DBZ-SPJ01', + name: '拉杆', + dimensions: { length: 830, width: 40, thickness: 30 }, + modelUrl: '/models/rod.glb', + mountPoints: [{ id: 'origin', name: 'origin', position: [0, 0, 0] }], + lossFactor: 1, + estimatedCostPrice: null, + assemblyBasis: { installPattern: 'rod' }, + } + + expect( + validateAssetVariantForReview({ + ...baseInput, + assetType: 'COMPONENT', + }), + ).toEqual([]) + + expect( + validateAssetVariantForReview({ + ...baseInput, + assetType: 'HARDWARE', + }), + ).toEqual([]) + }) }) diff --git a/furniture-3d-system/src/lib/open-product/asset-coding.ts b/furniture-3d-system/src/lib/open-product/asset-coding.ts index 47ea3f5d..876c76c6 100644 --- a/furniture-3d-system/src/lib/open-product/asset-coding.ts +++ b/furniture-3d-system/src/lib/open-product/asset-coding.ts @@ -4,8 +4,8 @@ export const ASSET_SPU_SEGMENT = 'SPJ' export const DEFAULT_SKU_VERSION_NO = 'V01' const SERIES_CODE_PATTERN = /^[A-Z][A-Z0-9]{1,15}$/ -const FAMILY_CODE_PATTERN = /^[A-Z][A-Z0-9]*-SPJK\d{3}$/ -const VARIANT_CODE_PATTERN = /^[A-Z][A-Z0-9]*-SPJ\d{5}$/ +const FAMILY_CODE_PATTERN = /^[A-Z][A-Z0-9]*-SPJK\d{2,}$/ +const VARIANT_CODE_PATTERN = /^[A-Z][A-Z0-9]*-SPJ\d{2,}$/ const SUPPLIER_CODE_PATTERN = /^[A-Z0-9]{2,12}$/ function trimUpper(value: string | null | undefined): string { @@ -44,11 +44,11 @@ export function buildSpuCode(seriesCode: string): string { } export function buildAssetFamilyCode(seriesCode: string, sequence: number): string { - return `${buildSpuCode(seriesCode)}K${String(sequence).padStart(3, '0')}` + return `${buildSpuCode(seriesCode)}K${String(sequence).padStart(2, '0')}` } export function buildAssetVariantCode(seriesCode: string, sequence: number): string { - return `${buildSpuCode(seriesCode)}${String(sequence).padStart(5, '0')}` + return `${buildSpuCode(seriesCode)}${String(sequence).padStart(2, '0')}` } export function normalizeSkuVersionNo(value: string | null | undefined): string { @@ -90,13 +90,13 @@ export function validateSeriesCode(code: string): string | null { export function validateAssetFamilyCode(code: string): string | null { return FAMILY_CODE_PATTERN.test(trimUpper(code)) ? null - : '资产族编码格式应为 系列编码-SPJK001' + : '资产组型号格式应为 系列编码-SPJK01' } export function validateAssetVariantCode(code: string): string | null { return VARIANT_CODE_PATTERN.test(trimUpper(code)) ? null - : '规格款编码格式应为 系列编码-SPJ00001' + : '规格款货号格式应为 系列编码-SPJ01' } export function validateSupplierCode(code: string): string | null { diff --git a/furniture-3d-system/src/lib/open-product/asset-validation.ts b/furniture-3d-system/src/lib/open-product/asset-validation.ts index 351ad34d..fb5922a1 100644 --- a/furniture-3d-system/src/lib/open-product/asset-validation.ts +++ b/furniture-3d-system/src/lib/open-product/asset-validation.ts @@ -59,6 +59,7 @@ export function validateAssetFamilyForReview(input: AssetFamilyValidationInput): export function validateAssetVariantForReview(input: AssetVariantValidationInput): string[] { const errors: string[] = [] + const requiresAssemblyModel = input.assetType !== 'PACKAGING' if (!input.code.trim()) { errors.push('规格款编码不能为空') @@ -66,22 +67,18 @@ export function validateAssetVariantForReview(input: AssetVariantValidationInput if (!input.name.trim()) { errors.push('规格款名称不能为空') } - if (!hasDimensions(input.dimensions)) { + if (requiresAssemblyModel && !hasDimensions(input.dimensions)) { errors.push('规格款缺少尺寸') } - if (!input.modelUrl?.trim()) { + if (requiresAssemblyModel && !input.modelUrl?.trim()) { errors.push('规格款缺少 3D 模型') } - if (!hasMountPoints(input.mountPoints)) { + if (requiresAssemblyModel && !hasMountPoints(input.mountPoints)) { errors.push('规格款缺少挂载点') } - if (input.lossFactor === null || input.lossFactor === undefined) { + if (requiresAssemblyModel && (input.lossFactor === null || input.lossFactor === undefined)) { errors.push('规格款缺少损耗系数') } - if (input.estimatedCostPrice === null || input.estimatedCostPrice === undefined) { - errors.push('规格款缺少预估成本价') - } - if (input.assetType === 'BOARD') { if (!input.substrateId) { errors.push('板材规格款缺少基材') diff --git a/furniture-3d-system/src/lib/open-product/platform-api.ts b/furniture-3d-system/src/lib/open-product/platform-api.ts index 19bae056..5722aa4b 100644 --- a/furniture-3d-system/src/lib/open-product/platform-api.ts +++ b/furniture-3d-system/src/lib/open-product/platform-api.ts @@ -4,6 +4,7 @@ import type { AssetFamilyDTO, AssetCadImportResult, AssetSeriesDTO, + AssetSeriesComponentDetailSummaryDTO, AssetVariantDTO, AssetVariantBindingDTO, PreSkuBindingDTO, @@ -27,6 +28,7 @@ import type { DraftGroupDTO, FormalizeDraftGroupInput, FormalizeDraftGroupResult, + GetPreSkuPackagingMaterialOptionsDTO, PreSkuBasicInfoMetadataDTO, PreviewPreSkuPackagingPlanDTO, PreSkuPackagingPlanDTO, @@ -103,6 +105,18 @@ export async function updateAssetSeries( return data.series } +export async function ensureAssetSeriesComponentDetail( + assetSeriesId: string, +): Promise { + const data = await requestPlatform<{ + componentDetail: AssetSeriesComponentDetailSummaryDTO + }>(`/api/asset-center/series/${encodeURIComponent(assetSeriesId)}/component-detail`, { + method: 'POST', + body: JSON.stringify({}), + }) + return data.componentDetail +} + export async function listAssetFamilies(input?: { assetSeriesId?: string | null type?: 'BOARD' | 'COMPONENT' | 'HARDWARE' | 'PACKAGING' | null @@ -297,6 +311,15 @@ export async function createAssetVariantWithSimilarity( }) } +export async function createPackagingAssetVariant( + input: CreateAssetVariantInput, +): Promise { + return requestPlatform('/api/asset-center/packaging-variants', { + method: 'POST', + body: JSON.stringify(input), + }) +} + export async function getAssetOperationProgress( operationId: string, ): Promise { @@ -593,6 +616,15 @@ export async function savePreSkuPackagingPlan( return data.packagingPlan } +export async function getPreSkuPackagingMaterialOptions( + preSkuId: string, +): Promise { + const data = await requestPlatform<{ result: GetPreSkuPackagingMaterialOptionsDTO }>( + `/api/pre-skus/${preSkuId}/packaging/material-options`, + ) + return data.result +} + export async function previewPreSkuPackagingPlan( preSkuId: string, input: SavePreSkuPackagingPlanInput, diff --git a/furniture-3d-system/src/server/repositories/asset-center.repository.ts b/furniture-3d-system/src/server/repositories/asset-center.repository.ts index 7596836c..f3e0d20a 100644 --- a/furniture-3d-system/src/server/repositories/asset-center.repository.ts +++ b/furniture-3d-system/src/server/repositories/asset-center.repository.ts @@ -255,7 +255,7 @@ class AssetFamilyRepositoryClass extends BaseRepository< ): Promise<{ items: AssetFamilyWithRelations[]; total: number }> { const { filter, pagination, sort } = options const where = this.buildWhereClause(filter) - const orderBy = sort ? { [sort.field]: sort.order } : { updatedAt: 'desc' as const } + const orderBy = sort ? { [sort.field]: sort.order } : [{ createdAt: 'desc' as const }, { code: 'desc' as const }] const skip = pagination ? (pagination.page - 1) * pagination.limit : 0 const take = pagination?.limit @@ -517,7 +517,7 @@ class AssetVariantRepositoryClass extends BaseRepository< deletedAt: null, assetFamily: { is: { deletedAt: null } }, }, - orderBy: [{ assetFamilyId: 'asc' }, { updatedAt: 'desc' }], + orderBy: [{ assetFamilyId: 'asc' }, { createdAt: 'desc' }, { code: 'desc' }], include: assetVariantRelationInclude, }) as Promise } @@ -529,7 +529,7 @@ class AssetVariantRepositoryClass extends BaseRepository< where: { id: { in: ids }, }, - orderBy: [{ assetFamilyId: 'asc' }, { updatedAt: 'desc' }], + orderBy: [{ assetFamilyId: 'asc' }, { createdAt: 'desc' }, { code: 'desc' }], include: assetVariantRelationInclude, }) as Promise } @@ -547,7 +547,7 @@ class AssetVariantRepositoryClass extends BaseRepository< deletedAt: null, assetFamily: { is: { deletedAt: null } }, }, - orderBy: [{ assetFamilyId: 'asc' }, { updatedAt: 'desc' }], + orderBy: [{ assetFamilyId: 'asc' }, { createdAt: 'desc' }, { code: 'desc' }], include: assetVariantRelationInclude, }) as Promise } @@ -562,7 +562,29 @@ class AssetVariantRepositoryClass extends BaseRepository< deletedAt: null, assetFamily: { is: { deletedAt: null } }, }, - orderBy: [{ assetFamilyId: 'asc' }, { updatedAt: 'desc' }], + orderBy: [{ assetFamilyId: 'asc' }, { createdAt: 'desc' }, { code: 'desc' }], + include: assetVariantRelationInclude, + }) as Promise + } + + async findActiveBySeriesCode(seriesCode: string): Promise { + const normalizedSeriesCode = seriesCode.trim().toUpperCase() + if (!normalizedSeriesCode) return [] + + return this.prisma.assetVariant.findMany({ + where: { + code: { startsWith: `${normalizedSeriesCode}-SPJ` }, + deletedAt: null, + assetFamily: { + is: { + deletedAt: null, + assetSeries: { + is: { code: normalizedSeriesCode }, + }, + }, + }, + }, + orderBy: [{ code: 'asc' }, { updatedAt: 'asc' }], include: assetVariantRelationInclude, }) as Promise } diff --git a/furniture-3d-system/src/server/services/__tests__/asset-center.service.test.ts b/furniture-3d-system/src/server/services/__tests__/asset-center.service.test.ts index 1ece1e85..bb4bcd41 100644 --- a/furniture-3d-system/src/server/services/__tests__/asset-center.service.test.ts +++ b/furniture-3d-system/src/server/services/__tests__/asset-center.service.test.ts @@ -10,6 +10,7 @@ import { assetFamilyRepository, assetSeriesRepository, assetVariantRepository, + intakeNonIntegratedProductRepository, materialCategoryRepository, materialRepository, substrateRepository, @@ -39,8 +40,13 @@ jest.mock('../../repositories', () => ({ update: jest.fn(), updateWithRelations: jest.fn(), findManyByFamilyIds: jest.fn(), + findActiveBySeriesCode: jest.fn(), releaseDeletedUniqueKeys: jest.fn(), }, + intakeNonIntegratedProductRepository: { + listActive: jest.fn(), + updatePayloadByUser: jest.fn(), + }, substrateRepository: { findById: jest.fn(), findByCode: jest.fn(), @@ -82,6 +88,7 @@ describe('assetCenterService', () => { const mockedAssetFamilyRepository = jest.mocked(assetFamilyRepository) const mockedAssetSeriesRepository = jest.mocked(assetSeriesRepository) const mockedAssetVariantRepository = jest.mocked(assetVariantRepository) + const mockedIntakeNonIntegratedProductRepository = jest.mocked(intakeNonIntegratedProductRepository) const mockedSubstrateRepository = jest.mocked(substrateRepository) const mockedMaterialRepository = jest.mocked(materialRepository) const mockedMaterialCategoryRepository = jest.mocked(materialCategoryRepository) @@ -149,12 +156,17 @@ describe('assetCenterService', () => { mockedAssetSeriesRepository.updateSeries.mockResolvedValue(defaultAssetSeries as never) mockedAssetVariantRepository.findByCode.mockResolvedValue(null) + mockedAssetVariantRepository.findByBarcode.mockResolvedValue(null) mockedAssetVariantRepository.findByIdentityKey.mockResolvedValue(null) mockedAssetVariantRepository.findById.mockResolvedValue(null) mockedAssetVariantRepository.findByIdWithRelations.mockResolvedValue(null) mockedAssetVariantRepository.update.mockResolvedValue({} as never) mockedAssetVariantRepository.updateWithRelations.mockResolvedValue({} as never) + mockedAssetVariantRepository.findManyByFamilyIds.mockResolvedValue([] as never) + mockedAssetVariantRepository.findActiveBySeriesCode.mockResolvedValue([] as never) mockedAssetVariantRepository.releaseDeletedUniqueKeys.mockResolvedValue(undefined as never) + mockedIntakeNonIntegratedProductRepository.listActive.mockResolvedValue([] as never) + mockedIntakeNonIntegratedProductRepository.updatePayloadByUser.mockResolvedValue({} as never) mockedSubstrateRepository.findById.mockResolvedValue({ id: 'substrate-particle-board', code: 'PB18', @@ -341,6 +353,104 @@ describe('assetCenterService', () => { expect(result.lossFactor).toBe(1) }) + it('duplicates a component variant with empty input dimensions by inheriting source dimensions', async () => { + const componentFamily = { + ...defaultBoardFamily, + id: 'family-component-leg', + code: 'DBZ-SPJK03', + name: 'leg component family', + type: 'COMPONENT', + } + const inheritedVariant = { + id: 'variant-component-source', + assetFamilyId: componentFamily.id, + code: 'DBZ-SPJ06', + name: 'source component', + identityKey: 'COMPONENT|code=DBZ-SPJ06', + assetType: 'COMPONENT', + status: 'AVAILABLE', + sizeLabel: '60x590x700', + substrateId: null, + finishId: null, + dimensions: { length: 60, width: 590 }, + modelUrl: '/models/component-source.glb', + thumbnailUrl: null, + barcode: null, + supplierName: null, + supplierCode: null, + versionNo: 'V01', + mountPoints: [{ name: 'origin', position: [0, 0, 0] }], + assemblyBasis: { source: 'cad' }, + compatibilityRules: null, + namingFields: null, + businessData: null, + weightKg: null, + costPrice: null, + lossFactor: 1, + estimatedCostPrice: null, + inheritedFromVariantId: null, + createdBy: 'user-1', + submittedAt: null, + submittedById: null, + reviewedAt: null, + reviewedById: null, + rejectedAt: null, + rejectedById: null, + rejectionReason: null, + lastModifiedById: null, + deletedAt: null, + deletedById: null, + createdAt: new Date('2026-04-01T10:00:00.000Z'), + updatedAt: new Date('2026-04-01T10:00:00.000Z'), + assetFamily: componentFamily, + substrate: null, + finish: null, + creator: null, + submitter: null, + reviewer: null, + rejecter: null, + lastModifier: null, + } + + mockedAssetFamilyRepository.findWithRelationsById.mockResolvedValue(componentFamily as never) + mockedAssetVariantRepository.findByIdWithRelations.mockResolvedValue(inheritedVariant as never) + mockedAssetVariantRepository.createWithRelations.mockResolvedValue({ + ...inheritedVariant, + id: 'variant-component-duplicate', + code: 'DBZ-SPJ07', + name: 'duplicate component', + identityKey: 'COMPONENT|code=DBZ-SPJ07', + status: 'DRAFT', + inheritedFromVariantId: inheritedVariant.id, + } as never) + + await assetCenterService.createVariant({ + assetFamilyId: componentFamily.id, + code: 'DBZ-SPJ07', + name: 'duplicate component', + status: 'DRAFT', + dimensions: {}, + businessData: { + skuContentFields: { + size: '60x590x700', + }, + }, + substrateId: null, + finishId: null, + modelUrl: '/models/component-source.glb', + mountPoints: [{ name: 'origin', position: [0, 0, 0] }], + inheritedFromVariantId: inheritedVariant.id, + lossFactor: 1, + }) + + expect(mockedAssetVariantRepository.createWithRelations).toHaveBeenCalledWith( + expect.objectContaining({ + dimensions: { length: 60, width: 590, height: 700 }, + inheritedFromVariant: { connect: { id: inheritedVariant.id } }, + }), + ) + }) + it('以规格款为模板新建时会继承 CAD 孔位和装配语义,但材质仍按新规格款保存', async () => { mockedAssetVariantRepository.findByIdWithRelations.mockResolvedValue({ id: 'variant-board-top-template', @@ -1895,7 +2005,7 @@ describe('assetCenterService', () => { }) it('软删除规格款时会释放编码和身份键,避免回收站继续占用新建编码', async () => { - mockedAssetVariantRepository.findById.mockResolvedValue({ + mockedAssetVariantRepository.findByIdWithRelations.mockResolvedValue({ id: 'variant-board-delete', assetFamilyId: 'family-board-top', code: 'DBZ-SPJ00017', @@ -1933,6 +2043,22 @@ describe('assetCenterService', () => { deletedById: null, createdAt: new Date('2026-04-01T10:00:00.000Z'), updatedAt: new Date('2026-04-01T10:00:00.000Z'), + assetFamily: { + id: 'family-board-top', + code: 'DBZ-SPJK001', + name: '妗岄潰鏉胯祫浜ф棌', + type: 'BOARD', + assetSeriesId: defaultAssetSeries.id, + deletedAt: null, + assetSeries: defaultAssetSeries, + }, + substrate: null, + finish: null, + creator: null, + submitter: null, + reviewer: null, + rejecter: null, + lastModifier: null, } as never) await assetCenterService.deleteVariant('variant-board-delete', 'user-2') @@ -2360,4 +2486,754 @@ describe('assetCenterService', () => { }), ]) }) + + it('deletes the component-detail SKU row and shifts later asset variant codes down', async () => { + const buildComponentVariant = (overrides: Record) => ({ + id: 'variant-03', + assetFamilyId: 'family-component', + code: 'DBZ-SPJ03', + name: 'component 03', + identityKey: 'COMPONENT|code=DBZ-SPJ03', + assetType: 'COMPONENT', + status: 'DRAFT', + sizeLabel: null, + substrateId: null, + finishId: null, + dimensions: {}, + modelUrl: '/models/component-03.glb', + thumbnailUrl: '/thumbs/component-03.png', + barcode: 'DBZ-SPJ03K001V01', + supplierName: 'supplier', + supplierCode: 'K001', + versionNo: 'V01', + mountPoints: [], + assemblyBasis: null, + compatibilityRules: null, + namingFields: null, + businessData: null, + weightKg: null, + costPrice: null, + lossFactor: null, + estimatedCostPrice: null, + inheritedFromVariantId: null, + createdBy: 'user-1', + submittedAt: null, + submittedById: null, + reviewedAt: null, + reviewedById: null, + rejectedAt: null, + rejectedById: null, + rejectionReason: null, + lastModifiedById: null, + deletedAt: null, + deletedById: null, + createdAt: new Date('2026-04-01T10:00:00.000Z'), + updatedAt: new Date('2026-04-01T10:00:00.000Z'), + assetFamily: { + id: 'family-component', + code: 'DBZ-SPJK01', + name: 'component family', + type: 'COMPONENT', + assetSeriesId: defaultAssetSeries.id, + deletedAt: null, + assetSeries: defaultAssetSeries, + }, + substrate: null, + finish: null, + creator: null, + submitter: null, + reviewer: null, + rejecter: null, + lastModifier: null, + ...overrides, + }) + + mockedAssetVariantRepository.findByIdWithRelations.mockResolvedValue( + buildComponentVariant({ + id: 'variant-02', + code: 'DBZ-SPJ02', + name: 'component 02', + identityKey: 'COMPONENT|code=DBZ-SPJ02', + barcode: 'DBZ-SPJ02K001V01', + }) as never, + ) + mockedAssetVariantRepository.findActiveBySeriesCode.mockResolvedValue([ + buildComponentVariant({ + id: 'variant-03', + code: 'DBZ-SPJ03', + identityKey: 'COMPONENT|code=DBZ-SPJ03', + }), + ] as never) + mockedAssetVariantRepository.updateWithRelations.mockResolvedValue( + buildComponentVariant({ + id: 'variant-03', + code: 'DBZ-SPJ02', + identityKey: 'COMPONENT|code=DBZ-SPJ02', + barcode: 'DBZ-SPJ02K001V01', + }) as never, + ) + mockedIntakeNonIntegratedProductRepository.listActive.mockResolvedValue([ + { + id: 'component-detail-product', + updatedBy: 'user-1', + payload: { + id: 'component-detail-product', + productDevelopmentKind: 'series', + metadata: { componentDetailType: 'asset-series-components' }, + skuItems: [ + { + source: 'asset_series_component', + sourceTable: 'asset_variant', + sourceSkuId: 'variant-02', + skuCode: 'DBZ-SPJ02', + skuSequence: 1, + }, + { + source: 'asset_series_component', + sourceTable: 'asset_variant', + sourceSkuId: 'variant-03', + skuCode: 'DBZ-SPJ03', + skuSequence: 2, + specName: 'manual spec', + }, + ], + }, + }, + ] as never) + + await assetCenterService.deleteVariant('variant-02', 'user-2') + + expect(mockedAssetVariantRepository.updateWithRelations).toHaveBeenCalledWith( + 'variant-03', + expect.objectContaining({ + code: 'DBZ-SPJ02', + identityKey: 'COMPONENT|code=DBZ-SPJ02', + barcode: 'DBZ-SPJ02K001V01', + }), + ) + expect(mockedIntakeNonIntegratedProductRepository.updatePayloadByUser).toHaveBeenCalled() + const syncedPayload = + mockedIntakeNonIntegratedProductRepository.updatePayloadByUser.mock.calls[0]?.[1] as { + skuItems: Array> + } + expect(syncedPayload.skuItems).toHaveLength(1) + expect(syncedPayload.skuItems[0]).toEqual( + expect.objectContaining({ + sourceSkuId: 'variant-03', + skuCode: 'DBZ-SPJ02', + model: 'DBZ-SPJK01', + skuSequence: 1, + specName: 'manual spec', + }), + ) + }) + + it('appends newly created packaging asset variant SKU content to component detail products', async () => { + const businessData = { + skuContentFields: { + model: 'DBZ-SPJK06', + skuCode: 'DBZ-SPJ04', + barcode: 'DBZ-SPJ04N1280V01', + setCount: '1', + specName: 'carton 120/120/6', + size: '120/120/6', + color: 'carton', + material: 'corrugated', + versionNo: 'V01', + drawingId: 'DBZ-SPJK06V01', + manufacturer: 'supplier', + manufacturerCode: 'N1280', + batchNo: 'batch1', + }, + } + const packagingFamily = { + ...defaultBoardFamily, + id: 'family-packaging', + type: 'PACKAGING', + code: 'DBZ-SPJK06', + name: 'packaging family', + } + const createdPackagingVariant = { + id: 'variant-packaging-04', + assetFamilyId: 'family-packaging', + code: 'DBZ-SPJ04', + name: 'carton 120/120/6', + identityKey: 'PACKAGING|code=DBZ-SPJ04', + assetType: 'PACKAGING', + status: 'DRAFT', + sizeLabel: '120/120/6', + substrateId: null, + finishId: null, + dimensions: { length: 1200, width: 1200, thickness: 60 }, + modelUrl: '', + thumbnailUrl: null, + barcode: 'DBZ-SPJ04N1280V01', + supplierName: 'supplier', + supplierCode: 'N1280', + versionNo: 'V01', + mountPoints: [], + assemblyBasis: null, + compatibilityRules: null, + namingFields: null, + businessData, + weightKg: null, + costPrice: null, + lossFactor: null, + estimatedCostPrice: null, + inheritedFromVariantId: null, + createdBy: 'user-2', + submittedAt: null, + submittedById: null, + reviewedAt: null, + reviewedById: null, + rejectedAt: null, + rejectedById: null, + rejectionReason: null, + lastModifiedById: null, + deletedAt: null, + deletedById: null, + createdAt: new Date('2026-04-02T10:00:00.000Z'), + updatedAt: new Date('2026-04-02T10:00:00.000Z'), + assetFamily: packagingFamily, + substrate: null, + finish: null, + creator: null, + submitter: null, + reviewer: null, + rejecter: null, + lastModifier: null, + } + + mockedAssetFamilyRepository.findWithRelationsById.mockResolvedValue(packagingFamily as never) + mockedAssetVariantRepository.createWithRelations.mockResolvedValue(createdPackagingVariant as never) + mockedIntakeNonIntegratedProductRepository.listActive.mockResolvedValue([ + { + id: 'component-detail-product', + spu: 'DBZ-SPJ', + updatedBy: 'user-1', + payload: { + id: 'component-detail-product', + productDevelopmentKind: 'series', + metadata: { + componentDetailType: 'asset-series-components', + sourceSeriesCode: 'DBZ', + }, + spu: 'DBZ-SPJ', + skuItems: [ + { + source: 'asset_series_component', + sourceTable: 'asset_variant', + sourceSkuId: 'variant-existing', + skuCode: 'DBZ-SPJ03', + skuSequence: 1, + batchNo: 1, + }, + ], + }, + }, + ] as never) + + await assetCenterService.createVariantWithSimilarity( + { + assetFamilyId: 'family-packaging', + code: 'DBZ-SPJ04', + name: 'carton 120/120/6', + status: 'DRAFT', + sizeLabel: '120/120/6', + substrateId: null, + finishId: null, + dimensions: { length: 1200, width: 1200, thickness: 60 }, + modelUrl: '', + supplierName: 'supplier', + supplierCode: 'N1280', + versionNo: 'V01', + barcode: 'DBZ-SPJ04N1280V01', + mountPoints: [], + businessData, + lossFactor: null, + createdBy: 'user-2', + }, + { skipThumbnail: true }, + ) + + expect(mockedIntakeNonIntegratedProductRepository.updatePayloadByUser).toHaveBeenCalled() + const syncedPayload = + mockedIntakeNonIntegratedProductRepository.updatePayloadByUser.mock.calls[0]?.[1] as { + skuItems: Array> + skuBatchCount: number + } + expect(syncedPayload.skuBatchCount).toBe(1) + expect(syncedPayload.skuItems).toHaveLength(2) + expect(syncedPayload.skuItems[1]).toEqual( + expect.objectContaining({ + sourceSkuId: 'variant-packaging-04', + model: 'DBZ-SPJK06', + skuCode: 'DBZ-SPJ04', + barcode: 'DBZ-SPJ04N1280V01', + specName: 'carton 120/120/6', + size: '120/120/6', + color: 'carton', + material: 'corrugated', + boardMaterialType: '非ENF级', + attributeCode: 'A', + installMethod: '拆装', + executeStandard: 'GB/T3324-2024', + nationalStandardCompliant: '是', + salesStatus: '销售', + drawingId: 'DBZ-SPJK06V01', + manufacturer: 'supplier', + manufacturerCode: 'N1280', + skuSequence: 2, + batchNo: 1, + }), + ) + }) + + it('backfills missing packaging asset variants when ensuring an existing component detail product', async () => { + const businessData = { + skuContentFields: { + model: 'DBZ-SPJK06', + skuCode: 'DBZ-SPJ04', + barcode: 'DBZ-SPJ04N1280V01', + specName: 'carton 120/120/6', + size: '120/120/6', + color: 'carton', + material: 'corrugated', + versionNo: 'V01', + drawingId: 'DBZ-SPJK06V01', + manufacturer: 'supplier', + manufacturerCode: 'N1280', + batchNo: 'batch1', + }, + } + const packagingVariant = { + id: 'variant-packaging-04', + assetFamilyId: 'family-packaging', + code: 'DBZ-SPJ04', + name: 'carton 120/120/6', + identityKey: 'PACKAGING|code=DBZ-SPJ04', + assetType: 'PACKAGING', + status: 'DRAFT', + sizeLabel: '120/120/6', + substrateId: null, + finishId: null, + dimensions: { length: 1200, width: 1200, thickness: 60 }, + modelUrl: '', + thumbnailUrl: null, + barcode: 'DBZ-SPJ04N1280V01', + supplierName: 'supplier', + supplierCode: 'N1280', + versionNo: 'V01', + mountPoints: [], + assemblyBasis: null, + compatibilityRules: null, + namingFields: null, + businessData, + weightKg: null, + costPrice: null, + lossFactor: null, + estimatedCostPrice: null, + inheritedFromVariantId: null, + createdBy: 'user-2', + submittedAt: null, + submittedById: null, + reviewedAt: null, + reviewedById: null, + rejectedAt: null, + rejectedById: null, + rejectionReason: null, + lastModifiedById: null, + deletedAt: null, + deletedById: null, + createdAt: new Date('2026-04-02T10:00:00.000Z'), + updatedAt: new Date('2026-04-02T10:00:00.000Z'), + assetFamily: { + ...defaultBoardFamily, + id: 'family-packaging', + type: 'PACKAGING', + code: 'DBZ-SPJK06', + name: 'packaging family', + }, + substrate: null, + finish: null, + creator: null, + submitter: null, + reviewer: null, + rejecter: null, + lastModifier: null, + } + + mockedAssetVariantRepository.findActiveBySeriesCode.mockResolvedValue([ + packagingVariant, + ] as never) + mockedIntakeNonIntegratedProductRepository.listActive.mockResolvedValue([ + { + id: 'component-detail-product', + spu: 'DBZ-SPJ', + updatedBy: 'user-1', + payload: { + id: 'component-detail-product', + productDevelopmentKind: 'series', + metadata: { + componentDetailType: 'asset-series-components', + sourceSeriesCode: 'DBZ', + }, + spu: 'DBZ-SPJ', + skuItems: [], + }, + }, + ] as never) + + await assetCenterService.ensureSeriesComponentDetailProduct( + defaultAssetSeries.id, + { id: 'user-2' } as never, + ) + + expect(mockedIntakeNonIntegratedProductRepository.updatePayloadByUser).toHaveBeenCalled() + const syncedPayload = + mockedIntakeNonIntegratedProductRepository.updatePayloadByUser.mock.calls[0]?.[1] as { + skuItems: Array> + } + expect(syncedPayload.skuItems).toHaveLength(1) + expect(syncedPayload.skuItems[0]).toEqual( + expect.objectContaining({ + sourceSkuId: 'variant-packaging-04', + model: 'DBZ-SPJK06', + skuCode: 'DBZ-SPJ04', + barcode: 'DBZ-SPJ04N1280V01', + specName: 'carton 120/120/6', + }), + ) + }) + + it('syncs updated asset variant SKU content back to component detail products', async () => { + const buildComponentVariant = (overrides: Record) => ({ + id: 'variant-01', + assetFamilyId: 'family-component', + code: 'DBZ-SPJ01', + name: 'component 01', + identityKey: 'COMPONENT|code=DBZ-SPJ01', + assetType: 'COMPONENT', + status: 'DRAFT', + sizeLabel: null, + substrateId: null, + finishId: null, + dimensions: {}, + modelUrl: '/models/component-01.glb', + thumbnailUrl: '/thumbs/component-01.png', + barcode: null, + supplierName: null, + supplierCode: null, + versionNo: 'V01', + mountPoints: [], + assemblyBasis: null, + compatibilityRules: null, + namingFields: null, + businessData: null, + weightKg: null, + costPrice: null, + lossFactor: null, + estimatedCostPrice: null, + inheritedFromVariantId: null, + createdBy: 'user-1', + submittedAt: null, + submittedById: null, + reviewedAt: null, + reviewedById: null, + rejectedAt: null, + rejectedById: null, + rejectionReason: null, + lastModifiedById: null, + deletedAt: null, + deletedById: null, + createdAt: new Date('2026-04-01T10:00:00.000Z'), + updatedAt: new Date('2026-04-01T10:00:00.000Z'), + assetFamily: { + id: 'family-component', + code: 'DBZ-SPJK01', + name: 'component family', + type: 'COMPONENT', + assetSeriesId: defaultAssetSeries.id, + deletedAt: null, + assetSeries: defaultAssetSeries, + }, + substrate: null, + finish: null, + creator: null, + submitter: null, + reviewer: null, + rejecter: null, + lastModifier: null, + ...overrides, + }) + const businessData = { + skuContentFields: { + model: 'DBZ-SPJK01', + skuCode: 'DBZ-SPJ01', + barcode: 'DBZ-SPJ01N1280V01', + setCount: '1', + specName: '款式一 100/60/2.5 胡桃色', + size: '100/60/2.5', + color: '胡桃色', + material: '25ENF级橡胶木', + versionNo: 'V01', + drawingId: 'DBZ-SPJK01V01', + manufacturer: '兰考华兰家具', + manufacturerCode: 'N1280', + batchNo: '批次1', + }, + } + + mockedAssetVariantRepository.findByIdWithRelations.mockResolvedValue( + buildComponentVariant({}) as never, + ) + mockedAssetVariantRepository.updateWithRelations.mockResolvedValue( + buildComponentVariant({ + name: '款式一 100/60/2.5 胡桃色', + sizeLabel: '100/60/2.5', + barcode: 'DBZ-SPJ01N1280V01', + supplierName: '兰考华兰家具', + supplierCode: 'N1280', + businessData, + }) as never, + ) + mockedIntakeNonIntegratedProductRepository.listActive.mockResolvedValue([ + { + id: 'component-detail-product', + updatedBy: 'user-1', + payload: { + id: 'component-detail-product', + productDevelopmentKind: 'series', + metadata: { componentDetailType: 'asset-series-components' }, + skuItems: [ + { + source: 'asset_series_component', + sourceTable: 'asset_variant', + sourceSkuId: 'variant-01', + skuCode: 'DBZ-SPJ01', + skuSequence: 1, + specName: 'old spec', + }, + ], + }, + }, + ] as never) + + await assetCenterService.updateVariant( + 'variant-01', + { + name: '款式一 100/60/2.5 胡桃色', + sizeLabel: '100/60/2.5', + supplierName: '兰考华兰家具', + supplierCode: 'N1280', + versionNo: 'V01', + barcode: 'DBZ-SPJ01N1280V01', + businessData, + updatedBy: 'user-2', + }, + { skipThumbnail: true }, + ) + + expect(mockedIntakeNonIntegratedProductRepository.updatePayloadByUser).toHaveBeenCalled() + const syncedPayload = + mockedIntakeNonIntegratedProductRepository.updatePayloadByUser.mock.calls[0]?.[1] as { + skuItems: Array> + skuBatchCount: number + } + expect(syncedPayload.skuBatchCount).toBe(1) + expect(syncedPayload.skuItems[0]).toEqual( + expect.objectContaining({ + sourceSkuId: 'variant-01', + model: 'DBZ-SPJK01', + skuCode: 'DBZ-SPJ01', + barcode: 'DBZ-SPJ01N1280V01', + specName: '款式一 100/60/2.5 胡桃色', + size: '100/60/2.5', + color: '胡桃色', + material: '25ENF级橡胶木', + drawingId: 'DBZ-SPJK01V01', + manufacturer: '兰考华兰家具', + manufacturerCode: 'N1280', + batchNo: 1, + }), + ) + }) + + it('syncs shared SKU fields to sibling variants in the same asset family', async () => { + const buildComponentVariant = (overrides: Record) => ({ + id: 'variant-01', + assetFamilyId: 'family-component', + code: 'DBZ-SPJ01', + name: 'component 01', + identityKey: 'COMPONENT|code=DBZ-SPJ01', + assetType: 'COMPONENT', + status: 'DRAFT', + sizeLabel: null, + substrateId: null, + finishId: null, + dimensions: {}, + modelUrl: '/models/component-01.glb', + thumbnailUrl: '/thumbs/component-01.png', + barcode: 'DBZ-SPJ01N1280V01', + supplierName: 'supplier', + supplierCode: 'N1280', + versionNo: 'V01', + mountPoints: [], + assemblyBasis: null, + compatibilityRules: null, + namingFields: null, + businessData: null, + weightKg: null, + costPrice: null, + lossFactor: null, + estimatedCostPrice: null, + inheritedFromVariantId: null, + createdBy: 'user-1', + submittedAt: null, + submittedById: null, + reviewedAt: null, + reviewedById: null, + rejectedAt: null, + rejectedById: null, + rejectionReason: null, + lastModifiedById: null, + deletedAt: null, + deletedById: null, + createdAt: new Date('2026-04-01T10:00:00.000Z'), + updatedAt: new Date('2026-04-01T10:00:00.000Z'), + assetFamily: { + id: 'family-component', + code: 'DBZ-SPJK01', + name: 'component family', + type: 'COMPONENT', + assetSeriesId: defaultAssetSeries.id, + deletedAt: null, + assetSeries: defaultAssetSeries, + }, + substrate: null, + finish: null, + creator: null, + submitter: null, + reviewer: null, + rejecter: null, + lastModifier: null, + ...overrides, + }) + const sourceBusinessData = { + skuContentFields: { + model: 'DBZ-SPJK01', + skuCode: 'DBZ-SPJ01', + barcode: 'DBZ-SPJ01N1280V01', + specName: 'style one', + size: '100/60/2.5', + color: 'walnut', + material: 'rubber wood', + versionNo: '', + attributeCode: 'B', + installMethod: '整装', + executeStandard: 'GB/T3325-2024', + nationalStandardCompliant: '', + salesStatus: '', + boardMaterialType: '非ENF级', + }, + } + const siblingBusinessData = { + skuContentFields: { + model: 'DBZ-SPJK01', + skuCode: 'DBZ-SPJ02', + barcode: 'DBZ-SPJ02N1280V01', + specName: 'style two', + size: '120/60/2.5', + color: 'black', + material: 'steel', + versionNo: 'V01', + attributeCode: 'A', + installMethod: '拆装', + executeStandard: 'GB/T3324-2024', + nationalStandardCompliant: '是', + salesStatus: '销售', + boardMaterialType: 'ENF级', + }, + } + const existingVariant = buildComponentVariant({ + businessData: { skuContentFields: { versionNo: 'V01' } }, + }) + const updatedSourceVariant = buildComponentVariant({ + businessData: sourceBusinessData, + }) + const siblingVariant = buildComponentVariant({ + id: 'variant-02', + code: 'DBZ-SPJ02', + name: 'component 02', + identityKey: 'COMPONENT|code=DBZ-SPJ02', + barcode: 'DBZ-SPJ02N1280V01', + businessData: siblingBusinessData, + }) + + mockedAssetVariantRepository.findByIdWithRelations.mockResolvedValue( + existingVariant as never, + ) + mockedAssetVariantRepository.updateWithRelations + .mockResolvedValueOnce(updatedSourceVariant as never) + .mockResolvedValueOnce( + buildComponentVariant({ + ...siblingVariant, + businessData: { + skuContentFields: { + ...siblingBusinessData.skuContentFields, + versionNo: '', + attributeCode: 'B', + installMethod: '整装', + executeStandard: 'GB/T3325-2024', + nationalStandardCompliant: '', + salesStatus: '', + boardMaterialType: '非ENF级', + }, + }, + }) as never, + ) + mockedAssetVariantRepository.findManyByFamilyIds.mockResolvedValueOnce([ + updatedSourceVariant, + siblingVariant, + ] as never) + mockedIntakeNonIntegratedProductRepository.listActive.mockResolvedValue([]) + + await assetCenterService.updateVariant( + 'variant-01', + { + businessData: sourceBusinessData, + updatedBy: 'user-2', + }, + { skipThumbnail: true }, + ) + + expect(mockedAssetVariantRepository.findManyByFamilyIds).toHaveBeenCalledWith([ + 'family-component', + ]) + expect(mockedAssetVariantRepository.updateWithRelations).toHaveBeenNthCalledWith( + 2, + 'variant-02', + expect.objectContaining({ + businessData: { + skuContentFields: expect.objectContaining({ + model: 'DBZ-SPJK01', + skuCode: 'DBZ-SPJ02', + barcode: 'DBZ-SPJ02N1280V01', + specName: 'style two', + size: '120/60/2.5', + color: 'black', + material: 'steel', + versionNo: '', + attributeCode: 'B', + installMethod: '整装', + executeStandard: 'GB/T3325-2024', + nationalStandardCompliant: '', + salesStatus: '', + boardMaterialType: '非ENF级', + }), + }, + lastModifier: { connect: { id: 'user-2' } }, + }), + ) + }) }) diff --git a/furniture-3d-system/src/server/services/__tests__/draft-group.service.test.ts b/furniture-3d-system/src/server/services/__tests__/draft-group.service.test.ts index a5c48ee5..31de6244 100644 --- a/furniture-3d-system/src/server/services/__tests__/draft-group.service.test.ts +++ b/furniture-3d-system/src/server/services/__tests__/draft-group.service.test.ts @@ -77,6 +77,7 @@ function buildLegacyCandidateWorkspace(input?: { modelUrl: string }> connectorCount?: number + connectorZone?: 'main' | 'staging' validation?: AssemblyWorkspaceSnapshot['validation'] }): AssemblyWorkspaceSnapshot { const includeDesktop = input?.includeDesktop !== false @@ -161,7 +162,7 @@ function buildLegacyCandidateWorkspace(input?: { position: [index * 40, 640, 0] as [number, number, number], rotation: [0, 0, 0] as [number, number, number], scale: [1, 1, 1] as [number, number, number], - zone: 'main' as const, + zone: input?.connectorZone ?? ('main' as const), source: 'connector' as const, inventoryId: `connector:family-connector-bracket:${index + 1}`, slotKey: `connector-${index + 1}`, @@ -696,6 +697,82 @@ describe('draftGroupService', () => { expect(result.preSkus).toHaveLength(2) }) + it('keeps staging connector nodes in draft-group hardware selections', async () => { + const result = await draftGroupService.createFromAutoCombination( + { + name: 'staging connector draft', + categoryId: 'category-desk', + candidates: [ + { + key: 'family-desktop-a::family-leg-slim::staging-connector', + defaultName: 'staging connector sku', + familySelection: { + desktopFamilyId: 'family-desktop-a', + legGroupFamilyId: 'family-leg-slim', + legRoles: { + frontLeft: 'family-leg-slim', + frontRight: null, + rearLeft: null, + rearRight: null, + }, + connectorFamilyIds: ['family-connector-bracket'], + }, + assemblyWorkspace: buildLegacyCandidateWorkspace({ + legs: [ + { + slotKey: 'frontLeftLeg', + role: 'frontLeft', + familyId: 'family-leg-slim', + variantId: 'variant-leg-slim-black', + code: 'LEG-SLIM-BK-720', + name: 'slim leg', + modelUrl: '/models/leg-slim-720.glb', + }, + ], + connectorCount: 1, + connectorZone: 'staging', + }), + }, + ], + }, + authUser, + ) + + expect(mockedPreSkuRepository.createManyForDraftGroup).toHaveBeenCalledWith( + 'draft-group-1', + expect.arrayContaining([ + expect.objectContaining({ + variantSelection: expect.objectContaining({ + slots: expect.not.arrayContaining([ + expect.objectContaining({ + variantId: 'variant-connector-bracket', + }), + ]), + hardwareSelections: [ + expect.objectContaining({ + variantId: 'variant-connector-bracket', + assetFamilyId: 'family-connector-bracket', + quantity: 1, + }), + ], + }), + bomPreview: expect.arrayContaining([ + expect.objectContaining({ + variantId: 'variant-connector-bracket', + assetType: 'HARDWARE', + quantity: 1, + }), + ]), + }), + ]), + expect.anything(), + ) + expect(mockedAssetVariantRepository.findByIdsWithRelations).toHaveBeenCalledWith( + expect.arrayContaining(['variant-connector-bracket']), + ) + expect(result.preSkus).toHaveLength(1) + }) + it('存在 BLOCKED 装配工作区时,不允许进入草稿组', async () => { await expect( draftGroupService.createFromAutoCombination( @@ -1375,7 +1452,28 @@ describe('draftGroupService', () => { }, recommendedHardware: [], previewNodes: [], - displaySummary: {}, + displaySummary: { + assemblyWorkspace: { + nodes: [ + { + nodeId: 'desktop-node', + zone: 'main', + position: [0, 737.5, 0], + rotation: [0, 0, 0], + scale: [1, 1, 1], + dimensions: { length: 1200, width: 600, thickness: 25 }, + }, + { + nodeId: 'leg-node', + zone: 'main', + position: [0, 362.5, 0], + rotation: [0, 0, 0], + scale: [1, 1, 1], + dimensions: { length: 50, width: 50, height: 725 }, + }, + ], + }, + }, bomPreview: [], weightPreview: null, componentCodes: [], @@ -1469,6 +1567,7 @@ describe('draftGroupService', () => { color: '柚木色', material: '颗粒板 + 柚木色', specName: '桌面 1200 柚木色', + size: '120 / 60 / 75', versionNo: 'V01', }), ) diff --git a/furniture-3d-system/src/server/services/__tests__/intake-non-integrated-product.service.test.ts b/furniture-3d-system/src/server/services/__tests__/intake-non-integrated-product.service.test.ts index f6cef2c2..ee3ee139 100644 --- a/furniture-3d-system/src/server/services/__tests__/intake-non-integrated-product.service.test.ts +++ b/furniture-3d-system/src/server/services/__tests__/intake-non-integrated-product.service.test.ts @@ -14,6 +14,12 @@ jest.mock('../../repositories/intake-non-integrated-product.repository', () => ( }, })) +jest.mock('../../repositories/asset-center.repository', () => ({ + assetVariantRepository: { + findActiveBySeriesCode: jest.fn(), + }, +})) + jest.mock('../../repositories/draft-group.repository', () => ({ draftGroupRepository: { findByIdWithRelations: jest.fn(), @@ -41,10 +47,12 @@ jest.mock('../sku-quality-inspection.service', () => ({ })) import { intakeNonIntegratedProductRepository } from '../../repositories/intake-non-integrated-product.repository' +import { assetVariantRepository } from '../../repositories/asset-center.repository' import { draftGroupRepository, preSkuRepository } from '../../repositories/draft-group.repository' import { intakeNonIntegratedProductService } from '../intake-non-integrated-product.service' const mockedRepository = jest.mocked(intakeNonIntegratedProductRepository) +const mockedAssetVariantRepository = jest.mocked(assetVariantRepository) const mockedDraftGroupRepository = jest.mocked(draftGroupRepository) const mockedPreSkuRepository = jest.mocked(preSkuRepository) @@ -111,6 +119,89 @@ function createRecord(overrides: Record = {}) { } } +function createAssetVariant(overrides: Record = {}) { + const code = typeof overrides.code === 'string' ? overrides.code : 'DBZ-SPJ11' + const id = typeof overrides.id === 'string' ? overrides.id : `variant-${code}` + return { + id, + assetFamilyId: 'family-packaging', + assetType: 'PACKAGING', + code, + name: typeof overrides.name === 'string' ? overrides.name : `${code} packaging`, + identityKey: code, + status: 'DRAFT', + sizeLabel: typeof overrides.sizeLabel === 'string' ? overrides.sizeLabel : '', + substrateId: null, + finishId: null, + dimensions: {}, + modelUrl: '', + thumbnailUrl: null, + barcode: null, + supplierName: null, + supplierCode: 'N12', + versionNo: 'V01', + mountPoints: [], + assemblyBasis: null, + compatibilityRules: null, + namingFields: null, + businessData: { + skuContentFields: { + model: 'DBZ-SPJK06', + skuCode: code, + barcode: `${code}N12V01`, + specName: `${code} packaging`, + size: typeof overrides.sizeLabel === 'string' ? overrides.sizeLabel : '', + color: '', + material: '', + manufacturer: '', + manufacturerCode: 'N12', + versionNo: 'V01', + attributeCode: 'N12', + drawingId: 'DBZ-SPJK06N12V01', + }, + }, + weightKg: null, + costPrice: null, + lossFactor: null, + estimatedCostPrice: null, + inheritedFromVariantId: null, + createdBy: null, + submittedAt: null, + submittedById: null, + reviewedAt: null, + reviewedById: null, + rejectedAt: null, + rejectedById: null, + reviewNote: null, + lastModifiedById: null, + deletedAt: null, + deletedById: null, + createdAt: new Date('2026-06-02T07:00:00.000Z'), + updatedAt: new Date('2026-06-02T07:00:00.000Z'), + assetFamily: { + id: 'family-packaging', + code: 'DBZ-SPJK06', + name: 'Packaging family', + type: 'PACKAGING', + assetSeriesId: 'series-dbz', + deletedAt: null, + assetSeries: { + id: 'series-dbz', + code: 'DBZ', + name: 'Single board desk', + }, + }, + substrate: null, + finish: null, + creator: null, + submitter: null, + reviewer: null, + rejecter: null, + lastModifier: null, + ...overrides, + } +} + describe('intakeNonIntegratedProductService', () => { beforeEach(() => { jest.clearAllMocks() @@ -119,6 +210,7 @@ describe('intakeNonIntegratedProductService', () => { mockedDraftGroupRepository.delete.mockResolvedValue({} as never) mockedDraftGroupRepository.findByIdWithRelations.mockResolvedValue(null as never) mockedPreSkuRepository.findByIdWithRelations.mockResolvedValue(null as never) + mockedAssetVariantRepository.findActiveBySeriesCode.mockResolvedValue([] as never) }) it('lists all shared records when permissions are relaxed', async () => { @@ -465,6 +557,75 @@ describe('intakeNonIntegratedProductService', () => { expect(mockedRepository.update).toHaveBeenCalled() }) + it('appends missing asset center component SKUs before saving a stale component detail payload', async () => { + const staleSkuItems = Array.from({ length: 10 }, (_, index) => { + const sequence = index + 1 + const skuCode = `DBZ-SPJ${String(sequence).padStart(2, '0')}` + return { + id: `asset-variant-variant-${sequence}`, + skuSequence: sequence, + skuCode, + source: 'asset_series_component', + sourceTable: 'asset_variant', + sourceSkuId: `variant-${sequence}`, + } + }) + const componentPayload = createPayload({ + id: 'DBZ-SPJ-1780300716699', + spu: 'DBZ-SPJ', + productCode: 'DBZ-SPJ', + productDevelopmentKind: 'series', + metadata: { + componentDetailType: 'asset-series-components', + sourceSeriesCode: 'DBZ', + }, + skuItems: staleSkuItems, + skuBatchCount: 1, + }) + const componentRecord = createRecord({ + id: 'DBZ-SPJ-1780300716699', + spu: 'DBZ-SPJ', + spuBase: 'DBZ-SPJ', + payload: componentPayload, + }) + + mockedRepository.findBySpu.mockResolvedValue(null as never) + mockedRepository.findById.mockResolvedValue(componentRecord as never) + mockedRepository.update.mockResolvedValue(componentRecord as never) + mockedRepository.findActiveById.mockResolvedValue(componentRecord as never) + mockedAssetVariantRepository.findActiveBySeriesCode.mockResolvedValue([ + createAssetVariant({ + id: 'variant-11', + code: 'DBZ-SPJ11', + sizeLabel: '140/140/0.3', + }), + createAssetVariant({ + id: 'variant-12', + code: 'DBZ-SPJ12', + sizeLabel: '120/120/0.3', + }), + ] as never) + + await intakeNonIntegratedProductService.save(componentPayload, baseUser) + + expect(mockedAssetVariantRepository.findActiveBySeriesCode).toHaveBeenCalledWith('DBZ') + const updatePayload = mockedRepository.update.mock.calls[0]?.[1]?.payload as { + skuItems?: Array> + skuBatchCount?: number + } + expect(updatePayload.skuItems).toHaveLength(12) + expect(updatePayload.skuItems?.slice(-2).map((item) => item.skuCode)).toEqual([ + 'DBZ-SPJ11', + 'DBZ-SPJ12', + ]) + expect(updatePayload.skuItems?.[10]).toMatchObject({ + sourceSkuId: 'variant-11', + model: 'DBZ-SPJK06', + barcode: 'DBZ-SPJ11N12V01', + }) + expect(updatePayload.skuBatchCount).toBe(1) + }) + it('rejects purchasers from confirming product photo through the shared save API', async () => { const existingConfirmations = { ...createDefaultDocumentWorkspaceConfirmations(), diff --git a/furniture-3d-system/src/server/services/asset-center.service.ts b/furniture-3d-system/src/server/services/asset-center.service.ts index 5ed15ccb..e9b7c8d7 100644 --- a/furniture-3d-system/src/server/services/asset-center.service.ts +++ b/furniture-3d-system/src/server/services/asset-center.service.ts @@ -33,6 +33,17 @@ import { validateSupplierCode, } from '@/lib/open-product/asset-coding' import { + NON_INTEGRATED_DEFAULT_BRAND, + buildNonIntegratedProductId, + createDefaultDocumentWorkspaceConfirmations, + createEmptyNonIntegratedOpeningReference, + createEmptyNonIntegratedPatentApplication, + createEmptyNonIntegratedProjectReview, + type NonIntegratedProductRecord, + type NonIntegratedSkuItem, +} from '@/app/intake/non-integrated/nonIntegratedStorage' +import { + ASSET_VARIANT_SOFT_DELETE_MARKER, buildDeletedAssetVariantUniqueValue, buildSoftDeletedAssetVariantBusinessData, clearSoftDeletedAssetVariantBusinessData, @@ -69,6 +80,7 @@ import { assetVariantRepository, assetVariantRelationInclude, categoryRepository, + intakeNonIntegratedProductRepository, materialRepository, substrateRelationInclude, substrateRepository, @@ -84,6 +96,7 @@ import type { AssetTrashCleanupResultDTO, AssetTrashDataDTO, AssetSeriesDTO, + AssetSeriesComponentDetailSummaryDTO, AssetReviewActionInput, AssetVariantDTO, AssetWorkflowAuditDTO, @@ -112,6 +125,7 @@ import { assetVariantThumbnailService, } from './asset-variant-thumbnail.service' import { assetSkuSyncService, type AssetSkuSyncReason } from './asset-sku-sync.service' +import { intakeNonIntegratedProductService } from './intake-non-integrated-product.service' import { materialService } from './material.service' import type { AssetOperationProgressStep } from './asset-operation-progress.service' @@ -152,6 +166,697 @@ function trimOrNull(value: string | null | undefined): string | null { return next ? next : null } +function normalizeDimensionRecord(value: unknown): Record { + if (!isRecord(value)) return {} + return Object.entries(value).reduce>((dimensions, [key, entry]) => { + if (typeof entry === 'number' && Number.isFinite(entry)) { + dimensions[key] = entry + } + return dimensions + }, {}) +} + +function hasDimensionValue(dimensions: Record): boolean { + return Object.values(dimensions).some((value) => Number.isFinite(value)) +} + +function toFiniteNumber(value: unknown): number | null { + if (typeof value === 'number' && Number.isFinite(value)) return value + if (typeof value === 'string' && value.trim()) { + const parsed = Number(value.trim()) + return Number.isFinite(parsed) ? parsed : null + } + return null +} + +function buildDimensionsFromTriplet( + assetType: string, + values: number[], +): Record { + if (values.length < 3) return {} + if (assetType === 'HARDWARE') { + return { + width: values[0], + height: values[1], + depth: values[2], + } + } + return { + length: values[0], + width: values[1], + [assetType === 'BOARD' ? 'thickness' : 'height']: values[2], + } +} + +function parseDimensionsFromSizeText( + assetType: string, + value: unknown, +): Record { + if (typeof value !== 'string') return {} + const values = value + .split(/[xX×**/\\,\s]+/) + .map((part) => toFiniteNumber(part)) + .filter((part): part is number => part !== null) + return buildDimensionsFromTriplet(assetType, values) +} + +function parseDimensionsFromModelBounds( + assetType: string, + value: unknown, +): Record { + if (!Array.isArray(value) || value.length < 6) return {} + const numbers = value.map((entry) => toFiniteNumber(entry)) + if (numbers.some((entry) => entry === null)) return {} + const bounds = numbers as number[] + return buildDimensionsFromTriplet(assetType, [ + Math.abs(bounds[3] - bounds[0]), + Math.abs(bounds[4] - bounds[1]), + Math.abs(bounds[5] - bounds[2]), + ]) +} + +function parseDimensionsFromCadPanel( + assetType: string, + value: unknown, +): Record { + if (!Array.isArray(value) || value.length < 3) return {} + const values = value + .slice(0, 3) + .map((entry) => toFiniteNumber(entry)) + if (values.some((entry) => entry === null)) return {} + return buildDimensionsFromTriplet(assetType, values as number[]) +} + +function inferDimensionsFromBusinessData( + assetType: string, + businessData: unknown, +): Record { + const record = normalizeJsonRecord(businessData) + if (!record) return {} + + const skuContentFields = normalizeJsonRecord(record.skuContentFields) + const cadData = normalizeJsonRecord(record.cadData) + const panels = Array.isArray(cadData?.panels) ? cadData.panels : [] + const firstPanel = normalizeJsonRecord(panels[0]) + + return { + ...parseDimensionsFromModelBounds(assetType, record.modelBounds), + ...parseDimensionsFromCadPanel(assetType, firstPanel?.size), + ...parseDimensionsFromSizeText(assetType, skuContentFields?.size), + } +} + +function resolveVariantDimensionsForCreate(input: { + assetType: string + inputDimensions: Record + inputBusinessData?: unknown + inheritedDimensions: Record + inheritedBusinessData?: unknown + sizeLabel?: string | null +}): Record { + return { + ...input.inheritedDimensions, + ...inferDimensionsFromBusinessData(input.assetType, input.inheritedBusinessData), + ...parseDimensionsFromSizeText(input.assetType, input.sizeLabel), + ...inferDimensionsFromBusinessData(input.assetType, input.inputBusinessData), + ...normalizeDimensionRecord(input.inputDimensions), + } +} + +const SERIES_COMPONENT_DETAIL_METADATA_TYPE = 'asset-series-components' +const SERIES_COMPONENT_ASSET_SKU_SOURCE = 'asset_series_component' +const ASSET_VARIANT_SOURCE_TABLE = 'asset_variant' +const ASSET_VARIANT_SKU_CONTENT_BUSINESS_DATA_KEY = 'skuContentFields' +const NON_BOARD_ASSET_BOARD_MATERIAL_TYPE = '非ENF级' +const DEFAULT_ASSET_VARIANT_ATTRIBUTE_CODE = 'A' +const DEFAULT_ASSET_VARIANT_INSTALL_METHOD = '拆装' +const DEFAULT_ASSET_VARIANT_EXECUTE_STANDARD = 'GB/T3324-2024' +const DEFAULT_STEEL_ASSET_VARIANT_EXECUTE_STANDARD = 'GB/T3325-2024' +const DEFAULT_ASSET_VARIANT_NATIONAL_STANDARD_COMPLIANT = '是' +const DEFAULT_ASSET_VARIANT_SALES_STATUS = '销售' +const SHARED_ASSET_VARIANT_SKU_FIELD_KEYS = [ + 'versionNo', + 'attributeCode', + 'installMethod', + 'executeStandard', + 'nationalStandardCompliant', + 'salesStatus', + 'boardMaterialType', +] as const +const ORIGINAL_ASSET_FAMILY_CODE_KEY = '_originalAssetFamilyCode' +const DELETED_ASSET_FAMILY_CODE_AT_KEY = '_deletedAssetFamilyCodeAt' +const SERIES_COMPONENT_SECONDARY_CATEGORY = '家具辅料' +const SERIES_COMPONENT_PRODUCT_CATEGORY = '其它家具配件' + +function buildSeriesComponentDetailSpu(seriesCode: string): string { + const normalizedSeriesCode = seriesCode.trim().toUpperCase() + return normalizedSeriesCode ? `${normalizedSeriesCode}-SPJ` : '' +} + +function buildSeriesComponentSourceSeriesName(series: AssetSeriesDTO): string { + return series.displayName || `${series.name} ${series.code}`.trim() +} + +function buildSeriesComponentProductName(series: AssetSeriesDTO): string { + return `${buildSeriesComponentDetailSpu(series.code)}部件开发明细` +} + +function readSeriesComponentDetailSummaryFromRecord( + record: { id: string; spu: string; payload: Prisma.JsonValue }, + fallbackCreated: boolean, +): AssetSeriesComponentDetailSummaryDTO | null { + const payload = isRecord(record.payload) ? record.payload : null + const metadata = isRecord(payload?.metadata) ? payload.metadata : null + if (metadata?.componentDetailType !== SERIES_COMPONENT_DETAIL_METADATA_TYPE) { + return null + } + + const sourceSeriesCode = + typeof metadata.sourceSeriesCode === 'string' + ? metadata.sourceSeriesCode.trim().toUpperCase() + : '' + const sourceSeriesName = + typeof metadata.sourceSeriesName === 'string' + ? metadata.sourceSeriesName.trim() + : '' + const spu = typeof payload?.spu === 'string' ? payload.spu.trim() : record.spu.trim() + + return { + productId: record.id, + spu, + sourceSeriesCode, + sourceSeriesName, + created: fallbackCreated, + } +} + +function createEmptySeriesComponentSkuPayloadItem( + variant: AssetVariantDTO, + skuSequence: number, +): NonIntegratedSkuItem { + return { + id: `asset-variant-${variant.id}`, + skuSequence, + batchNo: 1, + packageGroupId: '', + packageSuffix: '', + image: '', + imageName: '', + model: '', + skuCode: '', + setCount: '1', + specName: '', + barcode: '', + size: '', + color: '', + material: '', + boardMaterialType: '', + versionNo: DEFAULT_SKU_VERSION_NO, + attributeCode: '', + drawingId: '', + installMethod: '', + executeStandard: '', + nationalStandardCompliant: '', + manufacturer: '', + manufacturerCode: '', + salesStatus: '', + tagMaterial: '', + model3dFileName: '', + model3dDataUrl: '', + model3dNodeOffsets: {}, + model3dNodeRotations: {}, + model3dNodeMaterialIds: {}, + model3dUvConfig: null, + model3dPreviewNodes: [], + componentDetails: [], + holePoints: [], + source: SERIES_COMPONENT_ASSET_SKU_SOURCE, + sourceTable: ASSET_VARIANT_SOURCE_TABLE, + sourceSkuId: variant.id, + contentLocked: false, + } +} + +function escapeRegExp(value: string): string { + return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') +} + +function parseAssetVariantSequence(seriesCode: string, code: string): number | null { + const normalizedSeriesCode = seriesCode.trim().toUpperCase() + const normalizedCode = code.trim().toUpperCase() + if (!normalizedSeriesCode || !normalizedCode) return null + + const match = normalizedCode.match( + new RegExp(`^${escapeRegExp(normalizedSeriesCode)}-SPJ(\\d+)$`), + ) + if (!match) return null + + const sequence = Number.parseInt(match[1] ?? '', 10) + return Number.isFinite(sequence) && sequence > 0 ? sequence : null +} + +function parseSeriesCodeFromAssetVariantCode(code: string): string { + const matched = code.trim().toUpperCase().match(/^([A-Z][A-Z0-9]*)-SPJ\d+$/) + return matched?.[1] ?? '' +} + +function parseAssetFamilySequence(seriesCode: string, code: string): number | null { + const normalizedSeriesCode = seriesCode.trim().toUpperCase() + const normalizedCode = code.trim().toUpperCase() + if (!normalizedSeriesCode || !normalizedCode) return null + + const match = normalizedCode.match( + new RegExp(`^${escapeRegExp(normalizedSeriesCode)}-SPJK(\\d+)$`), + ) + if (!match) return null + + const sequence = Number.parseInt(match[1] ?? '', 10) + return Number.isFinite(sequence) && sequence > 0 ? sequence : null +} + +function getRestorableAssetFamilyCode(input: { + code: string + metadata: Prisma.JsonValue | Record | null | undefined +}): string { + const metadata = normalizeJsonRecord(input.metadata) + const metadataCode = metadata?.[ORIGINAL_ASSET_FAMILY_CODE_KEY] + if (typeof metadataCode === 'string' && metadataCode.trim()) { + return metadataCode.trim() + } + + const markerIndex = input.code.indexOf(ASSET_VARIANT_SOFT_DELETE_MARKER) + return markerIndex > 0 ? input.code.slice(0, markerIndex) : input.code +} + +function buildSoftDeletedAssetFamilyMetadata(input: { + metadata: Prisma.JsonValue | Record | null | undefined + originalCode: string + deletedAt: Date +}): Record { + return { + ...(normalizeJsonRecord(input.metadata) ?? {}), + [ORIGINAL_ASSET_FAMILY_CODE_KEY]: input.originalCode, + [DELETED_ASSET_FAMILY_CODE_AT_KEY]: input.deletedAt.toISOString(), + } +} + +function clearSoftDeletedAssetFamilyMetadata( + metadata: Prisma.JsonValue | Record | null | undefined, +): Record | null { + const next = normalizeJsonRecord(metadata) ?? {} + delete next[ORIGINAL_ASSET_FAMILY_CODE_KEY] + delete next[DELETED_ASSET_FAMILY_CODE_AT_KEY] + return Object.keys(next).length > 0 ? next : null +} + +function buildVariantBusinessDataAfterFamilyCodeChange(input: { + businessData: Prisma.JsonValue | Record | null | undefined + oldFamilyCode: string + nextFamilyCode: string +}): Record { + const businessData = normalizeJsonRecord(input.businessData) ?? {} + const skuContentFields = isRecord(businessData[ASSET_VARIANT_SKU_CONTENT_BUSINESS_DATA_KEY]) + ? { ...(businessData[ASSET_VARIANT_SKU_CONTENT_BUSINESS_DATA_KEY] as Record) } + : {} + const oldCode = input.oldFamilyCode.trim().toUpperCase() + const nextCode = input.nextFamilyCode.trim().toUpperCase() + const drawingId = typeof skuContentFields.drawingId === 'string' + ? skuContentFields.drawingId.trim().toUpperCase() + : '' + + skuContentFields.model = nextCode + if (oldCode && drawingId.startsWith(oldCode)) { + skuContentFields.drawingId = `${nextCode}${drawingId.slice(oldCode.length)}` + } + + return { + ...businessData, + [ASSET_VARIANT_SKU_CONTENT_BUSINESS_DATA_KEY]: skuContentFields, + } +} + +function normalizeSourceMarker(value: unknown): string { + return typeof value === 'string' ? value.trim().toLowerCase() : '' +} + +function isSeriesComponentDevelopmentPayload(payload: unknown): payload is Record { + if (!isRecord(payload)) return false + if (payload.productDevelopmentKind !== 'series') return false + + const metadata = isRecord(payload.metadata) ? payload.metadata : null + return metadata?.componentDetailType === SERIES_COMPONENT_DETAIL_METADATA_TYPE +} + +function isSeriesComponentDevelopmentPayloadForSeries( + payload: unknown, + seriesCode: string, + recordSpu?: string | null, +): payload is Record { + if (!isSeriesComponentDevelopmentPayload(payload)) return false + + const normalizedSeriesCode = seriesCode.trim().toUpperCase() + if (!normalizedSeriesCode) return false + + const metadata = isRecord(payload.metadata) ? payload.metadata : null + const sourceSeriesCode = typeof metadata?.sourceSeriesCode === 'string' + ? metadata.sourceSeriesCode.trim().toUpperCase() + : '' + const payloadSpu = typeof payload.spu === 'string' + ? payload.spu.trim().toUpperCase() + : '' + const normalizedRecordSpu = recordSpu?.trim().toUpperCase() ?? '' + const expectedSpu = buildSeriesComponentDetailSpu(normalizedSeriesCode).toUpperCase() + + return ( + sourceSeriesCode === normalizedSeriesCode || + payloadSpu === expectedSpu || + normalizedRecordSpu === expectedSpu + ) +} + +function isSeriesComponentAssetSkuPayloadItem(item: unknown): item is Record { + if (!isRecord(item)) return false + + return ( + normalizeSourceMarker(item.source) === SERIES_COMPONENT_ASSET_SKU_SOURCE || + normalizeSourceMarker(item.sourceTable) === ASSET_VARIANT_SOURCE_TABLE + ) +} + +function readPayloadString(item: Record, key: string): string { + const value = item[key] + if (typeof value === 'string') return value.trim() + if (typeof value === 'number' && Number.isFinite(value)) return String(value) + return '' +} + +function parseSeriesComponentBatchNo(value: string, fallback: number): number { + const matched = value.trim().match(/\d+/) + const parsed = matched ? Number.parseInt(matched[0] ?? '', 10) : NaN + return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback +} + +function getSeriesComponentSkuBatchCount(items: unknown[]): number { + return Math.max( + 1, + ...items.map((item) => { + if (!isRecord(item)) return 1 + return parseSeriesComponentBatchNo(readPayloadString(item, 'batchNo'), 1) + }), + ) +} + +function readVariantSkuContentFields(variant: AssetVariantDTO): Record { + const businessData = isRecord(variant.businessData) ? variant.businessData : null + const rawFields = businessData?.[ASSET_VARIANT_SKU_CONTENT_BUSINESS_DATA_KEY] + if (!isRecord(rawFields)) return {} + + return Object.entries(rawFields).reduce>((fields, [key, value]) => { + if (typeof value === 'string') { + fields[key] = value.trim() + } else if (typeof value === 'number' && Number.isFinite(value)) { + fields[key] = String(value) + } + return fields + }, {}) +} + +function getVariantSkuContentField( + fields: Record, + key: string, + fallback = '', +): string { + return Object.prototype.hasOwnProperty.call(fields, key) + ? fields[key] ?? '' + : fallback +} + +function hasVariantSkuContentField(fields: Record, key: string): boolean { + return Object.prototype.hasOwnProperty.call(fields, key) +} + +function getVariantSkuContentFieldWithDefault( + fields: Record, + key: string, + defaultValue: string, +): string { + return hasVariantSkuContentField(fields, key) ? fields[key] ?? '' : defaultValue +} + +function getDefaultVariantExecuteStandard(assetType: string): string { + return assetType === 'COMPONENT' || assetType === 'HARDWARE' + ? DEFAULT_STEEL_ASSET_VARIANT_EXECUTE_STANDARD + : DEFAULT_ASSET_VARIANT_EXECUTE_STANDARD +} + +function getAssetVariantBoardMaterialTypeForSku( + _assetType: string, + fields: Record, +): string { + return getVariantSkuContentFieldWithDefault( + fields, + 'boardMaterialType', + NON_BOARD_ASSET_BOARD_MATERIAL_TYPE, + ) +} + +function updateSeriesComponentSkuPayloadItemFromVariant( + item: Record, + variant: AssetVariantDTO, + skuSequence: number, +): Record { + const normalizedCode = variant.code.trim().toUpperCase() + const normalizedModel = variant.assetFamilyCode.trim().toUpperCase() + const normalizedModelUrl = variant.modelUrl.trim() + const thumbnailUrl = variant.thumbnailUrl?.trim() ?? '' + const skuContentFields = readVariantSkuContentFields(variant) + const rawVersionNo = hasVariantSkuContentField(skuContentFields, 'versionNo') + ? skuContentFields.versionNo ?? '' + : (variant.versionNo ?? readPayloadString(item, 'versionNo')) || DEFAULT_SKU_VERSION_NO + const versionNo = rawVersionNo.trim() ? normalizeSkuVersionNo(rawVersionNo) : '' + const manufacturerCode = getVariantSkuContentField( + skuContentFields, + 'manufacturerCode', + variant.supplierCode ?? readPayloadString(item, 'manufacturerCode'), + ).trim().toUpperCase() + const barcode = getVariantSkuContentField( + skuContentFields, + 'barcode', + variant.barcode ?? ( + versionNo && + buildAssetVariantBarcode({ + variantCode: normalizedCode, + supplierCode: manufacturerCode, + versionNo, + }) || + readPayloadString(item, 'barcode') + ), + ).trim().toUpperCase() + const batchNo = parseSeriesComponentBatchNo( + getVariantSkuContentField(skuContentFields, 'batchNo', readPayloadString(item, 'batchNo')), + 1, + ) + const attributeCode = getVariantSkuContentFieldWithDefault( + skuContentFields, + 'attributeCode', + DEFAULT_ASSET_VARIANT_ATTRIBUTE_CODE, + ).toUpperCase() + const drawingIdFallback = `${getVariantSkuContentField(skuContentFields, 'model', normalizedModel) || normalizedModel}${attributeCode}${versionNo}` + + return { + ...item, + skuSequence, + model: getVariantSkuContentField(skuContentFields, 'model', normalizedModel) || normalizedModel, + skuCode: normalizedCode, + barcode, + setCount: getVariantSkuContentField(skuContentFields, 'setCount', readPayloadString(item, 'setCount') || '1'), + specName: getVariantSkuContentField(skuContentFields, 'specName', readPayloadString(item, 'specName') || variant.name.trim()), + size: getVariantSkuContentField(skuContentFields, 'size', readPayloadString(item, 'size') || (variant.sizeLabel ?? '')), + color: getVariantSkuContentField(skuContentFields, 'color', readPayloadString(item, 'color')), + material: getVariantSkuContentField(skuContentFields, 'material', readPayloadString(item, 'material')), + boardMaterialType: getAssetVariantBoardMaterialTypeForSku( + variant.assetType, + skuContentFields, + ), + versionNo, + attributeCode, + drawingId: getVariantSkuContentField(skuContentFields, 'drawingId', readPayloadString(item, 'drawingId') || drawingIdFallback).toUpperCase(), + installMethod: getVariantSkuContentFieldWithDefault( + skuContentFields, + 'installMethod', + DEFAULT_ASSET_VARIANT_INSTALL_METHOD, + ), + executeStandard: getVariantSkuContentFieldWithDefault( + skuContentFields, + 'executeStandard', + getDefaultVariantExecuteStandard(variant.assetType), + ), + nationalStandardCompliant: getVariantSkuContentFieldWithDefault( + skuContentFields, + 'nationalStandardCompliant', + DEFAULT_ASSET_VARIANT_NATIONAL_STANDARD_COMPLIANT, + ), + manufacturer: getVariantSkuContentField(skuContentFields, 'manufacturer', readPayloadString(item, 'manufacturer') || (variant.supplierName ?? '')), + manufacturerCode, + salesStatus: getVariantSkuContentFieldWithDefault( + skuContentFields, + 'salesStatus', + DEFAULT_ASSET_VARIANT_SALES_STATUS, + ), + batchNo, + dingTalkFlowNo: getVariantSkuContentField(skuContentFields, 'dingTalkFlowNo', readPayloadString(item, 'dingTalkFlowNo')), + image: thumbnailUrl, + imageName: thumbnailUrl ? `${normalizedCode}-thumb` : '', + model3dFileName: normalizedModelUrl ? `${normalizedCode}-model.glb` : '', + model3dDataUrl: normalizedModelUrl, + source: SERIES_COMPONENT_ASSET_SKU_SOURCE, + sourceTable: ASSET_VARIANT_SOURCE_TABLE, + sourceSkuId: variant.id, + } +} + +function buildSeriesComponentSkuItemsFromVariants( + variants: AssetVariantDTO[], +): NonIntegratedSkuItem[] { + return variants.map((variant, index) => + updateSeriesComponentSkuPayloadItemFromVariant( + createEmptySeriesComponentSkuPayloadItem(variant, index + 1), + variant, + index + 1, + ) as NonIntegratedSkuItem, + ) +} + +function buildSeriesComponentDetailProductPayload(input: { + series: AssetSeriesDTO + variants: AssetVariantDTO[] + user: AuthUser +}): NonIntegratedProductRecord { + const now = new Date().toISOString() + const spu = buildSeriesComponentDetailSpu(input.series.code) + const sourceSeriesName = buildSeriesComponentSourceSeriesName(input.series) + const productName = buildSeriesComponentProductName(input.series) + const skuItems = buildSeriesComponentSkuItemsFromVariants(input.variants) + const openingReference = { + ...createEmptyNonIntegratedOpeningReference(), + productName, + temporaryCode: spu, + brand: NON_INTEGRATED_DEFAULT_BRAND, + adaptableBrands: [NON_INTEGRATED_DEFAULT_BRAND], + productCategory: SERIES_COMPONENT_PRODUCT_CATEGORY, + salesCategory: SERIES_COMPONENT_SECONDARY_CATEGORY, + currentStage: '部件开发明细', + year: String(new Date(now).getFullYear()), + } + + return { + id: buildNonIntegratedProductId(spu), + productDevelopmentKind: 'series', + metadata: { + componentDetailType: SERIES_COMPONENT_DETAIL_METADATA_TYPE, + sourceSeriesName, + sourceSeriesCode: input.series.code.trim().toUpperCase(), + sourceAssetSeriesId: input.series.id, + }, + spu, + projectStatus: 'draft', + projectReview: createEmptyNonIntegratedProjectReview(), + openingReference, + patentApplication: createEmptyNonIntegratedPatentApplication(), + brand: NON_INTEGRATED_DEFAULT_BRAND, + adaptableBrands: [NON_INTEGRATED_DEFAULT_BRAND], + designer: '', + operator: '', + purchaser: '', + previewImage: '', + previewImageName: '', + year: openingReference.year, + demandFlowNo: '', + processTemplate: '', + productCategory: SERIES_COMPONENT_PRODUCT_CATEGORY, + salesCategory: SERIES_COMPONENT_SECONDARY_CATEGORY, + productPlanning: '', + brandPlanning: '', + demandDepartment: '', + isSelfDevelopedPatentProduct: '', + patentOwner: '', + spuOwner: '', + needsClearanceHandling: '', + operationsOwner: '', + profitCenter: '', + salesChannel: '', + salesPlatform: '', + purchaseOwner: '', + goodsType: '', + materialType: '', + productionType: '', + manualProducer: '', + shippingMode: '', + visualDirector: '', + itemId: '', + priceBand: '', + outputRequirementType: '', + visualPlanning: '', + visualPlanningType: '', + photographer: '', + graphicDesigner: '', + designer3d: '', + sampleRequired: '', + flatOutputPath: '', + output3dPath: '', + productCode: spu, + size: '', + color: '', + installMethod: '', + installSteps: '', + tagMaterial: '', + packageDetail: '', + craftDetail: '', + model3dFileName: '', + model3dDataUrl: '', + styleDetails: [], + bomDetails: [], + reviewSheet: { + version: '', + factory: '', + reviewDate: '', + reviewMethod: '', + productName: '', + productImage: '', + productImageName: '', + size: '', + material: '', + barcode: '', + reviewResult: '', + color: '', + issues: [], + }, + reviewSheets: [], + qualityInspectionSheet: { rows: [] }, + skuItems, + skuBatchCount: getSeriesComponentSkuBatchCount(skuItems), + skuBatchFlowNos: {}, + skuBatchChangeTypes: {}, + skuBatchConfirmedAt: {}, + factoryRows: [], + pricingRows: [], + planningLayoutRows: [], + productLimitRows: [], + sampleMeasurementRows: [], + finishedSampleShipmentRows: [], + firstQualityRows: [], + uploadFiles: [], + documentWorkspaceNotes: {}, + documentWorkspaceConfirmations: createDefaultDocumentWorkspaceConfirmations(), + documentWorkspaceApprovedAt: {}, + formalSpuAssigned: true, + createdBy: input.user.id, + updatedBy: input.user.id, + createdAt: now, + updatedAt: now, + } +} + const STALE_SERIES_DESCRIPTION_PATTERN = /(固定模板|自动连接件推荐|自动拼装|自动组合|auto-combinations)/i @@ -592,7 +1297,10 @@ function toDeletedAssetFamilyDTO( type: 'assetFamily', id: record.id, assetType: record.type, - code: record.code, + code: getRestorableAssetFamilyCode({ + code: record.code, + metadata: record.metadata, + }), name: record.name, status: record.status, variantCount: record._count?.variants ?? 0, @@ -1054,29 +1762,159 @@ class AssetCenterService { } private async generateNextFamilyCode(seriesCode: string): Promise { + const normalizedSeriesCode = seriesCode.trim().toUpperCase() const existingCodes = await prisma.assetFamily.findMany({ where: { - code: { startsWith: `${seriesCode}-SPJK` }, + code: { startsWith: `${normalizedSeriesCode}-SPJK` }, deletedAt: null, + assetSeries: { is: { code: normalizedSeriesCode } }, }, select: { code: true }, }) - const used = new Set(existingCodes.map((item) => item.code)) - const maxSequence = existingCodes.reduce((max, item) => { - const matched = item.code.match(new RegExp(`^${seriesCode}-SPJK(\\d{3})$`)) - const value = matched ? Number.parseInt(matched[1] ?? '', 10) : 0 - return Number.isFinite(value) ? Math.max(max, value) : max - }, 0) + const usedSequences = new Set( + existingCodes + .map((item) => parseAssetFamilySequence(normalizedSeriesCode, item.code)) + .filter((sequence): sequence is number => sequence !== null), + ) - let sequence = maxSequence + 1 - let candidate = buildAssetFamilyCode(seriesCode, sequence) - while (used.has(candidate) || await assetFamilyRepository.findByCode(candidate)) { + let sequence = 1 + let candidate = buildAssetFamilyCode(normalizedSeriesCode, sequence) + while (usedSequences.has(sequence)) { sequence += 1 - candidate = buildAssetFamilyCode(seriesCode, sequence) + candidate = buildAssetFamilyCode(normalizedSeriesCode, sequence) + } + + await this.releaseDeletedFamilyCode(candidate) + while (await assetFamilyRepository.findByCode(candidate)) { + sequence += 1 + candidate = buildAssetFamilyCode(normalizedSeriesCode, sequence) + if (usedSequences.has(sequence)) continue + await this.releaseDeletedFamilyCode(candidate) } return candidate } + private async releaseDeletedFamilyCode(code: string): Promise { + const deletedFamilies = await prisma.assetFamily.findMany({ + where: { + deletedAt: { not: null }, + OR: [ + { code }, + { code: { startsWith: `${code}${ASSET_VARIANT_SOFT_DELETE_MARKER}` } }, + ], + }, + select: { + id: true, + code: true, + metadata: true, + deletedAt: true, + }, + }) + + for (const family of deletedFamilies) { + const originalCode = getRestorableAssetFamilyCode({ + code: family.code, + metadata: family.metadata, + }) + if (originalCode !== code) continue + + const deletedAt = family.deletedAt ?? new Date() + await prisma.assetFamily.update({ + where: { id: family.id }, + data: { + code: buildDeletedAssetVariantUniqueValue(family.code, family.id, deletedAt), + metadata: buildSoftDeletedAssetFamilyMetadata({ + metadata: family.metadata, + originalCode, + deletedAt, + }) as Prisma.InputJsonValue, + }, + }) + } + } + + private async compactFamilyCodesForSeries( + seriesCode: string, + updatedById?: string | null, + ): Promise { + const normalizedSeriesCode = seriesCode.trim().toUpperCase() + if (!normalizedSeriesCode) return + + const activeFamilies = await prisma.assetFamily.findMany({ + where: { + code: { startsWith: `${normalizedSeriesCode}-SPJK` }, + deletedAt: null, + assetSeries: { is: { code: normalizedSeriesCode } }, + }, + select: { + id: true, + code: true, + }, + }) + const sequencedFamilies = activeFamilies + .map((family) => ({ + ...family, + sequence: parseAssetFamilySequence(normalizedSeriesCode, family.code), + })) + .filter((family): family is { id: string; code: string; sequence: number } => + family.sequence !== null, + ) + .sort((left, right) => left.sequence - right.sequence) + const updatedVariants: AssetVariantDTO[] = [] + + let nextSequence = 1 + for (const family of sequencedFamilies) { + const nextCode = buildAssetFamilyCode(normalizedSeriesCode, nextSequence) + nextSequence += 1 + if (family.code === nextCode) continue + + await this.releaseDeletedFamilyCode(nextCode) + await prisma.assetFamily.update({ + where: { id: family.id }, + data: { + code: nextCode, + lastModifiedById: updatedById ?? undefined, + }, + }) + + const variants = await prisma.assetVariant.findMany({ + where: { + assetFamilyId: family.id, + deletedAt: null, + }, + select: { + id: true, + businessData: true, + }, + }) + + for (const variant of variants) { + const updated = await assetVariantRepository.updateWithRelations(variant.id, { + businessData: buildVariantBusinessDataAfterFamilyCodeChange({ + businessData: variant.businessData, + oldFamilyCode: family.code, + nextFamilyCode: nextCode, + }) as Prisma.InputJsonValue, + lastModifier: updatedById ? { connect: { id: updatedById } } : undefined, + }) + updatedVariants.push(toAssetVariantDTO(updated)) + } + } + + await Promise.all( + updatedVariants.map(async (variant) => { + await this.syncSeriesComponentDevelopmentPayloadsAfterVariantUpdate({ + variant, + updatedById: updatedById ?? null, + }) + await this.enqueueVariantSkuSync(variant, 'VARIANT_UPDATED', { + updatedBy: updatedById ?? null, + reason: 'FAMILY_RENUMBERED_AFTER_DELETE', + }) + }), + ) + } + private async generateNextVariantCode(seriesCode: string): Promise { const existingCodes = await prisma.assetVariant.findMany({ where: { @@ -1088,7 +1926,7 @@ class AssetCenterService { }) const used = new Set(existingCodes.map((item) => item.code)) const maxSequence = existingCodes.reduce((max, item) => { - const matched = item.code.match(new RegExp(`^${seriesCode}-SPJ(\\d{5})$`)) + const matched = item.code.match(new RegExp(`^${seriesCode}-SPJ(\\d+)$`)) const value = matched ? Number.parseInt(matched[1] ?? '', 10) : 0 return Number.isFinite(value) ? Math.max(max, value) : max }, 0) @@ -1198,6 +2036,82 @@ class AssetCenterService { return [toAssetSeriesDTO(created)] } + private async findSeriesComponentDetailRecord(series: AssetSeriesDTO) { + const seriesCode = series.code.trim().toUpperCase() + const spu = buildSeriesComponentDetailSpu(seriesCode) + const componentRecords = await intakeNonIntegratedProductRepository.listActive({ + payload: { + path: ['metadata', 'componentDetailType'], + equals: SERIES_COMPONENT_DETAIL_METADATA_TYPE, + }, + }) + + const matchedByMetadata = componentRecords.find((record) => { + const summary = readSeriesComponentDetailSummaryFromRecord(record, false) + if (!summary) return false + return ( + summary.sourceSeriesCode.trim().toUpperCase() === seriesCode || + summary.spu.trim().toUpperCase() === spu + ) + }) + if (matchedByMetadata) return matchedByMetadata + + return intakeNonIntegratedProductRepository.findBySpu(spu) + } + + async ensureSeriesComponentDetailProduct( + assetSeriesId: string, + user: AuthUser, + ): Promise { + const seriesRecord = await assetSeriesRepository.findById(assetSeriesId) + if (!seriesRecord || !seriesRecord.isActive) { + throw new AppError(ErrorCode.VALIDATION_FAILED, '系列不存在或已停用') + } + + const series = toAssetSeriesDTO(seriesRecord) + const spu = buildSeriesComponentDetailSpu(series.code) + const sourceSeriesName = buildSeriesComponentSourceSeriesName(series) + const existingRecord = await this.findSeriesComponentDetailRecord(series) + if (existingRecord) { + const variants = (await assetVariantRepository.findActiveBySeriesCode(series.code)).map( + (variant) => toAssetVariantDTO(variant), + ) + await this.syncSeriesComponentDevelopmentPayloadsAfterMissingVariantBackfill({ + seriesCode: series.code, + variants, + updatedById: user.id, + }) + + return ( + readSeriesComponentDetailSummaryFromRecord(existingRecord, false) ?? { + productId: existingRecord.id, + spu, + sourceSeriesCode: series.code.trim().toUpperCase(), + sourceSeriesName, + created: false, + } + ) + } + + const variants = (await assetVariantRepository.findActiveBySeriesCode(series.code)).map( + (variant) => toAssetVariantDTO(variant), + ) + const product = buildSeriesComponentDetailProductPayload({ + series, + variants, + user, + }) + const savedProduct = await intakeNonIntegratedProductService.save(product, user) + + return { + productId: savedProduct.id, + spu, + sourceSeriesCode: series.code.trim().toUpperCase(), + sourceSeriesName, + created: true, + } + } + async createSeries(input: CreateAssetSeriesInput): Promise { const name = input.name.trim() if (!name) { @@ -1837,12 +2751,17 @@ class AssetCenterService { options?: VariantThumbnailRenderOptions, ): Promise { const variant = await this.createVariantInternal(input) - return this.maybeGenerateVariantThumbnail({ + const finalVariant = await this.maybeGenerateVariantThumbnail({ variant, renderBaseUrl: options?.renderBaseUrl, updatedBy: input.createdBy ?? null, skip: options?.skipThumbnail || hasUsableVariantThumbnail(input.thumbnailUrl), }) + await this.syncSeriesComponentDevelopmentPayloadsAfterVariantCreate({ + variant: finalVariant, + updatedById: input.createdBy ?? null, + }) + return finalVariant } async createVariantWithSimilarity( @@ -1887,6 +2806,11 @@ class AssetCenterService { detail: '整理规格款、缩略图和相似候选结果', }) + await this.syncSeriesComponentDevelopmentPayloadsAfterVariantCreate({ + variant, + updatedById: input.createdBy ?? null, + }) + return { variant, similarCandidates: similarity.similarCandidates, @@ -1918,10 +2842,26 @@ class AssetCenterService { : null) await ensureFinishExists(resolvedFinishId) + const dimensionSourceVariant = input.inheritedFromVariantId + ? await assetVariantRepository.findByIdWithRelations(input.inheritedFromVariantId) + : null + if (input.inheritedFromVariantId && !dimensionSourceVariant) { + throw new AppError(ErrorCode.ASSET_VARIANT_NOT_FOUND, '继承来源规格款不存在') + } + const inheritedDimensions = normalizeDimensionRecord(dimensionSourceVariant?.dimensions) + const resolvedDimensions = resolveVariantDimensionsForCreate({ + assetType: family.type, + inputDimensions: input.dimensions, + inputBusinessData: input.businessData, + inheritedDimensions, + inheritedBusinessData: dimensionSourceVariant?.businessData, + sizeLabel: input.sizeLabel ?? dimensionSourceVariant?.sizeLabel, + }) + const identityKey = buildAssetVariantIdentityKey({ assetType: family.type, code, - dimensions: input.dimensions, + dimensions: resolvedDimensions, substrateId: input.substrateId ?? null, finishId: resolvedFinishId, }) @@ -1953,7 +2893,7 @@ class AssetCenterService { input.estimatedCostPrice ?? await computeEstimatedCostPrice({ substrateId: input.substrateId ?? null, - dimensions: input.dimensions, + dimensions: resolvedDimensions, lossFactor: resolvedLossFactor, }) const resolvedBusinessData = resolveBusinessDataForVariantCreate({ @@ -1992,7 +2932,7 @@ class AssetCenterService { sizeLabel: trimOrNull(input.sizeLabel), substrate: input.substrateId ? { connect: { id: input.substrateId } } : undefined, finish: resolvedFinishId ? { connect: { id: resolvedFinishId } } : undefined, - dimensions: input.dimensions as Prisma.InputJsonValue, + dimensions: resolvedDimensions as Prisma.InputJsonValue, modelUrl: input.modelUrl.trim(), thumbnailUrl: trimOrNull(input.thumbnailUrl), barcode: commercialFields.barcode, @@ -2339,10 +3279,33 @@ class AssetCenterService { }) } + const sharedFieldUpdatedVariants = + await this.syncSharedSkuFieldsToSiblingVariants({ + variant: finalVariant, + updatedById: input.updatedBy ?? null, + }) + await this.enqueueVariantSkuSync(finalVariant, 'VARIANT_UPDATED', { updatedBy: input.updatedBy ?? null, thumbnailRegenerated: didModelUrlChange || didRenderConfigChange, }) + await this.syncSeriesComponentDevelopmentPayloadsAfterVariantUpdate({ + variant: finalVariant, + updatedById: input.updatedBy ?? null, + }) + await Promise.all( + sharedFieldUpdatedVariants.map(async (variant) => { + await this.enqueueVariantSkuSync(variant, 'VARIANT_UPDATED', { + updatedBy: input.updatedBy ?? null, + reason: 'SHARED_SKU_FIELDS_UPDATED', + sourceVariantId: finalVariant.id, + }) + await this.syncSeriesComponentDevelopmentPayloadsAfterVariantUpdate({ + variant, + updatedById: input.updatedBy ?? null, + }) + }), + ) return finalVariant } @@ -2395,7 +3358,7 @@ class AssetCenterService { } async deleteFamily(id: string, deletedById?: string | null): Promise { - const existing = await assetFamilyRepository.findById(id) + const existing = await assetFamilyRepository.findWithRelationsById(id) if (!existing) { throw new AppError(ErrorCode.ASSET_FAMILY_NOT_FOUND, '资产族不存在') } @@ -2404,6 +3367,11 @@ class AssetCenterService { } const deletedAt = new Date() + const originalFamilyCode = getRestorableAssetFamilyCode({ + code: existing.code, + metadata: existing.metadata, + }) + const seriesCode = existing.assetSeries?.code ?? '' const activeVariants = await prisma.assetVariant.findMany({ where: { assetFamilyId: id, @@ -2425,6 +3393,12 @@ class AssetCenterService { deletedAt, deletedById: deletedById ?? null, lastModifiedById: deletedById ?? existing.lastModifiedById ?? null, + code: buildDeletedAssetVariantUniqueValue(existing.code, id, deletedAt), + metadata: buildSoftDeletedAssetFamilyMetadata({ + metadata: existing.metadata, + originalCode: originalFamilyCode, + deletedAt, + }) as Prisma.InputJsonValue, }, }) @@ -2456,10 +3430,315 @@ class AssetCenterService { }) } }) + + await this.compactFamilyCodesForSeries(seriesCode, deletedById ?? null) + } + + private async syncSeriesComponentDevelopmentPayloadsAfterVariantUpdate(input: { + variant: AssetVariantDTO + updatedById?: string | null + }): Promise { + const records = await intakeNonIntegratedProductRepository.listActive({ + payload: { + path: ['metadata', 'componentDetailType'], + equals: SERIES_COMPONENT_DETAIL_METADATA_TYPE, + }, + }) + + await Promise.all( + records.map(async (record) => { + if (!isSeriesComponentDevelopmentPayload(record.payload)) return + const currentItems = Array.isArray(record.payload.skuItems) + ? record.payload.skuItems + : [] + if (currentItems.length === 0) return + + let changed = false + const nextItems = currentItems.map((item, index) => { + if (!isSeriesComponentAssetSkuPayloadItem(item)) return item + const sourceSkuId = typeof item.sourceSkuId === 'string' ? item.sourceSkuId.trim() : '' + if (sourceSkuId !== input.variant.id) return item + + changed = true + return updateSeriesComponentSkuPayloadItemFromVariant( + item, + input.variant, + index + 1, + ) + }) + + if (!changed) return + + const updatedAt = new Date().toISOString() + await intakeNonIntegratedProductRepository.updatePayloadByUser( + record.id, + { + ...record.payload, + skuItems: nextItems, + skuBatchCount: getSeriesComponentSkuBatchCount(nextItems), + updatedAt, + updatedBy: input.updatedById ?? record.updatedBy, + } as Prisma.InputJsonValue, + input.updatedById ?? record.updatedBy, + ) + }), + ) + } + + private async syncSharedSkuFieldsToSiblingVariants(input: { + variant: AssetVariantDTO + updatedById?: string | null + }): Promise { + const sourceFields = readVariantSkuContentFields(input.variant) + const sharedFields = SHARED_ASSET_VARIANT_SKU_FIELD_KEYS.reduce>( + (fields, key) => { + if (hasVariantSkuContentField(sourceFields, key)) { + fields[key] = sourceFields[key] ?? '' + } + return fields + }, + {}, + ) + if (Object.keys(sharedFields).length === 0) return [] + + const siblings = await assetVariantRepository.findManyByFamilyIds([ + input.variant.assetFamilyId, + ]) + const updatedVariants: AssetVariantDTO[] = [] + + for (const sibling of siblings) { + if (sibling.id === input.variant.id || sibling.deletedAt) continue + + const businessData = normalizeJsonRecord(sibling.businessData) ?? {} + const skuContentFields = isRecord( + businessData[ASSET_VARIANT_SKU_CONTENT_BUSINESS_DATA_KEY], + ) + ? { + ...(businessData[ + ASSET_VARIANT_SKU_CONTENT_BUSINESS_DATA_KEY + ] as Record), + } + : {} + + let changed = false + Object.entries(sharedFields).forEach(([key, value]) => { + if (skuContentFields[key] === value) return + skuContentFields[key] = value + changed = true + }) + if (!changed) continue + + const updated = await assetVariantRepository.updateWithRelations(sibling.id, { + businessData: { + ...businessData, + [ASSET_VARIANT_SKU_CONTENT_BUSINESS_DATA_KEY]: skuContentFields, + } as Prisma.InputJsonValue, + lastModifier: input.updatedById + ? { connect: { id: input.updatedById } } + : undefined, + }) + updatedVariants.push(toAssetVariantDTO(updated)) + } + + return updatedVariants + } + + private async syncSeriesComponentDevelopmentPayloadsAfterVariantCreate(input: { + variant: AssetVariantDTO + updatedById?: string | null + }): Promise { + const seriesCode = parseSeriesCodeFromAssetVariantCode(input.variant.code) + if (!seriesCode) return + + const records = await intakeNonIntegratedProductRepository.listActive({ + payload: { + path: ['metadata', 'componentDetailType'], + equals: SERIES_COMPONENT_DETAIL_METADATA_TYPE, + }, + }) + + await Promise.all( + records.map(async (record) => { + const recordSpu = typeof record.spu === 'string' ? record.spu : '' + if (!isSeriesComponentDevelopmentPayloadForSeries(record.payload, seriesCode, recordSpu)) { + return + } + + const currentItems = Array.isArray(record.payload.skuItems) + ? record.payload.skuItems + : [] + const existingIndex = currentItems.findIndex((item) => { + if (!isSeriesComponentAssetSkuPayloadItem(item)) return false + const sourceSkuId = typeof item.sourceSkuId === 'string' ? item.sourceSkuId.trim() : '' + return sourceSkuId === input.variant.id + }) + + const nextItems = existingIndex >= 0 + ? currentItems.map((item, index) => { + if (index !== existingIndex || !isRecord(item)) return item + return updateSeriesComponentSkuPayloadItemFromVariant( + item, + input.variant, + index + 1, + ) + }) + : [ + ...currentItems, + updateSeriesComponentSkuPayloadItemFromVariant( + createEmptySeriesComponentSkuPayloadItem(input.variant, currentItems.length + 1), + input.variant, + currentItems.length + 1, + ), + ] + + const updatedAt = new Date().toISOString() + await intakeNonIntegratedProductRepository.updatePayloadByUser( + record.id, + { + ...record.payload, + skuItems: nextItems, + skuBatchCount: getSeriesComponentSkuBatchCount(nextItems), + updatedAt, + updatedBy: input.updatedById ?? record.updatedBy, + } as Prisma.InputJsonValue, + input.updatedById ?? record.updatedBy, + ) + }), + ) + } + + private async syncSeriesComponentDevelopmentPayloadsAfterMissingVariantBackfill(input: { + seriesCode: string + variants: AssetVariantDTO[] + updatedById?: string | null + }): Promise { + const seriesCode = input.seriesCode.trim().toUpperCase() + if (!seriesCode || input.variants.length === 0) return + + const records = await intakeNonIntegratedProductRepository.listActive({ + payload: { + path: ['metadata', 'componentDetailType'], + equals: SERIES_COMPONENT_DETAIL_METADATA_TYPE, + }, + }) + + await Promise.all( + records.map(async (record) => { + const recordSpu = typeof record.spu === 'string' ? record.spu : '' + if (!isSeriesComponentDevelopmentPayloadForSeries(record.payload, seriesCode, recordSpu)) { + return + } + + const currentItems = Array.isArray(record.payload.skuItems) + ? record.payload.skuItems + : [] + const existingSourceSkuIds = new Set( + currentItems + .map((item) => { + if (!isSeriesComponentAssetSkuPayloadItem(item)) return '' + return typeof item.sourceSkuId === 'string' ? item.sourceSkuId.trim() : '' + }) + .filter(Boolean), + ) + const missingVariants = input.variants.filter((variant) => !existingSourceSkuIds.has(variant.id)) + if (missingVariants.length === 0) return + + const appendedItems = missingVariants.map((variant, index) => { + const skuSequence = currentItems.length + index + 1 + return updateSeriesComponentSkuPayloadItemFromVariant( + createEmptySeriesComponentSkuPayloadItem(variant, skuSequence), + variant, + skuSequence, + ) + }) + const nextItems = [...currentItems, ...appendedItems] + const updatedAt = new Date().toISOString() + await intakeNonIntegratedProductRepository.updatePayloadByUser( + record.id, + { + ...record.payload, + skuItems: nextItems, + skuBatchCount: getSeriesComponentSkuBatchCount(nextItems), + updatedAt, + updatedBy: input.updatedById ?? record.updatedBy, + } as Prisma.InputJsonValue, + input.updatedById ?? record.updatedBy, + ) + }), + ) + } + + private async syncSeriesComponentDevelopmentPayloadsAfterVariantDelete(input: { + deletedVariantId: string + shiftedVariants: AssetVariantDTO[] + updatedById?: string | null + }): Promise { + const shiftedVariantById = new Map(input.shiftedVariants.map((variant) => [variant.id, variant])) + + const records = await intakeNonIntegratedProductRepository.listActive({ + payload: { + path: ['metadata', 'componentDetailType'], + equals: SERIES_COMPONENT_DETAIL_METADATA_TYPE, + }, + }) + + await Promise.all( + records.map(async (record) => { + if (!isSeriesComponentDevelopmentPayload(record.payload)) return + const currentItems = Array.isArray(record.payload.skuItems) + ? record.payload.skuItems + : [] + if (currentItems.length === 0) return + + let changed = false + const nextItems = currentItems + .filter((item) => { + if (!isSeriesComponentAssetSkuPayloadItem(item)) return true + const sourceSkuId = typeof item.sourceSkuId === 'string' ? item.sourceSkuId.trim() : '' + const keep = sourceSkuId !== input.deletedVariantId + if (!keep) changed = true + return keep + }) + .map((item, index) => { + if (!isRecord(item)) return item + + const sourceSkuId = typeof item.sourceSkuId === 'string' ? item.sourceSkuId.trim() : '' + const shiftedVariant = shiftedVariantById.get(sourceSkuId) + if (!shiftedVariant) { + if (typeof item.skuSequence === 'number' && item.skuSequence === index + 1) { + return item + } + changed = true + return { + ...item, + skuSequence: index + 1, + } + } + + changed = true + return updateSeriesComponentSkuPayloadItemFromVariant(item, shiftedVariant, index + 1) + }) + + if (!changed) return + + const updatedAt = new Date().toISOString() + await intakeNonIntegratedProductRepository.updatePayloadByUser( + record.id, + { + ...record.payload, + skuItems: nextItems, + skuBatchCount: getSeriesComponentSkuBatchCount(nextItems), + updatedAt, + updatedBy: input.updatedById ?? record.updatedBy, + } as Prisma.InputJsonValue, + input.updatedById ?? record.updatedBy, + ) + }), + ) } async deleteVariant(id: string, deletedById?: string | null): Promise { - const existing = await assetVariantRepository.findById(id) + const existing = await assetVariantRepository.findByIdWithRelations(id) if (!existing) { throw new AppError(ErrorCode.ASSET_VARIANT_NOT_FOUND, '规格款不存在') } @@ -2490,6 +3769,74 @@ class AssetCenterService { deletedAt, }) as Prisma.InputJsonValue, } as Prisma.AssetVariantUpdateInput) + + const seriesCode = existing.assetFamily.assetSeries?.code ?? '' + const deletedSequence = parseAssetVariantSequence(seriesCode, originalCode) + const shiftedVariants: AssetVariantDTO[] = [] + + if (seriesCode && deletedSequence) { + const activeSeriesVariants = await assetVariantRepository.findActiveBySeriesCode(seriesCode) + const variantsToShift = activeSeriesVariants + .map((variant) => ({ + variant, + sequence: parseAssetVariantSequence(seriesCode, variant.code), + })) + .filter( + (entry): entry is { variant: AssetVariantWithRelations; sequence: number } => + entry.variant.id !== id && + entry.sequence !== null && + entry.sequence > deletedSequence, + ) + .sort((left, right) => left.sequence - right.sequence) + + for (const { variant, sequence } of variantsToShift) { + const nextCode = buildAssetVariantCode(seriesCode, sequence - 1) + if (nextCode === variant.code) continue + + const dimensions = isRecord(variant.dimensions) + ? (variant.dimensions as Record) + : {} + const nextIdentityKey = buildAssetVariantIdentityKey({ + assetType: variant.assetType, + code: nextCode, + dimensions, + substrateId: variant.substrateId, + finishId: variant.finishId, + }) + + await assetVariantRepository.releaseDeletedUniqueKeys({ + code: nextCode, + assetFamilyId: variant.assetFamilyId, + identityKey: nextIdentityKey, + }) + + const commercialFields = resolveVariantCommercialFields({ + code: nextCode, + supplierName: variant.supplierName, + supplierCode: variant.supplierCode, + versionNo: variant.versionNo, + }) + await ensureVariantBarcodeAvailable(commercialFields.barcode, variant.id) + + const updated = await assetVariantRepository.updateWithRelations(variant.id, { + code: nextCode, + identityKey: nextIdentityKey, + barcode: commercialFields.barcode, + supplierName: commercialFields.supplierName, + supplierCode: commercialFields.supplierCode, + versionNo: commercialFields.versionNo, + lastModifier: deletedById ? { connect: { id: deletedById } } : undefined, + }) + shiftedVariants.push(toAssetVariantDTO(updated)) + } + } + + await this.syncSeriesComponentDevelopmentPayloadsAfterVariantDelete({ + deletedVariantId: id, + shiftedVariants, + updatedById: deletedById ?? null, + }) + await assetSkuSyncService.enqueueVariantSync({ assetVariantId: id, reason: 'VARIANT_DELETED', @@ -2498,6 +3845,15 @@ class AssetCenterService { deletedById: deletedById ?? null, }, }) + await Promise.all( + shiftedVariants.map((variant) => + this.enqueueVariantSkuSync(variant, 'VARIANT_UPDATED', { + updatedBy: deletedById ?? null, + reason: 'VARIANT_RENUMBERED_AFTER_DELETE', + deletedVariantId: id, + }), + ), + ) } async restoreFamilyFromTrash(id: string): Promise { @@ -2509,6 +3865,18 @@ class AssetCenterService { throw new AppError(ErrorCode.VALIDATION_FAILED, '资产族未在回收站中') } + const restoredFamilyCode = getRestorableAssetFamilyCode({ + code: existing.code, + metadata: existing.metadata, + }) + const duplicateByFamilyCode = await assetFamilyRepository.findByCode(restoredFamilyCode) + if (duplicateByFamilyCode && duplicateByFamilyCode.id !== id) { + throw new AppError( + ErrorCode.ASSET_FAMILY_CODE_EXISTS, + `资产族编码「${restoredFamilyCode}」已被新的资产族使用,不能直接恢复`, + ) + } + const familyDeletedAt = existing.deletedAt const variantsToRestore = await prisma.assetVariant.findMany({ where: { @@ -2588,6 +3956,8 @@ class AssetCenterService { data: { deletedAt: null, deletedById: null, + code: restoredFamilyCode, + metadata: toJsonValue(clearSoftDeletedAssetFamilyMetadata(existing.metadata)), }, include: assetFamilyRelationInclude, }) @@ -2922,6 +4292,7 @@ export type { AssetFamilyDTO, AssetReviewActionInput, AssetSeriesDTO, + AssetSeriesComponentDetailSummaryDTO, AssetSeriesSummaryDTO, AssetVariantDTO, CreateAssetVariantResultDTO, diff --git a/furniture-3d-system/src/server/services/asset-center.service.types.ts b/furniture-3d-system/src/server/services/asset-center.service.types.ts index fd009af4..0ac9d142 100644 --- a/furniture-3d-system/src/server/services/asset-center.service.types.ts +++ b/furniture-3d-system/src/server/services/asset-center.service.types.ts @@ -35,6 +35,14 @@ export interface AssetSeriesSummaryDTO { name: string } +export interface AssetSeriesComponentDetailSummaryDTO { + productId: string + spu: string + sourceSeriesCode: string + sourceSeriesName: string + created: boolean +} + export interface CreateAssetSeriesInput { name: string code?: string | null diff --git a/furniture-3d-system/src/server/services/draft-group.service.ts b/furniture-3d-system/src/server/services/draft-group.service.ts index 995bc9a1..d38ecc18 100644 --- a/furniture-3d-system/src/server/services/draft-group.service.ts +++ b/furniture-3d-system/src/server/services/draft-group.service.ts @@ -145,24 +145,107 @@ function addConflict( conflicts[conflict.field] = [...(conflicts[conflict.field] ?? []), conflict] } -function formatDimensionsForBasicInfo(dimensions: Record | null | undefined): string { - if (!dimensions) return '' - const labels: Record = { - length: '长', - width: '宽', - height: '高', - depth: '深', - thickness: '厚', +function readPositiveNumber(value: unknown): number | null { + return typeof value === 'number' && Number.isFinite(value) && value > 0 + ? value + : null +} + +function readVector3(value: unknown, fallback: [number, number, number]) { + if (!Array.isArray(value) || value.length < 3) return fallback + const vector = value.slice(0, 3) + return vector.every((item) => typeof item === 'number' && Number.isFinite(item)) + ? (vector as [number, number, number]) + : fallback +} + +function readDimensionValue( + dimensions: Record, + keys: string[], +) { + for (const key of keys) { + const value = readPositiveNumber(dimensions[key]) + if (value !== null) return value } - const order = ['length', 'width', 'height', 'depth', 'thickness'] - return Object.entries(dimensions) - .filter((entry): entry is [string, number] => { - const [, value] = entry - return typeof value === 'number' && Number.isFinite(value) && value > 0 - }) - .sort(([left], [right]) => order.indexOf(left) - order.indexOf(right)) - .map(([key, value]) => `${labels[key] ?? key}${Number(value.toFixed(2))}mm`) - .join(' / ') + + return null +} + +function rotateLocalHalfSize( + halfSize: [number, number, number], + rotation: [number, number, number], +) { + const [x, y, z] = rotation + const cx = Math.cos(x) + const sx = Math.sin(x) + const cy = Math.cos(y) + const sy = Math.sin(y) + const cz = Math.cos(z) + const sz = Math.sin(z) + const matrix = [ + [cy * cz, cz * sx * sy - cx * sz, sx * sz + cx * cz * sy], + [cy * sz, cx * cz + sx * sy * sz, cx * sy * sz - cz * sx], + [-sy, cy * sx, cx * cy], + ] + + return matrix.map((row) => + row.reduce((total, value, index) => total + Math.abs(value) * halfSize[index], 0), + ) as [number, number, number] +} + +function formatCentimeterSize(valueMm: number) { + const valueCm = Math.round((valueMm / 10) * 10) / 10 + return Number.isInteger(valueCm) ? String(valueCm) : valueCm.toFixed(1) +} + +function buildPreSkuOverallSizeSuggestion(preSku: PreSkuWithRelations): string { + const displaySummary = isRecord(preSku.displaySummary) ? preSku.displaySummary : null + const assemblyWorkspace = isRecord(displaySummary?.assemblyWorkspace) + ? displaySummary.assemblyWorkspace + : null + const nodes = Array.isArray(assemblyWorkspace?.nodes) + ? assemblyWorkspace.nodes + : [] + + let min = [Infinity, Infinity, Infinity] + let max = [-Infinity, -Infinity, -Infinity] + let boundedNodeCount = 0 + let hasExplicitHeightDimension = false + + nodes.forEach((node) => { + if (!isRecord(node) || node.zone === 'staging') return + const dimensions = isRecord(node.dimensions) ? node.dimensions : null + if (!dimensions) return + + const localSize: [number | null, number | null, number | null] = [ + readDimensionValue(dimensions, ['length', 'diameter', 'width']), + readDimensionValue(dimensions, ['height', 'thickness', 'depth']), + readDimensionValue(dimensions, ['width', 'depth', 'thickness']), + ] + if (localSize.some((value) => value === null)) return + + const position = readVector3(node.position, [0, 0, 0]) + const rotation = readVector3(node.rotation, [0, 0, 0]) + const scale = readVector3(node.scale, [1, 1, 1]) + const halfSize = rotateLocalHalfSize( + localSize.map((value, index) => ( + ((value as number) * Math.abs(scale[index])) / 2 + )) as [number, number, number], + rotation, + ) + + min = min.map((value, index) => Math.min(value, position[index] - halfSize[index])) + max = max.map((value, index) => Math.max(value, position[index] + halfSize[index])) + boundedNodeCount += 1 + hasExplicitHeightDimension ||= readPositiveNumber(dimensions.height) !== null + }) + + if (boundedNodeCount < 2 || !hasExplicitHeightDimension) return '' + + const size = max.map((value, index) => value - min[index]) + if (size.some((value) => !Number.isFinite(value) || value <= 0)) return '' + + return `${formatCentimeterSize(size[0])} / ${formatCentimeterSize(size[2])} / ${formatCentimeterSize(size[1])}` } function resolvePrimaryVariantId(preSku: PreSkuWithRelations): string | null { @@ -561,7 +644,7 @@ class DraftGroupService { setIfPresent(suggestions, 'model', snapshot?.model) setIfPresent(suggestions, 'formalSkuCode', snapshot?.specCode) setIfPresent(suggestions, 'barcode', snapshot?.barcode) - setIfPresent(suggestions, 'size', formatDimensionsForBasicInfo(snapshot?.size)) + setIfPresent(suggestions, 'size', buildPreSkuOverallSizeSuggestion(preSku)) setIfPresent(suggestions, 'color', snapshot?.color) setIfPresent(suggestions, 'material', snapshot?.material) setIfPresent(suggestions, 'specName', snapshot?.specName) diff --git a/furniture-3d-system/src/server/services/index.ts b/furniture-3d-system/src/server/services/index.ts index 7464d463..6da5791d 100644 --- a/furniture-3d-system/src/server/services/index.ts +++ b/furniture-3d-system/src/server/services/index.ts @@ -165,6 +165,7 @@ export type { AssetFamilyDTO, AssetReviewActionInput, AssetSeriesDTO, + AssetSeriesComponentDetailSummaryDTO, AssetSeriesSummaryDTO, AssetVariantDTO, CreateAssetVariantResultDTO, diff --git a/furniture-3d-system/src/server/services/intake-non-integrated-product.service.ts b/furniture-3d-system/src/server/services/intake-non-integrated-product.service.ts index 08b46d83..e1607001 100644 --- a/furniture-3d-system/src/server/services/intake-non-integrated-product.service.ts +++ b/furniture-3d-system/src/server/services/intake-non-integrated-product.service.ts @@ -12,15 +12,25 @@ import { type NonIntegratedDocumentWorkspaceApprovalMap, type NonIntegratedDocumentWorkspaceConfirmationMap, type NonIntegratedProductRecord, + type NonIntegratedSkuItem, type NonIntegratedUploadFile, } from '@/app/intake/non-integrated/nonIntegratedStorage' import { normalizeNonIntegratedAssetUrl } from '@/app/intake/non-integrated/nonIntegratedAssetUrl' +import { + buildAssetVariantBarcode, + DEFAULT_SKU_VERSION_NO, + normalizeSkuVersionNo, +} from '@/lib/open-product/asset-coding' import { AppError, ErrorCode } from '@/server/core/errors' import type { AuthUser } from '@/server/core/types' import { intakeNonIntegratedProductRepository, type IntakeNonIntegratedProductRepositoryClass, } from '../repositories/intake-non-integrated-product.repository' +import { + assetVariantRepository, + type AssetVariantWithRelations, +} from '../repositories/asset-center.repository' import { draftGroupRepository, preSkuRepository, @@ -128,6 +138,7 @@ export type IntakeNonIntegratedProductListParams = { productDevelopmentKind?: 'product' | 'series' productKind?: 'all' | 'new' | 'stock' quickScope?: 'all' | 'created' | 'pending' + seriesName?: string spu?: string appearanceDesigner?: string structureDesigner?: string @@ -2049,6 +2060,24 @@ function buildSpuSearchWhere(spu: string): Prisma.IntakeNonIntegratedProductWher } } +function buildSeriesNameSearchWhere( + seriesName: string | undefined, +): Prisma.IntakeNonIntegratedProductWhereInput | null { + const keyword = trimListFilter(seriesName) + if (!keyword) return null + + return { + OR: [ + jsonTextContains(['openingReference', 'productName'], keyword), + jsonTextContains(['openingReference', 'temporaryCode'], keyword), + jsonTextContains(['metadata', 'sourceSeriesName'], keyword), + jsonTextContains(['metadata', 'sourceSeriesCode'], keyword), + { spu: { contains: keyword, mode: 'insensitive' } }, + { spuBase: { contains: keyword, mode: 'insensitive' } }, + ], + } +} + function buildStockTextSearchWhere( value: string | undefined, paths: string[][], @@ -2303,6 +2332,7 @@ function buildListFilterWhere( const filters = [ buildDevelopmentKindWhere(params.productDevelopmentKind), buildProductKindWhere(params.productKind), + buildSeriesNameSearchWhere(params.seriesName), buildSpuSearchWhere(params.spu ?? ''), buildQuickScopeWhere(params.quickScope, user), ...buildStockSourceSearchWhere(params), @@ -2398,6 +2428,339 @@ function readSourceSkuIdSet(product: SharedNonIntegratedProductRecord | null | u ) } +const SERIES_COMPONENT_DETAIL_METADATA_TYPE = 'asset-series-components' +const SERIES_COMPONENT_ASSET_SKU_SOURCE = 'asset_series_component' +const ASSET_VARIANT_SOURCE_TABLE = 'asset_variant' +const ASSET_VARIANT_SKU_CONTENT_BUSINESS_DATA_KEY = 'skuContentFields' +const NON_BOARD_ASSET_BOARD_MATERIAL_TYPE = '非ENF级' +const DEFAULT_ASSET_VARIANT_ATTRIBUTE_CODE = 'A' +const DEFAULT_ASSET_VARIANT_INSTALL_METHOD = '拆装' +const DEFAULT_ASSET_VARIANT_EXECUTE_STANDARD = 'GB/T3324-2024' +const DEFAULT_STEEL_ASSET_VARIANT_EXECUTE_STANDARD = 'GB/T3325-2024' +const DEFAULT_ASSET_VARIANT_NATIONAL_STANDARD_COMPLIANT = '是' +const DEFAULT_ASSET_VARIANT_SALES_STATUS = '销售' + +function readPayloadString(item: Record, key: string): string { + const value = item[key] + if (typeof value === 'string') return value.trim() + if (typeof value === 'number' && Number.isFinite(value)) return String(value) + return '' +} + +function readVariantSkuContentFields( + variant: AssetVariantWithRelations, +): Record { + const businessData = isRecord(variant.businessData) ? variant.businessData : null + const rawFields = businessData?.[ASSET_VARIANT_SKU_CONTENT_BUSINESS_DATA_KEY] + if (!isRecord(rawFields)) return {} + + return Object.entries(rawFields).reduce>((fields, [key, value]) => { + if (typeof value === 'string') { + fields[key] = value.trim() + } else if (typeof value === 'number' && Number.isFinite(value)) { + fields[key] = String(value) + } + return fields + }, {}) +} + +function getVariantSkuContentField( + fields: Record, + key: string, + fallback = '', +): string { + return Object.prototype.hasOwnProperty.call(fields, key) + ? fields[key] ?? '' + : fallback +} + +function hasVariantSkuContentField(fields: Record, key: string): boolean { + return Object.prototype.hasOwnProperty.call(fields, key) +} + +function getVariantSkuContentFieldWithDefault( + fields: Record, + key: string, + defaultValue: string, +): string { + return hasVariantSkuContentField(fields, key) ? fields[key] ?? '' : defaultValue +} + +function getDefaultVariantExecuteStandard(assetType: string): string { + return assetType === 'COMPONENT' || assetType === 'HARDWARE' + ? DEFAULT_STEEL_ASSET_VARIANT_EXECUTE_STANDARD + : DEFAULT_ASSET_VARIANT_EXECUTE_STANDARD +} + +function getAssetVariantBoardMaterialTypeForSku( + _assetType: string, + fields: Record, +): string { + return getVariantSkuContentFieldWithDefault( + fields, + 'boardMaterialType', + NON_BOARD_ASSET_BOARD_MATERIAL_TYPE, + ) +} + +function parseSeriesComponentBatchNo(value: string, fallback: number): number { + const matched = value.trim().match(/\d+/) + const parsed = matched ? Number.parseInt(matched[0] ?? '', 10) : NaN + return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback +} + +function createEmptyAssetSeriesComponentSkuItem( + variant: AssetVariantWithRelations, + skuSequence: number, +): NonIntegratedSkuItem { + return { + id: `asset-variant-${variant.id}`, + skuSequence, + batchNo: 1, + packageGroupId: '', + packageSuffix: '', + image: '', + imageName: '', + model: '', + skuCode: '', + setCount: '1', + specName: '', + barcode: '', + size: '', + color: '', + material: '', + boardMaterialType: '', + versionNo: DEFAULT_SKU_VERSION_NO, + attributeCode: '', + drawingId: '', + installMethod: '', + executeStandard: '', + nationalStandardCompliant: '', + manufacturer: '', + manufacturerCode: '', + salesStatus: '', + tagMaterial: '', + model3dFileName: '', + model3dDataUrl: '', + model3dNodeOffsets: {}, + model3dNodeRotations: {}, + model3dNodeMaterialIds: {}, + model3dUvConfig: null, + model3dPreviewNodes: [], + componentDetails: [], + holePoints: [], + source: SERIES_COMPONENT_ASSET_SKU_SOURCE, + sourceTable: ASSET_VARIANT_SOURCE_TABLE, + sourceSkuId: variant.id, + contentLocked: false, + } +} + +function updateAssetSeriesComponentSkuItemFromVariant( + item: NonIntegratedSkuItem, + variant: AssetVariantWithRelations, + skuSequence: number, +): NonIntegratedSkuItem { + const itemRecord = item as unknown as Record + const normalizedCode = variant.code.trim().toUpperCase() + const normalizedModel = variant.assetFamily.code.trim().toUpperCase() + const normalizedModelUrl = variant.modelUrl.trim() + const thumbnailUrl = variant.thumbnailUrl?.trim() ?? '' + const skuContentFields = readVariantSkuContentFields(variant) + const rawVersionNo = hasVariantSkuContentField(skuContentFields, 'versionNo') + ? skuContentFields.versionNo ?? '' + : (variant.versionNo ?? readPayloadString(itemRecord, 'versionNo')) || DEFAULT_SKU_VERSION_NO + const versionNo = rawVersionNo.trim() ? normalizeSkuVersionNo(rawVersionNo) : '' + const manufacturerCode = getVariantSkuContentField( + skuContentFields, + 'manufacturerCode', + variant.supplierCode ?? readPayloadString(itemRecord, 'manufacturerCode'), + ).trim().toUpperCase() + const barcode = getVariantSkuContentField( + skuContentFields, + 'barcode', + variant.barcode ?? ( + versionNo && + buildAssetVariantBarcode({ + variantCode: normalizedCode, + supplierCode: manufacturerCode, + versionNo, + }) || + readPayloadString(itemRecord, 'barcode') + ), + ).trim().toUpperCase() + const batchNo = parseSeriesComponentBatchNo( + getVariantSkuContentField( + skuContentFields, + 'batchNo', + readPayloadString(itemRecord, 'batchNo'), + ), + 1, + ) + const attributeCode = getVariantSkuContentFieldWithDefault( + skuContentFields, + 'attributeCode', + DEFAULT_ASSET_VARIANT_ATTRIBUTE_CODE, + ).toUpperCase() + const drawingIdFallback = `${getVariantSkuContentField(skuContentFields, 'model', normalizedModel) || normalizedModel}${attributeCode}${versionNo}` + + return { + ...item, + skuSequence, + model: getVariantSkuContentField(skuContentFields, 'model', normalizedModel) || normalizedModel, + skuCode: normalizedCode, + barcode, + setCount: getVariantSkuContentField( + skuContentFields, + 'setCount', + readPayloadString(itemRecord, 'setCount') || '1', + ), + specName: getVariantSkuContentField( + skuContentFields, + 'specName', + readPayloadString(itemRecord, 'specName') || variant.name.trim(), + ), + size: getVariantSkuContentField( + skuContentFields, + 'size', + readPayloadString(itemRecord, 'size') || (variant.sizeLabel ?? ''), + ), + color: getVariantSkuContentField( + skuContentFields, + 'color', + readPayloadString(itemRecord, 'color'), + ), + material: getVariantSkuContentField( + skuContentFields, + 'material', + readPayloadString(itemRecord, 'material'), + ), + boardMaterialType: getAssetVariantBoardMaterialTypeForSku( + variant.assetType, + skuContentFields, + ), + versionNo, + attributeCode, + drawingId: getVariantSkuContentField( + skuContentFields, + 'drawingId', + readPayloadString(itemRecord, 'drawingId') || drawingIdFallback, + ).toUpperCase(), + installMethod: getVariantSkuContentFieldWithDefault( + skuContentFields, + 'installMethod', + DEFAULT_ASSET_VARIANT_INSTALL_METHOD, + ), + executeStandard: getVariantSkuContentFieldWithDefault( + skuContentFields, + 'executeStandard', + getDefaultVariantExecuteStandard(variant.assetType), + ), + nationalStandardCompliant: getVariantSkuContentFieldWithDefault( + skuContentFields, + 'nationalStandardCompliant', + DEFAULT_ASSET_VARIANT_NATIONAL_STANDARD_COMPLIANT, + ), + manufacturer: getVariantSkuContentField( + skuContentFields, + 'manufacturer', + readPayloadString(itemRecord, 'manufacturer') || (variant.supplierName ?? ''), + ), + manufacturerCode, + salesStatus: getVariantSkuContentFieldWithDefault( + skuContentFields, + 'salesStatus', + DEFAULT_ASSET_VARIANT_SALES_STATUS, + ), + batchNo, + image: thumbnailUrl, + imageName: thumbnailUrl ? `${normalizedCode}-thumb` : '', + model3dFileName: normalizedModelUrl ? `${normalizedCode}-model.glb` : '', + model3dDataUrl: normalizedModelUrl, + source: SERIES_COMPONENT_ASSET_SKU_SOURCE, + sourceTable: ASSET_VARIANT_SOURCE_TABLE, + sourceSkuId: variant.id, + } +} + +function readAssetSeriesComponentSourceSeriesCode( + product: SharedNonIntegratedProductRecord, +): string { + const metadata = isRecord(product.metadata) ? product.metadata : null + if (metadata?.componentDetailType !== SERIES_COMPONENT_DETAIL_METADATA_TYPE) return '' + + const metadataSeriesCode = + typeof metadata.sourceSeriesCode === 'string' + ? metadata.sourceSeriesCode.trim().toUpperCase() + : '' + if (metadataSeriesCode) return metadataSeriesCode + + const matched = product.spu.trim().toUpperCase().match(/^([A-Z][A-Z0-9]*)-SPJ$/) + return matched?.[1] ?? '' +} + +function getSkuBatchCountFromItems( + items: NonIntegratedSkuItem[], + fallbackBatchCount?: number, +): number { + const maxBatchNo = Math.max( + 1, + ...items.map((item) => + typeof item.batchNo === 'number' && Number.isFinite(item.batchNo) + ? Math.max(1, Math.floor(item.batchNo)) + : 1, + ), + ) + return Math.max( + maxBatchNo, + typeof fallbackBatchCount === 'number' && Number.isFinite(fallbackBatchCount) + ? Math.max(1, Math.floor(fallbackBatchCount)) + : 1, + ) +} + +async function mergeMissingAssetSeriesComponentSkuItems( + product: SharedNonIntegratedProductRecord, +): Promise { + const seriesCode = readAssetSeriesComponentSourceSeriesCode(product) + if (!seriesCode) return product + + const activeVariants = await assetVariantRepository.findActiveBySeriesCode(seriesCode) + if (activeVariants.length === 0) return product + + const existingSourceSkuIds = new Set() + const existingSkuCodes = new Set() + product.skuItems.forEach((item) => { + const sourceSkuId = item.sourceSkuId?.trim() + if (sourceSkuId) existingSourceSkuIds.add(sourceSkuId) + + const skuCode = item.skuCode?.trim().toUpperCase() + if (skuCode) existingSkuCodes.add(skuCode) + }) + + const missingVariants = activeVariants.filter((variant) => { + const variantCode = variant.code.trim().toUpperCase() + return !existingSourceSkuIds.has(variant.id) && !existingSkuCodes.has(variantCode) + }) + if (missingVariants.length === 0) return product + + const appendedItems = missingVariants.map((variant, index) => { + const skuSequence = product.skuItems.length + index + 1 + return updateAssetSeriesComponentSkuItemFromVariant( + createEmptyAssetSeriesComponentSkuItem(variant, skuSequence), + variant, + skuSequence, + ) + }) + const skuItems = [...product.skuItems, ...appendedItems] + + return { + ...product, + skuItems, + skuBatchCount: getSkuBatchCountFromItems(skuItems, product.skuBatchCount), + } +} + function hasIncomingSkuItems(productInput: unknown) { if (!isRecord(productInput)) return false const product = isRecord(productInput.product) ? productInput.product : productInput @@ -2713,7 +3076,7 @@ class IntakeNonIntegratedProductService { const scopedDepartmentId = intakeNonIntegratedScopeService.getScopedDepartmentId(user) const scopedTeamId = intakeNonIntegratedScopeService.getScopedTeamId(user) - const persistedProduct = deletedRecordToRestore + const persistedProductBase = deletedRecordToRestore ? { ...normalizedProduct, id: deletedRecordToRestore.id, @@ -2727,6 +3090,9 @@ class IntakeNonIntegratedProductService { createdBy: existingRecord?.createdBy ?? user.id, updatedBy: user.id, } + const persistedProduct = await mergeMissingAssetSeriesComponentSkuItems( + persistedProductBase, + ) const shouldSyncRemovedSourceSkuDraftGroups = Boolean(existingRecord) && hasIncomingSkuItems(productInput) diff --git a/furniture-3d-system/src/server/services/pre-sku-materialization.service.ts b/furniture-3d-system/src/server/services/pre-sku-materialization.service.ts index 47992a40..acdb2e06 100644 --- a/furniture-3d-system/src/server/services/pre-sku-materialization.service.ts +++ b/furniture-3d-system/src/server/services/pre-sku-materialization.service.ts @@ -172,7 +172,16 @@ function normalizeWorkspaceNodes(workspace: AssemblyWorkspaceSnapshot) { return workspace.nodes.filter((node) => node.zone === 'main') } -function assertAllMainNodesHaveAvailableVariants( +function shouldIncludeNodeInPreSkuSelection(node: AssemblyWorkspaceNode) { + if (node.zone === 'main') return true + return node.source === 'connector' || node.role === 'connector' +} + +function normalizePreSkuSelectionNodes(workspace: AssemblyWorkspaceSnapshot) { + return workspace.nodes.filter(shouldIncludeNodeInPreSkuSelection) +} + +function assertAllSelectionNodesHaveAvailableVariants( nodes: AssemblyWorkspaceNode[], variantsById: Map, ) { @@ -265,7 +274,7 @@ class PreSkuMaterializationService { const selectedVariantIds = Array.from( new Set( assemblies.flatMap((assembly) => - normalizeWorkspaceNodes(assembly.assemblyWorkspace).map((node) => node.variantId), + normalizePreSkuSelectionNodes(assembly.assemblyWorkspace).map((node) => node.variantId), ), ), ) @@ -290,9 +299,10 @@ class PreSkuMaterializationService { } const mainNodes = normalizeWorkspaceNodes(assembly.assemblyWorkspace) - assertAllMainNodesHaveAvailableVariants(mainNodes, variantsById) - const variantSelection = buildVariantSelection(mainNodes, variantsById) - const bom = aggregateBom(mainNodes, variantsById) + const selectionNodes = normalizePreSkuSelectionNodes(assembly.assemblyWorkspace) + assertAllSelectionNodesHaveAvailableVariants(selectionNodes, variantsById) + const variantSelection = buildVariantSelection(selectionNodes, variantsById) + const bom = aggregateBom(selectionNodes, variantsById) const totalWeight = toMoney( bom.reduce((sum, item) => sum + (item.totalWeightKg ?? 0), 0), )