diff --git a/autocad-plugin/FurnitureExporter/Commands.cs b/autocad-plugin/FurnitureExporter/Commands.cs index a5b97b74..39ece423 100644 --- a/autocad-plugin/FurnitureExporter/Commands.cs +++ b/autocad-plugin/FurnitureExporter/Commands.cs @@ -72,6 +72,8 @@ public class Commands public List Holes { get; } = new(); public List HoleGroups { get; } = new(); public List MountPatterns { get; } = new(); + public List SnapPatterns { get; } = new(); + public List SnapSurfaces { get; } = new(); public int LogicalHoleCount { get; set; } public List EdgeFeatures { get; } = new(); public List ExcludedHoles { get; } = new(); @@ -339,6 +341,7 @@ public class Commands HoleGrouping.AttachGroupsToPanels(panels, holeGroups); var mountPatterns = MountPatternAnalyzer.BuildMountPatterns(panels, allHoles, holeGroups); MountPatternAnalyzer.AttachPatternsToPanels(panels, mountPatterns); + var snapSurfaces = SnapSurfaceBuilder.BuildSnapSurfaces(panels); var logicalHoleCount = HoleGrouping.ComputeLogicalHoleCount(allHoles); foreach (var hole in allHoles) @@ -357,6 +360,8 @@ public class Commands result.Holes.AddRange(allHoles); result.HoleGroups.AddRange(holeGroups); result.MountPatterns.AddRange(mountPatterns); + result.SnapPatterns.AddRange(mountPatterns); + result.SnapSurfaces.AddRange(snapSurfaces); result.LogicalHoleCount = logicalHoleCount; result.EdgeFeatures.AddRange(allEdgeFeatures); result.ExcludedHoles.AddRange(panelAnalyzer.ExcludedHoles); @@ -689,6 +694,7 @@ public class Commands HoleGrouping.AttachGroupsToPanels(panels, holeGroups); var mountPatterns = MountPatternAnalyzer.BuildMountPatterns(panels, allHoles, holeGroups); MountPatternAnalyzer.AttachPatternsToPanels(panels, mountPatterns); + var snapSurfaces = SnapSurfaceBuilder.BuildSnapSurfaces(panels); var logicalHoleCount = HoleGrouping.ComputeLogicalHoleCount(allHoles); @@ -736,6 +742,8 @@ public class Commands exportData.Holes = allHoles; exportData.HoleGroups = holeGroups; exportData.MountPatterns = mountPatterns; + exportData.SnapPatterns = mountPatterns; + exportData.SnapSurfaces = snapSurfaces; exportData.LogicalHoleCount = logicalHoleCount; if (panelAnalyzer.ExcludedHoles.Count > 0) @@ -993,6 +1001,8 @@ public class Commands exportData.Holes = panelAnalysis.Holes; exportData.HoleGroups = panelAnalysis.HoleGroups; exportData.MountPatterns = panelAnalysis.MountPatterns; + exportData.SnapPatterns = panelAnalysis.SnapPatterns; + exportData.SnapSurfaces = panelAnalysis.SnapSurfaces; exportData.LogicalHoleCount = panelAnalysis.LogicalHoleCount; exportData.EdgeFeatures = panelAnalysis.EdgeFeatures; exportData.PanelCount = panelAnalysis.Panels.Count; @@ -1032,21 +1042,11 @@ public class Commands if (mode.AnalyzePanels && panelAnalysis.Panels.Count > 0) { - ed.WriteMessage(" [4/5] 生成装配语义..."); - var assemblyAnalyzer = new AssemblySemanticAnalyzer(); - exportData.Assembly = assemblyAnalyzer.Analyze( - panelAnalysis.Panels, - panelAnalysis.Holes, - panelAnalysis.HoleGroups, - exportData.HardwareTypes); - var highConfidenceCount = exportData.Assembly.PanelAssemblies.Count(item => - item.Confidence >= 0.75 && - !string.Equals(item.MountMode, "unknown", StringComparison.OrdinalIgnoreCase)); - ed.WriteMessage($" ✓ ({exportData.Assembly.PanelAssemblies.Count} 个板件语义, {highConfidenceCount} 个高置信)\n"); + ed.WriteMessage(" [4/5] 跳过旧装配语义... ✓ (single_asset 使用 snapPatterns/snapSurfaces)\n"); } else { - ed.WriteMessage(" [4/5] 生成装配语义... ✓ (当前模式无需生成)\n"); + ed.WriteMessage(" [4/5] 跳过旧装配语义... ✓ (当前模式无需生成)\n"); } ed.WriteMessage(" [5/5] 打包文件..."); diff --git a/autocad-plugin/FurnitureExporter/FurnitureExporter.Tests/MountPatternAnalyzerTests.cs b/autocad-plugin/FurnitureExporter/FurnitureExporter.Tests/MountPatternAnalyzerTests.cs index b3ad97a4..0f33131f 100644 --- a/autocad-plugin/FurnitureExporter/FurnitureExporter.Tests/MountPatternAnalyzerTests.cs +++ b/autocad-plugin/FurnitureExporter/FurnitureExporter.Tests/MountPatternAnalyzerTests.cs @@ -24,6 +24,8 @@ namespace FurnitureExporter.Tests Assert.Equal("line_2", pattern.PatternType); Assert.Equal(2, pattern.MinRequiredHoles); Assert.Equal(2, pattern.PreferredHoleCount); + Assert.Single(panel.SnapPatterns); + Assert.Equal(panel.MountPatterns, panel.SnapPatterns); } [Fact] diff --git a/autocad-plugin/FurnitureExporter/FurnitureExporter.Tests/SnapSurfaceBuilderTests.cs b/autocad-plugin/FurnitureExporter/FurnitureExporter.Tests/SnapSurfaceBuilderTests.cs new file mode 100644 index 00000000..92043dbf --- /dev/null +++ b/autocad-plugin/FurnitureExporter/FurnitureExporter.Tests/SnapSurfaceBuilderTests.cs @@ -0,0 +1,103 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Newtonsoft.Json.Serialization; + +namespace FurnitureExporter.Tests +{ + public class SnapSurfaceBuilderTests + { + [Fact] + public void BuildSnapSurfaces_FromBoundingBox_CreatesSixAxisFaces() + { + var panel = CreatePanel("panel_001"); + + var surfaces = SnapSurfaceBuilder.BuildSnapSurfaces(new[] { panel }); + + Assert.Equal(6, surfaces.Count); + Assert.Equal(6, panel.SnapSurfaces.Count); + + var top = Assert.Single(surfaces.Where(surface => surface.Face == "top")); + Assert.Equal("panel_001_snap_top", top.Id); + Assert.Equal("panel_001", top.PanelId); + Assert.Equal(new[] { 0.0, 0.0, 1.0 }, top.Normal); + Assert.Equal(new[] { 0.0, 0.0, 18.0 }, top.Center); + Assert.Equal(18.0, top.Bounds.Min[2]); + Assert.Equal(18.0, top.Bounds.Max[2]); + Assert.Equal(1.0, top.Confidence); + + var front = Assert.Single(surfaces.Where(surface => surface.Face == "front")); + Assert.Equal(new[] { 0.0, -1.0, 0.0 }, front.Normal); + Assert.Equal(-280.0, front.Center[1]); + Assert.Equal(-280.0, front.Bounds.Min[1]); + Assert.Equal(-280.0, front.Bounds.Max[1]); + } + + [Fact] + public void ExportData_ForSingleAsset_EmitsSnapFieldsAndOmitsAssembly() + { + var panel = CreatePanel("panel_001"); + var pattern = new MountPatternInfo + { + Id = "panel_001_mount_top_000", + PanelId = "panel_001", + MountFace = "top", + PatternType = "line_2", + HoleIds = new[] { "hole_a", "hole_b" }, + RequiredHoleIds = new[] { "hole_a", "hole_b" }, + MinRequiredHoles = 2, + PreferredHoleCount = 2, + Normal = new[] { 0.0, 0.0, 1.0 }, + Position = new[] { 0.0, 0.0, 18.0 }, + Confidence = 0.95, + }; + panel.MountPatterns = new List { pattern }; + panel.SnapPatterns = panel.MountPatterns; + + var exportData = new ExportData + { + ExportMode = "single_asset", + Panels = new List { panel }, + MountPatterns = new List { pattern }, + SnapPatterns = new List { pattern }, + SnapSurfaces = SnapSurfaceBuilder.BuildSnapSurfaces(new[] { panel }), + }; + + var json = JsonConvert.SerializeObject( + exportData, + new JsonSerializerSettings + { + ContractResolver = new CamelCasePropertyNamesContractResolver(), + NullValueHandling = NullValueHandling.Ignore, + }); + var root = JObject.Parse(json); + + Assert.Null(root["assembly"]); + Assert.DoesNotContain("\"mates\"", json, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("\"connections\"", json, StringComparison.OrdinalIgnoreCase); + Assert.Single(Assert.IsType(root["mountPatterns"])); + Assert.Single(Assert.IsType(root["snapPatterns"])); + Assert.Equal(6, Assert.IsType(root["snapSurfaces"]).Count); + var panels = Assert.IsType(root["panels"]); + Assert.Equal(6, Assert.IsType(panels[0]?["snapSurfaces"]).Count); + } + + private static PanelInfo CreatePanel(string id) + { + return new PanelInfo + { + Id = id, + Position = new[] { 0.0, 0.0, 9.0 }, + Normal = new[] { 0.0, 0.0, 1.0 }, + BoundingBox = new BoundingBox3D + { + Min = new[] { -300.0, -280.0, 0.0 }, + Max = new[] { 300.0, 280.0, 18.0 }, + }, + Size = new[] { 600.0, 560.0, 18.0 }, + }; + } + } +} diff --git a/autocad-plugin/FurnitureExporter/FurnitureExporter.csproj b/autocad-plugin/FurnitureExporter/FurnitureExporter.csproj index 912893eb..d7c50877 100644 --- a/autocad-plugin/FurnitureExporter/FurnitureExporter.csproj +++ b/autocad-plugin/FurnitureExporter/FurnitureExporter.csproj @@ -11,7 +11,7 @@ FurnitureExporter FurnitureExporter - 2.5.0 + 2.6.0 Furniture 3D System 家具 3D 模型导出插件 - 导出 GLB 模型和五金件位置数据 diff --git a/autocad-plugin/FurnitureExporter/Models.cs b/autocad-plugin/FurnitureExporter/Models.cs index 15580f2c..27f9e7b1 100644 --- a/autocad-plugin/FurnitureExporter/Models.cs +++ b/autocad-plugin/FurnitureExporter/Models.cs @@ -111,14 +111,23 @@ public class ExportData public List HoleGroups { get; set; } = new(); /// - /// 安装图样(v2.5 新增) - /// 说明: - /// - 吸附面先缩小范围; - /// - HoleGroup 负责把几何孔组织成业务孔位; - /// - MountPattern 负责定义“至少命中几个孔才允许吸附成立”。 + /// 安装图样(v2.5 兼容字段)。 + /// 新方案主字段是 SnapPatterns;这里继续保留给旧 Web 端兼容。 /// public List MountPatterns { get; set; } = new(); + /// + /// 吸附图样(v2.6 新主字段)。 + /// 内容与 MountPatterns 保持一致,Web 端后续优先读取 snapPatterns。 + /// + public List SnapPatterns { get; set; } = new(); + + /// + /// 吸附面(v2.6 新增)。 + /// 每块板件至少提供 6 个轴向外表面,用于辅助装配阶段做面级吸附候选。 + /// + public List SnapSurfaces { get; set; } = new(); + /// /// 逻辑孔位数量(v2.2.4 新增) /// 计算方式:以 HoleGroupId 合并计数(HoleGroupId 为空则按 Hole.Id 计数)。 @@ -331,9 +340,19 @@ public class PanelInfo public List HoleGroups { get; set; } = new(); /// - /// 该板件上的安装图样(v2.5 新增) + /// 该板件上的安装图样(v2.5 兼容字段) /// public List MountPatterns { get; set; } = new(); + + /// + /// 该板件上的吸附图样(v2.6 新主字段) + /// + public List SnapPatterns { get; set; } = new(); + + /// + /// 该板件的吸附面(v2.6 新增) + /// + public List SnapSurfaces { get; set; } = new(); } /// @@ -647,6 +666,47 @@ public class MountPatternInfo public List Warnings { get; set; } = new(); } +/// +/// 吸附面信息(v2.6 新增) +/// +public class SnapSurfaceInfo +{ + /// + /// 吸附面 ID(如 panel_001_snap_top) + /// + public string Id { get; set; } = ""; + + /// + /// 面标签:left / right / front / back / bottom / top + /// + public string Face { get; set; } = ""; + + /// + /// 所属板件 ID + /// + public string PanelId { get; set; } = ""; + + /// + /// 外法向量 [X, Y, Z] + /// + public double[] Normal { get; set; } = new double[3]; + + /// + /// 面中心 [X, Y, Z] (mm) + /// + public double[] Center { get; set; } = new double[3]; + + /// + /// 面边界框。薄轴最小值和最大值相同,表示该外表面所在平面。 + /// + public BoundingBox3D Bounds { get; set; } = new(); + + /// + /// 推导置信度(0-1) + /// + public double Confidence { get; set; } +} + /// /// 3D 边界框 /// diff --git a/autocad-plugin/FurnitureExporter/MountPatternAnalyzer.cs b/autocad-plugin/FurnitureExporter/MountPatternAnalyzer.cs index 3612634d..73be0879 100644 --- a/autocad-plugin/FurnitureExporter/MountPatternAnalyzer.cs +++ b/autocad-plugin/FurnitureExporter/MountPatternAnalyzer.cs @@ -50,6 +50,7 @@ public static class MountPatternAnalyzer if (units.Count == 0) { panel.MountPatterns = new List(); + panel.SnapPatterns = new List(); continue; } @@ -71,6 +72,7 @@ public static class MountPatternAnalyzer } panel.MountPatterns = panelPatterns; + panel.SnapPatterns = panelPatterns; patterns.AddRange(panelPatterns); } @@ -85,9 +87,11 @@ public static class MountPatternAnalyzer foreach (var panel in panels) { - panel.MountPatterns = map.TryGetValue(panel.Id, out var items) + var panelPatterns = map.TryGetValue(panel.Id, out var items) ? items : new List(); + panel.MountPatterns = panelPatterns; + panel.SnapPatterns = panelPatterns; } } diff --git a/autocad-plugin/FurnitureExporter/SnapSurfaceBuilder.cs b/autocad-plugin/FurnitureExporter/SnapSurfaceBuilder.cs new file mode 100644 index 00000000..65107276 --- /dev/null +++ b/autocad-plugin/FurnitureExporter/SnapSurfaceBuilder.cs @@ -0,0 +1,135 @@ +using System; +using System.Collections.Generic; + +namespace FurnitureExporter; + +/// +/// 从板件包围盒推导辅助装配吸附面。 +/// +public static class SnapSurfaceBuilder +{ + private static readonly FaceDefinition[] Faces = + { + new("left", 0, false, new[] { -1.0, 0.0, 0.0 }), + new("right", 0, true, new[] { 1.0, 0.0, 0.0 }), + new("front", 1, false, new[] { 0.0, -1.0, 0.0 }), + new("back", 1, true, new[] { 0.0, 1.0, 0.0 }), + new("bottom", 2, false, new[] { 0.0, 0.0, -1.0 }), + new("top", 2, true, new[] { 0.0, 0.0, 1.0 }), + }; + + public static List BuildSnapSurfaces(IReadOnlyList panels) + { + var allSurfaces = new List(); + + foreach (var panel in panels) + { + var panelSurfaces = BuildPanelSurfaces(panel); + panel.SnapSurfaces = panelSurfaces; + allSurfaces.AddRange(panelSurfaces); + } + + return allSurfaces; + } + + private static List BuildPanelSurfaces(PanelInfo panel) + { + var (min, max, confidence) = ResolveBounds(panel); + var surfaces = new List(Faces.Length); + + foreach (var face in Faces) + { + var center = new[] + { + Round((min[0] + max[0]) / 2.0), + Round((min[1] + max[1]) / 2.0), + Round((min[2] + max[2]) / 2.0), + }; + + var boundsMin = new[] { min[0], min[1], min[2] }; + var boundsMax = new[] { max[0], max[1], max[2] }; + var planeValue = face.UseMax ? max[face.Axis] : min[face.Axis]; + center[face.Axis] = planeValue; + boundsMin[face.Axis] = planeValue; + boundsMax[face.Axis] = planeValue; + + surfaces.Add(new SnapSurfaceInfo + { + Id = $"{panel.Id}_snap_{face.Name}", + Face = face.Name, + PanelId = panel.Id, + Normal = face.Normal, + Center = center, + Bounds = new BoundingBox3D + { + Min = RoundAll(boundsMin), + Max = RoundAll(boundsMax), + }, + Confidence = confidence, + }); + } + + return surfaces; + } + + private static (double[] Min, double[] Max, double Confidence) ResolveBounds(PanelInfo panel) + { + if (panel.BoundingBox?.Min?.Length == 3 && panel.BoundingBox.Max?.Length == 3) + { + return (RoundAll(panel.BoundingBox.Min), RoundAll(panel.BoundingBox.Max), 1.0); + } + + var center = panel.Position?.Length == 3 + ? panel.Position + : new[] { 0.0, 0.0, 0.0 }; + var size = panel.Size?.Length == 3 + ? panel.Size + : new[] { 0.0, 0.0, 0.0 }; + + var min = new[] + { + center[0] - Math.Abs(size[0]) / 2.0, + center[1] - Math.Abs(size[1]) / 2.0, + center[2] - Math.Abs(size[2]) / 2.0, + }; + var max = new[] + { + center[0] + Math.Abs(size[0]) / 2.0, + center[1] + Math.Abs(size[1]) / 2.0, + center[2] + Math.Abs(size[2]) / 2.0, + }; + + return (RoundAll(min), RoundAll(max), 0.6); + } + + private static double[] RoundAll(IReadOnlyList values) + { + return new[] + { + Round(values[0]), + Round(values[1]), + Round(values[2]), + }; + } + + private static double Round(double value) + { + return Math.Round(value, 2); + } + + private sealed class FaceDefinition + { + public FaceDefinition(string name, int axis, bool useMax, double[] normal) + { + Name = name; + Axis = axis; + UseMax = useMax; + Normal = normal; + } + + public string Name { get; } + public int Axis { get; } + public bool UseMax { get; } + public double[] Normal { get; } + } +} diff --git a/autocad-plugin/build-installer.ps1 b/autocad-plugin/build-installer.ps1 index 4f65e023..8bb9be84 100644 --- a/autocad-plugin/build-installer.ps1 +++ b/autocad-plugin/build-installer.ps1 @@ -49,7 +49,7 @@ Write-Host "" # 路径设置 $PluginName = "FurnitureExporter" -$Version = "2.5.0" +$Version = "2.6.0" $SourceDir = Join-Path $PSScriptRoot "FurnitureExporter" $InstallerDir = Join-Path $PSScriptRoot "installer" $OutputDir = Join-Path $PSScriptRoot "dist" diff --git a/autocad-plugin/installer/FurnitureExporter.bundle/PackageContents.xml b/autocad-plugin/installer/FurnitureExporter.bundle/PackageContents.xml index a4a35657..2bdec4dd 100644 --- a/autocad-plugin/installer/FurnitureExporter.bundle/PackageContents.xml +++ b/autocad-plugin/installer/FurnitureExporter.bundle/PackageContents.xml @@ -3,12 +3,12 @@ SchemaVersion="1.0" AutodeskProduct="AutoCAD" Name="FurnitureExporter" - Description="家具导出插件 v2.5.0 - 支持整套兼容导出与资产中心单资产导出" + Description="家具导出插件 v2.6.0 - 支持整套兼容导出与资产中心单资产导出" Author="Furniture 3D System" - AppVersion="2.5.0" - FriendlyVersion="2.5.0" + AppVersion="2.6.0" + FriendlyVersion="2.6.0" ProductType="Application" - Version="2.5.0" + Version="2.6.0" ProductCode="{A1B2C3D4-E5F6-7890-ABCD-EF1234567890}"> > -}) { +} = {}) { const { authUser } = await requireSession('/login') const headerStore = await headers() const requestOrigin = resolveRequestOrigin(headerStore) @@ -551,12 +551,12 @@ export default async function AssistedAssemblyPage({ variant.uvConfig, ) const runtimeThumbnailUrl = - materialConfig && variant.modelUrl + variant.modelUrl ? buildAssetThumbnailImageUrl(requestOrigin, { modelUrl: variant.modelUrl, assetType: variant.assetType as AssetThumbnailRenderAssetType, expiresAt: buildAssetThumbnailExpiryTimestamp(), - materialConfig, + materialConfig: materialConfig ?? null, }) : variant.thumbnailUrl 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 181d33c0..9bf048cf 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 @@ -11,6 +11,7 @@ import { } from "./nonIntegratedApi"; import { createDefaultDocumentWorkspaceConfirmations, + createEmptyNonIntegratedOpeningReference, getNonIntegratedProductById, NON_INTEGRATED_STORAGE_KEY, saveNonIntegratedProduct, @@ -156,6 +157,15 @@ function createProductRecord( return { id: "test-product", spu: "DNZ0001", + projectStatus: "approved", + projectReview: { + reviewDate: "", + reviewers: "", + conclusion: "", + revisionNotes: "", + decidedAt: "", + }, + openingReference: createEmptyNonIntegratedOpeningReference(), year: "", demandFlowNo: "", processTemplate: "", @@ -348,13 +358,14 @@ describe("NonIntegratedDetailClient", () => { const actor = userEvent.setup(); const { container } = render(); - await actor.type(screen.getByLabelText("SPU"), "DNZ0001"); + await actor.type(screen.getByLabelText("开品名称"), "测试开品"); + await actor.type(screen.getByLabelText("临时编号"), "DNZ0001"); await actor.type(screen.getByLabelText("设计师"), "测试设计师"); const imageFile = new File(["image"], "preview.png", { type: "image/png" }); const fileInputs = container.querySelectorAll('input[type="file"]'); await actor.upload(fileInputs[0] as HTMLInputElement, imageFile); - await actor.click(screen.getByRole("button", { name: "提交完成" })); + await actor.click(screen.getByRole("button", { name: "创建开品单" })); await waitFor(() => expect(push).toHaveBeenCalledTimes(1)); @@ -364,8 +375,11 @@ describe("NonIntegratedDetailClient", () => { expect(savedProducts).toHaveLength(1); expect(savedProducts[0]?.spu).toBe("DNZ0001"); + expect(savedProducts[0]?.projectStatus).toBe("draft"); expect(savedProducts[0]?.brand).toBe("基本盘"); expect(savedProducts[0]?.designer).toBe("测试设计师"); + expect(savedProducts[0]?.openingReference.productName).toBe("测试开品"); + expect(savedProducts[0]?.openingReference.temporaryCode).toBe("DNZ0001"); expect(savedProducts[0]?.previewImage).toContain( "data:image/png;base64,dGVzdA==", ); @@ -379,7 +393,7 @@ describe("NonIntegratedDetailClient", () => { expect(screen.getByRole("button", { name: "返回" })).toBeInTheDocument(); expect( - screen.getByRole("button", { name: "提交完成" }), + screen.getByRole("button", { name: "创建开品单" }), ).toBeInTheDocument(); createRender.unmount(); @@ -399,7 +413,7 @@ describe("NonIntegratedDetailClient", () => { expect(screen.queryByRole("button", { name: "返回" })).not.toBeInTheDocument(); expect( - screen.queryByRole("button", { name: "提交完成" }), + screen.queryByRole("button", { name: "创建开品单" }), ).not.toBeInTheDocument(); }); it("keeps brand as a single value when adaptable brands change", async () => { @@ -426,7 +440,7 @@ describe("NonIntegratedDetailClient", () => { await actor.click(adaptableBrandButton); await actor.click(screen.getByLabelText("基本盘")); expect(brandSelect).toHaveValue("顾家"); - expect(screen.getByLabelText("SPU")).toHaveValue(""); + expect(screen.getByLabelText("临时编号")).toHaveValue(""); }); it("shows the document sidebar in the new order and marks empty categories softly", () => { @@ -471,7 +485,7 @@ describe("NonIntegratedDetailClient", () => { 'button[data-testid^="document-workspace"]', ), )[0]?.getAttribute("data-testid"), - ).toBe("document-workspace-basic-info-trigger"); + ).toBe("document-workspace-trigger-开品参考"); const triggerIds = Array.from( sidebar.querySelectorAll( @@ -480,12 +494,14 @@ describe("NonIntegratedDetailClient", () => { ).map((element) => element.dataset.testid); expect(triggerIds).toEqual([ - "document-workspace-trigger-产品实拍图", - "document-workspace-trigger-评审资料", + "document-workspace-trigger-开品参考", + "document-workspace-trigger-产品模型", "document-workspace-trigger-设计卖点", + "document-workspace-trigger-立项评审", + "document-workspace-trigger-评审资料", + "document-workspace-trigger-产品实拍图", "document-workspace-trigger-安装方式", "document-workspace-trigger-包装细节", - "document-workspace-trigger-产品模型", "document-workspace-trigger-产品定厂", "document-workspace-trigger-样包测量", "document-workspace-trigger-产品核价", @@ -502,6 +518,170 @@ describe("NonIntegratedDetailClient", () => { expect(reportTrigger).toHaveAttribute("data-has-files", "false"); expect(reportTrigger).toHaveClass("bg-[#e6ebf0]"); expect(reviewTrigger).not.toHaveClass("bg-[#e6ebf0]"); + expect( + Array.from( + sidebar.querySelectorAll( + 'button[data-testid^="document-workspace"]', + ), + )[4]?.getAttribute("data-testid"), + ).toBe("document-workspace-basic-info-trigger"); + }); + + it("limits draft products to setup nodes until project review is approved", async () => { + const actor = userEvent.setup(); + + window.localStorage.setItem( + NON_INTEGRATED_STORAGE_KEY, + JSON.stringify([ + createProductRecord({ + id: "DNZ0001-draft-project", + projectStatus: "draft", + openingReference: { + ...createEmptyNonIntegratedOpeningReference(), + productName: "测试开品", + temporaryCode: "KP-001", + brand: "顾家", + adaptableBrands: ["顾家", "基本盘"], + productCategory: "书桌", + salesCategory: "书桌", + designer: "测试设计师", + planningOwner: "测试企划", + currentStage: "待立项评审", + year: "2026", + targetPriceBand: "399-499", + size: "140/60/78", + material: "18ENF级橡胶木", + urgent: "否", + reason: "补齐书房价格带", + }, + }), + ]), + ); + + render( + , + ); + + const sidebar = screen.getByTestId("document-workspace-sidebar"); + const draftTriggerIds = Array.from( + sidebar.querySelectorAll( + 'button[data-testid^="document-workspace-trigger-"]', + ), + ).map((element) => element.dataset.testid); + + expect(draftTriggerIds).toEqual([ + "document-workspace-trigger-开品参考", + "document-workspace-trigger-产品模型", + "document-workspace-trigger-设计卖点", + "document-workspace-trigger-立项评审", + ]); + expect( + sidebar.querySelector( + 'button[data-testid="document-workspace-basic-info-trigger"]', + ), + ).toBeNull(); + expect(screen.getByText("开品参考填写")).toBeInTheDocument(); + + await actor.click(screen.getByTestId("document-workspace-trigger-立项评审")); + await actor.click(screen.getByRole("button", { name: "立项通过" })); + + expect(screen.getByRole("dialog", { name: "确认立项" })).toBeInTheDocument(); + await actor.type(screen.getByLabelText("正式 SPU"), "SZ0230"); + await actor.click(screen.getByRole("button", { name: "确认立项" })); + + expect( + screen.getByTestId("document-workspace-basic-info-trigger"), + ).toHaveAttribute("data-active", "true"); + expect( + screen.getByTestId("document-workspace-trigger-产品实拍图"), + ).toBeInTheDocument(); + expect( + screen.getByTestId("document-workspace-trigger-立项评审"), + ).toHaveTextContent("1"); + + await waitFor(() => { + const savedProduct = getNonIntegratedProductById("DNZ0001-draft-project"); + + expect(savedProduct?.projectStatus).toBe("approved"); + expect(savedProduct?.spu).toBe("SZ0230"); + expect(savedProduct?.brand).toBe("顾家"); + expect(savedProduct?.productCategory).toBe("书桌"); + expect(savedProduct?.salesCategory).toBe("书桌"); + expect(savedProduct?.designer).toBe("测试设计师"); + expect(savedProduct?.productPlanning).toBe("测试企划"); + expect(savedProduct?.year).toBe("2026"); + expect(savedProduct?.priceBand).toBe("399-499"); + expect(savedProduct?.size).toBe("140/60/78"); + expect(savedProduct?.materialType).toBe("18ENF级橡胶木"); + expect(savedProduct?.openingReference.currentStage).toBe("已立项"); + }); + }); + + it("renders opening reference fields and persists edits", async () => { + const actor = userEvent.setup(); + + saveNonIntegratedProduct( + createProductRecord({ + id: "SZ0230-opening-reference", + spu: "SZ0230", + openingReference: { + ...createEmptyNonIntegratedOpeningReference(), + productName: "胡桃木色窄边书桌", + temporaryCode: "KP-SZ0230", + brand: "基本盘", + adaptableBrands: ["基本盘", "顾家"], + productCategory: "书桌", + salesCategory: "书桌", + designer: "徐霞客", + planningOwner: "企划A", + currentStage: "立项前", + year: "2026", + competitorLink: "https://example.com/item", + targetPriceBand: "399-499", + size: "140/60/78", + material: "18ENF级橡胶木", + urgent: "否", + reason: "补齐书房价格带", + }, + uploadFiles: [ + { + id: "opening-doc-1", + name: "竞品资料.pdf", + category: "开品参考", + dataUrl: "data:application/pdf;base64,AAAA", + mimeType: "application/pdf", + }, + ], + }), + ); + + render( + , + ); + + await actor.click(screen.getByTestId("document-workspace-trigger-开品参考")); + + expect(screen.getByTestId("opening-reference-workspace")).toBeInTheDocument(); + expect(screen.getByLabelText("开品名称")).toHaveValue("胡桃木色窄边书桌"); + expect(screen.getByLabelText("临时编号")).toHaveValue("KP-SZ0230"); + expect(screen.getByLabelText("企划负责人")).toHaveValue("企划A"); + expect(screen.getByLabelText("目标价格带")).toHaveValue("399-499"); + expect(screen.getByText("竞品资料.pdf")).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "下载" })).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "删除" })).toBeInTheDocument(); + + await actor.clear(screen.getByLabelText("开品理由")); + await actor.type(screen.getByLabelText("开品理由"), "新的开品理由"); + + await waitFor(() => { + const savedProduct = getNonIntegratedProductById( + "SZ0230-opening-reference", + ); + expect(savedProduct?.openingReference.reason).toBe("新的开品理由"); + }); }); it("links the SKU material lookup to the raw material process config", () => { @@ -1529,13 +1709,7 @@ describe("NonIntegratedDetailClient", () => { />, ); - const productPhotoTrigger = screen - .getByTestId("document-workspace-sidebar") - .querySelector( - 'button[data-testid^="document-workspace-trigger-"]', - ); - expect(productPhotoTrigger).not.toBeNull(); - await actor.click(productPhotoTrigger!); + await actor.click(screen.getByTestId("document-workspace-trigger-产品实拍图")); await actor.click(screen.getByTestId("product-photo-slot-back")); await actor.upload( screen.getByTestId("product-photo-current-upload-input"), @@ -1566,13 +1740,7 @@ describe("NonIntegratedDetailClient", () => { />, ); - const productPhotoTrigger = screen - .getByTestId("document-workspace-sidebar") - .querySelector( - 'button[data-testid^="document-workspace-trigger-"]', - ); - expect(productPhotoTrigger).not.toBeNull(); - await actor.click(productPhotoTrigger!); + await actor.click(screen.getByTestId("document-workspace-trigger-产品实拍图")); await actor.click(screen.getByTestId("product-photo-panel-tab-detail")); await actor.click(screen.getByTestId("product-photo-empty-panel-upload-detail")); await actor.upload( @@ -1616,13 +1784,7 @@ describe("NonIntegratedDetailClient", () => { />, ); - const productPhotoTrigger = screen - .getByTestId("document-workspace-sidebar") - .querySelector( - 'button[data-testid^="document-workspace-trigger-"]', - ); - expect(productPhotoTrigger).not.toBeNull(); - await actor.click(productPhotoTrigger!); + await actor.click(screen.getByTestId("document-workspace-trigger-产品实拍图")); expect(screen.getByTestId("product-photo-style-K01")).toBeInTheDocument(); expect(screen.queryByTestId("product-photo-style-K02")).not.toBeInTheDocument(); 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 4ef63f2b..bf208871 100644 --- a/furniture-3d-system/src/app/intake/non-integrated/NonIntegratedDetailClient.tsx +++ b/furniture-3d-system/src/app/intake/non-integrated/NonIntegratedDetailClient.tsx @@ -96,6 +96,8 @@ import { buildNonIntegratedSkuId, buildNonIntegratedUploadFileId, createDefaultDocumentWorkspaceConfirmations, + createEmptyNonIntegratedOpeningReference, + createEmptyNonIntegratedProjectReview, listNonIntegratedProducts, NON_INTEGRATED_BRAND_PREFIX_MAP, NON_INTEGRATED_DUPLICATE_SPU_MESSAGE, @@ -103,6 +105,9 @@ import { getNonIntegratedDocumentWorkspaceCategoryLabel, getNonIntegratedProductById, hasPendingDocumentWorkspaceConfirmation, + normalizeNonIntegratedOpeningReference, + normalizeNonIntegratedProjectReview, + normalizeNonIntegratedProjectStatus, replaceNonIntegratedProducts, saveNonIntegratedProduct, stripNonIntegratedBrandPrefix, @@ -112,9 +117,12 @@ import { type NonIntegratedDocumentWorkspaceCategory, type NonIntegratedDocumentWorkspaceConfirmationMap, type NonIntegratedFactoryRow, + type NonIntegratedOpeningReference, type NonIntegratedPricingRow, type NonIntegratedPackagingInnerItem, type NonIntegratedProductRecord, + type NonIntegratedProjectReview, + type NonIntegratedProjectStatus, type NonIntegratedQualityInspectionSheet, type NonIntegratedReviewIssue, type NonIntegratedReviewRound, @@ -142,6 +150,8 @@ type SkuTabKey = "skuInfo" | "fileUpload"; type ProductFactoryTabKey = "factoryInfo" | "skuInfo"; type UploadCategoryKey = | "未分类" + | "开品参考" + | "立项评审" | "评审资料" | "产品模型" | "产品实拍图" @@ -368,6 +378,14 @@ type ReviewSheetAutoFieldKey = | "size" | "material" | "color"; +type ProjectReviewFieldKey = Exclude< + keyof NonIntegratedProjectReview, + "decidedAt" +>; +type OpeningReferenceFieldKey = Exclude< + keyof NonIntegratedOpeningReference, + "productImage" | "productImageName" | "adaptableBrands" +>; const REVIEW_SHEET_AUTO_FIELD_KEYS: ReviewSheetAutoFieldKey[] = [ "factory", "productName", @@ -752,6 +770,65 @@ const DOCUMENT_WORKSPACE_CATEGORY_ORDER: DocumentWorkspaceCategory[] = [ ...NON_INTEGRATED_DOCUMENT_WORKSPACE_CATEGORIES, ]; +const OPENING_REFERENCE_WORKSPACE_CATEGORY: DocumentWorkspaceCategory = + "开品参考"; +const PROJECT_REVIEW_WORKSPACE_CATEGORY: DocumentWorkspaceCategory = + "立项评审"; +const PROJECT_SETUP_WORKSPACE_CATEGORIES: DocumentWorkspaceCategory[] = [ + OPENING_REFERENCE_WORKSPACE_CATEGORY, + PRODUCT_DATA_WORKSPACE_CATEGORY, + "设计卖点", + PROJECT_REVIEW_WORKSPACE_CATEGORY, +]; +const PROJECT_SETUP_NODE_COUNT = PROJECT_SETUP_WORKSPACE_CATEGORIES.length; +const PROJECT_STATUS_COPY: Record< + NonIntegratedProjectStatus, + { + label: string; + description: string; + badgeClassName: string; + panelClassName: string; + saveMessage: string; + } +> = { + draft: { + label: "待立项", + description: "先整理开品参考、产品资料和设计卖点,再由负责人判断是否进入开发。", + badgeClassName: "bg-[#fff2d9] text-[#8a5a00]", + panelClassName: "border-[#efd49d] bg-[#fff9ec]", + saveMessage: "已标记为待立项", + }, + revision: { + label: "退回修改", + description: "资料需要回到产品资料或设计卖点继续补充,补完后再重新评审。", + badgeClassName: "bg-[#e8f1fb] text-[#23659b]", + panelClassName: "border-[#c7ddec] bg-[#f4f9fd]", + saveMessage: "已退回修改,后续节点保持收起", + }, + rejected: { + label: "废弃不开", + description: "这个品暂不进入开发,只保留前期资料和立项结论。", + badgeClassName: "bg-[#ffe6e9] text-[#a32135]", + panelClassName: "border-[#f4c7ce] bg-[#fff7f8]", + saveMessage: "已标记为废弃不开,后续节点保持收起", + }, + approved: { + label: "已立项", + description: "立项通过后展开基础信息和后续节点,采购可基于资料推进打样。", + badgeClassName: "bg-[#dff7eb] text-[#156b3f]", + panelClassName: "border-[#bde8ce] bg-[#f4fbf7]", + saveMessage: "立项已通过,已展开基础信息和后续节点", + }, +}; +const OPENING_REFERENCE_STAGE_OPTIONS = [ + "立项前", + "资料补充中", + "待立项评审", + "已立项", + "退回修改", + "废弃不开", +]; + const UPLOAD_CATEGORY_OPTIONS: UploadCategoryKey[] = [ "未分类", ...DOCUMENT_WORKSPACE_CATEGORY_ORDER, @@ -771,7 +848,7 @@ const SUPPLEMENT_WORKSPACE_SHORTCUT_LAYOUT: DocumentWorkspaceCategory[] = [ ]; const DEFAULT_DOCUMENT_WORKSPACE_CATEGORY: DocumentWorkspaceCategory = - "产品实拍图"; + OPENING_REFERENCE_WORKSPACE_CATEGORY; const PRODUCT_PHOTO_CATEGORY: DocumentWorkspaceCategory = "产品实拍图"; const AUTO_SAVE_DELAY_MS = 500; @@ -975,8 +1052,10 @@ const EMPTY_DOCUMENT_WORKSPACE_NOTES: Record< DocumentWorkspaceCategory, string > = { + 开品参考: "", 产品实拍图: "", 评审资料: "", + 立项评审: "", 设计卖点: "", 安装方式: "", 包装细节: "", @@ -998,6 +1077,13 @@ const DOCUMENT_WORKSPACE_COPY: Record< emptyDescription: string; } > = { + 开品参考: { + description: "维护开品前的参考资料、竞品链接和方向说明。", + noteLabel: "参考备注", + notePlaceholder: "可填写竞品链接、参考方向、价格段或开品理由。", + emptyTitle: "当前还没有开品参考", + emptyDescription: "可先上传竞品截图、参考文件,或在备注里记录竞品链接。", + }, 产品模型: { description: "按四个大类集中维护打样资料、线稿爆炸图、孔位图和模型资料。", noteLabel: "资料备注", @@ -1015,12 +1101,19 @@ const DOCUMENT_WORKSPACE_COPY: Record< "可先上传九视图、细节图、质检照片或竞品照片,再在这里集中查看。", }, 评审资料: { - description: "按评审记录单模板在本地填写评审信息,并支持一键导出 Excel。", - noteLabel: "评审备注", - notePlaceholder: "可填写评审用途、版本说明或交接备注。", - emptyTitle: "当前还没有评审资料", + description: "按样品评审记录单模板在本地填写评审信息,并支持一键导出 Excel。", + noteLabel: "样品评审备注", + notePlaceholder: "可填写样品评审用途、版本说明或交接备注。", + emptyTitle: "当前还没有样品评审资料", emptyDescription: "可直接在当前工作区填写评审记录,并导出成 Excel。", }, + 立项评审: { + description: "记录立项会议资料和评审结论;确认通过后会展开基础信息及后续节点。", + noteLabel: "立项备注", + notePlaceholder: "可填写会议结论、负责人意见、待补资料或废弃原因。", + emptyTitle: "当前还没有立项评审资料", + emptyDescription: "可上传会议记录、立项判断材料,确认通过后继续维护基础信息。", + }, 设计卖点: { description: "集中查看设计卖点图、卖点文案和展示素材。", noteLabel: "卖点备注", @@ -3163,6 +3256,145 @@ function createFormValuesFromProduct( }; } +function getOpeningReferenceStageFromStatus( + status: NonIntegratedProjectStatus, +) { + if (status === "approved") return "已立项"; + if (status === "revision") return "退回修改"; + if (status === "rejected") return "废弃不开"; + return "立项前"; +} + +function createInitialOpeningReference( + product: NonIntegratedProductRecord | null, +): NonIntegratedOpeningReference { + if (!product) { + return { + ...createEmptyNonIntegratedOpeningReference(), + brand: "基本盘", + adaptableBrands: ["基本盘"], + currentStage: "立项前", + urgent: "否", + }; + } + + const normalized = normalizeNonIntegratedOpeningReference( + product.openingReference, + ); + const normalizedBrand = normalized.brand || product.brand || "基本盘"; + const fallbackAdaptableBrands = Array.from( + new Set([ + normalizedBrand, + ...(product.adaptableBrands?.filter((brand) => + BRAND_OPTIONS.includes(brand), + ) ?? []), + ]), + ); + const normalizedAdaptableBrands = normalized.adaptableBrands.length + ? Array.from( + new Set([ + normalizedBrand, + ...normalized.adaptableBrands.filter((brand) => + BRAND_OPTIONS.includes(brand), + ), + ]), + ) + : fallbackAdaptableBrands; + const projectStatus = normalizeNonIntegratedProjectStatus( + product?.projectStatus, + ); + + return { + ...normalized, + productImage: normalized.productImage || product.previewImage || "", + productImageName: + normalized.productImageName || product.previewImageName || "", + productName: normalized.productName || product.spu || "", + temporaryCode: normalized.temporaryCode || product.spu || product.id || "", + brand: normalizedBrand, + adaptableBrands: normalizedAdaptableBrands, + productCategory: + normalized.productCategory || product.productCategory || "", + salesCategory: normalized.salesCategory || product.salesCategory || "", + designer: normalized.designer || product.designer || "", + planningOwner: normalized.planningOwner || product.productPlanning || "", + currentStage: + normalized.currentStage || getOpeningReferenceStageFromStatus(projectStatus), + year: normalized.year || product.year || "", + targetPriceBand: normalized.targetPriceBand || product.priceBand || "", + size: normalized.size || product.size || "", + material: + normalized.material || product.materialType || product.tagMaterial || "", + urgent: normalized.urgent || "否", + }; +} + +function hasOpeningReferenceContent(reference: NonIntegratedOpeningReference) { + return ( + [ + reference.productImage, + reference.productName, + reference.temporaryCode, + reference.productCategory, + reference.salesCategory, + reference.designer, + reference.planningOwner, + reference.year, + reference.competitorLink, + reference.targetPriceBand, + reference.size, + reference.material, + reference.reason, + ].some((value) => value.trim()) || + reference.adaptableBrands.length > 1 || + (reference.brand.trim() && reference.brand.trim() !== "基本盘") || + (reference.urgent.trim() && reference.urgent.trim() !== "否") + ); +} + +function buildOpeningReferenceFormValues( + baseValues: FormValues, + reference: NonIntegratedOpeningReference, + spu: string, +): FormValues { + const normalizedSpu = spu.trim(); + const normalizedBrand = reference.brand.trim() || baseValues.brand || "基本盘"; + const normalizedAdaptableBrands = Array.from( + new Set([ + normalizedBrand, + ...reference.adaptableBrands.filter((brand) => + BRAND_OPTIONS.includes(brand), + ), + ...baseValues.adaptableBrands.filter((brand) => + BRAND_OPTIONS.includes(brand), + ), + ]), + ); + + return { + ...baseValues, + spu: normalizedSpu, + productCode: baseValues.productCode || normalizedSpu, + previewImage: reference.productImage.trim() || baseValues.previewImage, + previewImageName: + reference.productImageName.trim() || baseValues.previewImageName, + year: reference.year.trim() || baseValues.year, + brand: normalizedBrand, + adaptableBrands: normalizedAdaptableBrands, + productCategory: + reference.productCategory.trim() || baseValues.productCategory, + salesCategory: reference.salesCategory.trim() || baseValues.salesCategory, + productPlanning: + reference.planningOwner.trim() || baseValues.productPlanning, + spuOwner: baseValues.spuOwner || reference.designer.trim(), + designer: reference.designer.trim() || baseValues.designer, + priceBand: reference.targetPriceBand.trim() || baseValues.priceBand, + size: reference.size.trim() || baseValues.size, + materialType: reference.material.trim() || baseValues.materialType, + tagMaterial: reference.material.trim() || baseValues.tagMaterial, + }; +} + function createInitialDocumentWorkspaceNotes( product: NonIntegratedProductRecord | null, ) { @@ -3687,32 +3919,45 @@ function SectionCard({ bodyClassName = "", headerActions, }: { - title: string; + title?: string; description?: string; children: React.ReactNode; className?: string; bodyClassName?: string; headerActions?: React.ReactNode; }) { + const hasHeaderText = Boolean(title || description); + const hasHeader = hasHeaderText || Boolean(headerActions); + return (
-
-
-

- {title} -

- {description ? ( -

- {description} -

+ {hasHeader ? ( +
+ {hasHeaderText ? ( +
+ {title ? ( +

+ {title} +

+ ) : null} + {description ? ( +

+ {description} +

+ ) : null} +
+ ) : null} + {headerActions ? ( +
+ {headerActions} +
) : null}
- {headerActions ?
{headerActions}
: null} -
+ ) : null}
{children}
); @@ -4115,6 +4360,7 @@ function productHasLocalAssets(product: NonIntegratedProductRecord) { if ( isDataUrlSource(product.previewImage) || + isDataUrlSource(product.openingReference.productImage) || isDataUrlSource(product.model3dDataUrl ?? "") ) { return true; @@ -5170,6 +5416,9 @@ function buildProductPayload( uploadFiles: NonIntegratedUploadFile[], documentWorkspaceNotes: Record, documentWorkspaceConfirmations: NonIntegratedDocumentWorkspaceConfirmationMap, + openingReference: NonIntegratedOpeningReference, + projectReview: NonIntegratedProjectReview, + projectStatus: NonIntegratedProjectStatus, createdAt?: string, copiedFromProductId?: string, copiedFromSpu?: string, @@ -5360,6 +5609,9 @@ function buildProductPayload( return { id, + projectStatus, + projectReview: normalizeNonIntegratedProjectReview(projectReview), + openingReference: normalizeNonIntegratedOpeningReference(openingReference), spu: formValues.spu.trim(), year: formValues.year.trim(), demandFlowNo: formValues.demandFlowNo.trim(), @@ -5478,6 +5730,7 @@ export default function NonIntegratedDetailClient({ }) { const router = useRouter(); const previewFileInputRef = useRef(null); + const openingReferenceImageInputRef = useRef(null); const batchSkuImageInputRef = useRef(null); const fileUploadInputRef = useRef(null); const documentWorkspaceUploadInputRef = useRef(null); @@ -5507,6 +5760,10 @@ export default function NonIntegratedDetailClient({ ? initialProduct : getNonIntegratedProductById(productId) : null; + const initialProjectStatus: NonIntegratedProjectStatus = + mode === "create" + ? "draft" + : normalizeNonIntegratedProjectStatus(existingProduct?.projectStatus); const initialBomDetailsResultRef = useRef(null); if (!initialBomDetailsResultRef.current) { initialBomDetailsResultRef.current = createInitialBomDetails(existingProduct); @@ -5543,8 +5800,25 @@ export default function NonIntegratedDetailClient({ const [uploadFiles, setUploadFiles] = useState( existingProduct?.uploadFiles ?? [], ); + const [projectStatus, setProjectStatus] = + useState(initialProjectStatus); + const [projectReview, setProjectReview] = useState( + () => + existingProduct?.projectReview + ? normalizeNonIntegratedProjectReview(existingProduct.projectReview) + : createEmptyNonIntegratedProjectReview(), + ); + const [openingReference, setOpeningReference] = + useState(() => + createInitialOpeningReference(existingProduct), + ); + const [projectApprovalDialogOpen, setProjectApprovalDialogOpen] = + useState(false); + const [projectApprovalSpu, setProjectApprovalSpu] = useState(""); const [documentWorkspaceView, setDocumentWorkspaceView] = - useState("detail"); + useState( + initialProjectStatus === "approved" ? "detail" : "document", + ); const [activeDocumentWorkspaceCategory, setActiveDocumentWorkspaceCategory] = useState(DEFAULT_DOCUMENT_WORKSPACE_CATEGORY); const [documentWorkspaceNotes, setDocumentWorkspaceNotes] = useState< @@ -5860,8 +6134,8 @@ export default function NonIntegratedDetailClient({ } : undefined; const isCopiedBrandProduct = Boolean(existingProduct?.copiedFromProductId); - const isDocumentWorkspaceMode = - mode !== "create" && documentWorkspaceView === "document"; + const isProjectApproved = projectStatus === "approved"; + const isDocumentWorkspaceMode = documentWorkspaceView === "document"; const derivedSkuItems = useMemo( () => skuItems.map((item, index) => @@ -6192,6 +6466,23 @@ export default function NonIntegratedDetailClient({ })), [uploadFiles], ); + const visibleDocumentWorkspaceCategories = useMemo( + () => + isProjectApproved + ? UPLOAD_CATEGORY_PANEL_ORDER + : PROJECT_SETUP_WORKSPACE_CATEGORIES, + [isProjectApproved], + ); + const visibleGroupedUploadFiles = useMemo( + () => + visibleDocumentWorkspaceCategories.map((category) => ({ + category, + files: + groupedUploadFiles.find((group) => group.category === category) + ?.files ?? [], + })), + [groupedUploadFiles, visibleDocumentWorkspaceCategories], + ); const uploadFileCountByCategory = useMemo( () => Object.fromEntries( @@ -6236,6 +6527,12 @@ export default function NonIntegratedDetailClient({ return { ...uploadFileCountByCategory, + [OPENING_REFERENCE_WORKSPACE_CATEGORY]: + uploadFileCountByCategory[OPENING_REFERENCE_WORKSPACE_CATEGORY] + + (hasOpeningReferenceContent(openingReference) ? 1 : 0), + [PROJECT_REVIEW_WORKSPACE_CATEGORY]: + uploadFileCountByCategory[PROJECT_REVIEW_WORKSPACE_CATEGORY] + + (isProjectApproved ? 1 : 0), [REVIEW_WORKSPACE_CATEGORY]: uploadFileCountByCategory[REVIEW_WORKSPACE_CATEGORY] + populatedReviewRoundCount, @@ -6252,6 +6549,8 @@ export default function NonIntegratedDetailClient({ }; }, [ confirmedProductFactoryRowCount, + isProjectApproved, + openingReference, populatedReviewRoundCount, populatedProductPricingRowCount, populatedSampleMeasurementRowCount, @@ -6346,6 +6645,10 @@ export default function NonIntegratedDetailClient({ activeDocumentWorkspaceCategory === FACTORY_QUALITY_WORKSPACE_CATEGORY; const isReviewWorkspace = activeDocumentWorkspaceCategory === REVIEW_WORKSPACE_CATEGORY; + const isOpeningReferenceWorkspace = + activeDocumentWorkspaceCategory === OPENING_REFERENCE_WORKSPACE_CATEGORY; + const isProjectReviewWorkspace = + activeDocumentWorkspaceCategory === PROJECT_REVIEW_WORKSPACE_CATEGORY; const isDetectionWorkspace = activeDocumentWorkspaceCategory === DETECTION_WORKSPACE_CATEGORY; const isInstallationWorkspace = @@ -6943,6 +7246,8 @@ export default function NonIntegratedDetailClient({ ? `按款式分栏维护产品实拍。当前款式:${currentProductPhotoStyleLabel};九视图支持按文件名自动匹配,其他照片分组支持批量上传和替换。` : isProductDataWorkspace ? "左侧按四个大类切换,中间查看当前分类文件明细,右侧只预览 PDF 和图片;其他资料会展开文件明细。" + : isProjectReviewWorkspace + ? "承接开品参考、产品资料和设计卖点,记录立项会议结论;只有立项通过后才展开基础信息和后续节点。" : isReviewWorkspace ? activeDocumentWorkspaceCopy.description : isDetectionWorkspace @@ -7055,8 +7360,10 @@ export default function NonIntegratedDetailClient({ ? `当前还没有${selectedFactoryQualityStyleEntry?.label ?? "该款式"}的${activeFactoryQualityAssetLabel},可点击上方“上传到当前栏”补充。` : activeDocumentWorkspaceCopy.emptyDescription; const canSubmitCreate = - formValues.spu.trim().length > 0 && - formValues.previewImage.length > 0; + mode === "create" + ? openingReference.productName.trim().length > 0 || + openingReference.temporaryCode.trim().length > 0 + : formValues.spu.trim().length > 0 && formValues.previewImage.length > 0; const existingProductCreatedAt = existingProduct?.createdAt ?? ""; const uploadAssetSourceToServer = useCallback( @@ -7118,6 +7425,7 @@ export default function NonIntegratedDetailClient({ ]; const [ previewImage, + openingReferenceProductImage, model3dDataUrl, styleDetailsWithAssets, skuItemsWithAssets, @@ -7131,6 +7439,13 @@ export default function NonIntegratedDetailClient({ `${product.spu || product.id}-preview.png`, "image/png", ), + uploadAssetSourceToServer( + product.id, + product.openingReference.productImage, + product.openingReference.productImageName || + `${product.spu || product.id}-opening-reference.png`, + "image/png", + ), uploadAssetSourceToServer( product.id, product.model3dDataUrl ?? "", @@ -7223,6 +7538,10 @@ export default function NonIntegratedDetailClient({ return { ...product, previewImage, + openingReference: { + ...product.openingReference, + productImage: openingReferenceProductImage, + }, model3dDataUrl, styleDetails: styleDetailsWithAssets, skuItems: skuItemsWithAssets, @@ -7294,6 +7613,9 @@ export default function NonIntegratedDetailClient({ uploadFiles, documentWorkspaceNotes, documentWorkspaceConfirmations, + openingReference, + projectReview, + projectStatus, existingProductCreatedAt, existingProduct?.copiedFromProductId, existingProduct?.copiedFromSpu, @@ -7333,6 +7655,9 @@ export default function NonIntegratedDetailClient({ productFactoryRows, productPricingRows, productSampleMeasurementRows, + openingReference, + projectReview, + projectStatus, skuItems, styleDetails, uploadFiles, @@ -7346,6 +7671,23 @@ export default function NonIntegratedDetailClient({ void compactStoredProducts().catch(() => undefined); }, [compactStoredProducts]); + useEffect(() => { + if (isProjectApproved) return; + if ( + documentWorkspaceView === "document" && + PROJECT_SETUP_WORKSPACE_CATEGORIES.includes(activeDocumentWorkspaceCategory) + ) { + return; + } + + setDocumentWorkspaceView("document"); + setActiveDocumentWorkspaceCategory(OPENING_REFERENCE_WORKSPACE_CATEGORY); + }, [ + activeDocumentWorkspaceCategory, + documentWorkspaceView, + isProjectApproved, + ]); + useEffect(() => { if (!isInstallationWorkspace) return; @@ -7605,6 +7947,8 @@ export default function NonIntegratedDetailClient({ mode, persistEditedProduct, productId, + projectReview, + projectStatus, reviewRounds, skuItems, styleDetails, @@ -9078,6 +9422,81 @@ export default function NonIntegratedDetailClient({ setSaveMessageType("success"); } + function handleOpeningReferenceFieldChange( + field: OpeningReferenceFieldKey, + value: string, + ) { + if (isReadOnly) return; + + setOpeningReference((current) => { + if (field !== "brand") { + return { + ...current, + [field]: value, + }; + } + + const nextBrand = value.trim() || "基本盘"; + const nextAdaptableBrands = Array.from( + new Set([ + nextBrand, + ...current.adaptableBrands.filter((brand) => + BRAND_OPTIONS.includes(brand), + ), + ]), + ); + + return { + ...current, + brand: nextBrand, + adaptableBrands: nextAdaptableBrands, + }; + }); + setSaveMessage(""); + setSaveMessageType("success"); + } + + function handleOpeningReferenceAdaptableBrandsChange(value: string[]) { + if (isReadOnly) return; + + setOpeningReference((current) => { + const nextBrand = current.brand.trim() || "基本盘"; + + return { + ...current, + adaptableBrands: Array.from( + new Set([ + nextBrand, + ...BRAND_OPTIONS.filter((brand) => value.includes(brand)), + ]), + ), + }; + }); + setSaveMessage(""); + setSaveMessageType("success"); + } + + async function handleOpeningReferenceImageChange( + event: ChangeEvent, + ) { + if (isReadOnly) return; + const file = event.target.files?.[0]; + if (!file) return; + + try { + const uploadedAsset = await uploadFileToServer(file, detachedUploadOptions); + setOpeningReference((current) => ({ + ...current, + productImage: uploadedAsset.url, + productImageName: uploadedAsset.fileName, + })); + setSaveMessage(""); + setSaveMessageType("success"); + } finally { + event.target.value = ""; + } + } + function updateSelectedPackagingStyleDetail( updater: (detail: StyleDetailForm) => StyleDetailForm, ) { @@ -9146,6 +9565,73 @@ export default function NonIntegratedDetailClient({ setSaveMessageType("success"); } + function handleProjectReviewFieldChange( + field: ProjectReviewFieldKey, + value: string, + ) { + if (isReadOnly) return; + + setProjectReview((current) => ({ + ...current, + [field]: value, + })); + } + + function handleSetProjectStatus(nextStatus: NonIntegratedProjectStatus) { + if (isReadOnly || projectStatus === nextStatus) return; + + if (nextStatus === "approved") { + setProjectApprovalSpu(""); + setProjectApprovalDialogOpen(true); + return; + } + + setProjectStatus(nextStatus); + setProjectReview((current) => ({ + ...current, + decidedAt: new Date().toISOString(), + })); + setOpeningReference((current) => ({ + ...current, + currentStage: getOpeningReferenceStageFromStatus(nextStatus), + })); + + setDocumentWorkspaceView("document"); + setActiveDocumentWorkspaceCategory(PROJECT_REVIEW_WORKSPACE_CATEGORY); + + setSaveMessage(PROJECT_STATUS_COPY[nextStatus].saveMessage); + setSaveMessageType("success"); + } + + function handleConfirmProjectApproval() { + if (isReadOnly) return; + + const normalizedSpu = projectApprovalSpu.trim().toUpperCase(); + if (!normalizedSpu) { + setSaveMessage("请先填写正式 SPU"); + setSaveMessageType("error"); + return; + } + + setFormValues((current) => + buildOpeningReferenceFormValues(current, openingReference, normalizedSpu), + ); + setProjectStatus("approved"); + setProjectReview((current) => ({ + ...current, + decidedAt: new Date().toISOString(), + })); + setOpeningReference((current) => ({ + ...current, + temporaryCode: current.temporaryCode.trim() || normalizedSpu, + currentStage: getOpeningReferenceStageFromStatus("approved"), + })); + setDocumentWorkspaceView("detail"); + setProjectApprovalDialogOpen(false); + setSaveMessage(PROJECT_STATUS_COPY.approved.saveMessage); + setSaveMessageType("success"); + } + function renderDocumentWorkspaceConfirmationAction() { if (isReadOnly || !activeDocumentWorkspaceNeedsConfirmation) { return null; @@ -10349,12 +10835,27 @@ export default function NonIntegratedDetailClient({ setIsSubmitting(true); try { - const nextProductId = buildNonIntegratedProductId(formValues.spu); + const draftSpu = + openingReference.temporaryCode.trim() || + openingReference.productName.trim() || + `KP-${Date.now()}`; + const nextOpeningReference = normalizeNonIntegratedOpeningReference({ + ...openingReference, + productName: openingReference.productName.trim() || draftSpu, + temporaryCode: draftSpu, + currentStage: getOpeningReferenceStageFromStatus(projectStatus), + }); + const nextFormValues = buildOpeningReferenceFormValues( + formValues, + nextOpeningReference, + draftSpu, + ); + const nextProductId = buildNonIntegratedProductId(nextFormValues.spu); await compactStoredProducts(); const normalizedProduct = await normalizeProductAssetsForStorage( buildProductPayload( nextProductId, - formValues, + nextFormValues, skuItems, styleDetails, bomDetails, @@ -10366,6 +10867,9 @@ export default function NonIntegratedDetailClient({ uploadFiles, documentWorkspaceNotes, documentWorkspaceConfirmations, + nextOpeningReference, + projectReview, + projectStatus, ), ); const savedProduct = shouldUseRemoteAssetStorage() @@ -10385,6 +10889,32 @@ export default function NonIntegratedDetailClient({ } } + function renderCreateFooter() { + if (isReadOnly || mode !== "create") return null; + + return ( +
+
+ + +
+
+ ); + } + if (mode !== "create" && productId && !existingProduct) { return (
@@ -11978,6 +12508,611 @@ export default function NonIntegratedDetailClient({ ); } + function renderOpeningReferenceWorkspace() { + const topFields: { + key: OpeningReferenceFieldKey; + label: string; + type?: BasicFieldType; + options?: string[]; + placeholder?: string; + className?: string; + }[] = [ + { + key: "productName", + label: "开品名称", + placeholder: "如:胡桃木色窄边书桌", + }, + { + key: "temporaryCode", + label: "临时编号", + placeholder: "可先保留,立项后再生成正式 SPU", + }, + { + key: "brand", + label: "品牌", + type: "select", + options: availableBrandOptions.length ? availableBrandOptions : BRAND_OPTIONS, + }, + { + key: "productCategory", + label: "商品类目", + placeholder: "如:书桌", + }, + { + key: "salesCategory", + label: "销售类目", + placeholder: "如:书桌", + }, + { + key: "designer", + label: "设计师", + placeholder: "请输入设计师", + }, + { + key: "planningOwner", + label: "企划负责人", + placeholder: "请输入企划负责人", + }, + { + key: "currentStage", + label: "当前阶段", + type: "select", + options: OPENING_REFERENCE_STAGE_OPTIONS, + }, + { + key: "year", + label: "年份", + placeholder: "如:2026", + }, + ]; + const demandFields: { + key: OpeningReferenceFieldKey; + label: string; + type?: BasicFieldType; + options?: string[]; + placeholder?: string; + className?: string; + }[] = [ + { + key: "competitorLink", + label: "竞品链接", + placeholder: "粘贴竞品链接,可多个链接用换行分隔", + type: "textarea", + className: "xl:col-span-2", + }, + { + key: "targetPriceBand", + label: "目标价格带", + placeholder: "如:399-499", + }, + { + key: "size", + label: "尺寸", + placeholder: "如:140/60/78", + }, + { + key: "material", + label: "材质", + placeholder: "如:18ENF级橡胶木", + }, + { + key: "urgent", + label: "是否急开", + type: "select", + options: ["否", "是"], + }, + { + key: "reason", + label: "开品理由", + placeholder: "说明为什么要开这个品,目标机会点是什么。", + type: "textarea", + className: "xl:col-span-6", + }, + ]; + const openingReferenceFiles = activeDocumentWorkspaceFiles; + const renderCompactOpeningReferenceField = (field: { + key: OpeningReferenceFieldKey; + label: string; + type?: BasicFieldType; + options?: string[]; + placeholder?: string; + className?: string; + }) => ( +
+ + {field.type === "textarea" ? ( +