Merge remote-tracking branch 'origin/main' into HEAD

This commit is contained in:
WuYongJie 2026-12-02 15:31:03 +08:00
commit 662f6924cf
11 changed files with 493 additions and 103 deletions

View File

@ -3,7 +3,11 @@ import { accessoryMachiningSchema, type CamMachining } from '@/lib/intake-access
import { resolveAssemblyMachining, resolveCamWheelProcessing } from '@/lib/intake-accessory-machining-assets'
import type { AccessoryDraft } from '@/lib/intake-accessory-models'
import { accessoryComponentDrillSummary } from '@/lib/intake-accessory-component-drill'
import { accessoryMachiningSummary } from '@/lib/intake-accessory-drilling'
import { camProcessingLines } from './AccessoryMachiningDetails'
import { assemblyMemberProcessingLines, assemblyMemberStandards } from './accessory-connection-standards'
import { draftAssemblyRod, draftInsertAnchor } from './accessory-assembly-model-draft'
import Button from '@/components/ui/Button'
const fields = [
['firstDiameter', '孔径'], ['firstDepth', '深度'], ['rodDiameter', '杆孔孔径'],
@ -19,21 +23,32 @@ export function assemblyProcessing(assembly: AccessoryAssembly, item: AccessoryD
const rodId = member('rod')
const wheelId = member('cam')
const insertId = member('insert')
const drill = items.find(entry => entry.id === wheelId)?.componentDrill
const first = rule?.rodMount === 'direct' ? rule.pilot : rule?.insert
const members = assemblyMemberStandards(assembly, items)
const wheelItem = members.find(entry => entry.role === 'cam')?.item
const wheelStandard = wheelItem?.drilling
const drill = wheelStandard ?? wheelItem?.componentDrill
const insert = members.find(entry => entry.role === 'insert')?.item
const insertStandard = insert?.drilling
const first = insertId && insertStandard ? (insertStandard.holeType === 'blind' ? insertStandard : undefined)
: rule?.rodMount === 'direct' ? rule.pilot : rule?.insert
const rod = members.find(entry => entry.role === 'rod')?.item
const suggested = !rule && insertId && !rod?.drilling ? draftAssemblyRod(rod?.model, first?.depthMm) : undefined
const values: Values = { firstDiameter: first?.diameterMm, firstDepth: first?.depthMm,
rodDiameter: rule?.rodDiameterMm, rodLength: rule?.rodLengthMm, engagement: rule?.engagementMm, ...edits }
const wheel = drill?.holeType === 'blind' ? { diameterMm: drill.diameterMm, depthMm: drill.depthMm } : rule?.wheel
if (!edits) return { values, rule, drill, issue: undefined, machining: undefined }
if (!wheel || drill?.holeType === 'through') return { values, rule, drill, machining: undefined,
rodDiameter: rule?.rodDiameterMm, rodLength: rule?.rodLengthMm, engagement: rule?.engagementMm,
...suggested, ...edits }
const wheel = drill ? (drill.holeType === 'blind' ? { diameterMm: drill.diameterMm, depthMm: drill.depthMm } : undefined) : rule?.wheel
if (!edits) return { values, rule, drill, suggested, issue: undefined, machining: undefined }
if (!wheel) return { values, rule, drill, suggested, machining: undefined,
issue: '请先在偏心轮资料中确认盲孔孔径和深度。' }
if (insertId && insertStandard && insertStandard.holeType !== 'blind') return { values, rule, drill, suggested, machining: undefined,
issue: '请先在预埋件资料中确认盲孔孔径和深度。' }
const bore = { diameterMm: values.firstDiameter, depthMm: values.firstDepth }
const parsed = accessoryMachiningSchema.safeParse({
type: 'cam', rodId, wheelId, wheel, rodDiameterMm: values.rodDiameter, rodLengthMm: values.rodLength,
engagementMm: values.engagement, ...(insertId ? { rodMount: 'insert', insertId, insert: bore }
: { rodMount: 'direct', pilot: bore }),
})
return { values, rule, drill, machining: parsed.success ? parsed.data as CamMachining : undefined,
return { values, rule, drill, suggested, machining: parsed.success ? parsed.data as CamMachining : undefined,
issue: parsed.success ? undefined : parsed.error.issues[0]?.message ?? '请补全零件加工参数。' }
}
@ -46,11 +61,16 @@ export function AccessoryAssemblyProcessing({ assembly, items, data, fieldClassN
canEdit: boolean
onChange: (value: Values) => void
}) {
const { values, rule, drill, issue } = data
const { values, rule, suggested, machining, issue } = data
const usesInsert = assembly.components.some(part => part.role === 'insert')
const firstHole = usesInsert ? '预埋孔' : '首板引孔'
const wheel = rule && resolveCamWheelProcessing(rule, drill)
const lines = rule ? camProcessingLines(rule, items) : ['未填写']
const members = assemblyMemberStandards(assembly, items)
const wheelItem = members.find(entry => entry.role === 'cam')?.item
const insert = members.find(entry => entry.role === 'insert')?.item
const wheel = rule && resolveCamWheelProcessing(rule, wheelItem?.drilling ? undefined : wheelItem?.componentDrill)
const lines = rule ? camProcessingLines(rule, items) : [
...assemblyMemberProcessingLines(assembly, items), '整套开孔待确认。',
]
return <fieldset className="min-w-0 space-y-2 border-t border-apple-separator pt-2 text-xs">
<legend className="pr-2 text-sm font-semibold">零件加工参数</legend>
{canEdit ? <>
@ -63,9 +83,24 @@ export function AccessoryAssemblyProcessing({ assembly, items, data, fieldClassN
</label>)}
</div>
<p className="text-apple-label-secondary">
偏心轮:{drill ? accessoryComponentDrillSummary(drill)
偏心轮:{wheelItem?.drilling ? accessoryMachiningSummary(wheelItem.drilling)
: wheelItem?.componentDrill ? accessoryComponentDrillSummary(wheelItem.componentDrill)
: wheel ? `盲孔 Ø${wheel.wheel.diameterMm} × 深 ${wheel.wheel.depthMm} mm` : '请在偏心轮资料填写盲孔'}
</p>
{insert?.drilling && <p className="text-apple-label-secondary">预埋件 {insert.code}:{accessoryMachiningSummary(insert.drilling)}</p>}
{insert && draftInsertAnchor(insert.model) && <p className="text-amber-700">
预埋件基准已从模型识别,可点「编辑零件」查看并保存。
</p>}
{suggested && <div className="space-y-1 text-apple-label-secondary">
<p>杆孔按模型外径向上取整;拧入长度先按模型螺纹段预填。请核对实际配合后保存。</p>
{!machining && !issue && <Button type="button" size="small" variant="gray" disabled={disabled}
onClick={() => onChange(values)}>采用预填参数</Button>}
</div>}
{!rule && !suggested && <ul className="space-y-1 text-apple-label-secondary">
{assemblyMemberProcessingLines({ ...assembly, components: assembly.components.filter(part => part.role === 'rod') }, items)
.map(line => <li key={line}>{line}</li>)}
<li>请核对并补齐杆孔孔径、杆有效长度及拧入长度。</li>
</ul>}
{issue && <p className="text-red-700">{issue}</p>}
{!issue && wheel?.conflict && <p className="text-amber-700">偏心轮孔与原组合不同,核对并更新本组参数后再保存。</p>}
</> : <ul className="space-y-1 text-apple-label-secondary">{lines.map(line => <li key={line}>{line}</li>)}</ul>}

View File

@ -0,0 +1,129 @@
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import type { AccessoryDraft } from '@/lib/intake-accessory-models'
import { assemblyRecipe, assemblySources, standaloneInsert } from '../../../../../tests/fixtures/accessory-assembly'
import { AccessoryMachiningDetails } from './AccessoryMachiningDetails'
import { AccessoryModelEditor } from './AccessoryModelEditor'
import { assemblyProcessing } from './AccessoryAssemblyProcessing'
import { saveAccessoryDraft } from './draft-client'
import { draftInsertAnchor } from './accessory-assembly-model-draft'
jest.mock('next/dynamic', () => ({ __esModule: true, default: () => function Preview() { return null } }))
jest.mock('./draft-client', () => ({ saveAccessoryDraft: jest.fn() }))
const blindHole = (diameterMm: number, depthMm: number) => ({
version: 1, operation: 'drill', target: 'mating-panel', positionReference: 'installation-center',
directionReference: 'installation-direction', holeType: 'blind', diameterMm, depthMm,
} as const)
test('详情优先使用已填加工标准,隐藏偏心轮旧孔深,也显示连接杆已填的孔位', () => {
const wheel = { ...assemblySources[0], drilling: blindHole(12, 12), componentDrill: blindHole(12, 13.5) }
const rod = { ...assemblySources[1], drilling: blindHole(8, 32) }
const { rerender } = render(<dl><AccessoryMachiningDetails item={wheel} /></dl>)
expect(screen.getByText('盲孔 Ø12 × 深 12 mm')).toBeInTheDocument()
expect(screen.queryByText(/13\.5/)).not.toBeInTheDocument()
rerender(<dl><AccessoryMachiningDetails item={rod} /></dl>)
expect(screen.getByText('盲孔 Ø8 × 深 32 mm')).toBeInTheDocument()
})
test('木榫只从模型带出尺寸,普通配件不展示自动加工参数', () => {
const dowel: AccessoryDraft = { ...assemblySources[0], category: '圆棒榫', kind: '圆棒榫',
model: { ...assemblySources[0].model!, cad: undefined, dimensions: { diameter: 6, length: 20 } } }
const { rerender } = render(<dl><AccessoryMachiningDetails item={dowel} /></dl>)
expect(screen.getByText('第一块板盲孔 Ø6 mm')).toBeInTheDocument()
expect(screen.getByText('模型榫长 20 mm,需确认两块板各自的孔深')).toBeInTheDocument()
expect(screen.getByText('自动带出 · 待确认')).toBeInTheDocument()
rerender(<dl><AccessoryMachiningDetails item={{ ...dowel, module: 'accessory' }} /></dl>)
expect(screen.queryByText('零件加工参数')).not.toBeInTheDocument()
})
test('组合带出偏心轮和预埋件的盲孔,但仍须确认杆孔参数', () => {
const wheel = { ...assemblySources[0], drilling: blindHole(12, 12), componentDrill: blindHole(12, 13.5) }
const insert = { ...standaloneInsert, drilling: blindHole(10, 11) }
const assembly = { ...assemblyRecipe, components: [...assemblyRecipe.components,
{ ...assemblyRecipe.components[0], role: 'insert' as const, sourceId: insert.id, sourceCode: insert.code }] }
const items = [wheel, assemblySources[1], insert]
const group = { ...wheel, code: 'SHY-04', drilling: undefined, componentDrill: undefined,
model: { ...wheel.model!, assembly } }
render(<dl><AccessoryMachiningDetails item={group} items={items} /></dl>)
expect(screen.getByText(/PXL-01:盲孔 Ø12 × 深 12 mm/)).toBeInTheDocument()
expect(screen.getByText(/YMJ-01:盲孔 Ø10 × 深 11 mm/)).toBeInTheDocument()
expect(screen.getByText(/整套开孔仍待确认/)).toBeInTheDocument()
const draft = assemblyProcessing(assembly, group, items)
expect(draft.values).toMatchObject({ firstDiameter: 10, firstDepth: 11, rodLength: undefined })
expect(draft.machining).toBeUndefined()
expect(assemblyProcessing(assembly, group, items, { rodDiameter: 6, rodLength: 32, engagement: 8 }).machining)
.toMatchObject({ wheel: { diameterMm: 12, depthMm: 12 }, insert: { diameterMm: 10, depthMm: 11 } })
})
test('按已定位的杆模型预填三合一,采用后保存,人工填写优先', () => {
const wheel = { ...assemblySources[0], drilling: blindHole(12, 12) }
const insert = { ...standaloneInsert, drilling: blindHole(10, 11) }
const source = assemblySources[1]
const rod: AccessoryDraft = { ...source, model: {
...source.model!, installationAnchors: [{
partPath: '0/0', partName: '连接杆', role: 'rod', originMm: [0, 32, 0], direction: '-y',
}],
} }
const assembly = { ...assemblyRecipe, components: [...assemblyRecipe.components,
{ ...assemblyRecipe.components[0], role: 'insert' as const, sourceId: insert.id, sourceCode: insert.code }] }
const items = [wheel, rod, insert]
const draft = assemblyProcessing(assembly, undefined, items)
expect(draft.values).toMatchObject({ firstDiameter: 10, firstDepth: 11, rodDiameter: 7, rodLength: 40, engagement: 8 })
expect(draft.machining).toBeUndefined()
const accepted = assemblyProcessing(assembly, undefined, items, { ...draft.values, engagement: 7.5 })
expect(accepted.machining).toMatchObject({ rodDiameterMm: 7, rodLengthMm: 40, engagementMm: 7.5,
wheel: { diameterMm: 12, depthMm: 12 }, insert: { diameterMm: 10, depthMm: 11 } })
})
test('从不对称同轴预埋件读出孔口安装基准,编辑确认后沿用原模型保存', async () => {
const initial: AccessoryDraft = { ...standaloneInsert, drilling: blindHole(10, 11), model: {
...standaloneInsert.model!,
cad: { engine: 'photo-cad-v1', scale: 'dimensioned', review: ['带宽口和较窄尾端'], parts: [{
name: '预埋件', color: '#dddddd',
base: { shape: 'revolve', at: [0, 0, 0], axis: 'y', outline: [[0, 0], [5, 0], [4, 10], [0, 10]] },
operations: [{ op: 'cut', tool: { shape: 'cylinder', at: [0, -.1, 0], axis: 'y', diameter: 5, length: 10.2 } }],
}] },
} }
const anchor = draftInsertAnchor(initial.model)
expect(anchor).toMatchObject({ role: 'insert', originMm: [0, 0, 0], direction: '+y' })
jest.mocked(saveAccessoryDraft).mockClear().mockResolvedValue({ item: initial })
render(<AccessoryModelEditor initial={initial} initialModule="connector" initialCategory="" canEdit canSave onClose={jest.fn()} onSaved={jest.fn()} />)
fireEvent.click(await screen.findByRole('checkbox', { name: /采用模型安装基准/ }))
fireEvent.click(screen.getByRole('button', { name: '保存资料', exact: true }))
await waitFor(() => expect(saveAccessoryDraft).toHaveBeenCalled())
expect(jest.mocked(saveAccessoryDraft).mock.calls[0][2]).toMatchObject({ id: initial.model!.id, installationAnchors: [anchor] })
})
test('只改基本资料不会保存自动建议,明确采用后才写入加工规则', async () => {
const initial: AccessoryDraft = {
...assemblySources[0], category: '木螺丝', kind: '木螺丝', spec: 'M4*13', code: 'MLS-03', name: '木螺丝',
model: {
...assemblySources[0].model!, kind: '木螺丝', sourceSpec: 'M4*13',
cad: { engine: 'photo-cad-v1', scale: 'dimensioned', review: ['螺纹直径 4 mm'], parts: [{
name: '木螺丝', color: '#444444',
base: { shape: 'revolve', at: [0, 0, 0], axis: 'y', outline: [[0, 0], [2, 0], [2, 13], [3.5, 13], [3.5, 16], [0, 16]] },
operations: [{ op: 'add', tool: { shape: 'thread', at: [0, 1, 0], axis: 'y', diameter: 4, core: 3, length: 12, pitch: 1 } }],
}] },
},
}
const reference = { ...initial, id: 'screw-reference', code: 'MLS-01', machining: {
type: 'screw' as const, throughDiameterMm: 4, pilotDiameterMm: 3, effectiveLengthMm: 13, allowanceMm: 2,
} }
jest.mocked(saveAccessoryDraft).mockClear().mockResolvedValue({ item: initial })
const props = { initial, initialModule: 'connector' as const, initialCategory: '木螺丝', items: [reference],
canEdit: true, canSave: true, onClose: jest.fn(), onSaved: jest.fn() }
const { unmount } = render(<AccessoryModelEditor {...props} />)
await screen.findByRole('button', { name: '采用建议值' })
fireEvent.change(screen.getByLabelText('配件名称'), { target: { value: '木螺丝样件' } })
fireEvent.click(screen.getByRole('button', { name: '保存资料', exact: true }))
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
await waitFor(() => expect(props.onSaved).toHaveBeenCalledTimes(1))
expect(jest.mocked(saveAccessoryDraft).mock.calls[0][0].machining).toBeUndefined()
unmount()
render(<AccessoryModelEditor {...props} />)
fireEvent.click(await screen.findByRole('button', { name: '采用建议值' }))
fireEvent.click(screen.getByRole('button', { name: '保存资料', exact: true }))
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
await waitFor(() => expect(props.onSaved).toHaveBeenCalledTimes(2))
expect(jest.mocked(saveAccessoryDraft).mock.calls[1][0].machining).toEqual(reference.machining)
})

View File

@ -0,0 +1,77 @@
import type { AccessoryMachining } from '@/lib/intake-accessory-drilling'
type DrillingFields = {
title: string
connector: boolean
references: readonly string[]
fieldClassName: string
disabled: boolean
holeType: '' | AccessoryMachining['holeType']
setHoleType: (type: '' | AccessoryMachining['holeType']) => void
holeDiameter: string
setHoleDiameter: (text: string) => void
holeDepth: string
setHoleDepth: (text: string) => void
reverseHoleDepth: string
setReverseHoleDepth: (text: string) => void
headDiameterText: string
headDiameterOverride: string | null
setHeadDiameterOverride: (text: string) => void
modelHeadDiameter: number | undefined
countersinkDiameterMm: number | null
clearError: () => void
}
export function AccessoryDrillingEditor({
title, connector, references, fieldClassName, disabled, holeType, setHoleType, holeDiameter, setHoleDiameter,
holeDepth, setHoleDepth, reverseHoleDepth, setReverseHoleDepth, headDiameterText, headDiameterOverride,
setHeadDiameterOverride, modelHeadDiameter, countersinkDiameterMm, clearError,
}: DrillingFields) {
const countersunkThrough = holeType === 'countersunk-through'
return <fieldset className="min-w-0 border-t border-apple-separator pt-4">
<legend className="pr-2 text-sm font-semibold">{title}</legend>
{references.map(line => <p key={line} className="my-2 text-xs text-apple-label-secondary">{line}</p>)}
<div className="grid grid-cols-2 gap-x-3 gap-y-2.5 sm:grid-cols-3 xl:grid-cols-2">
<label className="space-y-1"><span>开孔方式</span>
<select className={fieldClassName} value={holeType} disabled={disabled}
onChange={(event) => { setHoleType(event.target.value as typeof holeType) }}>
<option value="">{connector ? '待确认' : '未设置'}</option><option value="blind">盲孔</option><option value="through">通孔</option>
<option value="countersunk-through">沉头通孔</option>
<option value="bidirectional">双向打孔</option>
</select>
</label>
{holeType && <>
<label className="space-y-1"><span>{countersunkThrough ? '通孔孔径(mm)' : '孔径(mm)'}</span>
<input className={fieldClassName} type="number" min="0.01" max="10000" step="any"
value={holeDiameter} disabled={disabled} onChange={(event) => { setHoleDiameter(event.target.value); clearError() }} />
</label>
{countersunkThrough && <>
<label className="space-y-1"><span>螺帽直径(mm)</span>
<input className={fieldClassName} type="number" min="0.01" max="9999" step="any"
value={headDiameterText} disabled={disabled} placeholder="按参考图或实物填写"
onChange={event => { setHeadDiameterOverride(event.target.value); clearError() }} />
</label>
<label className="space-y-1"><span>沉头孔径(mm)</span>
<input className={fieldClassName} type="number" readOnly value={countersinkDiameterMm ?? ''}
aria-describedby="accessory-countersink-rule" />
</label>
<p id="accessory-countersink-rule" className="col-span-full text-xs text-apple-label-secondary">
沉头孔径 = 螺帽直径 + 1 mm{headDiameterOverride === null && modelHeadDiameter !== undefined ? ';螺帽直径取自当前模型,可按参考图或实物修正' : ''}。沉头角度、深度待确认。
</p>
</>}
{holeType !== 'through' && !countersunkThrough && <label className="space-y-1"><span>{holeType === 'bidirectional' ? '正向孔深(mm)' : '孔深(mm)'}</span>
<input className={fieldClassName} type="number" min="0.01" max="10000" step="any"
value={holeDepth} disabled={disabled} onChange={(event) => { setHoleDepth(event.target.value); clearError() }} />
</label>}
{holeType === 'bidirectional' && <label className="space-y-1"><span>反向孔深(mm)</span>
<input className={fieldClassName} type="number" min="0.01" max="10000" step="any"
value={reverseHoleDepth} disabled={disabled} onChange={(event) => { setReverseHoleDepth(event.target.value); clearError() }} />
</label>}
<div className="col-span-full flex flex-wrap items-center gap-x-3 gap-y-1 text-xs">
<span>开孔基准</span>
<p className="text-apple-label-secondary">安装中心 · {holeType === 'bidirectional' ? '安装方向正反两向' : '安装方向'}</p>
</div>
</>}
</div>
</fieldset>
}

View File

@ -1,9 +1,11 @@
import { accessoryComponentDrillSummary } from '@/lib/intake-accessory-component-drill'
import { accessoryMachiningConstraintSummary, accessoryMachiningSummary } from '@/lib/intake-accessory-drilling'
import type { CamMachining } from '@/lib/intake-accessory-machining'
import { resolveCamWheelProcessing } from '@/lib/intake-accessory-machining-assets'
import type { AccessoryDraft } from '@/lib/intake-accessory-models'
import { surfaceMountProcessing } from '@/lib/intake-accessory-surface-mount'
import { accessoryProcessingDraft, type ProcessingDraft } from './accessory-processing-draft'
import { assemblyMemberProcessingLines, connectionModelReference } from './accessory-connection-standards'
const bore = (label: string, value: { diameterMm: number; depthMm: number }, part = '') =>
[label + ' Ø' + value.diameterMm + ' × 深 ' + value.depthMm + ' mm', part].filter(Boolean).join(' · ')
@ -13,13 +15,20 @@ export function camProcessingLines(rule: CamMachining, items: readonly Accessory
const item = items.find(row => row.id === id)
return item ? item.code + ' · ' + item.name : ''
}
const drill = items.find(item => item.id === rule.wheelId)?.componentDrill
const { wheel, conflict } = resolveCamWheelProcessing(rule, drill)
const wheelItem = items.find(item => item.id === rule.wheelId)
const rodDrill = items.find(item => item.id === rule.rodId)?.drilling
const insertDrill = rule.rodMount === 'insert' ? items.find(item => item.id === rule.insertId)?.drilling : undefined
const wheelDrill = wheelItem?.drilling
const { wheel, conflict } = resolveCamWheelProcessing(rule, wheelDrill ? undefined : wheelItem?.componentDrill)
return [
rule.rodMount === 'direct' ? bore('首板引孔', rule.pilot) : bore('预埋孔', rule.insert, name(rule.insertId)),
rule.rodMount === 'direct' ? bore('首板引孔', rule.pilot) : insertDrill && insertDrill.holeType !== 'blind'
? '预埋件孔型待核对:' + accessoryMachiningSummary(insertDrill)
: bore('预埋孔', insertDrill ?? rule.insert, name(rule.insertId)),
['杆孔 Ø' + rule.rodDiameterMm + ' · 有效 ' + rule.rodLengthMm + ' · 拧入 ' + rule.engagementMm + ' mm',
name(rule.rodId)].filter(Boolean).join(' · '),
bore('偏心轮盲孔', wheel, name(rule.wheelId)),
...(rodDrill ? ['连接杆标准:' + accessoryMachiningSummary(rodDrill) + ' · 杆孔用途和进刀面待确认'] : []),
wheelDrill && wheelDrill.holeType !== 'blind' ? '偏心轮孔型待核对:' + accessoryMachiningSummary(wheelDrill)
: bore('偏心轮盲孔', wheelDrill ?? wheel, name(rule.wheelId)),
...(conflict ? ['偏心轮的孔型或孔径与本组不一致,请核对。'] : []),
]
}
@ -30,11 +39,11 @@ function draftProcessingLines({ family, values, suggestionSource }: ProcessingDr
...(values.pilot !== undefined ? [`拧入板 Ø${values.pilot} 引孔(建议值)`] : []),
...(values.length !== undefined ? [`有效长度 ${values.length} mm`] : []),
...(values.allowance !== undefined ? [`孔深余量 ${values.allowance} mm(建议值)`] : []),
...(suggestionSource ? [`建议值参考同结构的 ${suggestionSource},核对后保存。`] : []),
...(suggestionSource ? [`建议值参考同结构的 ${suggestionSource}`] : []),
]
if (family === 'dowel') return [
...(values.firstDiameter !== undefined ? [`第一块板盲孔 Ø${values.firstDiameter}`] : []),
...(values.secondDiameter !== undefined ? [`第二块板盲孔 Ø${values.secondDiameter}`] : []),
...(values.firstDiameter !== undefined ? [`第一块板盲孔 Ø${values.firstDiameter} mm`] : []),
...(values.secondDiameter !== undefined ? [`第二块板盲孔 Ø${values.secondDiameter} mm`] : []),
]
return family === 'component' && values.diameter !== undefined
? [`${values.holeType === 'through' ? '通孔' : '盲孔'} Ø${values.diameter} mm`] : []
@ -44,8 +53,14 @@ export function AccessoryMachiningDetails({ item, items }: {
item: AccessoryDraft
items?: readonly AccessoryDraft[]
}) {
const { machining: rule, componentDrill, holes } = item
const draftLines = !rule && !componentDrill ? draftProcessingLines(accessoryProcessingDraft(item, items)) : []
const { machining: rule, drilling, componentDrill, holes } = item
const isConnector = item.module === 'connector'
const assembly = item.model?.assembly
const draftLines = isConnector && !rule && !drilling && !componentDrill && !assembly && !item.surfaceMount
? [...draftProcessingLines(accessoryProcessingDraft(item, items)), ...connectionModelReference(item.kind, item.model)] : []
const standardLines = drilling ? [accessoryMachiningSummary(drilling),
drilling.holeType === 'bidirectional' ? '安装中心 · 安装方向正反两向' : '安装中心 · 安装方向',
accessoryMachiningConstraintSummary(drilling.holeType)] : []
const companion = item.surfaceMount?.companion
const screw = companion && items?.find(source => source.id === companion.accessoryId)
const lines = item.surfaceMount ? [surfaceMountProcessing,
@ -54,12 +69,19 @@ export function AccessoryMachiningDetails({ item, items }: {
'有效长度 ' + rule.effectiveLengthMm + ' mm · 孔深余量 ' + rule.allowanceMm + ' mm',
] : rule?.type === 'dowel' ? [bore('第一块板盲孔', rule.first), bore('第二块板盲孔', rule.second)]
: rule?.type === 'cam' ? camProcessingLines(rule, items)
: componentDrill ? [accessoryComponentDrillSummary(componentDrill)] : draftLines
: isConnector && assembly ? assemblyMemberProcessingLines(assembly, items)
: componentDrill && !drilling ? [accessoryComponentDrillSummary(componentDrill)] : draftLines
const guidance = isConnector && assembly && rule?.type !== 'cam' ? '整套开孔仍待确认,可在编辑资料中查看并核对预填参数。'
: draftLines.length ? '自动带出 · 待确认'
: !standardLines.length && !lines.length && isConnector ? '孔型、孔径和深度待确认,请在编辑资料中补充。' : ''
if (!standardLines.length && !lines.length && !holes?.length && !isConnector) return null
return <div className="grid grid-cols-[88px_minmax(0,1fr)] gap-2 py-2">
<dt className="text-apple-label-secondary">零件加工参数</dt>
<dd className="min-w-0 space-y-1 break-words">
{lines.length > 0 ? <ul className="space-y-1">{lines.map(line => <li key={line}>{line}</li>)}</ul> : '未填写'}
{!!draftLines.length && <p className="text-xs text-amber-700">自动带出 · 待确认</p>}
{[...standardLines, ...lines].length > 0 && <ul className="space-y-1">
{[...standardLines, ...lines].map(line => <li key={line}>{line}</li>)}
</ul>}
{guidance && <p className="text-xs text-amber-700">{guidance}</p>}
{!!holes?.length && <ul className="space-y-1 text-apple-label-secondary">
{holes.map((hole, index) => <li key={index}>{bore('补充孔', hole,
hole.boardThicknessMm === undefined ? '' : '板厚 ' + hole.boardThicknessMm + ' mm')}</li>)}

View File

@ -4,7 +4,6 @@ import { useState } from 'react'
import Button from '@/components/ui/Button'
import { accessorySpec, CAM_KIT_KIND, type AccessoryDraft } from '@/lib/intake-accessory-models'
import { downloadAccessoryGlb, downloadAccessoryStep } from './draft-client'
import { accessoryMachiningConstraintSummary, accessoryMachiningSummary } from '@/lib/intake-accessory-drilling'
import { AccessoryMachiningDetails } from './AccessoryMachiningDetails'
import { accessoryScrewHeadDirection } from '@/lib/accessory-model-orientation'
@ -39,9 +38,6 @@ export function AccessoryModelDetail({ item, items, feedback, onBack, onEdit, on
['颜色', item.color || '未填写'],
[priceUnit === '套' ? '单套重量' : '单件重量', item.weightGrams == null ? '未填写' : item.weightGrams + ' 克'],
['单价', price === undefined ? '未填写' : '¥' + price + (priceUnit ? ' / ' + priceUnit : '')],
['加工参数', item.drilling ? accessoryMachiningSummary(item.drilling) : '未设置'],
...(item.drilling ? [['开孔基准', item.drilling.holeType === 'bidirectional' ? '安装中心 · 安装方向正反两向' : '安装中心 · 安装方向']] : []),
...(item.drilling ? [['孔深约束', accessoryMachiningConstraintSummary(item.drilling.holeType)]] : []),
]
async function saveGlb() {

View File

@ -14,6 +14,9 @@ import { generateAccessoryModel } from './generate-model'
import { AccessoryWeightField } from './AccessoryWeightField'
import { AccessoryHoleEditor, fromHoleRows, toHoleRows } from './AccessoryHoleEditor'
import { AccessoryProcessingEditor } from './AccessoryProcessingEditor'
import { AccessoryDrillingEditor } from './AccessoryDrillingEditor'
import { connectionModelReference } from './accessory-connection-standards'
import { draftInsertAnchor } from './accessory-assembly-model-draft'
import { accessoryProcessingDraft, preservedProcessingAnchors, processingPayload, type ProcessingValues } from './accessory-processing-draft'
import { accessoryFolderFor, accessoryFoldersFor, defaultAccessoryFolders, hasAccessoryFolders, type AccessoryFolderId } from '@/lib/intake-accessory-folders'
import {
@ -63,6 +66,7 @@ export function AccessoryModelEditor({ initial, template, initialModule, initial
const [weight, setWeight] = useState(seed?.weightGrams?.toString() ?? '')
const [holeRows, setHoleRows] = useState(() => toHoleRows(seed?.holes))
const [processingEdits, setProcessingEdits] = useState<Record<string, ProcessingValues>>({})
const [acceptedInsertModelId, setAcceptedInsertModelId] = useState<string | null>(null)
const [holeType, setHoleType] = useState<'' | AccessoryMachining['holeType']>(seed?.drilling?.holeType ?? '')
const [holeDiameter, setHoleDiameter] = useState(seed?.drilling?.diameterMm.toString() ?? '')
const [holeDepth, setHoleDepth] = useState(seed?.drilling?.depthMm?.toString() ?? '')
@ -137,6 +141,13 @@ export function AccessoryModelEditor({ initial, template, initialModule, initial
} } : {}),
depthRule: countersunkThrough ? accessoryCountersunkThroughDepthRule : accessoryMachiningDepthRule,
} : null
const connector = module === 'connector'
const showProcessing = processing.family !== 'other' && (!!processing.machining || !!processingInput.surfaceMount ||
(!drilling && (connector || !!processing.componentDrill)))
const modelReferences = connector && !drilling && !processing.machining && !processing.componentDrill
? connectionModelReference(kind, generationModel) : []
const insertAnchor = connector && ['预埋件', '带介内外牙', '直通内外牙'].includes(kind)
? draftInsertAnchor(generationModel) : undefined
function changeKind(value: string) {
if (value === kind) return
@ -291,15 +302,17 @@ export function AccessoryModelEditor({ initial, template, initialModule, initial
if (disabled || !canSave || (includeModel && !canSaveModel)) return
const selected = includeModel ? preview : savedModel
const selectedProcessing = accessoryProcessingDraft({ ...processingInput, model: selected }, items)
const confirmProcessing = !!edits || !!processing.suggestionSource
const confirmProcessing = showProcessing && !!edits
const rule = processingPayload(processing, edits ?? {}, confirmProcessing)
if (rule.error) { setError(rule.error); return }
if (confirmProcessing && JSON.stringify(rule) !== JSON.stringify(processingPayload(selectedProcessing, edits ?? {}, true))) {
setError('加工参数引用了新模型的尺寸,请选择同时保存资料和模型。')
return
}
const model = selected && rule.machining && selectedProcessing.anchor && !selected.installationAnchors?.length
? { ...selected, installationAnchors: [selectedProcessing.anchor] } : selected
const acceptedInsertAnchor = selected && selected.id === acceptedInsertModelId ? insertAnchor : undefined
const anchor = acceptedInsertAnchor ?? (rule.machining ? selectedProcessing.anchor : undefined)
const model = selected && anchor && !selected.installationAnchors?.length
? { ...selected, installationAnchors: [anchor] } : selected
const input = accessoryDraftInputSchema.safeParse({
id: initial?.id, revision: initial?.revision, module, category, kind, code, name, material, color, spec,
folderId: hasAccessoryFolders({ module, category }) ? folderId : null,
@ -440,59 +453,27 @@ export function AccessoryModelEditor({ initial, template, initialModule, initial
</div>
</div>
</fieldset>
<fieldset className="min-w-0 border-t border-apple-separator pt-4">
<legend className="pr-2 text-sm font-semibold">加工参数</legend>
<div className="grid grid-cols-2 gap-x-3 gap-y-2.5 sm:grid-cols-3 xl:grid-cols-2">
<label className="space-y-1"><span>开孔方式</span>
<select className={accessoryInput} value={holeType} disabled={disabled}
onChange={(event) => { setHoleType(event.target.value as typeof holeType); setMachiningCheck(null); setError('') }}>
<option value="">未设置</option><option value="blind">盲孔</option><option value="through">通孔</option>
<option value="countersunk-through">沉头通孔</option>
<option value="bidirectional">双向打孔</option>
</select>
</label>
{holeType && <>
<label className="space-y-1"><span>{countersunkThrough ? '通孔孔径(mm)' : '孔径(mm)'}</span>
<input className={accessoryInput} type="number" min="0.01" max="10000" step="any"
value={holeDiameter} disabled={disabled} onChange={(event) => { setHoleDiameter(event.target.value); setError('') }} />
</label>
{countersunkThrough && <>
<label className="space-y-1"><span>螺帽直径(mm)</span>
<input className={accessoryInput} type="number" min="0.01" max="9999" step="any"
value={headDiameterText} disabled={disabled} placeholder="按参考图或实物填写"
onChange={event => { setHeadDiameterOverride(event.target.value); setError('') }} />
</label>
<label className="space-y-1"><span>沉头孔径(mm)</span>
<input className={accessoryInput} type="number" readOnly value={countersinkDiameterMm ?? ''}
aria-describedby="accessory-countersink-rule" />
</label>
<p id="accessory-countersink-rule" className="col-span-full text-xs text-apple-label-secondary">
沉头孔径 = 螺帽直径 + 1 mm{headDiameterOverride === null && modelHeadDiameter !== undefined ? ';螺帽直径取自当前模型,可按参考图或实物修正' : ''}。沉头角度、深度待确认。
</p>
</>}
{holeType !== 'through' && !countersunkThrough && <label className="space-y-1"><span>{holeType === 'bidirectional' ? '正向孔深(mm)' : '孔深(mm)'}</span>
<input className={accessoryInput} type="number" min="0.01" max="10000" step="any"
value={holeDepth} disabled={disabled} onChange={(event) => { setHoleDepth(event.target.value); setError('') }} />
</label>}
{holeType === 'bidirectional' && <label className="space-y-1"><span>反向孔深(mm)</span>
<input className={accessoryInput} type="number" min="0.01" max="10000" step="any"
value={reverseHoleDepth} disabled={disabled} onChange={(event) => { setReverseHoleDepth(event.target.value); setError('') }} />
</label>}
<div className="col-span-full flex flex-wrap items-center gap-x-3 gap-y-1 text-xs">
<span>开孔基准</span>
<p className="text-apple-label-secondary">安装中心 · {holeType === 'bidirectional' ? '安装方向正反两向' : '安装方向'}</p>
</div>
</>}
</div>
</fieldset>
<AccessoryProcessingEditor draft={processing} edits={edits} disabled={disabled} onChange={patch => {
<AccessoryDrillingEditor title={connector && !showProcessing ? '零件加工参数' : '加工参数'} connector={connector}
references={showProcessing ? [] : modelReferences} fieldClassName={accessoryInput} disabled={disabled}
holeType={holeType} setHoleType={value => { setHoleType(value); setMachiningCheck(null); setError('') }}
holeDiameter={holeDiameter} setHoleDiameter={setHoleDiameter} holeDepth={holeDepth} setHoleDepth={setHoleDepth}
reverseHoleDepth={reverseHoleDepth} setReverseHoleDepth={setReverseHoleDepth}
headDiameterText={headDiameterText} headDiameterOverride={headDiameterOverride} setHeadDiameterOverride={setHeadDiameterOverride}
modelHeadDiameter={modelHeadDiameter} countersinkDiameterMm={countersinkDiameterMm} clearError={() => setError('')} />
{insertAnchor && generationModel && <label className="flex items-start gap-2 text-xs text-apple-label-secondary">
<input type="checkbox" className="mt-0.5" disabled={disabled} checked={acceptedInsertModelId === generationModel.id}
onChange={event => setAcceptedInsertModelId(event.target.checked ? generationModel.id : null)} />
<span>采用模型安装基准:孔口中心({insertAnchor.originMm.join(', ')} mm),沿 {insertAnchor.direction.toUpperCase()} 安装。随当前模型保存。</span>
</label>}
{(showProcessing || holeRows.length > 0) && <AccessoryProcessingEditor draft={showProcessing ? processing : undefined}
references={showProcessing ? modelReferences : []} edits={edits} disabled={disabled} onChange={patch => {
setProcessingEdits(previous => ({ ...previous, [processingKey]: { ...previous[processingKey], ...patch } }))
setError('')
}}>
{!!holeRows.length && <AccessoryHoleEditor rows={holeRows} canEdit={canEdit} disabled={disabled} onChange={rows => {
setHoleRows(rows); setError('')
}} />}
</AccessoryProcessingEditor>
</AccessoryProcessingEditor>}
<AccessoryAssemblyApplication mode={currentModel?.assembly ? 'assembly' : 'part'} value={application}
disabled={disabled} fieldClassName={accessoryInput} onChange={value => { setApplication(value); setError('') }}>
{holeType && <AccessoryMachiningCheck holeType={holeType} drilling={drilling} value={machiningCheck} onChange={value => {

View File

@ -1,3 +1,4 @@
import Button from '@/components/ui/Button'
import type { AccessoryDraft } from '@/lib/intake-accessory-models'
import { surfaceMountProcessing } from '@/lib/intake-accessory-surface-mount'
import { camProcessingLines } from './AccessoryMachiningDetails'
@ -13,17 +14,18 @@ const dowelFields = [
['secondDiameter', '第二块板盲孔孔径'], ['secondDepth', '第二块板盲孔深度'],
] as const
export function AccessoryProcessingEditor({ draft, edits, disabled, onChange, items, children }: {
draft: ProcessingDraft
export function AccessoryProcessingEditor({ draft, edits, disabled, onChange, items, children, references = [] }: {
draft?: ProcessingDraft
edits?: ProcessingValues
disabled: boolean
onChange: (patch: ProcessingValues) => void
items?: readonly AccessoryDraft[]
children?: ReactNode
references?: readonly string[]
}) {
const { family, machining, componentDrill, comparison, suggestionSource } = draft
const { family = 'other', machining, componentDrill, comparison, suggestionSource } = draft ?? {}
const suggestionId = useId()
const values = { ...draft.values, ...edits }
const values = { ...draft?.values, ...edits }
const automatic = (family === 'screw' || family === 'dowel' || family === 'component') && !machining && !componentDrill
const camLines = machining?.type === 'cam' ? camProcessingLines(machining, items) : []
const suggested = (key: ProcessingField) => !!suggestionSource && (key === 'pilot' || key === 'allowance') &&
@ -45,7 +47,7 @@ export function AccessoryProcessingEditor({ draft, edits, disabled, onChange, it
}
return <fieldset className="min-w-0 space-y-2.5 border-t border-apple-separator pt-2">
<legend className="pr-2 text-sm font-semibold">零件加工参数</legend>
<legend className="pr-2 text-sm font-semibold">{draft ? '零件加工参数' : '补充孔位'}</legend>
{family === 'surface' && <p className="text-apple-label-secondary">{surfaceMountProcessing}</p>}
{family === 'screw' && <>
<div className="grid grid-cols-2 gap-2.5">{screwFields.map(([key, label]) => number(key, label))}</div>
@ -67,11 +69,19 @@ export function AccessoryProcessingEditor({ draft, edits, disabled, onChange, it
{family === 'cam' && (camLines.length ? <ul className="space-y-1 text-apple-label-secondary">
{camLines.map(line => <li key={line}>{line}</li>)}
</ul> : <p className="text-apple-label-secondary">这组五金还没有完整的加工参数。</p>)}
{suggestionSource && <p id={suggestionId} className="text-apple-label-secondary">参考同结构的 {suggestionSource} 带出建议值,核对后保存。</p>}
{suggestionSource && <div className="flex flex-wrap items-center gap-2">
<p id={suggestionId} className="text-apple-label-secondary">
参考同结构的 {suggestionSource} 带出建议值。{edits ? '确认后的参数将在保存后生效。' : '请核对后采用,或直接修改。'}
</p>
{!edits && <Button type="button" size="small" variant="gray" disabled={disabled} onClick={() => onChange(values)}>
采用建议值
</Button>}
</div>}
{automatic && !suggestionSource && <p className="text-apple-label-secondary">
{Object.values(values).some(value => typeof value === 'number') ? '已带出可读取的尺寸,补齐空项后保存。' : '按实际工艺填写后保存。'}
</p>}
{comparison && <p className="text-amber-700">{comparison}</p>}
{references.map(line => <p key={line} className="text-xs text-apple-label-secondary">{line}</p>)}
{children}
</fieldset>
}

View File

@ -0,0 +1,74 @@
import { accessoryAxialRange } from '@/lib/accessory-model-orientation'
import type { AccessoryCadPrimitive } from '@/lib/intake-accessory-cad'
import type { AccessoryAnchor, InstallationAxis } from '@/lib/intake-accessory-installation'
import type { AccessoryModel } from '@/lib/intake-accessory-models'
const mm = (n: number) => Number(n.toFixed(3))
const additions = (part: NonNullable<AccessoryModel['cad']>['parts'][number]) =>
[part.base, ...part.operations.flatMap(({ op, tool }) => op === 'add' ? [tool] : [])]
const radius = (solid: AccessoryCadPrimitive) => {
if (solid.shape === 'cylinder' || solid.shape === 'thread') return solid.diameter / 2
if (solid.shape === 'revolve' && !solid.angle) return Math.max(...solid.outline.map(([r]) => r))
}
const coaxial = (a: readonly number[], b: readonly number[], axis: number) =>
a.every((value, i) => i === axis || Math.abs(value - b[i]) <= .01)
/** Use the contact in the saved model to separate the exposed rod from its thread. */
export function draftAssemblyRod(model?: AccessoryModel | null, insertDepth?: number) {
const cad = model?.cad
const anchors = model?.installationAnchors?.filter(anchor => anchor.role === 'rod')
if (!insertDepth || cad?.scale !== 'dimensioned' || cad.rotation || anchors?.length !== 1) return
const anchor = anchors[0]
const axis = anchor.direction[1] as 'x' | 'y' | 'z'
const index = 'xyz'.indexOf(axis)
const sign = anchor.direction.startsWith('+') ? 1 : -1
const solids = cad.parts.flatMap(additions)
const threads = solids.filter(solid => solid.shape === 'thread')
if (threads.length !== 1 || threads[0].axis !== axis) return
const thread = threads[0]
const coordinate = (value: number) => (value - anchor.originMm[index]) * sign
const threadEnds = [coordinate(thread.at[index]), coordinate(thread.at[index] + thread.length)]
if (Math.abs(Math.max(...threadEnds)) > .2 || Math.min(...threadEnds) >= 0) return
let rodReach = 0
let rodRadius = 0
for (const solid of solids) {
const range = accessoryAxialRange(solid, axis)
const r = radius(solid)
if (!range || r === undefined || !coaxial(solid.at, anchor.originMm, index)) return
const far = Math.max(...range.map(coordinate))
if (far <= .2) continue
rodReach = Math.max(rodReach, far)
rodRadius = Math.max(rodRadius, r)
}
const engagement = mm(-Math.min(...threadEnds))
if (rodReach <= 0 || rodRadius <= 0 || engagement > insertDepth) return
return { rodDiameter: Math.ceil(rodRadius * 2), rodLength: mm(rodReach + engagement), engagement }
}
/** The wider end of a simple coaxial insert is the mounting face. */
export function draftInsertAnchor(model?: AccessoryModel | null): AccessoryAnchor | undefined {
const cad = model?.cad
if (model?.imported || model?.installationAnchors?.length || cad?.scale !== 'dimensioned' ||
cad.rotation || cad.parts.length !== 1) return
const { name, base, operations } = cad.parts[0]
if (base.shape !== 'revolve' || base.angle) return
const axis = 'xyz'.indexOf(base.axis)
const heights = base.outline.map(([, height]) => height)
const low = Math.min(...heights)
const high = Math.max(...heights)
const endRadius = (height: number) => Math.max(...base.outline.filter(([, y]) => y === height).map(([r]) => r))
const holes = operations.flatMap(({ op, tool }) => op === 'cut' && (tool.shape === 'cylinder' || tool.shape === 'thread') &&
tool.axis === base.axis && coaxial(base.at, tool.at, axis) ? [tool] : [])
if (holes.length !== 1) return
const start = holes[0].at[axis] - base.at[axis]
const end = start + holes[0].length
const opensLow = start <= low + .02 && end > low
const opensHigh = end >= high - .02 && start < high
if (!opensLow && !opensHigh || opensLow && opensHigh && Math.abs(endRadius(low) - endRadius(high)) < .1) return
const fromLow = opensLow && (!opensHigh || endRadius(low) > endRadius(high))
const originMm: AccessoryAnchor['originMm'] = [...base.at]
originMm[axis] = mm(originMm[axis] + (fromLow ? low : high))
return { partPath: '0/0', partName: name, role: 'insert', originMm,
direction: ((fromLow ? '+' : '-') + base.axis) as InstallationAxis }
}

View File

@ -0,0 +1,56 @@
import { assemblyRoleNames, type AccessoryAssembly } from '@/lib/intake-accessory-assembly'
import { accessoryComponentDrillSummary } from '@/lib/intake-accessory-component-drill'
import { accessoryMachiningSummary } from '@/lib/intake-accessory-drilling'
import { readDowelModelGeometry } from '@/lib/intake-accessory-dowel-model'
import type { AccessoryDraft } from '@/lib/intake-accessory-models'
type Model = AccessoryDraft['model']
export function connectionModelReference(kind: string, model?: Model) {
if (!model || model.assembly || (model.kind && model.kind !== kind)) return []
if (kind === '圆棒榫' || kind === '木销') {
const length = readDowelModelGeometry(kind, model)?.length
return length ? [`模型榫长 ${length} mm,需确认两块板各自的孔深`] : []
}
const cad = model.cad
if (cad?.scale !== 'dimensioned') return []
if (kind === '连接杆' || kind === '双头连接杆') {
const threads = cad.parts.flatMap(part => [part.base, ...part.operations.flatMap(op => op.op === 'add' ? [op.tool] : [])])
.filter(solid => solid.shape === 'thread')
if (threads.length === 1) {
const [{ diameter, length }] = threads
return [`模型螺纹外径 Ø${diameter} mm · 螺纹段长 ${length} mm`]
}
}
if (cad.parts.length !== 1 || !['偏心轮', '预埋件', '带介内外牙', '直通内外牙'].includes(kind)) return []
const part = cad.parts[0]
if (part.operations.some(op => op.op === 'add')) return []
if (part.base.shape === 'cylinder') return [`模型外径 Ø${part.base.diameter} mm · 高 ${part.base.length} mm`]
if (part.base.shape === 'revolve') {
const heights = part.base.outline.map(([, height]) => height)
const diameter = Math.max(...part.base.outline.map(([radius]) => radius)) * 2
const height = Number((Math.max(...heights) - Math.min(...heights)).toFixed(3))
return [`模型外径 Ø${diameter} mm · 高 ${height} mm`]
}
return []
}
export function assemblyMemberStandards(assembly: AccessoryAssembly | undefined, items: readonly AccessoryDraft[] = []) {
return assembly?.components.map(component => {
const item = items.find(entry => entry.id === component.sourceId)
const drill = item?.drilling ?? item?.componentDrill
return { ...component, item, drill }
}) ?? []
}
export function assemblyMemberProcessingLines(assembly: AccessoryAssembly | undefined, items?: readonly AccessoryDraft[]) {
return assemblyMemberStandards(assembly, items).map(({ role, sourceCode, item, drill }) => {
const label = [assemblyRoleNames[role], item?.code ?? sourceCode].join(' · ')
const lines = item?.drilling ? [accessoryMachiningSummary(item.drilling)]
: item?.componentDrill ? [accessoryComponentDrillSummary(item.componentDrill)]
: item ? connectionModelReference(item.kind, item.model) : []
if (!drill) lines.push('标准孔位待确认')
if (role === 'rod' && drill) lines.push('杆孔用途和进刀面待确认')
return label + ':' + lines.join(' · ')
})
}

View File

@ -4,6 +4,7 @@ import type { AccessoryAnchor, InstallationAxis } from '@/lib/intake-accessory-i
import { accessoryMachiningSchema, type AccessoryMachining } from '@/lib/intake-accessory-machining'
import type { AccessoryDraft } from '@/lib/intake-accessory-models'
import { accessoryStandaloneProcessingType } from '@/lib/intake-accessory-machining-assets'
import { readDowelModelGeometry } from '@/lib/intake-accessory-dowel-model'
type Model = NonNullable<AccessoryDraft['model']>
type Input = Pick<AccessoryDraft, 'kind' | 'category' | 'spec' | 'machining' | 'componentDrill' | 'surfaceMount'> &
@ -91,25 +92,6 @@ function nominalScrew(spec = '') {
return match && Number(match[1]) > 0 && Number(match[2]) > 0 ? { diameter: Number(match[1]), length: Number(match[2]) } : undefined
}
function pegFacts(kind: string, model?: Model | null) {
if (!model || (model.kind && model.kind !== kind)) return
const cad = model.cad
if (cad) {
const part = cad.parts[0]
if (cad.rotation || cad.parts.length !== 1 || part.operations.length || part.base.shape !== 'cylinder') return
const { axis, diameter, length } = part.base
const originMm: AccessoryAnchor['originMm'] = [...part.base.at]
originMm[axes.indexOf(axis)] += length / 2
return { diameter: cad.scale === 'dimensioned' ? diameter : undefined,
anchor: { partPath: '0/0', partName: part.name, role: 'other', originMm, direction: '+' + axis } as AccessoryAnchor }
}
if (kind !== '圆棒榫') return
const { length, diameter } = model.dimensions
if (!(length > 0 && diameter > 0) || model.pending.includes('length')) return
return { diameter: model.pending.includes('diameter') ? undefined : diameter,
anchor: { partPath: '0/0', partName: 'Wood dowel', role: 'other', originMm: [0, length / 2, 0], direction: '+y' } as AccessoryAnchor }
}
function screwSuggestion(input: Input, measured: NonNullable<ReturnType<typeof screwFacts>>, items: readonly AccessoryDraft[]) {
if (!measured.profile || !input.module || input.kind !== '木螺丝') return
const candidates = items.flatMap(item => {
@ -162,7 +144,7 @@ export function accessoryProcessingDraft(input: Input, items: readonly Accessory
}
}
} else if (family === 'dowel') {
const facts = pegFacts(kind, matching)
const facts = readDowelModelGeometry(kind, matching)
anchor = facts?.anchor
if (machining?.type === 'dowel') Object.assign(values, { firstDiameter: machining.first.diameterMm,
firstDepth: machining.first.depthMm, secondDiameter: machining.second.diameterMm, secondDepth: machining.second.depthMm })

View File

@ -0,0 +1,28 @@
import type { AccessoryAnchor } from './intake-accessory-installation'
import type { AccessoryDraft } from './intake-accessory-models'
export function readDowelModelGeometry(kind: string, model?: AccessoryDraft['model']) {
if (!model || (model.kind && model.kind !== kind)) return
const cad = model.cad
if (cad) {
const part = cad.parts[0]
if (cad.rotation || cad.parts.length !== 1 || !part || part.operations.length) return
const { base } = part
if (base.shape !== 'cylinder' && base.shape !== 'fluted-dowel') return
const { axis, diameter, length } = base
const originMm: AccessoryAnchor['originMm'] = [...base.at]
originMm['xyz'.indexOf(axis)] += length / 2
const anchor: AccessoryAnchor = {
partPath: '0/0', partName: part.name, role: 'other', originMm, direction: `+${axis}`,
}
return { diameter: cad.scale === 'dimensioned' ? diameter : undefined,
length: cad.scale === 'dimensioned' ? length : undefined, anchor }
}
if (kind !== '圆棒榫' || model.imported || model.source === 'imported-glb') return
const { length, diameter } = model.dimensions
if (!(length > 0 && diameter > 0) || model.pending.includes('length')) return
const anchor: AccessoryAnchor = {
partPath: '0/0', partName: 'Wood dowel', role: 'other', originMm: [0, length / 2, 0], direction: '+y',
}
return { diameter: model.pending.includes('diameter') ? undefined : diameter, length, anchor }
}