fix(intake): save estimate inputs and confirm cabinet rails
This commit is contained in:
parent
fe63525ff2
commit
7ff94d6bdc
@ -22,7 +22,9 @@ description: 按柜类结构标准v0.24识别板式开放格柜,生成尺寸
|
||||
- 输入图片和已有尺寸、板件组材料、封边与本款特殊要求。已给信息直接使用,只问影响当前结果的缺项。
|
||||
- 模型、六视图/爆炸图/连接明细、包装和成本共用稳定板件编号与连接记录。长宽厚采用含封边成品口径;开料与机加工参数须另核。
|
||||
- 原标准完整文字及每条状态见 `references/结构标准.json`。填写提示、待填写、待验证与已生效分别处理。不得将案例尺寸升级为所有柜类的默认规则。
|
||||
- 首个可执行结构为横板连续、竖隔分段的开放格书柜。识别出与六格 B 版同为 3 列、2 层且进深 300 mm 时,已有宽、高和板厚即先按本款尺寸拆板。缺失的内部尺寸、连接用量和封边厚度可参照案例暂估。三围均与案例相同时,缺失板厚也可暂按案例估算。型号保留为未知,暂估参数随模型和 BOM 记录。其他结构按各自已经明确的输入计算,关键结构无法判断时才询问。
|
||||
- 程序 0.24.3 支持横板连续、竖隔分段的 3 列 2 层开放格书柜按本款成品宽、深、高和板厚拆板。图文或人工明确的参数优先。隔板和搁板进深缺失时,暂按本款柜深减 30 mm;底板进深缺失时,暂按本款柜深减 15 mm。背板槽和封边可参照六格 B 版暂估,随模型和 BOM 记录,打样前核对。三围均与案例相同时,缺失板厚也可按案例暂估。
|
||||
- 前踢脚板与后横档各自判断有、无或待确认。格数只决定分格。已确认有才采用本款尺寸或参照同结构案例暂估尺寸;已确认无即不生成。看不清仍生成柜体,待确认条板及相应五金暂不计入。确认是六格 B 版时可沿用已知做法,明确的本款说明优先。旧测算只在主动重算时更新。
|
||||
- 后横档未确认时先用整片背板预估板材。背板超过包装限宽时,按 CB-013、CB-024、CB-025 核实是否分片、各片尺寸及承接方式;确认前保留摆包预览,不计待确认包材。
|
||||
- 六格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扣,超限询问。
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
{
|
||||
"version": "0.24.1",
|
||||
"version": "0.24.3",
|
||||
"sourceVersion": "v0.24",
|
||||
"status": "测试中",
|
||||
"scope": "板式开放格书柜:横板连续、竖隔分段;其他结构先确认",
|
||||
|
||||
@ -209,6 +209,7 @@ export function IntakeActiveWorkspaceContent({
|
||||
<ReferenceEstimatorWorkspaceContent
|
||||
activeWorkspaceTab={activeWorkspaceTab}
|
||||
materialLibrarySubstrates={materialLibrarySubstrates}
|
||||
userId={currentUser.id}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@ -217,6 +217,7 @@ export function buildIntakePrimaryDomainProps(params: {
|
||||
canViewReferenceEstimator: params.canViewReferenceEstimator,
|
||||
referenceEstimator: {
|
||||
materialLibrarySubstrates: params.materialLibrarySubstrates,
|
||||
userId: params.user.id,
|
||||
},
|
||||
canViewProductPatentLedger: params.canViewProductPatentLedger,
|
||||
productPatent: {
|
||||
|
||||
@ -6,29 +6,66 @@ import { toMaterialSnapshot, type EstimateController } from './useEstimateContro
|
||||
import styles from './estimate.module.css'
|
||||
|
||||
export type EstimateInputController = Pick<EstimateController, 'document'|'busy'|'update'|'upload'|'analyze'|'applyNotes'|'skillIssue'|'options'|'chooseMain'>
|
||||
export function EstimateInputPanel({ controller: c }: { controller: EstimateInputController }) {
|
||||
export type ReferenceImageFeedback = { text: string; error?: boolean; retrySave?: boolean }
|
||||
|
||||
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>)}
|
||||
</> }
|
||||
}
|
||||
|
||||
export function EstimateInputPanel({
|
||||
controller: c,
|
||||
imageFeedback,
|
||||
onRetryImageSave,
|
||||
pagePaste = false,
|
||||
}: {
|
||||
controller: EstimateInputController
|
||||
imageFeedback?: ReferenceImageFeedback
|
||||
onRetryImageSave?: () => void
|
||||
pagePaste?: boolean
|
||||
}) {
|
||||
const { document: d } = c
|
||||
const main = materialChoices(c, false), back = materialChoices(c, true)
|
||||
return <aside className={styles.inputPanel}>
|
||||
<h3>参考图预估成本</h3>
|
||||
<div className={styles.upload} onPaste={event => {
|
||||
<div className={styles.upload} onPaste={pagePaste ? undefined : event => {
|
||||
const file = Array.from(event.clipboardData.files).find(item => item.type.startsWith('image/'))
|
||||
if (file) { event.preventDefault(); void c.upload(file) }
|
||||
}} tabIndex={0}>
|
||||
{d.imageUrl ? <Image src={d.imageUrl} alt="参考图预览" width={300} height={240} unoptimized className={styles.preview} /> : <span>上传参考图,或在此 Ctrl+V 粘贴截图</span>}
|
||||
{d.imageUrl ? <Image src={d.imageUrl} alt="参考图预览" width={300} height={240} unoptimized className={styles.preview} /> : <span>{pagePaste ? '上传参考图,或按 Ctrl+V 粘贴截图' : '上传参考图,或在此 Ctrl+V 粘贴截图'}</span>}
|
||||
<label className={styles.uploadButton}><input type="file" accept="image/png,image/jpeg,image/webp" disabled={Boolean(c.busy)} onChange={event => {
|
||||
const file = event.target.files?.[0]; if (file) void c.upload(file); event.currentTarget.value = ''
|
||||
}} />{d.imageUrl ? '更换参考图' : '上传参考图'}</label>
|
||||
{imageFeedback && <small role={imageFeedback.error ? 'alert' : 'status'}>
|
||||
{imageFeedback.text}
|
||||
</small>}
|
||||
{imageFeedback?.retrySave && onRetryImageSave && (
|
||||
<Button type="button" size="small" variant="gray" disabled={Boolean(c.busy)} onClick={onRetryImageSave}>重试保存</Button>
|
||||
)}
|
||||
</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>
|
||||
{d.structure && <Button size="small" variant="gray" disabled={Boolean(c.busy) || Boolean(c.skillIssue)} onClick={() => void c.applyNotes()}>更新测算</Button>}
|
||||
<label>主体板材<select aria-label="主体板材" value={d.mainMaterial?.id ?? ''} onChange={event => c.chooseMain(event.target.value)}>
|
||||
<option value="">请选择板材</option>{c.options.filter(item => !item.categoryName.includes('三合')).map(item => <option key={item.id} value={item.id}>{item.selectionLabel}</option>)}
|
||||
<label>主体板材<select aria-label="主体板材" value={main.value} onChange={event => c.chooseMain(event.target.value)}>
|
||||
{main.options}
|
||||
</select></label>
|
||||
<label>同色双贴背板<select aria-label="背板材料" value={d.backMaterial?.id ?? ''} onChange={event => {
|
||||
<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) : null,
|
||||
c.update(current => ({ ...current, backMaterial: option ? toMaterialSnapshot(option, true) : null,
|
||||
settings: option ? { ...current.settings, backThicknessMm: option.thicknessMm } : current.settings }))
|
||||
}}><option value="">请选择背板</option>{c.options.filter(item => item.categoryName.includes('三合')).map(item => <option key={item.id} value={item.id}>{item.selectionLabel}</option>)}</select></label>
|
||||
}}>{back.options}</select></label>
|
||||
</aside>
|
||||
}
|
||||
|
||||
@ -3,6 +3,6 @@
|
||||
import type { SubstrateDTO } from '@/server/services'
|
||||
import { StandardEstimator } from './standard/StandardEstimator'
|
||||
|
||||
export function ReferenceEstimatorDomain({materialLibrarySubstrates=[]}:{materialLibrarySubstrates?:SubstrateDTO[]}) {
|
||||
return <StandardEstimator substrates={materialLibrarySubstrates}/>
|
||||
export function ReferenceEstimatorDomain({materialLibrarySubstrates=[],userId}:{materialLibrarySubstrates?:SubstrateDTO[];userId?:string}) {
|
||||
return <StandardEstimator substrates={materialLibrarySubstrates} userId={userId}/>
|
||||
}
|
||||
|
||||
@ -17,13 +17,16 @@ export function isReferenceEstimatorWorkspaceTab(
|
||||
|
||||
export function ReferenceEstimatorWorkspaceContent({
|
||||
materialLibrarySubstrates,
|
||||
userId,
|
||||
}: {
|
||||
activeWorkspaceTab: ReferenceEstimatorWorkspaceTab;
|
||||
materialLibrarySubstrates: SubstrateDTO[];
|
||||
userId: string;
|
||||
}) {
|
||||
return (
|
||||
<ReferenceEstimatorDomain
|
||||
materialLibrarySubstrates={materialLibrarySubstrates}
|
||||
userId={userId}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@ -0,0 +1,40 @@
|
||||
const estimateQuery = 'estimateId'
|
||||
const productLibraryPath = '/intake/product-library'
|
||||
export const referenceEstimateWorkspaceKey = 'reference-estimator'
|
||||
|
||||
export function referenceEstimateHref(id: string) {
|
||||
return '/intake?' + new URLSearchParams({ [estimateQuery]: id })
|
||||
}
|
||||
|
||||
export function linkedReferenceEstimateId(search: string) {
|
||||
const id = new URLSearchParams(search).get(estimateQuery)?.trim()
|
||||
return id && id.length <= 150 ? id : null
|
||||
}
|
||||
|
||||
export function clearReferenceEstimateLinkUnless(id?: string) {
|
||||
const url = new URL(window.location.href)
|
||||
const linkedId = linkedReferenceEstimateId(url.search)
|
||||
if (!linkedId || linkedId === id) return
|
||||
url.searchParams.delete(estimateQuery)
|
||||
window.history.replaceState(null, '', url.pathname + url.search + url.hash)
|
||||
}
|
||||
|
||||
export async function pushEstimateToProductLibrary(estimate: { id: string; revision: number }) {
|
||||
const response = await fetch('/api/intake/product-library/estimate-link', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ estimateId: estimate.id, revision: estimate.revision }),
|
||||
})
|
||||
const body = await response.json().catch(() => null)
|
||||
if (response.status === 405 || (response.status === 404 && !body)) {
|
||||
throw new Error('产品资料推送接口尚未接入。测算单已保存。')
|
||||
}
|
||||
if (response.status === 409) {
|
||||
throw new Error('测算单版本已更新,请重新打开后再推送。')
|
||||
}
|
||||
const archiveId = body?.data?.archive?.id
|
||||
if (!response.ok || !body?.success || typeof archiveId !== 'string' || !archiveId) {
|
||||
throw new Error(body?.error?.message ?? '推送到产品资料失败,请重试。')
|
||||
}
|
||||
return productLibraryPath + '?' + new URLSearchParams({ archive: archiveId })
|
||||
}
|
||||
@ -1,7 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import { useRef, useState } from 'react'
|
||||
import { Download } from 'lucide-react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { Download, Send } from 'lucide-react'
|
||||
import Button from '@/components/ui/Button'
|
||||
import type { SubstrateDTO } from '@/server/services'
|
||||
import { StandardTemplateTable } from './StandardTemplateTable'
|
||||
@ -15,19 +15,40 @@ import { StandardQuotesPanel } from './StandardQuotesPanel'
|
||||
import { StandardRecognitionReview } from './StandardRecognitionReview'
|
||||
import { StandardModelPanel } from './StandardModelPanel'
|
||||
import { StandardSamplingPanel } from './StandardSamplingPanel'
|
||||
import { useReferenceImagePaste } from './reference-image-paste'
|
||||
import { readWorkspacePosition, writeWorkspacePosition } from '@/lib/workspace-session-state'
|
||||
import { referenceEstimateWorkspaceKey } from '../referenceEstimateLinks'
|
||||
|
||||
export function StandardEstimator({substrates}:{substrates:SubstrateDTO[]}){
|
||||
const c=useStandardEstimator(substrates),input=useRef<HTMLInputElement>(null),[tab,setTab]=useState('model'),[settings,setSettings]=useState(false)
|
||||
const stages = [['model','1 模型'],['sampling','2 打样资料'],['packing','3 包装'],['cost','4 成本明细']] as const
|
||||
type Stage = typeof stages[number][0]
|
||||
|
||||
export function StandardEstimator({substrates,userId}:{substrates:SubstrateDTO[];userId?:string}){
|
||||
const c=useStandardEstimator(substrates,userId),input=useRef<HTMLInputElement>(null),[tab,setTab]=useState<Stage>('model'),[settings,setSettings]=useState(false)
|
||||
useEffect(()=>{
|
||||
const saved=readWorkspacePosition(userId,referenceEstimateWorkspaceKey,'stage')
|
||||
setTab(stages.find(([id])=>id===saved)?.[0]??'model')
|
||||
},[userId])
|
||||
const chooseStage=(stage:Stage)=>{
|
||||
setTab(stage)
|
||||
writeWorkspacePosition(userId,referenceEstimateWorkspaceKey,'stage',stage)
|
||||
}
|
||||
const workbench = useRef<HTMLDivElement>(null)
|
||||
useReferenceImagePaste(workbench, c.upload, Boolean(c.busy))
|
||||
const money=(n:number|null)=>n===null?'未生成':`¥${n.toFixed(2)}`
|
||||
const estimated=Object.keys(c.standard.costEstimates??{}).some(a=>a!=='S112'&&!a.startsWith('AB'))
|
||||
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 className={`${layout.workbench} ${styles.standardWorkbench}`}>
|
||||
return <div ref={workbench} className={`${layout.workbench} ${styles.standardWorkbench}`}>
|
||||
<EstimateSkillLibrary/>
|
||||
<div className={layout.toolbar}>
|
||||
<Button size="small" variant="gray" onClick={c.newDocument} disabled={Boolean(c.busy)}>新建</Button>
|
||||
<input aria-label="测算单名称" value={c.document.title} disabled={Boolean(c.busy)} onChange={e=>c.title(e.target.value)}/>
|
||||
<select aria-label="打开已保存测算单" value={c.record?.id??''} disabled={Boolean(c.busy)} onChange={e=>{if(e.target.value)void c.open(e.target.value)}}><option value="">打开已保存测算单</option>{c.records.map(r=><option key={r.id} value={r.id}>{r.title}</option>)}</select>
|
||||
<Button size="small" onClick={()=>void c.save()} disabled={Boolean(c.busy)}>保存</Button>
|
||||
<span title={!c.record||c.dirty?'请先保存测算单':undefined}>
|
||||
<Button type="button" size="small" variant="gray" disabled={!c.record||c.dirty||Boolean(c.busy)} onClick={()=>void c.pushToProductLibrary()}>
|
||||
<Send size={14} aria-hidden="true"/>推送到产品资料
|
||||
</Button>
|
||||
</span>
|
||||
{c.record&&<Button size="small" variant="gray" onClick={()=>void c.save(true)} disabled={Boolean(c.busy)}>另存为</Button>}
|
||||
{c.record&&<Button size="small" variant="plain" tone="danger" onClick={()=>void c.remove()} disabled={Boolean(c.busy)}>删除</Button>}
|
||||
<Button size="small" variant="gray" onClick={()=>void c.excel()} disabled={Boolean(c.busy)}>下载Excel</Button>
|
||||
@ -41,13 +62,13 @@ export function StandardEstimator({substrates}:{substrates:SubstrateDTO[]}){
|
||||
<input ref={input} hidden type="file" accept=".xlsx" onChange={e=>{const file=e.target.files?.[0];if(file)void c.importFile(file);e.currentTarget.value=''}}/>
|
||||
<small>{c.dirty?'有未保存修改':c.record?'已保存':''}</small>
|
||||
</div>
|
||||
{(c.busy||c.message)&&<div className={layout.status} role="status" aria-live="polite">{c.busy||c.message}</div>}
|
||||
{((c.busy && !c.imageBusy) || c.message)&&<div className={layout.status} role="status" aria-live="polite">{c.busy||c.message}</div>}
|
||||
{c.error&&<div className={layout.error} role="alert">{c.error}</div>}
|
||||
<fieldset disabled={Boolean(c.busy)}><div className={layout.body}>
|
||||
<EstimateInputPanel controller={left}/>
|
||||
<EstimateInputPanel controller={left} pagePaste imageFeedback={c.imageFeedback} onRetryImageSave={() => void c.save()}/>
|
||||
<section className={layout.main}>
|
||||
<div className={layout.summary}><div><h3>参考图产品测算</h3><small>{c.result.boards.reduce((n,b)=>n+b.quantity,0)}块板件 · 柜类结构标准v0.24 · BOM模板1116.1</small></div>{tab==='cost'&&<div className={layout.totals}><div><span>{estimated?'预估总成本':'总成本'}</span><strong>{money(c.result.materialTotal)}</strong></div><div><span>{estimated?'预估采购成本':'采购成本'}</span><strong>{money(c.result.total)}</strong></div></div>}</div>
|
||||
<div className={layout.tabs} role="tablist">{[['model','1 模型'],['sampling','2 打样资料'],['packing','3 包装'],['cost','4 成本明细']].map(([key,name])=><button type="button" role="tab" key={key} aria-selected={tab===key} onClick={()=>setTab(key)}>{name}</button>)}</div>
|
||||
<div className={layout.tabs} role="tablist">{stages.map(([key,name])=><button type="button" role="tab" key={key} aria-selected={tab===key} onClick={()=>chooseStage(key)}>{name}</button>)}</div>
|
||||
<div className={layout.content} role="tabpanel">
|
||||
{settings&&<StandardQuotesPanel c={c}/>}
|
||||
{tab==='model'&&<StandardModelPanel c={c}/>}
|
||||
|
||||
@ -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(<StandardEstimator substrates={[]}/>)
|
||||
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(<StandardEstimator substrates={[]}/>)
|
||||
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(<StandardEstimator substrates={[]}/>)
|
||||
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)
|
||||
})
|
||||
@ -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<HTMLDivElement | null>,
|
||||
upload: (file: File) => Promise<void>,
|
||||
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)
|
||||
}, [])
|
||||
}
|
||||
@ -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<T>(url:string,init?:RequestInit):Promise<T>{
|
||||
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<RecordSummary|null>(null),[records,setRecords]=useState<RecordSummary[]>([])
|
||||
const document=useMemo(()=>completeStandardCosts(storedDocument),[storedDocument])
|
||||
const [dirty,setDirty]=useState(false),[busy,setBusy]=useState(''),[message,setMessage]=useState(''),[error,setError]=useState('')
|
||||
const [imageFeedback, setImageFeedback] = useState<ReferenceImageFeedback>()
|
||||
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>|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> | 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<typeof useStandardEstimator>
|
||||
|
||||
@ -22,10 +22,14 @@ export async function estimateRequest<T>(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])
|
||||
|
||||
@ -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);
|
||||
},
|
||||
|
||||
@ -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)
|
||||
|
||||
@ -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<typeof materialSchema>
|
||||
export const lineOverrideSchema = z.object({
|
||||
|
||||
@ -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),
|
||||
|
||||
@ -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) 暂估。`)
|
||||
}
|
||||
|
||||
@ -0,0 +1,32 @@
|
||||
import type { EstimateDocument } from '../contracts'
|
||||
import type { CabinetInput, CabinetPart } from './cabinet-contracts'
|
||||
|
||||
type CabinetMaterials = Pick<EstimateDocument, 'mainMaterial' | 'backMaterial'>
|
||||
|
||||
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 }
|
||||
}
|
||||
@ -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<typeof selectedCabinetPartMaterial>[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!<bt||p.grooveRear!+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;r<m-1;r++){for(const side of ['02','04'])connect('07',side,'screw',h.railEndScrews,`后横档${r+1}端部`);connect('07','06','screw',netW>h.railJointLimit?h.railJointLarge:h.railJointSmall,`后横档${r+1}接搁板`)}
|
||||
if(netW+2*g<=h.backLengthLimit)for(let r=0;r<m;r++)connect('05','框架','clip',h.backClips,`背板${r+1}四角各1个`)
|
||||
if(kick>0){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;r<railZ.length;r++){for(const side of ['02','04'])connect('07',side,'screw',h.railEndScrews,`后横档${r+1}端部`);connect('07','06','screw',netW>h.railJointLimit?h.railJointLarge:h.railJointSmall,`后横档${r+1}接搁板`)}
|
||||
if(netW+2*g<=h.backLengthLimit)for(let r=0;r<backPositions.length;r++)connect('05','框架','clip',h.backClips,`背板${r+1}四角各1个`)
|
||||
const source = p.referenceCase ? rules.cases[p.referenceCase].source
|
||||
: p.caseEstimates?.length ? '柜类结构标准 v0.24,部分参数参照六格 B 版暂估'
|
||||
: '柜类家具结构标准化_v0.24.xlsx;本款明确参数'
|
||||
|
||||
@ -69,9 +69,10 @@ function jointsPage(model: CabinetModel) {
|
||||
|
||||
export function samplingPages(model: CabinetModel):string[] {
|
||||
const count=model.parts.reduce((n,b)=>n+b.quantity,0)
|
||||
const railNote=model.parts.some(part=>part.role==='rail')?'背板与后横档的接合关系见第 1 页 C-C 剖面。':'背板安装做法见第 1 页。'
|
||||
return [
|
||||
dimensionPage(model),
|
||||
`<div class="exploded-page">${samplingAxonometric(model,true)}</div><p class="drawing-note">共 ${count} 块;同加工规格共用编号。背板与后横档的接合关系见第 1 页 C-C 剖面。</p>`,
|
||||
`<div class="exploded-page">${samplingAxonometric(model,true)}</div><p class="drawing-note">共 ${count} 块;同加工规格共用编号。${railNote}</p>`,
|
||||
jointsPage(model),
|
||||
]
|
||||
}
|
||||
|
||||
@ -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)+
|
||||
'<path d="M'+coord(markX+13)+' '+coord(at-9)+'l-4 -2v4z" fill="#222"/></g>' +
|
||||
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)+
|
||||
|
||||
@ -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[]{
|
||||
|
||||
@ -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}`)))
|
||||
|
||||
@ -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}}}
|
||||
}
|
||||
|
||||
@ -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]),
|
||||
|
||||
@ -7,8 +7,8 @@ export function cabinetRecognitionPrompt(p:Omit<ReferenceImageEstimateInput,'ima
|
||||
'独立识别门和抽屉。带门抽、通高竖隔板、非均分及不属于横板连续/竖隔分段的柜子,cabinet=null,在questions里指出需确认的实际结构,保留已知overallDimensions。',
|
||||
'单位mm。优先明确标注mm的值。成品长宽厚含封边。等级E1与E0不同,材料不同板件组单独识别。',
|
||||
'案例6G-960-B为960×300×725的3列2层开放书柜。型号和结构均明确对应时填referenceCase="6G-960-B";未明确型号填null。即使没有型号,只要识别出横板连续、竖隔分段的开放格结构,就返回cabinet与实际尺寸、列数、层数。程序决定能否参照案例补齐暂估值。',
|
||||
'确认能匹配开放格结构时,未见的进深、踢脚、槽位、五金及封边填null,交由程序集中处理,不逐项追问。三围同时写入cabinet和overallDimensions。人工已选板厚可用于预估。',
|
||||
'cabinet字段:referenceCase,name,width,depth,height,columns,rows,thickness,kickHeight,innerDepth,bottomDepth,railHeight,backThickness,grooveWidth,grooveDepth,grooveRear,kickEndCams,edgeThickness,material,grade,topColor,bodyColor,veneer,hardwareCode,screwCode,clipCode,drillFeet,packingLabor,topFoam。',
|
||||
'前踢脚板和后横档分开识别:hasFrontKick、hasRearRail分别填true、false或null。只在图文有明确证据或用户明确确认时填有无;看不清填null。不要因层数、格数、底部阴影或案例猜测是否存在。高度只有在明确给出时才填写;未见的进深、槽位、五金和封边也填null。',
|
||||
'三围同时写入cabinet和overallDimensions。人工已选板厚可用于预估。cabinet字段:referenceCase,name,width,depth,height,columns,rows,thickness,hasFrontKick,hasRearRail,kickHeight,innerDepth,bottomDepth,railHeight,backThickness,grooveWidth,grooveDepth,grooveRear,kickEndCams,edgeThickness,material,grade,topColor,bodyColor,veneer,hardwareCode,screwCode,clipCode,drillFeet,packingLabor,topFoam。',
|
||||
'grade使用E1级/E0级等准确名称;花色必须准确,经典北美黑胡桃色和胡桃木色不同,只有“胡桃色”时保留原词询问。部件组成的“1套五金”不是一种配件的数量。',
|
||||
'用户明确回答优先覆盖旧图与案例;未明确改动的原事实保留。drillFeet只接受明确的每块主体板机台踩数,不从孔数推算。packingLabor仅小件/中件/大件;未给填null。hardwareCode/screwCode/clipCode只提取明确选择的物料代码。',
|
||||
`已保存的本款信息及补充:${p.imageNote||'-'}`,
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user