参考图产品测算
{c.result.boards.reduce((n,b)=>n+b.quantity,0)}块板件 · 柜类结构标准v0.24 · BOM模板1116.1{tab==='cost'&&
{estimated?'预估总成本':'总成本'}{money(c.result.materialTotal)}
{estimated?'预估采购成本':'采购成本'}{money(c.result.total)}
}
- {[['model','1 模型'],['sampling','2 打样资料'],['packing','3 包装'],['cost','4 成本明细']].map(([key,name])=>)}
+ {stages.map(([key,name])=>)}
{settings&&
}
{tab==='model'&&}
diff --git a/furniture-3d-system/src/app/intake/reference-estimator/standard/reference-image-autosave.test.tsx b/furniture-3d-system/src/app/intake/reference-estimator/standard/reference-image-autosave.test.tsx
new file mode 100644
index 00000000..485a355c
--- /dev/null
+++ b/furniture-3d-system/src/app/intake/reference-estimator/standard/reference-image-autosave.test.tsx
@@ -0,0 +1,103 @@
+import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
+import { compressImageFileForUpload } from '@/lib/client-image-compression'
+import { newStandardDocument } from '@/lib/reference-estimator/standard/workbook'
+import { StandardEstimator } from './StandardEstimator'
+
+jest.mock('@/lib/client-image-compression', () => ({
+ compressImageFileForUpload: jest.fn(async (file: File) => file),
+}))
+jest.mock('../EstimateSkillLibrary', () => ({ EstimateSkillLibrary: () => null }))
+jest.mock('./StandardModelPanel', () => ({ StandardModelPanel: () => null }))
+jest.mock('./StandardSamplingPanel', () => ({ StandardSamplingPanel: () => null }))
+jest.mock('./StandardPackingPanel', () => ({ StandardPackingPanel: () => null }))
+jest.mock('./StandardQuotesPanel', () => ({ StandardQuotesPanel: () => null }))
+jest.mock('./StandardRecognitionReview', () => ({ StandardRecognitionReview: () => null }))
+jest.mock('./StandardTemplateTable', () => ({ StandardTemplateTable: () => null }))
+jest.mock('./model-export-images', () => ({ modelExportImages: jest.fn() }))
+
+const recordsUrl = '/api/intake/reference-estimates'
+const imageUrl = '/api/storage/object?key=reference-estimates%2Ftest%2Fimage.jpg'
+const record = { id: 'estimate-test', title: '六格书柜', ruleVersion: 'standard-1116.1', revision: 1 }
+const response = (data: object) => ({ ok: true, json: async () => ({ success: true, data }) })
+const fetchMock = jest.fn()
+const originalFetch = global.fetch
+
+function pasteScreenshot(useItems = false) {
+ const screenshot = new File(['screenshot'], 'screenshot.png', { type: 'image/png' })
+ fireEvent.paste(document.body, {
+ clipboardData: useItems
+ ? { files: [], items: [{ kind: 'file', type: 'image/png', getAsFile: () => screenshot }] }
+ : { files: [screenshot], items: [] },
+ })
+}
+
+beforeEach(() => {
+ fetchMock.mockReset()
+ global.fetch = fetchMock
+ jest.mocked(compressImageFileForUpload).mockClear()
+ jest.spyOn(HTMLElement.prototype, 'getClientRects').mockReturnValue({ length: 1 } as DOMRectList)
+})
+
+afterEach(() => {
+ global.fetch = originalFetch
+ jest.restoreAllMocks()
+})
+
+it('pastes with focus outside the image box, creates a draft, then updates that same estimate with its revision', async () => {
+ const replacement = '/api/storage/object?key=reference-estimates%2Ftest%2Fnew.jpg'
+ fetchMock.mockResolvedValueOnce(response({ records: [] }))
+ .mockResolvedValueOnce(response({ url: imageUrl }))
+ .mockResolvedValueOnce(response({ record }))
+ .mockResolvedValueOnce(response({ url: replacement }))
+ .mockResolvedValueOnce(response({ record: { ...record, revision: 2 } }))
+
+ render()
+ fireEvent.change(screen.getByLabelText('测算单名称'), { target: { value: record.title } })
+ pasteScreenshot(true)
+ expect(await screen.findByText('参考图已保存,已创建测算草稿')).toBeInTheDocument()
+ const [createUrl, create] = fetchMock.mock.calls[2]
+ expect([createUrl, create.method]).toEqual([recordsUrl, 'POST'])
+ expect(JSON.parse(create.body).document).toMatchObject({ title: record.title, imageUrl })
+ expect(screen.getByLabelText('打开已保存测算单')).toHaveValue(record.id)
+
+ pasteScreenshot()
+ expect(await screen.findByText('参考图已保存')).toBeInTheDocument()
+ const [updateUrl, update] = fetchMock.mock.calls[4]
+ expect([updateUrl, update.method]).toEqual([`${recordsUrl}/${record.id}`, 'PUT'])
+ expect(JSON.parse(update.body)).toMatchObject({ revision: 1, document: { imageUrl: replacement } })
+ expect(screen.getByAltText('参考图预览')).toHaveAttribute('src', replacement)
+})
+
+it('keeps the uploaded reference and retries saving without uploading a second time', async () => {
+ fetchMock.mockResolvedValueOnce(response({ records: [record] }))
+ .mockResolvedValueOnce(response({ record: { ...record, document: { ...newStandardDocument(), title: record.title } } }))
+ .mockResolvedValueOnce(response({ url: imageUrl }))
+ .mockResolvedValueOnce({ ok: false, json: async () => ({ success: false, error: { message: '服务暂时不可用' } }) })
+ .mockResolvedValueOnce(response({ record: { ...record, revision: 2 } }))
+
+ render()
+ const select = screen.getByLabelText('打开已保存测算单')
+ await within(select).findByRole('option', { name: record.title })
+ fireEvent.change(select, { target: { value: record.id } })
+ await screen.findByText('已打开测算单')
+
+ pasteScreenshot()
+ expect(await screen.findByRole('alert')).toHaveTextContent('参考图已上传,测算单保存失败')
+ expect(screen.getByAltText('参考图预览')).toHaveAttribute('src', imageUrl)
+ fireEvent.click(screen.getByRole('button', { name: '重试保存' }))
+ await screen.findByText('参考图已保存')
+ expect(fetchMock.mock.calls.filter(([url]) => url === `${recordsUrl}/image`)).toHaveLength(1)
+ expect(JSON.parse(fetchMock.mock.calls[4][1].body)).toMatchObject({ revision: 1, document: { imageUrl } })
+})
+
+it('leaves the document untouched if uploading fails', async () => {
+ fetchMock.mockResolvedValueOnce(response({ records: [] }))
+ .mockResolvedValueOnce({ ok: false, json: async () => ({ success: false, error: { message: '无法读取图片' } }) })
+
+ render()
+ pasteScreenshot()
+ expect(await screen.findByRole('alert')).toHaveTextContent('参考图上传失败')
+ expect(screen.queryByAltText('参考图预览')).not.toBeInTheDocument()
+ await waitFor(() => expect(screen.getByRole('button', { name: '保存', exact: true })).toBeEnabled())
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+})
diff --git a/furniture-3d-system/src/app/intake/reference-estimator/standard/reference-image-paste.ts b/furniture-3d-system/src/app/intake/reference-estimator/standard/reference-image-paste.ts
new file mode 100644
index 00000000..83ed5eac
--- /dev/null
+++ b/furniture-3d-system/src/app/intake/reference-estimator/standard/reference-image-paste.ts
@@ -0,0 +1,35 @@
+import { useEffect, useEffectEvent, type RefObject } from 'react'
+
+function clipboardImage(data: DataTransfer | null): File | undefined {
+ if (!data) return
+ const isImage = (file: File) => file.type.startsWith('image/')
+ return Array.from(data.files ?? []).find(isImage)
+ ?? Array.from(data.items ?? [])
+ .filter(item => item.kind === 'file' && item.type.startsWith('image/'))
+ .map(item => item.getAsFile())
+ .find((file): file is File => file !== null)
+}
+
+export function useReferenceImagePaste(
+ workbench: RefObject,
+ upload: (file: File) => Promise,
+ busy: boolean,
+) {
+ const paste = useEffectEvent((event: ClipboardEvent) => {
+ const root = workbench.current
+ if (event.defaultPrevented || !root || root.closest('[hidden], [inert], [aria-hidden="true"]')) return
+ const target = event.target
+ if (target !== document && target !== document.body && !(target instanceof Node && root.contains(target))) return
+ if (!root.getClientRects().length) return
+ const file = clipboardImage(event.clipboardData)
+ if (!file) return
+ event.preventDefault()
+ if (!busy) void upload(file)
+ })
+
+ useEffect(() => {
+ const listener = (event: ClipboardEvent) => paste(event)
+ window.addEventListener('paste', listener)
+ return () => window.removeEventListener('paste', listener)
+ }, [])
+}
diff --git a/furniture-3d-system/src/app/intake/reference-estimator/standard/useStandardEstimator.ts b/furniture-3d-system/src/app/intake/reference-estimator/standard/useStandardEstimator.ts
index d927b8bb..0817b46d 100644
--- a/furniture-3d-system/src/app/intake/reference-estimator/standard/useStandardEstimator.ts
+++ b/furniture-3d-system/src/app/intake/reference-estimator/standard/useStandardEstimator.ts
@@ -1,6 +1,6 @@
'use client'
-import { useEffect, useMemo, useState } from 'react'
+import { useEffect, useEffectEvent, useMemo, useRef, useState } from 'react'
import { estimateDocumentSchema, type EstimateDocument } from '@/lib/reference-estimator/contracts'
import type { StandardTemplate } from '@/lib/reference-estimator/standard/contracts'
import { calculateStandard } from '@/lib/reference-estimator/standard/calculate'
@@ -9,6 +9,8 @@ import { compressImageFileForUpload } from '@/lib/client-image-compression'
import type { SubstrateDTO } from '@/server/services'
import { buildNonIntegratedBomBoardMaterialOptions } from '@/lib/non-integrated-bom-board-materials'
import { toMaterialSnapshot } from '../useEstimateController'
+import { clearReferenceEstimateLinkUnless, linkedReferenceEstimateId, pushEstimateToProductLibrary, referenceEstimateWorkspaceKey } from '../referenceEstimateLinks'
+import { readWorkspacePosition, writeWorkspacePosition } from '@/lib/workspace-session-state'
import { applySelectedMaterials } from '@/lib/reference-estimator/standard/materials'
import { withStandardTemplate } from '@/lib/reference-estimator/standard/legacy-input'
import { importEstimateWorkbook } from '@/lib/reference-estimator/workbook-import'
@@ -24,23 +26,31 @@ import { applyStandardMaterial } from '@/lib/reference-estimator/standard/materi
import { modelExportImages } from './model-export-images'
import { applyPackagingMaterials } from '@/lib/reference-estimator/standard/packaging'
import { completeStandardCosts } from '@/lib/reference-estimator/standard/cabinet-costs'
+import { withSelectedCabinetInputs } from '@/lib/reference-estimator/standard/cabinet-material-selection'
+import type { ReferenceImageFeedback } from '../EstimateInputPanel'
type RecordSummary={id:string;title:string;ruleVersion:string;revision:number}
+class EstimateRequestError extends Error {
+ constructor(message:string,readonly status:number){super(message)}
+}
async function request(url:string,init?:RequestInit):Promise{
- const response=await fetch(url,init),body=await response.json()
- if(!response.ok||!body.success)throw new Error(body.error?.message??'请求失败')
+ const response=await fetch(url,init),body=await response.json().catch(()=>null)
+ if(!response.ok||!body?.success)throw new EstimateRequestError(body?.error?.message??(response.status===401?'登录已失效,请重新登录。':'请求失败,请重试。'),response.status)
return body.data
}
function download(bytes:BlobPart,name:string,mime:string){
const url=URL.createObjectURL(new Blob([bytes],{type:mime})),a=document.createElement('a')
a.href=url;a.download=name.replace(/[\\/:*?"<>|]/g,'_');a.click();setTimeout(()=>URL.revokeObjectURL(url),1000)
}
-export function useStandardEstimator(substrates:SubstrateDTO[]){
+export function useStandardEstimator(substrates:SubstrateDTO[],userId?:string){
const options=useMemo(()=>[...quotaBoardOptions(),...buildNonIntegratedBomBoardMaterialOptions(substrates)],[substrates])
const initial=()=>newStandardDocument()
const [storedDocument,setDocument]=useState(initial),[record,setRecord]=useState(null),[records,setRecords]=useState([])
const document=useMemo(()=>completeStandardCosts(storedDocument),[storedDocument])
const [dirty,setDirty]=useState(false),[busy,setBusy]=useState(''),[message,setMessage]=useState(''),[error,setError]=useState('')
+ const [imageFeedback, setImageFeedback] = useState()
+ const [imageBusy, setImageBusy] = useState(false)
+ const running = useRef(false)
const standard=document.standardTemplate!
const result=useMemo(()=>calculateStandard(standard),[standard])
const questions=useMemo(()=>standardQuestions(document),[document])
@@ -57,12 +67,14 @@ export function useStandardEstimator(substrates:SubstrateDTO[]){
try{const next=fn(document),materialsChanged=document.mainMaterial!==next.mainMaterial||document.backMaterial!==next.backMaterial
const model=next.standardTemplate?.cabinet,back=next.backMaterial
if(model&&document.backMaterial?.id!==back?.id){
- const choice=options.find(o=>o.id===back?.id)
- if(!choice)throw new Error('请选择完整的背板材料规格。')
- if(choice.environmentGradeName!==model.input.grade||choice.surfaceOptionName!==model.input.veneer)throw new Error('背板环保等级或贴面与当前模型不同,请补充确认背板单独的材料要求。')
- setDocument(applyCabinetWorkflow(next,{...model.input,backThickness:choice.thicknessMm,backColor:choice.finishNames[0]??''}));setDirty(true);return
+ if(!back?.selection)throw new Error('请选择完整的背板材料规格。')
+ setDocument(applyCabinetWorkflow(next,withSelectedCabinetInputs(model.input,next)));setDirty(true);setError('');return
}
if(model&&materialsChanged){
+ if ((['mainMaterial', 'backMaterial'] as const).some(key =>
+ next[key]?.selection && document[key]?.sheetPrice !== next[key]?.sheetPrice)) {
+ setDocument(applyCabinetWorkflow(next,model.input));setDirty(true);setError('');return
+ }
let s=next.standardTemplate!
for(const [key,roles] of [['mainMaterial',['side','shelf','bottom','divider','kick','rail']],['backMaterial',['back']]] as const){
const m=next[key];if(m&&document[key]?.sheetPrice!==m.sheetPrice)for(const [i,p] of model.parts.entries())if((roles as readonly string[]).includes(p.role))s=applyStandardMaterial(s,boardRowAt(i),{...m,name:p.material?.name??m.name},true)
@@ -72,29 +84,95 @@ export function useStandardEstimator(substrates:SubstrateDTO[]){
setDocument(applySelectedMaterials(materialsChanged?rebuildStandardSkill(next):next,materialsChanged));setDirty(true)
}catch(e){setError(e instanceof Error?e.message:'修改失败')}
}
- const chooseMain=(id:string)=>{const m=options.find(o=>o.id===id);if(!m)return
- if(standard.cabinet){setCabinetInput({...standard.cabinet.input,material:m.categoryName,grade:m.environmentGradeName,bodyColor:m.finishNames[0]??'',thickness:m.thicknessMm,veneer:m.surfaceOptionName??''});return}
- const b=options.find(o=>o.categoryName.includes('三合')&&o.thicknessMm===document.settings.backThicknessMm&&o.finishNames.some(n=>m.finishNames.includes(n))&&o.surfaceOptionName?.includes('双'));updateDocument(current=>({...current,mainMaterial:toMaterialSnapshot(m),backMaterial:b?toMaterialSnapshot(b):null}))}
- const setCabinetInput=(input:CabinetInput)=>{try{setDocument(current=>applyCabinetWorkflow(current,input));setDirty(true);setError('')}catch(cause){setError(cause instanceof Error?cause.message:'更新失败')}}
+ const chooseMain=(id:string)=>{
+ const m=options.find(o=>o.id===id);if(!m)return
+ const mainMaterial=toMaterialSnapshot(m,true)
+ if(standard.cabinet){
+ const next={...document,mainMaterial}
+ setCabinetInput(withSelectedCabinetInputs(standard.cabinet.input,next),next);return
+ }
+ const b=options.find(o=>o.categoryName.includes('三合')&&o.thicknessMm===document.settings.backThicknessMm&&o.finishNames.some(n=>m.finishNames.includes(n))&&o.surfaceOptionName?.includes('双'))
+ updateDocument(current=>({...current,mainMaterial,backMaterial:current.backMaterial?.selection?current.backMaterial:b?toMaterialSnapshot(b):null}))
+ }
+ const setCabinetInput=(input:CabinetInput, current=document)=>{
+ try{setDocument(applyCabinetWorkflow(current,input));setDirty(true);setError('')}
+ catch(cause){setError(cause instanceof Error?cause.message:'更新失败')}
+ }
const title=(value:string)=>{setDocument(current=>({...current,title:value,standardTemplate:{...current.standardTemplate!,cells:{...current.standardTemplate!.cells,C2:value}}}));setDirty(true)}
- const run=async(label:string,fn:()=>Promise|void)=>{setBusy(label);setMessage('');setError('');try{await fn()}catch(e){setError(e instanceof Error?e.message:'操作失败')}finally{setBusy('')}}
+ const run = async (label: string, action: () => Promise | void) => {
+ if (running.current) return
+ running.current = true
+ setBusy(label)
+ setMessage('')
+ setError('')
+ try {
+ await action()
+ } catch (cause) {
+ setError(cause instanceof Error ? cause.message : '操作失败')
+ } finally {
+ running.current = false
+ setBusy('')
+ }
+ }
const refresh=async()=>{const data=await request<{records:RecordSummary[]}>('/api/intake/reference-estimates');setRecords(data.records)}
useEffect(()=>{void refresh().catch(e=>setError(e.message))},[])
useEffect(()=>{const handler=(e:BeforeUnloadEvent)=>{if(dirty){e.preventDefault();e.returnValue=''}};window.addEventListener('beforeunload',handler);return()=>window.removeEventListener('beforeunload',handler)},[dirty])
- const replace=(next:EstimateDocument,saved:RecordSummary|null)=>{setDocument(next);setRecord(saved);setDirty(!saved)}
- const newDocument=()=>{if(dirty&&!window.confirm('当前修改尚未保存,确定新建吗?'))return;replace({...newStandardDocument(),mainMaterial:document.mainMaterial,backMaterial:document.backMaterial},null);setDirty(false);setMessage('已新建测算单')}
- const open=async(id:string)=>{if(dirty&&!window.confirm('当前修改尚未保存,确定打开其他测算单吗?'))return;await run('打开中…',async()=>{
- const data=await request<{record:RecordSummary&{document:EstimateDocument}}>(`/api/intake/reference-estimates/${id}`)
+ const rememberRecord=(saved:RecordSummary|null)=>{
+ writeWorkspacePosition(userId,referenceEstimateWorkspaceKey,'record',saved?.id??null)
+ clearReferenceEstimateLinkUnless(saved?.id)
+ }
+ const replace=(next:EstimateDocument,saved:RecordSummary|null)=>{
+ setDocument(next);setRecord(saved);setDirty(!saved);setImageFeedback(undefined)
+ rememberRecord(saved)
+ }
+ const newDocument=()=>{if(dirty&&!window.confirm('当前修改尚未保存,确定新建吗?'))return;replace(newStandardDocument(),null);setDirty(false);setMessage('已新建测算单')}
+ const open=async(id:string,fromMemory=false)=>{if(dirty&&!window.confirm('当前修改尚未保存,确定打开其他测算单吗?'))return;await run('打开中…',async()=>{
+ const data=await request<{record:RecordSummary&{document:EstimateDocument}}>(`/api/intake/reference-estimates/${encodeURIComponent(id)}`).catch(error=>{
+ if(fromMemory&&error instanceof EstimateRequestError&&error.status===404){
+ writeWorkspacePosition(userId,referenceEstimateWorkspaceKey,'record',null)
+ return null
+ }
+ throw error
+ })
+ if(!data)return
const parsed=estimateDocumentSchema.parse(data.record.document),wasLegacy=!parsed.standardTemplate,next=withStandardTemplate(parsed)
calculateStandard(next.standardTemplate!);replace(next,data.record);setDirty(wasLegacy);setMessage(wasLegacy?'已载入保存的板件,新模板内容将另存为测算单':'已打开测算单')
})}
+ const openedEstimateLink=useRef(false)
+ const openFromLink=useEffectEvent(open)
+ useEffect(()=>{
+ if(openedEstimateLink.current)return
+ openedEstimateLink.current=true
+ const linked=linkedReferenceEstimateId(window.location.search)
+ const id=linked??readWorkspacePosition(userId,referenceEstimateWorkspaceKey,'record')
+ if(id&&id.length<=150)void openFromLink(id,!linked)
+ },[userId])
+ const persist = async (next: EstimateDocument, asNew = false) => {
+ const parsed = estimateDocumentSchema.parse(next)
+ const existing = !asNew && record?.ruleVersion === 'standard-1116.1' ? record : null
+ const endpoint = existing ? `/api/intake/reference-estimates/${existing.id}` : '/api/intake/reference-estimates'
+ const data = await request<{ record: RecordSummary }>(endpoint, {
+ method: existing ? 'PUT' : 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ document: parsed, revision: existing?.revision }),
+ })
+ setRecord(data.record)
+ rememberRecord(data.record)
+ setRecords(current => [data.record, ...current.filter(item => item.id !== data.record.id)])
+ setDirty(false)
+ }
const save=async(asNew=false)=>run('保存中…',async()=>{
- const parsed=estimateDocumentSchema.parse(document)
- const existing=record?.ruleVersion==='standard-1116.1'&&!asNew
- const data=await request<{record:RecordSummary}>(existing?`/api/intake/reference-estimates/${record.id}`:'/api/intake/reference-estimates',{
- method:existing?'PUT':'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({document:parsed,revision:record?.revision})})
- setRecord(data.record);setDirty(false);setMessage('已保存');await refresh()
+ await persist(document, asNew)
+ if (imageFeedback?.retrySave) setImageFeedback({ text: '参考图已保存' })
+ setMessage('已保存')
})
+ const pushToProductLibrary=async()=>{
+ if(!record||dirty)return
+ await run('推送到产品资料中…',async()=>{
+ const href=await pushEstimateToProductLibrary(record)
+ window.location.assign(href)
+ })
+ }
const excel=async()=>run('生成Excel中…',async()=>{
const [image,modelImages]=await Promise.all([prepareEstimateExportImage(document.imageUrl),modelExportImages(standard.cabinet)]),bytes=await exportStandardWorkbook(estimateDocumentSchema.parse(document),undefined,image,modelImages);download(bytes as BlobPart,document.title+'-BOM.xlsx','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');setMessage('Excel已下载,版式沿用原模板')
})
@@ -126,23 +204,57 @@ export function useStandardEstimator(substrates:SubstrateDTO[]){
download(await response.blob(),document.title+'-结构模型.step','application/step')
setMessage('STEP 已下载')
})
- const upload=async(file:File)=>run('上传参考图中…',async()=>{
- const prepared=await compressImageFileForUpload(file,{targetBytes:2*1024*1024,hardLimitBytes:20*1024*1024,maxDimension:2000}),form=new FormData();form.append('file',prepared)
- const data=await request<{url:string}>('/api/intake/reference-estimates/image',{method:'POST',body:form})
- setDocument(current=>({...current,imageUrl:data.url}));setDirty(true);setMessage('参考图已上传')
+ const upload = async (file: File) => run('上传参考图中…', async () => {
+ setImageBusy(true)
+ setImageFeedback({ text: '正在上传参考图…' })
+ let next: EstimateDocument | undefined
+ try {
+ const prepared = await compressImageFileForUpload(file, {
+ targetBytes: 2 * 1024 * 1024,
+ hardLimitBytes: 20 * 1024 * 1024,
+ maxDimension: 2000,
+ })
+ const form = new FormData()
+ form.append('file', prepared)
+ const { url } = await request<{ url: string }>('/api/intake/reference-estimates/image', { method: 'POST', body: form })
+ if (typeof url !== 'string' || !url.startsWith('/api/storage/object?')) {
+ throw new Error('系统没有返回可保存的图片,请重新上传。')
+ }
+ const title = document.title.trim() || '未命名测算'
+ next = {
+ ...document,
+ title,
+ imageUrl: url,
+ standardTemplate: { ...standard, cells: { ...standard.cells, C2: title } },
+ }
+ setDocument(next)
+ setDirty(true)
+ setImageFeedback({ text: '正在保存测算单…' })
+ await persist(next)
+ setImageFeedback({ text: record ? '参考图已保存' : '参考图已保存,已创建测算草稿' })
+ } catch (cause) {
+ const detail = cause instanceof Error ? cause.message : '请重试。'
+ setImageFeedback({
+ text: next ? `参考图已上传,测算单保存失败。 ${detail}` : `参考图上传失败。 ${detail}`,
+ error: true,
+ retrySave: Boolean(next),
+ })
+ } finally {
+ setImageBusy(false)
+ }
})
const analyze=async(input?:EstimateDocument)=>{
if(!input&&result.boards.length&&!window.confirm('重新识别会更新当前板件行,继续吗?'))return
await run('识别结构并按技能拆BOM…',async()=>{
const before=input??document,data=await recognizeStandardImage(before),next=applyStandardRecognition(before,data)
- replace(next,record);setDirty(true)
+ setDocument(next);setDirty(true)
const count=next.pieces.reduce((n,p)=>n+p.quantity,0),skill=next.skillRouting
setMessage(next.standardTemplate!.cabinet?`已按柜类技能生成模型和预估 BOM,共${count}块板件。`:next.standardTemplate!.recognition?.generatedBySkill?`已匹配技能(${skill?.version}),生成${count}块板件并填入标准BOM模板。`:
count?`已填入${count}块有明确尺寸的板件,其余请补充待确认信息。`:'已保留识别资料,请补充下方待确认信息后继续。')
})
}
const answer=async(text:string)=>{if(!text.trim())return;await analyze({...document,imageNote:[document.imageNote,text.trim()].filter(Boolean).join('\n')})}
- const remove=async()=>{if(!record||!window.confirm(`确定删除测算单“${record.title}”吗?`))return;await run('删除中…',async()=>{await request(`/api/intake/reference-estimates/${record.id}`,{method:'DELETE',headers:{'Content-Type':'application/json'},body:JSON.stringify({revision:record.revision})});replace({...newStandardDocument(),mainMaterial:document.mainMaterial,backMaterial:document.backMaterial},null);setDirty(false);await refresh();setMessage('已删除测算单')})}
- return {document,standard,result,questions,record,records,dirty,busy,message,error,update,updateDocument,options,chooseMain,title,run,newDocument,open,save,excel,importFile,pdf,samplingPdf,step,setCabinetInput,upload,analyze,answer,remove}
+ const remove=async()=>{if(!record||!window.confirm(`确定删除测算单“${record.title}”吗?`))return;await run('删除中…',async()=>{await request(`/api/intake/reference-estimates/${record.id}`,{method:'DELETE',headers:{'Content-Type':'application/json'},body:JSON.stringify({revision:record.revision})});replace(newStandardDocument(),null);setDirty(false);await refresh();setMessage('已删除测算单')})}
+ return {document,standard,result,questions,record,records,dirty,busy,message,error,imageBusy,imageFeedback,update,updateDocument,options,chooseMain,title,run,newDocument,open,save,pushToProductLibrary,excel,importFile,pdf,samplingPdf,step,setCabinetInput,upload,analyze,answer,remove}
}
export type StandardController=ReturnType
diff --git a/furniture-3d-system/src/app/intake/reference-estimator/useEstimateController.ts b/furniture-3d-system/src/app/intake/reference-estimator/useEstimateController.ts
index 214c1420..bb3db997 100644
--- a/furniture-3d-system/src/app/intake/reference-estimator/useEstimateController.ts
+++ b/furniture-3d-system/src/app/intake/reference-estimator/useEstimateController.ts
@@ -22,10 +22,14 @@ export async function estimateRequest(url: string, init?: RequestInit): Promi
if (!response.ok || !payload?.success) throw new Error(payload?.error?.message || payload?.message || '请求失败')
return payload.data
}
-export function toMaterialSnapshot(option: NonIntegratedBomBoardMaterialOption): MaterialSnapshot {
+export function toMaterialSnapshot(option: NonIntegratedBomBoardMaterialOption, explicitlySelected = false): MaterialSnapshot {
return { id: option.id, code: option.code, name: option.selectionLabel, thicknessMm: option.thicknessMm,
sheetLengthMm: option.sheetLengthMm, sheetWidthMm: option.sheetWidthMm,
- sheetPrice: option.suggestedPrice, sheetWeightKg: option.weightKg }
+ sheetPrice: option.suggestedPrice, sheetWeightKg: option.weightKg,
+ ...(explicitlySelected ? { selection: {
+ category: option.categoryName, grade: option.environmentGradeName,
+ color: option.finishNames[0] ?? '', veneer: option.surfaceOptionName ?? '',
+ } } : {}) }
}
export function useEstimateController(substrates: SubstrateDTO[]) {
const options = useMemo(() => buildNonIntegratedBomBoardMaterialOptions(substrates), [substrates])
diff --git a/furniture-3d-system/src/app/intake/useIntakeClientViewModel.ts b/furniture-3d-system/src/app/intake/useIntakeClientViewModel.ts
index 3ffde5d4..950784e3 100644
--- a/furniture-3d-system/src/app/intake/useIntakeClientViewModel.ts
+++ b/furniture-3d-system/src/app/intake/useIntakeClientViewModel.ts
@@ -1,5 +1,6 @@
"use client";
+import { useEffect, useRef } from "react";
import type {
IntakeClientWorkspaceViewProps,
} from "@/app/intake/IntakeClientWorkspaceView";
@@ -22,6 +23,7 @@ import { useIntakeWorkspaceActivation } from "@/app/intake/useIntakeWorkspaceAct
import { useInitialNewNonIntegratedProductWorkspace } from "@/app/intake/useInitialNewNonIntegratedProductWorkspace";
import { useIntakeInitialWorkspaceState } from "@/app/intake/useIntakeInitialWorkspaceState";
import { useIntakeMaterialLibraryFinishes } from "@/app/intake/useIntakeMaterialLibraryFinishes";
+import { linkedReferenceEstimateId } from "@/app/intake/reference-estimator/referenceEstimateLinks";
import { buildIntakeClientDerivedData } from "@/app/intake/intakeClientDerivedData";
import { canCreateNonIntegratedProductFromIntake } from "@/lib/non-integrated-permissions";
import {
@@ -215,6 +217,13 @@ export function useIntakeClientViewModel(
user: props.user,
workspaceTabs,
});
+ const openedEstimateLink = useRef(false);
+ useEffect(() => {
+ if (!workspaceStateReady || !canViewReferenceEstimator || openedEstimateLink.current) return;
+ if (!linkedReferenceEstimateId(window.location.search)) return;
+ openedEstimateLink.current = true;
+ openReferenceEstimatorWorkspace();
+ }, [workspaceStateReady, canViewReferenceEstimator, openReferenceEstimatorWorkspace]);
useInitialNewNonIntegratedProductWorkspace({
canCreateNonIntegratedProducts,
@@ -311,6 +320,10 @@ export function useIntakeClientViewModel(
: null,
activeSection,
onToggle: (section) => {
+ if (section === "referenceEstimator") {
+ openReferenceEstimatorWorkspace();
+ return;
+ }
setActiveWorkspaceTabId(null);
toggleActiveSection(section);
},
diff --git a/furniture-3d-system/src/lib/reference-estimator/__tests__/cabinet-workflow.test.ts b/furniture-3d-system/src/lib/reference-estimator/__tests__/cabinet-workflow.test.ts
index 16f7aefd..ddae4111 100644
--- a/furniture-3d-system/src/lib/reference-estimator/__tests__/cabinet-workflow.test.ts
+++ b/furniture-3d-system/src/lib/reference-estimator/__tests__/cabinet-workflow.test.ts
@@ -1,7 +1,9 @@
/** @jest-environment node */
-import { cabinetInputSchema } from '../standard/cabinet-contracts'
+import { cabinetInputSchema, type CabinetInput } from '../standard/cabinet-contracts'
import { buildCabinetModel } from '../standard/cabinet-model'
import { applyCabinetWorkflow } from '../standard/cabinet-workflow'
+import { withSelectedCabinetInputs } from '../standard/cabinet-material-selection'
+import { boardRowAt } from '../standard/rows'
import { newStandardDocument, exportStandardWorkbook, importStandardWorkbook } from '../standard/workbook'
import { estimateDocumentSchema } from '../contracts'
import { packingScene } from '../standard/packaging'
@@ -30,7 +32,8 @@ describe('cabinet standard v0.24 shared model workflow',()=>{
expect(m.issues.join(' ')).toContain('拟定')
})
test('does not apply case dimensions to an unrelated cabinet or substitute grades and colors',()=>{
- expect(()=>buildCabinetModel(cabinetInputSchema.parse({width:1200,depth:320,height:900,columns:3,rows:2,thickness:15}))).toThrow('缺少可用的暂估案例')
+ expect(()=>buildCabinetModel(cabinetInputSchema.parse({width:1200,depth:320,height:900,columns:4,rows:2,thickness:15}))).toThrow('缺少可用的暂估案例')
+ expect(()=>buildCabinetModel(cabinetInputSchema.parse({width:974,depth:380,height:654,columns:3,rows:2}))).toThrow('生成模型还需要:板厚')
expect(matchCabinetMaterial('生态板','E0级','荷花白色','双贴',15)).toBeNull()
expect(matchCabinetMaterial('生态板','E1级','胡桃色','双贴',15)).toBeNull()
expect(quotaHardware('A206')?.price).toBeNull()
@@ -109,6 +112,38 @@ describe('cabinet standard v0.24 shared model workflow',()=>{
expect(result.skillRouting.skillId).toBe('cabinet-standard')
expect(buildReferenceImageEstimatePrompt({estimationMode:'standard-template',fileName:'',imageNote:'',materialName:'',boardThicknessMm:null,imageDataUrl:'data:image/png;base64,AA=='})).toContain('柜类家具结构标准v0.24')
})
+ test('saved library selections and their prices survive recognition and cabinet rebuilds',()=>{
+ const main=matchCabinetMaterial('生态板','E1级','荷花白色','双贴',15)!
+ const back=matchCabinetMaterial('三合板','E1级','经典北美黑胡桃色','双贴',2.2)!
+ const chosen={
+ mainMaterial:{...main,id:'library-main',sheetPrice:109,sheetWeightKg:28,
+ selection:{category:'生态板',grade:'E1级',color:'荷花白色',veneer:'双贴'}},
+ backMaterial:{...back,id:'library-back',sheetPrice:35,
+ selection:{category:'三合板',grade:'E0级',color:'经典北美黑胡桃色',veneer:'单贴'}},
+ }
+ const selection={...newStandardDocument(),...chosen}
+ const recognition=parseReferenceImageEstimateResult(JSON.stringify({
+ recognition:{hasDoors:false,hasDrawers:false},
+ cabinet:{...input(),material:'刨花板',grade:'E0级',bodyColor:'木纹色',veneer:'单贴',thickness:12,backThickness:3},
+ }))
+ const first=applyStandardRecognition(selection,recognition)
+ const saved=estimateDocumentSchema.parse(JSON.parse(JSON.stringify(first)))
+ const model=saved.standardTemplate!.cabinet!
+ expect(saved.mainMaterial).toMatchObject({id:'library-main',sheetPrice:109,selection:chosen.mainMaterial.selection})
+ expect(saved.backMaterial).toMatchObject({id:'library-back',sheetPrice:35,selection:chosen.backMaterial.selection})
+ expect(model.input).toMatchObject({thickness:15,backThickness:2.2,grade:'E1级',topColor:'经典北美黑胡桃色',bodyColor:'荷花白色'})
+ const sideRow=boardRowAt(model.parts.findIndex(p=>p.role==='side')),backRow=boardRowAt(model.parts.findIndex(p=>p.role==='back'))
+ expect(model.parts[0].material?.id).not.toBe('library-main')
+ expect(saved.standardTemplate!.cells['G'+backRow]).toBe('单贴')
+ expect(saved.standardTemplate!.materialQuotes[sideRow]).toMatchObject({id:'library-main',sheetPrice:109,sheetWeight:28})
+ expect(saved.standardTemplate!.materialQuotes[backRow]).toMatchObject({id:'library-back',sheetPrice:35})
+ const changed={...saved,mainMaterial:{...saved.mainMaterial!,sheetPrice:119}}
+ const rebuilt=applyCabinetWorkflow(changed,withSelectedCabinetInputs(model.input,changed))
+ expect(rebuilt.standardTemplate!.materialQuotes[sideRow]).toMatchObject({id:'library-main',sheetPrice:119})
+ expect(rebuilt.standardTemplate!.cells['S'+sideRow]).toBeCloseTo(119*1e6/(main.sheetLengthMm*main.sheetWidthMm))
+ expect(rebuilt.standardTemplate!.cabinet!.parts.find(p=>p.role==='side')?.material?.sheetPrice).toBe(119)
+ expect(rebuilt.standardTemplate!.materialQuotes[backRow]).toMatchObject({id:'library-back',sheetPrice:35})
+ })
test('null optional text does not discard a recognized model, and new incomplete images do not reuse stale geometry',()=>{
const recognized={recognition:{classification:{materialType:'板式',primaryCategory:'柜类',secondaryCategory:'书柜',placement:'落地'},hasDoors:false,hasDrawers:false},cabinet:{...input(),hardwareCode:null,screwCode:null,clipCode:null},boardPieces:[],hardwareItems:[]}
const parsed=parseReferenceImageEstimateResult(JSON.stringify(recognized))
@@ -146,7 +181,7 @@ describe('cabinet standard v0.24 shared model workflow',()=>{
})
test('keeps the model and board estimate if the carton needs to be split',()=>{
const former=applyCabinetWorkflow(newStandardDocument(),input())
- const next=applyCabinetWorkflow(former,{...input(),width:1600})
+ const next=applyCabinetWorkflow(former,{...former.standardTemplate!.cabinet!.input,width:1600})
const standard=next.standardTemplate!
expect(standard.cabinet?.parts[0].length).toBe(1600)
expect(packingScene(standard).assessment.split).toBe(true)
@@ -154,6 +189,50 @@ describe('cabinet standard v0.24 shared model workflow',()=>{
expect(standard.recognition?.summary).toContain('未计待确认包材')
expect(calculateStandard(standard).total).toBeGreaterThan(0)
})
+ test('the 380 mm open cabinet derives board depths from its own dimensions and keeps case estimates traceable',()=>{
+ const result=parseReferenceImageEstimateResult(JSON.stringify({
+ recognition:{hasDoors:false,hasDrawers:false},
+ overallDimensions:{widthMm:974,depthMm:380,heightMm:654},
+ cabinet:{name:'六格开放柜',columns:3,rows:2},
+ }))
+ const document=applyStandardRecognition({
+ ...newStandardDocument(),
+ mainMaterial:matchCabinetMaterial('生态板','E1级','荷花白色','双贴',15)!,
+ backMaterial:{...matchCabinetMaterial('生态板','E1级','荷花白色','双贴',15)!,thicknessMm:3},
+ },result)
+ const standard=document.standardTemplate!,model=standard.cabinet!
+ expect(model.input).toMatchObject({
+ referenceCase:null,width:974,depth:380,height:654,thickness:15,backThickness:3,
+ innerDepth:350,bottomDepth:365,caseEstimateDepth:380,
+ })
+ expect(model.parts.reduce((total,part)=>total+part.quantity,0)).toBe(10)
+ expect(model.parts.find(part=>part.role==='back')).toMatchObject({width:634,quantity:1})
+ expect(model.parts.some(part=>part.role==='kick'||part.role==='rail')).toBe(false)
+ expect(standard.cells).toMatchObject({O68:28,O69:0,P69:0,O74:4,O94:0})
+ expect(model.parts.find(part=>part.role==='top')?.width).toBe(380)
+ expect(model.parts.find(part=>part.role==='shelf')?.width).toBe(350)
+ expect(model.parts.find(part=>part.role==='bottom')?.width).toBe(365)
+ expect(model.input.caseEstimates).toEqual(expect.arrayContaining(['innerDepth','bottomDepth','grooveRear']))
+ expect(model.input.caseEstimates).not.toContain('backThickness')
+ expect(standard.recognition?.assumptions.join(' ')).toContain('隔板和搁板进深 350 mm')
+ expect(packingScene(standard).issues.join(' ')).toContain('背板超过包装限宽')
+ expect(calculateStandard(standard).total).toBeGreaterThan(0)
+ expect(estimateDocumentSchema.parse(document).skillRouting?.version).toBe('0.24.3')
+ expect(model.version).toBe('0.24.1')
+
+ const resized=buildCabinetModel({...model.input,depth:400,bottomDepth:370})
+ expect(resized.input).toMatchObject({innerDepth:370,bottomDepth:370,caseEstimateDepth:400})
+ expect(resized.input.caseEstimates).toContain('innerDepth')
+ expect(resized.input.caseEstimates).not.toContain('bottomDepth')
+
+ const previousGuess={...model.input,kickHeight:80,railHeight:100,
+ caseEstimates:[...model.input.caseEstimates!,'kickHeight','railHeight'] as CabinetInput['caseEstimates']}
+ expect(buildCabinetModel(previousGuess).parts).toEqual(model.parts)
+ const confirmed=buildCabinetModel({...previousGuess,hasFrontKick:false,hasRearRail:true,railHeight:60})
+ expect(confirmed.parts.find(part=>part.role==='rail')).toMatchObject({width:60,quantity:1})
+ expect(confirmed.parts.some(part=>part.role==='kick')).toBe(false)
+ expect(confirmed.parts.find(part=>part.role==='back')?.quantity).toBe(2)
+ })
test('supplier choices retain price units and use actual thickness instead of choosing a price silently',()=>{
const solid=quotaConsumableOptions('solid',.8,15),wood=quotaConsumableOptions('wood',.8,15),glue=quotaConsumableOptions('glue',.8,15)
expect(solid.find(o=>o.width===15&&o.supplier==='无锡双文')?.price).toBe(.16)
diff --git a/furniture-3d-system/src/lib/reference-estimator/contracts.ts b/furniture-3d-system/src/lib/reference-estimator/contracts.ts
index 23fb4a1a..7c8f0c9a 100644
--- a/furniture-3d-system/src/lib/reference-estimator/contracts.ts
+++ b/furniture-3d-system/src/lib/reference-estimator/contracts.ts
@@ -53,6 +53,9 @@ export const materialSchema = z.object({
id: z.string().max(150), code: z.string().max(150), name: z.string().max(300),
thicknessMm: positive, sheetLengthMm: positive, sheetWidthMm: positive,
sheetPrice: nonNegative.nullable(), sheetWeightKg: nonNegative.nullable(),
+ selection: z.object({
+ category: z.string().max(50), grade: z.string().max(20), color: z.string().max(50), veneer: z.string().max(20),
+ }).optional(),
})
export type MaterialSnapshot = z.infer
export const lineOverrideSchema = z.object({
diff --git a/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-contracts.ts b/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-contracts.ts
index 8c93f380..e6420917 100644
--- a/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-contracts.ts
+++ b/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-contracts.ts
@@ -11,11 +11,13 @@ export const cabinetCaseFields = Object.keys(cabinetCaseFieldLabels) as [Cabinet
export const cabinetInputSchema=z.object({
referenceCase:z.enum(['6G-960-B']).nullable().default(null),
caseEstimates: z.array(z.enum(cabinetCaseFields)).max(cabinetCaseFields.length).optional(),
+ caseEstimateDepth: mm.optional(),
name:z.string().max(100).default('开放格书柜'),
width:mm.nullable().default(null),depth:mm.nullable().default(null),height:mm.nullable().default(null),
columns:z.number().int().min(1).max(12).nullable().default(null),rows:z.number().int().min(1).max(12).nullable().default(null),
+ hasFrontKick:z.boolean().nullish(),hasRearRail:z.boolean().nullish(),
thickness:mm.nullable().default(null),kickHeight:z.number().min(0).max(500).nullable().default(null),
- innerDepth:mm.nullable().default(null),bottomDepth:mm.nullable().default(null),railHeight:mm.nullable().default(null),
+ innerDepth:mm.nullable().default(null),bottomDepth:mm.nullable().default(null),railHeight:z.number().finite().min(0).max(10000).nullable().default(null),
backThickness:mm.nullable().default(null),grooveWidth:mm.nullable().default(null),grooveDepth:mm.nullable().default(null),grooveRear:mm.nullable().default(null),
kickEndCams:z.union([z.literal(1),z.literal(2)]).nullable().default(null),
edgeThickness:z.number().min(0).max(5).nullable().default(null),
diff --git a/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-costs.ts b/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-costs.ts
index fa329c5f..264da95d 100644
--- a/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-costs.ts
+++ b/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-costs.ts
@@ -40,11 +40,12 @@ export function completeCabinetCosts(d:StandardTemplate):StandardTemplate {
for(const row of boardRows){
const part=boardByRow.get(row),back=part?.role==='back'||/背板|三合/.test(String(inputValue(next,'I'+row)))
const material=back?'三合板':p.material,thickness=qty('H'+row),density=back?budget.backDensity:budget.boardDensity
- const exact=matchCabinetMaterial(material,p.grade,String(inputValue(next,'F'+row)??part?.color??''),String(inputValue(next,'G'+row)??p.veneer),thickness)
+ const veneer=String(inputValue(next,'G'+row)??p.veneer)
+ const exact=part?.material??matchCabinetMaterial(material,p.grade,String(inputValue(next,'F'+row)??part?.color??''),veneer,thickness)
const face=exact?exact.sheetLengthMm*exact.sheetWidthMm/1e6:0
if(exact?.sheetPrice!=null&&face>0)fill('S'+row,exact.sheetPrice/face)
else if(!has('S'+row)){
- const ref=comparableCabinetBoard(material,p.grade,p.veneer,thickness)
+ const ref=comparableCabinetBoard(material,p.grade,veneer,thickness)
if(ref)fill('S'+row,ref.price!*1e6/(ref.sheetLength*ref.sheetWidth),`本规格无定额价。参照 ${ref.source} 的 ${ref.grade}${ref.thickness}mm${ref.material}|${ref.color}|${ref.veneer},¥${ref.price}/张,按 ${ref.sheetLength}×${ref.sheetWidth}mm 折算为元/m²。`)
else fill('S'+row,thickness*(back?budget.backPricePerMm:budget.boardPricePerMm),`定额无同类同厚报价。按板厚 ${thickness}mm × ¥${back?budget.backPricePerMm:budget.boardPricePerMm}/(m²·mm) 暂估。`)
}
diff --git a/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-material-selection.ts b/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-material-selection.ts
new file mode 100644
index 00000000..6a81213b
--- /dev/null
+++ b/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-material-selection.ts
@@ -0,0 +1,32 @@
+import type { EstimateDocument } from '../contracts'
+import type { CabinetInput, CabinetPart } from './cabinet-contracts'
+
+type CabinetMaterials = Pick
+
+export function withSelectedCabinetInputs(input: CabinetInput, materials: CabinetMaterials): CabinetInput {
+ const main = materials.mainMaterial, back = materials.backMaterial
+ const next = { ...input }
+ if (main?.selection) {
+ const { category, grade, color, veneer } = main.selection
+ const top = input.topColor
+ next.topColor = !top || top === input.bodyColor || /^(白色|木色|浅色|深色)(系)?$/.test(top) ? color : top
+ Object.assign(next, { material: category, grade, bodyColor: color, thickness: main.thicknessMm, veneer })
+ }
+ if (back?.selection) {
+ next.backThickness = back.thicknessMm
+ next.backColor = back.selection.color
+ }
+ next.caseEstimates = input.caseEstimates?.filter(field =>
+ !(field === 'thickness' && main?.selection) && !(field === 'backThickness' && back?.selection))
+ return next
+}
+
+export function selectedCabinetPartMaterial(
+ input: CabinetInput, materials: CabinetMaterials | undefined, role: CabinetPart['role'], color: string, thickness: number,
+): CabinetPart['material'] {
+ const material = role === 'back' ? materials?.backMaterial : materials?.mainMaterial
+ const spec = material?.selection
+ if (!material || !spec || material.thicknessMm !== thickness || spec.color !== color) return null
+ if (role !== 'back' && (spec.category !== input.material || spec.grade !== input.grade || spec.veneer !== input.veneer)) return null
+ return { ...material, source: material.code }
+}
diff --git a/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-model.ts b/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-model.ts
index be714bf2..90a858df 100644
--- a/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-model.ts
+++ b/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-model.ts
@@ -1,39 +1,68 @@
import rules from '../../../../.agents/skills/cabinet-standard-bom/规则.json'
-import { cabinetCaseFieldLabels, cabinetCaseFields, cabinetInputSchema, type CabinetInput, type CabinetModel, type CabinetPart } from './cabinet-contracts'
+import { cabinetCaseFieldLabels, cabinetCaseFields, cabinetInputSchema, type CabinetCaseField, type CabinetInput, type CabinetModel, type CabinetPart } from './cabinet-contracts'
import { matchCabinetMaterial } from './cabinet-quota'
+import { selectedCabinetPartMaterial } from './cabinet-material-selection'
export function resolveCabinetInput(raw:CabinetInput):CabinetInput {
- const input=cabinetInputSchema.parse(raw),sample=input.referenceCase?rules.cases[input.referenceCase]:null
- if (sample) {
+ const parsed = cabinetInputSchema.parse(raw)
+ const sample = parsed.referenceCase ? rules.cases[parsed.referenceCase] : null
+ const caseMatches = sample && (['width','depth','height','columns','rows'] as const).every(k=>parsed[k]===null||parsed[k]===sample[k])
+ const presence = (explicit:boolean|null|undefined,key:'kickHeight'|'railHeight') =>
+ explicit ?? (parsed[key]!==null&&!parsed.caseEstimates?.includes(key) ? parsed[key]>0 : caseMatches ? true : null)
+ const hasFrontKick=presence(parsed.hasFrontKick,'kickHeight'),hasRearRail=presence(parsed.hasRearRail,'railHeight')
+ const input = {
+ ...parsed,referenceCase:caseMatches?parsed.referenceCase:null,hasFrontKick,hasRearRail,
+ kickHeight:hasFrontKick===false?0:hasFrontKick===true&&parsed.kickHeight!==0?parsed.kickHeight:null,
+ railHeight:hasRearRail===false?0:hasRearRail===true&&parsed.railHeight!==0?parsed.railHeight:null,
+ kickEndCams:hasFrontKick===true?parsed.kickEndCams:null,
+ }
+ if (sample && caseMatches) {
const fields = ['width', 'depth', 'height', 'columns', 'rows', ...cabinetCaseFields] as const
- return { ...input, ...Object.fromEntries(fields.map(k => [k, input[k] ?? sample[k]])), caseEstimates: undefined, veneer: input.veneer || '双贴' }
+ return { ...input, ...Object.fromEntries(fields.map(k => [k, input[k] ?? sample[k]])),
+ kickEndCams:hasFrontKick?input.kickEndCams??sample.kickEndCams:null,
+ caseEstimates: undefined, caseEstimateDepth: undefined, veneer: parsed.veneer || '双贴' }
}
const example = rules.cases['6G-960-B']
- // Use the measured exterior for a matching layout. Hidden dimensions can use the case as a draft reference.
- if (input.columns !== example.columns || input.rows !== example.rows || input.depth !== example.depth
- || input.width === null || input.height === null) return input
- const sameExterior = input.width === example.width && input.height === example.height
- const caseEstimates = cabinetCaseFields.filter(field =>
- (field !== 'thickness' || sameExterior) && (input[field] === null
- || (input.caseEstimates?.includes(field) && input[field] === example[field])))
+ const { depth } = input
+ if (input.columns !== example.columns || input.rows !== example.rows
+ || input.width === null || input.height === null || depth === null) return input
+
+ const estimateValue = (field: CabinetCaseField, actualDepth: number) =>
+ field === 'innerDepth' || field === 'bottomDepth'
+ ? actualDepth - (example.depth - example[field])
+ : example[field]
+ const previousDepth = input.caseEstimateDepth ?? example.depth
+ const sameExterior = input.width === example.width && input.height === example.height && depth === example.depth
+ const caseEstimates = cabinetCaseFields.filter(field => {
+ if ((field==='kickHeight'||field==='kickEndCams')&&hasFrontKick!==true) return false
+ if (field==='railHeight'&&hasRearRail!==true) return false
+ const value = estimateValue(field, depth)
+ if ((field === 'thickness' && !sameExterior) || value <= 0) return false
+ return input[field] === null ||
+ (input.caseEstimates?.includes(field) && input[field] === estimateValue(field, previousDepth))
+ })
return {
...input,
- ...Object.fromEntries(caseEstimates.map(field => [field, example[field]])),
+ ...Object.fromEntries(caseEstimates.map(field => [field, estimateValue(field, depth)])),
caseEstimates,
+ caseEstimateDepth: caseEstimates.length ? depth : undefined,
}
}
-export function buildCabinetModel(raw:CabinetInput):CabinetModel {
+export function buildCabinetModel(raw:CabinetInput,materials?:Parameters[1]):CabinetModel {
const p=resolveCabinetInput(raw)
const outline = { width: '宽', depth: '深', height: '高', columns: '列数', rows: '层数', thickness: '板厚' } as const
const missingOutline = (Object.keys(outline) as (keyof typeof outline)[]).filter(key => p[key] === null)
if (missingOutline.length) throw new Error(`生成模型还需要:${missingOutline.map(key => outline[key]).join('、')}。`)
- const missingDetails = cabinetCaseFields.filter(key => p[key] === null)
+ const missingDetails = cabinetCaseFields.filter(key => key!=='kickHeight'&&key!=='railHeight'&&key!=='kickEndCams'&&p[key]===null)
if (missingDetails.length) throw new Error(`此结构缺少可用的暂估案例,请补充${missingDetails.map(key => cabinetCaseFieldLabels[key]).join('、')}。`)
- const W=p.width!,D=p.depth!,H=p.height!,t=p.thickness!,n=p.columns!,m=p.rows!,kick=p.kickHeight!,inner=p.innerDepth!,bottom=p.bottomDepth!,rail=p.railHeight!,g=p.grooveDepth!,bt=p.backThickness!
+ const W=p.width!,D=p.depth!,H=p.height!,t=p.thickness!,n=p.columns!,m=p.rows!,kick=p.kickHeight??0,inner=p.innerDepth!,bottom=p.bottomDepth!,rail=p.railHeight??0,g=p.grooveDepth!,bt=p.backThickness!
const netW=W-2*t,clearW=(W-(n+1)*t)/n,clearH=(H-(m+1)*t-kick)/m
if(Math.min(netW,clearW,clearH)<=0||inner>D||bottom>D||p.grooveWidth!D)throw new Error('结构尺寸不兼容,请核对板厚、格数、板件进深与槽位。')
const issues:string[]=[],assumptions:string[]=[]
+ if(p.hasFrontKick==null||p.hasFrontKick&&!kick)issues.push('前踢脚板待确认:请确认有无及高度。暂未计入板件和五金。')
+ if(p.hasRearRail==null||p.hasRearRail&&(!rail||m===1))issues.push('后横档待确认:请确认有无、高度和背板接法。暂未计入板件和五金。')
+ if(kick>0&&!p.kickEndCams)issues.push('请确认前踢脚板接左右旁板各用几套偏心。')
if(p.referenceCase)assumptions.push('按六格B版打样案例的搭接、进深、踢脚和连接做法生成;案例尺寸不作为其他柜类默认值。')
if(p.caseEstimates?.length){
assumptions.push('六格 B 版暂估:'+p.caseEstimates.map(field =>
@@ -49,12 +78,14 @@ export function buildCabinetModel(raw:CabinetInput):CabinetModel {
: '背板槽位置、加工面和孔系需在打样前核对。')
if(p.drillFeet===null)issues.push('请补充每块主体板打眼脚数,或提供各板件的排钻脚数。')
if(!p.hardwareCode)issues.push('15mm偏心候选B042,需确认实际型号。')
- if(!p.screwCode)issues.push('后横档5×40螺丝候选A206/A025,请确认头型与代码。')
+ if(rail>0&&m>1&&!p.screwCode)issues.push('后横档5×40螺丝候选A206/A025,请确认头型与代码。')
if(!p.clipCode)issues.push('背板扣候选B172/B173,请确认实际型号。')
if(p.packingLabor===null)issues.push('请确认打包人工按小件、中件还是大件。')
const parts:CabinetPart[]=[],connections:CabinetModel['connections']=[]
const add=(code:string,name:string,role:CabinetPart['role'],L:number,B:number,T:number,size:CabinetPart['size'],positions:CabinetPart['positions'],grooveMeters=0)=>{
- const color=role==='top'?p.topColor:role==='back'?p.backColor||p.bodyColor:p.bodyColor,material=matchCabinetMaterial(role==='back'?'三合板':p.material,p.grade,color,p.veneer,T)
+ const color=role==='top'?p.topColor:role==='back'?p.backColor||p.bodyColor:p.bodyColor
+ const material=selectedCabinetPartMaterial(p,materials,role,color,T)
+ ??matchCabinetMaterial(role==='back'?'三合板':p.material,p.grade,color,p.veneer,T)
if(!material)issues.push(`${name}没有匹配到完整规格报价(${p.grade} ${color} ${p.veneer} ${T}mm)。`)
else if(material.sheetWeightKg===null)issues.push(`${name}对应板材未提供大板重量。`)
const sample=p.referenceCase?rules.cases[p.referenceCase]:null
@@ -62,12 +93,11 @@ export function buildCabinetModel(raw:CabinetInput):CabinetModel {
parts.push({id:'part-'+code,code,name,role,length:L,width:B,thickness:T,quantity:positions.length,size,positions,material,color,grooveMeters,notch})
}
const backY=D-p.grooveRear!-p.grooveWidth!/2-bt/2
- const railZ=Array.from({length:m-1},(_,i)=>kick+t+(i+1)*clearH+i*t+t/2-rail/2)
+ const railZ=Array.from({length:rail>0?m-1:0},(_,i)=>kick+t+(i+1)*clearH+i*t+t/2-rail/2)
const backLow=[kick+t,...railZ.map(z=>z+rail)],backHigh=[...railZ,H-t]
const backPositions=backLow.map(z=>[t-g,backY,z-g] as [number,number,number])
const backWidths=backLow.map((z,i)=>backHigh[i]-z+2*g)
if(backLow.some((z,i)=>backHigh[i]<=z))throw new Error('后横档高度超出背板空间,请核对踢脚或后横档高度。')
- if(backWidths.some(b=>b>D))issues.push('背板宽度超过最大主体板宽,需按标准确认分片与后横档方案。')
if(netW+2*g>rules.hardware.backLengthLimit)issues.push('背板长度超过1300mm,请逐块确认背板扣数量。')
add('01','顶板','top',W,D,t,[W,D,t],[[0,0,H-t]],netW/1000)
add('02','左旁板','side',H-t,D,t,[t,D,H-t],[[0,0,0]],backWidths.reduce((a,b)=>a+b,0)/1000)
@@ -79,7 +109,7 @@ export function buildCabinetModel(raw:CabinetInput):CabinetModel {
add(parts.some(v=>v.code==='05')?'05-'+b:'05','背板','back',netW+2*g,b,bt,[netW+2*g,bt,b],positions)
}
if(m>1)add('06','中部搁板','shelf',netW,inner,t,[netW,inner,t],Array.from({length:m-1},(_,r)=>[t,0,kick+t+(r+1)*clearH+r*t] as [number,number,number]))
- if(m>1)add('07','后横档','rail',netW,rail,t,[netW,t,rail],railZ.map(z=>[t,inner,z]),netW*2/1000)
+ if(railZ.length)add('07','后横档','rail',netW,rail,t,[netW,t,rail],railZ.map(z=>[t,inner,z]),netW*2/1000)
add('08','底板','bottom',netW,bottom,t,[netW,bottom,t],[[t,0,kick]],netW/1000)
if(kick>0)add('09','踢脚板','kick',netW,kick,t,[netW,t,kick],[[t,0,0]])
const connect=(from:string,to:string,type:'cam'|'screw'|'clip',quantity:number,note:string)=>connections.push({id:'joint-'+connections.length,from,to,type,quantity,note})
@@ -89,9 +119,9 @@ export function buildCabinetModel(raw:CabinetInput):CabinetModel {
connect('03',r===m-1?'01':'06','cam',h.camPerJoint,`第${r+1}层第${c+1}块竖隔板上接`)
connect('03',r===0?'08':'06','cam',h.camPerJoint,`第${r+1}层第${c+1}块竖隔板下接`)
}
- if(kick>0){for(const side of ['02','04'])connect('09',side,'cam',p.kickEndCams!,`踢脚接${side}旁板`);connect('09','08','cam',netW>=h.kickHorizontalLimit?h.kickHorizontalLarge:h.kickHorizontalSmall,'踢脚接底板,兼作中部防转')}
- for(let r=0;rh.railJointLimit?h.railJointLarge:h.railJointSmall,`后横档${r+1}接搁板`)}
- if(netW+2*g<=h.backLengthLimit)for(let r=0;r0){if(p.kickEndCams)for(const side of ['02','04'])connect('09',side,'cam',p.kickEndCams,`踢脚接${side}旁板`);connect('09','08','cam',netW>=h.kickHorizontalLimit?h.kickHorizontalLarge:h.kickHorizontalSmall,'踢脚接底板,兼作中部防转')}
+ for(let r=0;rh.railJointLimit?h.railJointLarge:h.railJointSmall,`后横档${r+1}接搁板`)}
+ if(netW+2*g<=h.backLengthLimit)for(let r=0;rn+b.quantity,0)
+ const railNote=model.parts.some(part=>part.role==='rail')?'背板与后横档的接合关系见第 1 页 C-C 剖面。':'背板安装做法见第 1 页。'
return [
dimensionPage(model),
- `${samplingAxonometric(model,true)}
共 ${count} 块;同加工规格共用编号。背板与后横档的接合关系见第 1 页 C-C 剖面。
`,
+ `${samplingAxonometric(model,true)}
共 ${count} 块;同加工规格共用编号。${railNote}
`,
jointsPage(model),
]
}
diff --git a/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-sampling-views.ts b/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-sampling-views.ts
index 9ccfeb46..c8bfbd86 100644
--- a/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-sampling-views.ts
+++ b/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-sampling-views.ts
@@ -58,7 +58,8 @@ export function samplingOrthographic(model: CabinetModel) {
}
const div=model.parts.find(part=>part.role==='divider')
const clearW=(W-(p.columns!+1)*T)/p.columns!
- const clearH=div?.size[2]??(H-(p.rows!+1)*T-p.kickHeight!)/p.rows!
+ const kick=model.parts.find(part=>part.role==='kick')?.size[2]??0
+ const clearH=div?.size[2]??(H-(p.rows!+1)*T-kick)/p.rows!
const notch=model.parts.find(part=>part.notch)?.notch
const rail=model.parts.find(part=>part.role==='rail')
const back=model.parts.find(part=>part.role==='back')
@@ -68,7 +69,8 @@ export function samplingOrthographic(model: CabinetModel) {
ink(markX,at-10,markX,at+8)+ink(markX,at-9,markX+13,at-9)+
'' +
label(markX-9,at-6,'C','middle',10)
- const faceSizes=Array.from({length:p.rows!*2+2},(_,i)=>i===p.rows!*2+1?p.kickHeight!:i%2?clearH:T)
+ const faceSizes=Array.from({length:p.rows!*2+1},(_,i)=>i%2?clearH:T)
+ if(kick)faceSizes.push(kick)
const marks = dimension(front,front+w,y-39,y,false,W)+
chain(Array.from({length:p.columns!*2+1},(_,i)=>i%2?clearW:T),front,y-16)+
dimension(front+T*s,front+w-T*s,y+h+33,y+h,false,W-2*T)+
diff --git a/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-workflow.ts b/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-workflow.ts
index da7833d5..39fdaf5f 100644
--- a/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-workflow.ts
+++ b/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-workflow.ts
@@ -1,4 +1,5 @@
import type { EstimateDocument, EstimatePiece } from '../contracts'
+import rules from '../../../../.agents/skills/cabinet-standard-bom/规则.json'
import type { CabinetInput } from './cabinet-contracts'
import { buildCabinetModel } from './cabinet-model'
import { createStandardTemplate } from './contracts'
@@ -9,27 +10,39 @@ import { generatePlacements, applyPackagingMaterials,packingScene } from './pack
import { completeCabinetCosts, laborRows } from './cabinet-costs'
export function applyCabinetWorkflow(document:EstimateDocument,input:CabinetInput):EstimateDocument{
- const model=buildCabinetModel(input),p=model.input,previous=document.standardTemplate??createStandardTemplate()
+ const previous=document.standardTemplate??createStandardTemplate()
+ const previousInput = previous.cabinet?.input
+ const model=buildCabinetModel({
+ ...input,
+ caseEstimateDepth: input.caseEstimateDepth ?? previousInput?.caseEstimateDepth ?? previousInput?.depth ?? undefined,
+ },document),p=model.input
const cells={...previous.cells}
for(const address of Object.keys(cells))if(ordinaryBoardRows(previous).includes(Number(address.replace(/^[A-Z]+/,''))))delete cells[address]
cells.C2=p.name;cells.K2=`${p.width}×${p.depth}×${p.height}mm`
- let d={...previous,cells,boardRowCount:Math.max(14,model.parts.length),cabinet:model,materialQuotes:{}}
+ const costEstimates={...previous.costEstimates}
+ for(const address of Object.keys(costEstimates)){
+ if(ordinaryBoardRows(previous).includes(Number(address.replace(/^[A-Z]+/,''))))delete costEstimates[address]
+ }
+ let d={...previous,cells,costEstimates,boardRowCount:Math.max(14,model.parts.length),cabinet:model,materialQuotes:{}}
const pieces:EstimatePiece[]=model.parts.map((part,i)=>{
const r=boardRowAt(i),back=part.role==='back'
+ const veneer=back&&document.backMaterial?.id===part.material?.id?document.backMaterial?.selection?.veneer??p.veneer:p.veneer
Object.assign(cells,{['C'+r]:part.code,['D'+r]:part.material?.name??`${p.grade}${part.thickness}mm${p.material}`,
- ['F'+r]:part.color,['G'+r]:p.veneer,['H'+r]:part.thickness,['I'+r]:part.name,['J'+r]:part.length,['K'+r]:part.width,
+ ['F'+r]:part.color,['G'+r]:veneer,['H'+r]:part.thickness,['I'+r]:part.name,['J'+r]:part.length,['K'+r]:part.width,
['L'+r]:back?0:2,['M'+r]:back?0:2,['O'+r]:part.quantity,['U'+r]:/胡桃|木纹|橡木|柚木/.test(part.color)?'木色':'素色',
['W'+r]:part.grooveMeters*part.quantity,['Z'+r]:back?0:p.drillFeet})
if(part.material){d=applyStandardMaterial({...d,cells},r,part.material,true) as typeof d;Object.assign(cells,d.cells)}
const oldIndex=previous.cabinet?.parts.findIndex(b=>b.id===part.id)??-1,oldPart=previous.cabinet?.parts[oldIndex]
if(oldPart&&oldPart.material?.id===part.material?.id&&oldPart.color===part.color&&oldPart.thickness===part.thickness&&
previous.cabinet?.input.grade===p.grade&&previous.cabinet?.input.material===p.material&&previous.cabinet?.input.veneer===p.veneer){
- for(const col of ['S','AB','Z','Y','X']){
+ const sameQuote=oldPart.material?.sheetPrice===part.material?.sheetPrice&&oldPart.material?.sheetWeightKg===part.material?.sheetWeightKg&&
+ oldPart.material?.sheetLengthMm===part.material?.sheetLengthMm&&oldPart.material?.sheetWidthMm===part.material?.sheetWidthMm
+ for(const col of sameQuote?['S','AB','Z','Y','X']:['Z','Y','X']){
if(col==='Z'&&previous.cabinet?.input.drillFeet!==p.drillFeet)continue
const address=col+boardRowAt(oldIndex),value=previous.cells[address]
if(typeof value==='number'&&previous.costEstimates?.[address]?.value!==value)cells[col+r]=value
}
- const oldQuote=previous.materialQuotes[boardRowAt(oldIndex)];if(oldQuote)d={...d,materialQuotes:{...d.materialQuotes,[r]:oldQuote}}
+ const oldQuote=previous.materialQuotes[boardRowAt(oldIndex)];if(sameQuote&&oldQuote)d={...d,materialQuotes:{...d.materialQuotes,[r]:oldQuote}}
}
return {id:part.id,name:part.name,role:part.role==='kick'?'pull':part.role==='rail'?'other':part.role,
lengthMm:part.length,widthMm:part.width,thicknessMm:part.thickness,quantity:part.quantity,camSets:0,screws:0,grooveMeters:part.grooveMeters}
@@ -43,7 +56,7 @@ export function applyCabinetWorkflow(document:EstimateDocument,input:CabinetInpu
for(const[row,type,code,name,unit]of [[68,'cam',p.hardwareCode,'偏心轮+偏心杆','套'],[69,'screw',p.screwCode,'5×40木螺丝','颗'],[74,'clip',p.clipCode,'背板扣','个']] as const){
const h=quotaHardware(code),quantity=type==='clip'&&p.width!-2*p.thickness!+2*p.grooveDepth!>1300?null:totals(type)
const same=Boolean(previous.cabinet)&&(previous.cells['C'+row]??'')===code&&previous.cabinet?.input.thickness===p.thickness
- write(row,{C:code,D:h?.name??name,N:unit,O:quantity,P:same?keep('P'+row,null):null,
+ write(row,{C:code,D:h?.name??name,N:unit,O:quantity,P:quantity===0?0:same?keep('P'+row,null):null,
S:same?keep('S'+row,h?.price??null):h?.price??null,AB:same?keep('AB'+row,h?.weight??null):h?.weight??null})
}
for(const[row,name]of laborRows)write(row,{S:keep('S'+row,quotaLabor(name).price)})
@@ -77,8 +90,9 @@ export function applyCabinetWorkflow(document:EstimateDocument,input:CabinetInpu
return {...document,title:p.name,ruleVersion:'standard-1116.1',standardTemplate:d,pieces,
mainMaterial:document.mainMaterial?.id===model.parts.find(b=>b.role==='side')?.material?.id?document.mainMaterial:model.parts.find(b=>b.role==='side')?.material??null,
backMaterial:document.backMaterial?.id===model.parts.find(b=>b.role==='back')?.material?.id?document.backMaterial:model.parts.find(b=>b.role==='back')?.material??null,
+ settings:{...document.settings,backThicknessMm:p.backThickness!},
overallDimensions:{widthMm:p.width,depthMm:p.depth,heightMm:p.height},structure:null,
- skillRouting:{skillId:'cabinet-standard',version:model.version,source:'auto',suggestedSkillId:'cabinet-standard',
+ skillRouting:{skillId:'cabinet-standard',version:rules.version,source:'auto',suggestedSkillId:'cabinet-standard',
classification:{materialType:'板式',primaryCategory:'柜类',secondaryCategory:'书柜',placement:'落地'},hasDoors:false,hasDrawers:false,note:'横板连续、竖隔分段',ruleSnapshot:['柜类结构标准v0.24;同一模型驱动四步','成品尺寸含封边;孔槽待核保留状态']}}
}
export function cabinetCostQuestions(document:EstimateDocument):string[]{
diff --git a/furniture-3d-system/src/lib/reference-estimator/standard/packaging.ts b/furniture-3d-system/src/lib/reference-estimator/standard/packaging.ts
index 6bd47a39..a0b3a583 100644
--- a/furniture-3d-system/src/lib/reference-estimator/standard/packaging.ts
+++ b/furniture-3d-system/src/lib/reference-estimator/standard/packaging.ts
@@ -27,6 +27,11 @@ export function generatePlacements(d: StandardTemplate, legacyOpenCabinet = fals
}
export function packingScene(d: StandardTemplate) {
const result=calculateStandard(d),p=d.packing,g=packagingGrades[p.materialGrade],issues=[...result.issues]
+ const parts=d.cabinet?.parts??[]
+ const boardWidth=Math.max(0,...parts.filter(part=>part.role!=='back').map(part=>part.width))
+ if(boardWidth&&parts.some(part=>part.role==='back'&&part.width>boardWidth)){
+ issues.push('背板超过包装限宽,当前按模型暂估板材;请确认分片与承接方式,暂不计待确认包材。')
+ }
const count=result.boards.reduce((n,b)=>n+b.quantity,0)
if(count>300)issues.push('当前逐层图支持单包300块板件,请分包生成')
const expected=new Set((count<=300?result.boards:[]).flatMap(b=>Array.from({length:Math.max(0,Math.floor(b.quantity))},(_,i)=>`${b.row}:${i}`)))
diff --git a/furniture-3d-system/src/lib/reference-estimator/standard/recognition.ts b/furniture-3d-system/src/lib/reference-estimator/standard/recognition.ts
index eab00477..7b43348a 100644
--- a/furniture-3d-system/src/lib/reference-estimator/standard/recognition.ts
+++ b/furniture-3d-system/src/lib/reference-estimator/standard/recognition.ts
@@ -10,6 +10,7 @@ import { ordinaryBoardRows } from './rows'
import { findEstimateSkill } from '../skill-catalog'
import { applyCabinetWorkflow, cabinetCostQuestions } from './cabinet-workflow'
import { CABINET_QUOTA } from './cabinet-quota'
+import { withSelectedCabinetInputs } from './cabinet-material-selection'
export function applyStandardRecognition(document:EstimateDocument,result:ReferenceImageEstimateResult):EstimateDocument {
if(result.cabinet){
@@ -17,18 +18,21 @@ export function applyStandardRecognition(document:EstimateDocument,result:Refere
const recognized=result.cabinet,dimensions=result.overallDimensions
const selected=CABINET_QUOTA.boards.find(b=>b.id===document.mainMaterial?.id)
const prior=document.standardTemplate?.cabinet?.input
- const input={
+ const input=withSelectedCabinetInputs({
...recognized,
width:recognized.width??dimensions?.widthMm??null,
depth:recognized.depth??dimensions?.depthMm??null,
height:recognized.height??dimensions?.heightMm??null,
thickness:recognized.thickness??document.mainMaterial?.thicknessMm??null,
+ backThickness:recognized.backThickness??document.backMaterial?.thicknessMm??null,
grade:recognized.grade||selected?.grade||'',
bodyColor:recognized.bodyColor && !/^(浅色|深色|浅色系|深色系)$/.test(recognized.bodyColor)
? recognized.bodyColor : selected?.color??recognized.bodyColor,
veneer:recognized.veneer||selected?.veneer||'',
+ topColor:recognized.topColor||prior?.topColor||'',
caseEstimates:prior?.caseEstimates?.filter(key=>recognized[key]===prior[key]),
- }
+ caseEstimateDepth:prior?.caseEstimateDepth,
+ },document)
try{return applyCabinetWorkflow(document,input)}catch(error){
return {...document,pieces:[],structure:null,overallDimensions:{widthMm:input.width,depthMm:input.depth,heightMm:input.height},standardTemplate:{...createStandardTemplate(),recognition:{summary:result.summary,questions:[error instanceof Error?error.message:'请核对结构参数'],assumptions:result.assumptions,generatedBySkill:false}}}
}
diff --git a/furniture-3d-system/src/lib/reference-estimator/standard/workbook-cost-notes.ts b/furniture-3d-system/src/lib/reference-estimator/standard/workbook-cost-notes.ts
index 3dc87ff4..25d4d705 100644
--- a/furniture-3d-system/src/lib/reference-estimator/standard/workbook-cost-notes.ts
+++ b/furniture-3d-system/src/lib/reference-estimator/standard/workbook-cost-notes.ts
@@ -2,10 +2,15 @@ import type JSZip from 'jszip'
import { cabinetEstimateNotes } from './cabinet-costs'
import type { StandardTemplate } from './contracts'
import { cellXml } from './workbook-sheet'
+import { packingScene } from './packaging'
export async function addWorkbookCostNotes(zip:JSZip,d:StandardTemplate) {
const notes=cabinetEstimateNotes(d)
- const structureNotes=d.cabinet?.input.caseEstimates?.length?d.cabinet.assumptions:[]
+ const structureNotes=[
+ ...(d.cabinet?.input.caseEstimates?.length?d.cabinet.assumptions:[]),
+ ...(d.cabinet?.issues.filter(issue=>issue.includes('暂未计入板件和五金'))??[]),
+ ...(d.cabinet?packingScene(d).issues.filter(issue=>issue.startsWith('背板超过包装限宽')):[]),
+ ]
if(!notes.length&&!structureNotes.length)return
const rows=[['原表格号','项目','暂估值','金额格号','暂估依据'],
...structureNotes.map(note=>['','结构参数','','',note]),
diff --git a/furniture-3d-system/src/server/services/reference-image-estimate/cabinet-recognition-prompt.ts b/furniture-3d-system/src/server/services/reference-image-estimate/cabinet-recognition-prompt.ts
index 1b57d489..16d3ed34 100644
--- a/furniture-3d-system/src/server/services/reference-image-estimate/cabinet-recognition-prompt.ts
+++ b/furniture-3d-system/src/server/services/reference-image-estimate/cabinet-recognition-prompt.ts
@@ -7,8 +7,8 @@ export function cabinetRecognitionPrompt(p:Omit