@huaqiu/dsh-engineering-workbench 0.7.29 → 0.7.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,227 @@
1
+ import { useCallback, useEffect, useRef, useState } from 'react'
2
+ import { Drawing } from './Drawings'
3
+ import { Manufacture, manufacturingTabs, type ManufacturingTab } from './Manufacture'
4
+ import { basename, defaultCircuitProject, filesOf, matches, type Part } from './files'
5
+ import { loadProjects, messageOf, openArtifact } from '../../dsh-hardware-ui/src/client/transport'
6
+ import type { DiscoveryInfo,HardwareProjectInfo } from '../../dsh-hardware-ui/src/client/model'
7
+ import { validRequest } from './navigation.mjs'
8
+ import { styles } from './styles'
9
+
10
+ import { pages, type View } from './pages'
11
+ import type { DesignTool } from './ToolRail'
12
+ type Kind = 'pcb'|'schematic'
13
+ const drawingNames = {pcb:'PCB', schematic:'原理图'}
14
+ export interface Nav {view:View; path?:string;project?:string;reference?:string;requestId?:string;designTool?:DesignTool}
15
+ export interface Face {
16
+ open:(session:string,kind:string,params?:Record<string,unknown>)=>void
17
+ draft:(session:string,text:string)=>void
18
+ }
19
+ export interface Selection { project?:string; board?:string; sheet?:string; reference?:string; kind?:Kind }
20
+ interface Props extends Face {
21
+ view:View
22
+ selectionFor:(session:string)=>Selection
23
+ sessionId:string
24
+ useSessions:(read:(s:{byId:Record<string,{cwd?:string}>})=>string|undefined)=>string|undefined
25
+ useTabInfo:()=>{tab:{navigation:{params?:Nav;revision?:number}}}
26
+ }
27
+
28
+ export function Workbench(props:Props) {
29
+ const cwd=props.useSessions(s=>s.byId[props.sessionId]?.cwd)
30
+ const nav=props.useTabInfo().tab.navigation
31
+ return <Workspace key={props.sessionId+(cwd??'')} cwd={cwd??''} session={props.sessionId} view={props.view} selection={props.selectionFor(props.sessionId)} nav={nav.params}
32
+ open={props.open} draft={props.draft}/>
33
+ }
34
+
35
+ interface WorkspaceProps extends Face {cwd:string;session:string;view:View;selection:Selection;nav?:Nav}
36
+ export function Workspace({cwd,session,view,selection,nav,open,draft}:WorkspaceProps) {
37
+ const [data,setData]=useState<DiscoveryInfo>()
38
+ const [reload,setReload]=useState(0)
39
+ const [error,setError]=useState('')
40
+ const [projectPath,setProjectPath]=useState(selection.project??'')
41
+ const [request,setRequest]=useState<Nav>()
42
+ const lastNav=useRef('')
43
+ useEffect(()=>{
44
+ let live=true
45
+ setError('')
46
+ loadProjects(cwd,undefined,session).then(result=>{
47
+ if(!live)return
48
+ if(view==='design' && !result.selected){
49
+ const preferred=defaultCircuitProject(result.projects??[],result.cwd||cwd)
50
+ if(preferred){
51
+ if(!selection.project)selection.project=preferred.path
52
+ setData({...result,selected:preferred})
53
+ return
54
+ }
55
+ }
56
+ setData(result)
57
+ }).catch(e=>{if(live){setData(undefined);setError(messageOf(e))}})
58
+ return ()=>{live=false}
59
+ },[cwd,session,reload,view,selection])
60
+ const projects=data?.projects??[]
61
+ const active=projects.find(p=>p.path===projectPath) ?? data?.selected ?? (projects.length===1?projects[0]:undefined)
62
+ useEffect(()=>{
63
+ if(!data || !nav || nav.view!==view || !validRequest(nav) || !nav.requestId || lastNav.current===nav.requestId)return
64
+ lastNav.current=nav.requestId
65
+ let candidates=data.projects??[]
66
+ if(nav.project) candidates=candidates.filter(p=>matches(p.path,nav.project!))
67
+ if(nav.path) candidates=candidates.filter(p=>{
68
+ const files=filesOf(p)
69
+ return [...files.boards,...files.sheets].some(f=>matches(f.path,nav.path!))
70
+ })
71
+ if(nav.path || nav.project){
72
+ if(candidates.length!==1){
73
+ setError(candidates.length?'多个工程匹配,请指定完整路径。':'当前工作区未找到指定文件或工程。');return
74
+ }
75
+ setProjectPath(candidates[0]!.path)
76
+ }
77
+ setError('');setRequest(nav)
78
+ },[data,nav,view])
79
+ return <section className="ew" aria-label={pages[view].title} data-view={view}><style>{styles}</style><header className="ew-head">
80
+ {projects.length>1 ? <select aria-label="当前工程" value={active?.path??''} onChange={e=>{if(active || !request?.designTool)setRequest(undefined);setError('');setProjectPath(e.target.value);Object.assign(selection,{project:e.target.value,board:undefined,sheet:undefined,reference:undefined,kind:undefined})}}>
81
+ <option value="" disabled>选择工程</option>{projects.map(p=><option key={p.path} value={p.path}>{p.name} · {p.path}</option>)}</select> :
82
+ <span title={active?.path}>{active?.name??basename(cwd)}</span>}
83
+ <button onClick={()=>setReload(n=>n+1)}>刷新</button></header>
84
+ {error && <p role="alert">{error}</p>}
85
+ {active ? <Project view={view} selection={selection} key={active.path} project={active} cwd={data?.cwd||cwd} session={session} request={request} open={open} draft={draft}/> :
86
+ <p role="status">{!data&&!error?'正在查找 KiCad 工程…':projects.length?'请选择要查看的工程。':'当前工作区没有可用的 KiCad 工程。'}</p>}
87
+ </section>
88
+ }
89
+
90
+ function Project({project,cwd,session,view,selection,request,open,draft}:Omit<WorkspaceProps,'nav'>&{project:HardwareProjectInfo;request?:Nav}) {
91
+ const {boards,sheets}=filesOf(project)
92
+ const seed = selection.project === project.path ? selection : {}
93
+ const preferSchematic = (view === 'design' && sheets.length > 0) || boards.length === 0
94
+ const [kind,setKind]=useState<Kind>(seed.kind ?? (preferSchematic ? 'schematic' : 'pcb'))
95
+ const [awaiting3d,setAwaiting3d]=useState(false)
96
+ const [manufacturingTab,setManufacturingTab]=useState<ManufacturingTab>('BOM')
97
+ const [boardPath,setBoard]=useState(boards.find(f=>f.path===seed.board)?.path || project.defaultBoard || (boards.length===1?boards[0]!.path:''))
98
+ const [sheetPath,setSheet]=useState(sheets.find(f=>f.path===seed.sheet)?.path || project.rootSheet?.path || project.schematic?.path || sheets[0]?.path || '')
99
+ const [reference,setReference]=useState(seed.reference??'')
100
+ const [parsedBoard,setParsedBoard]=useState<{key:string;parts:Part[]}>()
101
+ const [message,setMessage]=useState('')
102
+ const [visited,setVisited]=useState<Partial<Record<Kind,boolean>>>({})
103
+ const [closed,setClosed]=useState({pcb:false, schematic:false})
104
+ const [records,setRecords]=useState<string[]>([])
105
+ const seen=useRef('')
106
+ const board=boards.find(f=>f.path===boardPath)
107
+ const sheet=sheets.find(f=>f.path===sheetPath)
108
+ const boardKey=boardPath+'@'+(board?.revision??'')
109
+ const parts=parsedBoard?.key===boardKey?parsedBoard.parts:[]
110
+ const rememberParts=useCallback((parts:Part[])=>setParsedBoard({key:boardKey,parts}),[boardKey])
111
+ useEffect(()=>{
112
+ if(!request?.requestId || seen.current===request.requestId)return
113
+ seen.current=request.requestId
114
+ const next = {project:project.path,board:boardPath,sheet:sheetPath,reference,kind}
115
+ setAwaiting3d(false)
116
+ if(request.path){
117
+ const targets=[...boards,...sheets].filter(f=>matches(f.path,request.path!))
118
+ if(targets.length!==1){setMessage('文件路径不唯一或已移除,请手动选择。');return}
119
+ const target=targets[0]!
120
+ const targetKind = boards.includes(target) ? 'pcb' : 'schematic'
121
+ setClosed(prev=>({...prev,[targetKind]:false}))
122
+ if(boards.includes(target)){
123
+ if(target.path!==boardPath){setReference('');next.reference=''}
124
+ setBoard(target.path);setKind('pcb')
125
+ next.board=target.path;next.kind='pcb'
126
+ }
127
+ else{setSheet(target.path);setKind('schematic');next.sheet=target.path;next.kind='schematic'}
128
+ }
129
+ setMessage('')
130
+ if(view==='design' && request.designTool) {
131
+ const tool=request.designTool
132
+ const drawing=tool==='3d'?'pcb':tool
133
+ next.kind=drawing
134
+ setKind(drawing)
135
+ setClosed(prev=>({...prev,[drawing]:false}))
136
+ if(tool==='3d' && boards.some(b=>b.path===next.board)){
137
+ open(session,'hardware-engineering',{destination:'3d',path:next.board,projectPath:project.path})
138
+ } else if(tool==='3d' && boards.length){
139
+ setAwaiting3d(true)
140
+ setMessage('请选择要在 3D 中查看的板文件。')
141
+ } else if(!(drawing==='pcb'?boards:sheets).length){
142
+ setMessage(drawing==='pcb'?'当前工程没有板文件。':'当前工程没有原理图文件。')
143
+ }
144
+ }
145
+ if(request.reference){next.reference=request.reference.trim().toUpperCase();setReference(next.reference)}
146
+ Object.assign(selection,next)
147
+ },[request,boards,sheets])
148
+ const showPcb=!!board && !closed.pcb && (view!=='design'||kind==='pcb') && (view!=='manufacture'||manufacturingTab==='BOM')
149
+ const showSch=!!sheet && !closed.schematic && (view==='review'||(view==='design'&&kind==='schematic'))
150
+ const hasPreview=showPcb||showSch
151
+ useEffect(()=>{setVisited(prev=>({...prev,pcb:prev.pcb||showPcb,schematic:prev.schematic||showSch}))},[showPcb,showSch])
152
+ const selected=parts.find(p=>p.ref.toUpperCase()===reference.toUpperCase())
153
+ const inspectPath=(kind==='pcb'?board:sheet)?.path
154
+ const ask=()=>{
155
+ try{draft(session,'请结合当前工程回答:'+project.name+'\n文件:'+(view==='manufacture'?sheetPath:inspectPath||project.path)+(reference?'\n位号:'+reference:'')+'\n');setMessage('已加入左侧对话草稿。')}
156
+ catch(e){setMessage(messageOf(e))}
157
+ }
158
+ function nativeOpen(){
159
+ if(inspectPath)openArtifact({application:'kicad',artifactPath:inspectPath,projectPath:project.path,kind,session}).catch(e=>setMessage(messageOf(e)))
160
+ }
161
+ function remember(updates:Partial<Selection>) {
162
+ Object.assign(selection,{project:project.path,board:boardPath,sheet:sheetPath,kind,reference},updates)
163
+ }
164
+ function chooseReference(value:string) { setReference(value); remember({reference:value}) }
165
+ function chooseKind(value:Kind) {
166
+ setAwaiting3d(false);setMessage('')
167
+ setKind(value); remember({kind:value})
168
+ setClosed(prev=>({...prev,[value]:false}))
169
+ }
170
+ const selectFile=(type:Kind,path:string)=>{
171
+ setClosed(prev=>({...prev,[type]:false}))
172
+ if(type==='pcb'){setBoard(path);setReference('')}else setSheet(path)
173
+ setKind(type);setMessage('');remember(type==='pcb'?{board:path,reference:'',kind:type}:{sheet:path,kind:type})
174
+ if(type==='pcb' && awaiting3d){
175
+ setAwaiting3d(false)
176
+ open(session,'hardware-engineering',{destination:'3d',path,projectPath:project.path})
177
+ }
178
+ }
179
+ const order=()=>{
180
+ if(!board){setMessage('请先选择要下单的板文件。');return}
181
+ open(session,'hardware-engineering',{destination:'order',path:board.path,projectPath:project.path,schematicPath:project.rootSheet?.path||project.schematic?.path})
182
+ }
183
+ const recordKey=[boardPath,board?.revision,sheetPath,sheet?.revision,reference.trim().toUpperCase()].join(' · ')
184
+ return <>{view==='design' && <div className="ew-tools">
185
+ <button aria-pressed={kind==='schematic'} onClick={()=>chooseKind('schematic')}>原理图</button>
186
+ <button aria-pressed={kind==='pcb'} onClick={()=>chooseKind('pcb')}>PCB</button>
187
+ <button disabled={!board} onClick={()=>open(session,'hardware-engineering',{destination:'3d',path:boardPath,projectPath:project.path})}>板级 3D ↗</button>
188
+ <button disabled={!inspectPath} onClick={nativeOpen}>在 KiCad 中打开 ↗</button></div>}
189
+ {view==='manufacture' && <nav className="ew-tools" aria-label="制造文件">{manufacturingTabs.map(tab=>
190
+ <button key={tab} aria-pressed={tab===manufacturingTab} onClick={()=>setManufacturingTab(tab)}>{tab}</button>)}</nav>}
191
+ <div className="ew-files">{(['schematic','pcb'] as Kind[]).filter(type=>(view!=='design'||kind===type) && (view!=='manufacture'||manufacturingTab==='BOM'||type==='pcb')).map(type=>{
192
+ const files=type==='pcb'?boards:sheets
193
+ const file=type==='pcb'?board:sheet
194
+ const action=closed[type]?'打开':'关闭'
195
+ return <div className="ew-file-control" key={type}><label>{type==='pcb'?'板文件':'原理图'} <select value={file?.path||''} onChange={e=>selectFile(type,e.target.value)}>
196
+ <option value="" disabled>选择文件</option>{files.map(f=><option key={f.path} value={f.path}>{basename(f.path)}</option>)}</select></label>
197
+ {file && (view!=='manufacture'||(type==='pcb' && manufacturingTab==='BOM')) && <button type="button" className="ew-preview-toggle"
198
+ aria-label={action+drawingNames[type]+'预览'} title={action+drawingNames[type]+'预览'}
199
+ onClick={()=>setClosed(prev=>({...prev,[type]:!prev[type]}))}>{action}预览</button>}
200
+ </div>
201
+ })}</div>
202
+ {message&&<p role="status">{message}</p>}
203
+ <div className="ew-content" data-preview={hasPreview}><div className="ew-main" data-manufacture={view==='manufacture'} hidden={!hasPreview&&view!=='manufacture'}>
204
+ <div className="ew-drawings" hidden={!hasPreview} data-review={showPcb&&showSch}>
205
+ {(['schematic','pcb'] as Kind[]).map(type=>{
206
+ const visible=type==='pcb'?showPcb:showSch
207
+ const file=type==='pcb'?board:sheet
208
+ if (!file || closed[type] || (!visible && !visited[type])) return null
209
+ return <section className="ew-pane" hidden={!visible} key={type}>
210
+ {view==='review'&&<small>{type==='pcb'?'PCB':'原理图'}</small>}
211
+ <Drawing key={file.path+'@'+(file.revision??'')} kind={type} path={file.path} session={session} cwd={cwd} onParts={type==='pcb'?rememberParts:undefined}/>
212
+ </section>
213
+ })}</div>
214
+ {view==='manufacture' && <Manufacture key={JSON.stringify([sheet?.path,sheet?.revision,boardKey])} tab={manufacturingTab}
215
+ path={sheet?.path || ''} board={board?.path || ''} boardKey={boardKey} cwd={cwd} session={session} reference={reference} location={selected?.location} select={chooseReference} ask={ask} order={order}/>}
216
+ </div>
217
+ {view!=='manufacture' && <section className="ew-inspect"><header><strong>{view==='review'?'评审记录':'对象属性'}</strong>
218
+ <input list={'ew-refs-'+view+'-'+session} aria-label="位号" placeholder="输入位号,如 J1" value={reference} onChange={e=>chooseReference(e.target.value)}/>
219
+ <datalist id={'ew-refs-'+view+'-'+session}>{parts.map((p,i)=><option key={i} value={p.ref}/>)}</datalist>
220
+ <button onClick={ask}>询问助手</button></header>
221
+ {selected && <div className="ew-details"><b>{selected.ref}</b> {selected.value} · {selected.footprint}
222
+ {selected.location&&<p>{selected.location}</p>}
223
+ <details><summary>焊盘与网络({selected.pins.length})</summary>{selected.pins.map((p,i)=><span key={i}>{p.number} {p.net}</span>)}</details></div>}
224
+ {reference&&!selected&&<small>当前已读 PCB 中未找到此位号。</small>}
225
+ {view==='review' && <label><input type="checkbox" disabled={!board||!sheet||!reference} checked={records.includes(recordKey)} onChange={e=>setRecords(prev=>e.target.checked?[...prev,recordKey]:prev.filter(k=>k!==recordKey))}/> 当前文件对 · {reference || '选定位号'} 已复核</label>}
226
+ </section>}</div></>
227
+ }
package/src/bom-csv.ts ADDED
@@ -0,0 +1,107 @@
1
+ import type { BomRecord as BomRow } from '../../dsh-hardware-ui/src/client/transport'
2
+
3
+ /** Delimited text reader: quoted fields, doubled quotes, CRLF rows. */
4
+ export function parseCsv(text: string, delimiter: ',' | '\t' = ','): string[][] {
5
+ const rows: string[][] = []
6
+ let row: string[] = []
7
+ let field = ''
8
+ let quoted = false
9
+ const source = text.replace(/^\uFEFF/u, '')
10
+ for (let index = 0; index < source.length; index += 1) {
11
+ const char = source[index]
12
+ if (quoted) {
13
+ if (char === '"') {
14
+ if (source[index + 1] === '"') {
15
+ field += '"'
16
+ index += 1
17
+ } else {
18
+ quoted = false
19
+ }
20
+ } else {
21
+ field += char
22
+ }
23
+ continue
24
+ }
25
+ if (char === '"') {
26
+ quoted = true
27
+ } else if (char === delimiter) {
28
+ row.push(field)
29
+ field = ''
30
+ } else if (char === '\r') {
31
+ continue
32
+ } else if (char === '\n') {
33
+ row.push(field)
34
+ rows.push(row)
35
+ row = []
36
+ field = ''
37
+ } else {
38
+ field += char
39
+ }
40
+ }
41
+ if (field !== '' || row.length > 0) {
42
+ row.push(field)
43
+ rows.push(row)
44
+ }
45
+ return rows.filter(cells => cells.some(cell => cell.trim() !== ''))
46
+ }
47
+
48
+ /**
49
+ * Group KiCad's per-reference BOM rows.
50
+ *
51
+ * Identity is every column except the reference and quantity columns, so a
52
+ * different MPN or a DNP flag always produces a separate line; ordering follows
53
+ * the first reference seen, which keeps the table stable between reads.
54
+ *
55
+ * Column names follow `kicad-cli sch export bom`'s default field set, which is
56
+ * `Refs,Value,Footprint,Qty,DNP`; a customized `--fields` header may spell the
57
+ * same columns out in full, and a grouped export may pack several references
58
+ * into one cell, so both spellings and both shapes are accepted.
59
+ */
60
+ export function groupBomRows(table: readonly string[][]): BomRow[] {
61
+ const [header, ...body] = table
62
+ if (header === undefined) return []
63
+ const columns = header.map(cell => cell.trim())
64
+ const find = (...aliases: readonly RegExp[]): number =>
65
+ columns.findIndex(cell => aliases.some(alias => alias.test(cell)))
66
+ const referenceIndex = find(/^refs?$/iu, /^references?$/iu)
67
+ const quantityIndex = find(/^qty$/iu, /^quantity$/iu)
68
+ const valueIndex = find(/^value$/iu)
69
+ const footprintIndex = find(/^footprint$/iu)
70
+ const dnpIndex = find(/^dnp$/iu)
71
+ const groups = new Map<string, { references: string[]; fields: Record<string, string>; dnp: boolean }>()
72
+ for (const cells of body) {
73
+ const references = referenceIndex === -1
74
+ ? []
75
+ : (cells[referenceIndex] ?? '').split(/[,;\s]+/u).map(reference => reference.trim()).filter(reference => reference !== '')
76
+ if (references.length === 0) continue
77
+ const fields: Record<string, string> = {}
78
+ columns.forEach((column, index) => {
79
+ if (index === referenceIndex || index === quantityIndex || index === valueIndex
80
+ || index === footprintIndex || index === dnpIndex) return
81
+ const text = (cells[index] ?? '').trim()
82
+ if (text !== '') fields[column] = text
83
+ })
84
+ const dnpText = dnpIndex === -1 ? '' : (cells[dnpIndex] ?? '').trim()
85
+ const dnp = /^(1|true|yes|dnp|x)$/iu.test(dnpText)
86
+ const identity = JSON.stringify([
87
+ valueIndex === -1 ? '' : (cells[valueIndex] ?? '').trim(),
88
+ footprintIndex === -1 ? '' : (cells[footprintIndex] ?? '').trim(),
89
+ dnp,
90
+ Object.fromEntries(Object.entries(fields).sort(([a], [b]) => a.localeCompare(b))),
91
+ ])
92
+ const group = groups.get(identity) ?? { references: [], fields, dnp }
93
+ group.references.push(...references)
94
+ groups.set(identity, group)
95
+ }
96
+ return [...groups.entries()].map(([identity, group]) => {
97
+ const [value, footprint, dnp] = JSON.parse(identity) as [string, string, boolean]
98
+ return {
99
+ references: group.references,
100
+ quantity: group.references.length,
101
+ value,
102
+ footprint,
103
+ dnp,
104
+ fields: group.fields,
105
+ } satisfies BomRow
106
+ })
107
+ }
@@ -0,0 +1,34 @@
1
+ import { demandFor, descriptionOf, modelOf, originalMpn, referencesLabel, rowKey, type BomLine } from './bom-rows'
2
+ import { basket, identity, type MatchTable } from './procurement'
3
+
4
+ function cell(value:unknown):string{
5
+ let text=String(value??'')
6
+ if(typeof value==='string' && (/^\s*[=+@-]/.test(text)||/^[\t\r\n]/.test(text)))text="'"+text
7
+ return '"'+text.replaceAll('"','""')+'"'
8
+ }
9
+ export function bomCsv(rows:readonly BomLine[],matches:MatchTable,quantity:number,queriedAt:string){
10
+ const summary=basket(rows,matches,quantity)
11
+ const counted=new Set<string>()
12
+ const table:unknown[][]=[['位号','型号','封装','原厂型号','每套用量','生产套数','需求数量','采购状态','采购型号','制造商','华秋料号','供应商','供应商料号','库存','起订量','单价(元)','同型号合购数量(仅首行)','合购金额(元,仅首行)','待确认候选型号','询价时间','查询说明','需求描述','匹配描述']]
13
+ for(const row of rows){
14
+ const match=matches[rowKey(row)],part=row.dnp?undefined:match?.selected
15
+ const price=summary.priceFor(part)
16
+ const id=part&&identity(part)
17
+ const first=!!id && !counted.has(id)
18
+ if(id)counted.add(id)
19
+ const state=row.dnp?'不装配':match?.error?'查询失败':part?(price?'已匹配':'未报价'):match?.candidates.length?'待确认':match?'无匹配':'待查询'
20
+ table.push([referencesLabel(row),modelOf(row),row.footprint,originalMpn(row),row.quantity,quantity,demandFor(row,quantity),state,
21
+ part?.mpn,part?.manufacturer,part?.huaqiuPn,price?.offer.vendor,price?.offer.sku,price?.offer.stock,
22
+ price && (price.offer.moq||1),price?.unit,first?price?.count:'',first && price?Number(price.cost.toFixed(6)):'',
23
+ !part?match?.candidates.map(c=>c.mpn).join(' / '):'',queriedAt,match?.error,descriptionOf(row),part?.description])
24
+ }
25
+ return '\uFEFF'+table.map(r=>r.map(cell).join(',')).join('\r\n')+'\r\n'
26
+ }
27
+ export function downloadBom(path:string,csv:string){
28
+ const link=document.createElement('a')
29
+ const url=URL.createObjectURL(new Blob([csv],{type:'text/csv;charset=utf-8'}))
30
+ link.href=url
31
+ link.download=(path.split(/[\\/]/).pop()||'工程').replace(/\.kicad_sch$/i,'')+'-BOM.csv'
32
+ document.body.append(link)
33
+ try{link.click()}finally{link.remove();setTimeout(()=>URL.revokeObjectURL(url),30000)}
34
+ }
@@ -0,0 +1,35 @@
1
+ import type { BomRecord } from '../../dsh-hardware-ui/src/client/transport'
2
+
3
+ export interface BomLine extends BomRecord {
4
+ readonly manual?: true
5
+ readonly source?: BomRecord
6
+ }
7
+
8
+ export const mpnFields = ['MPN', 'Mpn', 'Manufacturer Part Number', '制造商料号', '型号']
9
+ export const manufacturerFields = ['Manufacturer', '品牌']
10
+ export const descriptionFields = ['Description', '描述']
11
+
12
+ function field(row: Pick<BomRecord, 'fields'>, names: readonly string[]) {
13
+ return names.map(name => row.fields[name]).find(Boolean) ?? ''
14
+ }
15
+
16
+ export const originalMpn = (row: Pick<BomRecord, 'fields'>) => field(row, mpnFields)
17
+ export const manufacturerOf = (row: BomRecord) => field(row, manufacturerFields)
18
+ export const descriptionOf = (row: BomRecord) => field(row, descriptionFields)
19
+ export const modelOf = (row: Pick<BomRecord, 'fields' | 'value'>) => row.value.trim() || originalMpn(row)
20
+
21
+ export function referencesLabel(row: BomLine) {
22
+ return row.references.join(', ')
23
+ }
24
+
25
+ export function rowKey(row: BomLine) {
26
+ return row.manual ? 'manual:' + referencesLabel(row) : boardReferences(row).join(', ')
27
+ }
28
+
29
+ export function boardReferences(row: BomLine) {
30
+ return (row.source ?? row).references
31
+ }
32
+
33
+ export function demandFor(row: BomLine, sets: number) {
34
+ return row.dnp ? 0 : row.quantity * sets
35
+ }
@@ -0,0 +1,85 @@
1
+ import { descriptionFields, rowKey, type BomLine } from './bom-rows'
2
+ import type { Candidate, MatchTable } from './procurement'
3
+
4
+ export interface SavedLine {
5
+ row:BomLine
6
+ candidates?:Candidate[]
7
+ selection?:number
8
+ pending?:number
9
+ error?:string
10
+ }
11
+ export interface BomSnapshot {
12
+ schema:1
13
+ quantity:number
14
+ queriedAt:string
15
+ boardKey:string
16
+ quotes:{pcb:string;smt:string}
17
+ lines:SavedLine[]
18
+ }
19
+ export interface SavedBom extends BomSnapshot {version:string;savedAt:string}
20
+
21
+ export function snapshotLines(rows:readonly BomLine[],matches:MatchTable):SavedLine[]{
22
+ return rows.map(row=>{
23
+ const match=matches[rowKey(row)]
24
+ if(!match)return {row}
25
+ const pending=match.pending ? match.candidates.indexOf(match.pending) : -1
26
+ return {row,candidates:match.candidates,selection:match.selected?match.candidates.indexOf(match.selected):-1,
27
+ pending:pending>=0?pending:undefined,error:match.error}
28
+ })
29
+ }
30
+ function signature(row:BomLine, includeDescription:boolean) {
31
+ const fields=Object.entries(row.fields).filter(([name])=>includeDescription || !descriptionFields.includes(name))
32
+ return JSON.stringify([row.manual??false,[...row.references].sort(),row.quantity,row.value,row.footprint,row.dnp,fields.sort(([a],[b])=>a.localeCompare(b))])
33
+ }
34
+ export function restoreRows(rows:readonly BomLine[],saved:SavedBom) {
35
+ const edits=new Map<string,BomLine>()
36
+ const additions:BomLine[]=[]
37
+ for(const {row} of saved.lines){
38
+ if(row.manual)additions.push(row)
39
+ else if(row.source)edits.set(signature(row.source,true),row)
40
+ }
41
+ return [...rows.map(row=>edits.get(signature(row,true))??row),...additions]
42
+ }
43
+ export function restoreMatches(rows:readonly BomLine[],saved:SavedBom) {
44
+ const previous=new Map(saved.lines.map(line=>[signature(line.row,false),line]))
45
+ const matches:MatchTable={}
46
+ let unchanged=0
47
+ for(const row of rows){
48
+ const line=previous.get(signature(row,false))
49
+ if(!line)continue
50
+ unchanged++
51
+ if(line.candidates)matches[rowKey(row)]={candidates:line.candidates,
52
+ selected:line.candidates[line.selection??-1],pending:line.candidates[line.pending??-1],error:line.error}
53
+ }
54
+ return {matches,changed:unchanged!==rows.length || unchanged!==saved.lines.length}
55
+ }
56
+ const object=(x:unknown):x is Record<string,unknown>=>typeof x==='object' && x!==null && !Array.isArray(x)
57
+ const optionalNumber=(x:unknown)=>x==null || typeof x==='number' && Number.isFinite(x)
58
+ const optionalString=(x:unknown)=>x==null || typeof x==='string'
59
+ function candidate(x:unknown):boolean {
60
+ return object(x) && typeof x.mpn==='string' && typeof x.manufacturerId==='string' && optionalString(x.manufacturer)
61
+ && optionalString(x.package) && optionalString(x.huaqiuPn) && optionalString(x.description) && Array.isArray(x.offers) && x.offers.every(o=>
62
+ object(o) && optionalString(o.vendor) && optionalString(o.sku) && optionalNumber(o.stock) && optionalNumber(o.moq)
63
+ && Array.isArray(o.priceBreaks) && o.priceBreaks.every(t=>object(t) && optionalNumber(t.breakMin) && optionalNumber(t.breakMax)
64
+ && object(t.prices) && optionalNumber(t.prices.rmb) && optionalNumber(t.prices.cny)))
65
+ }
66
+ function validRow(r:unknown):r is BomLine {
67
+ return object(r) && Array.isArray(r.references) && r.references.every(v=>typeof v==='string') && typeof r.value==='string'
68
+ && typeof r.footprint==='string' && typeof r.dnp==='boolean' && typeof r.quantity==='number' && Number.isSafeInteger(r.quantity)
69
+ && object(r.fields) && Object.values(r.fields).every(v=>typeof v==='string')
70
+ }
71
+ export function validSnapshot(x:unknown):x is BomSnapshot {
72
+ if(!object(x) || x.schema!==1 || typeof x.quantity!=='number' || !Number.isInteger(x.quantity) || x.quantity<1 || x.quantity>100000
73
+ || typeof x.queriedAt!=='string' || typeof x.boardKey!=='string' || !object(x.quotes)
74
+ || typeof x.quotes.pcb!=='string' || typeof x.quotes.smt!=='string' || !Array.isArray(x.lines))return false
75
+ return x.lines.every(line=>{
76
+ if(!object(line) || !validRow(line.row))return false
77
+ const r=line.row
78
+ return (r.manual===undefined || r.manual===true && r.references.length===1 && r.quantity>=1 && r.quantity<=100000)
79
+ && (r.source===undefined || !r.manual && validRow(r.source)) && optionalString(line.error)
80
+ && (line.candidates===undefined ? line.pending===undefined : Array.isArray(line.candidates) && line.candidates.every(candidate)
81
+ && typeof line.selection==='number' && Number.isInteger(line.selection) && line.selection>=-1 && line.selection<line.candidates.length
82
+ && (line.pending===undefined || typeof line.pending==='number' && Number.isInteger(line.pending)
83
+ && line.pending>=0 && line.pending<line.candidates.length && line.selection===-1))
84
+ })
85
+ }
@@ -0,0 +1,86 @@
1
+ export const bomStyles = `
2
+ .ew-manufacture[data-manufacturing-tab=BOM] {
3
+ --bom-line: var(--dsw-alias-border-l2,#cad4cd);
4
+ --bom-surface: var(--dsw-alias-bg-layer-1,#faf8f2);
5
+ --bom-head: var(--dsw-alias-bg-layer-2,#e7ece5);
6
+ --bom-label: var(--dsw-alias-label-secondary,#506357);
7
+ --bom-green: var(--dsw-alias-brand-primary,#236045);
8
+ }
9
+ .ew-manufacture[data-manufacturing-tab=BOM] .ew-prices {gap:0;padding:5px 0}
10
+ .ew-manufacture[data-manufacturing-tab=BOM] .ew-prices div {padding:1px 12px}
11
+ .ew-manufacture[data-manufacturing-tab=BOM] .ew-prices div+div {border-inline-start:1px solid var(--bom-line)}
12
+ .ew-bom-grid {min-width:0;min-height:155px;flex:1;display:flex;flex-direction:column;border-top:1px solid var(--bom-line)}
13
+ .ew-bom-bar {display:flex;align-items:center;justify-content:space-between;gap:4px 12px;flex-wrap:wrap;padding:0 10px}
14
+ .ew-bom-filters,.ew-bom-search {display:flex;align-items:center;gap:6px;min-width:0}
15
+ .ew-bom-filters {flex-wrap:wrap;gap:2px}
16
+ .ew .ew-bom-filters button {
17
+ padding:8px 6px 7px;background:transparent;border:0;border-radius:0;
18
+ border-bottom:2px solid transparent;color:var(--bom-label);white-space:nowrap;font-size:12px;
19
+ }
20
+ .ew .ew-bom-filters button[aria-pressed=true] {border-bottom-color:var(--bom-green);color:var(--bom-green);font-weight:600}
21
+ .ew-bom-filters span {font-variant-numeric:tabular-nums}
22
+ .ew-bom-search {margin-inline-start:auto;padding-block:4px}
23
+ .ew .ew-bom-search input {width:min(16em,56cqw);min-width:0;font-size:12px}
24
+ .ew .ew-bom-search button {flex:none;color:var(--bom-green);font-size:12px;font-weight:600;white-space:nowrap}
25
+ .ew-bom-add {
26
+ display:grid;grid-template-columns:repeat(auto-fit,minmax(min(9em,100%),1fr));gap:8px;
27
+ margin:5px 10px 8px;padding:10px;border:1px solid var(--bom-line);border-radius:5px;background:var(--bom-surface);
28
+ }
29
+ .ew-bom-add label,.ew-bom-edit label {display:grid;gap:3px;min-width:0;color:var(--bom-label);font-size:12px}
30
+ .ew-bom-add label input,.ew-bom-edit input,.ew-bom-part-search input {width:100%;min-width:0;color:var(--dsw-alias-label-primary,currentColor)}
31
+ .ew-bom-description {grid-column:1/-1}
32
+ .ew-bom-description textarea {min-width:0;width:100%;border:1px solid var(--bom-line);border-radius:4px;padding:4px 8px;
33
+ font:inherit;color:var(--dsw-alias-label-primary,currentColor);background:var(--bom-surface);resize:vertical}
34
+ .ew-bom-add [role=alert],.ew-bom-edit [role=alert] {grid-column:1/-1;color:var(--dsw-alias-label-primary,currentColor)}
35
+ .ew-bom-add-actions {grid-column:1/-1;display:flex;justify-content:flex-end;gap:6px}
36
+ .ew .ew-bom-add-actions button[type=submit] {background:#235642;border-color:#386c53;color:#fff8e9}
37
+ .ew-bom-scroll {min-width:0;min-height:80px;flex:1;overflow:auto;overscroll-behavior:contain}
38
+ .ew .ew-bom-table {width:100%;min-width:720px;border-collapse:separate;border-spacing:0;table-layout:fixed;font-size:11px;line-height:1.35}
39
+ .ew-bom-refs {width:11%}
40
+ .ew-bom-material {width:22%}
41
+ .ew-bom-match {width:24%}
42
+ .ew-bom-usage {width:11%}
43
+ .ew-bom-offer {width:14%}
44
+ .ew-bom-result {width:18%}
45
+ .ew-bom-table thead {position:sticky;top:0;z-index:2}
46
+ .ew .ew-bom-table th,.ew .ew-bom-table td {padding:5px 7px;border-inline-end:1px solid var(--bom-line);border-bottom:1px solid var(--bom-line);vertical-align:top}
47
+ .ew .ew-bom-table th {position:static;background:var(--bom-head);font-weight:600;text-align:start}
48
+ .ew .ew-bom-table thead th {border-top:1px solid var(--bom-line)}
49
+ .ew .ew-bom-section th {padding-block:5px;background:var(--bom-surface);color:var(--bom-green)}
50
+ .ew-bom-table td {font-variant-numeric:tabular-nums}
51
+ .ew-bom-table tr[data-bom-row] td:nth-child(n+3) {background:color-mix(in srgb,var(--bom-green) 4%,transparent)}
52
+ .ew .ew-bom-table tr[data-bom-row]:hover {background:color-mix(in srgb,currentColor 5%,transparent)}
53
+ .ew .ew-bom-table tr[data-selected=true] {background:color-mix(in srgb,#769f87 26%,var(--bom-surface));box-shadow:inset 3px 0 #c58c60}
54
+ .ew-bom-details {display:grid;gap:2px;margin:0;min-width:0}
55
+ .ew-bom-details > div {display:flex;align-items:baseline;gap:4px;min-width:0}
56
+ .ew-bom-details dt {flex:none;white-space:nowrap;color:var(--bom-label)}
57
+ .ew-bom-details dd,.ew-bom-clip,.ew-bom-result-text>* {min-width:0;margin:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
58
+ .ew-bom-cell-head {display:flex;align-items:center;gap:4px;min-height:18px;margin-bottom:2px}
59
+ .ew-bom-cell-head>:first-child {flex:1;min-width:0}
60
+ .ew .ew-bom-table button.ew-bom-ref {border:0;border-radius:0;padding:0;background:transparent;font:inherit;text-align:start}
61
+ .ew-bom-ref:hover {text-decoration:underline}
62
+ .ew .ew-bom-table button.ew-bom-inline {flex:none;line-height:1.15;padding:2px 4px;font-size:10px;color:var(--bom-green);white-space:nowrap}
63
+ .ew .ew-bom-table .ew-bom-confirm {margin-inline-start:5px}
64
+ .ew-bom-empty,.ew .ew-bom-table td small {color:var(--bom-label);font-size:inherit}
65
+ .ew-bom-status {display:inline-block;font-weight:600;margin-bottom:3px}
66
+ .ew-bom-status::before {content:'';display:inline-block;vertical-align:1px;margin-right:5px;width:5px;height:5px;border-radius:50%;background:currentColor;opacity:.5}
67
+ .ew-bom-status[data-state=已匹配]::before {background:#4da478;opacity:1}
68
+ .ew-bom-status:is([data-state=待确认],[data-state=未报价],[data-state=查询失败])::before {background:#c48c48;opacity:1}
69
+ .ew-bom-dialog {
70
+ width:min(520px,calc(100vw - 24px));max-height:calc(100vh - 32px);overflow:auto;
71
+ border:1px solid var(--bom-line);border-radius:8px;background:var(--bom-surface);
72
+ color:var(--dsw-alias-label-primary,#213b30);padding:12px;box-shadow:0 12px 40px rgb(0 0 0 / .24);
73
+ }
74
+ .ew-bom-dialog::backdrop {background:rgb(15 26 22 / .4)}
75
+ .ew-bom-dialog-title {display:flex;align-items:center;justify-content:space-between;gap:8px;margin:0 0 10px}
76
+ .ew-bom-dialog-title h3 {margin:0;font-size:14px;overflow-wrap:anywhere}
77
+ .ew-bom-edit {display:grid;gap:8px;grid-template-columns:repeat(auto-fit,minmax(min(11em,100%),1fr))}
78
+ .ew-bom-edit label:only-of-type {grid-column:1/-1}
79
+ .ew-bom-part-search {display:flex;gap:6px}
80
+ .ew-bom-part-search button {flex:none}
81
+ .ew-bom-search-results {list-style:none;padding:0;margin:8px 0 0}
82
+ .ew-bom-search-results li {display:flex;align-items:center;gap:8px;border-top:1px solid var(--bom-line);padding:6px 0}
83
+ .ew-bom-search-results button {flex:none}
84
+ .ew-bom-result-text {flex:1;min-width:0;display:grid}
85
+ .ew-bom-result-text small {color:var(--bom-label)}
86
+ `
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Caption-menu copy (zh / en).
3
+ *
4
+ * Same balance rule as the sibling packages: `ZH as const` defines the key set,
5
+ * `EN: Record<CaptionKey, string>` makes a missing English string a compile
6
+ * error, and zh is the runtime fallback. The desktop resolves its own caption
7
+ * strings from `document.documentElement.lang`, so we read the same attribute.
8
+ */
9
+ export const ZH = {
10
+ design: '设计',
11
+ review: '评审',
12
+ manufacture: '制造',
13
+ circuitDesign: '电路设计',
14
+ mechanicalDesign: '结构设计',
15
+ openPage: '打开{title}页面',
16
+ needSession: '请先打开会话',
17
+ } as const
18
+
19
+ export type CaptionKey = keyof typeof ZH
20
+
21
+ export const EN: Record<CaptionKey, string> = {
22
+ design: 'Design',
23
+ review: 'Review',
24
+ manufacture: 'Manufacture',
25
+ circuitDesign: 'Circuit Design',
26
+ mechanicalDesign: 'Mechanical Design',
27
+ openPage: 'Open {title}',
28
+ needSession: 'Open a session first',
29
+ }
30
+
31
+ export type CaptionCopy = (key: CaptionKey, params?: Record<string, string>) => string
32
+
33
+ /** `en*` → English; anything else falls back to zh, matching the desktop. */
34
+ export function captionCopyFor(lang: string | undefined): CaptionCopy {
35
+ const pack: Record<CaptionKey, string> = lang?.toLowerCase().startsWith('en') ? EN : ZH
36
+ return (key, params) => {
37
+ let text: string = pack[key]
38
+ if (params) {
39
+ for (const name of Object.keys(params)) text = text.split(`{${name}}`).join(params[name]!)
40
+ }
41
+ return text
42
+ }
43
+ }