@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,91 @@
1
+ import { loadBom, type BomRecord } from '../../dsh-hardware-ui/src/client/transport'
2
+ import { demandFor, manufacturerOf, originalMpn, rowKey, type BomLine } from './bom-rows'
3
+ import type { SavedBom } from './bom-snapshot'
4
+
5
+ export interface Offer {
6
+ vendor?: string
7
+ sku?: string
8
+ stock?: number
9
+ moq?: number
10
+ priceBreaks: {breakMin?: number; breakMax?: number | null; prices: {rmb?: number|null; cny?: number|null}}[]
11
+ }
12
+ export interface Candidate {
13
+ mpn:string; manufacturer:string; manufacturerId:string; package?:string; huaqiuPn?:string; description?:string; offers:Offer[]
14
+ }
15
+ export interface Matching { candidates:Candidate[]; selected?:Candidate; pending?:Candidate; error?:string }
16
+ export type MatchTable = Record<string, Matching>
17
+ export function searchTerm(r:BomRecord) {
18
+ const pkg = r.footprint.split(':').pop() || ''
19
+ const size = pkg.match(/(?:^|_)(\d{4})(?:_|$)/)?.[1]
20
+ const passive = /^R\d/i.test(r.references[0] || '') ? '电阻' : /^C\d/i.test(r.references[0] || '') ? '电容' : ''
21
+ const fallback = passive ? [r.value,size || pkg,passive].filter(Boolean).join(' ') : r.value
22
+ return (originalMpn(r) || r.fields['Huaqiu PN'] || r.fields['华秋料号'] || fallback).slice(0,200)
23
+ }
24
+ export function matchRow(r:BomRecord,candidates:Candidate[]):Matching {
25
+ const mpn = (originalMpn(r) || r.value).trim().toUpperCase()
26
+ const maker = manufacturerOf(r).trim().toUpperCase()
27
+ const pn = (r.fields['Huaqiu PN'] || r.fields['华秋料号'])?.trim().toUpperCase()
28
+ const exact = candidates.filter(p => (!maker || maker === p.manufacturer?.trim().toUpperCase())
29
+ && (pn ? pn === p.huaqiuPn?.toUpperCase() : p.mpn.toUpperCase() === mpn))
30
+ return { candidates, selected:exact.length === 1 ? exact[0] : undefined }
31
+ }
32
+ export function bestOffer(part:Candidate, demand:number) {
33
+ const choices = part.offers.flatMap(offer => {
34
+ const tiers = [...offer.priceBreaks].sort((a,b)=>(a.breakMin ?? 1)-(b.breakMin ?? 1))
35
+ return tiers.flatMap((tier,i)=>{
36
+ const count = Math.max(demand,offer.moq || 1,tier.breakMin || 1)
37
+ const max = tier.breakMax ?? ((tiers[i+1]?.breakMin ?? Infinity)-1)
38
+ if (count>max || offer.stock===undefined || offer.stock<count) return []
39
+ const unit = tier.prices.rmb ?? tier.prices.cny
40
+ if (typeof unit !== 'number' || !Number.isFinite(unit) || unit <= 0) return []
41
+ return [{offer,count,unit,cost:count*unit}]
42
+ })
43
+ })
44
+ return choices.sort((a,b) => a.cost-b.cost)[0]
45
+ }
46
+ export const identity = (p:Candidate) => JSON.stringify([p.manufacturerId,p.mpn.toUpperCase()])
47
+ export function basket(rows:readonly BomLine[], matches:MatchTable, quantity:number) {
48
+ const demand = new Map<string,{part:Candidate;count:number}>()
49
+ const included = rows.filter(r => !r.dnp)
50
+ for (const row of included) {
51
+ const part = matches[rowKey(row)]?.selected
52
+ if (!part) continue
53
+ const id = identity(part)
54
+ demand.set(id,{part,count:(demand.get(id)?.count || 0)+demandFor(row,quantity)})
55
+ }
56
+ const prices = new Map([...demand].map(([id,{part,count}]) => [id,bestOffer(part,count)]))
57
+ const priceFor = (part?:Candidate) => part && prices.get(identity(part))
58
+ const covered = included.filter(r => priceFor(matches[rowKey(r)]?.selected)).length
59
+ const total = [...prices.values()].reduce((sum,price) => sum+(price?.cost ?? 0),0)
60
+ return {priceFor,covered,lines:included.length,total}
61
+ }
62
+
63
+ class MissingManufacturingRoute extends Error {
64
+ constructor() {
65
+ super('制造服务尚未加载,请从系统托盘退出华秋 DSH 后重新打开。')
66
+ }
67
+ }
68
+
69
+ export async function manufacturingRequest<T>(operation:string, args:Record<string,unknown>, signal:AbortSignal):Promise<T> {
70
+ const res = await fetch('/api/v1/engineering-workbench/manufacture', {
71
+ method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({operation,...args}), signal,
72
+ })
73
+ if (!res.headers.get('content-type')?.includes('application/json')) {
74
+ if (res.status === 404) throw new MissingManufacturingRoute()
75
+ throw new Error('制造服务响应异常(HTTP '+res.status+')。')
76
+ }
77
+ const body = await res.json()
78
+ if (!res.ok || body.error) throw new Error(body.error || '制造服务暂时不可用。')
79
+ return body as T
80
+ }
81
+
82
+ export async function readManufacturingBom(path:string, cwd:string, session:string, signal:AbortSignal) {
83
+ try {
84
+ const data = await manufacturingRequest<{rows:BomRecord[];saved?:SavedBom;warning?:string}>('bom',{path},signal)
85
+ return { ...data, builtIn:false }
86
+ } catch (error) {
87
+ if (!(error instanceof MissingManufacturingRoute) || signal.aborted) throw error
88
+ const data = await loadBom(path,{cwd,session,signal})
89
+ return { rows:data.rows, saved:undefined, warning:undefined, builtIn:true }
90
+ }
91
+ }
package/src/styles.ts ADDED
@@ -0,0 +1,41 @@
1
+ import { bomStyles } from './bom-styles'
2
+
3
+ export const styles = `
4
+ .ew-model{margin:0 6px 6px;min-height:180px}.ew-model-info{overflow-wrap:anywhere}.ew-model-picker{position:relative;cursor:pointer;padding:4px 8px;border:1px solid var(--dsw-alias-border-l2,#abbcac);border-radius:4px}.ew-model-picker input{position:absolute;inset:0;width:100%;height:100%;opacity:0;cursor:pointer}.ew-model-picker:focus-within{outline:2px solid #bf845d;outline-offset:1px}
5
+ .ew-file-control{display:inline-flex;flex-wrap:wrap;align-items:center;gap:4px;max-width:100%}.ew-files .ew-preview-toggle{padding:3px 6px;font-size:12px}
6
+ .ew .ew-content[data-preview=false]{min-height:0}.ew .ew-content[data-preview=false] .ew-inspect{flex:1;width:auto;max-height:none}.ew .ew-content[data-preview=false] .ew-main{min-height:0}
7
+ .ew-content{display:flex;flex:1;flex-direction:column;min-height:260px}.ew-content .ew-main{min-width:0}
8
+ @container(min-width:800px){.ew-content{flex-direction:row}.ew-content .ew-inspect{width:230px;max-height:100%;border-left:1px solid var(--dsw-alias-border-l2,#c4cabb)}}
9
+ .ew{container-type:inline-size;box-sizing:border-box;height:100%;min-height:0;display:flex;flex-direction:column;overflow:auto;background:var(--dsw-alias-bg-layer-1,#f7f4ed);color:var(--dsw-alias-label-primary,#213b30);font-size:13px;line-height:1.5;font-family:inherit}
10
+ .ew-main{display:flex;flex:1;min-height:220px}.ew-main[data-manufacture=true] .ew-drawings{order:2;flex:1;min-width:0}.ew-manufacture{min-width:0}.ew *{box-sizing:border-box}.ew p{margin:12px}.ew button,.ew select,.ew input{font:inherit;color:inherit}
11
+ .ew button,.ew select,.ew input:not([type=checkbox]){background:var(--dsw-alias-bg-layer-1,#faf8f1);border:1px solid var(--dsw-alias-border-l2,#abbcac);border-radius:4px;padding:4px 8px}
12
+ .ew button{cursor:pointer}.ew button:disabled{opacity:.45;cursor:default}.ew :focus-visible{outline:2px solid #bf845d;outline-offset:1px}
13
+ .ew-head,.ew-tools,.ew-files,.ew-inspect header,.ew-manufacture header,.ew-manufacture footer{display:flex;align-items:center;gap:8px;padding:8px 12px;flex-wrap:wrap}
14
+ .ew-head{min-height:32px;padding-block:3px;padding-right:76px;background:#153f35;color:#faf3df;flex:none}
15
+ .ew-head span{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:40%}.ew-head select,.ew-head button{background:#204d40;border-color:#739181;color:#fff5e2}.ew-head select{max-width:48%}
16
+ .ew button[aria-pressed=true]{background:#235642;color:#fff8e9;border-color:#386c53}
17
+ .ew-tools,.ew-files{font-size:12px;padding-block:5px}.ew-files label{max-width:100%}.ew-files select{max-width:min(240px,70cqw)}.ew-drawings{display:flex;flex:1 0 200px;min-height:200px;padding:6px;gap:5px}.ew-pane{display:flex;flex-direction:column;flex:1;min-width:0;background:var(--dsw-alias-bg-base);border:1px solid var(--dsw-alias-border-l2,#bac8bc);border-radius:5px;overflow:hidden}.ew [hidden]{display:none!important}
18
+ .ew-stage{position:relative;flex:1;min-height:140px}.ew-surface{position:absolute;inset:0;overflow:hidden}.ew-message{position:absolute;inset:15px;display:grid;place-content:center;text-align:center;pointer-events:none}.ew-pane small,.ew-inspect small{padding:3px 8px}
19
+ .ew-inspect{padding:0 0 8px;border-top:1px solid var(--dsw-alias-border-l2,#c4cabb);max-height:32%;overflow:auto;flex:none}.ew-inspect input:not([type=checkbox]){width:130px}.ew-details,.ew-inspect>label{padding:2px 12px}.ew-details details span{display:inline-block;margin:2px 10px 2px 0}
20
+ .ew-manufacture{display:flex;flex:1;min-height:180px;flex-direction:column}.ew-manufacture header{justify-content:space-between}.ew-table-wrap{overflow:auto;flex:1}
21
+ .ew table{border-collapse:collapse;width:100%;text-align:left;font-size:12px}.ew th,.ew td{padding:6px 10px;border-bottom:1px solid var(--dsw-alias-border-l2,#c9d0c5)}.ew th{position:sticky;top:0;background:var(--dsw-alias-bg-layer-2,#e4e9de)}.ew tr[data-selected=true]{box-shadow:inset 3px 0 #ca906a;background:var(--dsw-alias-button-primary-dimmed)}
22
+ @container(max-width:580px){.ew-main[data-manufacture=true]{flex-direction:column-reverse;min-height:440px}.ew-drawings[data-review=true]{flex-direction:column;min-height:310px}.ew-head{padding-right:68px}.ew-tools,.ew-files{gap:4px}}
23
+ .ew[data-view=manufacture] .ew-main{flex-direction:column;min-height:0}
24
+ .ew[data-view=manufacture] .ew-drawings{flex:0 1 26%;min-height:140px}
25
+ .ew-manufacture{flex:1 1 300px;min-height:220px;overflow:auto}
26
+ .ew-pricing input{width:6em}.ew-manufacture .ew-pricing{justify-content:flex-start}
27
+ .ew-prices{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px;padding:8px 12px;margin:0;border-block:1px solid var(--dsw-alias-border-l2,#bac8bc)}
28
+ .ew-prices dt,.ew-manufacture td small{font-size:12px}.ew-prices dd{margin:2px 0;font-weight:600;font-variant-numeric:tabular-nums;overflow-wrap:anywhere}
29
+ .ew-manufacture td{vertical-align:top}.ew-manufacture td small{display:block;margin-top:3px}.ew-manufacture td select{max-width:18em}
30
+ .ew-fab-file{display:flex;flex:1;min-height:160px;flex-direction:column}.ew-fab-file select{max-width:65cqw}
31
+ .ew-fab-file header{justify-content:flex-start}.ew-gerber{display:grid;flex:1;min-height:160px;place-items:center;background:#15332c}.ew-gerber img{width:100%;height:100%;max-height:65vh;min-height:140px;object-fit:contain}
32
+ .ew-coordinates{overflow:auto;flex:1;margin:0;padding:12px;white-space:pre;font:12px/1.6 ui-monospace,monospace}
33
+ .ew-position-scroll{flex:1;min-width:0;min-height:80px;overflow:auto;overscroll-behavior:contain}
34
+ .ew .ew-position-table{border-collapse:separate;border-spacing:0;font-size:11px;font-variant-numeric:tabular-nums;line-height:1.4;white-space:nowrap}
35
+ .ew .ew-position-table th,.ew .ew-position-table td{padding:5px 9px;border-inline-end:1px solid var(--dsw-alias-border-l2,#cad4cd)}
36
+ .ew .ew-position-table th{z-index:1}
37
+ .ew-position-table [data-numeric=true]{text-align:end}
38
+ .ew-position-table td span{display:block;max-width:18em;overflow:hidden;text-overflow:ellipsis}
39
+ .ew-position-table tbody tr:nth-child(even){background:color-mix(in srgb,currentColor 4%,transparent)}
40
+ ${bomStyles}
41
+ `
package/src/tool.mjs ADDED
@@ -0,0 +1,24 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { TOOL, MODES, validRequest } from './navigation.mjs'
3
+
4
+ export const name = '@huaqiu/dsh-engineering-workbench'
5
+ export const inject = ['tools']
6
+
7
+ export function apply(ctx) {
8
+ ctx.effect(() => ctx.tools.register({
9
+ name: TOOL,
10
+ description: 'Open the engineering workbench in the current conversation’s right pane. Use only when the user asks to open, show, compare or locate an engineering artifact. Choose design for a schematic/PCB, mechanical for enclosure or part models, review for side-by-side, manufacture for BOM. Never use for general questions. This is navigation only and does not place orders. Supply the project when multiple KiCad projects exist.',
11
+ parameters: { type: 'object', additionalProperties: false, required: ['view'], properties: {
12
+ view: { type: 'string', enum: MODES },
13
+ action: { type: 'string', enum: ['open','suggest'], description: 'open when explicitly requested; suggest displays a button that the engineer can choose.' },
14
+ path: { type: 'string', description: 'Exact board or sheet path in this workspace, if known.' },
15
+ project: { type: 'string', description: 'Exact KiCad project file, if known.' },
16
+ reference: { type: 'string', description: 'Component reference to inspect or select, such as J1.' },
17
+ }},
18
+ output: { schema: {}, render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }] },
19
+ async execute(args) {
20
+ if (!validRequest(args)) throw new Error('请选择有效视图和 KiCad 工程文件。')
21
+ return { ...args, requestId: randomUUID(), issuedAt: Date.now() }
22
+ },
23
+ }), 'workbench navigation tool')
24
+ }