feat(reference-estimator): 收口预估成本测算工作台与模型能力

整合模型版本、技能维护、板材库与工作台入口,以及批量五金、输出模板、条码复制、对话与自动保存。

保留远端配件删除和组合校验;41 套目标测试,共 329 项通过。
This commit is contained in:
WuYongJie 2026-12-02 17:46:06 +08:00
parent 6f8bcad08d
commit ab97e37e4f
234 changed files with 9447 additions and 1656 deletions

View File

@ -53,13 +53,13 @@ description: 识图拆分板式家具,生成模型、打样资料、分层包
识图先判断本款是横排门、上下分门还是其他结构。相近的板式落地侧开门鞋柜可以借用已经确认的三门样板。横排双门保留一个双门区,横排三门可用双门区加单门区,横排四门可用两个双门区。上下四门按实际水平分区拆。门板、搁板、共用隔板和后背按本款尺寸生成,图中看不到的分区与板件列为暂估。系统直接读取[鞋柜分区示例](references/鞋柜分区示例.json)。
## 书柜初版 · 程序 0.24.8
## 书柜初版 · 程序 0.24.9
- 板式开放格书柜、书架识图后直接按技能生成柜身、槽装背板和后横档,带腿款按图补柜腿。后背初版使用技能暂估参数并记录依据。
- 左侧补充和右侧建模对话都可更新并保存本款。明确的补腿、补背板和两层开放格的槽装后背做法可直接应用到已有模型。其余补充由识图服务解析,无法应用时说明缺项。
- 板式开放格书柜、书架自动按 CB-013、CB-024、CB-025 计算槽装后背。后横档高度不得小于 80 mm,未给高度采用 80 mm,已给更高规格采用本款值。单片背板宽为(背部内高-横档根数×横档高)÷(横档根数+1)+两端入槽量。有效限宽取本款主体板件最大宽与本款明确背板限宽的较小值,排除背板自身。先试一根横档、两片背板;单片超宽时每次加一根横档、均分,直到符合限宽。背部内高放不下更多横档时报告尺寸冲突。2026-12-01 用户确认识图直接执行本技能;用户明确指定无背板、无后横档或左右分片时采用该方案。六格 B 版案例继续采用其已给的 100 mm 横档。
- 板式开放格书柜、书架自动按 CB-013、CB-024、CB-025 计算槽装后背。最低高度、默认高度和自动加高上限以对应类目的生效修订为准;本款给定的更高规格优先。单片背板宽为(背部内高-横档根数×横档高)÷(横档根数+1)+两端入槽量。有效限宽取本款主体板件最大宽与本款明确背板限宽的较小值,排除背板自身。先试一根横档和两片背板,超宽时先在上限内提高横档,优先减少背板片数;仍超宽时逐根增加横档,每次先尝试加高后均分,直到符合限宽。背部内高放不下更多横档时报告尺寸冲突。用户明确指定无背板、无后横档或左右分片时采用该方案。六格 B 版案例采用其已给的 100 mm 横档。
- 分片结果同时生成实际横档和背板,沿用板件编号进入打样、包装及 BOM。增加横档后按实际承接位置暂估连接五金,拉板高度、入槽量、承接及孔位在打样前复核。本款明确的背板限宽随测算保存。
- 系统把已落实的结构纠正保存到「书柜」案例。槽装后背规则用于板式开放格书柜、书架,下次识图按新款尺寸直接计算。本款尺寸及例外保留在案例内。「技能维护」同步展示实际分片规则、横档高度下限和默认值。
- 系统把已落实的结构纠正保存到「书柜」案例。板式开放格书柜和书架分别在「测算技能库 → 技能维护 → 对应类目 → 后背 → 背板分片」维护 CB-025 的最低高度、默认高度、自动加高上限。规则文件给出初始参数 80/80/150 mm;从页面保存后,下次重新识图读取该类目最新修订。标准柜体使用同一修订计算,已有模型保留保存时的修订和本款尺寸。旧背板分片对话保留为历史参考。
- 参考图初版识别为「书柜 / 板式」后,从「测算技能库 → 技能维护」读取已生效的结构关系,按部位和问题提供给建模。优先采用本款明确规格与可见结构,互斥做法无法判断时列为待核。书架、其他材质、待审核和已撤销的关系不带入本款。此入口与槽装后背计算规则同时使用。
- 柜腿由识图或纠正对话给出形状、规格及各根在柜底的相对位置。程序按本款尺寸放置并检查重叠、越界。用户明确给出适用于同类书柜的柜宽下限时,技能库保存阈值和位置;本款明确指定的位置优先,直径等本款规格随测算保存。历史记录的四腿和六腿布局继续可打开。
- 柜腿和只指定位置的后拉板按预览部件处理,工艺和用料待核。按 CB-024 生成的后拉板和三合板同时进入模型、打样、包装和预估 BOM。
@ -79,7 +79,7 @@ description: 识图拆分板式家具,生成模型、打样资料、分层包
| 用途 | 原始文件 | 系统使用方式 |
|---|---|---|
| 柜类拆板与连接 | [柜类家具结构标准化_v0.24.xlsx](references/柜类家具结构标准化_v0.24.xlsx) | 按[现行规则及案例](规则.json)建模。[结构标准摘录](references/结构标准.json)保留原表条目和状态。 |
| 打样资料 | [六格书柜 B 版打样单](references/六格书柜_打样单_960×300×725_B版.pdf) | 六视图、爆炸图和连接明细共用本款板件编号。参考图初版的暂估依据放在连接页,板件清单较长时增补续页。 |
| 打样资料 | [六格书柜 B 版打样单](references/六格书柜_打样单_960×300×725_B版.pdf) | 六视图、爆炸图和连接明细共用本款板件编号。首页为六视图及局部详图,同一缺口合并并保留实测尺寸;第二页在爆炸图右侧列尺寸明细,饰面随板件表。第三页列出连接板件、实际五金规格和用量;孔位按板件与孔规格合并列出坐标,需要时增补附页。 |
| 包装 | [1118 版包装标准](references/产品包装方案标准(1118版).xlsx) · [六格书柜折耳 30° 包装示例](references/六格书柜_包装方案_折耳向外展开30度版.pdf) | 格子柜新生成的包装采用原表「板式格子柜类别」规则。示例用来核对箱型、折耳和包装图。 |
| 成本取价 | [定额与命名.xlsx](references/定额与命名.xlsx) | 从[导入定额](references/定额数据.json)查询板材、五金和人工,回查原表时用来源单元格。 |
| BOM 版式与公式 | [落地矮书柜 BOM 原模板](references/板式家具-柜类-书柜-矮柜-落地-BOM模版.xlsx) | 用原表结构生成成本明细。与应用 `standards/1116` 下的在用模板内容一致。 |
@ -94,7 +94,7 @@ description: 识图拆分板式家具,生成模型、打样资料、分层包
| BOM 核算 | 当前模板 1116.1,可独立换版。程序从本款结构、包装和取价数据生成成本明细。 |
| 定额与报价 | 定额与命名原表及本款报价。所选规格、价格和来源随当前测算单保存。 |
打样和包装共用建模配置的看图模型。每次修订按阶段随测算保存。确认可复用做法后,按阶段、类目和材质归入技能库。同类测算可用「按已确认技能检查」应用适用做法。
打样和包装共用建模配置的看图模型。所有类目的打样资料统一按六格书柜 B 版样单排版:A3 第一角法六视图、尺寸明细、局部详图、爆炸图和连接明细。尺寸和加工特征读取本款实际模型;无该结构或缺加工参数时不套用样单的尺寸。包装统一采用 1118 版规则和示例版式:总览及用料、逐层摆包、折耳展开和封箱。本款对话修订随各阶段的结果保存。确认可复用做法后,按阶段、类目和材质归入技能库。同类测算可用「按已确认技能检查」应用适用做法。
## 柜类五金自动带入 v4(本地测试中)
@ -111,9 +111,9 @@ description: 识图拆分板式家具,生成模型、打样资料、分层包
- 输入图片和已有尺寸、板件组材料、封边与本款特殊要求。已给信息直接使用,只问影响当前结果的缺项。
- 模型、六视图/爆炸图/连接明细、包装和成本共用稳定板件编号与连接记录。长宽厚采用含封边成品口径;开料与机加工参数须另核。
- 原标准完整文字及每条状态见 `references/结构标准.json`。填写提示、待填写、待验证与已生效分别处理。不得将案例尺寸升级为所有柜类的默认规则。
- 程序 0.24.8 支持横板连续、竖隔分段的板式开放格书柜按本款成品宽、深、高和板厚拆板。图文或人工明确的参数优先。隔板和搁板进深缺失时,暂按本款柜深减 30 mm;底板进深缺失时,暂按本款柜深减 15 mm。背板槽和封边可参照六格 B 版暂估,随模型和 BOM 记录,打样前核对。三围均与案例相同时,缺失板厚也可按案例暂估。
- 程序 0.24.9 支持横板连续、竖隔分段的板式开放格书柜按本款成品宽、深、高和板厚拆板。图文或人工明确的参数优先。隔板和搁板进深缺失时,暂按本款柜深减 30 mm;底板进深缺失时,暂按本款柜深减 15 mm。背板槽和封边可参照六格 B 版暂估,随模型和 BOM 记录,打样前核对。三围均与案例相同时,缺失板厚也可按案例暂估。
- 前踢脚板按图文判断有、无或待确认。板式开放格书柜、书架的后背按 CB-013、CB-024、CB-025 自动生成,后横档最低 80 mm,未知采用 80 mm。明确的本款例外优先。旧测算在主动重算时更新。
- 背板分片在模型阶段完成,实际后横档、背板和承接位置同步进入打样、包装及 BOM。单片超宽时逐根增加横档并均分,直到符合有效限宽。
- 背板分片在模型阶段完成,实际后横档、背板和承接位置同步进入打样、包装及 BOM。单片超宽时先尝试加高横档,最多加到该类目维护的上限(初始为 150 mm);仍超宽再逐根增加横档并均分,直到符合有效限宽。
- 六格960×300×725 B版案例独立保存在规则文件的 cases 中。该案例板厚15、主体11块、背板2块,偏心32套、5×40螺丝6颗、背板扣8个。图示E1优先于旧PDF的E0;胡桃色的具体花色须匹配或确认。
- 背板不封边;其余板件封边范围与条厚逐款确认。PDF中的槽后边距21mm是拟定值,原标准八格的10mm不能直接复制到六格;槽位与孔位待核必须保留在图纸和模型状态中。
- 偏心一套=一轮一杆,不能再计一份子件采购成本。踢脚端部各1套/2套逐款确认,中部与底板连接另计。后横档按实际接合计5×40螺丝,背板≤1300每块4扣,超限询问。

View File

@ -1,9 +1,9 @@
{
"version": "0.24.8",
"version": "0.24.9",
"sourceVersion": "v0.24",
"status": "测试中",
"scope": "板式开放格书柜:横板连续、竖隔分段;其他结构先确认",
"backPanelSplitting": {"automaticBookshelfBack":true,"minimumRailHeight":80,"defaultRailHeight":80,"initialRailCount":1,"maximumRailCount":null,"note":"2026-12-01 用户确认:板式开放格书柜、书架识图后自动生成槽装背板和后横档;横档高度不得小于80mm,未给高度按80mm;单片超宽时逐根增加后横档并均分,直到符合有效限宽;明确的本款后背方案优先"},
"backPanelSplitting": {"automaticBookshelfBack":true,"minimumRailHeight":80,"defaultRailHeight":80,"maximumAdjustedRailHeight":150,"initialRailCount":1,"maximumRailCount":null,"note":"板式开放格书柜、书架识图后自动生成槽装背板和后横档;默认80mm,单片超宽先加高横档至150mm以内,优先减少分片;仍超宽时逐根增加横档并均分;明确的本款后背方案优先"},
"hardware": {"camPerJoint":2,"camComponents":"一轮一杆","railEndScrews":2,"railJointLimit":400,"railJointSmall":1,"railJointLarge":2,"kickHorizontalLimit":600,"kickHorizontalSmall":1,"kickHorizontalLarge":2,"backLengthLimit":1300,"backClips":4},
"cabinetHardwareSkill": {
"version": 4,

View File

@ -0,0 +1,53 @@
# 产品资料与模型能力串联规划
状态:协作草案。记录当前代码基线、建议接法和待确认事项。功能由各模块负责人实施;本规划负责核对实际代码、维护跨模块依赖和验收口径。
## 1. 要实现什么
从一张参考图生成可修改的产品初版。打样后将工厂确认的结构、孔位、BOM、包法和资料更新为新版本。产品资料能查到初版、修改版、当前定版,以及每份图纸、表格和出图结果所用的版本。第一款验证能跑通,第二款验证同类做法能复用。
```text
参考图 + 确认规格
→ 参考图预估成本:板件、连接、材料、打样和包装初案
→ 产品信息:采用初版 → 打样修订 → 定版
├─ 生产:打样单、BOM、开料单、包装方案
├─ 出图:产品 SKU、DIY 换色、AI 模型生图、详情页
└─ 安装:步骤、动画、图纸,按需求再输出视频
→ 经验证的连接、包装和安装做法回到标准库,供下一款引用
```
## 2. 现有代码与缺口
| 模块 | 现有实现 | 串联要补的内容 |
| --- | --- | --- |
| 参考图预估成本 | 柜体结构能驱动模型、打样 PDF、包装 PDF 和 BOM Excel;模型有 STEP 和 GLB 导出。测算单按个人保存,修订号保护并发更新。 | 采用某次测算为产品初版时,保留当时的结构和结果;测算单之后改动不能改变已采用的初版。 |
| 产品信息与资料 | 产品资料已有模型文件版本、SKU 模型绑定和材质版本,BOM 工作区可导出开料单。 | 补上产品结构版本与模型、板件、物料、工艺、派生产物间的对应;复用已有资料入口和版本能力。 |
| 资产中心与辅助装配 | 已有资产分类和连接角色;辅助装配可以读取并匹配已有孔组。 | 柜体测算目前用板件编号和连接类型、数量、备注表达连接。补到每块实体板、连接面、五金型号和孔系标准,和现有资产及孔组能力对齐。 |
| BOM、原材料与包装 | 产品 BOM 已能匹配板材、钢架、封边及包材资料。柜体测算使用内置定额及部分暂估,能按板件自动摆包。 | 用物料规格标识对齐资料库、报价和测算;记录实际用量、报价来源、试包修正。包装规则按适用范围复用。 |
| DIY 和 AI 生图 | DIY 已有款式、模型和贴图目录;独立 AI 模型生图维护自己的款和 SKU;产品资料内已有按 SKU 的出图入口。 | 先验证产品资料内直接复用模型和材质,再给 DIY 和独立出图入口提供引用。保留生成结果所用的结构和花色版本;详情页使用经过确认的产品事实和卖点。 |
| 安装动画和图纸 | 安装工作台已有模型上传、爆炸布局、动作编辑、播放和图纸。通用步骤草稿按节点分组。 | 从产品结构版本读取板件、连接、五金及装配顺序,生成可审的步骤;实际装配后沉淀适用的步骤模板。播放、图纸、视频文件分别验收。 |
代码入口:[柜体模型](../../src/lib/reference-estimator/standard/cabinet-model.ts) · [测算保存](../../src/server/repositories/reference-estimate-record.repository.ts) · [GLB 导出](../../src/app/reference-estimator/standard/CabinetModelView.tsx) · [柜体取价](../../src/lib/reference-estimator/standard/cabinet-quota.ts) · [产品模型和材质](../../src/server/services/intake-ai-asset.service.ts) · [开料导出](../../src/app/intake/non-integrated/workspaces/bom/BomDetailToolbar.tsx) · [DIY 目录](../../src/server/services/diy-catalog.service.ts) · [独立出图](../../src/server/services/ai-render-workbench.service.ts) · [安装步骤草稿](../../src/app/installation-demo-workbench/lib/installationStepDraftBuilder.ts)。当前为源码核对,端到端可用性待实际试跑。
## 3. 需要各线程一起定的接口
- **产品和版本**:产品及 SKU 用现有标识。测算采用时固定来源和结构版本;打样修订另存一版;历史结果保持指向原版。资料存储线程核对可复用的结构,确定版本及产物的归属。
- **板件和模型**:区分板件用途、加工规格、同规格的实体板件。比如两块相同的层板可按规格合并开料,但模型、孔位和安装必须分得清是上层还是下层。GLB 节点与实体板件对应;同一结构可以绑多个花色 SKU。
- **连接、孔位和装配**:一条连接标准写清两侧板件用途、安装面、适用板厚、五金型号、定位基准和孔径、深度、方向等加工数据。先从旁板加固定层板开始。区分候选、工艺已确认和实样验证;安装顺序和工具空间单独校验。
- **材料与包装**:对齐板材、花色贴图、封板、钢架、五金、包材的物料标识;报价记录来源、单位和当时使用的值。试包结果回到本款,确认有复用价值后更新包装标准。
- **产物和变更**:记录每份资料的来源版本。换五金时复核孔位、BOM、打样及安装;只换饰面时复核对应 SKU 的贴图和出图;若用料或报价也变了,同时复核成本。外部定版模型先校对板件映射,再承接自动生成。
## 4. 推进顺序与验收
| 里程碑 | 最小验收 | 依赖 |
| --- | --- | --- |
| M1:采用产品初版 | 一张现有柜体测算关联至现有产品;产品打开时能查模型、结构和当时产物;测算后来修改,初版记录仍可查。 | 产品资料和测算线程先对齐标识、版本归属。 |
| M2:柜体打样与复用 | 旁板加层板验证一套五金和孔位;改一项结构,BOM、打样图和开料资料能对上版本;用真实样品核对,并在第二款同类柜复用。包装初案可修订为实际包法。 | 工艺提供真实五金规格、孔位或工厂确认结果。 |
| M3a:模型出图复用 | 共用结构的两个 SKU 直接换花色出图并回到产品;核对板件贴图和图的来源。后续再接 DIY、独立出图和详情页。 | 有稳定模型节点、SKU 与花色绑定。可和 M2 并行准备。 |
| M3b:安装内容复用 | 同一版结构可生成安装步骤、动画和图纸初稿;经实际装配修订后,在第二款复用。视频文件按实际交付需求单列。 | 依赖 M2 的连接与板件信息,以及可验证的步骤规则。 |
排期先按里程碑跟踪。待各线程反馈已实现的代码、缺口和人力后,再给日期。工厂核孔、试包和实际装配的往返时间单列。当前代码基线已核对;上述跨模块里程碑待联调验收。
## 5. 给各线程的协作约定
开工或继续涉及共享部分前,先核对自己模块的输入、输出和已有标识。反馈四项:**已有实现及代码入口、要从上游读取什么、能给下游产出什么、需要共同决定的字段或规则**。涉及产品和 SKU 标识、模型或板件编号、材料编码、版本归属的改动,先与对应模块对齐。模块自身迭代按原计划推进,发现接口冲突时在此规划更新依赖和状态。

View File

@ -0,0 +1,13 @@
BEGIN;
SET LOCAL lock_timeout = '5s';
SET LOCAL statement_timeout = '120s';
-- Only records with a model participate. The category is derived from the
-- saved document, so model writes need no second source of category data.
CREATE INDEX "ReferenceEstimateRecord_owner_category_model_page_idx"
ON "ReferenceEstimateRecord" (
"ownerId", (document #>> '{skillRouting,classification,secondaryCategory}'), "updatedAt" DESC, id
)
WHERE jsonb_typeof(document #> '{standardTemplate,cabinet}') = 'object';
COMMIT;

View File

@ -0,0 +1,167 @@
import { randomUUID } from 'node:crypto'
import { readFileSync } from 'node:fs'
import dotenv from 'dotenv'
import pg from 'pg'
// Run against the 3001 acceptance database. Default is a read-only preview.
const app = new URL('../', import.meta.url)
const env = Object.assign({}, ...['.env', '.env.local', '.env.development.local'].map(file => {
try { return dotenv.parse(readFileSync(new URL(file, app))) }
catch (error) { if (error.code !== 'ENOENT') throw error; return {} }
}))
const target = new URL(env.DATABASE_URL)
if (!['localhost', '127.0.0.1'].includes(target.hostname) || target.port !== '55432') throw new Error('只允许连接本地 3001 验收库')
const apply = process.argv.includes('--apply-local')
const backBoardWeightsOnly = process.argv.includes('--back-board-weights-only')
const quota = JSON.parse(readFileSync(new URL('.agents/skills/cabinet-standard-bom/references/定额数据.json', app), 'utf8')).boards
const weights = { 密度板: { 12: 22.9, 15: 27.7 }, 刨花板: { 12: 24.1, 15: 28.2 }, 生态板: { 12: 22.1, 15: 26.1 }, 橡胶木: { 12: 24, 15: 31 } }
const text = value => String(value ?? '').normalize('NFKC').replace(/\s/g, '').toLowerCase()
const grade = value => text(value).replace(/级$/, '')
const veneer = value => text(value).replace(/^([单双])面贴/, '$1贴')
const finish = value => text(value).replace(/色$/, '')
const dimensions = (thickness, length, width) => [thickness, Math.max(length, width), Math.min(length, width)].join('|')
const identity = (board, color) => [text(board.material), grade(board.grade), veneer(board.veneer),
dimensions(board.thickness, board.length, board.width), finish(color)].join('|')
const quotaBackWeights = new Map(quota.filter(row => row.material === '刨花板' && row.thickness === 8 &&
row.sheetLength === 2440 && row.sheetWidth === 1220 && row.veneer === '双贴' &&
['enf', 'e0'].includes(grade(row.grade)) && row.weight === 18)
.map(row => [identity({ ...row, length: row.sheetLength, width: row.sheetWidth }, row.color), row.weight]))
const quotaBackWeight = board => board.colors?.length === 1
? quotaBackWeights.get(identity(board, board.colors[0])) ?? null : null
const sheetWeight = board => board.length === 2440 && board.width === 1220
? weights[board.material]?.[board.thickness] ?? null : null
const db = new pg.Client({ connectionString: target.href })
const read = async sql => (await db.query(sql)).rows
async function run() {
await db.connect()
await db.query(apply ? 'BEGIN ISOLATION LEVEL SERIALIZABLE' : 'BEGIN READ ONLY')
await db.query("SET LOCAL statement_timeout = '10s'")
await db.query("SET LOCAL lock_timeout = '3s'")
const records = await read(`SELECT s.id, s.code, s."weightKg" AS weight, s."isActive" AS active, s.metadata,
c.name AS material, g.name AS grade, t."thicknessMm" AS thickness, t."sheetLengthMm" AS length,
t."sheetWidthMm" AS width, v.name AS veneer,
coalesce(array_agg(m.name) FILTER (WHERE m.id IS NOT NULL), ARRAY[]::text[]) AS colors
FROM "Substrate" s JOIN "SubstrateCategory" c ON c.id=s."categoryId"
JOIN "SubstrateEnvironmentGrade" g ON g.id=s."environmentGradeId"
JOIN "SubstrateThicknessSpec" t ON t.id=s."thicknessSpecId"
LEFT JOIN "SubstrateSurfaceOption" v ON v.id=s."surfaceOptionId"
LEFT JOIN "SubstrateFinish" sf ON sf."substrateId"=s.id LEFT JOIN "Material" m ON m.id=sf."finishId"
GROUP BY s.id,c.name,g.name,t.id,v.name`)
if (backBoardWeightsOnly) {
const targets = records.filter(row => row.active && quotaBackWeight(row) !== null)
if (quotaBackWeights.size !== 10 || targets.length !== 10 ||
new Set(targets.map(row => identity(row, row.colors[0]))).size !== quotaBackWeights.size) {
throw new Error('未找到 10 条唯一的 8 mm 定额规格,未更新板重。')
}
const missing = targets.filter(row => row.weight === null)
if (apply) {
for (const row of missing) {
const result = await db.query('UPDATE "Substrate" SET "weightKg"=$1,"updatedAt"=now() WHERE id=$2 AND "weightKg" IS NULL',
[quotaBackWeight(row), row.id])
if (result.rowCount !== 1) throw new Error('8 mm 板重同时被修改,未更新板重。')
}
}
await db.query(apply ? 'COMMIT' : 'ROLLBACK')
console.log(JSON.stringify({ status: apply ? 'applied' : 'preview', matched: targets.length,
updatedWeight: apply ? missing.length : 0, missingWeightBefore: missing.map(row => row.code).sort(),
sheetWeights: [...new Set(targets.map(row => row.weight ?? (apply ? quotaBackWeight(row) : null)))] }))
return
}
const category = await read('SELECT id,name,"isActive" AS active FROM "SubstrateCategory"')
const grades = await read('SELECT id,name,"isActive" AS active FROM "SubstrateEnvironmentGrade"')
const thickness = await read('SELECT id,name,"isActive" AS active,"thicknessMm" AS thickness,"sheetLengthMm" AS length,"sheetWidthMm" AS width FROM "SubstrateThicknessSpec"')
const surface = await read('SELECT id,name,"isActive" AS active FROM "SubstrateSurfaceOption"')
const materials = await read(`SELECT m.id,m.name,c.name AS category FROM "Material" m JOIN "MaterialCategory" c ON c.id=m."categoryId" WHERE m."isActive"`)
const seen = new Set()
const existing = new Set(records.flatMap(row => (row.colors.length ? row.colors : ['']).map(color => identity(row, color))))
const skipped = []
const additions = []
let matched = 0
let conflicts = 0
const oldQuotes = new Map()
for (const row of quota) {
const board = { ...row, length: row.sheetLength, width: row.sheetWidth }
const key = identity(board, row.color)
if (seen.has(key)) {
if (oldQuotes.get(key) !== row.price) conflicts++
continue
}
seen.add(key)
oldQuotes.set(key, row.price)
if (existing.has(key)) { matched++; continue }
const matches = materials.filter(material => finish(material.name) === finish(row.color) && material.category.includes('贴面'))
if (matches.length !== 1) {
skipped.push({ color: row.color, grade: row.grade, thickness: row.thickness, source: row.source })
continue
}
additions.push({ board, color: matches[0] })
}
if (conflicts) throw new Error('旧定额同规格存在不同报价,需先核对')
const weightChanges = records.filter(row => row.active && sheetWeight(row) !== null && row.weight !== sheetWeight(row))
const missingGrades = new Set()
const missingSizes = new Map()
for (const { board } of additions) {
if (!grades.some(item => item.active && grade(item.name) === grade(board.grade))) missingGrades.add(board.grade)
if (!thickness.some(item => item.active && dimensions(item.thickness, item.length, item.width)
=== dimensions(board.thickness, board.length, board.width))) {
missingSizes.set(dimensions(board.thickness, board.length, board.width), board)
}
if (!category.some(item => item.active && item.name === board.material)
|| !surface.some(item => item.active && veneer(item.name) === veneer(board.veneer))) {
throw new Error('板材主类或贴面字典缺失')
}
}
if (!apply) {
console.log(JSON.stringify({ status:'preview', existing: records.length, matched, add: additions.length,
updateWeight: weightChanges.length, grades: [...missingGrades], thicknesses: [...missingSizes.values()].map(row => row.thickness), skipped }, null, 2))
await db.query('ROLLBACK')
return
}
for (const name of missingGrades) {
if (grades.some(row => grade(row.name) === grade(name))) throw new Error('环保等级字典已有停用项,需先核对')
const id = randomUUID()
await db.query('INSERT INTO "SubstrateEnvironmentGrade"(id,name,"updatedAt") VALUES ($1,$2,now())', [id, name])
grades.push({ id, name, active:true })
}
for (const { thickness: size, length, width } of missingSizes.values()) {
const id = randomUUID(), name = String(size)
if (thickness.some(item => item.name === name)) throw new Error('厚度字典存在同名冲突,需先核对')
await db.query('INSERT INTO "SubstrateThicknessSpec"(id,name,"thicknessMm","sheetLengthMm","sheetWidthMm","updatedAt") VALUES ($1,$2,$3,$4,$5,now())',
[id, name, size, length, width])
thickness.push({ id, name, thickness:size, length, width, active:true })
}
let nextCode = Math.max(0, ...records.map(row => Number(/^BC-(\d+)$/.exec(row.code)?.[1] ?? 0)))
for (const { board, color } of additions) {
const cat = category.find(row => row.active && row.name === board.material)
const g = grades.find(row => row.active && row.name === board.grade)
?? grades.find(row => row.active && grade(row.name) === grade(board.grade))
const size = thickness.find(row => row.active && dimensions(row.thickness,row.length,row.width) === dimensions(board.thickness,board.length,board.width))
const coating = surface.find(row => row.active && veneer(row.name) === veneer(board.veneer))
const id = randomUUID(), code = 'BC-' + String(++nextCode).padStart(4, '0')
const name = [size.name,g.name,cat.name,coating.name,color.name].join(' ')
await db.query(`INSERT INTO "Substrate"(id,code,name,"categoryId","environmentGradeId","thicknessSpecId","surfaceOptionId",
"suggestedPrice","weightKg",metadata,"updatedAt") VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,now())`,
[id,code,name,cat.id,g.id,size.id,coating.id,board.price,sheetWeight(board) ?? quotaBackWeight({ ...board, colors: [color.name] }),
{ source:'参考图测算旧定额', quotaRow:board.source, quotaBoardId:board.id }])
await db.query('INSERT INTO "SubstrateFinish"(id,"substrateId","finishId") VALUES ($1,$2,$3)', [randomUUID(),id,color.id])
}
for (const row of weightChanges) {
const weight = sheetWeight(row)
const metadata = row.metadata && Object.hasOwn(row.metadata, 'sheetWeightKg')
? { ...row.metadata, sheetWeightKg:weight, weightPerSquareMeterKg:Number((weight / (row.length*row.width/1e6)).toFixed(4)),
...(Array.isArray(row.metadata.missingFields) ? { missingFields:row.metadata.missingFields.filter(item => item !== 'weightKg') } : {}) }
: row.metadata
await db.query('UPDATE "Substrate" SET "weightKg"=$1,metadata=$2,"updatedAt"=now() WHERE id=$3', [weight,metadata,row.id])
}
await db.query('COMMIT')
console.log(JSON.stringify({ status:'applied', added:additions.length, updatedWeight:weightChanges.length, matched, skipped }, null, 2))
}
try { await run() }
catch (error) {
await db.query('ROLLBACK').catch(() => undefined)
console.error(error.code ?? error.message)
process.exitCode = 1
}
finally { await db.end() }

View File

@ -3,6 +3,7 @@ import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response'
import { ErrorCode } from '@/server/core/errors'
import {
addStructureSkill,
forgetStructureSnapshot,
listStructureModels,
listStructureSkills,
registerStructureMaterial,
@ -10,16 +11,37 @@ import {
reviewStructureSkill,
structureRequestSchema,
} from '@/server/services/reference-image-estimate/structure-skill.service'
import { editDialogueRule, editDialogueRuleSchema } from '@/server/services/reference-image-estimate/structure-maintenance-rules'
import { saveBackPanelSkill, saveBackPanelSkillSchema } from '@/server/services/reference-image-estimate/back-panel-skill.service'
import { imageSkillCategorySchema } from '@/lib/reference-estimator/standard/cabinet-image-memory'
export async function GET(request: NextRequest) {
return handleRequest(request, async ctx => jsonSuccess(
// A caller that sends the version it already holds gets the library only when that version is out of date.
await listStructureSkills(ctx.user, request.nextUrl.searchParams.get('version') ?? undefined), 200, ctx.requestId))
return handleRequest(request, async ctx => {
const category = imageSkillCategorySchema.optional().safeParse(request.nextUrl.searchParams.get('category') ?? undefined)
if (!category.success) return jsonError(ErrorCode.VALIDATION_FAILED, '无效的技能类目', 400, ctx.requestId)
return jsonSuccess<unknown>(await listStructureSkills(ctx.user, category.data,
request.nextUrl.searchParams.get('version') ?? undefined), 200, ctx.requestId)
})
}
export async function POST(request: NextRequest) {
return handleRequest(request, async ctx => {
const input = structureRequestSchema.safeParse(await request.json().catch(() => null))
const body = await request.json().catch(() => null)
if (body?.action === 'edit-back-panel') {
const edit = saveBackPanelSkillSchema.safeParse(body)
if (!edit.success) return jsonError(ErrorCode.VALIDATION_FAILED, edit.error.issues[0]?.message ?? '无效的分片参数', 400, ctx.requestId)
const rule = await saveBackPanelSkill(ctx.user, edit.data)
forgetStructureSnapshot()
return jsonSuccess<unknown>(rule, 200, ctx.requestId)
}
if (body?.action === 'edit-dialogue') {
const edit = editDialogueRuleSchema.safeParse(body)
if (!edit.success) return jsonError(ErrorCode.VALIDATION_FAILED, edit.error.issues[0]?.message ?? '输入无效', 400, ctx.requestId)
await editDialogueRule(ctx.user, edit.data)
forgetStructureSnapshot()
return jsonSuccess<unknown>({ saved: true }, 200, ctx.requestId)
}
const input = structureRequestSchema.safeParse(body)
if (!input.success) return jsonError(ErrorCode.VALIDATION_FAILED, input.error.issues[0]?.message ?? '输入无效', 400, ctx.requestId)
const user = ctx.user
const result = input.data.action === 'models' ? await listStructureModels(user, input.data)
@ -27,6 +49,6 @@ export async function POST(request: NextRequest) {
: input.data.action === 'add' ? await addStructureSkill(user, input.data)
: input.data.action === 'material' ? await registerStructureMaterial(user, input.data)
: await reviewStructureSkill(user, input.data)
return jsonSuccess(result, 200, ctx.requestId)
return jsonSuccess<unknown>(result, 200, ctx.requestId)
})
}

View File

@ -0,0 +1,13 @@
import type { NextRequest } from 'next/server'
import { modelVersionRequestSchema } from '@/lib/reference-estimator/standard/model-version-contract'
import { ErrorCode } from '@/server/core/errors'
import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response'
import { editModelVersions } from '@/server/services/reference-image-estimate/model-versions.service'
export async function PATCH(request: NextRequest, context: { params: Promise<{ id: string }> }) {
return handleRequest(request, async ctx => {
const input = modelVersionRequestSchema.safeParse(await request.json().catch(() => null))
if (!input.success) return jsonError(ErrorCode.VALIDATION_FAILED, '模型版本请求无效,名称限 1~40 字且只能删除历史版本', 400, ctx.requestId)
return jsonSuccess(await editModelVersions((await context.params).id, input.data, ctx.user), 200, ctx.requestId)
})
}

View File

@ -0,0 +1,8 @@
import type { NextRequest } from 'next/server'
import { handleRequest, jsonSuccess } from '@/server/core/response'
import { listReferenceEstimateSummaries } from '@/server/services/reference-estimate-list.service'
export function GET(request: NextRequest) {
return handleRequest(request, async ({ user, requestId }) =>
jsonSuccess({ records: await listReferenceEstimateSummaries(user) }, 200, requestId))
}

View File

@ -0,0 +1,17 @@
import type { NextRequest } from 'next/server'
import { ErrorCode } from '@/server/core/errors'
import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response'
import { listEstimateConversationModels, ReferenceImageEstimateError } from '@/server/services/reference-image-estimate/estimate-vision-provider'
import { assertReferenceEstimateAccess } from '@/server/services/reference-image-estimate/reference-estimate-access'
export async function GET(request: NextRequest) {
return handleRequest(request, async ctx => {
await assertReferenceEstimateAccess(ctx.user)
try {
return jsonSuccess(await listEstimateConversationModels(), 200, ctx.requestId)
} catch (error) {
if (!(error instanceof ReferenceImageEstimateError)) throw error
return jsonError(ErrorCode.SYSTEM_INTERNAL, error.message, error.status, ctx.requestId)
}
})
}

View File

@ -1,12 +1,10 @@
import { NextRequest } from 'next/server'
import { handleRequest, jsonSuccess, jsonError } from '@/server/core/response'
import { handleRequest, jsonError } from '@/server/core/response'
import { ErrorCode } from '@/server/core/errors'
import { referenceEstimateRecordService, saveReferenceEstimateSchema } from '@/server/services/reference-estimate-record.service'
import { jsonEstimateRecord } from '@/server/services/reference-estimate-record-response'
export async function GET(request: NextRequest) {
return handleRequest(request, async ctx => jsonSuccess({ records: await referenceEstimateRecordService.list(ctx.user) }, 200, ctx.requestId))
}
export { GET } from './catalog/route'
export async function POST(request: NextRequest) {
return handleRequest(request, async ctx => {
const input = saveReferenceEstimateSchema.safeParse(await request.json().catch(() => null))

View File

@ -3,6 +3,7 @@ import { handleRequest } from '@/server/core/response'
import { referenceImageEstimateInputSchema } from '@/server/services/reference-image-estimate/reference-image-estimate-contracts'
import { assertReferenceEstimateAccess } from '@/server/services/reference-image-estimate/reference-estimate-access'
import { assertAccessoryAccess } from '@/server/services/intake-accessory-models/access'
import { readBackPanelSkills } from '@/server/services/reference-image-estimate/back-panel-skill.service'
import {
estimateReferenceImage,
ReferenceImageEstimateError,
@ -28,7 +29,7 @@ export async function POST(request: NextRequest) {
await assertAccessoryAccess(ctx.user)
const { accessoryModelDraftService } = await import('@/server/services/intake-accessory-models/drafts')
return accessoryModelDraftService.listForModeling()
})
}, readBackPanelSkills)
return NextResponse.json({ success: true, data })
} catch (error) {
if (!(error instanceof ReferenceImageEstimateError)) throw error

View File

@ -0,0 +1,26 @@
import { accessoryAssemblyTotals } from '@/lib/accessory-assembly-totals'
import type { AccessoryAssembly } from '@/lib/intake-accessory-assembly'
import type { AccessoryDraft } from '@/lib/intake-accessory-models'
export function AccessoryAssemblyTotals({ assembly, items }: {
assembly: AccessoryAssembly
items: readonly AccessoryDraft[]
}) {
const totals = accessoryAssemblyTotals(assembly, new Map(items.map(item => [item.id, item])))
const money = (value: number) => value.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 10 })
return <section className="space-y-2 border-t border-apple-separator pt-3 text-xs" aria-label="组合价格与重量">
<div className="flex flex-wrap justify-between gap-2 font-semibold">
<span>单价 {totals.price === null ? '待补齐' : '¥' + money(totals.price) + ' / 套'}</span>
<span>单套重量 {totals.weightGrams === null ? '待补齐' : totals.weightGrams + ' 克'}</span>
</div>
<ul className="space-y-1.5 text-apple-label-secondary">
{totals.members.map(member => <li key={member.id} className="flex flex-wrap justify-between gap-x-2 gap-y-1">
<span>{member.code} × 1</span>
<span>{member.missing ? '资料已移除' : [
member.price === null ? '缺单价' : '¥' + money(member.price),
member.weightGrams === null ? '缺重量' : member.weightGrams + ' 克',
].join(' · ')}</span>
</li>)}
</ul>
</section>
}

View File

@ -1,4 +1,5 @@
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { DndContext } from '@dnd-kit/core'
import { AccessoryAssemblyWorkspace } from './AccessoryAssemblyWorkspace'
import { downloadAccessoryGlb, saveAccessoryDraft } from './draft-client'
import { makeAccessoryAssembly } from './model-assembly'
@ -23,6 +24,25 @@ beforeEach(() => {
jest.mocked(saveAccessoryDraft).mockResolvedValue({ item: saved })
})
test('跨目录组合提供名称拖动入口,再编辑保存保留存放目录', async () => {
const directory = { module: 'accessory' as const, category: '工具类', folderId: null }
const moved = { ...saved, directory }
const onSaved = jest.fn()
jest.mocked(saveAccessoryDraft).mockResolvedValue({ item: moved })
const props = { rows: [...assemblySources, moved], items: [], initialId: moved.id, canEdit: true, canSave: true, onSaved }
const view = render(<DndContext><AccessoryAssemblyWorkspace {...props} canDrag={() => true} /></DndContext>)
await waitFor(() => expect(screen.getByRole('button', { name: '保存组合' })).toBeEnabled())
expect(view.container.querySelector('[data-accessory-drag="saved-assembly"]')).toHaveAttribute('data-drag-enabled', 'true')
fireEvent.change(screen.getByLabelText('组合名称'), { target: { value: '移动后编辑的组合' } })
fireEvent.click(screen.getByRole('button', { name: '保存组合' }))
await waitFor(() => expect(onSaved).toHaveBeenCalledWith(moved))
expect(saveAccessoryDraft).toHaveBeenCalledWith(expect.objectContaining({
id: moved.id, directory, name: '移动后编辑的组合', category: '三合一连接件', kind: CAM_KIT_KIND,
}), moved.photos, expect.objectContaining({ assembly: assemblyRecipe }), moved)
view.rerender(<DndContext><AccessoryAssemblyWorkspace {...props} canDrag={() => false} /></DndContext>)
expect(view.container.querySelector('[data-accessory-drag="saved-assembly"]')).toHaveAttribute('data-drag-enabled', 'false')
})
test('组合及所选零件可复制,复制不会提交未保存的位置更改', async () => {
const onCopy = jest.fn()
render(<AccessoryAssemblyWorkspace rows={[...assemblySources, saved]} items={[saved]} canEdit canSave onSaved={jest.fn()} onCopy={onCopy} />)
@ -478,7 +498,7 @@ test('应用设置实时计算中心位置并随组合保存,修改参数不
expect(makeAccessoryAssembly).toHaveBeenCalledTimes(generations)
fireEvent.click(screen.getByRole('button', { name: '保存组合' }))
await waitFor(() => expect(onSaved).toHaveBeenCalled())
expect(jest.mocked(saveAccessoryDraft).mock.lastCall![0].application).toEqual(assemblyApplication)
expect(jest.mocked(saveAccessoryDraft).mock.lastCall![0].application).toEqual({ ...assemblyApplication, dimensionBasis: 'actual-workpiece' })
const persisted = onSaved.mock.lastCall![0] as AccessoryDraft
view.unmount()
render(<AccessoryAssemblyWorkspace {...props} rows={[...assemblySources, persisted]} items={[persisted]} />)

View File

@ -10,9 +10,11 @@ import { accessoryDraftInputSchema, CAM_KIT_KIND, type AccessoryDraft } from '@/
import { accessoryAssemblySchema, assemblyCandidates, assemblyCombinationConflict, assemblyCombinationKey, assemblyCombinationMessage, assemblyRoleNames, assemblyRoles, assemblySelectionIssue, availableAssemblyCandidates, candidateComponent, componentCandidate, defaultAssembly, findSavedAssemblyCombination, normalizeAssemblyRecipe, type AccessoryAssembly, type AssemblyCandidate, type AssemblyRole } from '@/lib/intake-accessory-assembly'
import { downloadAccessoryGlb, saveAccessoryDraft, type DraftModel } from './draft-client'
import { accessoryApplicationSchema, type AccessoryApplicationDraft } from '@/lib/intake-accessory-application'
import { AccessoryModelName } from './AccessoryModelDragDrop'
import { AccessoryAssemblyApplication } from './AccessoryAssemblyApplication'
import { AccessoryModelName } from './AccessoryModelDragDrop'
import { AccessoryAssemblyProcessing, assemblyProcessing } from './AccessoryAssemblyProcessing'
import { accessoryAssemblyTotals } from '@/lib/accessory-assembly-totals'
import { AccessoryAssemblyTotals } from './AccessoryAssemblyTotals'
const Preview = dynamic(() => import('./AccessoryGlbPreview').then(m => m.AccessoryGlbPreview), { ssr: false })
const field = 'w-full min-w-0 rounded-md border border-[#d6dcd9] bg-white px-2 py-1.5 text-sm text-[#2d3335] outline-none focus:border-[#6c867a] focus:ring-1 focus:ring-[#6c867a] disabled:opacity-60'
@ -195,15 +197,16 @@ export function AccessoryAssemblyWorkspace({ rows, items, canEdit, canSave, init
const generatedSpecs = ['PXL + LJG', 'PXL + LJG + 套筒']
const spec = initial?.spec && !generatedSpecs.includes(initial.spec) ? initial.spec
: recipe.components.some(c => c.role === 'insert') ? generatedSpecs[1] : generatedSpecs[0]
const totals = accessoryAssemblyTotals(recipe, new Map(selected.map(item => [item.id, item])))
const input = accessoryDraftInputSchema.parse({
...(initial ? { id: initial.id, revision: initial.revision } : {}),
module: 'connector', category: '三合一连接件', kind: CAM_KIT_KIND, folderId: null, code, name,
directory: initial?.directory,
color: [...new Set(selected.map(c => c.color).filter(Boolean))].join(' / '),
material: [...new Set(selected.map(c => c.material).filter(Boolean))].join(' / '),
directory: initial?.directory,
spec, price: initial?.price ?? null, priceUnit: '套',
spec, price: totals.price, priceUnit: '套',
application, machining: processing?.machining,
weightGrams: initial?.weightGrams ?? null, dimensions: {}, pending: [], photos: initial?.photos ?? [], model,
weightGrams: totals.weightGrams, dimensions: {}, pending: [], photos: initial?.photos ?? [], model,
})
const { item } = await saveAccessoryDraft(input, initial?.photos ?? [], model, initial)
setDraft(current => ({ ...current, initial: item, code: item.code, name: item.name, automaticCode: false }))
@ -300,6 +303,7 @@ export function AccessoryAssemblyWorkspace({ rows, items, canEdit, canSave, init
</details>}
</section>
})}
<AccessoryAssemblyTotals assembly={recipe} items={rows} />
{processing && <AccessoryAssemblyProcessing assembly={recipe} items={rows} data={processing}
canEdit={canEdit} disabled={disabled} fieldClassName={field}
onChange={patch => { setDraft(current => ({ ...current, processing: { ...current.processing, ...patch } })); setFeedback('') }} />}

View File

@ -5,6 +5,7 @@ import Button from '@/components/ui/Button'
import { accessorySpec, CAM_KIT_KIND, type AccessoryDraft } from '@/lib/intake-accessory-models'
import { downloadAccessoryGlb, downloadAccessoryStep } from './draft-client'
import { AccessoryMachiningDetails } from './AccessoryMachiningDetails'
import { AccessoryAssemblyTotals } from './AccessoryAssemblyTotals'
import { accessoryScrewHeadDirection } from '@/lib/accessory-model-orientation'
const Preview = dynamic(() => import('./AccessoryGlbPreview').then((mod) => mod.AccessoryGlbPreview), {
@ -111,6 +112,7 @@ export function AccessoryModelDetail({ item, items, feedback, onBack, onEdit, on
</div>)}
<AccessoryMachiningDetails item={item} items={items} />
</dl>
{model?.assembly && <AccessoryAssemblyTotals assembly={model.assembly} items={items ?? []} />}
{model?.note && <p className="break-words text-apple-label-secondary">{model.note}</p>}
<div className="flex flex-wrap gap-2">
{onEdit && <Button size="small" onClick={onEdit}><Pencil size={15} />编辑资料</Button>}

View File

@ -70,7 +70,7 @@
font-size: 12px;
}
.sheetBody :global(.page-one),
.sheetBody :global(.page-two),
.sheetBody :global(.page-three) {
display: grid;
grid-template-columns: minmax(0, 1.55fr) minmax(0, 1fr);
@ -79,8 +79,7 @@
}
.sheetBody :global(.exploded-page) {
max-width: 850px;
margin-inline: auto;
min-width: 0;
}
.drawing {
@ -154,6 +153,6 @@
.sheetBody :global(.hardware-total) { font-weight: 650; }
@container (max-width: 810px) {
.sheetBody :global(.page-one),
.sheetBody :global(.page-two),
.sheetBody :global(.page-three) { grid-template-columns: minmax(0, 1fr); }
}

View File

@ -0,0 +1,112 @@
'use client'
import { useMemo, useState } from 'react'
import { createPortal } from 'react-dom'
import { Check, ChevronDown, Search } from 'lucide-react'
import { FloatingTablePagination } from '@/components/platform/FloatingTablePagination'
import Modal from '@/components/ui/Modal'
import type { NonIntegratedBomBoardMaterialOption } from '@/lib/non-integrated-bom-board-materials'
import { filterEstimateBoards } from '@/lib/reference-estimator/standard/board-library-options'
import styles from './estimate-board-picker.module.css'
const boardTypes = {
主体板材: ['密度板', '刨花板', '生态板', '橡胶木'],
背板材料: ['三合板', '刨花板'],
}
export function EstimateBoardPicker({ field, value, label, categoryHint, options, disabled, onSelect }: {
field: keyof typeof boardTypes; value?: string; label?: string; categoryHint?: string
options: readonly NonIntegratedBomBoardMaterialOption[]
disabled: boolean; onSelect: (id: string) => void
}) {
const [mounted, setMounted] = useState(false)
const [open, setOpen] = useState(false)
const [category, setCategory] = useState('')
const [query, setQuery] = useState('')
const [page, setPage] = useState(1)
const [pageSize, setPageSize] = useState(30)
const categories = useMemo(() => {
const counts = new Map(boardTypes[field].map(type => [type, 0]))
for (const option of options) counts.set(option.categoryName, (counts.get(option.categoryName) ?? 0) + 1)
return [...counts].map(([name, count]) => ({ name, count }))
}, [field, options])
const matches = useMemo(() => open ? filterEstimateBoards(options, category, query) : [], [open, options, category, query])
const pages = Math.max(1, Math.ceil(matches.length / pageSize))
const shown = Math.min(page, pages)
const paginated = matches.length > 15
const select = (id: string) => {
setOpen(false)
onSelect(id)
}
return <div className={styles.field}>
<span>{field}</span>
<button type="button" aria-label={field} aria-haspopup="dialog" aria-expanded={open}
className={styles.trigger} title={label} disabled={disabled} onClick={() => {
setCategory(options.find(option => option.id === value)?.categoryName
?? categories.find(type => type.name === categoryHint && type.count > 0)?.name
?? categories.find(type => type.count > 0)?.name ?? boardTypes[field][0])
setQuery('')
setPage(1)
setMounted(true)
setOpen(true)
}}>
<span>{label ?? (field === '背板材料' ? '请选择背板' : '请选择板材')}</span><ChevronDown size={14} aria-hidden="true"/>
</button>
{mounted && createPortal(<Modal title={`选择${field}`} variant="compact" size="large" className={styles.modal} bodyClassName={styles.modalBody}
isOpen={open} onClose={() => setOpen(false)}>
<div className={styles.panel}>
<div className={styles.types} role="group" aria-label="板材类型">{categories.map(type =>
<button key={type.name} type="button" className={styles.type} aria-label={type.name} aria-pressed={category === type.name}
onClick={() => { setCategory(type.name); setPage(1) }}>
<span>{type.name}</span><span className={styles.count}>{type.count}</span>
</button>)}</div>
<div className={styles.main}>
<div className={styles.filters}>
<label className={styles.search}>
<Search size={15} aria-hidden="true"/>
<input type="search" aria-label="搜索板材规格" placeholder="搜索厚度、花色、贴面或料号"
value={query} onChange={event => { setQuery(event.target.value); setPage(1) }}/>
</label>
</div>
<div className={styles.resultArea}>
<div className={`${styles.results} ${paginated ? styles.paged : ''}`}
key={JSON.stringify([category, query, shown, pageSize])}>
<table className={styles.table} aria-label="板材规格">
<thead><tr>
<th scope="col">花色</th><th scope="col">厚度 (mm)</th><th scope="col">等级</th>
<th scope="col">贴面</th><th scope="col">料号</th><th scope="col">kg/张</th>
<th scope="col"><span className="sr-only">已选</span></th>
</tr></thead>
<tbody>{matches.slice((shown - 1) * pageSize, shown * pageSize).map(option =>
<tr className={styles.option} key={option.id} data-selected={option.id === value}
onClick={() => select(option.id)}>
<td className={styles.finish}>
<button type="button" className={styles.select} aria-pressed={option.id === value}
aria-label={`选择 ${option.selectionLabel},料号 ${option.code}`}>
{option.finishLabel || option.displayName}
</button>
</td>
<td className={styles.thickness}>{option.thicknessMm}<span className={styles.unit}> mm</span></td>
<td className={styles.grade}>{option.environmentGradeName || '—'}</td>
<td className={styles.veneer}>{option.surfaceOptionName || '—'}</td>
<td className={styles.code}>{option.code}</td>
<td className={styles.weight}>{option.weightKg == null ? '—' : <>
{option.weightKg}<span className={styles.unit}> kg/张</span>
</>}</td>
<td className={styles.mark}>{option.id === value && <Check size={16} aria-hidden="true"/>}</td>
</tr>)}</tbody>
</table>
{!matches.length && <p className={styles.empty} role="status">
{query.trim() ? '没有匹配的板材' : '该类型暂无可用板材'}
</p>}
</div>
{paginated && <FloatingTablePagination page={shown} pageSize={pageSize} total={matches.length}
totalPages={pages} loading={false} pageSizes={[15, 30, 50]} onPageChange={setPage}
onPageSizeChange={size => { setPageSize(size); setPage(1) }}/>}
</div>
</div>
</div>
</Modal>, document.body)}
</div>
}

View File

@ -1,10 +1,13 @@
'use client'
import { useMemo } from 'react'
import Image from 'next/image'
import Button from '@/components/ui/Button'
import type { EstimateDocument } from '@/lib/reference-estimator/contracts'
import { toMaterialSnapshot } from '@/lib/reference-estimator/material-contract'
import type { NonIntegratedBomBoardMaterialOption } from '@/lib/non-integrated-bom-board-materials'
import { isEstimateBackBoard } from '@/lib/reference-estimator/standard/board-library-options'
import { EstimateBoardPicker } from './EstimateBoardPicker'
import styles from './estimate.module.css'
export type EstimateInputController = {
@ -22,20 +25,17 @@ export type ReferenceImageFeedback = { text: string; error?: boolean; retrySave?
function materialChoices(c: EstimateInputController, back: boolean) {
const { document: d } = c, input = d.standardTemplate?.cabinet?.input
const options = c.options.filter(item => item.categoryName.includes('三合') === back)
const saved = back ? d.backMaterial : d.mainMaterial
const pending = input && !saved
? [input.grade, back ? '三合板' : input.material, back ? input.backThickness : input.thickness,
back ? input.backColor || input.bodyColor : input.bodyColor, input.veneer]
: null
const pendingSpec = pending?.filter(Boolean).map(item => typeof item === 'number' ? item + 'mm' : item).join(' · ')
const value = saved?.id ?? (pendingSpec ? '__pending_material_spec__' : '')
return { value, options: <>
<option value="" disabled={Boolean(input)}>{back ? '请选择背板' : '请选择板材'}</option>
{pendingSpec && <option value={value} disabled>待选规格:{pendingSpec}</option>}
{saved && !options.some(item => item.id === saved.id) && <option value={saved.id}>{saved.name}(已保存)</option>}
{options.map(item => <option key={item.id} value={item.id}>{item.selectionLabel}</option>)}
</> }
const value = saved?.id
const label = c.options.find(item => item.id === saved?.id)?.selectionLabel ?? saved?.name
?? (pendingSpec ? `待选规格:${pendingSpec}` : undefined)
const category = saved?.selection?.category ?? (back ? '三合板' : input?.material)
return { value, label, category }
}
export function EstimateInputPanel({
@ -43,14 +43,18 @@ export function EstimateInputPanel({
imageFeedback,
onRetryImageSave,
pagePaste = false,
variantTrial = false,
}: {
controller: EstimateInputController
imageFeedback?: ReferenceImageFeedback
onRetryImageSave?: () => void
pagePaste?: boolean
variantTrial?: boolean
}) {
const { document: d } = c
const main = materialChoices(c, false), back = materialChoices(c, true)
const mainOptions = useMemo(() => c.options.filter(item => !item.categoryName.includes('三合')), [c.options])
const backOptions = useMemo(() => c.options.filter(isEstimateBackBoard), [c.options])
return <aside className={styles.inputPanel}>
<h3>参考图预估成本</h3>
<div className={styles.upload} onPaste={pagePaste ? undefined : event => {
@ -69,15 +73,18 @@ export function EstimateInputPanel({
)}
</div>
<label>补充说明<textarea aria-label="补充说明" value={d.imageNote} placeholder="填写图片看不清的尺寸、材质或需要纠正的地方" onChange={event => c.update(current => ({ ...current, imageNote: event.target.value }))} /></label>
<Button size="small" disabled={Boolean(c.busy) || !d.imageUrl} onClick={() => void c.analyze()}>识别参考图</Button>
<Button size="small" disabled={Boolean(c.busy) || (!variantTrial && !d.imageUrl)} onClick={() => void c.analyze()}>
{variantTrial ? '按说明修改模型' : '识别参考图'}
</Button>
{d.structure && <Button size="small" variant="gray" disabled={Boolean(c.busy) || Boolean(c.skillIssue)} onClick={() => void c.applyNotes()}>更新测算</Button>}
<label>主体板材<select aria-label="主体板材" value={main.value} onChange={event => c.chooseMain(event.target.value)}>
{main.options}
</select></label>
<label>背板材料<select aria-label="背板材料" value={back.value} onChange={event => {
const option = c.options.find(item => item.id === event.target.value)
c.update(current => ({ ...current, backMaterial: option ? toMaterialSnapshot(option, true) : null,
settings: option ? { ...current.settings, backThicknessMm: option.thicknessMm } : current.settings }))
}}>{back.options}</select></label>
<EstimateBoardPicker field="主体板材" value={main.value} label={main.label} categoryHint={main.category} options={mainOptions}
disabled={Boolean(c.busy)} onSelect={c.chooseMain}/>
<EstimateBoardPicker field="背板材料" value={back.value} label={back.label} categoryHint={back.category} options={backOptions}
disabled={Boolean(c.busy)} onSelect={id => {
const option = backOptions.find(item => item.id === id)
if (!option) return
c.update(current => ({ ...current, backMaterial: toMaterialSnapshot(option, true),
settings: { ...current.settings, backThicknessMm: option.thicknessMm } }))
}}/>
</aside>
}

View File

@ -11,7 +11,7 @@ import { ImageSkillRecords } from './standard/ImageSkillRecords'
import { EstimateStageSkillLibrary, EstimateStandardLinks } from './EstimateStageSkillLibrary'
import styles from './skill-library.module.css'
export function EstimateSkillLibrary({ quotes }: { quotes?: ReactNode }) {
export function EstimateSkillLibrary({ quotes, userId }: { quotes?: ReactNode; userId?: string }) {
const statusLabel=(status:string)=>status==='confirmed'?'已确认':status==='testing'?'测试中':'讨论中'
const [request, setRequest] = useState<SkillLibraryRequest | null>(null)
const [selectedId, setSelectedId] = useState('cabinet-standard')
@ -64,7 +64,7 @@ export function EstimateSkillLibrary({ quotes }: { quotes?: ReactNode }) {
<nav className={styles.libraryTabs} aria-label="测算技能分类">{skillSections.map(([key, label]) =>
<button key={key} type="button" aria-pressed={section === key} onClick={() => setSection(key)}>{label}</button>)}</nav>
<div key={section} className={styles.libraryContent}>
{section === 'skills' ? <EstimateSkillMaintenance onOpenSection={setSection}/> : section !== 'model' ? <EstimateStageSkillLibrary section={section} quotes={quotes}/> : <>
{section === 'skills' ? <EstimateSkillMaintenance key={userId} userId={userId}/> : section !== 'model' ? <EstimateStageSkillLibrary section={section} quotes={quotes}/> : <>
<label className={styles.search}>材质<select aria-label="按材质筛选技能" value={material} onChange={e => setMaterial(e.target.value)}>
<option value="">全部材质</option>{materialTypes.map(value=><option key={value}>{value}</option>)}
</select></label>

View File

@ -1,10 +1,17 @@
'use client'
import type { SubstrateDTO } from '@/server/services'
import { StandardEstimator } from './standard/StandardEstimator'
import { lazy, Suspense } from 'react'
import { EstimateCatalogEntry } from './catalog/EstimateCatalog'
import type { EstimateCatalogRecord } from './catalog/estimate-catalog'
export function ReferenceEstimatorDomain({ materialLibrarySubstrates = [], userId, canPushToLibrary }: {
materialLibrarySubstrates?: SubstrateDTO[]; userId?: string; canPushToLibrary?: boolean
const EstimateWorkbenchEntry = lazy(() => import('./standard/EstimateWorkbenchEntry').then(module => ({ default: module.EstimateWorkbenchEntry })))
export function ReferenceEstimatorDomain({ userId, canPushToLibrary, initialRecords }: {
userId: string; canPushToLibrary: boolean; initialRecords?: EstimateCatalogRecord[]
}) {
return <StandardEstimator substrates={materialLibrarySubstrates} userId={userId} canPushToLibrary={canPushToLibrary} />
return <EstimateCatalogEntry initialRecords={initialRecords}>
<Suspense fallback={<p className="p-4 text-sm text-zinc-500" role="status">正在打开测算工作台…</p>}>
<EstimateWorkbenchEntry userId={userId} canPushToLibrary={canPushToLibrary} />
</Suspense>
</EstimateCatalogEntry>
}

View File

@ -1,13 +1,14 @@
'use client'
import { useEffect, useMemo, useState, type ReactNode } from 'react'
import { useMemo, useState, type ReactNode } from 'react'
import { useSearchParams } from 'next/navigation'
import { ArrowLeft, ChevronDown, ImageOff, Plus, Search } from 'lucide-react'
import Button from '@/components/ui/Button'
import { SearchableMultiSelect } from '@/components/platform/SearchableMultiSelect'
import { REFERENCE_ESTIMATOR_PATH } from '@/config/intake-library-navigation'
import { linkedReferenceEstimateId } from '../referenceEstimateLinks'
import { estimateCatalogWorkbenchHref, isCatalogWorkbench, loadEstimateCatalog, type EstimateCatalogCard } from './estimate-catalog'
import { estimateCatalogWorkbenchHref, isCatalogWorkbench, type EstimateCatalogRecord } from './estimate-catalog'
import { useEstimateCatalog } from './useEstimateCatalog'
import styles from './estimate-catalog.module.css'
const filters = [
@ -17,9 +18,9 @@ const filters = [
] as const
type Filter = typeof filters[number][0]
export function EstimateCatalogEntry({ children }: { children: ReactNode }) {
export function EstimateCatalogEntry({ children, initialRecords }: { children: ReactNode; initialRecords?: EstimateCatalogRecord[] }) {
const search = useSearchParams()?.toString() ?? ''
return isCatalogWorkbench(search) || linkedReferenceEstimateId(search) ? children : <EstimateCatalog />
return isCatalogWorkbench(search) || linkedReferenceEstimateId(search) ? children : <EstimateCatalog initialRecords={initialRecords} />
}
export function BackToEstimateCatalog() {
@ -44,30 +45,18 @@ function EstimateCover({ image }: { image: string | null }) {
</div>
}
function EstimateCatalog() {
const [cards, setCards] = useState<EstimateCatalogCard[] | null>(null)
const [error, setError] = useState('')
const [attempt, setAttempt] = useState(0)
function EstimateCatalog({ initialRecords }: { initialRecords?: EstimateCatalogRecord[] }) {
const { cards, error, retryRecords, libraryStatus, retryLibrary } = useEstimateCatalog(initialRecords)
const [filter, setFilter] = useState<Filter>('all')
const [query, setQuery] = useState('')
const [categories, setCategories] = useState<string[]>([])
const [order, setOrder] = useState<'recent' | 'oldest'>('recent')
useEffect(() => {
const controller = new AbortController()
void loadEstimateCatalog(controller.signal).then(result => {
if (!controller.signal.aborted) setCards(result)
}).catch(cause => {
if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : '无法读取测算清单')
})
return () => controller.abort()
}, [attempt])
const allCategories = useMemo(() => [...new Set(cards?.map(card => card.category))].sort((a, b) => a.localeCompare(b, 'zh-CN')), [cards])
const visible = useMemo(() => {
const term = query.trim().toLowerCase()
const matches = (cards ?? []).filter(card => {
if (filter === 'bound' && !card.spu) return false
if (filter === 'bound' && !card.spu && !card.unavailableSpu) return false
if (filter === 'unbound' && (card.spu || card.unavailableSpu)) return false
if (categories.length && !categories.includes(card.category)) return false
return !term || [card.title, card.spu ?? '', ...card.barcodes].some(value => value.toLowerCase().includes(term))
@ -109,8 +98,12 @@ function EstimateCatalog() {
</div>
</header>
<div className={styles.results} role="region" aria-label="测算结果" tabIndex={0}>
{!!cards?.length && libraryStatus === 'failed' && <div className="mb-3 flex items-center gap-2 text-sm" role="status">
SPU 资料暂不可用,仍可打开测算单。
<Button size="small" variant="gray" onClick={retryLibrary}>重试读取 SPU</Button>
</div>}
{error ? <div className={styles.message} role="alert">{error}
<Button size="small" variant="gray" onClick={() => { setError(''); setAttempt(value => value + 1) }}>重试</Button>
<Button size="small" variant="gray" onClick={retryRecords}>重试</Button>
</div> : !cards ? <p className={styles.message} role="status">正在读取测算清单…</p> :
visible.length === 0 ? <p className={styles.message}>{cards.length ? '没有符合当前筛选的测算单' : '还没有保存的测算单'}</p> :
<ul className={styles.gallery}>
@ -119,7 +112,7 @@ function EstimateCatalog() {
<EstimateCover key={card.image} image={card.image} />
<h2>{card.title}</h2>
<div className={styles.metadata}>
<span className={card.spu ? styles.spu : undefined}>{card.spu ?? (card.unavailableSpu ? 'SPU 不可用' : '未关联 SPU')}</span>
<span className={card.spu ? styles.spu : undefined}>{card.spu ?? (libraryStatus === 'loading' ? 'SPU 读取中' : card.unavailableSpu ? 'SPU 不可用' : '未关联 SPU')}</span>
{!card.unavailableSpu && <span>{card.barcodes.length} 个条码</span>}
</div>
</a>

View File

@ -1,6 +1,6 @@
import { REFERENCE_ESTIMATOR_PATH } from '@/config/intake-library-navigation'
import type { ProductArchive, ProductArchiveList } from '@/lib/product-library/contracts'
import { estimateWorkspaceSlotSchema } from '@/lib/reference-estimator/contracts'
import { estimateWorkspaceSlotSchema } from '@/lib/reference-estimator/workspace-slot-contract'
import { withEstimateReadTimeout } from '../estimate-read'
export type EstimateCatalogRecord = {
@ -24,24 +24,17 @@ export type EstimateCatalogCard = {
unavailableSpu?: boolean
}
async function getCatalogData<T>(path: string, signal: AbortSignal, optional = false): Promise<T | null> {
export function loadEstimateCatalogRecords(signal: AbortSignal): Promise<EstimateCatalogRecord[]> {
return withEstimateReadTimeout(async readSignal => {
const response = await fetch(path, { signal: readSignal })
if (optional && response.status === 403) return null
const response = await fetch('/api/intake/reference-estimates/catalog', { signal: readSignal, cache: 'no-store' })
const body = await response.json().catch(() => null)
if (!response.ok || !body?.success) throw new Error(body?.error?.message ?? '无法读取测算清单')
return body.data as T
if (!response.ok || !body?.success || !Array.isArray(body.data?.records)) {
throw new Error(body?.error?.message ?? '无法读取测算清单')
}
return body.data.records
}, signal)
}
export async function loadEstimateCatalog(signal: AbortSignal) {
const [estimates, library] = await Promise.all([
getCatalogData<{ records: EstimateCatalogRecord[] }>('/api/intake/reference-estimates', signal),
getCatalogData<ProductArchiveList>('/api/intake/product-library', signal, true),
])
return buildEstimateCatalog(estimates?.records ?? [], library)
}
export function buildEstimateCatalog(records: readonly EstimateCatalogRecord[], library: ProductArchiveList | null) {
const archives = library?.archives ?? []
const byId = new Map(archives.map(archive => [archive.id, archive]))
@ -55,7 +48,8 @@ export function buildEstimateCatalog(records: readonly EstimateCatalogRecord[],
const sorted = [...records].sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))
for (const record of sorted) {
const slot = estimateWorkspaceSlotSchema.safeParse(record.workspaceSlot).data
const archive = slot?.kind === 'barcode' ? byId.get(slot.archiveId) : byEstimate.get(record.id)
const binding = slot?.kind === 'barcode' ? slot : undefined
const archive = binding ? byId.get(binding.archiveId) : byEstimate.get(record.id)
const spu = archive?.spu?.trim() || null
const image = archive?.image || record.imageUrl || null
const category = categories.get(archive?.categoryConfigId ?? '') || archive?.sourceCategory || record.category || '未分类'
@ -70,11 +64,11 @@ export function buildEstimateCatalog(records: readonly EstimateCatalogRecord[],
title: spu ? archive!.name : record.title,
image,
spu,
barcodes: spu ? [...new Set(archive!.barcodes.filter(Boolean))] : [],
barcodes: spu ? [...new Set(archive!.barcodes.filter(Boolean))] : binding ? [binding.barcode] : [],
category,
updatedAt: record.updatedAt,
archiveId: spu ? archive?.id : undefined,
unavailableSpu: slot?.kind === 'barcode' && !spu,
archiveId: spu ? archive?.id : binding?.archiveId,
unavailableSpu: Boolean(binding && !spu),
}
if (key) grouped.set(key, card)
cards.push(card)

View File

@ -2,7 +2,7 @@ import { act, fireEvent, render, renderHook, screen } from '@testing-library/rea
import type { ProductArchive } from '@/lib/product-library/contracts'
import { newStandardDocument } from '@/lib/reference-estimator/standard/workbook'
import { EstimateCatalogEntry } from './EstimateCatalog'
import { loadEstimateCatalog } from './estimate-catalog'
import { readEstimateProductCatalog } from '../estimate-product-catalog'
import { listEstimateSpus } from '../standard/estimate-workspace-slots'
import { useEstimateWorkspaceSlots } from '../standard/useEstimateWorkspaceSlots'
import { EstimateSpuDialog } from '../standard/EstimateSpuDialog'
@ -17,6 +17,7 @@ const archive: ProductArchive = {
}
const slot = { kind: 'barcode' as const, archiveId: archive.id, barcode: archive.barcodes[0] }
const records = [{ id: 'estimate-01', title: '第一款测算', updatedAt: '2026-11-26', workspaceSlot: slot }]
const recordsUrl = '/api/intake/reference-estimates/catalog'
const library = { archives: [archive], categories: [{ id: 'shelves', categoryL2: '书柜' }] }
const detail = {
productInfo: { variants: archive.barcodes.map(barcode => ({ barcode })) },
@ -51,37 +52,75 @@ afterEach(() => {
it('清单与 SPU 读取新入口,保留产品与条码关联', async () => {
fetchMock.mockImplementation(async url => {
if (url === '/api/intake/reference-estimates') return response({ records })
expect(url).toBe('/api/intake/product-library')
if (url === recordsUrl) return response({ records })
expect(url).toBe('/api/intake/product-library/catalog')
return response(library)
})
const cards = await loadEstimateCatalog(new AbortController().signal)
expect(cards).toMatchObject([{
id: 'estimate-01', title: archive.name, spu: 'SG0164', archiveId: archive.id, barcodes: archive.barcodes,
}])
await act(async () => { render(<EstimateCatalogEntry><div>工作台</div></EstimateCatalogEntry>) })
expect(screen.getByRole('link', { name: /六格开放书柜.*SG0164/ })).toHaveAttribute('href',
expect.stringContaining('archiveId=' + archive.id))
await act(async () => { fireEvent.change(screen.getByRole('searchbox'), { target: { value: archive.barcodes[2] } }) })
expect(screen.getByRole('link', { name: /六格开放书柜/ })).toBeInTheDocument()
expect(await listEstimateSpus()).toEqual([archive])
expect(jest.getTimerCount()).toBe(0)
})
it('首屏直接显示服务器返回的清单,等 SPU 时仍可打开测算', async () => {
let finishLibrary: (value: Response) => void = () => {}
fetchMock.mockImplementation(() => new Promise(resolve => { finishLibrary = resolve }))
render(<EstimateCatalogEntry initialRecords={records}><div>工作台</div></EstimateCatalogEntry>)
expect(screen.getByRole('link', { name: /第一款测算.*SPU 读取中/ })).toHaveAttribute('href',
expect.stringContaining('estimateId=estimate-01'))
expect(fetchMock.mock.calls.map(([url]) => url)).toEqual(['/api/intake/product-library/catalog'])
await act(async () => { finishLibrary(response(library)) })
expect(screen.getByRole('link', { name: /六格开放书柜.*SG0164/ })).toBeInTheDocument()
})
it('仅在新目录不存在时用兼容入口,保留原有权限边界', async () => {
fetchMock.mockResolvedValueOnce(response(null, 404)).mockResolvedValueOnce(response(library))
await expect(readEstimateProductCatalog()).resolves.toEqual(library)
expect(fetchMock.mock.calls.map(([url]) => url)).toEqual(['/api/intake/product-library/catalog', '/api/intake/product-library'])
fetchMock.mockClear().mockResolvedValueOnce(response(null, 403))
await expect(readEstimateProductCatalog()).resolves.toBeNull()
expect(fetchMock).toHaveBeenCalledTimes(1)
})
it('产品资料无权限时仍展示测算,并保留已关联标识', async () => {
fetchMock.mockImplementation(async url => url === '/api/intake/reference-estimates'
fetchMock.mockImplementation(async url => url === recordsUrl
? response({ records }) : response(null, 403))
expect(await loadEstimateCatalog(new AbortController().signal)).toMatchObject([{
id: 'estimate-01', spu: null, unavailableSpu: true,
}])
await act(async () => { render(<EstimateCatalogEntry><div>工作台</div></EstimateCatalogEntry>) })
expect(screen.getByRole('link', { name: /第一款测算.*SPU 不可用/ })).toHaveAttribute('href',
expect.stringContaining('archiveId=' + archive.id))
})
it('清单卡住 15 秒后显示错误,点击重试可恢复', async () => {
it('产品资料超时也能打开测算,重试关联资料时保留清单', async () => {
let stalled = true
fetchMock.mockImplementation(async (url, options) => {
if (url === '/api/intake/reference-estimates') return response({ records })
if (url === recordsUrl) return response({ records })
return stalled ? pendingRead(options?.signal) : response(library)
})
render(<EstimateCatalogEntry><div>工作台</div></EstimateCatalogEntry>)
expect(screen.getByRole('status')).toHaveTextContent('正在读取测算清单')
await act(async () => {})
expect(screen.getByRole('link', { name: /第一款测算/ })).toBeInTheDocument()
await act(async () => { jest.advanceTimersByTime(15_000) })
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
expect(screen.getByRole('status')).toHaveTextContent('仍可打开测算单')
fireEvent.click(screen.getByRole('button', { name: '已关联 SPU', exact: true }))
expect(screen.getByRole('link', { name: /第一款测算/ })).toBeInTheDocument()
stalled = false
await act(async () => { fireEvent.click(screen.getByRole('button', { name: '重试读取 SPU' })) })
expect(screen.getByRole('link', { name: /六格开放书柜.*SG0164/ })).toBeInTheDocument()
expect(fetchMock.mock.calls.filter(([url]) => url === recordsUrl)).toHaveLength(1)
})
it('测算记录本身超时才显示整页读取错误,重试后可恢复', async () => {
let stalled = true
fetchMock.mockImplementation(async (url, options) => url === recordsUrl
? stalled ? pendingRead(options?.signal) : response({ records })
: response(library))
render(<EstimateCatalogEntry><div>工作台</div></EstimateCatalogEntry>)
await act(async () => { jest.advanceTimersByTime(15_000) })
expect(screen.getByRole('alert')).toHaveTextContent('读取超过 15 秒')
expect(screen.queryByRole('status')).not.toBeInTheDocument()
stalled = false
await act(async () => { fireEvent.click(screen.getByRole('button', { name: '重试' })) })
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
@ -109,7 +148,7 @@ it('已绑定 SPU 失败后可重试,迟到的旧档案响应不会覆盖当
let stalled = true
let releaseOld: (value: Response) => void = () => {}
fetchMock.mockImplementation(async (url, options) => {
if (url === '/api/intake/product-library') {
if (url === '/api/intake/product-library/catalog') {
if (stalled) return pendingRead(options?.signal)
return response({ ...library, archives: [archive, { ...archive, id: 'other-archive', spu: 'OTHER' }] })
}
@ -136,7 +175,7 @@ it('SPU 选择窗口的清单和条码详情都能在失败后重试', async ()
let listStalled = true
let detailStalled = true
fetchMock.mockImplementation(async (url, options) => {
if (url === '/api/intake/product-library') {
if (url === '/api/intake/product-library/catalog') {
return listStalled ? pendingRead(options?.signal) : response(library)
}
return detailStalled ? pendingRead(options?.signal) : response(detail)

View File

@ -0,0 +1,41 @@
import { useEffect, useMemo, useState } from 'react'
import type { ProductArchiveList } from '@/lib/product-library/contracts'
import { readEstimateProductCatalog } from '../estimate-product-catalog'
import { buildEstimateCatalog, loadEstimateCatalogRecords, type EstimateCatalogRecord } from './estimate-catalog'
type ReadState<T> = { status: 'loading' } | { status: 'ready'; data: T } | { status: 'failed'; message: string }
function useCatalogRead<T>(read: (signal: AbortSignal) => Promise<T>, fallback: string, initial?: T) {
const [loaded, setLoaded] = useState<ReadState<T>>({ status: 'loading' })
const [attempt, setAttempt] = useState(0)
useEffect(() => {
if (initial !== undefined && attempt === 0) return
const controller = new AbortController()
void read(controller.signal).then(data => {
if (!controller.signal.aborted) setLoaded({ status: 'ready', data })
}, error => {
if (!controller.signal.aborted) {
setLoaded({ status: 'failed', message: error instanceof Error ? error.message : fallback })
}
})
return () => controller.abort()
}, [read, fallback, attempt, initial])
const state: ReadState<T> = initial !== undefined && attempt === 0 ? { status: 'ready', data: initial } : loaded
return { state, retry: () => { setLoaded({ status: 'loading' }); setAttempt(value => value + 1) } }
}
export function useEstimateCatalog(initialRecords?: EstimateCatalogRecord[]) {
const records = useCatalogRead<EstimateCatalogRecord[]>(loadEstimateCatalogRecords, '无法读取测算清单', initialRecords)
const library = useCatalogRead<ProductArchiveList | null>(readEstimateProductCatalog, '无法读取产品资料')
const recordData = records.state.status === 'ready' ? records.state.data : null
const libraryData = library.state.status === 'ready' ? library.state.data : null
const cards = useMemo(() => recordData && buildEstimateCatalog(recordData, libraryData), [recordData, libraryData])
return {
cards,
error: records.state.status === 'failed' ? records.state.message : '',
retryRecords: records.retry,
libraryStatus: library.state.status,
retryLibrary: library.retry,
}
}

View File

@ -0,0 +1,88 @@
.field { display: grid; gap: 5px; min-width: 0; color: #59636b; font-size: 11px; }
.trigger {
display: flex; align-items: center; justify-content: space-between; gap: 6px; min-width: 0;
border: 1px solid var(--obs-shell-border, #dfe4e7); border-radius: 6px;
background: var(--obs-shell-panel-bg, #fff); color: #242b30; padding: 7px 8px; font-size: 12px; text-align: left;
}
.trigger span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.trigger svg, .search svg { flex: none; }
.trigger:focus-visible, .type:focus-visible, .select:focus-visible { outline: 2px solid #7c9690; outline-offset: -2px; }
.modal.modal { max-width: 720px; }
.modal > :first-child { padding: 5px 14px 5px 16px; }
.modal > :first-child h2 { font-size: 14px; }
.modal > :first-child button { min-width: 36px; min-height: 36px; }
.modalBody { min-height: 0; padding: 0; overflow: hidden; }
.panel {
display: grid; grid-template-columns: 116px minmax(0, 1fr); height: min(57dvh, 400px);
min-height: 0; border-top: 1px solid var(--obs-shell-border, #dfe4e7); font-size: 13px;
}
.types {
display: flex; flex-direction: column; gap: 4px; padding: 8px 6px; overflow: auto;
border-right: 1px solid var(--obs-shell-border, #dfe4e7); background: var(--obs-shell-muted-bg, #f5f6f6);
}
.type {
display: flex; align-items: center; justify-content: space-between; gap: 8px; flex: none;
padding: 7px 8px; border-radius: 5px; text-align: left; white-space: nowrap;
}
.type:hover { background: var(--obs-shell-hover-bg, #ecefef); }
.type[aria-pressed=true] { background: var(--obs-shell-panel-bg, #fff); color: var(--obs-shell-title, #242b30); font-weight: 600; }
.count { color: var(--obs-shell-muted, #59636b); font-size: 11px; font-weight: 400; font-variant-numeric: tabular-nums; }
.main { display: flex; flex-direction: column; min-width: 0; min-height: 0; }
.filters { flex: none; padding: 8px 10px; border-bottom: 1px solid var(--obs-shell-border, #dfe4e7); }
.search {
display: flex; align-items: center; gap: 8px;
min-width: 0; width: 100%; border: 1px solid var(--obs-shell-border, #dfe4e7); border-radius: 6px;
background: var(--obs-shell-panel-bg, #fff); color: var(--obs-shell-muted, #59636b); padding: 0 10px;
}
.search:focus-within { outline: 2px solid #7c9690; outline-offset: -2px; }
.search input { width: 100%; min-width: 0; padding: 6px 0; border: 0; outline: none; background: transparent; color: var(--obs-shell-text, #242b30); }
.resultArea { position: relative; flex: 1; min-height: 0; }
.results { height: 100%; overflow: auto; overscroll-behavior: contain; scrollbar-width: thin; }
.paged { padding-bottom: 96px; }
.table { width: 100%; min-width: 492px; border-collapse: separate; border-spacing: 0; text-align: left; }
.table th {
position: sticky; top: 0; z-index: 1; padding: 6px 7px; border-bottom: 1px solid var(--obs-shell-border, #dfe4e7);
background: var(--obs-shell-muted-bg, #f5f6f6); color: var(--obs-shell-muted, #59636b); font-size: 11px; font-weight: 500; white-space: nowrap;
}
.table td { padding: 0 7px; border-bottom: 1px solid var(--obs-shell-border, #eef0f1); vertical-align: middle; }
.table th:first-child, .table td:first-child { padding-left: 10px; }
.option { cursor: pointer; }
.option:hover, .option:focus-within { background: var(--obs-shell-hover-bg, #f5f6f6); }
.option[data-selected=true] { background: var(--obs-shell-muted-bg, #f5f6f6); }
.finish { width: 32%; min-width: 110px; overflow-wrap: anywhere; }
.select { display: block; width: 100%; min-height: 35px; padding: 7px 0; text-align: left; font-weight: 550; }
.thickness, .weight { white-space: nowrap; font-variant-numeric: tabular-nums; }
.code { color: var(--obs-shell-muted, #59636b); font-size: 12px; white-space: nowrap; }
.mark { width: 28px; color: var(--obs-shell-title, #242b30); }
.unit { display: none; }
.empty { padding: 40px 15px; color: var(--obs-shell-muted, #59636b); text-align: center; }
@media (max-width: 700px) {
.panel { grid-template-columns: 104px minmax(0, 1fr); }
.paged { padding-bottom: 128px; }
}
@media (max-width: 600px) {
.panel { grid-template-columns: minmax(0, 1fr); grid-template-rows: auto minmax(0, 1fr); height: min(63dvh, 400px); }
.types { flex-direction: row; padding: 6px 8px; border-right: 0; border-bottom: 1px solid var(--obs-shell-border, #dfe4e7); }
.type { gap: 5px; padding: 8px; }
.filters { padding: 10px; }
.table { display: block; min-width: 0; }
.table thead { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); }
.table tbody { display: block; }
.table .option {
display: grid; grid-template-columns: minmax(0, 1fr) auto auto auto 16px; gap: 3px 8px;
align-items: center; padding: 9px 12px; border-bottom: 1px solid var(--obs-shell-border, #eef0f1);
}
.table td, .table td:first-child { width: auto; min-width: 0; padding: 0; border: 0; }
.finish { grid-column: 1 / 4; grid-row: 1; }
.select { min-height: 24px; padding: 0; }
.thickness { grid-column: 4; grid-row: 1; text-align: right; }
.code { grid-column: 1; grid-row: 2; overflow-wrap: anywhere; white-space: normal; }
.grade { grid-column: 2; grid-row: 2; }
.veneer { grid-column: 3; grid-row: 2; }
.weight { grid-column: 4; grid-row: 2; text-align: right; }
.code, .grade, .veneer, .weight { color: var(--obs-shell-muted, #59636b); font-size: 11px; }
.mark { grid-column: 5; grid-row: 1 / 3; }
.unit { display: inline; }
}

View File

@ -0,0 +1,19 @@
import type { ProductArchiveList } from '@/lib/product-library/contracts'
import { withEstimateReadTimeout } from './estimate-read'
const productLibrary = '/api/intake/product-library'
export function readEstimateProductCatalog(signal?: AbortSignal): Promise<ProductArchiveList | null> {
return withEstimateReadTimeout(async readSignal => {
const options = { signal: readSignal, cache: 'no-store' as const }
let response = await fetch(productLibrary + '/catalog', options)
// Older deployments expose the same catalog at the base path.
if (response.status === 404) response = await fetch(productLibrary, options)
if (response.status === 403) return null
const body = await response.json().catch(() => null)
if (!response.ok || !body?.success || !body.data) {
throw new Error(body?.error?.message ?? '无法读取产品资料,请重试')
}
return body.data
}, signal)
}

View File

@ -1,23 +1,38 @@
import { redirect } from 'next/navigation'
import { getIntakeLibraryAccess, hasProductLibraryImportRole } from '@/lib/intake-library-access'
import { requireSession } from '@/lib/server-session'
import { assetCenterService } from '@/server/services/asset-center.service'
import { intakeNodePermissionSettingsService } from '@/server/services/intake-node-permission-settings.service'
import { listReferenceEstimateSummaries } from '@/server/services/reference-estimate-list.service'
import { isCatalogWorkbench } from './catalog/estimate-catalog'
import { linkedReferenceEstimateId } from './referenceEstimateLinks'
import { ReferenceEstimatorDomain } from './ReferenceEstimatorDomain'
export const metadata = { title: '预估成本测算' }
export default async function ReferenceEstimatorPage() {
export default async function ReferenceEstimatorPage({ searchParams }: {
searchParams: Promise<{ view?: string | string[]; estimateId?: string | string[] }>
}) {
const { authUser } = await requireSession()
const { overrides } = await intakeNodePermissionSettingsService.getSettings()
if (!getIntakeLibraryAccess(authUser, overrides, 'referenceEstimator').canView) redirect('/intake')
const canPushToLibrary = hasProductLibraryImportRole(authUser)
&& getIntakeLibraryAccess(authUser, overrides, 'productLibrary').canEdit
const params = await searchParams
const search = new URLSearchParams()
for (const key of ['view', 'estimateId'] as const) {
const value = params[key]
const first = Array.isArray(value) ? value[0] : value
if (first !== undefined) search.set(key, first)
}
const query = search.toString()
const initialRecords = isCatalogWorkbench(query) || linkedReferenceEstimateId(query) ? undefined
: await listReferenceEstimateSummaries(authUser).then(records => records.map(({ id, title, updatedAt, workspaceSlot, imageUrl, category }) => ({
id, title, updatedAt: updatedAt.toISOString(), workspaceSlot, imageUrl, category,
}))).catch(() => undefined)
const substrates = await assetCenterService.listSubstrates()
return (
<section aria-label="预估成本测算" className="h-full min-h-0 overflow-auto p-3 md:p-4">
<ReferenceEstimatorDomain materialLibrarySubstrates={substrates} userId={authUser.id} canPushToLibrary={canPushToLibrary} />
<ReferenceEstimatorDomain key={authUser.id} userId={authUser.id} canPushToLibrary={canPushToLibrary} initialRecords={initialRecords} />
</section>
)
}

View File

@ -0,0 +1,42 @@
'use client'
import { useState } from 'react'
import Button from '@/components/ui/Button'
import { backPanelParametersSchema, type BackPanelParameters, type BackPanelSkill } from '@/lib/reference-estimator/standard/back-panel-skill'
import styles from './skill-maintenance.module.css'
const fields = [
['minimumRailHeight', '后横档最低高度'],
['defaultRailHeight', '后横档默认高度'],
['maximumAdjustedRailHeight', '自动加高上限'],
] as const
export function BackPanelRuleEditor({ rule, frozen, onSave, onCancel }: {
rule: BackPanelSkill
frozen: boolean
onSave: (parameters: BackPanelParameters, notes?: string) => Promise<void>
onCancel: () => void
}) {
const [values, setValues] = useState(() => ({
minimumRailHeight: String(rule.minimumRailHeight),
defaultRailHeight: String(rule.defaultRailHeight),
maximumAdjustedRailHeight: String(rule.maximumAdjustedRailHeight),
}))
const [notes, setNotes] = useState(rule.notes ?? '')
const parsed = backPanelParametersSchema.safeParse(Object.fromEntries(fields.map(([key]) => [key, Number(values[key])])))
return <form className={styles.ruleEdit} onSubmit={event => {
event.preventDefault()
if (parsed.success && !frozen) void onSave(parsed.data, notes.trim() || undefined)
}}>
{fields.map(([key, label]) => <label key={key}>{label}(mm)
<input type="number" inputMode="decimal" step="any" min="0.001" max="400" required value={values[key]}
onChange={event => setValues({ ...values, [key]: event.target.value })} />
</label>)}
<label>工艺备注(选填)<textarea value={notes} maxLength={180} onChange={event => setNotes(event.target.value)} /></label>
{!parsed.success && <p className={styles.danger} role="status">高度应大于 0 且不超过 400 mm,最低高度 ≤ 默认高度 ≤ 自动加高上限。</p>}
<div className={styles.recordActions}>
<Button type="submit" size="small" disabled={!parsed.success || frozen}>保存背板规则</Button>
<Button type="button" size="small" variant="gray" disabled={frozen} onClick={onCancel}>取消</Button>
</div>
</form>
}

View File

@ -1,17 +0,0 @@
import rules from '../../../../.agents/skills/cabinet-standard-bom/规则.json'
import { backPanelSplitting } from '@/lib/reference-estimator/standard/cabinet-slotted-back'
import { imageSkillCategoryLabel } from '@/lib/reference-estimator/standard/cabinet-image-memory'
import styles from './skill-maintenance.module.css'
export function CabinetBackSkillRules({ category }: { category: string | null }) {
if (category && !/书柜|书架/.test(imageSkillCategoryLabel(category))) return null
return <details className={styles.sizeRules} open>
<summary>书柜背板规则 · v{rules.version}</summary>
<ul>
<li>板式开放格书柜、书架识图后自动生成槽装背板及后横档。</li>
<li>后横档高度至少 {backPanelSplitting.minimumRailHeight} mm,未给高度采用 {backPanelSplitting.defaultRailHeight} mm,明确更高规格时采用本款值。</li>
<li>先按一根后横档、两片背板计算。单片超宽时逐根增加横档并均分,直到符合有效限宽。</li>
<li>有效限宽取主体板件最大宽与本款背板限宽的较小值。板宽按板面短边计算。本款明确的后背方案优先。</li>
</ul>
</details>
}

View File

@ -0,0 +1,30 @@
'use client'
import { useState } from 'react'
import Button from '@/components/ui/Button'
import { maintenanceRuleDetailsSchema, type MaintenanceRuleDetails } from '@/lib/reference-estimator/standard/maintenance-rule'
import styles from './skill-maintenance.module.css'
export function DialogueMaintenanceEditor({ details, frozen, onSave, onCancel }: {
details: MaintenanceRuleDetails
frozen: boolean
onSave: (details: MaintenanceRuleDetails) => Promise<void>
onCancel: () => void
}) {
const [appliesWhen, setAppliesWhen] = useState(details.appliesWhen)
const [method, setMethod] = useState(details.method)
const [exceptions, setExceptions] = useState(details.exceptions ?? '')
const parsed = maintenanceRuleDetailsSchema.safeParse({ appliesWhen, method, exceptions: exceptions.trim() || undefined })
return <form className={styles.ruleEdit} onSubmit={event => {
event.preventDefault()
if (parsed.success && !frozen) void onSave(parsed.data)
}}>
<label>适用条件<input autoFocus value={appliesWhen} maxLength={100} onChange={event => setAppliesWhen(event.target.value)} /></label>
<label>做法<textarea value={method} maxLength={180} onChange={event => setMethod(event.target.value)} /></label>
<label>例外(选填)<textarea value={exceptions} maxLength={180} onChange={event => setExceptions(event.target.value)} /></label>
<div className={styles.recordActions}>
<Button type="submit" size="small" disabled={!parsed.success || frozen}>保存做法</Button>
<Button type="button" size="small" variant="gray" disabled={frozen} onClick={onCancel}>取消</Button>
</div>
</form>
}

View File

@ -1,16 +1,13 @@
'use client'
import { useEffect, useMemo, useState } from 'react'
import { Plus, Search } from 'lucide-react'
import { useId, useMemo, useState } from 'react'
import { Download, Plus, Search } from 'lucide-react'
import Button from '@/components/ui/Button'
import { ErrorEmptyState } from '@/components/ui/EmptyState'
import { imageMaterialTypeSchema, type ImageSkillCategory } from '@/lib/reference-estimator/standard/cabinet-image-memory'
import { bookshelfFieldValue, type SharedBookshelfRule } from '@/lib/reference-estimator/standard/bookshelf-learning'
import { structureCategoryQuery, structureModelLabel } from '@/lib/reference-estimator/standard/structure-summary'
import { readBookshelfMemory } from '../standard/bookshelf-memory-client'
import type { SkillSection } from '../skill-library-events'
import {
addStructureSkill, keptStructure, listStructureModels, readStructureSkills, registerStructureMaterial, rescanStructure, reviewStructure,
addStructureSkill, registerStructureMaterial, rescanStructure, reviewStructure, saveDialogueMaintenanceRule, saveBackPanelMaintenanceRule,
structureCategoryLabel, type StructureModel, type StructureRecord, type StructureRescan, type StructureReview, type StructureSnapshot,
} from './structure-client'
import { buildMatrix, countMissing, filterMatrix, type MatrixFilter, type MatrixRecord } from './structure-matrix'
@ -19,18 +16,12 @@ import { StructureDetail } from './StructureDetail'
import { StructureMatrix } from './StructureMatrix'
import { StructureModelMenu } from './StructureModelMenu'
import { StructureSupplement, type StructureSupplementInput, type StructureTarget } from './StructureSupplement'
import { CabinetBackSkillRules } from './CabinetBackSkillRules'
import type { MaintenanceRuleDetails } from '@/lib/reference-estimator/standard/maintenance-rule'
import type { BackPanelParameters, BackPanelSkill } from '@/lib/reference-estimator/standard/back-panel-skill'
import { useStructureMaintenance } from './useStructureMaintenance'
import { useStructureModelSelection } from './useStructureModelSelection'
import styles from './skill-maintenance.module.css'
type Load =
| { status: 'loading' }
| { status: 'error'; message: string }
| { status: 'ready'; snapshot: StructureSnapshot; at: number }
/** Whether what is on screen is what the server holds now. */
type Freshness = 'checking' | 'current' | 'updated' | 'failed'
type Models = { category: string; status: 'ready'; models: StructureModel[] } | { category: string; status: 'error'; models: [] }
type Rules = { status: 'idle' } | { status: 'loading' } | { status: 'failed' } | { status: 'ready'; rules: SharedBookshelfRule[] }
const filters: readonly (readonly [MatrixFilter, string])[] = [
['all', '全部'], ['diff', '做法不同'], ['same', '各材质相同'], ['missing', '有空格'], ['pending', '待核对'],
]
@ -40,43 +31,17 @@ const noCategories: StructureSnapshot['categories'] = []
const noModels: StructureModel[] = []
const clock = (at: number) => new Date(at).toTimeString().slice(0, 5)
export function EstimateSkillMaintenance(_props: { onOpenSection?: (section: SkillSection) => void }) {
// What was read last time is on screen at once; the server is only asked whether it changed.
const [load, setLoad] = useState<Load>(() => { const kept = keptStructure()
return kept ? { status: 'ready', snapshot: kept.snapshot, at: kept.at } : { status: 'loading' } })
const [freshness, setFreshness] = useState<Freshness>(() => keptStructure() ? 'checking' : 'current')
const [reload, setReload] = useState(0)
useEffect(() => {
const controller = new AbortController()
const kept = keptStructure()
if (!kept) setLoad({ status: 'loading' })
setFreshness(kept ? 'checking' : 'current')
void readStructureSkills(controller.signal, kept?.snapshot.version).then(({ snapshot, fresh }) => {
if (controller.signal.aborted) return
setLoad({ status: 'ready', snapshot, at: Date.now() })
setFreshness(fresh ? (kept ? 'updated' : 'current') : 'current')
}).catch((cause: unknown) => {
if (controller.signal.aborted) return
// With something still kept a failed check is only reported; with nothing kept (the session or the access ended) it is an error.
if (keptStructure()) setFreshness('failed')
else setLoad({ status: 'error', message: cause instanceof Error ? cause.message : '技能库读取失败' })
})
return () => controller.abort()
}, [reload])
const snapshot = load.status === 'ready' ? load.snapshot : null
const categories = snapshot?.categories ?? noCategories
const [selected, setSelected] = useState<ImageSkillCategory | null>(null)
// The first category that holds relations opens by default.
const category = selected && categories.some(item => item.category === selected) ? selected
: categories.find(item => item.materials.some(material => material.count > 0))?.category ?? categories[0]?.category ?? null
export function EstimateSkillMaintenance({ userId }: { userId?: string }) {
const { categories: categoryList, category, categoryError, current: load, freshness, setSelected, setLoad, setFreshness, refresh } = useStructureMaintenance(userId)
const snapshot = load?.status === 'ready' ? load.snapshot : null
const categories = categoryList ?? noCategories
// Relations of the category; a preview adds what reading the chosen models would bring.
const [preview, setPreview] = useState<{ category: string; result: StructureRescan } | null>(null)
const [preview, setPreview] = useState<{ category: string; ids: string[]; result: StructureRescan } | null>(null)
const queryCategory = category ? structureCategoryQuery(category) : null
// A reading with nothing to write leaves nothing to confirm, so it is not held as a preview.
const previewing = Boolean(category && preview && preview.result.items.length > 0 && preview.category === queryCategory)
const savedHere = useMemo(() => (snapshot?.structure ?? []).filter(item => item.category === category), [snapshot, category])
const savedHere = useMemo(() => [...snapshot?.structure ?? [], ...snapshot?.rules ?? []].filter(item => item.category === category), [snapshot, category])
const items = useMemo<MatrixRecord[]>(() => {
if (!previewing || !preview) return savedHere
const merged = new Map<string, MatrixRecord>(savedHere.map(item => [item.id, item]))
@ -105,28 +70,15 @@ export function EstimateSkillMaintenance(_props: { onOpenSection?: (section: Ski
const line = visible.find(row => row.id === selectedId) ?? visible[0] ?? null
const todo: StructureTodo | null = filter === 'pending' ? 'pending' : filter === 'missing' ? 'missing' : null
// The models to choose from belong to the selected category; another category's list is treated as still loading.
const [models, setModels] = useState<Models | null>(null)
const [chosen, setChosen] = useState<string[]>([])
useEffect(() => {
if (!queryCategory) return
const controller = new AbortController()
void listStructureModels(queryCategory, controller.signal).then(list => { if (!controller.signal.aborted) {
setModels({ category: queryCategory, status: 'ready', models: list })
// Models that recorded no structure cannot be read, so they start unchecked.
setChosen(list.filter(item => item.readable).map(item => item.id))
} }).catch(() => { if (!controller.signal.aborted) setModels({ category: queryCategory, status: 'error', models: [] }) })
return () => controller.abort()
}, [queryCategory])
const current = queryCategory && models?.category === queryCategory ? models : null
const list = current?.status === 'ready' ? current.models : noModels
const chosenHere = current ? chosen : []
const sources = list.map((model, index) => ({ id: model.id, number: index + 1 }))
const picker = useStructureModelSelection(queryCategory, userId ?? null)
const modelMenuId = useId()
const list = picker.shown?.models ?? noModels
const offset = picker.shown ? (picker.shown.page - 1) * picker.shown.pageSize : 0
const sources = list.map((model, index) => ({ id: model.id, number: offset + index + 1 }))
const known = useMemo(() => Object.fromEntries(list.map(model => [model.id, model.title])), [list])
const [busy, setBusy] = useState(false)
const [action, setAction] = useState('')
const [menuOpen, setMenuOpen] = useState(false)
const [target, setTarget] = useState<StructureTarget | null>(null)
// Adding a material and writing a supplement share one line under the filters, so only one is open at a time.
const [adding, setAdding] = useState(false)
@ -138,34 +90,61 @@ export function EstimateSkillMaintenance(_props: { onOpenSection?: (section: Ski
setAction(doing)
try { await task() } catch (cause) { setAction(cause instanceof Error ? cause.message : '操作失败,请重试。') } finally { setBusy(false) }
}
const patch = (change: (items: StructureRecord[]) => StructureRecord[]) => setLoad(state => state.status === 'ready'
const patch = (change: (items: StructureRecord[]) => StructureRecord[]) => setLoad(state => state?.status === 'ready' && state.category === category
? { ...state, snapshot: { ...state.snapshot, structure: change(state.snapshot.structure) } } : state)
const selectCategory = (id: ImageSkillCategory) => {
setSelected(id); setHidden([]); setFilter('all'); setQuery(''); setPreview(null); setSelectedId(null); setTarget(null); setAdding(false); setMenuOpen(false); setAction('')
if (busy) return
setSelected(id); setHidden([]); setFilter('all'); setQuery(''); setPreview(null); setSelectedId(null); setTarget(null); setAdding(false); picker.reset(); setAction('')
}
const toggleMaterial = (name: string) => setHidden(current => current.includes(name) ? current.filter(item => item !== name)
: columns.length > 1 ? [...current, name] : current)
const narrowTo = (next: MatrixFilter) => { setFilter(next); setQuery(''); setSelectedId(null) }
const scan = (dryRun: boolean) => category && queryCategory && void run(dryRun ? '正在读取选中的模型…' : '正在存入技能库…', async () => {
const result = await rescanStructure(queryCategory, chosenHere, dryRun)
if (dryRun) { setPreview(result.items.length ? { category: queryCategory, result } : null); setFilter('all'); setMenuOpen(false); setAdding(false); setTarget(null) }
else { setPreview(null); setReload(value => value + 1) }
const names = result.models.map(structureModelLabel).join('、')
// Say plainly when the models are already fully in the library, instead of "read 0".
const many = result.models.length === 1 ? '这 1 个' : `这 ${result.models.length} 个`
const change = [result.added ? `新读出 ${result.added} 条结构` : '', result.extended ? `${result.extended} 条补上了来源` : ''].filter(Boolean).join(',')
setAction(dryRun
? change ? `预览:选中${many}${structureCategoryLabel(category)}模型(${names}):${change}。还没保存。`
: `选中${many}${structureCategoryLabel(category)}模型(${names})的结构都已经在技能库里,没有新内容。`
: change ? `已存入技能库:${change}。读取的模型:${names}` : `没有新内容需要保存。读取的模型:${names}`)
})
const scan = (dryRun: boolean) => {
const ids = dryRun ? picker.chosen : (preview?.category === queryCategory ? preview?.ids ?? [] : [])
if (!category || !queryCategory || !ids.length) return
void run(dryRun ? '正在读取选中的模型…' : '正在存入技能库…', async () => {
const result = await rescanStructure(queryCategory, ids, dryRun)
if (dryRun) {
setPreview(result.items.length ? { category: queryCategory, ids: result.models.map(model => model.id), result } : null)
if (!result.models.length) { setAction('所选模型没有可读的结构,请重新勾选。'); return }
setFilter('all'); picker.setOpen(false); setAdding(false); setTarget(null)
} else { setPreview(null); refresh() }
const names = result.models.map(structureModelLabel).join('、')
const skipped = ids.length - result.models.length
const outcome = skipped > 0 ? ` 有 ${skipped} 个所选模型未读出结构。` : ''
const change = [result.added ? `新读出 ${result.added} 条结构` : '', result.extended ? `${result.extended} 条补上了来源` : ''].filter(Boolean).join(',')
setAction((dryRun
? change ? `预览:${names},${change}。还没保存。` : `${names}的结构都已经在技能库里,没有新内容。`
: change ? `已存入技能库:${change}。读取的模型:${names}` : '没有新内容需要保存。') + outcome)
})
}
const review = (id: string, decision: StructureReview) => void run(
decision === 'approve' ? '已标为对。' : decision === 'revoke' ? '已剔除,可以恢复。' : '已恢复。', async () => {
const updated = await reviewStructure(id, decision)
if (!updated) throw new Error('没有保存成功,请刷新后重试。')
patch(items => items.map(item => item.id === id ? updated : item))
})
const editDialogue = async (id: string, updatedAt: string, details: MaintenanceRuleDetails) => {
let saved = false
await run('正在保存做法…', async () => {
await saveDialogueMaintenanceRule(id, updatedAt, details)
refresh()
setAction('已更新这条做法。')
saved = true
})
return saved
}
const editBack = async (rule: BackPanelSkill, parameters: BackPanelParameters, notes?: string) => {
let saved = false
await run('正在保存分片参数…', async () => {
await saveBackPanelMaintenanceRule(rule.category, rule.revision, parameters, notes)
refresh()
setAction('已保存,下次识图建模使用新参数。')
saved = true
})
return saved
}
const save = async (input: StructureSupplementInput) => {
if (!category) return false
let saved = false
@ -183,33 +162,27 @@ export function EstimateSkillMaintenance(_props: { onOpenSection?: (section: Ski
}
const addMaterial = (materialType: string) => category && void run('正在添加…', async () => {
const next = await registerStructureMaterial({ category, materialType })
setLoad({ status: 'ready', snapshot: next, at: Date.now() }); setFreshness('current')
setLoad({ category, status: 'ready', snapshot: next, at: Date.now() }); setFreshness('current')
refresh()
setAdding(false)
setAction(`已加上「${materialType}」一列。读这个材质的模型或补充后,这一列会填上。`)
})
// The size rules ride along with the bookshelf memory, which is large: they are read only once they are unfolded.
const [rules, setRules] = useState<Rules>({ status: 'idle' })
const unfoldRules = (open: boolean) => {
if (!open || rules.status !== 'idle') return
setRules({ status: 'loading' })
void readBookshelfMemory().then(memory => setRules({ status: 'ready', rules: memory.rules }), () => setRules({ status: 'failed' }))
}
const sizeRules = rules.status === 'ready' && category ? rules.rules.filter(rule => rule.scope.category === category) : []
const offering = Boolean(previewing && preview && preview.result.items.length > 0)
const freshnessText = load.status !== 'ready' ? '' : {
const freshnessText = load?.status !== 'ready' ? '' : {
checking: '正在检查更新…', current: `已是最新 · ${clock(load.at)}`, updated: `刚更新 · ${clock(load.at)}`,
failed: `检查更新失败,显示的是 ${clock(load.at)} 读到的内容`,
}[freshness]
const free = !busy && !previewing
const free = !busy && !previewing && load?.status === 'ready'
return <div className={styles.split}>
<StructureCategoryTree categories={categories.map(node => node.category === category ? { ...node, materials } : node)}
selected={category} shown={columns} pending={items.filter(item => item.status === 'pending').length}
missing={missing} todo={todo} onSelect={selectCategory} onToggleMaterial={toggleMaterial} onTodo={narrowTo}>
<StructureModelMenu models={list} chosen={chosenHere} open={menuOpen} busy={busy || previewing} categoryLabel={category ? structureCategoryLabel(category) : ''}
onToggle={() => setMenuOpen(open => !open)} onChoose={ids => { setChosen(ids); setPreview(null) }} onPreview={() => scan(true)} />
<Button size="small" variant="plain" className={styles.readButton} disabled={busy || previewing || !category}
aria-expanded={picker.open} aria-controls={picker.open ? modelMenuId : undefined} onClick={() => picker.setOpen(!picker.open)}>
<Download size={14} strokeWidth={1.7} />读取模型
</Button>
</StructureCategoryTree>
<div className={styles.main}>
@ -230,7 +203,8 @@ export function EstimateSkillMaintenance(_props: { onOpenSection?: (section: Ski
<Plus size={14} strokeWidth={1.7} />加材质</Button>}
</div>
</div>
<CabinetBackSkillRules category={category} />
{picker.open && category && <StructureModelMenu id={modelMenuId} picker={picker} busy={busy || previewing}
categoryLabel={structureCategoryLabel(category)} onPreview={() => scan(true)} />}
<div className={styles.filters}>
<span>显示</span>
<div className={styles.segments} role="group" aria-label="显示哪些关系">
@ -256,25 +230,17 @@ export function EstimateSkillMaintenance(_props: { onOpenSection?: (section: Ski
</div>}
{action && !offering && <p className={styles.action} role="status">{action}</p>}
{load.status === 'error' ? <div className={styles.error}><ErrorEmptyState onRetry={() => setReload(value => value + 1)} /></div>
: load.status === 'loading' ? <p className={styles.loading} role="status">正在读取技能库…</p>
{load?.status === 'error' || (categoryError && !categoryList) ? <div className={styles.error}><ErrorEmptyState onRetry={refresh} /></div>
: !categoryList || (category && !load) ? <p className={styles.loading} role="status">正在读取技能库…</p>
: !category ? <p className={styles.empty}>技能库里还没有类目。保存一个测算模型后,它的类目会出现在这里。</p>
: <div className={styles.scroll}>
<StructureMatrix lines={visible} materials={columns} selectedId={line?.id ?? null} sources={sources} known={known}
onPick={setSelectedId} onFill={(row, materialType) => askSupplement({ materialType, module: row.module, subject: row.subject, intent: row.intent,
placeholder: `${materialType} · ${row.label}:${row.intent === 'has' ? '有没有这个部件?没有就写「无」和原因' : row.intent === 'fix' ? '写这种材质下怎么固定' : '写这种材质下的做法'}` })} />
</div>}
{load.status === 'ready' && category && !previewing && <details className={styles.sizeRules} onToggle={event => unfoldRules(event.currentTarget.open)}>
<summary>尺寸规则{rules.status === 'ready' ? ` · ${sizeRules.length} 条` : ''}(随款式变化的取值,不算结构)</summary>
{rules.status === 'loading' && <p>正在读取…</p>}
{rules.status === 'failed' && <p>尺寸规则读取失败,请重新打开技能库再试。</p>}
{rules.status === 'ready' && (sizeRules.length
? <ul>{sizeRules.map(rule => <li key={rule.id}>{bookshelfFieldValue(rule.field, rule.patch[rule.field])}</li>)}</ul>
: <p>这个类目还没有尺寸规则。</p>)}
</details>}
</div>
<StructureDetail line={line} materials={columns} models={list} frozen={busy || previewing} onReview={review}
<StructureDetail key={category} line={line} materials={columns} models={list} modelOffset={offset} frozen={busy || previewing} onReview={review} onEditDialogue={editDialogue} onEditBack={editBack}
onSupplement={() => line && askSupplement({ materialType: columns[0] ?? materials[0]?.materialType ?? '待确认', module: line.module,
subject: line.subject, intent: line.intent, placeholder: `${line.label}:换一种做法` })} />
</div>

View File

@ -1,66 +1,104 @@
'use client'
import { useState } from 'react'
import Button from '@/components/ui/Button'
import type { MaintenanceRuleDetails } from '@/lib/reference-estimator/standard/maintenance-rule'
import { structureIntentLabels } from '@/lib/reference-estimator/standard/structure-summary'
import type { StructureModel, StructureReview } from './structure-client'
import type { MatrixLine } from './structure-matrix'
import { DialogueMaintenanceEditor } from './DialogueMaintenanceEditor'
import { BackPanelRuleEditor } from './BackPanelRuleEditor'
import type { BackPanelParameters, BackPanelSkill } from '@/lib/reference-estimator/standard/back-panel-skill'
import styles from './skill-maintenance.module.css'
const day = (value?: string) => value ? value.slice(5, 10) : ''
const statusLabel = { pending: '待核对', active: '在用', revoked: '已剔除' } as const
/** The models that hold the selected relation, and each recorded relation with its state, so each can be judged on its own. */
export function StructureDetail({ line, materials, models, frozen, onReview, onSupplement }: {
export function StructureDetail({ line, materials, models, modelOffset, frozen, onReview, onSupplement, onEditDialogue, onEditBack }: {
line: MatrixLine | null
materials: readonly string[]
models: readonly StructureModel[]
modelOffset: number
frozen: boolean
onReview: (id: string, action: StructureReview) => void
onSupplement: () => void
onEditDialogue: (id: string, updatedAt: string, details: MaintenanceRuleDetails) => Promise<boolean>
onEditBack: (rule: BackPanelSkill, parameters: BackPanelParameters, notes?: string) => Promise<boolean>
}) {
const [editing, setEditing] = useState<string | null>(null)
if (!line) return <aside className={styles.detail} aria-label="来源与记录">
<h3 className={styles.detailTitle}>{materials.length ? '这个类目还没有结构关系' : '还没有结构关系'}</h3>
<p className={styles.hint}>从左下角「读取模型」开始:勾选要读的模型,读出的关系会按材质落到这张表里。</p>
</aside>
const ids = [...new Set(line.items.flatMap(item => item.modelIds))]
const ruleOnly = line.items.length > 0 && line.items.every(item => item.rule)
const gaps = line.cells.filter(cell => cell.kind === 'missing').length
return <aside className={styles.detail} aria-label="来源与记录">
<h3 className={styles.detailTitle}>{line.label} · {structureIntentLabels[line.intent]}</h3>
<p className={styles.sub}>{line.same ? '各材质做法相同' : gaps ? `各材质做法不同 · ${gaps} 格还没记录` : '各材质做法不同'}</p>
<section className={styles.detailSection}>
{!ruleOnly && <section className={styles.detailSection}>
<h4>谁有(模型编号)</h4>
{models.length
? <ul className={styles.models}>{models.map((model, index) => <li key={model.id}>
<span className={styles.number}>{index + 1}</span>
<span className={styles.number}>{modelOffset + index + 1}</span>
<span className={styles.spacer}>{model.spu ? `${model.spu.code} ${model.spu.name || model.title}` : model.title}</span>
<span className={styles.code}>{ids.includes(model.id) ? '有' : '没有'}</span>
</li>)}</ul>
: <p className={styles.hint}>我保存的这个类目下还没有测算模型。</p>}
</section>
: <p className={styles.hint}>{ids.length ? `来自 ${ids.length} 个模型。可在「读取模型」中查看本类目的模型列表。` : '这条关系没有模型来源。'}</p>}
</section>}
<section className={styles.detailSection}>
<h4>记录</h4>
<ul className={styles.records}>{line.items.map(item =>
<li key={item.id}>
<ul className={styles.records}>{[...line.items].sort((a, b) =>
Number(b.rule?.source === 'standard') - Number(a.rule?.source === 'standard')).map(item => {
const backPanel = item.rule?.source === 'standard' ? item.rule.backPanel : undefined
const reference = item.rule?.source === 'dialogue' || item.rule?.source === 'legacy' ? item.rule.referenceOnly : false
return <li key={item.id}>
<div className={styles.recordHead}>
<span className={styles.tag}>{item.materialType}</span>
<span className={`${styles.tag} ${item.status === 'pending' ? styles.tagPending : ''}`}>{statusLabel[item.status]}</span>
<span className={`${styles.tag} ${item.status === 'pending' ? styles.tagPending : ''}`}>{reference ? '历史参考' : statusLabel[item.status]}</span>
{item.isNew && <span className={`${styles.tag} ${styles.tagNew}`}>新读出</span>}
<span className={styles.code}>{item.origin === 'manual' ? '手工补充' : '从模型读出'} · {day(item.createdAt)}</span>
<span className={styles.code}>{backPanel ? `CB-025 · ${backPanel.revision ? `修订 ${backPanel.revision}` : '默认规则'}`
: item.rule?.source === 'standard' ? `建模标准 v${item.rule.version}`
: item.rule?.source === 'size' ? '尺寸规则' : item.rule ? '建模对话'
: item.origin === 'manual' ? '手工补充' : '从模型读出'}{item.createdAt && ` · ${day(item.createdAt)}`}</span>
</div>
<p className={item.status === 'revoked' ? `${styles.recordText} ${styles.revoked}` : styles.recordText}>{item.text}</p>
<div className={styles.recordActions}>
{backPanel && editing === item.id
? <BackPanelRuleEditor key={`${item.id}:${backPanel.revision}`} rule={backPanel} frozen={frozen}
onSave={async (params, notes) => { if (await onEditBack(backPanel, params, notes)) setEditing(null) }}
onCancel={() => setEditing(null)} />
: item.rule?.source === 'dialogue' && !reference && item.updatedAt && editing === item.id
? <DialogueMaintenanceEditor key={item.id} details={item.rule.details} frozen={frozen}
onSave={async details => {
if (item.rule?.source === 'dialogue' && item.updatedAt && await onEditDialogue(item.rule.savedId, item.updatedAt, details)) setEditing(null)
}} onCancel={() => setEditing(null)} />
: <>
{(item.rule?.source === 'dialogue' || item.rule?.source === 'legacy')
? <>
<p className={styles.recordText}>适用:{item.rule.details.appliesWhen}</p>
<p className={styles.recordText}>做法:{item.rule.details.method}</p>
{item.rule.details.exceptions && <p className={styles.recordText}>例外:{item.rule.details.exceptions}</p>}
</>
: <p className={item.status === 'revoked' ? `${styles.recordText} ${styles.revoked}` : styles.recordText}>{item.text}</p>}
{item.rule?.source === 'size' && <p className={styles.recordText}>适用:{item.rule.scope}</p>}
{backPanel?.notes && <p className={styles.recordText}>工艺备注:{backPanel.notes}</p>}
{backPanel && <Button type="button" size="small" variant="gray" disabled={frozen} onClick={() => setEditing(item.id)}>编辑做法</Button>}
{item.rule?.source === 'dialogue' && !reference && item.updatedAt &&
<Button type="button" size="small" variant="gray" disabled={frozen} onClick={() => setEditing(item.id)}>编辑做法</Button>}
</>}
{!item.rule && <div className={styles.recordActions}>
{item.status === 'pending' && <>
<Button size="small" variant="gray" disabled={frozen} onClick={() => onReview(item.id, 'approve')}>对</Button>
<Button size="small" variant="gray" tone="danger" disabled={frozen} onClick={() => onReview(item.id, 'revoke')}>不对</Button>
</>}
{item.status === 'active' && <Button size="small" variant="gray" tone="danger" disabled={frozen} onClick={() => onReview(item.id, 'revoke')}>剔除</Button>}
{item.status === 'revoked' && <Button size="small" variant="gray" disabled={frozen} onClick={() => onReview(item.id, 'restore')}>恢复</Button>}
</div>
</div>}
</li>
)}</ul>
})}</ul>
</section>
<div className={styles.detailActions}>
{!ruleOnly && <div className={styles.detailActions}>
<Button size="small" variant="gray" disabled={frozen} onClick={onSupplement}>补充做法</Button>
</div>
</div>}
</aside>
}

View File

@ -11,7 +11,9 @@ type TagSpec = readonly [label: string, className: string]
// One tag says the most that is true of a relation: newly read beats waiting for review beats the rest.
const tagOf = (item: MatrixRecord): TagSpec | null =>
item.isNew ? ['新读出', styles.tagNew] : item.status === 'pending' ? ['待核对', styles.tagPending]
: item.status === 'revoked' ? ['已剔除', ''] : item.origin === 'manual' ? ['我补充的', ''] : null
: item.status === 'revoked' ? ['已剔除', ''] : item.rule?.source === 'standard' ? ['建模标准', '']
: (item.rule?.source === 'dialogue' || item.rule?.source === 'legacy') && item.rule.referenceOnly ? ['历史参考', '']
: item.rule?.source === 'size' ? ['尺寸', ''] : item.rule ? ['对话保存', ''] : item.origin === 'manual' ? ['我补充的', ''] : null
function ItemTag({ item }: { item: MatrixRecord }) {
const tag = tagOf(item)
@ -50,7 +52,7 @@ export function StructureMatrix({ lines, materials, selectedId, sources, known,
<col style={{ width: '12%' }} />
</colgroup>
<thead>
<tr><th scope="col">部件 · 关系</th>{materials.map(name => <th key={name} scope="col" className={styles.materialCol}>{name}</th>)}<th scope="col">谁有</th></tr>
<tr><th scope="col">部件 · 规则</th>{materials.map(name => <th key={name} scope="col" className={styles.materialCol}>{name}</th>)}<th scope="col">来源</th></tr>
</thead>
<tbody>
{lines.length === 0 && <tr><td colSpan={span}><p className={styles.empty}>没有这样的关系。</p></td></tr>}
@ -58,14 +60,16 @@ export function StructureMatrix({ lines, materials, selectedId, sources, known,
<tr className={styles.partRow}><td colSpan={span}>{structureModuleLabels[module]}
<span className={styles.count}>{lines.filter(line => line.module === module).length} 行</span></td></tr>
{lines.filter(line => line.module === module).map(line => {
const who = describeSources(sourcesOf(line), sources, [], known)
const ruleOnly = line.items.length > 0 && line.items.every(item => item.rule)
const who = ruleOnly ? [...new Set(line.items.map(item => item.rule?.source === 'standard' ? '标准'
: item.rule?.source === 'size' ? '尺寸' : '对话'))].join('/') : describeSources(sourcesOf(line), sources, [], known)
// With a single material there is nothing to merge: its cell is shown as any other.
const merge = line.same && materials.length > 1
return <tr key={line.id} className={line.id === selectedId ? `${styles.row} ${styles.rowSelected}` : styles.row} onClick={() => onPick(line.id)}>
<td className={styles.label}>
<button type="button" className={styles.pick} onClick={() => onPick(line.id)}>{line.label}</button>
{line.items.map(item => item.status === 'pending' && <ItemTag key={item.id} item={item} />)}
<span className={styles.intent}>{structureIntentLabels[line.intent]}</span>
{!ruleOnly && <span className={styles.intent}>{structureIntentLabels[line.intent]}</span>}
</td>
{merge
? <td className={styles.merged} colSpan={materials.length}>{mergedText(line)}

View File

@ -1,8 +1,11 @@
'use client'
import { Download } from 'lucide-react'
import { useRef } from 'react'
import Button from '@/components/ui/Button'
import { FloatingTablePagination } from '@/components/platform/FloatingTablePagination'
import { structureModelPageSizes, structureModelSelectionLimit } from '@/lib/reference-estimator/standard/structure-model-selection'
import type { StructureModel } from './structure-client'
import type { useStructureModelSelection } from './useStructureModelSelection'
import styles from './skill-maintenance.module.css'
/** "SG0164 六格开放书柜" for a model linked to an SPU, otherwise the estimate name. */
@ -10,48 +13,52 @@ export const structureModelName = (model: Pick<StructureModel, 'title' | 'spu'>)
model.spu ? `${model.spu.code} ${model.spu.name}` : model.title
const detail = (model: StructureModel) => model.readable
? [model.materialType, `修订 ${model.revision}`, `可读出 ${model.statementCount} 条结构`].filter(Boolean).join(' · ')
? [model.materialType, `修订 ${model.revision}`].filter(Boolean).join(' · ')
: '这个模型没有可读的结构记录'
/**
* Lets the user choose which of their models of the category are read into the skill library.
* Folded it is one small button; open, the models are listed above it in a list that scrolls once it is long.
* Uses a native checkbox: inside the White Obsidian modal the shared Checkbox paints checked and unchecked alike.
*/
export function StructureModelMenu({ models, chosen, open, busy, onToggle, onChoose, onPreview, categoryLabel }: {
models: readonly StructureModel[]
chosen: readonly string[]
open: boolean
/** Selects models to preview. The current page and the selection can change independently. */
export function StructureModelMenu({ picker, busy, onPreview, categoryLabel, id }: {
picker: ReturnType<typeof useStructureModelSelection>
busy: boolean
onToggle: () => void
onChoose: (ids: string[]) => void
onPreview: () => void
categoryLabel: string
id: string
}) {
const readable = models.filter(model => model.readable).map(model => model.id)
return <>
{open && <div className={styles.menu}>
<p className={styles.menuTitle}>勾选要读取的{categoryLabel}模型 · 已选 {chosen.length} / {models.length}</p>
{models.length === 0
? <p className={styles.hint}>我保存的这个类目下还没有测算模型。</p>
: <ul className={styles.menuList}>
{models.map(model => { const checked = chosen.includes(model.id)
return <li key={model.id}>
<label className={model.readable ? styles.menuItem : `${styles.menuItem} ${styles.menuItemDisabled}`} title={detail(model)}>
<input type="checkbox" checked={checked} disabled={busy || !model.readable}
onChange={() => onChoose(checked ? chosen.filter(id => id !== model.id) : [...chosen, model.id])} />
<span className={styles.menuName}>{structureModelName(model)}</span>
</label>
</li> })}
</ul>}
<div className={styles.menuActions}>
<Button size="small" variant="plain" disabled={busy || !readable.length} onClick={() => onChoose(readable)}>勾选可读的</Button>
<Button size="small" variant="plain" disabled={busy} onClick={() => onChoose([])}>全部不选</Button>
<Button size="small" disabled={busy || !chosen.length} onClick={onPreview}>读出并预览</Button>
</div>
</div>}
<Button size="small" variant="plain" className={styles.readButton} disabled={busy} aria-expanded={open} onClick={onToggle}>
<Download size={14} strokeWidth={1.7} />读取模型
</Button>
</>
const list = useRef<HTMLUListElement>(null)
const { shown, pending, error, chosen, choose } = picker
const blocked = busy || pending || Boolean(error)
const remaining = structureModelSelectionLimit - chosen.length
const available = shown?.models.filter(model => model.readable && !chosen.includes(model.id)).map(model => model.id) ?? []
const paginate = Boolean(shown && shown.total > structureModelPageSizes[0])
const go = (change: () => void) => { change(); if (list.current) list.current.scrollTop = 0 }
return <section id={id} className={styles.menu} aria-label="读取模型">
<p className={styles.menuTitle}>勾选要读取的{categoryLabel}模型 · 已选 {chosen.length} 个(最多 {structureModelSelectionLimit} 个)</p>
{pending && <p className={styles.hint} role="status">正在读取模型列表…</p>}
{error && <p className={styles.hint} role="status">{error} <Button size="small" variant="plain" onClick={picker.retry}>重试</Button></p>}
{shown && (shown.models.length ? <div className={styles.menuResults}>
<ul ref={list} className={paginate ? `${styles.menuList} ${styles.menuListPaged}` : styles.menuList} aria-label="测算模型">
{shown.models.map((model, index) => {
const checked = chosen.includes(model.id)
return <li key={model.id}>
<label className={model.readable ? styles.menuItem : `${styles.menuItem} ${styles.menuItemDisabled}`} title={detail(model)}>
<input type="checkbox" checked={checked} disabled={blocked || !model.readable || (!checked && !remaining)}
onChange={() => choose(checked ? chosen.filter(id => id !== model.id) : [...chosen, model.id])} />
<span className={styles.number} aria-hidden="true">{(shown.page - 1) * shown.pageSize + index + 1}</span>
<span className={styles.menuName}>{structureModelName(model)}</span>
</label>
</li>
})}
</ul>
{paginate && <FloatingTablePagination page={shown.page} pageSize={shown.pageSize} total={shown.total}
totalPages={shown.totalPages} pageSizes={structureModelPageSizes} loading={blocked}
onPageChange={page => go(() => picker.changePage(page))} onPageSizeChange={size => go(() => picker.changePageSize(size))} />}
</div> : <p className={styles.hint}>我保存的这个类目下还没有测算模型。</p>)}
<div className={styles.menuActions}>
<Button size="small" variant="plain" disabled={blocked || !available.length || !remaining}
onClick={() => choose([...chosen, ...available.slice(0, remaining)])}>勾选本页</Button>
<Button size="small" variant="plain" disabled={busy || !chosen.length} onClick={() => choose([])}>清空勾选</Button>
<Button size="small" disabled={blocked || !chosen.length} onClick={onPreview}>读出并预览</Button>
<Button size="small" variant="plain" disabled={busy} onClick={() => picker.setOpen(false)}>收起</Button>
</div>
</section>
}

View File

@ -25,10 +25,17 @@
.railFooter { margin-top: auto; display: grid; justify-items: start; gap: 6px; }
.readButton { justify-self: start; }
/* Reading models: folded to one small button; open, the models scroll in a short list above it */
.menu { justify-self: stretch; border: 1px solid #e3e8e5; border-radius: 6px; padding: 8px; background: #fcfdfc; }
/* The picker uses the middle column so the pagination has room above the matrix. */
.menu { flex: none; min-width: 0; margin: 0 16px 12px; border: 1px solid #e3e8e5; border-radius: 6px; padding: 8px; background: #fcfdfc; }
.menuTitle { margin: 0 0 6px; font-size: 11px; font-weight: 500; letter-spacing: 0.02em; color: #5f656a; }
.menuList { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 2px; max-height: 168px; overflow: auto; }
.menuResults { position: relative; container-type: inline-size; }
.menuList { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 2px; max-height: min(34vh, 260px); overflow: auto; }
.menuListPaged { min-height: min(34vh, 260px); padding-bottom: 88px; }
@container (max-width: 475px) {
.menuResults > nav { bottom: 8px; width: max-content; gap: 6px; padding: 7px 10px; flex-wrap: wrap; justify-content: center; }
.menuResults > nav button { padding: 0 8px; }
.menuListPaged { padding-bottom: 116px; }
}
/* Two classes deep, as above, so checkbox and name stay on one line. */
.menuList .menuItem { display: flex; flex-direction: row; align-items: center; gap: 6px; min-height: 30px; color: #28352d; cursor: pointer; }
.menuList .menuItemDisabled { cursor: default; opacity: 0.6; }
@ -38,14 +45,14 @@
/* Middle: the table */
.main { flex: 1; min-width: 0; display: flex; flex-direction: column; }
.head { flex: none; display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; padding: 12px 16px 8px; }
.head > div:first-child { min-width: 0; }
.head { flex: none; display: flex; flex-wrap: wrap; align-items: flex-start; justify-content: space-between; gap: 8px 16px; padding: 12px 16px 8px; }
.head > div:first-child { flex: 1 1 170px; min-width: 0; }
.heading { margin: 0; font-size: 16px; font-weight: 600; color: #111315; }
.sub { margin: 2px 0 0; font-size: 11px; letter-spacing: 0.01em; color: #5f656a; }
/* The search and the two buttons keep their size and stay on one line; the title's line is what gives way. */
.tools { display: flex; align-items: center; gap: 8px; flex: none; }
.tools { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; max-width: 100%; }
.tools button { flex: none; white-space: nowrap; }
.search { display: flex; align-items: center; gap: 8px; width: 220px; height: 36px; border: 1px solid #8f959a; border-radius: 6px; padding: 0 12px; background: #fff; color: #5f656a; }
.search { display: flex; align-items: center; gap: 8px; width: 220px; max-width: 100%; height: 36px; border: 1px solid #8f959a; border-radius: 6px; padding: 0 12px; background: #fff; color: #5f656a; }
.search:focus-within { outline: 2px solid #5b7265; outline-offset: 1px; }
.search input { flex: 1; min-width: 0; border: 0; background: none; outline: none; color: #28352d; font-size: 12px; }
.filters { flex: none; display: flex; flex-wrap: wrap; align-items: center; gap: 12px; padding: 0 16px 12px; font-size: 11px; letter-spacing: 0.02em; color: #5f656a; }
@ -98,10 +105,6 @@
.tag { flex: none; display: inline-flex; align-items: center; height: 20px; border-radius: 4px; padding: 0 6px; font-size: 10px; line-height: 1.6; letter-spacing: 0.01em; color: #55635a; background: #eef2ef; }
.tagPending { color: #865c28; background: #fff1d6; }
.tagNew { color: #2f5e52; background: #e2f0e9; }
.sizeRules { flex: none; margin: 0; border-top: 1px solid #e3e8e5; padding: 10px 16px; font-size: 11px; line-height: 1.8; color: #5f656a; }
.sizeRules summary { cursor: pointer; }
.sizeRules ul { margin: 8px 0 0; padding-left: 18px; list-style: disc; }
/* Right: sources and records of the selected row */
.detail { flex: none; width: 300px; overflow: auto; border-left: 1px solid #e3e8e5; padding: 16px 12px 16px 16px; background: #f7f7f6; }
.detailTitle { margin: 0; font-size: 16px; font-weight: 600; color: #111315; }
@ -116,6 +119,10 @@
.recordHead { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; margin-bottom: 2px; }
.recordText { margin: 0 0 6px; line-height: 1.6; }
.recordActions { display: flex; gap: 6px; }
.ruleEdit { display: grid; gap: 8px; }
.ruleEdit label { display: grid; gap: 4px; }
.ruleEdit input, .ruleEdit textarea { width: 100%; padding: 6px 8px; border: 1px solid #cbd4cf; border-radius: 4px; background: #fff; }
.ruleEdit textarea { min-height: 60px; resize: vertical; }
.danger { color: #a5432f; }
.detailActions { display: flex; gap: 8px; margin-top: 16px; }
@ -126,6 +133,7 @@
.main { flex: none; }
.scroll { overflow: visible; }
.head { flex-direction: column; }
.head > div:first-child { flex-basis: auto; }
.search { width: 100%; }
.detail { border-bottom: 0; }
}

View File

@ -1,18 +1,21 @@
import { z } from 'zod'
import { backPanelSkillSchema, type BackPanelCategory, type BackPanelParameters } from '@/lib/reference-estimator/standard/back-panel-skill'
import { imageCategoryEntrySchema, imageSkillCategoryLabel } from '@/lib/reference-estimator/standard/cabinet-image-memory'
import { structureModelInfoSchema, structureModelSchema, structureSkillId, structureSkillSchema, type StructureIntent, type StructureModel, type StructureModelInfo,
import { maintenanceRecordId, maintenanceRuleSchema, type MaintenanceRecord, type MaintenanceRuleDetails } from '@/lib/reference-estimator/standard/maintenance-rule'
import { structureModelInfoSchema, structureSkillId, structureSkillSchema, type StructureIntent, type StructureModelInfo,
type StructureModule, type StructureSkill } from '@/lib/reference-estimator/standard/structure-summary'
import { structureModelPageSchema, type StructureModelPage } from '@/lib/reference-estimator/standard/structure-model-selection'
const endpoint = '/api/intake/reference-estimate-skills/structure'
export type { StructureModel } from '@/lib/reference-estimator/standard/structure-summary'
export type StructureRecord = StructureSkill & { id: string }
export type StructureReview = 'approve' | 'revoke' | 'restore'
export type StructureRescan = { models: StructureModelInfo[]; added: number; extended: number; items: StructureRecord[] }
export type StructureRescan = { models: (StructureModelInfo & { id: string })[]; added: number; extended: number; items: StructureRecord[] }
/** A relation the user adds. With a subject and intent it answers the same question about the same part as an existing row. */
export type StructureSupplement = { module: StructureModule; text: string; subject?: string; intent?: StructureIntent }
export type StructureCategorySummary = z.infer<typeof categorySummarySchema>
/** The library as one read: every relation, the categories with their materials, and the version it was read at. */
export type StructureSnapshot = { structure: StructureRecord[]; categories: StructureCategorySummary[]; version: string }
export type StructureSnapshot = { structure: StructureRecord[]; rules: MaintenanceRecord[]; categories: StructureCategorySummary[]; version: string }
const categorySummarySchema = z.object({
category: imageCategoryEntrySchema.shape.category,
@ -20,28 +23,66 @@ const categorySummarySchema = z.object({
materials: z.array(z.object({ materialType: z.string().min(1).max(20), count: z.number().int() })),
})
const headers = { 'Content-Type': 'application/json' }
export class StructureAccessError extends Error {}
const parseAll = <T>(schema: z.ZodType<T>, values: readonly unknown[] | undefined): T[] =>
(values ?? []).flatMap(value => { const parsed = schema.safeParse(value); return parsed.success ? [parsed.data] : [] })
type SnapshotResponse = { structure?: unknown[]; rules?: unknown[]; categories?: unknown[]; version?: string; unchanged?: boolean }
function readSnapshot(data: SnapshotResponse): StructureSnapshot {
return { structure: parseAll(structureSkillSchema, data.structure).map(item => ({ ...item,
id: structureSkillId(item.category, item.materialType, item.key) })),
rules: parseAll(maintenanceRuleSchema, data.rules).map(item => ({ ...item, id: maintenanceRecordId(item) })),
categories: parseAll(categorySummarySchema, data.categories), version: data.version ?? '' }
}
// What was read last stays here for the session: coming back to the page shows it at once and only asks whether it changed.
// It is only shown straight away while fresh; an older one is replaced by a new read.
const KEPT_FOR = 30 * 60_000
let kept: { snapshot: StructureSnapshot; at: number } | null = null
const modelLists = new Map<string, { at: number; models: StructureModel[] }>()
const kept = new Map<string, { snapshot: StructureSnapshot; at: number }>()
let account: string | null = null
let categoryList: { categories: StructureCategorySummary[]; at: number } | undefined
let lastCategory: string | null = null
const modelLists = new Map<string, { at: number; value: StructureModelPage }>()
const MODEL_LIST_TTL = 60_000
const MODEL_LIST_FRESH = 15_000
const modelPageKey = (category: string, page: number, pageSize: number) => JSON.stringify([category, page, pageSize])
export const clearStructureModelPages = () => { modelLists.clear() }
/** The library as last read, with when that was, when that is recent enough to show before checking; null otherwise. */
export const keptStructure = () => kept && Date.now() - kept.at < KEPT_FOR ? kept : null
export function scopeStructureAccount(id: string | null) {
if (account !== id) {
account = id; kept.clear(); modelLists.clear(); categoryList = undefined; lastCategory = null
}
}
export const keptStructureCategories = (userId: string | null) =>
account === userId && categoryList && Date.now() - categoryList.at < KEPT_FOR ? categoryList.categories : null
export const lastStructureCategory = (userId: string | null) => account === userId ? lastCategory : null
export const rememberStructureCategory = (category: string) => { lastCategory = category }
export const keptStructure = (category: string) => {
const entry = kept.get(category)
return entry && Date.now() - entry.at < KEPT_FOR ? entry : undefined
}
function remember(category: string, snapshot: StructureSnapshot) {
if (kept.size >= 32) kept.delete(kept.keys().next().value!)
kept.set(category, { snapshot, at: Date.now() })
}
function record(value: unknown): StructureRecord | null {
const parsed = structureSkillSchema.safeParse(value)
return parsed.success ? { ...parsed.data, id: structureSkillId(parsed.data.category, parsed.data.materialType, parsed.data.key) } : null
}
async function request<T>(init?: RequestInit, url = endpoint): Promise<T> {
const response = await fetch(url, { cache: 'no-store', ...init })
const timeout = AbortSignal.timeout(15_000)
const signal = init?.signal ? AbortSignal.any([init.signal, timeout]) : timeout
const response = await fetch(url, { cache: 'no-store', ...init, signal }).catch(error => {
if (timeout.aborted) throw new Error(init?.method === 'POST' ? '技能库操作超过 15 秒,请刷新确认结果。' : '读取技能库超过 15 秒,请重试。')
throw error
})
const body = await response.json().catch(() => null)
if (!response.ok || !body?.success) {
// A session that ended, or an account that lost access, may not keep showing what the last one read.
if (response.status === 401 || response.status === 403) { kept = null; modelLists.clear() }
if (response.status === 401 || response.status === 403) {
kept.clear(); modelLists.clear(); categoryList = undefined; lastCategory = null
throw new StructureAccessError(body?.error?.message ?? '当前账号无法访问技能库。')
}
throw new Error(body?.error?.message ?? (response.status === 401 ? '登录已失效,请重新登录。' : '技能库暂时不可用,请重试。'))
}
return body.data as T
@ -52,33 +93,54 @@ const post = <T>(body: Record<string, unknown>) => request<T>({ method: 'POST',
* Reads the library. A caller that passes the version it holds gets back the same snapshot again when nothing changed.
* `fresh` tells whether this call brought new content.
*/
export async function readStructureSkills(signal?: AbortSignal, version?: string): Promise<{ snapshot: StructureSnapshot; fresh: boolean }> {
const data = await request<{ structure?: unknown[]; categories?: unknown[]; version?: string; unchanged?: boolean }>({ signal },
version ? `${endpoint}?version=${encodeURIComponent(version)}` : endpoint)
if (data.unchanged && kept) return { snapshot: kept.snapshot, fresh: false }
const snapshot: StructureSnapshot = { structure: parseAll(structureSkillSchema, data.structure).map(item => ({ ...item,
id: structureSkillId(item.category, item.materialType, item.key) })), categories: parseAll(categorySummarySchema, data.categories), version: data.version ?? '' }
kept = { snapshot, at: Date.now() }
export async function readStructureCategories(signal?: AbortSignal) {
const data = await request<SnapshotResponse>({ signal })
const categories = parseAll(categorySummarySchema, data.categories)
if (!signal?.aborted) categoryList = { categories, at: Date.now() }
return categories
}
export async function readStructureSkills(category: string, signal?: AbortSignal, force = false): Promise<{ snapshot: StructureSnapshot; fresh: boolean }> {
const entry = keptStructure(category)
const query = new URLSearchParams({ category })
if (entry?.snapshot.version && !force) query.set('version', entry.snapshot.version)
const data = await request<SnapshotResponse>({ signal }, `${endpoint}?${query}`)
if (data.unchanged && entry) {
if (!signal?.aborted) remember(category, entry.snapshot)
return { snapshot: entry.snapshot, fresh: false }
}
const snapshot = readSnapshot(data)
if (!signal?.aborted) remember(category, snapshot)
return { snapshot, fresh: true }
}
/** Lists the caller's models of a category so they can choose which ones to read. Kept for a minute: the list rarely changes. */
export async function listStructureModels(category: string, signal?: AbortSignal) {
const cached = modelLists.get(category)
if (cached && Date.now() - cached.at < MODEL_LIST_TTL) return cached.models
const data = await request<{ models?: unknown[] }>({ method: 'POST', headers, signal,
body: JSON.stringify({ action: 'models', category }) })
const models = parseAll(structureModelSchema, data.models)
if (!signal?.aborted) modelLists.set(category, { at: Date.now(), models })
return models
export function keptStructureModelPage(userId: string | null, category: string, page: number, pageSize: number) {
const entry = account === userId ? modelLists.get(modelPageKey(category, page, pageSize)) : undefined
return entry && Date.now() - entry.at < MODEL_LIST_TTL ? entry.value : null
}
/** Reads the chosen models, or every model of the category when none is chosen. */
export async function rescanStructure(category: string, modelIds: readonly string[] | undefined, dryRun: boolean): Promise<StructureRescan> {
/** Lists this account's current page of models, without sending their documents over the network. */
export async function listStructureModels(category: string, page: number, pageSize: number, signal: AbortSignal, force = false) {
const user = account
const key = modelPageKey(category, page, pageSize)
const cached = modelLists.get(key)
if (!force && cached && Date.now() - cached.at < MODEL_LIST_FRESH) return cached.value
const data = await request<unknown>({ method: 'POST', headers, signal,
body: JSON.stringify({ action: 'models', category, page, pageSize }) })
const value = structureModelPageSchema.parse(data)
if (!signal.aborted && account === user) {
if (modelLists.size >= 32) modelLists.delete(modelLists.keys().next().value!)
modelLists.set(modelPageKey(category, value.page, value.pageSize), { at: Date.now(), value })
}
return value
}
/** Reads only the chosen models. */
export async function rescanStructure(category: string, modelIds: readonly string[], dryRun: boolean): Promise<StructureRescan> {
const data = await post<{ models?: unknown[]; added?: number; extended?: number; items?: unknown[] }>(
{ action: 'rescan', category, dryRun, ...(modelIds ? { modelIds } : {}) })
if (!dryRun) { kept = null; modelLists.clear() }
return { models: parseAll(structureModelInfoSchema, data.models), added: data.added ?? 0, extended: data.extended ?? 0,
{ action: 'rescan', category, dryRun, modelIds })
if (!dryRun) { kept.clear(); modelLists.clear() }
return { models: parseAll(structureModelInfoSchema.extend({ id: z.string().min(1).max(60) }), data.models), added: data.added ?? 0, extended: data.extended ?? 0,
items: parseAll(structureSkillSchema, data.items).flatMap(item => { const saved = record(item); return saved ? [saved] : [] }) }
}
@ -86,7 +148,7 @@ export async function reviewStructure(id: string, action: StructureReview) {
return post<unknown>({ action, id }).then(value => {
const updated = record(value)
// The kept copy follows the change, so coming back shows the library as it is now.
if (updated && kept) kept = { ...kept, snapshot: { ...kept.snapshot, structure: kept.snapshot.structure.map(item => item.id === id ? updated : item) } }
if (updated) kept.delete(updated.category)
return updated
})
}
@ -95,18 +157,27 @@ export async function reviewStructure(id: string, action: StructureReview) {
export async function addStructureSkill(input: StructureSupplement & { category: string; materialType: string }) {
return post<unknown>({ action: 'add', ...input }).then(value => {
const created = record(value)
if (created && kept) kept = { ...kept, snapshot: { ...kept.snapshot, structure: [...kept.snapshot.structure.filter(item => item.id !== created.id), created] } }
if (created) kept.delete(created.category)
return created
})
}
/** Gives a category a material column before any model of that material is read. */
export async function registerStructureMaterial(input: { category: string; materialType: string }) {
const data = await post<{ structure?: unknown[]; categories?: unknown[]; version?: string }>({ action: 'material', ...input })
const snapshot: StructureSnapshot = { structure: parseAll(structureSkillSchema, data.structure).map(item => ({ ...item,
id: structureSkillId(item.category, item.materialType, item.key) })), categories: parseAll(categorySummarySchema, data.categories), version: data.version ?? '' }
kept = { snapshot, at: Date.now() }
const snapshot = readSnapshot(await post<SnapshotResponse>({ action: 'material', ...input }))
remember(input.category, snapshot)
return snapshot
}
export async function saveDialogueMaintenanceRule(id: string, updatedAt: string, details: MaintenanceRuleDetails) {
await post({ action: 'edit-dialogue', id, updatedAt, ...details })
kept.clear()
}
export async function saveBackPanelMaintenanceRule(category: BackPanelCategory, revision: number, parameters: BackPanelParameters, notes?: string) {
const rule = backPanelSkillSchema.parse(await post({ action: 'edit-back-panel', category, revision, parameters, notes }))
kept.delete(category)
return rule
}
export const structureCategoryLabel = imageSkillCategoryLabel

View File

@ -2,10 +2,10 @@ import {
compareStructureStatements, structureIntents, structureIntent, structureIntentLabels, structureModuleLabels, structureModules, structureSubjectLabel,
type StructureIntent, type StructureModule,
} from '@/lib/reference-estimator/standard/structure-summary'
import type { StructureRecord } from './structure-client'
import type { MaintenanceRecord } from '@/lib/reference-estimator/standard/maintenance-rule'
/** A relation as the table shows it: a preview marks one that is read but not saved yet. */
export type MatrixRecord = StructureRecord & { isNew?: boolean }
export type MatrixRecord = MaintenanceRecord & { isNew?: boolean }
export type MatrixCell =
| { kind: 'text'; items: MatrixRecord[]; text: string }
| { kind: 'none'; why: string }
@ -46,12 +46,14 @@ export function buildMatrix(records: readonly MatrixRecord[], materials: readonl
const subjectRank = new Map<string, number>()
for (const item of [...records].sort(compareStructureStatements)) {
const subject = subjectKey(item), intent = structureIntent(item)
if (item.rule && !materials.includes(item.materialType)) continue
if (!subjectRank.has(subject)) subjectRank.set(subject, subjectRank.size)
const id = `${item.module}|${subject}|${intent}`
let line = lines.get(id)
if (!line) {
const free = isFree(item)
line = { id, module: item.module, subject, free, label: free ? item.text : structureSubjectLabel(subject), intent, byMaterial: new Map() }
line = { id, module: item.module, subject, free: free || Boolean(item.rule),
label: item.rule?.label ?? (free ? item.text : structureSubjectLabel(subject)), intent, byMaterial: new Map() }
lines.set(id, line)
}
line.byMaterial.set(item.materialType, [...(line.byMaterial.get(item.materialType) ?? []), item])
@ -94,7 +96,9 @@ export function filterMatrix(lines: readonly MatrixLine[], filter: MatrixFilter,
if (filter === 'diff' && line.same) return false
if (filter === 'missing' && !line.cells.some(cell => cell.kind === 'missing')) return false
if (filter === 'pending' && !line.items.some(item => item.status === 'pending')) return false
return !needle || `${structureModuleLabels[line.module]}${line.label}${structureIntentLabels[line.intent]}${line.items.map(item => item.text).join('')}`.includes(needle)
return !needle || `${structureModuleLabels[line.module]}${line.label}${structureIntentLabels[line.intent]}${line.items.map(item =>
item.text + (item.rule?.source === 'dialogue' || item.rule?.source === 'legacy'
? item.rule.details.appliesWhen + item.rule.details.method + (item.rule.details.exceptions ?? '') : '')).join('')}`.includes(needle)
})
}

View File

@ -0,0 +1,55 @@
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import { StructureModelMenu } from './StructureModelMenu'
import { scopeStructureAccount } from './structure-client'
import { useStructureModelSelection } from './useStructureModelSelection'
const originalFetch = globalThis.fetch
afterEach(() => {
globalThis.fetch = originalFetch
scopeStructureAccount(null)
})
it('跨页保留勾选,切回复用清单,预览只交出两页分别选中的模型', async () => {
scopeStructureAccount('local-test-account')
const fetchMock = jest.fn(async (_url: unknown, init: RequestInit) => {
const { page, pageSize } = JSON.parse(init.body as string)
const total = 12
const start = (page - 1) * pageSize
const models = Array.from({ length: Math.min(pageSize, total - start) }, (_, index) => {
const number = start + index + 1
return { id: `model-${number}`, title: `模型 ${number}`, revision: 1, updatedAt: '2026-12-02', readable: true, spu: null }
})
return { ok: true, json: async () => ({ success: true, data: { models, page, pageSize, total, totalPages: 2 } }) } as Response
})
globalThis.fetch = fetchMock as unknown as typeof fetch
const preview = jest.fn()
function Picker() {
const picker = useStructureModelSelection('书柜', 'local-test-account')
return <>
<button onClick={() => picker.setOpen(true)}>读取模型</button>
{picker.open && <StructureModelMenu id="picker" picker={picker} categoryLabel="书柜" busy={false}
onPreview={() => preview(picker.chosen)} />}
</>
}
render(<Picker />)
const open = screen.getByRole('button', { name: '读取模型' })
expect(fetchMock).not.toHaveBeenCalled()
fireEvent.click(open)
const panel = within(screen.getByRole('region', { name: '读取模型' }))
const first = await panel.findByRole('checkbox', { name: '模型 1' })
expect(panel.getAllByRole('checkbox')).toHaveLength(10)
expect(first).not.toBeChecked()
expect(panel.getByRole('button', { name: '读出并预览' })).toBeDisabled()
fireEvent.click(first)
fireEvent.click(panel.getByRole('button', { name: '下一页' }))
const last = await panel.findByRole('checkbox', { name: '模型 12' })
expect(panel.getAllByRole('checkbox')).toHaveLength(2)
fireEvent.click(last)
fireEvent.click(panel.getByRole('button', { name: '上一页' }))
await waitFor(() => expect(panel.getByRole('checkbox', { name: '模型 1' })).toBeChecked())
expect(panel.getByText('共 12 条')).toBeInTheDocument()
fireEvent.click(panel.getByRole('button', { name: '读出并预览' }))
expect(preview).toHaveBeenCalledWith(['model-1', 'model-12'])
expect(fetchMock).toHaveBeenCalledTimes(2)
})

View File

@ -0,0 +1,67 @@
'use client'
import { useEffect, useState } from 'react'
import { bookshelfMemoryChanged } from '../standard/bookshelf-memory-client'
import {
keptStructure, keptStructureCategories, lastStructureCategory, rememberStructureCategory, StructureAccessError,
readStructureCategories, readStructureSkills, scopeStructureAccount,
type StructureCategorySummary, type StructureSnapshot,
} from './structure-client'
type Load =
| { category: string; status: 'error' }
| { category: string; status: 'ready'; snapshot: StructureSnapshot; at: number }
type Freshness = 'checking' | 'current' | 'updated' | 'failed'
export function useStructureMaintenance(userId?: string) {
const [categories, setCategories] = useState<StructureCategorySummary[] | null>(() => keptStructureCategories(userId ?? null))
const [categoryError, setCategoryError] = useState(false)
const [selected, setSelected] = useState<string | null>(() => lastStructureCategory(userId ?? null))
const [load, setLoad] = useState<Load | null>(null)
const [freshness, setFreshness] = useState<Freshness>('current')
const [reload, setReload] = useState(0)
const refresh = () => { setCategoryError(false); setReload(value => value + 1) }
const category = selected && categories?.some(item => item.category === selected) ? selected
: categories?.find(item => item.materials.some(material => material.count > 0))?.category ?? categories?.[0]?.category ?? null
useEffect(() => {
window.addEventListener(bookshelfMemoryChanged, refresh)
return () => window.removeEventListener(bookshelfMemoryChanged, refresh)
}, [])
useEffect(() => {
scopeStructureAccount(userId ?? null)
const controller = new AbortController()
void readStructureCategories(controller.signal).then(value => {
if (!controller.signal.aborted) setCategories(value)
}).catch(error => {
if (controller.signal.aborted) return
if (error instanceof StructureAccessError) { setCategories(null); setLoad(null) }
setCategoryError(true)
})
return () => controller.abort()
}, [reload, userId])
useEffect(() => {
if (!category) return
rememberStructureCategory(category)
const controller = new AbortController()
const saved = keptStructure(category)
void readStructureSkills(category, controller.signal, reload > 0).then(({ snapshot, fresh }) => {
if (controller.signal.aborted) return
setLoad({ category, status: 'ready', snapshot, at: Date.now() })
setFreshness(fresh && saved ? 'updated' : 'current')
}).catch(error => {
if (controller.signal.aborted) return
if (error instanceof StructureAccessError) { setCategories(null); setCategoryError(true) }
if (keptStructure(category)) setFreshness('failed')
else setLoad({ category, status: 'error' })
})
return () => controller.abort()
}, [category, reload, userId])
const saved = category ? keptStructure(category) : undefined
const current = load?.category === category ? load
: category && saved ? { category, status: 'ready' as const, ...saved } : null
const status = current?.status === 'ready' && (categoryError || freshness === 'failed') ? 'failed'
: current && load?.category !== category ? 'checking' : freshness
return { categories, category, categoryError, current, freshness: status, setSelected, setLoad, setFreshness, refresh }
}

View File

@ -0,0 +1,65 @@
'use client'
import { useEffect, useState } from 'react'
import { structureModelDefaultPageSize, structureModelSelectionLimit, type StructureModelPage } from '@/lib/reference-estimator/standard/structure-model-selection'
import { bookshelfMemoryChanged } from '../standard/bookshelf-memory-client'
import { clearStructureModelPages, keptStructureModelPage, listStructureModels, StructureAccessError } from './structure-client'
type Load = { category: string; value: StructureModelPage | null; error?: string }
export function useStructureModelSelection(category: string | null, userId: string | null) {
const [open, setMenuOpen] = useState(false)
const [page, setPage] = useState(1)
const [pageSize, setPageSize] = useState<number>(structureModelDefaultPageSize)
const [retry, setRetry] = useState(0)
const [load, setLoad] = useState<Load | null>(null)
const [selection, setSelection] = useState<{ category: string | null; ids: string[] }>({ category: null, ids: [] })
const chosen = selection.category === category ? selection.ids : []
const reset = () => { setMenuOpen(false); setPage(1); setLoad(null); setSelection({ category: null, ids: [] }); setRetry(0) }
const choose = (ids: string[]) => setSelection({ category, ids: ids.slice(0, structureModelSelectionLimit) })
const setOpen = (next: boolean) => {
if (next) {
const value = category && keptStructureModelPage(userId, category, page, pageSize)
setLoad(category && value ? { category, value } : null)
setRetry(0)
}
setMenuOpen(next)
}
useEffect(() => {
const invalidate = () => { clearStructureModelPages(); setRetry(value => value + 1) }
window.addEventListener(bookshelfMemoryChanged, invalidate)
return () => window.removeEventListener(bookshelfMemoryChanged, invalidate)
}, [])
useEffect(() => {
if (!category || !open) return
const controller = new AbortController()
void listStructureModels(category, page, pageSize, controller.signal, retry > 0).then(value => {
if (controller.signal.aborted) return
if (value.page !== page) setPage(value.page)
setLoad({ category, value })
}).catch(error => {
if (controller.signal.aborted) return
if (error instanceof StructureAccessError) {
setSelection({ category: null, ids: [] })
setLoad({ category, value: null, error: error.message })
} else {
const cached = keptStructureModelPage(userId, category, page, pageSize)
setLoad(previous => ({ category, value: cached ?? (previous?.category === category ? previous.value : null),
error: '模型列表读取失败,请重试。' }))
}
})
return () => controller.abort()
}, [category, open, page, pageSize, retry, userId])
const current = load?.category === category ? load : null
const cached = open && category ? keptStructureModelPage(userId, category, page, pageSize) : null
const shown = cached ?? current?.value ?? null
const changePageSize = (size: number) => { setRetry(0); setPageSize(size); setPage(1) }
return {
open, setOpen, reset, shown, chosen, choose, changePage: (next: number) => { setRetry(0); setPage(next) }, changePageSize,
error: current?.error,
pending: !current?.error && (shown?.page !== page || shown?.pageSize !== pageSize),
retry: () => { setLoad(previous => previous ? { category: previous.category, value: previous.value } : null); setRetry(value => value + 1) },
}
}

View File

@ -0,0 +1,19 @@
import Button from '@/components/ui/Button'
import type { CabinetCornerGuardController } from './useCabinetCornerGuard'
import styles from './cabinet-hardware-placement-controls.module.css'
export function CabinetCornerGuardControls({ guard }: { guard: CabinetCornerGuardController }) {
const { preview, feedback, busy, confirm, cancel } = guard
if (!preview && !feedback) return null
return <section className={styles.selection} aria-label="顶板四角护角">
{preview && <>
<strong>{preview.item.name} · {preview.item.code} × 4</strong>
<p>顶板左前、右前、左后、右后各 1 个 · 免打孔</p>
<div className={styles.actions}>
<Button type="button" size="small" variant="gray" disabled={busy || !guard.modelState.ready} onClick={() => void confirm()}>确认安装 4 个</Button>
<Button type="button" size="small" variant="plain" disabled={busy} onClick={cancel}>取消预览</Button>
</div>
</>}
{feedback && <p role={feedback.error ? 'alert' : 'status'}>{feedback.text}</p>}
</section>
}

View File

@ -0,0 +1,32 @@
import { useMemo } from 'react'
import { Html } from '@react-three/drei'
import { cornerGuardLabels } from '@/lib/reference-estimator/standard/cabinet-corner-guard'
import type { CornerGuardModels } from './useCornerGuardModels'
import { cornerGuardRotation } from './corner-guard-model'
import type { cabinetSurfacePositions } from './cabinet-surface-selection'
import { CabinetSurfacePickTarget } from './CabinetSurfacePickTarget'
import styles from './estimate-workbench.module.css'
export function CabinetCornerGuardLayer({ rows, preview, models, selected, onPick }: {
rows: ReturnType<typeof cabinetSurfacePositions>['guards']; preview: boolean
models?: CornerGuardModels['models']
selected?: ReadonlySet<string>; onPick?: (key: string) => void
}) {
const clones = useMemo(() => rows.map(row => models?.[row.accessoryId]?.clone(true)), [rows, models])
if (!rows.length) return null
return <group name="顶板四角护角">
{rows.map(({ key, location, scenePoint, left, front }, index) => {
const clone = clones[index]
if (!clone) return null
const inX = left ? 1 : -1
const inZ = front ? -1 : 1
return <CabinetSurfacePickTarget key={key} position={scenePoint} selected={!preview && selected?.has(key)}
onPick={!preview && onPick ? () => onPick(key) : undefined}>
<primitive object={clone} rotation={[0, cornerGuardRotation[location], 0]} dispose={null}/>
{preview && <Html center position={[-inX * 8, 6, -inZ * 8]} zIndexRange={[12, 11]} style={{ pointerEvents: 'none' }}>
<span className={styles.dimensionLabel} style={{ transform: `translate(${left ? 15 : -15}px, ${front ? 12 : -12}px)` }}>{cornerGuardLabels[location]}</span>
</Html>}
</CabinetSurfacePickTarget>
})}
</group>
}

View File

@ -9,14 +9,15 @@ import styles from './cabinet-hardware-placement-controls.module.css'
type Pixel = [x: number, y: number]
type Drag = { start: Pixel; end: Pixel }
export type ProjectPoint = (point: MmPoint, width: number, height: number) => Pixel | undefined
export type SelectableHardware = { point: CamPlacement; position: MmPoint }
export type SelectableHardware<T = CamPlacement> = { point: T; position: MmPoint }
export function CabinetHardwareProjector({ projectRef }: { projectRef: RefObject<ProjectPoint | null> }) {
const get = useThree(state => state.get)
useLayoutEffect(() => {
const point = new Vector3()
projectRef.current = (position, width, height) => {
const { camera } = get()
const point = new Vector3(...position).project(camera)
point.set(...position).project(camera)
if (point.z < -1 || point.z > 1) return
return [(point.x + 1) * width / 2, (1 - point.y) * height / 2]
}
@ -25,10 +26,10 @@ export function CabinetHardwareProjector({ projectRef }: { projectRef: RefObject
return null
}
export function CabinetHardwareBoxSelect({ project, points, onSelect, onCancel }: {
export function CabinetHardwareBoxSelect<T>({ project, points, onSelect, onCancel }: {
project: RefObject<ProjectPoint | null>
points: SelectableHardware[]
onSelect: (points: CamPlacement[]) => void
points: SelectableHardware<T>[]
onSelect: (points: T[]) => void
onCancel: () => void
}) {
const start = useRef<Pixel | null>(null)
@ -53,7 +54,7 @@ export function CabinetHardwareBoxSelect({ project, points, onSelect, onCancel }
onSelect(matches.map(({ point }) => point))
onCancel()
}
return <div className={styles.boxOverlay} aria-label="框选五金区域" tabIndex={0}
return <div className={styles.boxOverlay} aria-label="框选区域" tabIndex={0}
onKeyDown={event => { if (event.key === 'Escape') onCancel() }}
onPointerDown={event => {
if (event.button !== 0) return

View File

@ -5,6 +5,8 @@ import { cabinetHardwareBoard } from '@/lib/reference-estimator/standard/hardwar
import Button from '@/components/ui/Button'
import styles from './cabinet-hardware-placement-controls.module.css'
const directions = [['向左', '向右'], ['向前', '向后'], ['向下', '向上']]
export function CabinetHardwareHoleDetails({ point, hardware, depthChoices, onConfirmDepth, busy }: {
point: CamPlacement; hardware?: PlacementHardware | null
depthChoices?: readonly number[]
@ -20,9 +22,10 @@ export function CabinetHardwareHoleDetails({ point, hardware, depthChoices, onCo
onClick={() => onConfirmDepth(depth)}>确认 {depth} mm</Button>)}
</div>}
</>
return <p aria-label="板件开孔">板件开孔
{holes.map(({ kind, board, diameter, depth }) => <span key={kind}>
<br/>{cabinetHardwareBoard(board.part, board.start, board.part.positions.indexOf(board.start)).label} · {holeLabels[kind]} Ø{diameter} · {kind === 'through' ? '打通' : '深'} {depth} mm
return <p aria-label="板件开孔">{hardware.machiningEstimated ? '板件开孔(按模型暂估)' : '板件开孔'}
{holes.map(({ kind, board, diameter, depth, direction }) => <span key={kind}>
<br/>{cabinetHardwareBoard(board.part, board.start, board.part.positions.indexOf(board.start)).label} · {holeLabels[kind]} Ø{diameter} · {kind === 'through' ? '打通' : '深'} {depth} mm · {directions[direction.findIndex(value => value !== 0)]?.[direction.some(value => value > 0) ? 1 : 0]}
{kind === 'wheel' && hardware.camLock && ` · 孔心距板缝 ${hardware.camLock.setbackMm} mm(按模型)`}
</span>)}
</p>
}

View File

@ -80,7 +80,7 @@ export function CabinetHardwarePreviewControls({ preview, boxing, onBox, picking
{preview.areas.map(([id, title]) => <button type="button" key={id}
aria-pressed={area === id} onClick={() => onAreaChange(id)}>{title}</button>)}
{onPickBoards && <button type="button" aria-pressed={pickingBoards} onClick={onPickBoards}>点选板件</button>}
{onBox && <button type="button" aria-pressed={boxing} onClick={onBox}>框选五金</button>}
{onBox && <button type="button" aria-pressed={boxing} onClick={onBox}>框选</button>}
</div>
<div className={styles.legend} role="status">
{message && <span>{message}</span>}

View File

@ -1,31 +1,47 @@
import { DoubleSide, Quaternion, Vector3 } from 'three'
import { Html } from '@react-three/drei'
import type { HardwarePlacementEdits } from '@/lib/reference-estimator/standard/hardware-placement-edits'
import { cabinetHardwareHoles, type CamPlacement, type MmPoint } from './cabinet-cam-preview'
import { seamPlacement, type CabinetSeam } from './cabinet-sg0164-seam'
import { seamEdges, seamPlacement, type CabinetSeam } from './cabinet-sg0164-seam'
import styles from './estimate-workbench.module.css'
const ringAxis = new Vector3(0, 0, 1)
const tubeAxis = new Vector3(0, 1, 0)
const ignoreRaycast = () => null
const sceneDirection = ([x, y, z]: MmPoint) => new Vector3(x, z, -y)
export function CabinetHardwareSeamLayer({ seam, size, points, edits, selected, previewOffsets }: {
seam: CabinetSeam; size: MmPoint; points: CamPlacement[]; edits: HardwarePlacementEdits
selected: ReadonlySet<string>; previewOffsets: number[]
export function CabinetHardwareSeamLayer({ seam, size, points, edits, selected, previewOffsets = [], showEdges = false }: {
seam?: CabinetSeam; size: MmPoint; points: CamPlacement[]; edits: HardwarePlacementEdits
selected: ReadonlySet<string>; previewOffsets?: number[]; showEdges?: boolean
}) {
const [width, depth, height] = size
const origin = new Vector3(-width / 2, -height / 2, depth / 2)
const midpoint: MmPoint = [...seam.template.center]
midpoint[seam.axis] = seam.start + seam.length / 2
const center = sceneDirection(midpoint).add(origin)
const midpoint: MmPoint = seam ? [...seam.template.center] : [0, 0, 0]
const along: MmPoint = [0, 0, 0]
along[seam.axis] = 1
const alongSeam = new Quaternion().setFromUnitVectors(tubeAxis, sceneDirection(along))
const seamColor = showEdges ? '#2563eb' : '#4076a0'
if (seam) {
midpoint[seam.axis] = seam.start + seam.length / 2
along[seam.axis] = 1
}
return <group name="selected-board-seam">
<mesh position={center} quaternion={alongSeam} raycast={ignoreRaycast} renderOrder={3}>
<cylinderGeometry args={[1.6, 1.6, seam.length, 8]}/>
<meshBasicMaterial color="#4076a0" depthTest={false}/>
</mesh>
{previewOffsets.map((offset, index) => {
{seam && <mesh position={sceneDirection(midpoint).add(origin)}
quaternion={new Quaternion().setFromUnitVectors(tubeAxis, sceneDirection(along))} raycast={ignoreRaycast} renderOrder={3}>
<cylinderGeometry args={[showEdges ? 2.5 : 1.6, showEdges ? 2.5 : 1.6, seam.length, 8]}/>
<meshBasicMaterial color={seamColor} depthTest={false} depthWrite={false}/>
</mesh>}
{seam && showEdges && seamEdges[seam.axis].map((label, index) => {
const position = sceneDirection(seamPlacement(seam, 'edge-label', index * seam.length).center).add(origin)
return <group key={label} position={position}>
<mesh raycast={ignoreRaycast} renderOrder={3}>
<sphereGeometry args={[3.5, 10, 6]}/>
<meshBasicMaterial color={seamColor} depthTest={false} depthWrite={false}/>
</mesh>
<Html center zIndexRange={[12, 11]} style={{ pointerEvents: 'none' }}>
<span className={styles.dimensionLabel} style={{ transform: `translateY(${index ? -16 : 16}px)` }}>{label}</span>
</Html>
</group>
})}
{seam && previewOffsets.map((offset, index) => {
const point = seamPlacement(seam, 'preview-' + index, offset)
return <mesh key={point.id} position={sceneDirection(point.center).add(origin)} raycast={ignoreRaycast} renderOrder={3}>
<sphereGeometry args={[4, 12, 8]}/>

View File

@ -1,23 +1,29 @@
'use client'
import { useState } from 'react'
import { Fragment, useState } from 'react'
import Button from '@/components/ui/Button'
import { readSeamRowSpacing } from '@/lib/reference-estimator/standard/hardware-seam-rows'
import { CabinetHardwareHoleDetails } from './CabinetHardwareHoleDetails'
import { CabinetSeamRowEditor, mm, seamEdges } from './CabinetSeamRowEditor'
import { seamOffset, type CabinetSeam } from './cabinet-sg0164-seam'
import { CabinetSeamRowEditor, mm } from './CabinetSeamRowEditor'
import { seamEdges, seamOffset, type CabinetSeam } from './cabinet-sg0164-seam'
import type { CabinetHardwareEdits } from './useCabinetHardwareEdits'
import styles from './cabinet-hardware-placement-controls.module.css'
export function CabinetHardwareSeamPanel({ editor, surfaceSelection }: { editor: CabinetHardwareEdits; surfaceSelection?: boolean }) {
const { seam, seamPicking } = editor
const [adding, setAdding] = useState(false)
const targets = seamPicking.targets
const basis = targets.reduce<CabinetSeam | undefined>((shortest, item) =>
!shortest || item.length < shortest.length ? item : shortest, undefined)
const batch = seamPicking.available.length > 1
const preview = editor.pendingAddition?.preview
if (!seamPicking.picking) return null
return <section className={styles.selection} aria-label="板件接缝">
<div className={styles.selectionHeader}>
<strong>已选 {seamPicking.keys.length} 块板件</strong>
<div className={styles.actions}>
{seamPicking.keys.length > 0 && <Button type="button" size="small" variant="plain"
onClick={() => { editor.select([]); seamPicking.clear() }}>清空</Button>}
onClick={() => { setAdding(false); editor.select([]); seamPicking.clear() }}>清空</Button>}
<Button type="button" size="small" variant="plain" onClick={seamPicking.reset}>退出</Button>
</div>
</div>
@ -32,18 +38,49 @@ export function CabinetHardwareSeamPanel({ editor, surfaceSelection }: { editor:
: seamPicking.keys.length < 2 ? <p>在模型上继续点选,重复点选可取消</p>
: !seamPicking.available.length ? <p>所选板件之间没有可编辑的五金接缝</p>
: <div className={styles.seamList} role="group" aria-label="可编辑接缝">
{seamPicking.available.map(item => <button type="button" key={item.key} aria-pressed={item.key === seam?.key}
onClick={() => seamPicking.chooseSeam(item.key)}>{item.boards.map(board => board.label).join(' + ')}</button>)}
{seamPicking.available.map(item => <Fragment key={item.key}>
{batch && <label><input type="checkbox" checked={targets.includes(item)} disabled={editor.busy}
onChange={() => { editor.cancelAddition(); seamPicking.toggleTarget(item.key) }}/>{item.boards.map(board => board.label).join(' + ')}</label>}
<button type="button" aria-pressed={item.key === seam?.key} disabled={editor.busy}
onClick={() => { setAdding(false); editor.cancelAddition(); seamPicking.chooseSeam(item.key) }}>
{batch ? '查看排布:' + item.boards.map(board => board.label).join(' + ') : item.boards.map(board => board.label).join(' + ')}
</button>
</Fragment>)}
</div>}
{seam && <SeamDetails key={seam.key} seam={seam} editor={editor}/>}
{!surfaceSelection && batch && <div className={styles.actions}>
<Button size="small" variant="gray" disabled={editor.busy || !basis} aria-expanded={adding} onClick={() => {
editor.select([])
setAdding(!adding)
}}>{adding ? '收起排布' : `+ 给所选 ${targets.length} 条接缝新增五金`}</Button>
</div>}
{!surfaceSelection && batch && adding && basis && <CabinetSeamRowEditor key={basis.key} seam={basis} editor={editor}
batch={targets.length > 1}/>}
{preview && <div className={styles.seamEditor} aria-label="批量五金孔位预览">
{preview.map(({ seam, opposite, mounts, stagger }) => <details key={seam.key} open>
<summary>{(opposite ? [...new Set([...seam.boards, ...opposite.boards].map(board => board.label))]
: seam.boards.map(board => board.label)).join(' + ')} · {mounts.length} 处
{stagger ? ` · 已错开 ${Math.abs(stagger)} mm` : ''}</summary>
{mounts.map(({ point, hardware }, i) => <div key={point.key}>
<strong>{i + 1}. {hardware.code} · 距接缝起点 {mm(seamOffset(seam, point))} mm</strong>
<CabinetHardwareHoleDetails point={point} hardware={hardware}/>
</div>)}
</details>)}
<Button size="small" disabled={editor.busy} onClick={() => void editor.confirmBatch()}>
确认批量安装 {preview.reduce((sum, row) => sum + row.mounts.length, 0)} 处
</Button>
</div>}
{batch && editor.placementIssue && <p role="alert">{editor.placementIssue}</p>}
{batch && editor.status === 'error' && <p role="alert">保存失败,已保留上次结果。</p>}
{batch && editor.status === 'limit' && <p role="alert">已达到测算单的连接点修改上限。</p>}
{seam && !adding && <SeamDetails key={seam.key} seam={seam} editor={editor} allowAdd={!batch}/>}
</section>
}
function SeamDetails({ editor, seam }: { editor: CabinetHardwareEdits; seam: CabinetSeam }) {
function SeamDetails({ editor, seam, allowAdd }: { editor: CabinetHardwareEdits; seam: CabinetSeam; allowAdd: boolean }) {
const { edits, selection, rows, status, busy } = editor
const [form, setForm] = useState<string>()
const selected = rows.find(row => selection.length > 0 && row.points.every(point => selection.some(value => value.key === point.key)))
const editing = rows.find(row => row.id === form)
const editing = rows.find(row => row.points[0]?.key === form)
const adding = form === 'new' && !selected && status !== 'added'
const [firstEdge, lastEdge] = seamEdges[seam.axis]
const hardware = selected && edits[selected.points[0].key]
@ -66,26 +103,26 @@ function SeamDetails({ editor, seam }: { editor: CabinetHardwareEdits; seam: Cab
<CabinetHardwareHoleDetails point={selected.points[0]} hardware={hardware} depthChoices={editor.depthChoices}
onConfirmDepth={depth => void editor.confirmDepth(depth)} busy={busy}/>
<div className={styles.actions}>
{hardware?.machining && <Button type="button" size="small" variant="gray" disabled={busy}
{hardware?.machining && !hardware.throughDowel && <Button type="button" size="small" variant="gray" disabled={busy}
onClick={() => void editor.reverse()}>反向安装</Button>}
<Button type="button" size="small" variant="gray" disabled={busy}
onClick={() => setForm(selected.id)}>{selected.saved ? '编辑排布' : '整理排布'}</Button>
onClick={() => setForm(selected.points[0].key)}>{selected.saved ? '编辑排布' : '整理排布'}</Button>
<Button type="button" size="small" variant="plain" disabled={busy} onClick={() => void editor.remove()}>
{selected.points.length === 1 ? '移除点位' : '移除所选'}
</Button>
</div>
</div>}
<div className={styles.actions}>
<Button type="button" size="small" variant="plain" aria-expanded={adding} disabled={busy}
{allowAdd && <Button type="button" size="small" variant="plain" aria-expanded={adding} disabled={busy || !editor.seamPicking.targets.length}
onClick={() => {
editor.select([])
setForm(adding ? undefined : 'new')
}}>{adding ? '收起排布' : '+ 新增一批'}</Button>
}}>{adding ? '收起排布' : '+ 新增一批'}</Button>}
<span role="status">{status === 'saving' ? '正在保存…' : status === 'saved' || status === 'added' ? '已保存'
: status === 'error' ? '保存失败,已保留上次结果' : status === 'limit' ? '已达到测算单的连接点修改上限' : ''}</span>
</div>
{editor.placementIssue && <p role="alert">{editor.placementIssue}</p>}
{adding && <CabinetSeamRowEditor seam={seam} editor={editor} onDone={() => setForm(undefined)}/>}
{editing && <CabinetSeamRowEditor key={editing.id} seam={seam} editor={editor} row={editing} onDone={() => setForm(undefined)}/>}
{adding && <CabinetSeamRowEditor seam={seam} editor={editor}/>}
{editing && <CabinetSeamRowEditor key={form} seam={seam} editor={editor} row={editing} onClose={() => setForm(undefined)}/>}
</>
}

View File

@ -1,41 +1,94 @@
'use client'
import Button from '@/components/ui/Button'
import { useState } from 'react'
import { CabinetHardwareHoleDetails } from './CabinetHardwareHoleDetails'
import { CabinetSeamRowEditor, mm } from './CabinetSeamRowEditor'
import { seamEdges, seamOffset } from './cabinet-sg0164-seam'
import { sg0164CabinetSeams } from '@/lib/reference-estimator/standard/cabinet-sg0164-seam'
import { readSeamRowSpacing } from '@/lib/reference-estimator/standard/hardware-seam-rows'
import type { CabinetHardwareEdits } from './useCabinetHardwareEdits'
import styles from './cabinet-hardware-placement-controls.module.css'
import { cabinetPartLabel } from '@/lib/reference-estimator/standard/cabinet-part-labels'
export function CabinetHardwareSelection({ editor }: { editor: CabinetHardwareEdits }) {
function boardName({ part, start }: CabinetHardwareEdits['selection'][number]['receiver']) {
const label = cabinetPartLabel(part, part.positions.indexOf(start))
return `${label.code} ${label.name}`
}
function SelectedHardwareHoles({ editor }: { editor: CabinetHardwareEdits }) {
const [expanded, setExpanded] = useState(false)
const { selection, edits } = editor
const pending = selection.some(point => edits[point.key]?.machiningPending)
return <details className={styles.holeDetails} onToggle={event => setExpanded(event.currentTarget.open)}>
<summary>孔位详情{pending ? ' · 有孔位待确认' : ''}</summary>
{expanded && selection.map((point, i) => {
const hardware = edits[point.key]
const short = [hardware?.code, hardware?.name].filter(Boolean).join(' · ')
return <div className={styles.seamEditor} key={point.key}>
{selection.length > 1 && <strong>{i + 1}. {short} · {boardName(point.donor)} / {boardName(point.receiver)}</strong>}
<CabinetHardwareHoleDetails point={point} hardware={hardware} depthChoices={i === 0 ? editor.depthChoices : undefined}
onConfirmDepth={i === 0 ? depth => void editor.confirmDepth(depth) : undefined} busy={editor.busy}/>
</div>
})}
</details>
}
function SelectedHardwarePoints({ editor }: { editor: CabinetHardwareEdits }) {
return <details>
<summary>所选点位 · 可单独取消</summary>
{sg0164CabinetSeams(editor.selection).map(seam => <div key={seam.key} className={styles.seamEditor}>
<p>{seam.boards.map(board => board.label).join(' + ')}</p>
<div className={styles.pointChoices}>
{seam.defaults.map(point => {
const label = `${editor.edits[point.key]?.code ?? '五金'} · 距${seamEdges[seam.axis][0]} ${mm(seamOffset(seam, point))} mm`
return <button type="button" key={point.key} disabled={editor.busy} title={'取消选中 ' + label}
aria-label={'取消选中 ' + label} onClick={() => editor.select(editor.selection.filter(item => item.key !== point.key))}>
<span>{label}</span><span aria-hidden="true">×</span>
</button>
})}
</div>
</div>)}
</details>
}
export function CabinetHardwareSelection({ editor, combinedRemoval = false }: { editor: CabinetHardwareEdits; combinedRemoval?: boolean }) {
const { selection, edits, status } = editor
const [editing, setEditing] = useState<{ seam: string; revision: number }>()
if (!selection.length) return null
const entries = selection.map(point => edits[point.key])
const allRemoved = entries.every(item => item === null)
const item = entries[0]
const oneReplacement = item && entries.every(entry => entry?.id === item.id)
? [item.name, item.code, item.spec].filter(Boolean).join(' · ') : undefined
const boardName = (board: (typeof selection)[number]['receiver']) => {
const { part, start } = board
const label = cabinetPartLabel(part,part.positions.indexOf(start))
return `${label.code} ${label.name}`
}
return <section className={styles.selection} aria-label="所选五金">
<div className={styles.selectionHeader}>
<strong>已选 {selection.length} 处</strong>
<Button type="button" size="small" variant="plain" onClick={() => editor.select([])}>清除选择</Button>
<Button type="button" size="small" variant="plain" disabled={editor.busy} onClick={() => editor.select([])}>清除选择</Button>
</div>
{selection.length === 1 && <p>{boardName(selection[0].donor)} · {boardName(selection[0].receiver)}</p>}
<p>{allRemoved ? '已移除' : oneReplacement ?? `${entries.filter(entry => entry != null).length} 处五金`}</p>
{(selection.length === 1 || editor.depthChoices.length > 0) &&
<CabinetHardwareHoleDetails point={selection[0]} hardware={item} depthChoices={editor.depthChoices}
onConfirmDepth={depth => void editor.confirmDepth(depth)} busy={editor.busy}/>}
<SelectedHardwarePoints editor={editor}/>
{entries.some(Boolean) && <SelectedHardwareHoles key={JSON.stringify(selection.map(point => point.key))} editor={editor}/>}
{editor.selectedRows.map(({ seam, row }) => {
const active = editing?.seam === seam.key && editing.revision === editor.selectionRevision
const { gaps } = readSeamRowSpacing(row.points.map(point => seamOffset(seam, point)))
return <div key={seam.key} className={styles.seamEditor} data-editing={active}>
<p>{seam.boards.map(board => board.label).join(' + ')} · {row.points.length} 个
{gaps.length > 0 && ` · 当前中心距 ${gaps.map(mm).join(' / ')} mm`}</p>
{active ? <CabinetSeamRowEditor key={editor.selectionRevision} seam={seam} editor={editor} row={row} onClose={() => setEditing(undefined)}/>
: <Button size="small" variant="gray" disabled={editor.busy}
onClick={() => setEditing({ seam: seam.key, revision: editor.selectionRevision })}>调整数量、前后位置和中心距</Button>}
</div>
})}
{editor.placementIssue && <p role="alert">{editor.placementIssue}</p>}
<div className={styles.actions}>
{!allRemoved && <Button type="button" size="small" variant="gray" onClick={() => void editor.remove()}>移除所选</Button>}
{entries.every(entry => entry?.machining) && <Button type="button" size="small" variant="gray" disabled={editor.busy}
{!allRemoved && !combinedRemoval && <Button type="button" size="small" variant="gray" disabled={editor.busy}
onClick={() => void editor.remove()}>移除所选</Button>}
{entries.every(entry => entry?.machining && !entry.throughDowel) && <Button type="button" size="small" variant="gray" disabled={editor.busy}
onClick={() => void editor.reverse()}>反向安装</Button>}
<span role="status">{status === 'saving' ? '正在保存…' : status === 'saved' ? '已自动保存'
: status === 'error' ? '保存失败,已保留上次结果' : '在下方点选配件替换'}</span>
<span role="status">{status === 'saving' ? '正在保存…' : status === 'saved' || status === 'added' ? '已自动保存'
: status === 'error' ? '保存失败,已保留上次结果' : status === 'limit' ? '已达到测算单的连接点修改上限' : '在下方点选配件替换'}</span>
</div>
</section>
}

View File

@ -0,0 +1,50 @@
'use client'
import { useEffect, useMemo } from 'react'
import { Edges, Html } from '@react-three/drei'
import * as THREE from 'three'
import type { CabinetInput, CabinetPart, CabinetPreviewPart } from '@/lib/reference-estimator/standard/cabinet-contracts'
import type { ModelFinish } from '@/lib/reference-estimator/standard/model-appearance'
import { cabinetPartLabel } from '@/lib/reference-estimator/standard/cabinet-part-labels'
import { partGeometry } from './cabinet-part-geometry'
import { CabinetExplodedBoardHoles } from './CabinetExplodedBoardHoles'
import type { BoardBore } from './cabinet-exploded-holes'
import { finishTextureAspect } from './cabinet-finish-textures'
import { applyModelFinishUv } from './cabinet-finish-uv'
import styles from './workflow.module.css'
export type ViewPart=CabinetPart | CabinetPreviewPart
function partColor(part: CabinetPart) {
const finish = part.color.trim()
if (/黑|深灰/.test(finish) && !/黑胡桃/.test(finish)) return '#373431'
if (/胡桃|木纹|柚木/.test(finish)) return '#755038'
if (/^(原木色|自然木色|橡胶木原色)$/.test(finish)) return '#a77b54'
return '#e5e1d5'
}
export const boardSelectionOverlay = 'board-selection-overlay'
export function CabinetModelPiece({part,positionIndex,input,position,labels,orientation,selected,onPick,translucent,bores,visible=true,finish,map}:{part:ViewPart;positionIndex:number;input:CabinetInput;position:[number,number,number];labels:boolean;orientation:THREE.Quaternion;selected?:boolean;onPick?:()=>void;translucent?:boolean;bores?:BoardBore[];visible?:boolean;finish?:ModelFinish;map?:THREE.Texture|null}){
const baseGeometry = useMemo(() => partGeometry(part, input), [part, input])
const textureFinish = map ? finish : undefined
const aspect = finishTextureAspect(map)
const geometry = useMemo(() => textureFinish
? applyModelFinishUv(baseGeometry.clone(), textureFinish, aspect) : baseGeometry, [baseGeometry, textureFinish, aspect])
const color = finish?.color ?? partColor(part)
useEffect(() => () => baseGeometry.dispose(), [baseGeometry])
useEffect(() => () => { if (geometry !== baseGeometry) geometry.dispose() }, [baseGeometry, geometry])
const label = cabinetPartLabel(part,positionIndex)
return <mesh name={`${label.code} ${label.name}`} geometry={geometry} position={position} quaternion={orientation}
visible={visible} renderOrder={translucent ? 1 : 0}
onClick={visible && onPick ? event => { if (event.delta <= 5) { event.stopPropagation(); onPick() } } : undefined}>
{translucent
? <meshBasicMaterial color={part.role === 'top' ? '#c2a48b' : '#aebfd0'}
transparent opacity={part.role === 'back' ? .032 : part.role === 'top' ? .078 : .062} depthWrite={false}/>
: bores?.length ? <CabinetExplodedBoardHoles bores={bores} color={color} map={map}/>
: <meshStandardMaterial key={map?.uuid ?? 'solid'} color={map ? '#ffffff' : color} map={map ?? null} roughness={.84}/>}
<Edges threshold={25} color={translucent ? '#99abb9' : '#655f56'}/>
{selected && <mesh name={boardSelectionOverlay} geometry={geometry} raycast={() => null}>
<meshBasicMaterial color="#2563eb" transparent opacity={translucent ? .22 : .55}
depthWrite={false} polygonOffset polygonOffsetFactor={-2} polygonOffsetUnits={-2}/>
</mesh>}
{labels&&<Html center distanceFactor={1500} zIndexRange={[10, 0]}><span className={styles.partTag}>{label.code}</span></Html>}
</mesh>
}

View File

@ -2,17 +2,16 @@
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import { Canvas, useThree } from '@react-three/fiber'
import { OrbitControls, Edges, Html } from '@react-three/drei'
import { OrbitControls } from '@react-three/drei'
import type { OrbitControls as OrbitControlsImpl } from 'three-stdlib'
import { Box, Link2, Maximize, Ruler } from 'lucide-react'
import * as THREE from 'three'
import { GLTFExporter } from 'three/examples/jsm/exporters/GLTFExporter.js'
import type { CabinetInput, CabinetModel, CabinetPart, CabinetPreviewPart } from '@/lib/reference-estimator/standard/cabinet-contracts'
import { resolveModelFinish, type ModelAppearance, type ModelFinish } from '@/lib/reference-estimator/standard/model-appearance'
import type { CabinetModel, CabinetPart } from '@/lib/reference-estimator/standard/cabinet-contracts'
import { resolveModelFinish, type ModelAppearance } from '@/lib/reference-estimator/standard/model-appearance'
import { cabinetExplodedPosition } from '@/lib/reference-estimator/standard/cabinet-explode'
import { cabinetPartLabel } from '@/lib/reference-estimator/standard/cabinet-part-labels'
import { CabinetModelPiece as Piece, boardSelectionOverlay, type ViewPart } from './CabinetModelPiece'
import { cabinetHardwareBoard } from '@/lib/reference-estimator/standard/hardware-board-connections'
import { profileAxes } from '@/lib/reference-estimator/standard/cabinet-image-contract'
import { partGeometry } from './cabinet-part-geometry'
import { motionCollision, motionPose, movableJoints } from '@/lib/reference-estimator/standard/cad-assembly'
import Button from '@/components/ui/Button'
@ -30,53 +29,22 @@ import { CabinetHardwareBoxSelect, CabinetHardwareProjector, type ProjectPoint }
import type { CabinetHardwareEdits } from './useCabinetHardwareEdits'
import { CabinetHardwareSeamLayer } from './CabinetHardwareSeamLayer'
import { CabinetExplodedHardware } from './CabinetExplodedHardware'
import { CabinetExplodedBoardHoles, previewBoreInteriors } from './CabinetExplodedBoardHoles'
import { groupCabinetBores, type BoardBore } from './cabinet-exploded-holes'
import { previewBoreInteriors } from './CabinetExplodedBoardHoles'
import { groupCabinetBores } from './cabinet-exploded-holes'
import { isSeamPlacement } from './cabinet-sg0164-seam'
import { finishTextureAspect, useCabinetFinishTextures } from './cabinet-finish-textures'
import { useCabinetFinishTextures } from './cabinet-finish-textures'
import { applyModelFinishUv } from './cabinet-finish-uv'
import type { SurfaceHardware } from '@/lib/reference-estimator/standard/surface-hardware'
import { isCornerGuardLocation } from '@/lib/reference-estimator/standard/cabinet-corner-guard'
import { useSurfaceHardwareModels } from './useSurfaceHardwareModels'
import { CabinetSurfaceHardware } from './CabinetSurfaceHardware'
import { CabinetCornerGuardLayer } from './CabinetCornerGuardLayer'
import { useCornerGuardModels, type CornerGuardModels } from './useCornerGuardModels'
import { cabinetSurfaceBoxTargets, cabinetSurfacePositions, type CabinetSurfaceSelectionState, type HardwareBoxTarget } from './cabinet-surface-selection'
import type { SelectableHardware } from './CabinetHardwareBoxSelect'
const noSurfaceHardware: SurfaceHardware = []
type ViewPart=CabinetPart | CabinetPreviewPart
function partColor(part: CabinetPart) {
const finish = part.color.trim()
if (/黑|深灰/.test(finish) && !/黑胡桃/.test(finish)) return '#373431'
if (/胡桃|木纹|柚木/.test(finish)) return '#755038'
if (/^(原木色|自然木色|橡胶木原色)$/.test(finish)) return '#a77b54'
return '#e5e1d5'
}
const boardSelectionOverlay = 'board-selection-overlay'
function Piece({part,positionIndex,input,position,labels,orientation,selected,onPick,translucent,bores,visible=true,finish,map}:{part:ViewPart;positionIndex:number;input:CabinetInput;position:[number,number,number];labels:boolean;orientation:THREE.Quaternion;selected?:boolean;onPick?:()=>void;translucent?:boolean;bores?:BoardBore[];visible?:boolean;finish?:ModelFinish;map?:THREE.Texture|null}){
const baseGeometry = useMemo(() => partGeometry(part, input), [part, input])
const textureFinish = map ? finish : undefined
const aspect = finishTextureAspect(map)
const geometry = useMemo(() => textureFinish
? applyModelFinishUv(baseGeometry.clone(), textureFinish, aspect) : baseGeometry, [baseGeometry, textureFinish, aspect])
const color = finish?.color ?? partColor(part)
useEffect(() => () => baseGeometry.dispose(), [baseGeometry])
useEffect(() => () => { if (geometry !== baseGeometry) geometry.dispose() }, [baseGeometry, geometry])
const label = cabinetPartLabel(part,positionIndex)
return <mesh name={`${label.code} ${label.name}`} geometry={geometry} position={position} quaternion={orientation}
visible={visible} renderOrder={translucent ? 1 : 0}
onClick={visible && onPick ? event => { if (event.delta <= 5) { event.stopPropagation(); onPick() } } : undefined}>
{translucent
? <meshBasicMaterial color={part.role === 'top' ? '#c2a48b' : '#aebfd0'}
transparent opacity={part.role === 'back' ? .032 : part.role === 'top' ? .078 : .062} depthWrite={false}/>
: bores?.length ? <CabinetExplodedBoardHoles bores={bores} color={color} map={map}/>
: <meshStandardMaterial key={map?.uuid ?? 'solid'} color={map ? '#ffffff' : color} map={map ?? null} roughness={.84}/>}
<Edges threshold={25} color={translucent ? '#99abb9' : '#655f56'}/>
{selected && <mesh name={boardSelectionOverlay} geometry={geometry} raycast={() => null}>
<meshBasicMaterial color="#2563eb" transparent opacity={translucent ? .22 : .55}
depthWrite={false} polygonOffset polygonOffsetFactor={-2} polygonOffsetUnits={-2}/>
</mesh>}
{labels&&<Html center distanceFactor={1500} zIndexRange={[10, 0]}><span className={styles.partTag}>{label.code}</span></Html>}
</mesh>
}
type View = 'iso'|'front'|'rear'
const previewFraming = {
all: { target: [0, 0, 0], direction: [.68, .32, 1], zoom: 0 },
@ -144,7 +112,7 @@ function ModelFrame({model,distance,position,preset,controls,showDimensions,prev
return null
}
export default function CabinetModelView({model,readOnly=false,showDimensions,onDimensionsChange,stepExport,boardPicking,onToggleBoardPicking,previewLibrary,hardwareEditor,appearance,surfaceHardware=noSurfaceHardware}:{
export default function CabinetModelView({model,readOnly=false,showDimensions,onDimensionsChange,stepExport,boardPicking,onToggleBoardPicking,previewLibrary,hardwareEditor,hardwareSnapshot,appearance,surfaceHardware=noSurfaceHardware,cornerGuardPreview,cornerGuardModels,surfaceSelection}:{
model: CabinetModel
appearance?: ModelAppearance
readOnly?: boolean
@ -155,7 +123,11 @@ export default function CabinetModelView({model,readOnly=false,showDimensions,on
onToggleBoardPicking?: () => void
previewLibrary?: EstimateHardwareLibraryState
hardwareEditor?: CabinetHardwareEdits
hardwareSnapshot?: Pick<CabinetHardwareEdits, 'edits' | 'plan'>
surfaceHardware?: SurfaceHardware
cornerGuardPreview?: SurfaceHardware
cornerGuardModels?: CornerGuardModels
surfaceSelection?: CabinetSurfaceSelectionState
}){
const [labels,setLabels]=useState(false),[explode,setExplode]=useState(0),group=useRef<THREE.Group>(null)
const finishTextures = useCabinetFinishTextures(model, appearance)
@ -164,15 +136,19 @@ export default function CabinetModelView({model,readOnly=false,showDimensions,on
const [opening,setOpening]=useState(0)
const [preset,setPreset]=useState<{view:View;token:number}>({view:'iso',token:0})
const controls=useRef<OrbitControlsImpl>(null)
const hardwarePreview=useCabinetHardwarePreview(previewLibrary, hardwareEditor?.edits, hardwareEditor?.plan)
const surfaceModels = useSurfaceHardwareModels(surfaceHardware, previewLibrary)
const hardwarePreview=useCabinetHardwarePreview(previewLibrary, (hardwareEditor ?? hardwareSnapshot)?.edits, (hardwareEditor ?? hardwareSnapshot)?.plan)
const backClips = useMemo(() => surfaceHardware.filter(row => !isCornerGuardLocation(row.location)), [surfaceHardware])
const surfaceModels = useSurfaceHardwareModels(backClips, previewLibrary)
const historicalCornerModels = useCornerGuardModels(cornerGuardModels ? noSurfaceHardware : surfaceHardware, previewLibrary)
const guardModels = cornerGuardModels ?? historicalCornerModels
const showExplodedHardware = explode > 0 && !hardwarePreview.active && hardwarePreview.installed.length > 0
const { installed, edits } = hardwarePreview
const boresByBoard = useMemo(() => groupCabinetBores(installed, edits), [installed, edits])
const [boxing, setBoxing] = useState(false)
const projector = useRef<ProjectPoint | null>(null)
const previewArea=hardwarePreview.active ? hardwarePreview.area : undefined
const scopeBoards = useMemo(() => new Set(hardwarePreview.filtered.flatMap(point => [point.donor.start, point.receiver.start])),
const scopeBoards = useMemo(() => new Set(hardwarePreview.filtered.flatMap(point =>
[point.donor.start, point.receiver.start, point.oppositeDowelPoint?.receiver.start])),
[hardwarePreview.filtered])
const chooseView=(view:View)=>setPreset(state=>({view,token:state.token+1}))
const p=model.input,W=p.width!,D=p.depth!,H=p.height!,distance=Math.max(W,H,D)*1.65
@ -181,12 +157,40 @@ export default function CabinetModelView({model,readOnly=false,showDimensions,on
const seam = hardwareEditor?.seam
const seamPicking = hardwareEditor?.seamPicking
const pickingSeam = hardwarePreview.active && seamPicking?.picking
const editingSeam = pickingSeam ? seam : undefined
const editingSeams = pickingSeam ? [...new Set([...(seamPicking?.targets ?? []), ...(seam ? [seam] : [])])] : []
const rowPreview = !pickingSeam ? seamPicking?.previewOffsets[0] : undefined
const rowSeam = rowPreview ? hardwareEditor?.selectedRows.find(row => row.seam.key === rowPreview[0])?.seam : undefined
const batchMounts = hardwareEditor?.pendingAddition?.preview?.flatMap(row => row.mounts)
const activeBoardPicking = pickingSeam ? seamPicking : boardPicking
const pickingBoardMeshes = activeBoardPicking?.picking
const pickHardware = hardwareEditor && !pickingSeam
? (point: (typeof hardwarePoints)[number]['point']) => hardwareEditor.select([point]) : undefined
? (point: (typeof hardwarePoints)[number]['point']) => {
if (hardwareEditor.busy) return
surfaceSelection?.select([])
hardwareEditor.select(selectedHardware.has(point.key)
? hardwareEditor.selection.filter(item => item.key !== point.key) : [point])
} : undefined
const position=useMemo(()=>cabinetExplodedPosition(model,explode),[model,explode])
const visibleGuards = cornerGuardPreview ?? surfaceHardware
const surfaceRows = useMemo(() => cabinetSurfacePositions(model, backClips, visibleGuards, position),
[model, backClips, visibleGuards, position])
const surfacePickable = surfaceSelection && !pickingBoardMeshes && !cornerGuardPreview
const boxTargets: SelectableHardware<HardwareBoxTarget>[] = boxing ? [
...hardwarePoints.map(({ point, position }) => ({ point: { kind: 'connection' as const, point }, position })),
...(surfacePickable ? cabinetSurfaceBoxTargets(surfaceRows, surfaceModels.models, guardModels.models) : []),
] : []
const canBox = !pickingBoardMeshes && !cornerGuardPreview && Boolean(
hardwareEditor && hardwarePoints.length || surfacePickable && (surfaceModels.models || guardModels.models))
function pickSurface(key: string) {
if (!surfaceSelection || surfaceSelection.busy) return
hardwareEditor?.select([])
surfaceSelection.select(surfaceSelection.keys.has(key) ? [] : [key])
}
function applyBox(targets: HardwareBoxTarget[]) {
if (hardwareEditor?.busy || surfaceSelection?.busy) return
hardwareEditor?.select(targets.flatMap(target => target.kind === 'connection' ? [target.point] : []))
surfaceSelection?.select(targets.flatMap(target => target.kind === 'surface' ? [target.key] : []))
}
const instances=useMemo(()=>[...model.parts,...model.previewParts??[]].flatMap(part=>
part.positions.map((pos,i)=>({part,pos,index:i,key:part.id+'-'+i,
boardKey: 'previewKind' in part ? undefined : cabinetHardwareBoard(part,pos,i).key}))),[model])
@ -227,6 +231,7 @@ export default function CabinetModelView({model,readOnly=false,showDimensions,on
const dimensionsVisible = Boolean(showDimensions && hasDimensions && !hardwarePreview.active)
const togglePreview = () => {
setBoxing(false)
surfaceSelection?.select([])
seamPicking?.reset()
if (hardwarePreview.active) hardwareEditor?.select([])
if (!hardwarePreview.active) {
@ -240,6 +245,7 @@ export default function CabinetModelView({model,readOnly=false,showDimensions,on
function toggleSeamPicking() {
if (!seamPicking) return
setBoxing(false)
surfaceSelection?.select([])
if (seamPicking.picking) {
seamPicking.reset()
return
@ -259,6 +265,8 @@ export default function CabinetModelView({model,readOnly=false,showDimensions,on
const explodeControl = <label className={workbench.explodeControl}>展开
<input aria-label="模型展开" type="range" min="0" max="1" step=".01" value={explode} onChange={e=>setExplode(Number(e.target.value))}/>
</label>
const boxActive = boxing && canBox
const toggleBox = () => setBoxing(!boxActive)
const glbDownload = <Button type="button" size="small" variant="gray" disabled={finishTextures.loading}
onClick={() => { setGlbError(''); void download().catch(() => setGlbError('GLB 下载失败,请重试。')) }}>
{onDimensionsChange ? '下载 GLB 模型' : '下载GLB模型'}
@ -273,6 +281,8 @@ export default function CabinetModelView({model,readOnly=false,showDimensions,on
disabled={!hasDimensions || hardwarePreview.active} onClick={()=>onDimensionsChange(!showDimensions)}><Ruler size={15} aria-hidden="true"/>尺寸</button>
{previewLibrary && <button type="button" className={workbench.dimensionToggle} aria-pressed={hardwarePreview.active}
onClick={togglePreview}><Box size={15} aria-hidden="true"/>五金预览</button>}
{!hardwarePreview.active && canBox && <button type="button" className={workbench.dimensionToggle}
aria-pressed={boxActive} onClick={toggleBox}>框选</button>}
{onToggleBoardPicking && <button type="button" className={workbench.dimensionToggle} aria-pressed={boardPicking?.picking ?? false}
onClick={()=>{if(hardwarePreview.active)hardwarePreview.toggle();onToggleBoardPicking()}}><Link2 size={15} aria-hidden="true"/>连接五金</button>}
{fit}
@ -291,7 +301,10 @@ export default function CabinetModelView({model,readOnly=false,showDimensions,on
{surfaceModels.loading && <p className={styles.empty} role="status">正在加载背板扣模型…</p>}
{surfaceModels.error && <p className={styles.empty} role="alert">{surfaceModels.error}
<Button type="button" size="small" variant="plain" onClick={surfaceModels.retry}>重试</Button></p>}
{hardwarePreview.active && <CabinetHardwarePreviewControls preview={hardwarePreview} boxing={boxing}
{guardModels.loading && <p className={styles.empty} role="status">正在加载 QT-01 原模型…</p>}
{guardModels.error && <p className={styles.empty} role="alert">{guardModels.error}
<Button type="button" size="small" variant="plain" onClick={guardModels.retry}>重试护角模型</Button></p>}
{hardwarePreview.active && <CabinetHardwarePreviewControls preview={hardwarePreview} boxing={boxActive}
onAreaChange={area => {
setBoxing(false)
seamPicking?.reset()
@ -299,7 +312,7 @@ export default function CabinetModelView({model,readOnly=false,showDimensions,on
hardwarePreview.setArea(area)
}}
pickingBoards={pickingSeam} onPickBoards={seamPicking?.boards.length ? toggleSeamPicking : undefined}
onBox={hardwareEditor && hardwarePoints.length && !pickingSeam ? () => setBoxing(!boxing) : undefined}/>}
onBox={canBox ? toggleBox : undefined}/>}
{joints.length>0&&!hardwarePreview.active&&<div className={styles.modelTools}>
<label>活动部件 <select aria-label="活动部件" value={selected?.joint.key??''} onChange={event=>{setJointKey(event.target.value);setOpening(0)}}>
{joints.map(item=><option key={item.joint.key} value={item.joint.key}>{item.moving.name}</option>)}
@ -307,8 +320,12 @@ export default function CabinetModelView({model,readOnly=false,showDimensions,on
<label>开启 <input aria-label="开启活动部件" type="range" min="0" max="1" step=".02" value={opening} onChange={event=>{setExplode(0);setOpening(Number(event.target.value))}} /></label>
{collision&&<span role="status">{collision}</span>}
</div>}
<div className={workspace.modelCanvas} aria-label="柜体三维模型" style={boxing ? { position: 'relative' } : undefined}><Canvas frameloop="demand"
onPointerMissed={hardwarePreview.active && hardwareEditor ? () => hardwareEditor.select([]) : undefined}
<div className={workspace.modelCanvas} aria-label="柜体三维模型" style={boxActive ? { position: 'relative' } : undefined}><Canvas frameloop="demand"
onPointerMissed={() => {
if (hardwareEditor?.busy || surfaceSelection?.busy) return
if (hardwarePreview.active) hardwareEditor?.select([])
if (surfaceSelection?.keys.size) surfaceSelection.select([])
}}
style={pickingBoardMeshes ? {cursor:'crosshair'} : undefined} camera={{position:[distance,distance*.6,distance],near:1,far:30000,fov:40}} gl={{preserveDrawingBuffer:true}}><color attach="background" args={['#f4f6f6']}/><ambientLight intensity={1.7}/><directionalLight position={[1000,2000,1500]} intensity={2}/><ModelFrame model={model} distance={distance} position={position} preset={preset} controls={controls} showDimensions={dimensionsVisible} previewArea={previewArea}/><group ref={group} userData={{ruleVersion:model.version,source:model.source,issues:model.issues}}>
{instances.map(({part,pos,key,boardKey,index})=>{
const pose=posePosition(part,pos)
@ -320,7 +337,10 @@ export default function CabinetModelView({model,readOnly=false,showDimensions,on
selected={boardKey ? activeBoardPicking?.keys.includes(boardKey) : false}
onPick={boardKey && pickingBoardMeshes ? () => activeBoardPicking.pick(boardKey) : undefined}/>
})}</group>
<CabinetSurfaceHardware model={model} placements={surfaceHardware} models={surfaceModels.models} boardPosition={position}/>
<CabinetSurfaceHardware rows={surfaceRows.clips} models={surfaceModels.models}
selected={surfaceSelection?.keys} onPick={surfacePickable ? pickSurface : undefined}/>
<CabinetCornerGuardLayer rows={surfaceRows.guards} preview={Boolean(cornerGuardPreview)} models={guardModels.models}
selected={surfaceSelection?.keys} onPick={surfacePickable ? pickSurface : undefined}/>
{hardwarePreview.active
? <CabinetHardwarePreviewLayer preview={hardwarePreview}
points={hardwarePoints} size={[W,D,H]} selected={selectedHardware} onPick={pickHardware}/>
@ -329,15 +349,22 @@ export default function CabinetModelView({model,readOnly=false,showDimensions,on
dowels={hardwarePreview.dowels} models={hardwarePreview.machiningModels} size={[W,D,H]}
amount={explode} boardPosition={position}/>
: <CabinetExposedCamLayer preview={hardwarePreview} size={[W,D,H]} boardPosition={position}/>}
{editingSeam && <CabinetHardwareSeamLayer seam={editingSeam} size={[W,D,H]} selected={selectedHardware}
previewOffsets={seamPicking?.previewOffsets ?? []}
points={hardwarePreview.installed.filter(point => isSeamPlacement(editingSeam, point))}
edits={hardwarePreview.edits}/>}
{hardwarePreview.active && hardwareEditor && <CabinetHardwareProjector projectRef={projector}/>}
{editingSeams.map(editingSeam => <CabinetHardwareSeamLayer key={editingSeam.key} seam={editingSeam}
size={[W,D,H]} selected={selectedHardware}
previewOffsets={batchMounts ? [] : seamPicking?.previewOffsets.find(([key]) => key === editingSeam.key)?.[1]}
points={hardwarePreview.installed.filter(point => isSeamPlacement(editingSeam, point))} edits={edits}/>)}
{hardwarePreview.active && !pickingSeam && selectedHardware.size > 0 &&
<CabinetHardwareSeamLayer size={[W,D,H]} selected={selectedHardware} seam={rowSeam} showEdges
previewOffsets={rowPreview?.[1]}
points={hardwareEditor?.selection ?? []} edits={edits}/>}
{pickingSeam && batchMounts && <CabinetHardwareSeamLayer size={[W,D,H]}
selected={new Set(batchMounts.map(({point}) => point.key))} points={batchMounts.map(({point}) => point)}
edits={Object.fromEntries(batchMounts.map(({point, hardware}) => [point.key, hardware]))}/>}
{boxActive && <CabinetHardwareProjector projectRef={projector}/>}
{dimensionsVisible && <CabinetModelDimensions width={W} depth={D} height={H} rear={preset.view==='rear'}/>}
<OrbitControls ref={controls} makeDefault enableDamping minDistance={200} maxDistance={10000}/></Canvas>
{boxing && hardwareEditor && <CabinetHardwareBoxSelect project={projector} points={hardwarePoints}
onSelect={hardwareEditor.select} onCancel={() => setBoxing(false)}/>}
{boxActive && <CabinetHardwareBoxSelect project={projector} points={boxTargets}
onSelect={applyBox} onCancel={() => setBoxing(false)}/>}
</div>
</div>
}

View File

@ -5,36 +5,39 @@ import Button from '@/components/ui/Button'
import { maxSeamRowPoints, seamPitch, type SeamRowAlignment } from '@/lib/reference-estimator/standard/hardware-seam-edits'
import { layoutSeamRow, readSeamRowSpacing, seamRowPitchOptions, type SeamRowLayout } from '@/lib/reference-estimator/standard/hardware-seam-rows'
import type { CabinetSeamRow } from '@/lib/reference-estimator/standard/cabinet-seam-rows'
import { seamOffset, type CabinetSeam } from './cabinet-sg0164-seam'
import { seamEdges, seamOffset, type CabinetSeam } from './cabinet-sg0164-seam'
import type { CabinetHardwareEdits } from './useCabinetHardwareEdits'
import styles from './cabinet-hardware-placement-controls.module.css'
export const mm = (value: number) => String(Number(value.toFixed(2)))
export const seamEdges = [['左边', '右边'], ['前沿', '后沿'], ['下沿', '上沿']] as const
export function CabinetSeamRowEditor({ seam, editor, row, onDone }: {
seam: CabinetSeam; editor: CabinetHardwareEdits; row?: CabinetSeamRow; onDone: () => void
export function CabinetSeamRowEditor({ seam, editor, row, onClose, batch = false }: {
seam: CabinetSeam; editor: CabinetHardwareEdits; row?: CabinetSeamRow; onClose?: () => void; batch?: boolean
}) {
const existing = row?.points.map(point => seamOffset(seam, point)) ?? []
const [count, setCount] = useState(existing.length || 1)
const [pitch, setPitch] = useState(readSeamRowSpacing(existing).pitch)
const [alignment, setAlignment] = useState<SeamRowAlignment>(row?.saved?.alignment ?? 'center')
const [alignment, setAlignment] = useState<SeamRowAlignment>(row?.saved?.alignment ?? (row ? 'front' : 'center'))
const [edge, setEdge] = useState<string>()
const [applied, setApplied] = useState<string>()
const [firstEdge, lastEdge] = seamEdges[seam.axis]
const choices = seamRowPitchOptions(seam.length, count)
const step = pitch !== undefined && choices.includes(pitch) ? pitch
: choices.find(value => editor.checkLayout({ count, pitch: value, alignment: 'center', edge: 0 }, row).length > 0)
: choices.find(value => editor.checkLayout({ count, pitch: value, alignment: 'center', edge: 0 }, row, seam).length > 0)
?? choices[0] ?? 0
const centeredEdge = (seam.length - (count - 1) * step) / 2
const edgeValue = edge ?? String(row?.saved?.alignment === alignment && alignment !== 'center'
const edgeValue = edge ?? String(row && (row.saved?.alignment ?? 'front') === alignment && alignment !== 'center'
? alignment === 'front' ? existing[0] : seam.length - existing[existing.length - 1] : centeredEdge)
const layout: SeamRowLayout = { count, pitch: step, alignment, edge: edgeValue.trim() ? Number(edgeValue) : NaN }
const layoutKey = JSON.stringify(layout)
const positions = layoutSeamRow(seam.length, layout)
const valid = editor.checkLayout(layout, row).length === count
const { setPreviewOffsets } = editor.seamPicking
const previewKey = JSON.stringify(valid ? positions : [])
const valid = editor.checkLayout(layout, row, seam).length === count
const { picking, setPreviewOffsets } = editor.seamPicking
const previewTargets = valid ? (batch ? editor.seamPicking.targets : [seam]).map(target =>
[target.key, layoutSeamRow(target.length, layout)]) : row && !picking ? [[seam.key, []]] : []
const previewKey = JSON.stringify(previewTargets)
useEffect(() => {
setPreviewOffsets(JSON.parse(previewKey) as number[])
setPreviewOffsets(JSON.parse(previewKey) as [string, number[]][])
return () => setPreviewOffsets([])
}, [previewKey, setPreviewOffsets])
const choosing = !row && Boolean(editor.pendingAddition)
@ -43,12 +46,11 @@ export function CabinetSeamRowEditor({ seam, editor, row, onDone }: {
const back = seam.length - positions[positions.length - 1]
return <div className={styles.seamEditor} aria-label={row ? '编辑批次排布' : '新增一批连接点'}>
<div className={styles.seamFields}>
{row ? <span className={styles.seamField}>数量<strong>{count} 个</strong></span>
: <label className={styles.seamField}>数量
<select value={count} disabled={disabled} onChange={event => setCount(Number(event.target.value))}>
{Array.from({ length: maxSeamRowPoints }, (_, i) => <option key={i + 1} value={i + 1}>{i + 1} 个</option>)}
</select>
</label>}
<label className={styles.seamField}>数量
<select value={count} disabled={disabled} onChange={event => setCount(Number(event.target.value))}>
{Array.from({ length: maxSeamRowPoints }, (_, i) => <option key={i + 1} value={i + 1}>{i + 1} 个</option>)}
</select>
</label>
<label className={styles.seamField}>对齐方式
<select value={alignment} disabled={disabled} onChange={event => {
const next = event.target.value as SeamRowAlignment
@ -79,15 +81,16 @@ export function CabinetSeamRowEditor({ seam, editor, row, onDone }: {
{!valid && <p role="status">此排布放不下或与其他点位过近,请调整间距或对齐位置。</p>}
<div className={styles.actions}>
{choosing ? <>
<span role="status">在下方配件库选用五金后保存本批</span>
<span role="status">{batch ? '在下方选用五金,预览各接缝孔位' : '在下方配件库选用五金后保存本批'}</span>
<Button type="button" size="small" variant="plain" disabled={editor.busy} onClick={editor.cancelAddition}>修改排布</Button>
</> : <>
<Button type="button" size="small" variant="gray" disabled={disabled || !valid}
onClick={async () => {
if (!row) editor.stageAddition(layout)
else if (await editor.updateRow(row.id, layout)) onDone()
else if (await editor.moveRow(seam, row, layout)) setApplied(layoutKey)
}}>{row ? '应用排布' : '选择五金'}</Button>
{row && <Button type="button" size="small" variant="plain" disabled={disabled} onClick={onDone}>取消</Button>}
{row && <Button type="button" size="small" variant="plain" disabled={disabled} onClick={onClose}>收起</Button>}
{row && applied === layoutKey && editor.status === 'saved' && <span role="status">已应用排布</span>}
</>}
</div>
</div>

View File

@ -1,32 +1,24 @@
import { useMemo } from 'react'
import type { CabinetModel } from '@/lib/reference-estimator/standard/cabinet-contracts'
import { resolveSurfaceHardware, surfaceHardwareKey, type SurfaceHardware } from '@/lib/reference-estimator/standard/surface-hardware'
import type { cabinetExplodedPosition } from '@/lib/reference-estimator/standard/cabinet-explode'
import type { SurfaceHardwareModel } from './useSurfaceHardwareModels'
import type { cabinetSurfacePositions } from './cabinet-surface-selection'
import { CabinetSurfacePickTarget } from './CabinetSurfacePickTarget'
export function CabinetSurfaceHardware({ model, placements, models, boardPosition }: {
model: CabinetModel
placements: SurfaceHardware
export function CabinetSurfaceHardware({ rows, models, selected, onPick }: {
rows: ReturnType<typeof cabinetSurfacePositions>['clips']
models?: Record<string, SurfaceHardwareModel>
boardPosition: ReturnType<typeof cabinetExplodedPosition>
selected?: ReadonlySet<string>; onPick?: (key: string) => void
}) {
const rows = useMemo(() => resolveSurfaceHardware(model, placements).flatMap(row => {
const instances = useMemo(() => rows.flatMap(row => {
const asset = models?.[row.accessoryId]
return asset ? [{ ...row, asset, scene: asset.scene.clone(true), screw: asset.screw?.scene.clone(true) }] : []
}), [model, placements, models])
const width = model.input.width ?? 0
const depth = model.input.depth ?? 0
const height = model.input.height ?? 0
}), [rows, models])
return <group name="背板扣安装位置">
{rows.map(row => {
const start = row.board.start
const current = boardPosition(row.board.part, start)
const [x, d, z] = row.position.map((value, axis) => value + current[axis] - start[axis])
{instances.map(row => {
const [ox, oy, oz] = row.asset.origin
return <group key={surfaceHardwareKey(row)} position={[x - width / 2, z - height / 2, depth / 2 - d]}
rotation={[0, 0, row.turn]}>
return <CabinetSurfacePickTarget key={row.key} position={row.scenePoint} selected={selected?.has(row.key)}
onPick={onPick ? () => onPick(row.key) : undefined}>
{/* 齿形底脚沿背板平面卡入板边,斜面与配套螺丝随扣件转向。 */}
<group rotation={[-Math.PI / 2, 0, 0]}>
<group rotation={[-Math.PI / 2, 0, row.turn, 'ZYX']}>
<group position={[-ox, -oy, -oz]}>
<primitive object={row.scene} scale={1000} dispose={null}/>
{row.asset.screw && row.screw && <group position={row.asset.screw.positionMm}
@ -37,7 +29,7 @@ export function CabinetSurfaceHardware({ model, placements, models, boardPositio
</group>}
</group>
</group>
</group>
</CabinetSurfacePickTarget>
})}
</group>
}

View File

@ -0,0 +1,37 @@
import { useEffect, useLayoutEffect, useMemo, useRef, type ReactNode } from 'react'
import { useThree } from '@react-three/fiber'
import { BoxHelper, Group } from 'three'
import type { MmPoint } from './cabinet-cam-preview'
function SelectionOutline({ target, position, children }: {
target: React.RefObject<Group | null>; position: MmPoint; children: ReactNode
}) {
const invalidate = useThree(state => state.invalidate)
const outline = useMemo(() => {
const helper = new BoxHelper(new Group(), '#2563eb')
helper.raycast = () => null
helper.material.depthTest = false
helper.renderOrder = 10
return helper
}, [])
useLayoutEffect(() => {
if (target.current) outline.setFromObject(target.current)
invalidate()
}, [target, position, children, outline, invalidate])
useEffect(() => () => outline.dispose(), [outline])
return <primitive object={outline} dispose={null}/>
}
export function CabinetSurfacePickTarget({ position, selected, onPick, children }: {
position: MmPoint; selected?: boolean; onPick?: () => void; children: ReactNode
}) {
const target = useRef<Group>(null)
return <>
<group ref={target} position={position} onClick={onPick ? event => {
if (event.delta > 5) return
event.stopPropagation()
onPick()
} : undefined}>{children}</group>
{selected && <SelectionOutline target={target} position={position}>{children}</SelectionOutline>}
</>
}

View File

@ -0,0 +1,61 @@
import Button from '@/components/ui/Button'
import { useState } from 'react'
import { cornerGuardLabels } from '@/lib/reference-estimator/standard/cabinet-corner-guard'
import type { AccessoryDraft } from '@/lib/intake-accessory-models'
import type { SurfaceHardware, SurfaceHardwarePlacement } from '@/lib/reference-estimator/standard/surface-hardware'
import { surfaceHardwareKey } from '@/lib/reference-estimator/standard/surface-hardware'
import type { CabinetSurfaceSelectionState } from './cabinet-surface-selection'
import type { CabinetHardwareEdits } from './useCabinetHardwareEdits'
import styles from './cabinet-hardware-placement-controls.module.css'
const locationLabels: Record<SurfaceHardwarePlacement['location'], string> = {
...cornerGuardLabels,
'top-left': '背板左上', 'top-right': '背板右上', 'bottom-left': '背板左下', 'bottom-right': '背板右下',
'top-middle': '背板上边中部', 'bottom-middle': '背板下边中部', 'left-middle': '背板左边中部', 'right-middle': '背板右边中部',
}
export function CabinetSurfaceSelection({ rows, selection, editor, items }: {
rows: SurfaceHardware; selection: CabinetSurfaceSelectionState; editor: CabinetHardwareEdits; items: readonly AccessoryDraft[]
}) {
const count = rows.length
const [removed, setRemoved] = useState(false)
if (!count) return removed ? <p className={styles.selection} role="status">已移除并保存。点击“保存”更新用量与成本。</p> : null
const library = new Map(items.map(item => [item.id, item]))
const connections = editor.selection.filter(point => editor.edits[point.key]).length
const mixed = connections > 0
const busy = selection.busy
const label = (row: SurfaceHardwarePlacement) => {
const model = library.get(row.accessoryId)
return [model?.code, model?.name, locationLabels[row.location]].filter(Boolean).join(' · ')
}
return <section className={styles.selection} aria-label="所选配件">
<div className={styles.selectionHeader}>
<strong>已选 {count} 个配件</strong>
<Button type="button" size="small" variant="plain" disabled={busy} onClick={() => selection.select([])}>清除配件选择</Button>
</div>
{count === 1 ? <p>{label(rows[0])}</p> : <details>
<summary>所选配件 · 可单独取消</summary>
<div className={styles.pointChoices}>
{rows.map(row => {
const key = surfaceHardwareKey(row)
return <button type="button" key={key} disabled={busy} aria-label={'取消选中 ' + label(row)}
onClick={() => selection.select(current => current.filter(item => item !== key))}>
<span>{label(row)}</span><span aria-hidden="true">×</span>
</button>
})}
</div>
</details>}
<div className={styles.actions}>
<Button type="button" size="small" variant="gray" disabled={busy} onClick={async () => {
setRemoved(false)
if (await editor.removeAccessories(selection.keys, mixed)) {
setRemoved(true)
selection.select([])
}
}}>{mixed ? `移除全部所选(${connections} 处五金、${count} 个配件)` : '移除所选配件'}</Button>
<span role="status">{editor.status === 'saving' ? '正在保存…'
: editor.status === 'error' ? '自动保存失败,请点击“重试自动保存”。'
: editor.status === 'limit' ? '已达到测算单的连接点修改上限。' : ''}</span>
</div>
</section>
}

View File

@ -40,11 +40,11 @@ export function EstimateBarcodeBindingDialog({ plan, onClose, onConfirm }: {
}
}
return <Modal isOpen title={adjusting ? '调整条码绑定' : '确认条码绑定'} variant="compact" size="large"
className={styles.dialog} onClose={close} showCloseButton={!busy} closeOnOverlayClick={!busy}
return <Modal isOpen title={adjusting ? '调整条码绑定' : '确认条码绑定'} variant="compact" size="medium"
onClose={close} showCloseButton={!busy} closeOnOverlayClick={!busy}
footer={<div className={styles.footer}>
<Button type="button" variant="gray" disabled={busy} onClick={close}>取消</Button>
<Button type="button" disabled={!ready} loading={busy} onClick={() => void confirm()}>确认绑定</Button>
<Button type="button" variant="gray" size="small" disabled={busy} onClick={close}>取消</Button>
<Button type="button" size="small" disabled={!ready} loading={busy} onClick={() => void confirm()}>确认绑定</Button>
</div>}>
<p className={styles.product}>{product.archive.spu} · {product.archive.name}</p>
<div className={styles.tableHeader} aria-hidden><span>测算款式</span><span>绑定条码</span></div>

View File

@ -12,7 +12,7 @@ import {
} from '@/lib/reference-estimator/standard/model-appearance'
import type { MaterialCategoryWithMaterialsDTO } from '@/server/services/material.service'
import { EstimateTextureControls } from './EstimateTextureControls'
import type { AppearanceSaveStatus } from './useEstimateAppearanceSave'
import type { EstimateSaveStatus } from './useEstimateAutosave'
import styles from './estimate-finish-library.module.css'
async function readFinishes(signal: AbortSignal) {
@ -41,7 +41,7 @@ export function EstimateFinishLibrary({ model, appearance, onChange, active, dis
disabled: boolean
userId?: string
queryClient: QueryClient
saveStatus: AppearanceSaveStatus
saveStatus: EstimateSaveStatus
onRetry: () => void
}) {
const [query, setQuery] = useState('')
@ -86,8 +86,8 @@ export function EstimateFinishLibrary({ model, appearance, onChange, active, dis
</div>
{model && saveStatus.state !== 'idle' && <div className={styles.save}
role={saveStatus.state === 'error' ? 'alert' : 'status'}>
<span>{saveStatus.state === 'saved' ? '外观已自动保存' : saveStatus.state === 'error'
? saveStatus.error : '正在自动保存外观…'}</span>
<span>{saveStatus.state === 'saved' ? '已自动保存' : saveStatus.state === 'error'
? saveStatus.error : '正在自动保存…'}</span>
{saveStatus.state === 'error' && <Button type="button" size="small" variant="plain" disabled={disabled}
onClick={onRetry}>重试保存外观</Button>}
</div>}

View File

@ -1,6 +1,6 @@
'use client'
import { useEffect, useMemo, useRef, useState, type MouseEvent } from 'react'
import { useMemo, useRef, useState, type MouseEvent } from 'react'
import { createPortal } from 'react-dom'
import dynamic from 'next/dynamic'
import { ArrowLeft, Box, ChevronRight, Plus, RefreshCw, Search } from 'lucide-react'
@ -9,10 +9,13 @@ import Modal from '@/components/ui/Modal'
import { accessoryCatalog, accessoryCategories, accessorySpec, type AccessoryDraft, type AccessoryModule } from '@/lib/intake-accessory-models'
import type { EstimateHardwareLibraryState } from './useEstimateHardwareLibrary'
import { hasUsableHardwareModel } from '@/lib/reference-estimator/standard/hardware-model-availability'
import { isCabinetCornerGuard } from '@/lib/reference-estimator/standard/cabinet-corner-guard'
import { inspectCabinetHardwareChoice } from './cabinet-hardware-choice'
import styles from './estimate-hardware-library.module.css'
import { BackPanelClipQuantity } from './BackPanelClipQuantity'
import type { BackPanelClipCount } from '@/lib/reference-estimator/standard/surface-hardware'
import type { CamPlacement } from './cabinet-cam-preview'
import type { CabinetCornerGuardController } from './useCabinetCornerGuard'
const AccessoryEditor = dynamic(() => import('@/app/database/bom-library/accessory-models/AccessoryModelEditor')
.then(module => module.AccessoryModelEditor), { ssr: false })
@ -27,16 +30,30 @@ const describe = (item: AccessoryDraft) => item.spec || accessorySpec(item.kind,
const modules = Object.keys(accessoryCatalog) as AccessoryModule[]
type Category = { module: AccessoryModule; name: string }
export function EstimateHardwareLibrary({ library, onUse, onReplace, onAddAtPoint, placementBusy, selectionHint, onMount, mountMessage, mountDisabled }: {
function draftHoleLabel(choice?: ReturnType<typeof inspectCabinetHardwareChoice>, point?: CamPlacement) {
const reference = choice?.reference
const rule = reference?.machining
if (!reference?.machiningEstimated || rule?.type !== 'dowel') return
const label = ({ diameterMm, depthMm }: typeof rule.first) => `Ø${diameterMm} × 深 ${depthMm} mm`
if (point && reference.dowelCenterOffsetMm !== undefined)
return `模型暂估:${point.donor.part.code} ${label(rule.first)};${point.receiver.part.code} ${label(rule.second)}`
return `模型暂估:两侧 ${label(rule.first)}`
}
export function EstimateHardwareLibrary({ library, onUse, onReplace, onAddAtPoint, additionPoints, batchAddition, throughDowelReplacement, placementBusy, selectionHint, onMount, mountMessage, mountDisabled, cornerGuard }: {
library: EstimateHardwareLibraryState
onUse?: (item: AccessoryDraft) => void
onReplace?: (item: AccessoryDraft) => Promise<void>
onAddAtPoint?: (item: AccessoryDraft) => Promise<void>
additionPoints?: readonly CamPlacement[]
batchAddition?: boolean
throughDowelReplacement?: boolean
placementBusy?: boolean
selectionHint?: string
onMount?: (item: AccessoryDraft, perPanel: BackPanelClipCount) => Promise<boolean>
mountMessage?: string
mountDisabled?: boolean
cornerGuard?: CabinetCornerGuardController
}) {
const [perPanel, setPerPanel] = useState<BackPanelClipCount>(4)
const [category, setCategory] = useState<Category | null>(null)
@ -45,7 +62,6 @@ export function EstimateHardwareLibrary({ library, onUse, onReplace, onAddAtPoin
const [adding, setAdding] = useState(false)
const [editing, setEditing] = useState<AccessoryDraft | null>(null)
const [added, setAdded] = useState<AccessoryDraft | null>(null)
const list = useRef<HTMLUListElement>(null)
const heading = useRef<HTMLHeadingElement>(null)
const trigger = useRef<HTMLButtonElement>(null)
const { data, error, loading } = library
@ -53,10 +69,8 @@ export function EstimateHardwareLibrary({ library, onUse, onReplace, onAddAtPoin
const mode = onAddAtPoint ? 'add' : onReplace ? 'replace' : undefined
const applyPlacement = onAddAtPoint ?? onReplace
const actionLabel = mode === 'replace' ? '替换' : '选用'
const detailChoice = detail && !detail.surfaceMount && mode && items ? inspectCabinetHardwareChoice(detail, items, mode) : undefined
useEffect(() => {
if (mode && list.current) list.current.scrollTop = 0
}, [mode])
const detailChoice = detail && !isCabinetCornerGuard(detail) && !detail.surfaceMount && mode && items
? inspectCabinetHardwareChoice(detail, items, mode, additionPoints, batchAddition, throughDowelReplacement) : undefined
const groups = useMemo(() => {
const counts: Record<AccessoryModule, Map<string, number>> = { accessory: new Map(), connector: new Map() }
for (const { module, category } of items ?? []) {
@ -77,10 +91,12 @@ export function EstimateHardwareLibrary({ library, onUse, onReplace, onAddAtPoin
const spec = describe(item)
const kind = item.kind && item.kind !== item.category ? item.kind : ''
const text = normalize([item.name, item.code, item.kind, spec].join(' '))
const use = !item.surfaceMount && mode && items ? inspectCabinetHardwareChoice(item, items, mode) : undefined
return { item, spec, kind, text, use }
const use = !isCabinetCornerGuard(item) && !item.surfaceMount && mode && items
? inspectCabinetHardwareChoice(item, items, mode, additionPoints, batchAddition, throughDowelReplacement) : undefined
const feedback = use?.issue ? mode === 'add' && item.kind === '圆棒榫' ? use.issue : '暂不能安装' : draftHoleLabel(use, additionPoints?.[0])
return { item, spec, kind, text, use, feedback }
}).sort((first, second) => Number(Boolean(second.use?.reference)) - Number(Boolean(first.use?.reference)))
}, [items, category, mode])
}, [items, category, mode, additionPoints, batchAddition, throughDowelReplacement])
const terms = normalize(query).trim().split(/\s+/).filter(Boolean)
const rows = indexed.filter(({ text }) => terms.every(term => text.includes(term)))
@ -152,18 +168,19 @@ export function EstimateHardwareLibrary({ library, onUse, onReplace, onAddAtPoin
<div className={styles.search} role="search">
<Search size={15} aria-hidden="true"/>
<input type="search" aria-label="搜索五金" value={query} placeholder="搜索名称、编号或规格"
onChange={event => { setQuery(event.target.value); setAdded(null); list.current?.scrollTo(0, 0) }}/>
onChange={event => { setQuery(event.target.value); setAdded(null) }}/>
</div>
</div>
{onMount && rows.some(row => row.item.surfaceMount) && <BackPanelClipQuantity value={perPanel}
{onMount && rows.some(row => row.item.surfaceMount && !isCabinetCornerGuard(row.item)) && <BackPanelClipQuantity value={perPanel}
onChange={setPerPanel} disabled={placementBusy}/>}
{data && <div className={styles.resultLine} role="status">
{added ? hasUsableHardwareModel(added, data.items) ? `已保存 · ${added.name}` : '资料已保存,补齐模型后可在测算中选用' : `${rows.length} 项`}
</div>}
{!data ? <p className={styles.message} role="status">正在读取配件资料…</p>
: !rows.length ? <p className={styles.message}>{terms.length ? '没有找到匹配的五金' : '此品类暂无已建模五金'}</p>
: <ul ref={list} className={styles.list} aria-label="五金资料">
{rows.map(({ item, spec, kind, use }) => <li key={item.id} className={onUse || use?.reference || item.surfaceMount && onMount ? styles.hardwareChoiceRow : undefined}>
: <ul className={styles.list} aria-label="五金资料">
{rows.map(({ item, spec, kind, use, feedback }) => <li key={item.id} className={onUse || use?.reference || item.surfaceMount && onMount ||
cornerGuard && isCabinetCornerGuard(item) ? styles.hardwareChoiceRow : undefined}>
<button type="button" className={styles.item}
onClick={event => { rememberTrigger(event); setDetail(item) }}>
<span className={styles.cover} aria-hidden="true">
@ -177,11 +194,14 @@ export function EstimateHardwareLibrary({ library, onUse, onReplace, onAddAtPoin
<strong>{item.name}</strong>
<span>{[item.code, kind].filter(Boolean).join(' · ')}</span>
{spec && <span title={spec}>{spec}</span>}
{use?.issue && <span title={use.issue}>暂不能安装</span>}
{feedback && <span className={styles.choiceFeedback} title={use?.issue ?? feedback}>{feedback}</span>}
</span>
<ChevronRight className={styles.chevron} size={14} aria-hidden="true"/>
</button>
{item.surfaceMount && onMount ? <Button type="button" size="small" variant="gray"
{cornerGuard && isCabinetCornerGuard(item) ? <Button type="button" size="small" variant="gray"
disabled={!cornerGuard.available || cornerGuard.busy || placementBusy}
onClick={() => cornerGuard.open(item)}>安装四角</Button>
: item.surfaceMount && onMount ? <Button type="button" size="small" variant="gray"
aria-label={`安装 ${item.code} ${item.name} 每块 ${perPanel} 个`}
title={mountDisabled ? '先点选背板' : '每个背板扣配一颗自攻丝'} disabled={placementBusy || mountDisabled}
onClick={() => void onMount(item, perPanel)}>安装</Button>
@ -195,7 +215,10 @@ export function EstimateHardwareLibrary({ library, onUse, onReplace, onAddAtPoin
</>}
{detail && createPortal(
<Modal isOpen title="五金资料" size="large" onClose={closeDetail} bodyClassName="!p-0"
footer={detail.surfaceMount && onMount ? <>
footer={cornerGuard && isCabinetCornerGuard(detail) ? <Button type="button" size="small"
disabled={!cornerGuard.available || cornerGuard.busy || placementBusy}
onClick={() => { cornerGuard.open(detail); closeDetail() }}>安装四角</Button>
: detail.surfaceMount && onMount ? <>
<BackPanelClipQuantity value={perPanel} onChange={setPerPanel} disabled={placementBusy}/>
<Button size="small" disabled={placementBusy || mountDisabled}
onClick={async () => { if (await onMount(detail, perPanel)) closeDetail() }}>
@ -203,7 +226,7 @@ export function EstimateHardwareLibrary({ library, onUse, onReplace, onAddAtPoin
</> : detailChoice?.reference && applyPlacement ? <Button size="small" disabled={placementBusy}
onClick={() => { void applyPlacement(detail); closeDetail() }}>{actionLabel}这个五金</Button>
: !mode && onUse && <Button size="small" onClick={() => { onUse(detail); closeDetail() }}>选用这个五金</Button>}>
<AccessoryDetail item={detail} items={data?.items} feedback={detailChoice?.issue ?? ''} onBack={closeDetail} onEdit={data?.canEdit ? () => {
<AccessoryDetail item={detail} items={data?.items} feedback={detailChoice?.issue ?? draftHoleLabel(detailChoice, additionPoints?.[0]) ?? ''} onBack={closeDetail} onEdit={data?.canEdit ? () => {
setEditing(detail); setDetail(null); setAdding(true)
} : undefined}/>
</Modal>, document.body)}
@ -217,7 +240,6 @@ export function EstimateHardwareLibrary({ library, onUse, onReplace, onAddAtPoin
setQuery('')
setAdded(item)
setEditing(null)
list.current?.scrollTo(0, 0)
closeAdd()
}}/>, document.body)}
</>

View File

@ -0,0 +1,121 @@
'use client'
import { useRef, useState } from 'react'
import Button from '@/components/ui/Button'
import Modal from '@/components/ui/Modal'
import { libraryVariantDimensions } from '@/lib/product-library/variant-dimensions'
import { variantSizeLabel, type VariantSize } from '@/lib/reference-estimator/standard/variant-copy'
import type { EstimateBarcode } from './estimate-workspace-slots'
import { variantPreviewAxes, readVariantPreviewSize, type VariantPreviewRequest } from './variant-copy-preview'
import { VariantReferenceImage } from './VariantReferenceImage'
import { uploadReferenceImage } from './upload-reference-image'
import { useReferenceImagePaste } from './reference-image-paste'
import styles from './estimate-variant-copy.module.css'
export function EstimateVariantCopyDialog({ active, barcodes, sources, targetImage, onClose, onCopy }: {
active: string
barcodes: EstimateBarcode[]
sources: (target: string) => EstimateBarcode[]
targetImage: (target: string) => string
onClose: () => void
onCopy: (source: string, target: string, request: VariantPreviewRequest) => Promise<void>
}) {
const [target, setTarget] = useState(active)
const available = sources(target)
const [source, setSource] = useState(active)
const from = available.some(item => item.slot.barcode === source) ? source : available[0]?.slot.barcode ?? ''
const choice = barcodes.find(item => item.slot.barcode === target)
const registered = choice && libraryVariantDimensions(choice.variant.size)
const [sizeEdits, setSizeEdits] = useState<Record<string, string[]>>({})
const dimensions = sizeEdits[target] ?? variantPreviewAxes.map(([key]) => String(registered?.[key] ?? ''))
const [note, setNote] = useState('')
const [busy, setBusy] = useState(false)
const starting = useRef(false)
const [uploading, setUploading] = useState(false)
const uploadInFlight = useRef(false)
const [images, setImages] = useState<Record<string, string>>({})
const imageUrl = images[target]
const fields = useRef<HTMLDivElement>(null)
const [error, setError] = useState('')
const locked = busy || uploading
const close = () => { if (!starting.current && !uploadInFlight.current) onClose() }
async function upload(file: File) {
if (starting.current || uploadInFlight.current) return
uploadInFlight.current = true
setUploading(true)
setError('')
try {
const url = await uploadReferenceImage(file)
setImages(previous => ({ ...previous, [target]: url }))
} catch (cause) { setError(cause instanceof Error ? cause.message : '参考图上传失败,请重试。') }
finally { uploadInFlight.current = false; setUploading(false) }
}
useReferenceImagePaste(fields, upload, locked, true)
async function start() {
if (!from || starting.current || uploadInFlight.current) return
starting.current = true
setBusy(true)
setError('')
try { await onCopy(from, target, { size: readVariantPreviewSize(dimensions), note: note.trim(), imageUrl }); onClose() }
catch (cause) { setError(cause instanceof Error ? cause.message : '无法复制模型,请重试。') }
finally { starting.current = false; setBusy(false) }
}
return <Modal isOpen title="复制模型" size="medium" variant="compact" onClose={close}
showCloseButton={!locked} closeOnOverlayClick={!locked} footer={<>
<Button type="button" variant="gray" size="small" disabled={locked} onClick={close}>取消</Button>
<Button type="button" size="small" loading={busy} disabled={!from || uploading} onClick={() => void start()}>{busy ? '正在生成预览…' : '生成试改预览'}</Button>
</>}>
<div className={styles.copyGrid} ref={fields}>
<div className={styles.fields}>
<label>当前条码(需要被调整的)<select value={target} disabled={locked} onChange={event => {setTarget(event.target.value); setError('')}}>
{barcodes.map(item => <option key={item.slot.barcode} value={item.slot.barcode}>{item.slot.barcode}</option>)}
</select></label>
<label>来源条码(被复制的条码)<select value={from} disabled={locked || !available.length} onChange={event => {setSource(event.target.value); setError('')}}>
{!available.length && <option value="">没有可用的已有款</option>}
{available.map(item => <option key={item.slot.barcode} value={item.slot.barcode}>{item.slot.barcode}</option>)}
</select></label>
{!available.length && <p>{sources('').length
? '若要从这款复制,请先把当前条码改成需要调整的另一款。'
: '这个 SPU 暂无可复制的模型。'}</p>}
<fieldset className={styles.sizeFields} disabled={locked}>
<legend>目标尺寸(mm)</legend>
<div className={styles.sizeRow}>
{variantPreviewAxes.map(([key, label], index) => <label key={key}>{label}
<input type="number" inputMode="decimal" min="0" max="10000" step="any" value={dimensions[index]}
onChange={event => {
const value = event.target.value
setSizeEdits(previous => ({ ...previous, [target]: dimensions.map((entry, i) => i === index ? value : entry) }))
setError('')
}} />
</label>)}
</div>
</fieldset>
{!registered && !dimensions.some(Boolean) && <p>产品资料未填尺寸。可补填,留空则沿用来源模型尺寸。</p>}
<label>补充说明<textarea placeholder="例如:改成 4 格柜" rows={2} maxLength={2000} disabled={locked} value={note}
onChange={event => { setNote(event.target.value); setError('') }}/></label>
{choice?.recordId && <p>该条码已有测算。采用时会把原模型保存在「模型记录」。</p>}
{error && <p className={styles.error} role="alert">{error}</p>}
</div>
<VariantReferenceImage url={imageUrl ?? targetImage(target)} uploading={uploading} disabled={busy}
onUpload={file => void upload(file)} onReset={imageUrl ? () => {
setImages(previous => { const next = { ...previous }; delete next[target]; return next })
setError('')
} : undefined} />
</div>
</Modal>
}
export function EstimateVariantStatus({ target, actual, source, trial, message, warning }: {
target?: VariantSize | null; actual?: VariantSize; source?: string; trial: boolean; message?: string; warning?: string
}) {
if (!trial) return null
const targetLabel = variantSizeLabel(target), actualLabel = variantSizeLabel(actual)
const showDimensions = Boolean(targetLabel && actualLabel && targetLabel !== actualLabel)
return <div className={styles.status} role="status">
<strong>试改 · 来源 {source}</strong>
{showDimensions && <><span>需求尺寸:{targetLabel}</span><span>当前模型:{actualLabel}</span></>}
{!targetLabel && <span>产品资料未填有效尺寸,可在对话里补充。</span>}
{warning && <span className={styles.warning}>{warning}</span>}
{message && <span>{message}</span>}
</div>
}

View File

@ -0,0 +1,44 @@
'use client'
import { useEffect, useState } from 'react'
import Button from '@/components/ui/Button'
import type { SubstrateDTO } from '@/server/services/asset-center.service.types'
import { BackToEstimateCatalog } from '../catalog/EstimateCatalog'
import { withEstimateReadTimeout } from '../estimate-read'
import { StandardEstimator } from './StandardEstimator'
type State = { status: 'loading' } | { status: 'ready'; substrates: SubstrateDTO[] } | { status: 'error'; message: string }
async function readSubstrates(signal: AbortSignal): Promise<SubstrateDTO[]> {
return withEstimateReadTimeout(async readSignal => {
const response = await fetch('/api/asset-center/substrates', { signal: readSignal, cache: 'no-store' })
const body = await response.json().catch(() => null)
if (!response.ok || !body?.success || !Array.isArray(body.data?.substrates)) {
throw new Error(body?.error?.message ?? '无法读取板材资料')
}
return body.data.substrates
}, signal)
}
export function EstimateWorkbenchEntry({ userId, canPushToLibrary }: { userId: string; canPushToLibrary: boolean }) {
const [state, setState] = useState<State>({ status: 'loading' })
const [attempt, setAttempt] = useState(0)
useEffect(() => {
const controller = new AbortController()
void readSubstrates(controller.signal).then(substrates => {
if (!controller.signal.aborted) setState({ status: 'ready', substrates })
}, error => {
if (!controller.signal.aborted) setState({ status: 'error', message: error instanceof Error ? error.message : '无法读取板材资料' })
})
return () => controller.abort()
}, [attempt])
if (state.status === 'ready') return <StandardEstimator substrates={state.substrates} userId={userId} canPushToLibrary={canPushToLibrary} />
return <div className="flex flex-wrap items-center gap-3 p-4 text-sm">
<BackToEstimateCatalog />
{state.status === 'loading' ? <span className="text-zinc-500" role="status">正在读取板材资料…</span> : <>
<span className="text-zinc-600" role="alert">板材资料读取失败:{state.message}</span>
<Button size="small" variant="gray" onClick={() => { setState({ status: 'loading' }); setAttempt(value => value + 1) }}>重试</Button>
</>}
</div>
}

View File

@ -11,12 +11,14 @@ export const estimateStages = [
] as const
export type EstimateStage = typeof estimateStages[number][0]
export function EstimateStageTabs({ stage, onStage, panelId }: {
export function EstimateStageTabs({ stage, onStage, panelId, modelOnly = false }: {
stage: EstimateStage
onStage: (stage: EstimateStage) => void
panelId: string
modelOnly?: boolean
}) {
function handleStageKey(event: KeyboardEvent<HTMLDivElement>) {
if (modelOnly) return
const current = estimateStages.findIndex(([id]) => id === stage)
const last = estimateStages.length - 1
const next = {
@ -33,20 +35,30 @@ export function EstimateStageTabs({ stage, onStage, panelId }: {
return <div className={styles.tabs} role="tablist" aria-label="测算阶段" onKeyDown={handleStageKey}>
{estimateStages.map(([id, label]) => <button type="button" role="tab" key={id} id={`${panelId}-${id}`}
aria-controls={panelId} aria-selected={stage === id} tabIndex={stage === id ? 0 : -1}
aria-controls={panelId} aria-selected={stage === id} tabIndex={stage === id ? 0 : -1} disabled={modelOnly && id !== 'model'}
onClick={() => onStage(id)}>{label}</button>)}
</div>
}
export function EstimateWorkbenchActions({ controller, bound, archiveEstimateId, canRemove, canPushToLibrary }: {
export function EstimateWorkbenchActions({ controller, bound, archiveEstimateId, canRemove, canPushToLibrary, onAdopt, onDiscard }: {
controller: StandardController
bound: boolean
archiveEstimateId?: string
canRemove: boolean
canPushToLibrary: boolean
onAdopt?: () => void
onDiscard?: () => void
}) {
const { busy, imageBusy, record, dirty, message } = controller
const status = busy ? (imageBusy ? '' : busy) : (dirty ? '有未保存修改' : message)
const { busy, imageBusy, record, dirty, message, autosave } = controller
if (onAdopt) return <div className={styles.actions} role="group" aria-label="试改操作">
<div className={styles.saveActions}>
<Button type="button" size="small" variant="gray" disabled={Boolean(busy)} onClick={onDiscard}>退出试改</Button>
<Button type="button" size="small" disabled={Boolean(busy)} onClick={onAdopt}>采用到此条码</Button>
</div>
</div>
const saveStatus = autosave.status
const status = busy ? (imageBusy ? '' : busy) : saveStatus.state === 'error' ? saveStatus.error
: dirty ? '正在自动保存…' : message || (saveStatus.state === 'saved' ? '已自动保存' : '')
const showPush = canPushToLibrary && !bound && Boolean(record)
const showDelete = canRemove && record && record.id !== archiveEstimateId
@ -59,6 +71,8 @@ export function EstimateWorkbenchActions({ controller, bound, archiveEstimateId,
</div>}
<div className={styles.saveActions}>
<span className={styles.status} role="status" title={status || undefined}>{status}</span>
{saveStatus.state === 'error' && <Button type="button" size="small" variant="plain" disabled={Boolean(busy)}
onClick={() => void controller.retryModelSave()}>重试自动保存</Button>}
<Button type="button" size="small" variant="gray" disabled={Boolean(busy)}
onClick={() => openEstimateSkillLibrary()}>测算技能库</Button>
<Button type="button" size="small" disabled={Boolean(busy)} onClick={() => void controller.save()}>保存</Button>

View File

@ -38,7 +38,7 @@ export function EstimateWorkspaceSlots({ active, spu, loadError, onRetry, hasSlo
</div>
}
export function EstimateRecordSelect({ active, slots, records, recordId, busy, onChoose, onOpen, onAdjust }: {
export function EstimateRecordSelect({ active, slots, records, recordId, busy, onChoose, onOpen, onAdjust, onCopy }: {
active?: EstimateWorkspaceSlot
slots: readonly EstimateWorkspaceSlot[]
records: readonly EstimateSlotRecord[]
@ -47,6 +47,7 @@ export function EstimateRecordSelect({ active, slots, records, recordId, busy, o
onChoose: (slot: EstimateWorkspaceSlot) => void
onOpen: (id: string) => void
onAdjust?: () => void
onCopy?: () => void
}) {
if (active?.kind !== 'barcode') {
return <select aria-label="打开已保存测算单" value={recordId ?? ''} disabled={busy}
@ -69,6 +70,8 @@ export function EstimateRecordSelect({ active, slots, records, recordId, busy, o
{barcodes.map(slot => <option key={slot.barcode} value={workspaceSlotKey(slot)}>{slot.barcode}</option>)}
</select>
{onAdjust && <button className={bindingStyles.adjust} type="button" aria-haspopup="dialog"
disabled={busy} onClick={onAdjust}>调整绑定</button>}
disabled={busy} onClick={onAdjust}>绑定</button>}
{onCopy && <button className={bindingStyles.adjust} type="button" aria-haspopup="dialog"
disabled={busy} onClick={onCopy}>复制</button>}
</div>
}

View File

@ -1,8 +1,8 @@
'use client'
import { useRef, useState } from 'react'
import { useRef, useState, type KeyboardEvent, type ReactNode } from 'react'
import Image from 'next/image'
import { ArrowUp, FileText, Paperclip, X } from 'lucide-react'
import { ArrowUp, FileText, Paperclip, Plus, X } from 'lucide-react'
import Button from '@/components/ui/Button'
import {
MAX_MODEL_ATTACHMENTS, MAX_MODEL_ATTACHMENT_BYTES, MODEL_ATTACHMENT_ACCEPT,
@ -10,6 +10,7 @@ import {
} from '@/lib/reference-estimator/standard/model-attachments'
import { clipboardImage } from './reference-image-paste'
import styles from './model-workspace.module.css'
import composerStyles from './model-conversation-composer.module.css'
async function upload(file: File) {
const form = new FormData()
@ -43,11 +44,13 @@ export function ModelConversationAttachments({ attachments, onRemove }: {
}
export function ModelConversationComposer({
disabled, placeholder, onSend, inputLabel = '输入建模纠正',
disabled, placeholder, onSend, inputLabel = '输入建模纠正', layout = 'inline', beforeSend,
}: {
disabled: boolean
placeholder: string
inputLabel?: string
layout?: 'inline' | 'chat'
beforeSend?: ReactNode
onSend: (message: string, attachments: ModelAttachment[]) => void
}) {
const [message, setMessage] = useState('')
@ -55,7 +58,10 @@ export function ModelConversationComposer({
const [uploading, setUploading] = useState(false)
const [error, setError] = useState('')
const picker = useRef<HTMLInputElement>(null)
const form = useRef<HTMLFormElement>(null)
const composing = useRef(false)
const blocked = disabled || uploading
const canSend = !blocked && Boolean(message.trim() || attachments.length)
async function addFiles(files: File[]) {
if (blocked || !files.length) return
@ -86,7 +92,25 @@ export function ModelConversationComposer({
}
}
return <form className={styles.composer} onPaste={event => {
function handleChatKey(event: KeyboardEvent<HTMLTextAreaElement>) {
if (event.key !== 'Enter' || event.shiftKey || event.altKey || event.ctrlKey || event.metaKey ||
composing.current || event.nativeEvent.isComposing || event.keyCode === 229) return
event.preventDefault()
if (!event.repeat && canSend) form.current?.requestSubmit()
}
const fileInput = <input ref={picker} type="file" accept={MODEL_ATTACHMENT_ACCEPT} multiple hidden
aria-label="选择对话附件" onChange={event => {
void addFiles(Array.from(event.currentTarget.files ?? []))
event.currentTarget.value = ''
}}/>
const chat = layout === 'chat'
const addButton = <Button type="button" size="small" variant={chat ? 'plain' : 'gray'} aria-label="添加附件"
className={chat ? composerStyles.iconButton : undefined}
title="添加附件,也可在输入框粘贴截图" disabled={blocked || attachments.length >= MAX_MODEL_ATTACHMENTS}
onClick={() => picker.current?.click()}>{chat ? <Plus size={19} aria-hidden="true"/> : <Paperclip size={15} aria-hidden="true"/>}</Button>
return <form ref={form} className={chat ? composerStyles.card : styles.composer} onPaste={event => {
const picture = clipboardImage(event.clipboardData)
if (!picture) return
event.preventDefault()
@ -94,9 +118,8 @@ export function ModelConversationComposer({
void addFiles([picture])
}} onSubmit={event => {
event.preventDefault()
const input = message.trim()
if (blocked || (!input && !attachments.length)) return
onSend(input, attachments)
if (!canSend) return
onSend(message.trim(), attachments)
setMessage('')
setAttachments([])
setError('')
@ -105,20 +128,33 @@ export function ModelConversationComposer({
onRemove={blocked ? undefined : index => setAttachments(list => list.filter((_, i) => i !== index))}/>
{uploading && <p className={styles.attachmentStatus} role="status">附件上传中…</p>}
{error && <p className={styles.attachmentError} role="alert">{error}</p>}
<div className={styles.composerRow}>
<input ref={picker} type="file" accept={MODEL_ATTACHMENT_ACCEPT} multiple hidden
aria-label="选择对话附件" onChange={event => {
void addFiles(Array.from(event.currentTarget.files ?? []))
event.currentTarget.value = ''
}}/>
<Button type="button" size="small" variant="gray" aria-label="添加附件"
title="添加附件,也可在输入框粘贴截图" disabled={blocked || attachments.length >= MAX_MODEL_ATTACHMENTS}
onClick={() => picker.current?.click()}><Paperclip size={15} aria-hidden="true"/></Button>
{chat ? <>
<div className={composerStyles.editor}>
<div className={composerStyles.measure} aria-hidden="true">{message}{' '}</div>
<textarea rows={1} maxLength={2000} aria-label={inputLabel} value={message} disabled={disabled}
placeholder={placeholder} onChange={event => setMessage(event.target.value)}
onKeyDown={handleChatKey}
onCompositionStart={() => { composing.current = true }}
onCompositionEnd={() => { composing.current = false }}/>
</div>
<div className={composerStyles.actions}>
{fileInput}
{addButton}
{beforeSend}
<Button type="button" size="small" className={`${composerStyles.iconButton} ${composerStyles.send}`}
aria-label="发送" title="发送(Enter;Shift+Enter 换行)" disabled={!canSend}
onClick={() => form.current?.requestSubmit()}>
<ArrowUp size={16} aria-hidden="true"/>
</Button>
</div>
</> : <div className={styles.composerRow}>
{fileInput}
{addButton}
<textarea rows={2} maxLength={2000} aria-label={inputLabel} value={message} disabled={disabled}
placeholder={placeholder} onChange={event => setMessage(event.target.value)}/>
<Button type="submit" size="small" disabled={blocked || (!message.trim() && !attachments.length)}>
<Button type="submit" size="small" disabled={!canSend}>
<ArrowUp size={15}/>发送
</Button>
</div>
</div>}
</form>
}

View File

@ -1,9 +1,8 @@
'use client'
import { useEffect, useId, useRef, useState } from 'react'
import { BookOpen, MessagesSquare, PanelRightClose } from 'lucide-react'
import { useId, useState } from 'react'
import { ArrowDown, BookOpen } from 'lucide-react'
import Button from '@/components/ui/Button'
import type { CabinetModel } from '@/lib/reference-estimator/standard/cabinet-contracts'
import { imageSkillCategoryLabel } from '@/lib/reference-estimator/standard/cabinet-image-memory'
import { cabinetModuleLabels } from '@/lib/reference-estimator/standard/cabinet-image-structure'
import { MAX_MODEL_TURNS, type ModelTurn } from '@/lib/reference-estimator/standard/model-conversation'
@ -12,8 +11,11 @@ import styles from './model-workspace.module.css'
import { CabinetStructureDetails } from './CabinetStructureDetails'
import { ModelConversationAttachments, ModelConversationComposer } from './ModelConversationComposer'
import { cabinetPartLabel } from '@/lib/reference-estimator/standard/cabinet-part-labels'
export type ModelRevision = { id: string; model: CabinetModel; version: number; summary: string; at?: string }
import { useModelConversationScroll } from './useModelConversationScroll'
import { ModelProviderPicker } from './ModelProviderPicker'
import { ModelVersionHistory } from './ModelVersionHistory'
import { MAX_SAVED_MODEL_VERSIONS } from '@/lib/reference-estimator/standard/model-version-contract'
import type { ModelRevision } from '@/lib/reference-estimator/standard/model-versions'
function formatTime(at: string, includeDate = false) {
return new Intl.DateTimeFormat('zh-CN', {
@ -34,7 +36,7 @@ function ConversationTurn({turn, version, c}: {turn:ModelTurn; version?:number;
</div>
<div className={styles.assistantMessage}>
<div className={styles.meta}><strong>{turn.providerModel ?? '建模助手'}</strong>
<span>{turn.outcome === 'updated' ? `模型 V${version}` : turn.outcome === 'appearance' ? '贴图已调整' : turn.outcome === 'hardware' ? '五金已调整' : turn.outcome === 'failed' ? '本轮未应用' : '未改动模型'}</span></div>
<span>{turn.outcome === 'updated' ? (version ? `模型 V${version}` : '模型已调整') : turn.outcome === 'appearance' ? '贴图已调整' : turn.outcome === 'hardware' ? '五金已调整' : turn.outcome === 'failed' ? '本轮未应用' : '未改动模型'}</span></div>
<p>{turn.reply}</p>
<CabinetStructureDetails structure={snapshot?.input.imageAssembly?.structure}
boards={[...snapshot?.parts ?? [], ...snapshot?.previewParts ?? []].flatMap(part =>
@ -44,26 +46,29 @@ function ConversationTurn({turn, version, c}: {turn:ModelTurn; version?:number;
<div className={styles.suggestionTitle}><strong><BookOpen size={14}/>技能建议</strong>
<span className={styles.tag} data-approved={Boolean(rule.approvedAt)}>{rule.approvedAt ? '已入库' : currentImage ? '待确认' : '旧参考图'}</span></div>
<strong>{imageSkillCategoryLabel(rule.category)} · {rule.materialType}</strong>
{rule.approvedAt && <p>可在「测算技能库 → 技能维护 → {imageSkillCategoryLabel(rule.category)}」的对照表查看。</p>}
<dl>{rule.module && <><dt>部位</dt><dd>{cabinetModuleLabels[rule.module]}</dd></>}
<dt>适用</dt><dd>{rule.appliesWhen}</dd><dt>做法</dt><dd>{rule.method}</dd>
{rule.exceptions && <><dt>例外</dt><dd>{rule.exceptions}</dd></>}
</dl>
{currentImage && !rule.approvedAt && <Button type="button" size="small" variant="gray"
{currentImage && !rule.approvedAt && turn.outcome !== 'reply' && <Button type="button" size="small" variant="gray"
disabled={!c.record || c.dirty || Boolean(c.busy)} onClick={()=>void c.approveModelSuggestion(turn.id)}>加入技能库</Button>}
</section>}
</li>
}
export function ModelConversationPanel({c, revisions, selected, onSelect, onClose}: {
export function ModelConversationPanel({c, revisions, selected, onSelect, active = true}: {
c:StandardController; revisions:ModelRevision[]; selected:string | null;
onSelect:(id:string|null)=>void; onClose:()=>void;
onSelect:(id:string|null)=>void; active?: boolean;
}) {
const [tab, setTab] = useState<'dialogue'|'history'>('dialogue')
const [sending, setSending] = useState(false)
const scroll = useRef<HTMLDivElement>(null)
const [conversationModel, setConversationModel] = useState<string>()
const uid = useId()
const turns = c.standard.modelConversation?.turns
const provider = turns?.findLast(turn => turn.providerModel)?.providerModel
const conversationKey = c.record?.id ?? c.document.imageUrl
const { scroll, content, followLatest, trackPosition, canReturnToLatest } =
useModelConversationScroll(active && tab === 'dialogue', conversationKey, turns?.length ?? 0, sending)
const versions = new Map(revisions.map(revision => [revision.id,revision.version]))
const hasModel = Boolean(c.standard.cabinet)
const limit = (turns?.length ?? 0) >= MAX_MODEL_TURNS
@ -71,21 +76,8 @@ export function ModelConversationPanel({c, revisions, selected, onSelect, onClos
c.standard.bookshelfMemory.reviewedImageUrl !== c.document.imageUrl
const unavailable = !hasModel || imageChanged || !c.document.imageUrl || limit
const disabled = unavailable || sending || Boolean(c.busy)
useEffect(() => {
if (tab !== 'dialogue') return
const frame = requestAnimationFrame(() => {
const panel = scroll.current
if (panel) panel.scrollTop = panel.scrollHeight
})
return () => cancelAnimationFrame(frame)
},[tab, turns?.length, sending])
return <aside className={styles.rail} aria-label="建模对话">
<header className={styles.railHeader}>
<h4><MessagesSquare size={17}/>建模对话</h4>
{provider && <span className={styles.provider} title={provider}>{provider}</span>}
<Button type="button" size="small" variant="plain" aria-label="收起建模对话" title="收起建模对话" onClick={onClose}><PanelRightClose size={16}/></Button>
</header>
<div className={styles.railTabs} role="tablist" aria-label="对话及记录" onKeyDown={event=>{
<div className={styles.modelRailTabs} role="tablist" aria-label="对话及记录" onKeyDown={event=>{
if(event.key!=='ArrowLeft' && event.key!=='ArrowRight')return
event.preventDefault()
const next = tab==='dialogue' ? 'history' : 'dialogue'
@ -93,32 +85,38 @@ export function ModelConversationPanel({c, revisions, selected, onSelect, onClos
}}>
{([['dialogue','对话'],['history','模型记录']] as const).map(([key,label])=>
<button key={key} type="button" role="tab" data-tab={key} id={uid+key} aria-selected={tab===key}
aria-controls={uid+'panel'} tabIndex={tab===key?0:-1} onClick={()=>setTab(key)}>{label}</button>)}
aria-controls={uid+key+'panel'} tabIndex={tab===key?0:-1} onClick={()=>setTab(key)}>{label}</button>)}
</div>
<div className={styles.railScroll} key={tab} ref={scroll} role="tabpanel" id={uid+'panel'} aria-labelledby={uid+tab} tabIndex={0}>
{tab==='dialogue' ? <>
{!!turns?.length && <ol className={styles.turns}>{turns.map(turn => <ConversationTurn key={turn.id} turn={turn} version={versions.get(turn.id)} c={c}/>)}</ol>}
{!turns?.length && <p className={styles.empty}>{hasModel ? '暂无建模对话' : '等待生成参考图模型'}</p>}
{sending && <p className={styles.empty} role="status">建模助手正在处理…</p>}
</> : <ul className={styles.history}>{revisions.slice().reverse().map(revision =>
<li key={revision.id}>
<div><strong>{revision.id==='current' ? '当前模型' : `模型 V${revision.version}`}
{revision.id===revisions.at(-1)?.id && revision.id!=='current' && ' · 当前'}</strong>
<p>{revision.at && <time dateTime={revision.at}>{formatTime(revision.at,true)} · </time>}{revision.summary}</p></div>
<Button type="button" size="small" variant="gray" aria-pressed={(selected ?? revisions.at(-1)?.id)===revision.id}
onClick={()=>onSelect(revision.id===revisions.at(-1)?.id ? null : revision.id)}>查看</Button>
</li>)}
{!revisions.length && <li className={styles.empty}>暂无模型记录</li>}
</ul>}
<div className={styles.dialoguePanel} role="tabpanel" id={uid+'dialoguepanel'} aria-labelledby={uid+'dialogue'} hidden={tab !== 'dialogue'}>
<div className={styles.railScroll} ref={scroll} tabIndex={0} role="group" aria-label="对话消息" onScroll={trackPosition}>
<div ref={content}>
{!!turns?.length && <ol className={styles.turns}>{turns.map(turn => <ConversationTurn key={turn.id} turn={turn} version={versions.get(turn.id)} c={c}/>)}</ol>}
{!turns?.length && <p className={styles.empty}>{hasModel ? '暂无建模对话' : '等待生成参考图模型'}</p>}
{sending && <p className={styles.empty} role="status">建模助手正在处理…</p>}
</div>
</div>
<div className={styles.composerSlot}>
{canReturnToLatest && <Button type="button" size="small" variant="gray" className={styles.returnToLatest}
aria-label="回到最底部" title="回到最底部" onClick={()=>{
scroll.current?.focus({ preventScroll: true })
followLatest()
}}><ArrowDown size={16} aria-hidden="true"/></Button>}
<ModelConversationComposer key={conversationKey} disabled={disabled} layout="chat"
placeholder={limit ? '本测算单已达到 60 轮' : imageChanged ? '请先识别新参考图' : '描述修改,或粘贴截图'}
beforeSend={<ModelProviderPicker value={conversationModel} onChange={setConversationModel} disabled={sending}
active={active && tab === 'dialogue' && !unavailable} queryClient={c.finishQueryClient}/>}
onSend={(message, attachments) => {
followLatest()
setSending(true)
onSelect(null)
void c.answer(message, attachments, conversationModel).finally(() => setSending(false))
}}/>
</div>
</div>
<div hidden={tab !== 'dialogue'} className={styles.composerSlot}>
<ModelConversationComposer key={c.record?.id ?? c.document.imageUrl} disabled={disabled}
placeholder={limit ? '本测算单已达到 60 轮' : imageChanged ? '请先识别新参考图' : '描述修改,或粘贴截图'}
onSend={(message, attachments) => {
setSending(true)
onSelect(null)
void c.answer(message, attachments).finally(() => setSending(false))
}}/>
<div className={styles.railScroll} role="tabpanel" id={uid+'historypanel'} aria-labelledby={uid+'history'} tabIndex={0} hidden={tab !== 'history'}>
{tab==='history' && <ModelVersionHistory key={conversationKey} revisions={revisions} selected={selected} onSelect={onSelect}
onChange={c.editModelHistory} saved={Boolean(c.record && !c.dirty)} busy={Boolean(c.busy)} error={c.error}
atLimit={(c.standard.modelConversation?.savedVersions?.length ?? 0) >= MAX_SAVED_MODEL_VERSIONS}/>}
</div>
</aside>
}

View File

@ -0,0 +1,71 @@
'use client'
import { useId, useRef, useState } from 'react'
import { useQuery, type QueryClient } from '@tanstack/react-query'
import { ChevronDown } from 'lucide-react'
import { estimateModelOptionsSchema } from '@/lib/reference-estimator/standard/estimate-model-options'
import styles from './model-conversation-composer.module.css'
async function readModels(signal: AbortSignal) {
const response = await fetch('/api/intake/reference-estimates/conversation-models', {
cache: 'no-store', signal: AbortSignal.any([signal, AbortSignal.timeout(5000)]),
})
const body = await response.json()
if (!response.ok || !body.success) throw new Error(body.error?.message ?? '模型列表读取失败')
return estimateModelOptionsSchema.parse(body.data)
}
export function ModelProviderPicker({ value, onChange, disabled, active, queryClient }: {
value?: string; onChange: (model?: string) => void; disabled: boolean; active: boolean; queryClient: QueryClient
}) {
const id = useId()
const trigger = useRef<HTMLButtonElement>(null)
const [open, setOpen] = useState(false)
const { data: options, error, isFetching, isStale, refetch } = useQuery({
queryKey: ['reference-estimate-conversation-models'],
queryFn: ({ signal }) => readModels(signal),
enabled: active,
staleTime: 30_000,
gcTime: 5 * 60_000,
retry: false,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
}, queryClient)
const name = value ?? options?.defaultModel ?? (isFetching ? '读取模型…' : '模型')
const unavailable = Boolean(value && options && !options.models.includes(value))
const choose = (model?: string) => {
onChange(model)
setOpen(false)
trigger.current?.focus()
}
return <div className={styles.modelPicker} onBlur={event => {
if (!event.currentTarget.contains(event.relatedTarget)) setOpen(false)
}} onKeyDown={event => {
if (event.key === 'Escape' && open) {
event.stopPropagation()
setOpen(false)
trigger.current?.focus()
}
}}>
<button type="button" className={styles.modelTrigger} ref={trigger}
aria-label={`选择 AI 模型:${name}`}
aria-expanded={open} aria-controls={id} disabled={disabled} onClick={() => {
setOpen(!open)
if (!open && isStale && !isFetching) void refetch()
}}><span>{name}</span><ChevronDown size={12} aria-hidden="true"/></button>
<div id={id} className={styles.modelOptions} hidden={!open} role="group" aria-label="可用 AI 模型">
{isFetching && <p role="status">正在读取…</p>}
{error && !isFetching && <><p role="alert">{['ZodError', 'TimeoutError', 'SyntaxError'].includes(error.name) ? '模型列表读取失败' : error.message}</p>
<button type="button" onClick={() => void refetch()}>重试</button></>}
{unavailable && <p role="alert">所选模型已不可用,请重新选择。</p>}
{options?.models.map(model => {
const isDefault = model === options.defaultModel
return <button type="button" key={model} aria-pressed={(value ?? options.defaultModel) === model}
onClick={() => choose(isDefault ? undefined : model)}>
{model}
</button>
})}
{value && !options && error && <button type="button" onClick={() => choose()}>使用默认模型</button>}
</div>
</div>
}

View File

@ -0,0 +1,75 @@
'use client'
import { useId, useState } from 'react'
import { createPortal } from 'react-dom'
import Button from '@/components/ui/Button'
import Modal from '@/components/ui/Modal'
import { MAX_SAVED_MODEL_VERSIONS, modelVersionName, type ModelVersionAction } from '@/lib/reference-estimator/standard/model-version-contract'
import type { ModelRevision } from '@/lib/reference-estimator/standard/model-versions'
import styles from './model-version-history.module.css'
const formatHistoryTime = new Intl.DateTimeFormat('zh-CN', { month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit', hour12: false })
export function ModelVersionHistory({ revisions, selected, onSelect, onChange, saved, busy, error, atLimit }: {
revisions: ModelRevision[]; selected: string | null; onSelect: (id: string | null) => void
onChange: (change: ModelVersionAction) => Promise<boolean>
saved: boolean; busy: boolean; error: string; atLimit: boolean
}) {
const [action, setAction] = useState<'save' | ModelRevision | null>(null)
const [name, setName] = useState('')
const formId = useId()
const remove = action && action !== 'save' ? action : null
const hasCurrent = revisions[0]?.id === 'current'
const allowed = hasCurrent && saved && !busy
const parsed = modelVersionName.safeParse(name)
const close = () => { if (!busy) setAction(null) }
async function submit() {
if (!allowed) return
const change: ModelVersionAction | undefined = remove ? { action: 'remove', id: remove.id }
: parsed.success && !atLimit ? { action: 'save', name: parsed.data } : undefined
if (!change) return
const completed = await onChange(change)
if (completed) {
if (remove && selected === remove.id) onSelect(null)
setAction(null)
}
}
return <>
{hasCurrent && <div className={styles.toolbar}>
<Button type="button" size="small" variant="gray" disabled={!allowed || atLimit}
onClick={() => { setName(''); setAction('save') }}>保存当前版本</Button>
{!saved && <p>请先保存测算单。</p>}
{atLimit && <p>已保存 {MAX_SAVED_MODEL_VERSIONS} 个手动版本。</p>}
</div>}
<ul className={styles.history}>
{revisions.map(version => <li key={version.id}>
<div className={styles.description}><strong>{version.name}</strong>
{version.at && <time dateTime={version.at}>{formatHistoryTime.format(new Date(version.at))}</time>}
{version.summary && <p>{version.summary}</p>}
</div>
<div className={styles.actions}>
<Button type="button" size="small" variant="gray" aria-label={`查看${version.name}`}
aria-pressed={(selected ?? 'current') === version.id}
onClick={() => onSelect(version.id === 'current' ? null : version.id)}>查看</Button>
{version.id !== 'current' && <Button type="button" size="small" variant="plain" tone="danger"
aria-label={`删除${version.name}`} disabled={!allowed} onClick={() => setAction(version)}>删除</Button>}
</div>
</li>)}
{!revisions.length && <li>暂无模型记录</li>}
</ul>
{action && createPortal(<Modal isOpen title={remove ? '删除历史版本' : '保存当前版本'} size="small" variant="compact"
onClose={close} footer={<>
<Button type="button" variant="gray" size="small" disabled={busy} onClick={close}>取消</Button>
<Button type="button" size="small" tone={remove ? 'danger' : 'default'} onClick={() => void submit()}
disabled={!allowed || (!remove && (!parsed.success || atLimit))}>{busy ? '处理中…' : remove ? '确认删除' : '保存版本'}</Button>
</>}>
<form id={formId} className={styles.form} onSubmit={event => { event.preventDefault(); void submit() }}>
<button type="submit" hidden>提交</button>
{remove ? <p>删除「{remove.name}」后将不能再回看这份快照。当前模型和对话会保留。</p>
: <label>版本名称<input value={name} onChange={event => setName(event.target.value)}
maxLength={40} required placeholder="例如:打样前确认版" disabled={busy}/></label>}
{error && <p className={styles.error} role="alert">{error}</p>}
</form>
</Modal>, document.body)}
</>
}

View File

@ -3,8 +3,7 @@
import { useMemo, useState } from 'react'
import { PanelRightOpen } from 'lucide-react'
import Button from '@/components/ui/Button'
import { modelChanged } from '@/lib/reference-estimator/standard/model-change-details'
import type { ModelRevision } from './ModelConversationPanel'
import { listModelVersions } from '@/lib/reference-estimator/standard/model-versions'
import { ModelWorkspaceRail, type ModelWorkspaceRailTab } from './ModelWorkspaceRail'
import { StandardModelPanel } from './StandardModelPanel'
import type { StandardController } from './useStandardEstimator'
@ -12,6 +11,9 @@ import type { EstimateHardwareLibraryState } from './useEstimateHardwareLibrary'
import { useHardwareBoardConnections } from './useHardwareBoardConnections'
import { useCabinetHardwareEdits } from './useCabinetHardwareEdits'
import { useSurfaceHardware } from './useSurfaceHardware'
import { useCabinetCornerGuard } from './useCabinetCornerGuard'
import { surfaceHardwareKey } from '@/lib/reference-estimator/standard/surface-hardware'
import type { CabinetSurfaceSelectionState } from './cabinet-surface-selection'
import styles from './model-workspace.module.css'
export function ModelWorkspace({c, showDimensions, onDimensionsChange, hardwareLibrary}: {
@ -23,35 +25,45 @@ export function ModelWorkspace({c, showDimensions, onDimensionsChange, hardwareL
const [open, setOpen] = useState(true)
const [tab, setTab] = useState<ModelWorkspaceRailTab>('model')
const [selected, setSelected] = useState<string|null>(null)
const [pickedAccessories, setPickedAccessories] = useState<{ scope: string; keys: string[] }>()
const {modelConversation, cabinet} = c.standard
const revisions = useMemo(()=>{
const list: ModelRevision[] = []
if(modelConversation?.initial){
const {model, at} = modelConversation.initial
list.push({id:'initial', model, at, version:1, summary:'识图初版'})
}
for(const turn of modelConversation?.turns ?? [])if(turn.snapshot){
list.push({id:turn.id, model:turn.snapshot, at:turn.at, version:list.length+1, summary:turn.reply})
}
if(cabinet && modelChanged(list.at(-1)?.model,cabinet)){
list.push({id:'current', model:cabinet, version:list.length+1, summary:list.length ? '当前测算单模型' : '已载入模型'})
}
return list
},[modelConversation,cabinet])
const historical = revisions.find(revision=>revision.id===selected && revision.id!==revisions.at(-1)?.id)
const revisions = useMemo(()=>listModelVersions({ cabinet, modelConversation }),[modelConversation,cabinet])
const historical = revisions.find(revision=>revision.id===selected && revision.id!=='current')
const connections = useHardwareBoardConnections(c, Boolean(historical), hardwareLibrary.data?.items)
const previewLibrary = !historical && cabinet ? hardwareLibrary : undefined
const hardwareEdits = useCabinetHardwareEdits(c, previewLibrary ? cabinet : undefined, hardwareLibrary.data?.items)
const surfaceHardware = useSurfaceHardware(c, hardwareEdits.seamPicking.keys, hardwareLibrary.data?.items ?? [])
const cornerGuard = useCabinetCornerGuard(c, hardwareLibrary)
const surfaceScope = JSON.stringify([c.record?.id, c.document.workspaceSlot])
const pickedKeys = useMemo(() => new Set(pickedAccessories?.scope === surfaceScope ? pickedAccessories.keys : []),
[pickedAccessories, surfaceScope])
const selectedAccessories = useMemo(() => (c.document.surfaceHardware ?? []).filter(row => pickedKeys.has(surfaceHardwareKey(row))),
[c.document.surfaceHardware, pickedKeys])
function choose(next: ModelWorkspaceRailTab) {
if (next === 'hardware' || next === 'info') hardwareLibrary.load()
if (next !== 'hardware' && connections.picking) connections.reset()
if (next !== 'hardware') cornerGuard.cancel()
if (next !== 'hardware' && hardwareEdits.seamPicking.picking) {
hardwareEdits.seamPicking.reset()
hardwareEdits.select([])
}
setTab(next)
}
const surfaceSelection: CabinetSurfaceSelectionState | undefined = previewLibrary ? {
keys: new Set(selectedAccessories.map(surfaceHardwareKey)),
busy: hardwareEdits.busy || cornerGuard.busy || surfaceHardware.busy,
select: action => {
setPickedAccessories(current => {
const previous = current?.scope === surfaceScope ? current.keys : []
const keys = typeof action === 'function' ? action(previous) : action
return keys.length ? { scope: surfaceScope, keys } : undefined
})
if (Array.isArray(action) && action.length) {
setOpen(true)
choose('hardware')
}
},
} : undefined
const placementEditor = previewLibrary ? {
...hardwareEdits,
seamPicking: {
@ -90,17 +102,23 @@ export function ModelWorkspace({c, showDimensions, onDimensionsChange, hardwareL
</Button></div>}
<StandardModelPanel c={c} historical={historical} onReturn={()=>setSelected(null)}
showDimensions={showDimensions} onDimensionsChange={onDimensionsChange}
previewLibrary={previewLibrary}
previewLibrary={historical && (historical.surfaceHardware?.length || historical.hardwarePlacementEdits || historical.hardwareSeamEdits) ? hardwareLibrary : previewLibrary}
cornerGuardPreview={cornerGuard.preview?.rows}
cornerGuardModels={historical ? undefined : cornerGuard.modelState}
surfaceSelection={surfaceSelection}
hardwareEditor={placementEditor}/>
</div>
<ModelWorkspaceRail c={c} selected={selected} revisions={revisions} onSelect={v => {
connections.reset()
hardwareEdits.seamPicking.reset()
hardwareEdits.select([])
setPickedAccessories(undefined)
cornerGuard.cancel()
setSelected(v)
}}
open={open} onClose={()=>setOpen(false)} library={hardwareLibrary}
open={open} onClose={()=>{cornerGuard.cancel(); setOpen(false)}} library={hardwareLibrary}
tab={tab} onTab={choose} connections={connections} historical={historical} placementEditor={placementEditor}
surfaceHardware={historical ? undefined : surfaceHardware}/>
surfaceHardware={historical ? undefined : surfaceHardware} cornerGuard={historical ? undefined : cornerGuard}
surfaceSelection={surfaceSelection} selectedAccessories={selectedAccessories}/>
</div>
}

View File

@ -4,7 +4,7 @@ import { CABINET_QUOTA } from '@/lib/reference-estimator/standard/cabinet-quota'
import {
cabinetLegs, type CabinetInput,
} from '@/lib/reference-estimator/standard/cabinet-contracts'
import type { ModelRevision } from './ModelConversationPanel'
import type { ModelRevision } from '@/lib/reference-estimator/standard/model-versions'
import { StandardRecognitionReview } from './StandardRecognitionReview'
import { ModelReviewItems } from './ModelReviewItems'
import { ModelParts } from './ModelParts'
@ -83,7 +83,7 @@ export function ModelWorkspaceInfo({ c, historical, version, hardwareItems }: {
return <div className={styles.info} tabIndex={0} aria-label="模型资料内容" role="region">
<div className={styles.overview} aria-label="模型概况">
<strong>V{historical?.version ?? version ?? 1}</strong>
<strong>{historical?.name ?? `V${version ?? 1}`}</strong>
<span>{boardCount} 块板件</span>
<span title="宽 × 深 × 高">{input.width}×{input.depth}×{input.height} mm</span>
</div>

View File

@ -10,12 +10,18 @@ import { CabinetHardwareSelection } from './CabinetHardwareSelection'
import { CabinetHardwareSeamPanel } from './CabinetHardwareSeamPanel'
import { CabinetSkillHardwareAction } from './CabinetSkillHardwareAction'
import type { CabinetHardwareEdits } from './useCabinetHardwareEdits'
import { ModelConversationPanel, type ModelRevision } from './ModelConversationPanel'
import { ModelConversationPanel } from './ModelConversationPanel'
import type { ModelRevision } from '@/lib/reference-estimator/standard/model-versions'
import { ModelWorkspaceInfo } from './ModelWorkspaceInfo'
import type { EstimateHardwareLibraryState } from './useEstimateHardwareLibrary'
import type { StandardController } from './useStandardEstimator'
import type { HardwareBoardConnectionController } from './useHardwareBoardConnections'
import type { useSurfaceHardware } from './useSurfaceHardware'
import type { CabinetCornerGuardController } from './useCabinetCornerGuard'
import { CabinetCornerGuardControls } from './CabinetCornerGuardControls'
import { CabinetSurfaceSelection } from './CabinetSurfaceSelection'
import type { CabinetSurfaceSelectionState } from './cabinet-surface-selection'
import type { SurfaceHardware } from '@/lib/reference-estimator/standard/surface-hardware'
import styles from './estimate-hardware-library.module.css'
import infoStyles from './model-workspace-info.module.css'
@ -27,7 +33,7 @@ const tabs = [
] as const
export type ModelWorkspaceRailTab = typeof tabs[number]['id']
export function ModelWorkspaceRail({ c, selected, revisions, onSelect, open, onClose, library, tab, onTab, connections, historical, placementEditor, surfaceHardware }: {
export function ModelWorkspaceRail({ c, selected, revisions, onSelect, open, onClose, library, tab, onTab, connections, historical, placementEditor, surfaceHardware, cornerGuard, surfaceSelection, selectedAccessories }: {
c: StandardController
selected: string | null
revisions: ModelRevision[]
@ -41,11 +47,16 @@ export function ModelWorkspaceRail({ c, selected, revisions, onSelect, open, onC
historical?: ModelRevision
placementEditor?: CabinetHardwareEdits
surfaceHardware?: ReturnType<typeof useSurfaceHardware>
cornerGuard?: CabinetCornerGuardController
surfaceSelection?: CabinetSurfaceSelectionState
selectedAccessories?: SurfaceHardware
}) {
const id = useId()
return <aside className={styles.rail} aria-label="模型工作区右栏" hidden={!open}>
<div className={styles.railHeader}>
<Button type="button" size="small" variant="plain" className={styles.collapse}
aria-label="收起右栏" title="收起右栏" onClick={onClose}><PanelRightClose size={14}/></Button>
<div className={styles.tabs} role="tablist" aria-label="模型侧栏" onKeyDown={event => {
const index = tabs.findIndex(item => item.id === tab)
const next = event.key === 'Home' ? tabs[0].id : event.key === 'End' ? tabs[tabs.length - 1].id
@ -61,15 +72,14 @@ export function ModelWorkspaceRail({ c, selected, revisions, onSelect, open, onC
aria-selected={tab === key} aria-controls={id + key + 'panel'} tabIndex={tab === key ? 0 : -1}
onClick={() => onTab(key)}>{label}</button>)}
</div>
{tab !== 'model' && <Button type="button" size="small" variant="plain"
aria-label="收起右栏" title="收起右栏" onClick={onClose}><PanelRightClose size={16}/></Button>}
</div>
<div className={styles.chatPanel} role="tabpanel" id={id + 'modelpanel'} aria-labelledby={id + 'model'} hidden={tab !== 'model'}>
<ModelConversationPanel c={c} selected={selected} revisions={revisions} onSelect={onSelect} onClose={onClose}/>
<ModelConversationPanel key={c.userId} c={c} selected={selected} revisions={revisions} onSelect={onSelect}
active={open && tab === 'model'}/>
</div>
<div className={infoStyles.panel} role="tabpanel" id={id + 'infopanel'} aria-labelledby={id + 'info'}
hidden={tab !== 'info'}>
{tab === 'info' && <ModelWorkspaceInfo c={c} historical={historical} version={revisions.at(-1)?.version}
{tab === 'info' && <ModelWorkspaceInfo c={c} historical={historical} version={revisions[0]?.version}
hardwareItems={library.data?.items ?? []}/>}
</div>
<div className={styles.hardwarePanel} role="tabpanel" id={id + 'finishpanel'} aria-labelledby={id + 'finish'} hidden={tab !== 'finish'}>
@ -77,22 +87,31 @@ export function ModelWorkspaceRail({ c, selected, revisions, onSelect, open, onC
model={historical ? undefined : c.standard.cabinet} appearance={historical ? undefined : c.document.modelAppearance}
active={tab === 'finish' && open} userId={c.userId} disabled={Boolean(c.busy || historical)}
onChange={c.setModelAppearance} queryClient={c.finishQueryClient}
saveStatus={c.appearanceSave.status} onRetry={c.appearanceSave.retry}/>
saveStatus={c.autosave.status} onRetry={c.autosave.retry}/>
</div>
<div className={styles.hardwarePanel} role="tabpanel" id={id + 'hardwarepanel'} aria-labelledby={id + 'hardware'}
hidden={tab !== 'hardware'}>
<div className={`${styles.hardwarePanel} ${styles.hardwareScroll}`} role="tabpanel" id={id + 'hardwarepanel'}
aria-labelledby={id + 'hardware'} hidden={tab !== 'hardware'} tabIndex={0}>
{!historical && <CabinetSkillHardwareAction key={JSON.stringify([c.record?.id, c.document.workspaceSlot])} c={c}/>}
{cornerGuard && <CabinetCornerGuardControls guard={cornerGuard}/>}
{tab === 'hardware' && surfaceSelection && placementEditor && !placementEditor.seamPicking.picking && !cornerGuard?.preview &&
<CabinetSurfaceSelection key={JSON.stringify(['surface', c.record?.id, c.document.workspaceSlot])}
rows={selectedAccessories ?? []} selection={surfaceSelection} editor={placementEditor} items={library.data?.items ?? []}/>}
{placementEditor && (placementEditor.seamPicking.picking
? <CabinetHardwareSeamPanel editor={placementEditor} surfaceSelection={surfaceHardware?.canMount}/>
: <CabinetHardwareSelection editor={placementEditor}/>)}
: tab === 'hardware' && <CabinetHardwareSelection editor={placementEditor}
combinedRemoval={Boolean(!cornerGuard?.preview && selectedAccessories?.length)}/>)}
{!historical && connections.connections.length > 0 && <EstimateHardwareConnections controller={connections} items={library.data?.items}
libraryError={library.error} readOnly/>}
<EstimateHardwareLibrary library={library}
cornerGuard={cornerGuard}
onMount={surfaceHardware?.mount} mountMessage={surfaceHardware?.message}
mountDisabled={!surfaceHardware?.canMount}
selectionHint={placementEditor && !placementEditor.seamPicking.picking && !placementEditor.selection.length
? '点选背板安装背板扣,或点选两块板件新增连接。' : undefined}
onAddAtPoint={placementEditor?.pendingAddition ? placementEditor.addHardware : undefined}
additionPoints={placementEditor?.additionPoints}
batchAddition={Boolean(placementEditor?.pendingAddition && placementEditor.seamPicking.targets.length > 1)}
throughDowelReplacement={placementEditor?.throughDowelReplacement}
placementBusy={placementEditor?.busy || surfaceHardware?.busy || Boolean(c.busy)}
onReplace={placementEditor?.selection.length ? placementEditor.replace : undefined}/>
</div>

View File

@ -1,11 +1,14 @@
'use client'
import { useEffect, useRef, useState, type ReactNode } from 'react'
import { BookOpen, MessageSquare, X } from 'lucide-react'
import { useState, type ReactNode } from 'react'
import { ArrowDown, BookOpen, MessageSquare, X } from 'lucide-react'
import Button from '@/components/ui/Button'
import { assistantStageLabel, type AssistantStage } from '@/lib/reference-estimator/standard/stage-assistant-contract'
import { imageSkillCategoryLabel } from '@/lib/reference-estimator/standard/cabinet-image-memory'
import type { ModelAttachment } from '@/lib/reference-estimator/standard/model-attachments'
import { ModelConversationAttachments, ModelConversationComposer } from './ModelConversationComposer'
import { ModelProviderPicker } from './ModelProviderPicker'
import { useModelConversationScroll } from './useModelConversationScroll'
import { openEstimateSkillLibrary } from '../skill-library-events'
import type { StandardController } from './useStandardEstimator'
import styles from './model-workspace.module.css'
@ -17,18 +20,27 @@ const examples = {
export function StageAssistantWorkspace({ c, stage, children }: { c: StandardController; stage: AssistantStage; children: ReactNode }) {
const [open, setOpen] = useState(true)
const [sending, setSending] = useState(false)
const [conversationModel, setConversationModel] = useState<string>()
const label = assistantStageLabel[stage]
const turns = c.standard.stageConversations?.[stage] ?? []
const scroll = useRef<HTMLDivElement>(null)
useEffect(() => {
if (open && scroll.current) scroll.current.scrollTop = scroll.current.scrollHeight
}, [open, turns.length])
const hasModel = Boolean(c.standard.cabinet)
const conversationKey = c.record?.id ?? c.document.imageUrl
const { scroll, content, trackPosition, followLatest, canReturnToLatest } =
useModelConversationScroll(open && hasModel, conversationKey, turns.length, sending)
const disabled = sending || Boolean(c.busy)
if (!c.standard.cabinet) return children
const send = (message: string, attachments: ModelAttachment[]) => {
followLatest()
setSending(true)
void c.sendStageMessage(stage, message, attachments, conversationModel).finally(() => setSending(false))
}
return <div className={styles.workspace} data-chat-open={open}>
<div className={styles.scene}>
{!open && <div className={styles.reopen}>
<Button type="button" size="small" variant="gray" onClick={() => setOpen(true)}>
<Button type="button" size="small" variant="gray" onClick={() => { followLatest(); setOpen(true) }}>
<MessageSquare size={14}/> {label}对话
</Button>
</div>}
@ -37,36 +49,50 @@ export function StageAssistantWorkspace({ c, stage, children }: { c: StandardCon
{open && <aside className={styles.rail} aria-label={label + '对话'}>
<header className={styles.railHeader}>
<h4><MessageSquare size={15}/>{label}对话</h4>
<span className={styles.provider}>{turns.findLast(turn => turn.providerModel)?.providerModel ?? ''}</span>
<Button type="button" size="small" variant="plain" aria-label="查看本阶段技能库" title="查看本阶段技能库"
onClick={() => openEstimateSkillLibrary({ section:stage })}><BookOpen size={15}/></Button>
<Button type="button" size="small" variant="plain" aria-label="收起对话" onClick={() => setOpen(false)}><X size={15}/></Button>
</header>
<div ref={scroll} className={styles.railScroll} role="tabpanel" aria-label={label + '对话记录'}>
{!turns.length && <p className={styles.empty}>可以用文字、截图或附件说明要改哪里。</p>}
<Button type="button" size="small" variant="plain" disabled={Boolean(c.busy)}
onClick={() => void c.sendStageMessage(stage, '检查并应用本款适用的已确认技能。没有适用的做法就说明情况,保持当前结果。', [])}>
按已确认技能检查
</Button>
<div className={styles.turns}>{turns.map(turn => <article className={styles.turn} key={turn.id}>
<div className={styles.userMessage}><p>{turn.input}</p><ModelConversationAttachments attachments={turn.attachments}/></div>
<div className={styles.assistantMessage}>
<div className={styles.meta}><span>{turn.providerModel ?? '系统'}</span>
<span>{turn.outcome === 'updated' ? '已修订' : turn.outcome === 'failed' ? '未应用' : ''}</span></div>
<p>{turn.reply}</p>
<div className={styles.dialoguePanel}>
<div ref={scroll} className={styles.railScroll} tabIndex={0} role="group" aria-label={label + '对话记录'} onScroll={trackPosition}>
<div ref={content}>
{!turns.length && <p className={styles.empty}>可以用文字、截图或附件说明要改哪里。</p>}
<Button type="button" size="small" variant="plain" disabled={disabled}
onClick={() => send('检查并应用本款适用的已确认技能。没有适用的做法就说明情况,保持当前结果。', [])}>
按已确认技能检查
</Button>
<div className={styles.turns}>{turns.map(turn => <article className={styles.turn} key={turn.id}>
<div className={styles.userMessage}><p>{turn.input}</p><ModelConversationAttachments attachments={turn.attachments}/></div>
<div className={styles.assistantMessage}>
<div className={styles.meta}><span>{turn.providerModel ?? '系统'}</span>
<span>{turn.outcome === 'updated' ? '已修订' : turn.outcome === 'failed' ? '未应用' : ''}</span></div>
<p>{turn.reply}</p>
</div>
{turn.suggestion && <div className={styles.suggestion}>
<div className={styles.suggestionTitle}><strong>技能建议 · {imageSkillCategoryLabel(turn.suggestion.category)}</strong>
<span className={styles.tag} data-approved={Boolean(turn.suggestion.approvedAt)}>{turn.suggestion.approvedAt ? '已入库' : '待确认'}</span></div>
<dl><dt>适用条件</dt><dd>{turn.suggestion.appliesWhen}</dd><dt>做法</dt><dd>{turn.suggestion.method}</dd>
{turn.suggestion.exceptions && <><dt>例外</dt><dd>{turn.suggestion.exceptions}</dd></>}</dl>
{!turn.suggestion.approvedAt && <Button type="button" size="small" variant="gray" disabled={disabled || c.dirty}
onClick={() => void c.approveStageSuggestion(stage, turn.id)}>确认并存入技能库</Button>}
</div>}
</article>)}</div>
{sending && <p className={styles.empty} role="status">{label}助手正在处理…</p>}
</div>
{turn.suggestion && <div className={styles.suggestion}>
<div className={styles.suggestionTitle}><strong>技能建议 · {imageSkillCategoryLabel(turn.suggestion.category)}</strong>
<span className={styles.tag} data-approved={Boolean(turn.suggestion.approvedAt)}>{turn.suggestion.approvedAt ? '已入库' : '待确认'}</span></div>
<dl><dt>适用条件</dt><dd>{turn.suggestion.appliesWhen}</dd><dt>做法</dt><dd>{turn.suggestion.method}</dd>
{turn.suggestion.exceptions && <><dt>例外</dt><dd>{turn.suggestion.exceptions}</dd></>}</dl>
{!turn.suggestion.approvedAt && <Button type="button" size="small" variant="gray" disabled={Boolean(c.busy) || c.dirty}
onClick={() => void c.approveStageSuggestion(stage, turn.id)}>确认并存入技能库</Button>}
</div>}
</article>)}</div>
</div>
<div className={styles.composerSlot}>
{canReturnToLatest && <Button type="button" size="small" variant="gray" className={styles.returnToLatest}
aria-label="回到最底部" title="回到最底部" onClick={() => {
scroll.current?.focus({ preventScroll: true })
followLatest()
}}><ArrowDown size={16} aria-hidden="true"/></Button>}
<ModelConversationComposer key={conversationKey} layout="chat" disabled={disabled}
inputLabel={'输入' + label + '修改'} placeholder={examples[stage]}
beforeSend={<ModelProviderPicker value={conversationModel} onChange={setConversationModel}
active={open} disabled={disabled} queryClient={c.finishQueryClient}/>}
onSend={send}/>
</div>
</div>
<ModelConversationComposer disabled={Boolean(c.busy)} inputLabel={'输入' + label + '修改'} placeholder={examples[stage]}
onSend={(message, attachments) => void c.sendStageMessage(stage, message, attachments)}/>
</aside>}
</div>
}

View File

@ -12,7 +12,6 @@ import { EstimateInputPanel } from '../EstimateInputPanel'
import { EstimateSkillLibrary } from '../EstimateSkillLibrary'
import { StageAssistantWorkspace } from './StageAssistantWorkspace'
import { StandardQuotesPanel } from './StandardQuotesPanel'
import { StandardRecognitionReview } from './StandardRecognitionReview'
import { ModelWorkspace } from './ModelWorkspace'
import { useEstimateHardwareLibrary } from './useEstimateHardwareLibrary'
import modelLayout from './model-workspace.module.css'
@ -23,18 +22,19 @@ import { referenceEstimateWorkspaceKey } from '../referenceEstimateLinks'
import { EstimateRecordSelect, EstimateWorkspaceSlots } from './EstimateWorkspaceSlots'
import { EstimateSpuDialog } from './EstimateSpuDialog'
import { useEstimateWorkspaceSlots } from './useEstimateWorkspaceSlots'
import { BackToEstimateCatalog, EstimateCatalogEntry } from '../catalog/EstimateCatalog'
import { BackToEstimateCatalog } from '../catalog/EstimateCatalog'
import { EstimateStageTabs, EstimateWorkbenchActions, estimateStages, type EstimateStage } from './EstimateWorkbenchToolbar'
import workbenchLayout from './estimate-workbench.module.css'
import { EstimateStageRefresh } from './EstimateStageRefresh'
import { EstimateBarcodeBindingDialog } from './EstimateBarcodeBindingDialog'
import type { EstimateBindingPlan } from './estimate-barcode-binding'
import { EstimateVariantCopyDialog, EstimateVariantStatus } from './EstimateVariantCopy'
import { variantModelSize } from '@/lib/reference-estimator/standard/variant-copy'
type Props = { substrates: SubstrateDTO[]; userId?: string; canPushToLibrary?: boolean }
export function StandardEstimator(props: Props) {
const workbench = <StandardEstimateWorkbench key={props.userId} {...props} />
return props.userId ? <EstimateCatalogEntry>{workbench}</EstimateCatalogEntry> : workbench
return <StandardEstimateWorkbench key={props.userId} {...props} />
}
function StandardEstimateWorkbench({ substrates, userId, canPushToLibrary = false }: Props) {
@ -45,6 +45,7 @@ function StandardEstimateWorkbench({ substrates, userId, canPushToLibrary = fals
const hardwareLibrary = useEstimateHardwareLibrary(hardwareTurn?.id)
const [showDimensions, setShowDimensions] = useState(false)
const [binding, setBinding] = useState<EstimateBindingPlan>()
const [copyOpen, setCopyOpen] = useState(false)
const panelId = useId()
const workspace = useEstimateWorkspaceSlots({
current: { document: c.document, record: c.record, dirty: c.dirty },
@ -53,11 +54,13 @@ function StandardEstimateWorkbench({ substrates, userId, canPushToLibrary = fals
loadRecord: c.loadRecord,
replace: c.activateRecord,
})
const stageKey = workspace.activeKey || c.record?.id || 'draft'
const stageKey = (workspace.activeKey || c.record?.id || 'draft') + (c.variantTrial ? ':trial' : '')
const returnToNumber = workspace.returnToNumber
const activeBarcode = workspace.active?.kind === 'barcode' ? workspace.active : undefined
const isBound = Boolean(activeBarcode)
const productEstimate = workspace.spu?.barcodes.find(item => item.slot.barcode === activeBarcode?.barcode)?.recordId
const activeVariant = workspace.spu?.barcodes.find(item => item.slot.barcode === activeBarcode?.barcode)
const productEstimate = activeVariant?.recordId
const targetSize = c.document.variantCopy?.targetSize
const stageWorkspace = tab !== 'cost'
const samplingController = c.stages.sampling ? {
...c,
@ -72,27 +75,34 @@ function StandardEstimateWorkbench({ substrates, userId, canPushToLibrary = fals
writeWorkspacePosition(userId,referenceEstimateWorkspaceKey,'stage',stage)
}
const workbench = useRef<HTMLDivElement>(null)
useReferenceImagePaste(workbench, c.upload, Boolean(c.busy || workspace.dialog || binding))
const money=(n:number|null)=>n===null?(c.finishBom.missingPrice?'待确认':'未生成'):`¥${n.toFixed(2)}`
useReferenceImagePaste(workbench, c.upload, Boolean(c.busy || workspace.dialog || binding || copyOpen))
const money=(n:number|null)=>n===null?'—':`¥${n.toFixed(2)}`
const estimated=Object.keys(c.finishBom.standard.costEstimates??{}).some(a=>a!=='S112'&&!a.startsWith('AB'))
const afterAppearance = async (action: () => Promise<void> | void) => {
await c.appearanceSave.saveBeforeSwitch()
const afterAutosave = async (action: () => Promise<void> | void) => {
await c.autosave.saveBeforeSwitch()
await action()
}
const left={document:c.document,busy:c.busy,update:c.updateDocument,upload:c.upload,analyze:c.analyze,applyNotes:c.analyze,skillIssue:'',options:c.options,chooseMain:c.chooseMain}
return <div ref={workbench} className={`${layout.workbench} ${styles.standardWorkbench}`}>
<EstimateSkillLibrary quotes={<StandardQuotesPanel c={c}/>}/>
<EstimateSkillLibrary userId={userId} quotes={<StandardQuotesPanel c={c}/>}/>
{workspace.dialog && <EstimateSpuDialog mode={workspace.dialog} numberedDrafts={workspace.draftNumbers}
active={workspace.active} slots={workspace.slots}
onContinue={async product => setBinding(await workspace.prepareBinding(product))}
onChoose={slot => afterAppearance(() => workspace.choose(slot))}
onAdd={() => void c.run('正在新建测算…', () => afterAppearance(workspace.add))} onMode={workspace.setDialog}
onChoose={slot => afterAutosave(() => workspace.choose(slot))}
onAdd={() => void c.run('正在新建测算…', () => afterAutosave(workspace.add))} onMode={workspace.setDialog}
onClose={() => workspace.setDialog(null)}/>}
{binding && <EstimateBarcodeBindingDialog plan={binding} onClose={() => setBinding(undefined)}
onConfirm={async choices => {
await c.waitForBindingWrites()
c.acceptBindingRecords(await workspace.confirmBinding(binding, choices))
}} />}
{copyOpen && activeBarcode && workspace.spu && <EstimateVariantCopyDialog active={activeBarcode.barcode}
barcodes={workspace.spu.barcodes} sources={workspace.copySources} targetImage={workspace.copyTargetImage} onClose={() => setCopyOpen(false)}
onCopy={async (source, target, request) => {
await c.waitForBindingWrites()
await workspace.startCopy(source, target, request, { boardLibrary: c.options }, substrates)
chooseStage('model')
}} />}
{c.error&&<div className={layout.error} role="alert">{c.error}</div>}
<fieldset disabled={Boolean(c.busy)}><div className={`${layout.body} ${workbenchLayout.body}`}>
<div className={workbenchLayout.inputColumn}>
@ -106,28 +116,34 @@ function StandardEstimateWorkbench({ substrates, userId, canPushToLibrary = fals
loadError={workspace.loadError} onRetry={workspace.retrySpu}
busy={Boolean(c.busy)} onSpu={() => workspace.setDialog('spu')} onOpen={() => {
if (workspace.slots.length) workspace.setDialog('slots')
else void c.run('正在打开编号测算…', () => afterAppearance(() => {
else void c.run('正在打开编号测算…', () => afterAutosave(() => {
workspace.add()
workspace.setDialog('slots')
}))
}} onNumbers={returnToNumber ? () => void c.run('正在打开编号测算…', async () => {
await afterAppearance(() => workspace.choose(returnToNumber))
}} onNumbers={returnToNumber && !c.variantTrial ? () => void c.run('正在打开编号测算…', async () => {
await afterAutosave(() => workspace.choose(returnToNumber))
workspace.setDialog('slots')
}) : undefined} />
{(isBound || !userId) && <EstimateRecordSelect active={workspace.active} slots={workspace.slots}
records={c.records} recordId={c.record?.id} busy={Boolean(c.busy)}
onChoose={slot => void c.run('正在打开款式…', () => afterAppearance(() => workspace.choose(slot)))}
onAdjust={workspace.spu ? () => void c.run('正在读取款式…', async () => {
records={c.records} recordId={c.record?.id} busy={Boolean(c.busy || c.variantTrial)}
onChoose={slot => void c.run('正在打开款式…', () => afterAutosave(() => workspace.choose(slot)))}
onAdjust={workspace.spu && !c.variantTrial ? () => void c.run('正在读取款式…', async () => {
setBinding(await workspace.prepareBinding(workspace.spu!))
}) : undefined}
onCopy={workspace.spu && !c.variantTrial && workspace.spu.barcodes.some(item => workspace.copySources(item.slot.barcode).length)
? () => setCopyOpen(true) : undefined}
onOpen={id => void c.open(id)} />}
<EstimateStageTabs stage={tab} onStage={chooseStage} panelId={panelId} />
{isBound && <EstimateVariantStatus target={targetSize} actual={variantModelSize(c.document)}
source={c.document.variantCopy?.sourceBarcode} trial={c.variantTrial} message={c.message} warning={workspace.trialWarning}/>}
<EstimateStageTabs stage={tab} onStage={chooseStage} panelId={panelId} modelOnly={c.variantTrial}/>
</div>
<div className={workbenchLayout.inputScroll}>
<EstimateInputPanel controller={left} pagePaste imageFeedback={c.imageFeedback} onRetryImageSave={() => void c.save()} />
<EstimateInputPanel controller={left} pagePaste variantTrial={c.variantTrial} imageFeedback={c.imageFeedback} onRetryImageSave={() => void c.retryModelSave()} />
</div>
<EstimateWorkbenchActions controller={c} bound={isBound} canPushToLibrary={canPushToLibrary}
archiveEstimateId={productEstimate} canRemove={!isBound || Boolean(workspace.spu)} />
archiveEstimateId={productEstimate} canRemove={!isBound || Boolean(workspace.spu)}
onAdopt={c.variantTrial ? () => void c.adoptVariant(workspace.finishCopy) : undefined}
onDiscard={() => { if (window.confirm('退出本次试改,恢复查看目标条码的原模型?')) workspace.discardCopy() }} />
</div>
<section className={layout.main}>
{tab === 'cost' && <div className={layout.summary}>
@ -143,16 +159,9 @@ function StandardEstimateWorkbench({ substrates, userId, canPushToLibrary = fals
{tab==='model'&&<ModelWorkspace c={c} showDimensions={showDimensions} onDimensionsChange={setShowDimensions}
hardwareLibrary={hardwareLibrary}/>}
{tab==='sampling'&&<StageAssistantWorkspace stage="sampling" c={samplingController}><StandardSamplingPanel c={samplingController}/></StageAssistantWorkspace>}
{tab==='cost'&&<StandardRecognitionReview c={c}/>}
{tab==='cost'&&c.finishBom.standard.cabinet&&!c.stages.costDrawings.drawings&&<div className={layout.status} role="status">
{c.stages.costDrawings.error ? <>{c.stages.costDrawings.error} <Button size="small" variant="gray" onClick={c.stages.costDrawings.retry}>重试</Button></> : '正在生成模型配图…'}
</div>}
{tab==='cost'&&c.finishBom.missingPrice>0&&<div className={layout.status} role="status">
{c.finishBom.missingPrice} 行板件的花色单价待确认,请在 BOM 中填写单价后核算总成本。
</div>}
{tab==='cost'&&c.document.stageResults?.cost.notes?.length ? <div className={layout.status}>
{c.document.stageResults.cost.notes.map(note => <p key={note}>{note}</p>)}
</div> : null}
{tab==='cost'&&<StandardTemplateTable value={c.finishBom.standard} result={c.bomResult} drawings={c.stages.costDrawings.drawings} onChange={c.updateBom} imageUrl={c.stages.costDocument.imageUrl} initialRow={1} onExport={c.excel}/>}
{tab==='packing'&&<StageAssistantWorkspace stage="packing" c={c}><StandardPackingPanel c={c}/></StageAssistantWorkspace>}
</div>

View File

@ -1,8 +1,9 @@
'use client'
import dynamic from 'next/dynamic'
import { useMemo } from 'react'
import Button from '@/components/ui/Button'
import type { ModelRevision } from './ModelConversationPanel'
import type { ModelRevision } from '@/lib/reference-estimator/standard/model-versions'
import type { StandardController } from './useStandardEstimator'
import type { CabinetBoardPicking } from './useHardwareBoardConnections'
import type { EstimateHardwareLibraryState } from './useEstimateHardwareLibrary'
@ -10,9 +11,13 @@ import type { CabinetHardwareEdits } from './useCabinetHardwareEdits'
import styles from './workflow.module.css'
import workspace from './model-workspace.module.css'
import workbench from './estimate-workbench.module.css'
import { modelVersionHardware } from './model-version-hardware'
import type { SurfaceHardware } from '@/lib/reference-estimator/standard/surface-hardware'
import type { CornerGuardModels } from './useCornerGuardModels'
import type { CabinetSurfaceSelectionState } from './cabinet-surface-selection'
const ModelView=dynamic(()=>import('./CabinetModelView'),{ssr:false,loading:()=> <p className={styles.empty}>加载三维模型…</p>})
export function StandardModelPanel({c,historical,onReturn,showDimensions,onDimensionsChange,boardPicking,onToggleBoardPicking,previewLibrary,hardwareEditor}:{
export function StandardModelPanel({c,historical,onReturn,showDimensions,onDimensionsChange,boardPicking,onToggleBoardPicking,previewLibrary,hardwareEditor,cornerGuardPreview,cornerGuardModels,surfaceSelection}:{
c:StandardController;historical?:ModelRevision;onReturn:()=>void
showDimensions: boolean
onDimensionsChange: (show: boolean) => void
@ -20,21 +25,34 @@ export function StandardModelPanel({c,historical,onReturn,showDimensions,onDimen
onToggleBoardPicking?: () => void
previewLibrary?: EstimateHardwareLibraryState
hardwareEditor?: CabinetHardwareEdits
cornerGuardPreview?: SurfaceHardware
cornerGuardModels?: CornerGuardModels
surfaceSelection?: CabinetSurfaceSelectionState
}){
const model=historical?.model ?? c.standard.cabinet
const slot = c.document.workspaceSlot
const barcode = slot?.kind === 'barcode' ? slot.barcode : undefined
const recordId = c.record?.id
const items = previewLibrary?.data?.items
const hardwareSnapshot = useMemo(() => historical && modelVersionHardware(historical, items ?? [], barcode, recordId),
[historical, items, barcode, recordId])
if(!model)return <div className={workbench.modelSceneContent}><p className={styles.empty}>上传参考图并识别后显示模型。</p></div>
const hasPreviewParts = Boolean(model.previewParts?.some(part => !part.imageKey))
return <div className={workbench.modelSceneContent}>
{historical && <div className={workspace.historyPreview} role="status">
<strong>回看模型 V{historical.version}</strong>
<strong>回看 {historical.name}</strong>
<Button type="button" size="small" variant="gray" onClick={onReturn}>返回当前模型</Button>
</div>}
<ModelView model={model} readOnly={Boolean(historical)} appearance={historical ? undefined : c.document.modelAppearance}
<ModelView model={model} readOnly={Boolean(historical)} appearance={historical ? historical.appearance : c.document.modelAppearance}
showDimensions={showDimensions} onDimensionsChange={onDimensionsChange}
boardPicking={boardPicking} onToggleBoardPicking={onToggleBoardPicking}
previewLibrary={previewLibrary}
hardwareEditor={hardwareEditor}
surfaceHardware={historical ? undefined : c.document.surfaceHardware}
hardwareSnapshot={hardwareSnapshot}
surfaceHardware={historical ? historical.surfaceHardware : c.document.surfaceHardware}
cornerGuardPreview={historical ? undefined : cornerGuardPreview}
cornerGuardModels={cornerGuardModels}
surfaceSelection={surfaceSelection}
stepExport={historical ? undefined : {
disabled: hasPreviewParts || Boolean(c.busy),
title: hasPreviewParts ? '初版含预览部件,可下载 GLB' : '下载 SOLIDWORKS 可打开的模型',

View File

@ -0,0 +1,38 @@
'use client'
import { useRef } from 'react'
import { ImagePlus } from 'lucide-react'
import Button from '@/components/ui/Button'
import styles from './estimate-variant-copy.module.css'
export function VariantReferenceImage({ url, uploading, disabled, onUpload, onReset }: {
url: string
uploading: boolean
disabled: boolean
onUpload: (file: File) => void
onReset?: () => void
}) {
const picker = useRef<HTMLInputElement>(null)
return <section className={styles.referenceImage} aria-label="补充参考图">
<h3>补充参考图</h3>
<div className={styles.imagePreview}>
{url ? (
// eslint-disable-next-line @next/next/no-img-element -- authenticated object storage URL
<img src={url} alt="复制模型参考图" decoding="async" />
) : <ImagePlus size={22} aria-hidden="true" />}
</div>
<input ref={picker} type="file" accept="image/*" hidden aria-label="选择参考图片"
onChange={event => {
const file = event.target.files?.[0]
event.target.value = ''
if (file) onUpload(file)
}} />
<div className={styles.imageActions}>
<Button type="button" variant="gray" size="small" loading={uploading} disabled={disabled}
onClick={() => picker.current?.click()}>{uploading ? '上传中…' : url ? '更换图片' : '上传图片'}</Button>
{onReset && <Button type="button" variant="gray" size="small" disabled={disabled || uploading}
onClick={onReset}>撤销换图</Button>}
</div>
<p>支持 Ctrl+V 粘贴截图</p>
</section>
}

View File

@ -0,0 +1,59 @@
import { act, renderHook } from '@testing-library/react'
import type { AccessoryDraft } from '@/lib/intake-accessory-models'
import { cabinetInputSchema } from '@/lib/reference-estimator/standard/cabinet-contracts'
import { applyCabinetWorkflow } from '@/lib/reference-estimator/standard/cabinet-workflow'
import { type SurfaceHardware } from '@/lib/reference-estimator/standard/surface-hardware'
import { newStandardDocument } from '@/lib/reference-estimator/standard/workbook'
import { useCabinetCornerGuard } from './useCabinetCornerGuard'
import type { StandardController } from './useStandardEstimator'
import { useCornerGuardModels } from './useCornerGuardModels'
jest.mock('./useCornerGuardModels', () => ({ useCornerGuardModels: jest.fn() }))
test('previews without saving, can retry a failed confirmation, and saves one four-corner set', async () => {
jest.mocked(useCornerGuardModels).mockReturnValue({ ready: true, loading: false, models: {}, error: undefined, retry: jest.fn() })
const document = applyCabinetWorkflow(newStandardDocument(), cabinetInputSchema.parse({
referenceCase: '6G-960-B', grade: 'E1级', material: '生态板', topColor: '经典北美黑胡桃色', bodyColor: '荷花白色',
}))
const existing: SurfaceHardware = [{ boardKey: 'back-panel', accessoryId: 'clip', location: 'top-left' }]
const item: AccessoryDraft = { id: 'guard', module: 'accessory', category: '其他配件', kind: '其他配件',
code: 'QT-01', name: '硅胶防撞护角', material: '', price: null, revision: '',
dimensions: {}, pending: [], photos: [], model: null }
let controller = { document: { ...document, surfaceHardware: existing }, standard: document.standardTemplate,
saveHardwarePlacements: jest.fn() } as unknown as StandardController
const save = jest.mocked(controller.saveHardwarePlacements).mockImplementation(async (edits, seams, surface) => {
controller = { ...controller, document: { ...controller.document, hardwarePlacementEdits: edits,
hardwareSeamEdits: seams, surfaceHardware: surface } }
return true
})
const { result, rerender } = renderHook(({ c }) => useCabinetCornerGuard(c), { initialProps: { c: controller } })
act(() => { result.current.open(item) })
expect(result.current.preview?.rows).toHaveLength(4)
jest.mocked(useCornerGuardModels).mockReturnValue({ ready: false, loading: false, error: '加载失败', models: undefined, retry: jest.fn() })
rerender({ c: controller })
await act(async () => { await result.current.confirm() })
expect(save).not.toHaveBeenCalled()
jest.mocked(useCornerGuardModels).mockReturnValue({ ready: true, loading: false, models: {}, error: undefined, retry: jest.fn() })
rerender({ c: controller })
act(() => result.current.cancel())
expect(result.current.preview).toBeUndefined()
expect(save).not.toHaveBeenCalled()
act(() => { result.current.open(item) })
save.mockResolvedValueOnce(false)
await act(async () => { await result.current.confirm() })
expect(result.current.feedback).toMatchObject({ error: true })
expect(result.current.preview?.rows).toHaveLength(4)
expect(controller.document.surfaceHardware).toEqual(existing)
await act(async () => { await result.current.confirm() })
rerender({ c: controller })
expect(result.current.preview).toBeUndefined()
expect(controller.document.surfaceHardware).toHaveLength(5)
expect(controller.document.surfaceHardware?.[0]).toEqual(existing[0])
act(() => { result.current.open(item) })
await act(async () => { await result.current.confirm() })
expect(save).toHaveBeenCalledTimes(2)
expect(result.current.feedback?.text).toContain('QT-01 × 4')
expect(controller.document.surfaceHardware).toHaveLength(5)
})

View File

@ -0,0 +1,251 @@
import { act, renderHook } from '@testing-library/react'
import { Group } from 'three'
import { accessoryDowelCad } from '@/lib/accessory-model-spec'
import { estimateDocumentSchema } from '@/lib/reference-estimator/contracts'
import type { AccessoryDraft } from '@/lib/intake-accessory-models'
import type { AccessoryMachining } from '@/lib/intake-accessory-machining'
import { cabinetInputSchema, type CabinetModel, type CabinetPart } from '@/lib/reference-estimator/standard/cabinet-contracts'
import { cabinetHardwarePlan } from '@/lib/reference-estimator/standard/cabinet-hardware-plan'
import { cabinetHardwareMachining, type HardwareHole } from '@/lib/reference-estimator/standard/cabinet-hardware-machining'
import { CabinetHoleIndex } from '@/lib/reference-estimator/standard/cabinet-hole-collisions'
import { cabinetPointsBySeam, opposingDowelSeams } from '@/lib/reference-estimator/standard/cabinet-through-dowel'
import { seamPlacement } from '@/lib/reference-estimator/standard/cabinet-sg0164-seam'
import { applyCabinetWorkflow } from '@/lib/reference-estimator/standard/cabinet-workflow'
import { readSeamEdits, hardwareSeamEditsSchema } from '@/lib/reference-estimator/standard/hardware-seam-edits'
import { hardwarePlacementEditsSchema } from '@/lib/reference-estimator/standard/hardware-placement-edits'
import { resolveStageHardware, applyStageHardware } from '@/lib/reference-estimator/standard/stage-hardware'
import { newStandardDocument } from '@/lib/reference-estimator/standard/workbook'
import { stageCabinetHardwareBatch } from './cabinet-hardware-batch'
import { hardwareMountKey, machiningModelParts } from './cabinet-machining-model'
import { modelVersionHardware } from './model-version-hardware'
import { useCabinetHardwareEdits } from './useCabinetHardwareEdits'
import type { StandardController } from './useStandardEstimator'
const estimate = applyCabinetWorkflow(newStandardDocument(), cabinetInputSchema.parse({
referenceCase: '6G-960-B', grade: 'E1级', material: '生态板', topColor: '经典北美黑胡桃色', bodyColor: '荷花白色',
}))
const source = estimate.standardTemplate!.cabinet!
function board(code: string, role: CabinetPart['role'], size: CabinetPart['size'], start: CabinetPart['size']): CabinetPart {
return { ...source.parts[0], id: code, code, name: code, role, size, positions: [start],
quantity: 1, length: Math.max(...size), width: 280, thickness: 15, profile: undefined,
solid: undefined, machining: undefined, notch: null }
}
const model: CabinetModel = { ...source, input: { ...source.input, width: 400, height: 615 }, parts: [
board('05', 'shelf', [400, 300, 15], [0, 0, 300]),
board('06', 'divider', [15, 280, 300], [150, 0, 0]),
board('09', 'divider', [15, 280, 300], [150, 0, 315]),
], connections: [] }
const targets = cabinetHardwarePlan(model).entries.map(entry => entry.seam)
const state = () => ({ changes: new Map(), points: new Map(targets.map(seam => [seam.key, []])), edits: {} })
const layout = { count: 2, pitch: 64, alignment: 'center', edge: 0 } as const
let sequence = 0
const id = () => '00000000-0000-4000-8000-' + String(++sequence).padStart(12, '0')
const accessory = (key: string, kind: string, machining?: AccessoryMachining): AccessoryDraft => ({
id: key, code: key, name: kind, kind, module: 'connector', category: '连接件', material: '',
price: null, revision: '', dimensions: {}, pending: [], photos: [], machining,
model: { id: key, createdAt: '', dimensions: {}, pending: [], note: '', url: '/model.glb' },
})
const dowel: AccessoryDraft = { ...accessory('YBS-02', '圆棒榫'), spec: 'Ø8×30',
model: { ...accessory('YBS-02', '圆棒榫').model!, cad: accessoryDowelCad({ diameter: 8, length: 30 }) } }
function camKit(depth: number) {
const rule: AccessoryMachining = { type: 'cam', insertId: 'INS', rodId: 'ROD', wheelId: 'CAM',
insert: { diameterMm: 10, depthMm: depth }, wheel: { diameterMm: 15, depthMm: 10 },
rodDiameterMm: 6, rodLengthMm: 40, engagementMm: Math.min(10, depth) }
const item = { ...accessory('KIT', '标准三合一套件', rule), model: null }
const component = (key: string, kind: string, role: 'insert' | 'rod' | 'wheel'): AccessoryDraft => {
const part = accessory(key, kind)
return { ...part, model: { ...part.model!, installationAnchors: [{ role, partPath: '0/0', partName: key,
originMm: [0, 0, 0], direction: '+y', ...(role === 'wheel' ? { slotDirection: '+z' as const } : {}) }] } }
}
return [item, component('INS', '预埋件', 'insert'), component('ROD', '连接杆', 'rod'), component('CAM', '偏心轮', 'wheel')]
}
test('two real opposite contacts produce one dowel per position, three bores, and one BOM count', () => {
expect(targets).toHaveLength(2)
expect(opposingDowelSeams(...targets as [typeof targets[number], typeof targets[number]])).toBe(true)
const [row] = stageCabinetHardwareBatch(targets, dowel, [dowel], layout, state(), id)
expect(row.opposite).toBeDefined()
expect(row.mounts).toHaveLength(2)
for (const { point, hardware } of row.mounts) {
expect(cabinetHardwareMachining(point, hardware).holes.map(hole =>
[hole.board.part.code, hole.diameter, hole.depth, hole.kind === 'through']))
.toEqual([['05', 8, 15, true], [point.oppositeDowelPoint!.receiver.part.code, 8, 10.5, false],
[point.receiver.part.code, 8, 10.5, false]])
expect(machiningModelParts(point, hardware, { [hardwareMountKey(dowel.id, 'dowel')]: { mount: new Group(), length: 30 } })[0].entry[2])
.toBe(307.5)
}
const edits = hardwarePlacementEditsSchema.parse(Object.fromEntries(row.mounts.map(mount => [mount.point.key, mount.hardware])))
const seams = hardwareSeamEditsSchema.parse({ seams: [{ key: row.seam.key,
offsets: Object.fromEntries(row.mounts.map(({ point }, i) => [point.id, row.positions[i]])),
rows: [{ id: id(), pointIds: row.mounts.map(({ point }) => point.id), alignment: 'center' }] }] })
const reloaded = cabinetPointsBySeam(new Map(targets.map(seam => [seam.key, seam])),
new Map(readSeamEdits(seams).map(seam => [seam.key, seam])), edits)
expect([...reloaded.values()].flat()).toHaveLength(2)
expect([...reloaded.values()].flat().every(point => point.oppositeDowelPoint)).toBe(true)
const document = estimateDocumentSchema.parse({ ...estimate, standardTemplate: { ...estimate.standardTemplate!, cabinet: model },
hardwarePlacementEdits: edits, hardwareSeamEdits: seams })
const history = modelVersionHardware({ id: 'test', name: '三板样板', model,
hardwarePlacementEdits: document.hardwarePlacementEdits, hardwareSeamEdits: document.hardwareSeamEdits }, [dowel])
expect(history?.plan).toHaveLength(2)
expect(history?.plan.every(point => Boolean(point.oppositeDowelPoint))).toBe(true)
const hardware = resolveStageHardware(document, undefined, [dowel])
expect(hardware.connections).toHaveLength(2)
expect(hardware.connections.every(connection => connection.count === 1 && connection.holes.length === 3)).toBe(true)
expect(applyStageHardware(document.standardTemplate!, hardware).summary).toBe('YBS-02 × 2')
})
test.each([6, 10])('opposite cam rows at %i mm insert depth align or move by exactly 32 mm as needed', depth => {
const items = camKit(depth)
const rows = stageCabinetHardwareBatch(targets, items[0], items, layout, state(), id)
expect(rows).toHaveLength(2)
expect(rows.map(row => row.mounts.length)).toEqual([2, 2])
expect(rows[0].stagger).toBe(0)
expect(rows[1].stagger).toBe(depth === 6 ? 0 : 32)
})
test('a short dowel and a groove on the second board block the whole preview', () => {
const short = { ...dowel, model: { ...dowel.model!, cad: accessoryDowelCad({ diameter: 8, length: 12 }) } }
expect(() => stageCabinetHardwareBatch(targets, short, [short], layout, state(), id)).toThrow('长度不足')
const blocked = targets.map(seam => ({ ...seam, template: { ...seam.template, clearance: { low: 150, high: 165,
grooves: new Map([[model.parts[2], [{ min: [0, 0, 0], max: [15, 280, 12], width: 15, depth: 12 }]]]) } } }))
expect(() => stageCabinetHardwareBatch(blocked, dowel, [dowel], layout, state(), id)).toThrow('与板槽或缺口相交')
})
test('orthogonal bores collide only where their finite cylinders intersect', () => {
const index = new CabinetHoleIndex()
const board = seamPlacement(targets[0], 'test', 50).donor
index.add([{ board, kind: 'rod', diameter: 10, depth: 10, entry: [0, 0, 0], direction: [1, 0, 0] }])
const perpendicular: HardwareHole = { board, kind: 'wheel', diameter: 10, depth: 10,
entry: [14, 4, 7], direction: [0, 1, 0] }
expect(index.conflict([perpendicular])).toBeUndefined()
expect(index.conflict([{ ...perpendicular, entry: [14, 4, 6] }])).toBeUndefined()
expect(index.conflict([{ ...perpendicular, entry: [14, 4, 5] }])).toContain('相撞')
})
test('multi seam preview saves once, reloads as two dowels, and moves selected holes on all three boards', async () => {
let current = { document: { ...estimate, standardTemplate: { ...estimate.standardTemplate!, cabinet: model } }, busy: '',
saveHardwarePlacements: jest.fn() } as unknown as StandardController
const save = jest.mocked(current.saveHardwarePlacements).mockImplementation(async (edits, seams) => {
current = { ...current, document: { ...current.document, hardwarePlacementEdits: edits, hardwareSeamEdits: seams } }
return true
})
const kit = camKit(10)
const items = [dowel, ...kit]
const { result, rerender } = renderHook(({ c }) => useCabinetHardwareEdits(c, model, items), { initialProps: { c: current } })
act(() => result.current.seamPicking.start())
act(() => result.current.seamPicking.boards.forEach(board => result.current.seamPicking.pick(board.key)))
act(() => result.current.stageAddition(layout))
await act(async () => { await result.current.addHardware(dowel) })
expect(result.current.pendingAddition?.preview).toHaveLength(1)
expect(save).not.toHaveBeenCalled()
await act(async () => { await result.current.confirmBatch() })
rerender({ c: current })
expect(save).toHaveBeenCalledTimes(1)
expect(result.current.selection).toHaveLength(2)
const selected = result.current.selectedRows[0]
const selectionRevision = result.current.selectionRevision
await act(async () => { await result.current.moveRow(selected.seam, selected.row,
{ count: 2, pitch: 96, alignment: 'front', edge: 30 }) })
rerender({ c: current })
expect(result.current.selection.map(point => point.center[1])).toEqual([30, 126])
expect(result.current.selection.map(point => point.oppositeDowelPoint?.center[1])).toEqual([30, 126])
for (const [count, positions] of [[3, [30, 126, 222]], [1, [30]], [2, [30, 126]]] as const) {
const { seam, row } = result.current.selectedRows[0]
await act(async () => { expect(await result.current.moveRow(seam, row,
{ count, pitch: 96, alignment: 'front', edge: 30 })).toBe(true) })
current = { ...current, document: estimateDocumentSchema.parse(current.document) }
rerender({ c: current })
expect(result.current.selection.map(point => point.center[1])).toEqual(positions)
expect(result.current.selectionRevision).toBe(selectionRevision)
expect(result.current.selection.map(point => point.oppositeDowelPoint?.center[1])).toEqual(positions)
expect(Object.keys(current.document.hardwarePlacementEdits!)).toHaveLength(count)
const hardware = resolveStageHardware(current.document, undefined, items)
expect(hardware.connections).toHaveLength(count)
expect(hardware.connections.every(connection => connection.count === 1 && connection.holes.length === 3)).toBe(true)
}
const beforeFailure = current.document
const resizing = result.current.selectedRows[0]
const expanded = { count: 3, pitch: 96, alignment: 'front', edge: 30 } as const
save.mockRejectedValueOnce(new Error('save failed'))
await act(async () => { expect(await result.current.moveRow(resizing.seam, resizing.row, expanded)).toBe(false) })
expect(current.document).toBe(beforeFailure)
expect(result.current.selection).toHaveLength(2)
expect(result.current.status).toBe('error')
await act(async () => { expect(await result.current.moveRow(resizing.seam, resizing.row, expanded)).toBe(true) })
rerender({ c: current })
expect(result.current.selection).toHaveLength(3)
await act(async () => { await result.current.replace(kit[0]) })
expect(save).toHaveBeenCalledTimes(7)
expect(result.current.placementIssue).toContain('连接三块板')
})
test('resizing checks opposite holes and keeps unselected points on the same and other seams', async () => {
const items = camKit(10)
const [first, other] = stageCabinetHardwareBatch(targets, items[0], items, layout, state(), id)
const firstPoints = [...first.seam.defaults, seamPlacement(first.seam, id(), first.positions[1] + 64)]
const firstPositions = [...first.positions, first.positions[1] + 64]
const firstRow = { id: id(), pointIds: firstPoints.map(point => point.id), alignment: 'front' as const }
const otherRow = { id: id(), pointIds: other.mounts.map(({ point }) => point.id), alignment: layout.alignment }
const document = estimateDocumentSchema.parse({ ...estimate,
hardwarePlacementEdits: Object.fromEntries([
...firstPoints.map(point => [point.key, first.mounts[0].hardware]),
...other.mounts.map(({ point, hardware }) => [point.key, hardware]),
]),
hardwareSeamEdits: { seams: [
{ key: first.seam.key, offsets: Object.fromEntries(firstRow.pointIds.map((key, i) => [key, firstPositions[i]])), rows: [firstRow] },
{ key: other.seam.key, offsets: Object.fromEntries(otherRow.pointIds.map((key, i) => [key, other.positions[i]])), rows: [otherRow] },
] },
})
let c = { document, busy: '', saveHardwarePlacements: jest.fn() } as unknown as StandardController
const save = jest.mocked(c.saveHardwarePlacements).mockImplementation(async (edits, seams) => {
c = { ...c, document: estimateDocumentSchema.parse({ ...c.document, hardwarePlacementEdits: edits, hardwareSeamEdits: seams }) }
return true
})
const { result, rerender } = renderHook(({ controller }) => useCabinetHardwareEdits(controller, model, items),
{ initialProps: { controller: c } })
const chosen = new Set([...firstPoints.slice(0, 2), ...other.mounts.map(({ point }) => point)].map(point => point.key))
act(() => result.current.select(result.current.plan.filter(point => chosen.has(point.key))))
const selected = result.current.selectedRows.find(({ seam }) => seam.key === first.seam.key)!
const selectionOrder = result.current.selectedRows.map(({ seam }) => seam.key)
const revision = result.current.selectionRevision
const collision = { count: 3, pitch: 32, alignment: 'front', edge: other.positions[0] } as const
expect(result.current.checkLayout(collision, selected.row, selected.seam)).toHaveLength(3)
await act(async () => { expect(await result.current.moveRow(selected.seam, selected.row, collision)).toBe(false) })
expect(result.current.placementIssue).toContain('相撞')
expect(save).not.toHaveBeenCalled()
expect(result.current.selection).toHaveLength(4)
await act(async () => { expect(await result.current.moveRow(selected.seam, selected.row,
{ count: 1, pitch: 0, alignment: 'front', edge: first.positions[0] })).toBe(true) })
rerender({ controller: c })
expect(result.current.selectedRows.map(({ seam }) => seam.key)).toEqual(selectionOrder)
expect(result.current.selectionRevision).toBe(revision)
expect(save).toHaveBeenCalledTimes(1)
expect(c.document.hardwarePlacementEdits![firstPoints[1].key]).toBeNull()
expect(result.current.plan.some(point => point.key === firstPoints[1].key)).toBe(false)
const next = new Map(readSeamEdits(c.document.hardwareSeamEdits).map(change => [change.key, change]))
expect(next.get(first.seam.key)?.rows?.map(row => row.pointIds)).toEqual([[firstPoints[2].id], [firstPoints[0].id]])
expect(next.get(first.seam.key)?.offsets[firstPoints[2].id]).toBe(firstPositions[2])
expect(next.get(other.seam.key)).toEqual(readSeamEdits(document.hardwareSeamEdits)[1])
expect(result.current.selection.map(point => point.key).sort()).toEqual([...chosen].filter(key => key !== firstPoints[1].key).sort())
const remaining = result.current.selection.slice(1)
act(() => result.current.select(remaining))
expect(result.current.selection.map(point => point.key)).toEqual(remaining.map(point => point.key))
expect(result.current.selectionRevision).toBe(revision + 1)
})
test('a preview is invalidated when the document changes before confirmation', async () => {
const c = { document: { ...estimate, standardTemplate: { ...estimate.standardTemplate!, cabinet: model } }, busy: '',
saveHardwarePlacements: jest.fn().mockResolvedValue(true) } as unknown as StandardController
const { result, rerender } = renderHook(({ controller }) => useCabinetHardwareEdits(controller, model, [dowel]),
{ initialProps: { controller: c } })
act(() => result.current.seamPicking.start())
act(() => result.current.seamPicking.boards.forEach(board => result.current.seamPicking.pick(board.key)))
act(() => result.current.stageAddition(layout))
await act(async () => { await result.current.addHardware(dowel) })
rerender({ controller: { ...c, document: { ...c.document, hardwarePlacementEdits: {} } } })
await act(async () => { await result.current.confirmBatch() })
expect(c.saveHardwarePlacements).not.toHaveBeenCalled()
expect(result.current.placementIssue).toContain('重新选用五金')
})

View File

@ -0,0 +1,133 @@
import type { AccessoryDraft } from '@/lib/intake-accessory-models'
import { readDowelModelGeometry } from '@/lib/intake-accessory-dowel-model'
import { cabinetHardwareMachining, type HardwareHole } from '@/lib/reference-estimator/standard/cabinet-hardware-machining'
import { attachOppositeDowelPoint, opposedDowelSpan, opposingDowelSeams } from '@/lib/reference-estimator/standard/cabinet-through-dowel'
import { CabinetHoleIndex } from '@/lib/reference-estimator/standard/cabinet-hole-collisions'
import { seamPlacement, seamOffset, type CabinetSeam } from '@/lib/reference-estimator/standard/cabinet-sg0164-seam'
import { maxCabinetSeams, maxSeamOffsets, seamPitch, type SeamEdit } from '@/lib/reference-estimator/standard/hardware-seam-edits'
import { fitsSeamRow, layoutSeamRow, type SeamRowLayout } from '@/lib/reference-estimator/standard/hardware-seam-rows'
import { maxHardwarePlacementEdits, type HardwarePlacementEdits, type PlacementHardware } from '@/lib/reference-estimator/standard/hardware-placement-edits'
import type { CamPlacement } from './cabinet-cam-preview'
import { mountCabinetHardwareChoice, resolveCabinetHardwareBase, resolveCabinetHardwareChoice } from './cabinet-hardware-choice'
type Mount = { point: CamPlacement; hardware: PlacementHardware }
type Group = { seam: CabinetSeam; opposite?: CabinetSeam }
type BatchRow = Group & { positions: number[]; mounts: Mount[]; stagger: number }
type LayoutState = {
changes: ReadonlyMap<string, SeamEdit>; points: ReadonlyMap<string, CamPlacement[]>; edits: HardwarePlacementEdits
}
export function boreIndex(points: Iterable<CamPlacement>, edits: HardwarePlacementEdits, exclude = new Set<string>()) {
const index = new CabinetHoleIndex()
for (const point of points) {
if (!exclude.has(point.key)) index.add(cabinetHardwareMachining(point, edits[point.key]).holes)
}
return index
}
export function validateMounts(mounts: readonly Mount[], index: CabinetHoleIndex, checkGeometry = false) {
const internal = new CabinetHoleIndex()
const all: HardwareHole[] = []
for (const { point, hardware } of mounts) {
if (!hardware.machining) continue
const { holes, pending } = cabinetHardwareMachining(point, { ...hardware, machiningPending: undefined })
if (pending && (checkGeometry || hardware.machiningEstimated || hardware.throughDowel || point.clearance)) throw new Error(pending)
const conflict = index.conflict(holes) ?? internal.conflict(holes)
if (conflict) throw new Error(conflict)
internal.add(holes)
all.push(...holes)
}
return all
}
export function fitsCabinetHardwareRow(seam: CabinetSeam, positions: number[], state: LayoutState, moving: CamPlacement[] = []) {
const ids = new Set(moving.map(point => point.key))
const offsets = state.changes.get(seam.key)?.offsets ?? {}
const occupied = (state.points.get(seam.key) ?? []).filter(point => !ids.has(point.key)).map(point => seamOffset(seam, point))
const replaced = moving.filter(point => Object.hasOwn(offsets, point.id)).length
return Object.keys(offsets).length - replaced + positions.length <= maxSeamOffsets && fitsSeamRow(seam.length, positions, occupied)
}
function batchGroups(seams: readonly CabinetSeam[], pairDowel: boolean): Group[] {
const paired = new Set<CabinetSeam>()
return seams.flatMap(seam => {
if (paired.has(seam)) return []
const opposite = pairDowel ? seams.find(other => !paired.has(other) && opposingDowelSeams(seam, other)) : undefined
paired.add(seam)
if (opposite) paired.add(opposite)
return [{ seam, opposite }]
})
}
export function throughDowelReference(item: AccessoryDraft, point: CamPlacement, opposite: CabinetSeam, base: PlacementHardware) {
const shape = readDowelModelGeometry(item.kind, item.model)
const span = opposedDowelSpan(point)
if (!shape?.diameter || !shape.length || !span) throw new Error('三板圆棒榫需要可读的模型尺寸及两条同轴接缝。')
const inserted = (shape.length - span.thickness) / 2
if (inserted <= 0) throw new Error('圆棒榫长度不足以穿过中板并插入两端。')
const endDepthMm = Math.round((inserted + 3) * 1000) / 1000
const end = { diameterMm: shape.diameter, depthMm: endDepthMm }
return { ...base, machining: { type: 'dowel', first: end, second: end }, machiningEstimated: true,
machiningPending: undefined, reverse: false, dowelCenterOffsetMm: undefined,
throughDowel: { oppositeSeamKey: opposite.key, diameterMm: shape.diameter, endDepthMm },
} satisfies PlacementHardware
}
function sharedLayout({ seam, opposite }: Group, layout: SeamRowLayout) {
const start = opposite ? Math.max(seam.start, opposite.start) : seam.start
const end = opposite ? Math.min(seam.start + seam.length, opposite.start + opposite.length) : seam.start + seam.length
return layoutSeamRow(end - start, layout).map(offset => start - seam.start + offset)
}
export function stageCabinetHardwareBatch(targets: readonly CabinetSeam[], item: AccessoryDraft, items: readonly AccessoryDraft[],
layout: SeamRowLayout, state: LayoutState, id: () => string) {
const rows: BatchRow[] = []
const isDowel = item.kind === '圆棒榫'
const common = !isDowel ? resolveCabinetHardwareChoice(item, items, 'add').reference : undefined
if (targets.length > 1 && common?.machiningPending) throw new Error(common.machiningPending)
const groups = batchGroups(targets, isDowel)
const newlyEdited = groups.filter(({ seam }) => !state.changes.has(seam.key)).length
if (newlyEdited + state.changes.size > maxCabinetSeams ||
Object.keys(state.edits).length + groups.length * layout.count > maxHardwarePlacementEdits)
throw new Error('已达到测算单的连接点修改上限,请减少所选接缝或数量。')
const base = isDowel ? resolveCabinetHardwareBase(item, items) : undefined
const index = boreIndex([...state.points.values()].flat(), state.edits)
const allSeams = new Map(targets.map(seam => [seam.key, seam]))
for (const group of groups) {
const { seam, opposite } = group
const initial = sharedLayout(group, layout)
const pointIds = initial.map(id)
// Only move the second of two opposing cam rows automatically.
const canStagger = common?.machining?.type === 'cam' && rows.some(row => opposingDowelSeams(seam, row.seam))
const offsets = [0]
if (canStagger) for (let n = seamPitch; n < seam.length; n += seamPitch) offsets.push(n, -n)
let problem = ''
let accepted = false
for (const stagger of offsets) {
const positions = initial.map(value => value + stagger)
if (!fitsCabinetHardwareRow(seam, positions, state) ||
(opposite && !fitsCabinetHardwareRow(opposite, positions.map(value => value + seam.start - opposite.start), state))) continue
try {
const rawPoints = positions.map((offset, i) => seamPlacement(seam, pointIds[i], offset))
const mounts = rawPoints.map(point => {
if (opposite && base) {
const linked = attachOppositeDowelPoint(point, seam, allSeams, opposite.key)
return { point: linked, hardware: throughDowelReference(item, linked, opposite, base) }
}
const reference = common ?? resolveCabinetHardwareChoice(item, items, 'add', undefined, [point]).reference
if (targets.length > 1 && reference.machiningPending) throw new Error(reference.machiningPending)
return { point, hardware: mountCabinetHardwareChoice(point, reference) }
})
index.add(validateMounts(mounts, index, true))
rows.push({ seam, opposite, positions, mounts, stagger })
accepted = true
break
} catch (error) {
problem ||= error instanceof Error ? error.message : '孔位不可用'
}
}
if (!accepted) throw new Error(seam.boards.map(board => board.label).join(' + ') + ':' +
(problem || (opposite ? '两条接缝没有可共用的孔位,请调整排布。' : '此排布放不下,请调整位置或间距。')))
}
return rows
}

View File

@ -1,5 +1,6 @@
import { accessorySpec, type AccessoryDraft } from '@/lib/intake-accessory-models'
import { accessoryStandaloneProcessingType, camComponentMatches } from '@/lib/intake-accessory-machining-assets'
import { accessoryStandaloneProcessingType, camComponentMatches, machiningModelAnchor } from '@/lib/intake-accessory-machining-assets'
import { readDowelModelGeometry } from '@/lib/intake-accessory-dowel-model'
import { resolveConversationHardware } from '@/lib/reference-estimator/standard/conversation-hardware-catalog'
import { hasUsableHardwareModel } from '@/lib/reference-estimator/standard/hardware-model-availability'
import { isRetiredTrialHardware, type PlacementHardware } from '@/lib/reference-estimator/standard/hardware-placement-edits'
@ -7,20 +8,39 @@ import { cabinetHardwareMachining } from '@/lib/reference-estimator/standard/cab
import type { CamPlacement } from './cabinet-cam-preview'
import { cabinetScrewCode } from './cabinet-screw-model'
import { dowelInstallation } from './cabinet-dowel-model'
import { checkCabinetDowelHoles, dowelShallowSide, draftCabinetDowelHoles } from '@/lib/reference-estimator/standard/cabinet-dowel-hole-draft'
export function resolveCabinetHardwareChoice(item: AccessoryDraft, items: readonly AccessoryDraft[],
mode: 'add' | 'replace', confirmedDepth?: number) {
export function resolveCabinetHardwareBase(item: AccessoryDraft, items: readonly AccessoryDraft[]): PlacementHardware {
if (!hasUsableHardwareModel(item, items) || !items.some(value => value.id === item.id) || isRetiredTrialHardware(item))
throw new Error('此配件没有可用模型,请刷新配件库后重试。')
const spec = item.spec || accessorySpec(item.kind, item.model?.dimensions ?? item.dimensions)
const reference: PlacementHardware = {
return {
id: item.id, code: item.code.slice(0, 48), name: item.name.slice(0, 70), spec: spec === '—' ? '' : spec.slice(0, 320),
...(item.machining !== undefined ? { machining: item.machining } : {}),
}
}
export function resolveCabinetHardwareChoice(item: AccessoryDraft, items: readonly AccessoryDraft[],
mode: 'add' | 'replace', confirmedDepth?: number, additionPoints?: readonly CamPlacement[]) {
const reference = resolveCabinetHardwareBase(item, items)
if (item.model?.assembly || item.machining) {
const resolved = resolveConversationHardware(item, items, confirmedDepth)
const { machining, machiningPending } = resolved.reference
return { reference: { ...reference, machining, machiningPending }, wheelDepths: resolved.wheelDepths }
const { machining, machiningPending, camLock } = resolved.reference
return { reference: { ...reference, machining, machiningPending, ...(camLock ? { camLock } : {}) }, wheelDepths: resolved.wheelDepths }
}
if (mode === 'add' && additionPoints?.length && item.kind === '圆棒榫') {
if (item.drilling?.holeType === 'bidirectional') {
if (!machiningModelAnchor(item, 'dowel') && !readDowelModelGeometry(item.kind, item.model)?.anchor)
throw new Error('配件库已设置加工参数,请补齐圆棒榫的安装基准。')
const { diameterMm, depthMm, reverseDepthMm } = item.drilling
const machining = { type: 'dowel', first: { diameterMm, depthMm: reverseDepthMm }, second: { diameterMm, depthMm } } as const
checkCabinetDowelHoles(item.id, machining, additionPoints)
return { reference: { ...reference, machining }, wheelDepths: [] }
}
if (item.drilling && (item.drilling.holeType !== 'blind' || !dowelShallowSide(additionPoints[0])))
throw new Error('配件库已设置加工参数,请确认接缝两块板的双向孔深。')
const draft = draftCabinetDowelHoles(item, additionPoints)
return { reference: { ...reference, ...draft, machiningEstimated: true as const }, wheelDepths: [] }
}
if (!item.machining && (['rod', 'wheel', 'insert'] as const).some(role => camComponentMatches(item, role)))
throw new Error('这是套件里的单件,请选择包含它的三合一套件。')
@ -30,9 +50,18 @@ export function resolveCabinetHardwareChoice(item: AccessoryDraft, items: readon
return { reference, wheelDepths: [] }
}
export function inspectCabinetHardwareChoice(item: AccessoryDraft, items: readonly AccessoryDraft[], mode: 'add' | 'replace') {
export function inspectCabinetHardwareChoice(item: AccessoryDraft, items: readonly AccessoryDraft[], mode: 'add' | 'replace',
additionPoints?: readonly CamPlacement[], batch?: boolean, throughDowelReplacement?: boolean) {
try {
return { ...resolveCabinetHardwareChoice(item, items, mode), issue: undefined }
if (mode === 'replace' && throughDowelReplacement) {
const geometry = readDowelModelGeometry(item.kind, item.model)
if (!geometry?.length || !geometry.diameter) throw new Error('这处五金连接三块板,请换用有模型尺寸的圆棒榫。')
return { reference: resolveCabinetHardwareBase(item, items), wheelDepths: [], issue: undefined }
}
if (batch && mode === 'add' && readDowelModelGeometry(item.kind, item.model)?.length) {
return { reference: resolveCabinetHardwareBase(item, items), wheelDepths: [], issue: undefined }
}
return { ...resolveCabinetHardwareChoice(item, items, mode, undefined, additionPoints), issue: undefined }
} catch (error) {
return { reference: undefined, wheelDepths: [], issue: error instanceof Error ? error.message : '此配件暂不能选用。' }
}
@ -49,6 +78,6 @@ export function mountCabinetHardwareChoice(point: CamPlacement, hardware: Placem
const opposite = { ...reference, reverse: true }
if (!geometryIssue(opposite)) return opposite
}
if (point.clearance || hardware.machining.type === 'cam') throw new Error(issue)
if (point.clearance || hardware.throughDowel || hardware.machining.type === 'cam') throw new Error(issue)
return reference
}

View File

@ -30,7 +30,6 @@
border-radius: 4px;
background: var(--obs-shell-surface, #fff);
}
.seamRows { max-height: 132px; overflow: auto; }
.seamRows button, .seamBoardChoices button, .seamList button {
padding: 4px 7px;
border-radius: 4px;
@ -43,12 +42,32 @@
.seamRows button span { color: var(--obs-shell-muted, #59636b); }
.seamRows button .seamWarning { color: #8b4a14; }
.selection .seamSummary { color: var(--obs-shell-text, #263540); font-variant-numeric: tabular-nums; }
.seamEditor[data-editing="true"] {
border-inline-start: 2px solid #4384bb;
padding-inline-start: 8px;
}
.pointChoices { display: flex; flex-wrap: wrap; gap: 5px; }
.pointChoices button {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 4px 7px;
border: 1px solid var(--obs-shell-border, #dce4e9);
border-radius: 4px;
background: var(--obs-shell-surface, #fff);
font-size: 11px;
color: var(--obs-shell-text, #263540);
}
.pointChoices button:hover { background: var(--obs-shell-hover-bg, #e8f1f8); }
.pointChoices button:disabled { opacity: .5; }
.seamRows button:hover, .seamBoardChoices button:hover, .seamList button:hover,
.seamRows button[aria-pressed="true"], .seamBoardChoices button[aria-pressed="true"],
.seamList button[aria-pressed="true"] { background: #e8f1f8; }
.seamBoardChoices { display: flex; flex-wrap: wrap; gap: 3px; }
.seamList { display: grid; max-height: 108px; overflow: auto; }
.seamList { display: grid; }
.seamList label { display: flex; align-items: center; gap: 6px; font-size: 12px; }
.selection details > summary { font-size: 11px; cursor: pointer; }
.holeDetails > summary { padding-block: 4px; }
.boxOverlay {
position: absolute;
inset: 0;

View File

@ -0,0 +1,58 @@
import { attachOppositeDowelPoint } from '@/lib/reference-estimator/standard/cabinet-through-dowel'
import { splitUnmovedSeamRows, type CabinetSeamRow } from '@/lib/reference-estimator/standard/cabinet-seam-rows'
import type { HardwarePlacementEdits, PlacementHardware } from '@/lib/reference-estimator/standard/hardware-placement-edits'
import type { SeamEdit, SeamRowAlignment } from '@/lib/reference-estimator/standard/hardware-seam-edits'
import { sameModelValue } from '@/lib/reference-estimator/standard/model-change-details'
import type { CamPlacement } from './cabinet-cam-preview'
import { boreIndex, validateMounts } from './cabinet-hardware-batch'
import { seamPlacement, type CabinetSeam } from './cabinet-sg0164-seam'
const comparableHardware = (item: PlacementHardware) => ({
...item, reverse: item.reverse ?? false, lateralMm: item.lateralMm ?? 0,
})
export function stageCabinetHardwareRow({ seam, row, positions, alignment, current, seamMap, plan, stored, edits }: {
seam: CabinetSeam; row: CabinetSeamRow; positions: number[]; alignment: SeamRowAlignment; current?: SeamEdit;
seamMap: ReadonlyMap<string, CabinetSeam>; plan: CamPlacement[]; stored: HardwarePlacementEdits; edits: HardwarePlacementEdits;
}, newId = () => crypto.randomUUID()) {
const references = row.points.map(point => {
const item = edits[point.key]
if (!item) throw new Error('这排五金已变化,请重新选择。')
return item
})
const adding = positions.length > row.points.length
const first = references[0]
if (adding) {
if (!first?.machining || first.machiningPending) throw new Error(first?.machiningPending ?? '请先补齐五金加工参数。')
if (references.some(item => !sameModelValue(comparableHardware(item), comparableHardware(first))))
throw new Error('这排的五金或安装参数不一致,请选中相同五金再增加数量。')
}
const mounts = positions.map((offset, i) => {
const reference = references[i] ?? first
const point = seamPlacement(seam, row.points[i]?.id ?? newId(), offset, reference.lateralMm)
return { point: attachOppositeDowelPoint(point, seam, seamMap, reference.throughDowel?.oppositeSeamKey,
reference.lateralMm), hardware: reference }
})
const previousKeys = new Set(row.points.map(point => point.key))
validateMounts(mounts, boreIndex(plan, edits, previousKeys), adding)
const nextEdits = { ...stored }
const offsets = { ...current?.offsets }
for (const point of row.points.slice(positions.length)) {
delete offsets[point.id]
if (seam.defaults.some(item => item.id === point.id)) nextEdits[point.key] = null
else delete nextEdits[point.key]
}
mounts.forEach(({ point, hardware }, i) => {
offsets[point.id] = positions[i]
if (i >= row.points.length) nextEdits[point.key] = hardware
})
const updated = { id: row.saved?.id ?? newId(), pointIds: mounts.map(({ point }) => point.id), alignment }
const previousIds = new Set(row.points.map(point => point.id))
const priorRows = current?.rows ?? []
const rows = priorRows.flatMap(value => value.id === updated.id ? [updated]
: splitUnmovedSeamRows(value, previousIds, newId))
if (!priorRows.some(value => value.id === updated.id)) rows.push(updated)
return { edits: nextEdits, change: { key: seam.key, offsets, rows }, previousKeys,
keys: mounts.map(({ point }) => point.key) }
}

View File

@ -4,9 +4,10 @@ import { cabinetHardwareMachining, hardwareOrientation } from '@/lib/reference-e
import type { PlacementHardware } from '@/lib/reference-estimator/standard/hardware-placement-edits'
import type { CamPlacement } from './cabinet-cam-preview'
import { direction } from './cabinet-hardware-poses'
import { opposedDowelSpan } from '@/lib/reference-estimator/standard/cabinet-through-dowel'
export type MountRole = 'screw' | 'dowel' | 'insert' | 'rod' | 'wheel'
export type MachiningMount = { mount: Group; length: number }
export type MachiningMount = { mount: Group; length: number; centerY?: number }
export type MachiningModels = Record<string, MachiningMount>
const localY = new Vector3(0, 1, 0)
@ -37,7 +38,7 @@ export function prepareMachiningMount(scene: Object3D, anchor: AccessoryAnchor,
const bounds = new Box3().setFromObject(mount)
if (bounds.isEmpty() || !Number.isFinite(bounds.max.y)) throw new Error('配件模型无法定位')
if (role === 'dowel' && !(bounds.min.y < 0 && bounds.max.y > 0)) throw new Error('木销安装基准应标在两块板的贴合处')
return { mount, length: Math.max(0, bounds.max.y - bounds.min.y) }
return { mount, length: Math.max(0, bounds.max.y - bounds.min.y), centerY: (bounds.min.y + bounds.max.y) / 2 }
}
export function hardwareMountKey(id: string, role: MountRole) { return id + ':' + role }
@ -48,7 +49,13 @@ export function machiningModelParts(point: CamPlacement, item: PlacementHardware
const { donor, receiver, toward, entry } = hardwareOrientation(point, item.reverse)
if (rule.type !== 'cam') {
const model = models[hardwareMountKey(item.id, rule.type)]
return model ? [{ role: rule.type, model, board: donor, entry: rule.type === 'screw' ? entry : point.center,
const offset = rule.type === 'dowel' ? item.dowelCenterOffsetMm ?? 0 : 0
const span = item.throughDowel && opposedDowelSpan(point)
if (item.throughDowel && !span) return []
const center: CamPlacement['center'] = span ? span.center.map((value, i) =>
value - toward[i] * (model?.centerY ?? 0)) as CamPlacement['center'] : [point.center[0] + toward[0] * offset,
point.center[1] + toward[1] * offset, point.center[2] + toward[2] * offset]
return model ? [{ role: rule.type, model, board: donor, entry: rule.type === 'screw' ? entry : center,
axis: direction(toward), slot: undefined }] : []
}
// A provisional hole recipe supplies poses only until the conflict is confirmed.
@ -80,7 +87,7 @@ export function hardwareMarkerPosition(point: CamPlacement, item: PlacementHardw
if (item.machining?.type === 'cam')
return previewCamHoles(point, item).find(hole => hole.kind === 'wheel')?.entry ?? point.center
if (item.machining?.type === 'screw') return hardwareOrientation(point, item.reverse).entry
return item.machining?.type === 'dowel' ? point.center : point.screwEntry
return item.machining?.type === 'dowel' ? (item.throughDowel && opposedDowelSpan(point)?.center) || point.center : point.screwEntry
}
function previewCamHoles(point: CamPlacement, item: PlacementHardware) {

View File

@ -1 +1,3 @@
export * from '@/lib/reference-estimator/standard/cabinet-sg0164-seam'
export const seamEdges = [['左边', '右边'], ['前沿', '后沿'], ['下沿', '上沿']] as const

View File

@ -0,0 +1,102 @@
import { act, fireEvent, render, renderHook, screen } from '@testing-library/react'
import { estimateDocumentSchema } from '@/lib/reference-estimator/contracts'
import { cabinetInputSchema } from '@/lib/reference-estimator/standard/cabinet-contracts'
import { previewTopCornerGuards } from '@/lib/reference-estimator/standard/cabinet-corner-guard'
import { cabinetExplodedPosition } from '@/lib/reference-estimator/standard/cabinet-explode'
import { cabinetHardwarePlan } from '@/lib/reference-estimator/standard/cabinet-hardware-plan'
import { applyCabinetWorkflow } from '@/lib/reference-estimator/standard/cabinet-workflow'
import { surfaceHardwareKey } from '@/lib/reference-estimator/standard/surface-hardware'
import { newStandardDocument } from '@/lib/reference-estimator/standard/workbook'
import { CabinetHardwareBoxSelect } from './CabinetHardwareBoxSelect'
import { cabinetSurfaceBoxTargets, cabinetSurfacePositions, type HardwareBoxTarget } from './cabinet-surface-selection'
import { useCabinetHardwareEdits } from './useCabinetHardwareEdits'
import type { StandardController } from './useStandardEstimator'
const base = applyCabinetWorkflow(newStandardDocument(), cabinetInputSchema.parse({
referenceCase: '6G-960-B', grade: 'E1级', material: '生态板', topColor: '经典北美黑胡桃色', bodyColor: '荷花白色',
}))
const model = base.standardTemplate!.cabinet!
const guards = previewTopCornerGuards(model, 'guard')
test('uses current exploded board positions and only offers loaded accessories for box selection', () => {
const closed = cabinetSurfacePositions(model, [], guards, cabinetExplodedPosition(model, 0))
const opened = cabinetSurfacePositions(model, [], guards, cabinetExplodedPosition(model, 1))
const top = model.parts.find(part => part.role === 'top')!
const shift = cabinetExplodedPosition(model, 1)(top, top.positions[0])[2] - top.positions[0][2]
opened.guards.forEach((row, index) => {
expect(row.scenePoint[1] - closed.guards[index].scenePoint[1]).toBeCloseTo(shift)
expect(row.scenePoint[0]).toBe(closed.guards[index].scenePoint[0])
})
expect(cabinetSurfaceBoxTargets(opened, undefined, undefined)).toHaveLength(0)
expect(cabinetSurfaceBoxTargets(opened, undefined, { guard: {} }).map(target => target.point))
.toEqual(guards.map(row => ({ kind: 'surface', key: surfaceHardwareKey(row) })))
})
test('box selection returns both connection and accessory targets within the drawn rectangle', () => {
const selected = jest.fn()
const cancel = jest.fn()
const connection = { kind: 'connection', point: { key: 'connection' } } as HardwareBoxTarget
const surface: HardwareBoxTarget = { kind: 'surface', key: 'surface' }
render(<CabinetHardwareBoxSelect project={{ current: point => [point[0], point[1]] }} points={[
{ point: connection, position: [30, 30, 0] }, { point: surface, position: [60, 60, 0] },
{ point: { kind: 'surface', key: 'outside' }, position: [150, 150, 0] },
]} onSelect={selected} onCancel={cancel}/>)
const overlay = screen.getByLabelText('框选区域')
overlay.getBoundingClientRect = () => ({ x: 0, y: 0, top: 0, left: 0, width: 200, height: 200,
right: 200, bottom: 200, toJSON: () => ({}) })
overlay.setPointerCapture = jest.fn()
// jsdom does not provide PointerEvent coordinates by default.
const pointer = (type: string, x: number, y: number) => new MouseEvent(type, { bubbles: true, button: 0, clientX: x, clientY: y })
fireEvent(overlay, pointer('pointerdown', 90, 90))
fireEvent(overlay, pointer('pointerup', 10, 10))
expect(selected).toHaveBeenCalledWith([connection, surface])
expect(cancel).toHaveBeenCalledTimes(1)
})
function controller() {
const point = cabinetHardwarePlan(model).entries[0].seam.defaults[0]
return { document: estimateDocumentSchema.parse({ ...base, surfaceHardware: guards,
hardwarePlacementEdits: { [point.key]: { id: 'connection', code: 'YBS-02', name: '圆棒榫', spec: 'φ8*30' } } }), busy: '',
saveHardwarePlacements: jest.fn().mockResolvedValue(true) } as unknown as StandardController
}
test('removes mixed selections in one save, keeps unselected installations, and blocks concurrent writes', async () => {
const c = controller()
const { result } = renderHook(() => useCabinetHardwareEdits(c, model))
const point = result.current.plan[0]
expect(point).toBeDefined()
act(() => result.current.select([point]))
let complete!: (value: boolean) => void
const save = jest.mocked(c.saveHardwarePlacements).mockImplementation(() => new Promise(resolve => { complete = resolve }))
let first!: Promise<boolean>
act(() => { first = result.current.removeAccessories(new Set([surfaceHardwareKey(guards[0])]), true) })
await act(async () => { expect(await result.current.removeAccessories(new Set(guards.map(surfaceHardwareKey)), true)).toBe(false) })
expect(save).toHaveBeenCalledTimes(1)
const [edits, , remaining, cleared] = save.mock.calls[0]
expect(edits[point.key]).toBeNull()
expect(remaining).toEqual(guards.slice(1))
expect(cleared).toBeUndefined()
await act(async () => { complete(true); expect(await first).toBe(true) })
expect(result.current.selection).toHaveLength(0)
})
test.each(['rejected', 'false'])('failed %s save retains selections and installations for retry', async failure => {
const c = controller()
const save = jest.mocked(c.saveHardwarePlacements)
if (failure === 'rejected') save.mockRejectedValueOnce(new Error('network'))
else save.mockResolvedValueOnce(false)
const { result } = renderHook(() => useCabinetHardwareEdits(c, model))
act(() => result.current.select([result.current.plan[0]]))
const selected = result.current.selection.map(point => point.key)
const keys = new Set(guards.map(surfaceHardwareKey))
await act(async () => { expect(await result.current.removeAccessories(keys, true)).toBe(false) })
expect(result.current.selection.map(point => point.key)).toEqual(selected)
expect(c.document.surfaceHardware).toEqual(guards)
expect(result.current.status).toBe('error')
await act(async () => { expect(await result.current.removeAccessories(keys, false)).toBe(true) })
const [edits, , remaining, cleared] = save.mock.calls[1]
expect(edits).toEqual(c.document.hardwarePlacementEdits ?? {})
expect(remaining).toEqual([])
expect(cleared).toEqual(['corner-guard'])
expect(result.current.selection.map(point => point.key)).toEqual(selected)
})

View File

@ -0,0 +1,48 @@
import type { CabinetModel, CabinetPart } from '@/lib/reference-estimator/standard/cabinet-contracts'
import type { cabinetExplodedPosition } from '@/lib/reference-estimator/standard/cabinet-explode'
import { resolveTopCornerGuards } from '@/lib/reference-estimator/standard/cabinet-corner-guard'
import { resolveSurfaceHardware, surfaceHardwareKey, type SurfaceHardware } from '@/lib/reference-estimator/standard/surface-hardware'
import type { CamPlacement, MmPoint } from './cabinet-cam-preview'
import type { SelectableHardware } from './CabinetHardwareBoxSelect'
import type { Dispatch, SetStateAction } from 'react'
export type CabinetSurfaceSelectionState = {
keys: ReadonlySet<string>
select: Dispatch<SetStateAction<string[]>>
busy: boolean
}
export type HardwareBoxTarget = { kind: 'connection'; point: CamPlacement } | { kind: 'surface'; key: string }
export function cabinetSurfacePositions(model: CabinetModel, clips: SurfaceHardware, guards: SurfaceHardware,
boardPosition: ReturnType<typeof cabinetExplodedPosition>) {
const width = model.input.width ?? 0
const depth = model.input.depth ?? 0
const height = model.input.height ?? 0
function scenePoint(part: CabinetPart, start: MmPoint, point: MmPoint): MmPoint {
const current = boardPosition(part, start)
return [point[0] + current[0] - start[0] - width / 2,
point[2] + current[2] - start[2] - height / 2,
depth / 2 - point[1] - current[1] + start[1]]
}
return {
clips: resolveSurfaceHardware(model, clips).map(row => ({
...row, key: surfaceHardwareKey(row), scenePoint: scenePoint(row.board.part, row.board.start, row.position),
})),
guards: resolveTopCornerGuards(model, guards).map(row => ({
...row, key: surfaceHardwareKey(row), scenePoint: scenePoint(row.panel.part, row.panel.start, row.point),
})),
}
}
export function cabinetSurfaceBoxTargets(rows: ReturnType<typeof cabinetSurfacePositions>,
clipModels: Record<string, unknown> | undefined, guardModels: Record<string, unknown> | undefined) {
const target = (key: string, position: MmPoint): SelectableHardware<HardwareBoxTarget> =>
({ point: { kind: 'surface', key }, position })
return [
...rows.clips.filter(row => clipModels?.[row.accessoryId]).map(row => target(row.key, row.scenePoint)),
...rows.guards.filter(row => guardModels?.[row.accessoryId]).map(row => {
const [x, y, z] = row.scenePoint
return target(row.key, [x + (row.left ? 9 : -9), y + 2, z + (row.front ? -9 : 9)])
}),
]
}

View File

@ -0,0 +1,48 @@
import { Box3, BoxGeometry, Group, Mesh, MeshPhysicalMaterial, Vector3 } from 'three'
import { cornerGuardContact, cornerGuardRotation, prepareCornerGuardModel } from './corner-guard-model'
// Three contact faces match the library GLB, including its metre root transform.
function libraryGuard() {
const root = new Group()
root.scale.setScalar(.001)
const material = new MeshPhysicalMaterial({ transmission: .96, ior: 1.41 })
for (const [size, center] of [
[[2.7, 15, 35], [1.35, 7.5, 17.5]],
[[35, 15, 2.7], [17.5, 7.5, 1.35]],
[[35, 3.25, 35], [17.5, 13.375, 17.5]],
]) {
const mesh = new Mesh(new BoxGeometry(...size), material)
mesh.position.set(...center as [number, number, number])
root.add(mesh)
}
return root
}
test('seats the inner walls and lid underside and rotates all four corners without stretching or mirroring', () => {
const scene = libraryGuard()
expect(cornerGuardContact(scene)).toEqual([2.7, 11.75, 2.7])
const mount = prepareCornerGuardModel(scene)
const material = (scene.children[0] as Mesh).material
for (const [location, angle] of Object.entries(cornerGuardRotation)) {
const clone = mount.clone(true)
clone.rotation.y = angle
clone.updateWorldMatrix(true, true)
const contact = new Vector3(2.7, 11.75, 2.7).applyMatrix4(clone.children[0].children[0].matrixWorld)
expect(contact.length()).toBeLessThan(1e-10)
const bounds = new Box3().setFromObject(clone, true)
const dimensions = bounds.getSize(new Vector3()).toArray()
dimensions.forEach((value, index) => expect(value).toBeCloseTo([35, 15, 35][index]))
expect(bounds.max.y).toBeCloseTo(3.25)
expect(bounds.min.y).toBeCloseTo(-11.75)
expect(location.endsWith('left') ? bounds.max.x : -bounds.min.x).toBeCloseTo(32.3)
expect(location.startsWith('front') ? -bounds.min.z : bounds.max.z).toBeCloseTo(32.3)
expect(clone.matrixWorld.determinant()).toBeGreaterThan(0)
expect((clone.children[0].children[0].children[0] as Mesh).material).toBe(material)
}
})
test('rejects an incompatible library revision before using an incorrect mounting origin', () => {
const scene = libraryGuard()
scene.scale.multiplyScalar(2)
expect(() => prepareCornerGuardModel(scene)).toThrow('尺寸或朝向已变化')
})

View File

@ -0,0 +1,59 @@
import { Box3, Group, Mesh, Vector3, type Object3D } from 'three'
import type { CornerGuardLocation } from '@/lib/reference-estimator/standard/cabinet-corner-guard'
export const cornerGuardRotation: Record<CornerGuardLocation, number> = {
'front-left': Math.PI / 2, 'front-right': Math.PI,
'rear-left': 0, 'rear-right': -Math.PI / 2,
}
/** Find the three broad inner contact faces in the library model, in millimetres. */
export function cornerGuardContact(scene: Object3D): [number, number, number] {
scene.updateWorldMatrix(true, true)
const planes = [new Map<number, number>(), new Map<number, number>(), new Map<number, number>()]
const a = new Vector3(), b = new Vector3(), c = new Vector3()
const edge = new Vector3(), secondEdge = new Vector3(), normal = new Vector3()
const signs = [1, -1, 1]
scene.traverse(node => {
if (!(node instanceof Mesh)) return
const positions = node.geometry.getAttribute('position')
const indices = node.geometry.index
for (let index = 0; index < (indices?.count ?? positions.count); index += 3) {
for (const [offset, point] of [a, b, c].entries()) {
point.fromBufferAttribute(positions, indices ? indices.getX(index + offset) : index + offset)
.applyMatrix4(node.matrixWorld).multiplyScalar(1000)
}
normal.crossVectors(edge.subVectors(b, a), secondEdge.subVectors(c, a))
const area = normal.length() / 2
if (!area) continue
normal.normalize()
for (let axis = 0; axis < 3; axis++) {
if (normal.getComponent(axis) * signs[axis] < .999999) continue
const coordinate = Math.round(a.getComponent(axis) * 100) / 100
planes[axis].set(coordinate, (planes[axis].get(coordinate) ?? 0) + area)
}
}
})
const bounds = new Box3().setFromObject(scene, true)
const size = bounds.getSize(new Vector3()).multiplyScalar(1000).toArray()
if (size.some((value, axis) => !Number.isFinite(value) || Math.abs(value - [35, 15, 35][axis]) > .5)) {
throw new Error('QT-01 原模型尺寸或朝向已变化,请复核安装基准。')
}
const origin = planes.map(faces => [...faces].sort((a, b) => b[1] - a[1])[0])
if (origin.some(face => !face || face[1] < 30)) throw new Error('QT-01 原模型缺少可识别的内侧贴合面。')
const point = origin.map(face => face[0]) as [number, number, number]
const inset = [point[0] - bounds.min.x * 1000, bounds.max.y * 1000 - point[1], point[2] - bounds.min.z * 1000]
if (inset.some(value => value <= 0 || value > 5)) throw new Error('QT-01 内侧贴合面已变化,请复核安装基准。')
return point
}
export function prepareCornerGuardModel(scene: Object3D) {
const contact = cornerGuardContact(scene)
const millimetres = new Group()
millimetres.scale.setScalar(1000)
millimetres.position.set(-contact[0], -contact[1], -contact[2])
millimetres.add(scene)
const mount = new Group()
mount.name = 'QT-01 原模型'
mount.add(millimetres)
return mount
}

View File

@ -1,6 +1,6 @@
import { act, renderHook } from '@testing-library/react'
import { newStandardDocument } from '@/lib/reference-estimator/standard/workbook'
import { useEstimateAppearanceSave } from './useEstimateAppearanceSave'
import { useEstimateAutosave } from './useEstimateAutosave'
it('coalesces texture input, queues changes behind an active save, and ignores a result after switching records', async () => {
jest.useFakeTimers()
@ -8,26 +8,26 @@ it('coalesces texture input, queues changes behind an active save, and ignores a
let resolve!: () => void
const persist = jest.fn().mockImplementationOnce(() => new Promise<void>(done => { resolve = done }))
.mockResolvedValue(undefined)
const { result } = renderHook(() => useEstimateAppearanceSave(persist, false))
const { result } = renderHook(() => useEstimateAutosave(persist, false))
const draft = newStandardDocument()
const fields = (size: number) => ({ modelAppearance: { all: { name: 'Oak', color: '#776655', textureSizeMm: size } } })
act(() => {
result.current.stage(fields(125), draft)
result.current.stage(fields(250), draft)
result.current.stage({ ...draft, ...fields(125) }, 1)
result.current.stage({ ...draft, ...fields(250) }, 2)
})
await act(async () => { jest.advanceTimersByTime(450) })
expect(persist).toHaveBeenCalledTimes(1)
expect(persist.mock.calls[0][0].fields).toEqual(fields(250))
act(() => { result.current.stage(fields(500), draft) })
expect(persist.mock.calls[0][0].document).toMatchObject(fields(250))
act(() => { result.current.stage({ ...draft, ...fields(500) }, 3) })
await act(async () => { jest.advanceTimersByTime(450) })
expect(persist).toHaveBeenCalledTimes(1)
await act(async () => { resolve() })
await act(async () => { jest.advanceTimersByTime(450) })
expect(persist.mock.calls[1][0].fields).toEqual(fields(500))
expect(persist.mock.calls[1][0].document).toMatchObject(fields(500))
expect(result.current.status.state).toBe('saved')
persist.mockImplementationOnce(() => new Promise<void>(done => { resolve = done }))
act(() => { result.current.stage(fields(600), draft) })
act(() => { result.current.stage({ ...draft, ...fields(600) }, 4) })
await act(async () => { jest.advanceTimersByTime(450) })
act(() => { result.current.reset() })
await act(async () => { resolve() })
@ -41,10 +41,10 @@ it('keeps unsaved appearance available for retry when the request fails', async
jest.useFakeTimers()
try {
const persist = jest.fn().mockRejectedValueOnce(new Error('服务不可用')).mockResolvedValue(undefined)
const { result } = renderHook(() => useEstimateAppearanceSave(persist, false))
act(() => { result.current.stage({ modelAppearance: undefined }, newStandardDocument()) })
const { result } = renderHook(() => useEstimateAutosave(persist, false))
act(() => { result.current.stage(newStandardDocument(), 1) })
await act(async () => { jest.advanceTimersByTime(450) })
expect(result.current.status).toEqual({ state: 'error', error: '外观保存失败:服务不可用' })
expect(result.current.status).toEqual({ state: 'error', error: '自动保存失败,服务不可用' })
expect(result.current.hasPending).toBe(true)
act(() => { result.current.retry() })
await act(async () => { jest.advanceTimersByTime(450) })

View File

@ -1,7 +1,7 @@
.selector {
display: flex;
align-items: center;
gap: 9px;
gap: 6px;
min-width: 0;
}
@ -9,9 +9,9 @@
flex: 1 1 0;
min-width: 0;
}
.adjust {
padding: 6px 0;
flex: none;
padding: 3px 2px;
color: var(--obs-shell-text, #3d4651);
font-size: 12px;
text-decoration: underline;
@ -22,14 +22,14 @@
.adjust:disabled { opacity: .5; }
.adjust:hover:not(:disabled) { text-decoration-color: currentColor; }
.dialog { max-width: 850px; }
.adjust:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; border-radius: 3px; }
.product { margin: 0 0 16px; font-size: 13px; color: var(--obs-shell-muted, #646d75); }
.tableHeader,
.row {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(0, .95fr);
gap: 20px;
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
gap: 12px;
align-items: center;
}
@ -42,12 +42,12 @@
.rows { margin: 0; padding: 0; list-style: none; }
.row { min-height: 88px; padding: 12px 0; border-bottom: 1px solid var(--obs-shell-border, #e1e3e6); }
.variant { display: flex; align-items: center; min-width: 0; gap: 12px; }
.variant { display: flex; align-items: center; min-width: 0; gap: 8px; }
.thumbnail {
display: grid;
width: 62px;
height: 62px;
width: 44px;
height: 44px;
flex: none;
overflow: hidden;
place-items: center;
@ -60,7 +60,7 @@
.thumbnail svg[viewBox]:not([width]) { width: 100%; height: 100%; object-fit: contain; }
.variantText { min-width: 0; }
.variantText strong { font-size: 14px; font-weight: 650; }
.variantText span { margin-left: 8px; white-space: nowrap; }
.variantText span { display: block; }
.variantText span,
.variantText small { color: var(--obs-shell-muted, #646d75); font-size: 12px; }
.variantText small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
@ -81,7 +81,7 @@
.error { margin: 6px 0 0; color: var(--danger, #b91c1c); font-size: 12px; }
.footer { display: flex; justify-content: flex-end; gap: 8px; padding-top: 8px; }
@media (max-width: 560px) {
@media (max-width: 390px) {
.tableHeader { display: none; }
.row { grid-template-columns: minmax(0, 1fr); gap: 8px; }
}

View File

@ -7,6 +7,7 @@ export type EstimateWorkspaceRecord = {
title: string
ruleVersion: string
revision: number
imageUrl?: string | null
workspaceSlot?: EstimateWorkspaceSlot | null
skillLearning?: { label: string; correctionSaved: boolean; ruleSaved: boolean }
}
@ -17,6 +18,7 @@ export type EstimateWorkspaceState = {
record: EstimateWorkspaceRecord | null
dirty: boolean
message?: string
variantTrial?: boolean
}
export type EstimateBindingSource = {

View File

@ -4,7 +4,7 @@ import type { CabinetDrawings } from '@/lib/reference-estimator/standard/cabinet
import type { SamplingRevision } from '@/lib/reference-estimator/standard/stage-assistant-contract'
// Bump when a change to drawing rules changes the generated SVG.
const cacheName = 'reference-estimate-drawings-v3'
const cacheName = 'reference-estimate-drawings-v4'
const maxEntries = 6
const maxEntryLength = 4_000_000

View File

@ -9,15 +9,20 @@
}
.rail[hidden], .chatPanel[hidden], .hardwarePanel[hidden] { display: none; }
.railHeader {
position: relative;
display: flex;
flex: none;
align-items: center;
justify-content: space-between;
padding: 0 8px 0 10px;
padding: 0 34px 0 10px;
border-bottom: 1px solid var(--obs-shell-border, #e3e7e5);
}
.tabs { display: flex; flex-wrap: wrap; gap: 0 8px; min-width: 0; }
.railHeader > button { flex: none; padding-inline: 0; }
.railHeader > .collapse { position: absolute; top: 1px; right: 4px; min-width: 30px; min-height: 30px; padding: 0; }
@media (pointer: coarse) {
.railHeader { padding-right: 46px; }
.railHeader > .collapse { min-width: 44px; min-height: 38px; }
}
.tabs button {
display: inline-flex;
align-items: center;
@ -36,6 +41,11 @@
}
.chatPanel, .hardwarePanel { display: flex; flex: 1; flex-direction: column; min-width: 0; min-height: 0; }
.rail .chatPanel[role='tabpanel'], .rail .hardwarePanel[role='tabpanel'] { border: 0; border-radius: 0; background: transparent; }
.rail .hardwareScroll[role='tabpanel']:not([hidden]) {
display: block;
overflow: hidden auto;
overscroll-behavior-y: contain;
}
.chatPanel > aside { flex: 1; min-height: 0; height: auto; border: 0; }
.libraryHeading {
display: flex;
@ -79,18 +89,14 @@
.search input[type='search']:focus { outline: 0; }
.search input::placeholder { color: var(--obs-shell-muted, #59636b); font-size: 11px; }
.resultLine { padding: 4px 12px 6px; color: var(--obs-shell-muted, #59636b); font-size: 11px; overflow-wrap: anywhere; }
.list { flex: 1; min-height: 0; padding: 0 10px 8px; overflow: auto; overscroll-behavior: contain; }
.list { padding: 0 10px 8px; }
.list li + li { border-top: 1px solid var(--obs-shell-border, #e3e7e5); }
.categoryIndex {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
align-content: start;
gap: 12px;
flex: 1;
min-height: 0;
padding: 0 12px 12px;
overflow: auto;
overscroll-behavior: contain;
}
.categoryGroup h4 {
padding: 2px 4px 8px;
@ -124,6 +130,7 @@
.itemText { display: grid; min-width: 0; gap: 1px; }
.itemText strong { overflow-wrap: anywhere; font-weight: 650; }
.itemText span { overflow: hidden; color: var(--obs-shell-muted, #59636b); font-size: 11px; text-overflow: ellipsis; white-space: nowrap; }
.itemText .choiceFeedback { white-space: normal; overflow-wrap: anywhere; }
.cover {
display: grid;
place-items: center;
@ -140,10 +147,6 @@
.skillAction { padding: 6px 12px; border-bottom: 1px solid var(--obs-shell-border, #e3e7e5); }
.skillAction p { margin-top: 4px; color: var(--obs-shell-muted, #59636b); font-size: 11px; overflow-wrap: anywhere; }
.connections {
flex: none;
max-height: min(45%, 240px);
overflow: auto;
overscroll-behavior: contain;
padding: 5px 12px 8px;
border-bottom: 1px solid var(--obs-shell-border, #e3e7e5);
}

View File

@ -0,0 +1,206 @@
import { act, renderHook } from '@testing-library/react'
import { estimateDocumentSchema, type EstimateDocument } from '@/lib/reference-estimator/contracts'
import { cabinetInputSchema } from '@/lib/reference-estimator/standard/cabinet-contracts'
import { applyCabinetWorkflow } from '@/lib/reference-estimator/standard/cabinet-workflow'
import { initializeStageResults, pendingStages, regenerateStage } from '@/lib/reference-estimator/standard/stage-results'
import { newStandardDocument } from '@/lib/reference-estimator/standard/workbook'
import { regenerateEstimateResults } from './regenerate-estimate-results'
import { useStandardEstimator } from './useStandardEstimator'
import type { EstimateStage } from './EstimateWorkbenchToolbar'
jest.mock('./model-export-images', () => ({ modelExportImages: jest.fn() }))
jest.mock('./useEstimateDrawings', () => ({ useEstimateDrawings: () => ({}) }))
jest.mock('./regenerate-estimate-results', () => ({ regenerateEstimateResults: jest.fn() }))
const initial = initializeStageResults(applyCabinetWorkflow(newStandardDocument(), cabinetInputSchema.parse({
referenceCase: '6G-960-B', name: '六格书柜',
})))
const record = { id: 'autosave-test', title: initial.title, ruleVersion: 'standard-1116.1' as const,
revision: 1, createdAt: '', updatedAt: '' }
const response = (data: object) => ({ ok: true, json: async () => ({ success: true, data }) })
const generate = jest.mocked(regenerateEstimateResults)
const fetchMock = jest.fn()
const originalFetch = global.fetch
let writes: { document: EstimateDocument; revision?: number }[]
let revision: number
let failWrite: boolean
let releaseWrite: (() => void) | undefined
beforeEach(() => {
jest.useFakeTimers()
global.fetch = fetchMock
writes = []
revision = 1
failWrite = false
releaseWrite = undefined
generate.mockReset().mockImplementation(async document =>
(['sampling', 'packing', 'cost'] as const).reduce((current, stage) => regenerateStage(current, stage, [], record.id, []), document))
fetchMock.mockReset().mockImplementation(async (url: string, init?: RequestInit) => {
if (!init?.method) return response({ records: [] })
if (failWrite) throw new Error('网络断开')
const body = JSON.parse(String(init.body))
expect(body.revision).toBe(init.method === 'POST' ? undefined : revision)
writes.push({ document: estimateDocumentSchema.parse(body.document), revision: body.revision })
if (releaseWrite) await new Promise<void>(done => { releaseWrite = done })
return response({ record: { ...record, revision: ++revision, document: body.document } })
})
})
afterEach(() => { global.fetch = originalFetch; jest.useRealTimers() })
function setup(document = initial, saved = true) {
const view = renderHook(() => useStandardEstimator([]))
act(() => view.result.current.activateRecord({ document, record: saved ? record : null, dirty: false }))
return view
}
async function tick() {
await act(async () => { jest.advanceTimersByTime(450) })
}
test('model, finish and hardware edits autosave while preserving all published outputs', async () => {
const { result } = setup()
act(() => result.current.setCabinetInput({ ...result.current.standard.cabinet!.input, width: 1280 }))
await tick()
expect(writes).toHaveLength(1)
expect(writes[0].document.standardTemplate!.cabinet!.input.width).toBe(1280)
expect(writes[0].document.stageResults).toEqual(initial.stageResults)
act(() => result.current.setModelAppearance({ all: { name: '胡桃色', color: '#776655' } }))
await tick()
await act(async () => { await result.current.saveHardwarePlacements({ 'test-point': null }) })
expect(writes).toHaveLength(3)
expect(writes[2].document.modelAppearance?.all.name).toBe('胡桃色')
expect(writes[2].document.hardwarePlacementEdits).toEqual({ 'test-point': null })
expect(writes[2].document.stageResults).toEqual(initial.stageResults)
expect(generate).not.toHaveBeenCalled()
expect(result.current.autosave.status.state).toBe('saved')
})
test('edits arriving during a write stay visible and save with the returned revision', async () => {
const { result } = setup()
releaseWrite = () => undefined
act(() => result.current.title('第一稿'))
await tick()
act(() => result.current.title('第二稿'))
await tick()
expect(writes).toHaveLength(1)
const finish = releaseWrite!
releaseWrite = undefined
await act(async () => { finish() })
expect(result.current.document.title).toBe('第二稿')
expect(result.current.dirty).toBe(true)
await tick()
expect(writes).toHaveLength(2)
expect(writes[1]).toMatchObject({ revision: 2, document: { title: '第二稿' } })
expect(result.current.dirty).toBe(false)
})
test('failed autosave retains the current model and retries the same change', async () => {
const { result } = setup()
failWrite = true
act(() => result.current.title('未保存的修改'))
await tick()
expect(result.current.autosave.status.state).toBe('error')
expect(result.current.document.title).toBe('未保存的修改')
failWrite = false
await act(async () => { await result.current.retryModelSave() })
expect(writes).toHaveLength(1)
expect(result.current.dirty).toBe(false)
})
test('Save flushes the model then writes three complete outputs from that model together', async () => {
const { result } = setup()
act(() => result.current.setCabinetInput({ ...result.current.standard.cabinet!.input, width: 1280 }))
await act(async () => { await result.current.save() })
expect(writes).toHaveLength(2)
expect(writes[0].document.stageResults).toEqual(initial.stageResults)
expect(generate).toHaveBeenCalledTimes(1)
expect(generate.mock.calls[0][0].standardTemplate!.cabinet!.input.width).toBe(1280)
expect(pendingStages(writes[1].document)).toEqual({ sampling: false, packing: false, cost: false })
expect(writes[1].document.stageResults!.sampling.cabinet.input.width).toBe(1280)
})
test('failed whole generation preserves all previous outputs and the saved latest model', async () => {
const { result } = setup()
act(() => result.current.setCabinetInput({ ...result.current.standard.cabinet!.input, width: 1280 }))
generate.mockRejectedValueOnce(new Error('图纸生成失败'))
await act(async () => { await result.current.save() })
expect(writes).toHaveLength(1)
expect(result.current.document.stageResults).toEqual(initial.stageResults)
expect(result.current.document.standardTemplate!.cabinet!.input.width).toBe(1280)
expect(result.current.error).toContain('图纸生成失败')
})
test('first model is persisted before generating and saving the initial outputs', async () => {
const { result } = setup(newStandardDocument(), false)
let finish!: (document: EstimateDocument) => void
generate.mockImplementationOnce(document => new Promise(done => { finish = () => done(document) }))
act(() => result.current.updateDocument(() => initial))
await tick()
expect(writes).toHaveLength(1)
expect(result.current.record?.id).toBe(record.id)
await act(async () => { finish(initial) })
expect(writes).toHaveLength(2)
expect(writes[1].revision).toBe(2)
})
test('first output generation failure still leaves the model saved', async () => {
const { result } = setup(newStandardDocument(), false)
generate.mockRejectedValueOnce(new Error('读取配件超时'))
act(() => result.current.updateDocument(() => initial))
await tick()
expect(writes).toHaveLength(1)
expect(result.current.record?.id).toBe(record.id)
expect(result.current.dirty).toBe(false)
expect(result.current.error).toContain('模型已保存,初版资料生成失败')
})
test('newer model edits survive initial generation and retain its saved outputs', async () => {
const { result } = setup(newStandardDocument(), false)
const generated = regenerateStage(initial, 'sampling', [], record.id, [])
let finish!: () => void
generate.mockImplementationOnce(() => new Promise(done => { finish = () => done(generated) }))
act(() => result.current.updateDocument(() => initial))
await tick()
act(() => result.current.setCabinetInput({ ...result.current.standard.cabinet!.input, width: 1280 }))
await tick()
expect(writes).toHaveLength(1)
await act(async () => { finish() })
expect(result.current.document.standardTemplate!.cabinet!.input.width).toBe(1280)
await tick()
expect(writes).toHaveLength(3)
expect(writes[2].revision).toBe(3)
expect(writes[2].document.standardTemplate!.cabinet!.input.width).toBe(1280)
expect(writes[2].document.stageResults).toEqual(generated.stageResults)
expect(result.current.dirty).toBe(false)
})
test('switching stage before a queued model save keeps the completed initial outputs', async () => {
const { result, rerender } = renderHook(({ stage }: { stage: EstimateStage }) =>
useStandardEstimator([], undefined, stage), { initialProps: { stage: 'model' as EstimateStage } })
act(() => result.current.activateRecord({ document: newStandardDocument(), record: null, dirty: false }))
const generated = regenerateStage(initial, 'sampling', [], record.id, [])
let finish!: () => void
generate.mockImplementationOnce(() => new Promise(done => { finish = () => done(generated) }))
act(() => result.current.updateDocument(() => initial))
await tick()
act(() => result.current.setCabinetInput({ ...result.current.standard.cabinet!.input, width: 1280 }))
rerender({ stage: 'packing' })
await tick()
await act(async () => { finish() })
await tick()
expect(writes).toHaveLength(3)
expect(writes[2].document.standardTemplate!.cabinet!.input.width).toBe(1280)
expect(writes[2].document.stageResults).toEqual(generated.stageResults)
})
test('separate sampling regeneration saves the current model and updates only sampling', async () => {
const { result } = setup()
act(() => result.current.setCabinetInput({ ...result.current.standard.cabinet!.input, width: 1280 }))
generate.mockImplementationOnce(async document => regenerateStage(document, 'sampling', [], record.id, []))
await act(async () => { await result.current.refreshStage('sampling') })
expect(writes).toHaveLength(2)
expect(writes[1].document.stageResults!.sampling.cabinet.input.width).toBe(1280)
expect(writes[1].document.stageResults!.packing).toEqual(initial.stageResults!.packing)
expect(writes[1].document.stageResults!.cost).toEqual(initial.stageResults!.cost)
})

View File

@ -0,0 +1,28 @@
.copyGrid { display: grid; grid-template-columns: minmax(0, 1fr) 198px; align-items: start; gap: 20px; }
.fields { display: grid; gap: 12px; font-size: 13px; }
.fields label { display: grid; gap: 5px; }
.fields :is(select, input, textarea) {
width: 100%; min-width: 0; padding: 7px 9px; border-radius: 6px;
border: 1px solid var(--obs-shell-border, #dfe4e7); background: var(--obs-shell-panel-bg, white);
}
.fields textarea { resize: vertical; }
.sizeFields { min-width: 0; padding: 0; border: 0; }
.sizeRow { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; }
.sizeFields legend { margin-bottom: 5px; }
.sizeFields label { color: var(--obs-shell-muted, #59636b); font-size: 12px; }
.fields p { margin: 0; color: var(--obs-shell-muted, #59636b); }
.fields .error { color: var(--danger, #b91c1c); }
.referenceImage { display: grid; gap: 8px; min-width: 0; }
.referenceImage h3 { margin: 0; font-size: 13px; font-weight: 500; }
.referenceImage p { margin: 0; font-size: 12px; color: var(--obs-shell-muted, #59636b); }
.imagePreview {
display: grid; place-items: center; height: 142px; overflow: hidden; border-radius: 6px;
background: var(--obs-shell-muted-bg, #f6f7f8); color: var(--obs-shell-muted, #59636b);
border: 1px solid var(--obs-shell-border, #dfe4e7);
}
.imagePreview img { width: 100%; height: 100%; min-height: 0; object-fit: contain; }
.imageActions { display: flex; flex-wrap: wrap; gap: 6px; }
@media (max-width: 560px) { .copyGrid { grid-template-columns: minmax(0, 1fr); gap: 14px; } }
.status { display: grid; gap: 3px; font-size: 11px; line-height: 1.5; color: var(--obs-shell-muted, #59636b); }
.status strong { color: var(--obs-shell-title, #242b30); font-weight: 600; }
.warning { white-space: pre-line; overflow-wrap: anywhere; }

View File

@ -1,8 +1,9 @@
import type { ProductArchive, ProductArchiveDetail, ProductArchiveList, ProductInfoVariant } from '@/lib/product-library/contracts'
import type { ProductArchive, ProductArchiveDetail, ProductInfoVariant } from '@/lib/product-library/contracts'
import { libraryVariantDimensions } from '@/lib/product-library/variant-dimensions'
import { estimateWorkspaceSlotSchema, type EstimateDocument, type EstimateWorkspaceSlot } from '@/lib/reference-estimator/contracts'
import { newStandardDocument } from '@/lib/reference-estimator/standard/workbook'
import { withEstimateReadTimeout } from '../estimate-read'
import { readEstimateProductCatalog } from '../estimate-product-catalog'
export type EstimateSlotRecord = { id: string; title: string; workspaceSlot?: unknown }
export type EstimateSpu = Pick<ProductArchive, 'id' | 'spu' | 'name' | 'barcodes'> & { spu: string }
@ -48,7 +49,9 @@ async function readProductLibrary<T>(url: string, signal?: AbortSignal): Promise
}
export async function listEstimateSpus(signal?: AbortSignal) {
const { archives } = await readProductLibrary<ProductArchiveList>('/api/intake/product-library', signal)
const catalog = await readEstimateProductCatalog(signal)
if (!catalog) throw new Error('当前账号没有查看产品资料的权限')
const { archives } = catalog
return archives.filter((archive): archive is ProductArchive & { spu: string } => Boolean(archive.spu && archive.barcodes.length))
}

View File

@ -2,6 +2,7 @@ import { act, renderHook, waitFor } from '@testing-library/react'
import { Box3, BoxGeometry, Group, Mesh, MeshPhysicalMaterial } from 'three'
import { listAccessoryDrafts } from '@/app/database/bom-library/accessory-models/draft-client'
import type { AccessoryDraft } from '@/lib/intake-accessory-models'
import { accessoryDowelCad } from '@/lib/accessory-model-spec'
import { cabinetInputSchema } from '@/lib/reference-estimator/standard/cabinet-contracts'
import { cabinetHardwareBoards } from '@/lib/reference-estimator/standard/hardware-board-connections'
import { hasHardwareModel, hasSavedHardwareModel } from '@/lib/reference-estimator/standard/hardware-model-availability'
@ -211,7 +212,7 @@ test('a new seam point and its modeled screw are saved together without a defaul
test('editing a screw batch does not move or reassign a later dowel batch', async () => {
const woodScrew = { ...screw, code: 'MLS-01', name: '木螺丝' }
const dowel: AccessoryDraft = { ...screw, id: 'dowel', code: 'MX-01', name: '木销', kind: '圆棒榫', category: '圆棒榫',
model: { ...kit.model!, installationAnchors: [{ partName: '木销', partPath: '0', role: 'other', originMm: [0, 0, 0], direction: '+y' }] } }
spec: 'Ø6×20', model: { ...kit.model!, cad: accessoryDowelCad({ diameter: 6, length: 20 }) } }
const initial = controller()
let current = { ...initial, document: { ...initial.document, hardwarePlacementEdits: {
[points[0].key]: null, [points[1].key]: null,
@ -242,8 +243,19 @@ test('editing a screw batch does not move or reassign a later dowel batch', asyn
expect(screwRow.pointIds.map(id => updated.offsets[id])).toEqual([30, 62, 94])
expect(updated.rows?.[1]).toEqual(dowelRow)
expect(dowelRow.pointIds.map(id => updated.offsets[id])).toEqual([238, 270])
expect(dowelRow.pointIds.map(id => current.document.hardwarePlacementEdits?.[JSON.stringify([updated.key, id])]?.code))
.toEqual(['MX-01', 'MX-01'])
for (const id of dowelRow.pointIds) {
expect(current.document.hardwarePlacementEdits?.[JSON.stringify([updated.key, id])]).toMatchObject({
code: 'MX-01', machiningEstimated: true, dowelCenterOffsetMm: 4, machining: { type: 'dowel', first: { diameterMm: 6, depthMm: 6 },
second: { diameterMm: 6, depthMm: 17 } },
})
}
const sampling = regenerateStage(current.document, 'sampling', [], undefined, [woodScrew, dowel]).stageResults!.sampling
const dowels = sampling.connections!.filter(connection => connection.hardware.includes('MX-01'))
expect(dowels).toHaveLength(2)
for (const connection of dowels) {
expect(connection.pending).toContain('按圆棒榫模型暂估开孔')
expect(connection.holes.map(hole => [hole.diameter, hole.depth])).toEqual([[6, 6], [6, 17]])
}
})
test('legacy default kit references produce no installed hardware or trial bores', () => {

View File

@ -0,0 +1,101 @@
import { act, renderHook } from '@testing-library/react'
import type { AccessoryDraft } from '@/lib/intake-accessory-models'
import { estimateDocumentSchema, type EstimateDocument } from '@/lib/reference-estimator/contracts'
import { cabinetInputSchema } from '@/lib/reference-estimator/standard/cabinet-contracts'
import { previewTopCornerGuards } from '@/lib/reference-estimator/standard/cabinet-corner-guard'
import { applyCabinetWorkflow } from '@/lib/reference-estimator/standard/cabinet-workflow'
import { pendingStages, regenerateStage } from '@/lib/reference-estimator/standard/stage-results'
import { newStandardDocument } from '@/lib/reference-estimator/standard/workbook'
import { useStandardEstimator } from './useStandardEstimator'
jest.mock('./model-export-images', () => ({ modelExportImages: jest.fn() }))
jest.mock('./useEstimateDrawings', () => ({ useEstimateDrawings: () => ({}) }))
jest.mock('./estimate-drawings-cache', () => ({ loadEstimateDrawings: jest.fn().mockResolvedValue({}) }))
const guard: AccessoryDraft = { id: 'guard', module: 'accessory', category: '其他配件', kind: '其他配件',
code: 'QT-01', name: '硅胶防撞护角', spec: '35*35*15', material: '硅胶', price: .88, weightGrams: 6,
revision: '', dimensions: {}, pending: [], photos: [], model: null }
const base = applyCabinetWorkflow(newStandardDocument(), cabinetInputSchema.parse({ referenceCase: '6G-960-B' }))
const guards = previewTopCornerGuards(base.standardTemplate!.cabinet!, guard.id)
const installed = estimateDocumentSchema.parse((['sampling', 'packing', 'cost'] as const).reduce((document, stage) =>
regenerateStage(document, stage, [], undefined, [guard]), { ...base, surfaceHardware: guards }))
const record = { id: 'estimate-test', title: installed.title, ruleVersion: 'standard-1116.1' as const,
revision: 1, createdAt: '', updatedAt: '' }
const originalFetch = global.fetch
const fetchMock = jest.fn()
const response = (data: object) => ({ ok: true, json: async () => ({ success: true, data }) })
let written: EstimateDocument[]
let rejectSave: boolean
beforeEach(() => {
written = []
rejectSave = false
global.fetch = fetchMock
fetchMock.mockReset().mockImplementation(async (url: string, init?: RequestInit) => {
if (url === '/api/intake/reference-estimates') return response({ records: [] })
if (url === '/api/intake/accessory-model-drafts') return response({ items: [guard], canSave: true })
if (url === '/api/asset-center/substrates') return response({ substrates: [] })
if (url === '/api/intake/reference-estimates/' + record.id && init?.method === 'PUT') {
if (rejectSave) throw new Error('network')
const body = JSON.parse(String(init.body))
const document = estimateDocumentSchema.parse(body.document)
written.push(document)
return response({ record: { ...record, revision: record.revision + written.length, document } })
}
throw new Error('Unexpected request ' + url)
})
})
afterEach(() => { global.fetch = originalFetch })
test('removal autosaves the model and retains previous outputs until Save regenerates them together', async () => {
const { result } = renderHook(() => useStandardEstimator([]))
act(() => result.current.activateRecord({ record, document: installed }))
await act(async () => {
expect(await result.current.saveHardwarePlacements({}, undefined, guards.slice(1))).toBe(true)
})
expect(written).toHaveLength(1)
const saved = written[0]
expect(saved.surfaceHardware).toEqual(guards.slice(1))
expect(saved.stageResults).toEqual(installed.stageResults)
expect(fetchMock.mock.calls.filter(([url]) => url === '/api/intake/accessory-model-drafts')).toHaveLength(0)
await act(async () => { await result.current.save() })
expect(written).toHaveLength(2)
expect(fetchMock.mock.calls.filter(([url]) => url === '/api/intake/accessory-model-drafts')).toHaveLength(1)
expect(fetchMock.mock.calls.filter(([url]) => url === '/api/asset-center/substrates')).toHaveLength(1)
const regenerated = written[1]
expect(regenerated.stageResults!.sampling.connections!.find(item => item.hardware.includes('QT-01'))?.count).toBe(3)
expect(regenerated.stageResults!.packing.hardware).toBe('QT-01 × 3')
const cells = regenerated.stageResults!.cost.standard.cells
const code = Object.keys(cells).find(address => /^C\d+$/.test(address) && cells[address] === guard.code)!
expect(cells['O' + code.slice(1)]).toBe(3)
expect(cells['S' + code.slice(1)]).toBe(.88)
expect(pendingStages(regenerated)).toEqual({ sampling: false, packing: false, cost: false })
act(() => result.current.activateRecord({ record: { ...record, revision: 3 }, document: regenerated }))
expect(result.current.document.surfaceHardware).toEqual(guards.slice(1))
expect(result.current.document.stageResults!.cost.standard.cells).toEqual(cells)
})
test('a failed removal save retains the local edit for retry and preserves previous outputs', async () => {
const { result } = renderHook(() => useStandardEstimator([]))
act(() => result.current.activateRecord({ record, document: installed }))
const original = result.current.document
rejectSave = true
await act(async () => {
expect(await result.current.saveHardwarePlacements({}, undefined, [], ['corner-guard'])).toBe(false)
})
expect(written).toHaveLength(0)
expect(result.current.document.surfaceHardware).toEqual([])
expect(result.current.document.stageResults).toEqual(original.stageResults)
expect(result.current.autosave.status.state).toBe('error')
rejectSave = false
await act(async () => { await result.current.retryModelSave() })
expect(written).toHaveLength(1)
expect(result.current.document.surfaceHardware).toEqual([])
expect(result.current.document.clearedSurfaceHardware).toEqual(['corner-guard'])
expect(result.current.document.stageResults).toEqual(original.stageResults)
await act(async () => { await result.current.save() })
expect(written).toHaveLength(2)
expect(result.current.document.stageResults!.packing.hardware).toBe('')
expect(Object.values(result.current.document.stageResults!.cost.standard.cells)).not.toContain(guard.code)
})

View File

@ -1,6 +1,6 @@
import type { EstimateDocument } from '@/lib/reference-estimator/contracts'
import { recognizedImageCategory } from '@/lib/reference-estimator/standard/cabinet-image-memory'
import { explicitlyRequestsReuse, type ModelTurn } from '@/lib/reference-estimator/standard/model-conversation'
import { explicitlyRequestsReuse, isFollowupSkillSave, type ModelTurn } from '@/lib/reference-estimator/standard/model-conversation'
import { applyStandardRecognition } from '@/lib/reference-estimator/standard/recognition'
import type { ReferenceImageEstimateResult } from '@/server/services/reference-image-estimate/reference-image-estimate-contracts'
import type { ModelAttachment } from '@/lib/reference-estimator/standard/model-attachments'
@ -8,6 +8,10 @@ import { describeModelChange, modelChanged } from '@/lib/reference-estimator/sta
type ApplyOptions = NonNullable<Parameters<typeof applyStandardRecognition>[2]>
export function hasStructurePatch(data: ReferenceImageEstimateResult) {
return Boolean(data.partLabelEdit || data.imageAssemblyEdit || data.cabinetPartEdit || data.cabinetPartEdits || Object.keys(data.cabinetCorrection ?? {}).length)
}
export function recordModelTurn(
before: EstimateDocument, input: string, data?: ReferenceImageEstimateResult, options?: ApplyOptions, failure?: string,
attachments?: ModelAttachment[],
@ -19,14 +23,18 @@ export function recordModelTurn(
...(attachments?.length ? { attachments } : {}),
}
let next = before
const previous = prior.modelConversation?.turns.filter(turn => (turn.imageUrl || '') === (before.imageUrl || '')).at(-1)
const savingSkill = explicitlyRequestsReuse(input, previous)
const onlySaveSkill = isFollowupSkillSave(input, previous)
if (failure) {
turn.outcome = 'failed'
turn.reply = failure
} else if (data) {
const hasPatch = Boolean(data.partLabelEdit || data.imageAssemblyEdit || data.cabinetPartEdit || data.cabinetPartEdits || Object.keys(data.cabinetCorrection ?? {}).length)
const hasPatch = hasStructurePatch(data)
try {
if (data.editRejection) throw new Error(data.editRejection)
const proposed = applyStandardRecognition(before, data, options)
const onlyReply = onlySaveSkill || (!hasPatch && Boolean(data.conversationReply || (savingSkill && data.reusableRule)))
const proposed = onlyReply ? before : applyStandardRecognition(before, data, options)
const model = proposed.standardTemplate?.cabinet
if (model && modelChanged(prior.cabinet, model)) {
next = { ...proposed, title:before.title, standardTemplate:{
@ -40,32 +48,45 @@ export function recordModelTurn(
if (rule && category && next.skillRouting) {
turn.suggestion = { ...rule, category, materialType: next.skillRouting.classification.materialType }
}
if (memory?.case && !explicitlyRequestsReuse(input)) memory.case.autoPublish = []
if (memory?.case && !savingSkill) memory.case.autoPublish = []
if (memory) memory.reviewedNote = before.imageNote
turn.appliedChanges = describeModelChange(prior.cabinet, model)
turn.reply = '本轮模型实际更新:\n' + turn.appliedChanges.join('\n')
turn.reply = '模型已调整:\n' + turn.appliedChanges.join('\n')
} else {
turn.reply = !hasPatch && data.conversationReply ? data.conversationReply : '本轮没有产生模型变化,仍是当前版本。'
turn.reply = onlyReply ? data.conversationReply || '我整理了这条做法。' : '本轮没有产生模型变化,仍是当前版本。'
}
} catch (error) {
const reason = error instanceof Error ? error.message : '模型校验未通过,请核对后重试。'
turn.outcome = !data.editRejection && !hasPatch && data.conversationReply ? 'reply' : 'failed'
turn.reply = turn.outcome === 'reply' ? data.conversationReply! : reason
}
if (savingSkill && data.reusableRule && (turn.outcome === 'updated' || ((!hasPatch || onlySaveSkill) && turn.outcome === 'reply'))) {
const category = recognizedImageCategory(before.skillRouting)
const materialType = before.skillRouting?.classification.materialType
if (category && materialType) {
turn.suggestion = { ...data.reusableRule, category, materialType }
if (turn.outcome === 'reply') turn.reply = '技能做法已整理,入库结果见下方。'
}
else turn.reply += '\n这条规则还没入库:当前款还没有可用的类目和材质。'
}
if (savingSkill && (!hasPatch || onlySaveSkill) && !data.reusableRule && !data.editRejection) {
turn.outcome = 'reply'
turn.reply = '这轮没有存入技能库。请说一下要保存的那条规则。'
}
}
turn.reply = (turn.reply || '模型保持原样。').slice(0, 2000)
if (data?.questions.length && next.standardTemplate?.recognition) {
if (next !== before && data?.questions.length && next.standardTemplate?.recognition) {
next = { ...next, standardTemplate: { ...next.standardTemplate, recognition: {
...next.standardTemplate.recognition,
questions: [...new Set([...next.standardTemplate.recognition.questions, ...data.questions])].slice(-30),
} } }
}
const conversation = prior.modelConversation
const initial = conversation?.initial ?? (prior.cabinet ? { model: prior.cabinet, at: turn.at } : undefined)
const initial = conversation?.initial ?? (!conversation?.initialRemoved && prior.cabinet ? { model: prior.cabinet, at: turn.at } : undefined)
return {
turn,
next: { ...next, standardTemplate: {
...next.standardTemplate!, modelConversation: { initial, turns: [...conversation?.turns ?? [], turn] },
...next.standardTemplate!, modelConversation: { ...conversation, initial, turns: [...conversation?.turns ?? [], turn] },
} },
}
}

View File

@ -0,0 +1,86 @@
.card {
display: grid;
gap: 5px;
min-width: 0;
margin: 6px 10px 10px;
padding: 8px;
border: 1px solid var(--obs-shell-border, #dce1e4);
border-radius: 20px;
background: var(--obs-shell-muted-bg, #f5f6f6);
}
.card:focus-within { border-color: #889592; }
.card > ul { max-height: 96px; overflow: auto; }
/* Mirror the wrapped draft to size the editor; the native input scrolls once it hits the cap. */
.editor {
display: grid;
min-width: 0;
max-height: min(160px, 23svh);
overflow: hidden;
}
.card .editor textarea, .measure {
grid-area: 1 / 1;
box-sizing: border-box;
min-width: 0;
min-height: 44px;
max-height: min(160px, 23svh);
width: 100%;
margin: 0;
padding: 7px 6px;
border: 0;
font: inherit;
font-size: 13px;
line-height: 1.5;
overflow-wrap: anywhere;
white-space: pre-wrap;
}
.measure { visibility: hidden; overflow: hidden; }
.card .editor textarea {
height: 100%;
border-radius: 0;
background: transparent;
outline: none;
box-shadow: none;
resize: none;
overflow-y: auto;
overscroll-behavior: contain;
}
.actions { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
.actions input[hidden] { display: none; }
.actions .iconButton {
min-width: var(--chat-action-size, 36px);
min-height: var(--chat-action-size, 36px);
width: var(--chat-action-size, 36px);
height: var(--chat-action-size, 36px);
padding: 0;
border-radius: 50%;
flex: none;
}
.actions .iconButton:focus-visible { outline: 2px solid #637570; outline-offset: 2px; }
.actions .send { --chat-action-size: 30px; }
.actions .send:disabled { opacity: 0.7; }
.modelPicker { position: relative; margin-left: auto; min-width: 0; }
.modelTrigger {
display: flex; align-items: center; gap: 4px; max-width: 142px; min-height: 30px;
padding: 2px 6px; border-radius: 6px; color: var(--obs-shell-muted, #59636b); font-size: 11px;
}
.modelTrigger span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.modelTrigger svg { flex: none; }
.modelTrigger:hover, .modelTrigger[aria-expanded=true] { background: var(--obs-shell-panel-bg, #fff); }
.modelOptions {
position: absolute; right: 0; bottom: calc(100% + 8px); z-index: 3; width: max-content; min-width: 146px;
max-width: 205px; max-height: min(232px, 40svh); overflow: auto; padding: 4px; border: 1px solid var(--obs-shell-border, #dce1e4);
border-radius: 8px; background: var(--obs-shell-panel-bg, #fff); box-shadow: 0 3px 12px #18292420; font-size: 12px;
}
.modelOptions button, .modelOptions p { display: block; width: 100%; padding: 6px 8px; overflow-wrap: anywhere; text-align: left; }
.modelOptions button { border-radius: 4px; }
.modelOptions button:hover, .modelOptions button[aria-pressed=true] { background: var(--obs-shell-muted-bg, #f5f6f6); }
@media (pointer: coarse) {
.actions .iconButton { min-width: 44px; min-height: 44px; }
.modelTrigger { min-height: 44px; }
}

View File

@ -0,0 +1,64 @@
import { fireEvent, render, screen } from '@testing-library/react'
import { ModelConversationComposer } from './ModelConversationComposer'
const originalFetch = globalThis.fetch
afterEach(() => { globalThis.fetch = originalFetch })
function renderComposer(layout: 'chat' | 'inline' = 'chat') {
const onSend = jest.fn()
render(<ModelConversationComposer layout={layout} disabled={false} placeholder="输入消息" onSend={onSend}/>)
return { onSend, draft: screen.getByRole('textbox', { name: '输入建模纠正' }) }
}
it('多行草稿可按 Enter 发送,选字和 Shift+Enter 不触发提交', () => {
const { onSend, draft } = renderComposer()
fireEvent.keyDown(draft, { key: 'Enter' })
fireEvent.change(draft, { target: { value: '第一行\n第二行' } })
fireEvent.keyDown(draft, { key: 'Enter', shiftKey: true })
fireEvent.compositionStart(draft)
fireEvent.keyDown(draft, { key: 'Enter' })
fireEvent.compositionEnd(draft)
fireEvent.keyDown(draft, { key: 'Enter', keyCode: 229 })
expect(onSend).not.toHaveBeenCalled()
fireEvent.keyDown(draft, { key: 'Enter' })
expect(onSend).toHaveBeenCalledTimes(1)
expect(onSend).toHaveBeenCalledWith('第一行\n第二行', [])
expect(draft).toHaveValue('')
})
it('文件按钮打开选择器,粘贴的截图上传后可移除或用发送按钮提交', async () => {
const { onSend, draft } = renderComposer()
const picker = screen.getByLabelText('选择对话附件')
const openPicker = jest.spyOn(picker, 'click').mockImplementation(() => {})
fireEvent.click(screen.getByRole('button', { name: '添加附件' }))
expect(openPicker).toHaveBeenCalledTimes(1)
const attachment = { name: '截图.png', kind: 'image', url: '/api/storage/object?key=testing.png' }
let sequence = 0
const fetchMock = jest.fn(async () => ({
ok: true,
json: async () => ({ success: true, data: { ...attachment, url: attachment.url + '-' + ++sequence } }),
}) as Response)
globalThis.fetch = fetchMock
const file = new File(['sample'], attachment.name, { type: 'image/png' })
fireEvent.change(picker, { target: { files: [file] } })
expect(screen.getByRole('status')).toHaveTextContent('附件上传中')
fireEvent.keyDown(draft, { key: 'Enter' })
expect(onSend).not.toHaveBeenCalled()
fireEvent.click(await screen.findByRole('button', { name: '移除 截图.png' }))
expect(screen.queryByRole('list', { name: '待发送附件' })).not.toBeInTheDocument()
fireEvent.paste(draft, { clipboardData: { files: [file] } })
await screen.findByRole('list', { name: '待发送附件' })
fireEvent.click(screen.getByRole('button', { name: '发送' }))
expect(fetchMock).toHaveBeenCalledTimes(2)
expect(onSend).toHaveBeenCalledWith('', [{ ...attachment, url: attachment.url + '-2' }])
})
it('打样和包装共用的旧布局保留原有提交方式', () => {
const { onSend, draft } = renderComposer('inline')
fireEvent.change(draft, { target: { value: '调整说明' } })
fireEvent.keyDown(draft, { key: 'Enter' })
expect(onSend).not.toHaveBeenCalled()
fireEvent.click(screen.getByRole('button', { name: '发送' }))
expect(onSend).toHaveBeenCalledWith('调整说明', [])
})

View File

@ -1,5 +1,6 @@
import type { EstimateDocument } from '@/lib/reference-estimator/contracts'
import { applyConversationHardware } from '@/lib/reference-estimator/standard/conversation-hardware'
import { applyConversationHardwareBatch } from '@/lib/reference-estimator/standard/conversation-hardware-batch'
import type { ReferenceImageEstimateResult } from '@/server/services/reference-image-estimate/reference-image-estimate-contracts'
import type { ModelTurn } from '@/lib/reference-estimator/standard/model-conversation'
import { cabinetHardwareFillSummary, type CabinetHardwareFillOptions, type CabinetSkillHardwareResult } from '@/lib/reference-estimator/standard/cabinet-skill-hardware'
@ -7,24 +8,44 @@ import { cabinetHardwareFillSummary, type CabinetHardwareFillOptions, type Cabin
export async function applyHardwareConversation(next: EstimateDocument, data: ReferenceImageEstimateResult,
turn: ModelTurn, recordId: string | undefined,
fill: (document: EstimateDocument, options: CabinetHardwareFillOptions) => Promise<CabinetSkillHardwareResult>) {
if (!data.hardwareEdit && !data.hardwareRejection) return next
if (turn.outcome === 'failed') {
turn.reply += '\n模型未通过检查,本轮未继续调整五金。'
return next
}
const structureUpdated = turn.outcome === 'updated'
const structureReply = turn.reply
const finish = (reply: string, outcome: ModelTurn['outcome']) => {
if (!structureUpdated) turn.outcome = outcome
turn.reply = structureUpdated ? structureReply + '\n' + reply : reply
turn.reply = turn.reply.slice(0, 2000)
}
if (data.hardwareRejection) {
finish('五金未调整:' + data.hardwareRejection, 'failed')
return next
}
if (!data.hardwareEdit) return next
turn.providerModel = data.providerModel?.slice(0, 100)
try {
if (data.hardwareEdit.action === 'fill') {
const { accessoryId, excludeBoardCodes } = data.hardwareEdit
const result = await fill(next, { accessoryId, excludeBoardCodes, restoreClearedSeams: true })
turn.outcome = result.added || result.repaired || result.surfaceAdded ? 'hardware' : 'reply'
turn.reply = cabinetHardwareFillSummary(result).slice(0, 2000)
finish(cabinetHardwareFillSummary(result), result.added || result.repaired || result.surfaceAdded ? 'hardware' : result.pending.length ? 'failed' : 'reply')
return result.document
}
if (data.hardwareEdit.action === 'batch') {
const applied = applyConversationHardwareBatch(next, data.hardwareEdit, recordId)
if (applied.targets.length === 1) turn.hardwareTarget = applied.targets[0]
else turn.hardwareTargets = applied.targets
finish(applied.reply, applied.updated ? 'hardware' : 'reply')
return applied.document
}
const applied = applyConversationHardware(next, data.hardwareEdit, data.hardwareReference, recordId)
turn.hardwareTarget = applied.target
turn.outcome = 'hardware'
turn.reply = applied.reply
finish(applied.reply, 'hardware')
return applied.document
} catch (error) {
turn.outcome = 'failed'
turn.reply = error instanceof Error ? error.message : '本轮五金修改未通过校验。'
finish('五金未调整:' + (error instanceof Error ? error.message : '本轮五金修改未通过校验。'), 'failed')
return next
}
}

View File

@ -0,0 +1,20 @@
import type { AccessoryDraft } from '@/lib/intake-accessory-models'
import { cabinetHardwarePlan } from '@/lib/reference-estimator/standard/cabinet-hardware-plan'
import { withLibraryMachining } from '@/lib/reference-estimator/standard/cabinet-hardware-machining'
import { cabinetPointsBySeam } from '@/lib/reference-estimator/standard/cabinet-through-dowel'
import { readSeamEdits } from '@/lib/reference-estimator/standard/hardware-seam-edits'
import { isRetiredTrialHardware } from '@/lib/reference-estimator/standard/hardware-placement-edits'
import type { ModelRevision } from '@/lib/reference-estimator/standard/model-versions'
export function modelVersionHardware(version: Pick<ModelRevision, 'model' | 'hardwarePlacementEdits' | 'hardwareSeamEdits'>,
items: readonly AccessoryDraft[], barcode?: string, recordId?: string) {
if (!version.hardwarePlacementEdits && !version.hardwareSeamEdits) return
const stored = version.hardwarePlacementEdits ?? {}
const byId = new Map(items.map(item => [item.id, item]))
const edits = Object.fromEntries(Object.entries(stored).filter(([, hardware]) => !isRetiredTrialHardware(hardware))
.map(([key, hardware]) => [key, hardware ? withLibraryMachining(hardware, byId, false) : null]))
const changes = new Map(readSeamEdits(version.hardwareSeamEdits).map(edit => [edit.key, edit]))
const seams = cabinetHardwarePlan(version.model, barcode, recordId, stored).entries.map(({ seam }) => [seam.key, seam] as const)
const plan = [...cabinetPointsBySeam(new Map(seams), changes, edits).values()].flat()
return { edits, plan }
}

View File

@ -0,0 +1,14 @@
.toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 8px; padding-bottom: 6px; }
.toolbar p, .description time { color: var(--obs-shell-muted, #59636b); font-size: 11px; }
.history li { display: flex; align-items: flex-start; justify-content: space-between; gap: 6px; padding: 9px 0; border-bottom: 1px solid var(--obs-shell-border, #e8ece9); }
.description { min-width: 0; overflow-wrap: anywhere; }
.description time { display: block; }
.description p { margin-top: 3px; color: var(--obs-shell-muted, #59636b); }
.actions { display: flex; flex: none; gap: 2px; }
.actions button, .toolbar button { min-height: 28px; padding: 2px 6px; font-size: 11px; }
.form label { display: grid; gap: 6px; }
.form input { min-width: 0; width: 100%; padding: 6px 8px; border: 1px solid var(--obs-shell-border, #dce1e4); border-radius: 6px; }
.error { color: #9d3434; margin-top: 8px; }
@media (pointer: coarse) {
.actions button, .toolbar button { min-height: 44px; }
}

Some files were not shown because too many files have changed in this diff Show More