@huaqiu/dsh-engineering-workbench 0.7.28 → 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.
- package/README.md +40 -26
- package/lib/client.js +13089 -1260
- package/lib/host.mjs +137 -18
- package/package.json +17 -2
- package/src/BomDialogs.tsx +220 -0
- package/src/BomGrid.tsx +172 -0
- package/src/Drawings.tsx +30 -0
- package/src/FabricationFiles.tsx +94 -0
- package/src/Manufacture.tsx +195 -0
- package/src/Mechanical.tsx +173 -0
- package/src/ToolRail.tsx +46 -0
- package/src/Workbench.tsx +227 -0
- package/src/bom-csv.ts +107 -0
- package/src/bom-export.ts +34 -0
- package/src/bom-rows.ts +35 -0
- package/src/bom-snapshot.ts +85 -0
- package/src/bom-styles.ts +86 -0
- package/src/caption-copy.ts +43 -0
- package/src/caption-menu.ts +158 -0
- package/src/client.tsx +100 -0
- package/src/files.ts +56 -0
- package/src/manufacturing-host.mjs +158 -0
- package/src/navigation.mjs +32 -0
- package/src/pages.ts +12 -0
- package/src/price.mjs +79 -0
- package/src/procurement.ts +91 -0
- package/src/styles.ts +41 -0
- package/src/tool.mjs +24 -0
package/lib/host.mjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { createRequire } from "node:module";
|
|
2
2
|
import { execFile } from "node:child_process";
|
|
3
|
-
import { mkdtemp, readFile, rm } from "node:fs/promises";
|
|
3
|
+
import { lstat, mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
4
5
|
import { tmpdir } from "node:os";
|
|
5
6
|
import { join } from "node:path";
|
|
6
7
|
import { promisify } from "node:util";
|
|
7
8
|
import { createRequire as createRequire$1 } from "module";
|
|
8
|
-
import { randomUUID } from "node:crypto";
|
|
9
9
|
//#region \0rolldown/runtime.js
|
|
10
10
|
var __create = Object.create;
|
|
11
11
|
var __defProp = Object.defineProperty;
|
|
@@ -6959,9 +6959,9 @@ function unzipSync(data, opts) {
|
|
|
6959
6959
|
return files;
|
|
6960
6960
|
}
|
|
6961
6961
|
//#endregion
|
|
6962
|
-
//#region
|
|
6963
|
-
/**
|
|
6964
|
-
function parseCsv(text) {
|
|
6962
|
+
//#region src/bom-csv.ts
|
|
6963
|
+
/** Delimited text reader: quoted fields, doubled quotes, CRLF rows. */
|
|
6964
|
+
function parseCsv(text, delimiter = ",") {
|
|
6965
6965
|
const rows = [];
|
|
6966
6966
|
let row = [];
|
|
6967
6967
|
let field = "";
|
|
@@ -6979,7 +6979,7 @@ function parseCsv(text) {
|
|
|
6979
6979
|
continue;
|
|
6980
6980
|
}
|
|
6981
6981
|
if (char === "\"") quoted = true;
|
|
6982
|
-
else if (char ===
|
|
6982
|
+
else if (char === delimiter) {
|
|
6983
6983
|
row.push(field);
|
|
6984
6984
|
field = "";
|
|
6985
6985
|
} else if (char === "\r") continue;
|
|
@@ -7170,6 +7170,15 @@ function snapOz(thicknessMm, allowed) {
|
|
|
7170
7170
|
for (const candidate of allowed) if (Math.abs(oz - candidate) < Math.abs(oz - best)) best = candidate;
|
|
7171
7171
|
return best;
|
|
7172
7172
|
}
|
|
7173
|
+
/** A footprint's value text: the `Value` property (KiCad 8+) or its legacy `fp_text`. */
|
|
7174
|
+
function footprintValue(node) {
|
|
7175
|
+
for (const entry of node) {
|
|
7176
|
+
if (!isNode(entry)) continue;
|
|
7177
|
+
if (head(entry) === "property" && entry[1] === "Value" && typeof entry[2] === "string") return entry[2];
|
|
7178
|
+
if (head(entry) === "fp_text" && entry[1] === "value" && typeof entry[2] === "string") return entry[2];
|
|
7179
|
+
}
|
|
7180
|
+
return "";
|
|
7181
|
+
}
|
|
7173
7182
|
/**
|
|
7174
7183
|
* Derive the fabrication facts the order form needs from a saved board.
|
|
7175
7184
|
*
|
|
@@ -7198,6 +7207,9 @@ function readBoardFacts(text) {
|
|
|
7198
7207
|
let minViaDrillMm;
|
|
7199
7208
|
let smdPads = 0;
|
|
7200
7209
|
let allPads = 0;
|
|
7210
|
+
let smdPadCount = 0;
|
|
7211
|
+
let pthPadCount = 0;
|
|
7212
|
+
const parts = /* @__PURE__ */ new Set();
|
|
7201
7213
|
for (const node of root) {
|
|
7202
7214
|
if (!isNode(node)) continue;
|
|
7203
7215
|
const name = head(node);
|
|
@@ -7212,9 +7224,18 @@ function readBoardFacts(text) {
|
|
|
7212
7224
|
continue;
|
|
7213
7225
|
}
|
|
7214
7226
|
if (name === "footprint") {
|
|
7215
|
-
const
|
|
7216
|
-
allPads +=
|
|
7217
|
-
|
|
7227
|
+
const padNodes = node.filter((entry) => isNode(entry) && head(entry) === "pad");
|
|
7228
|
+
allPads += padNodes.length;
|
|
7229
|
+
const attr = child$1(node, "attr") ?? [];
|
|
7230
|
+
if (attr.some((entry) => entry === "smd")) smdPads += padNodes.length;
|
|
7231
|
+
for (const pad of padNodes) if (pad[2] === "smd") smdPadCount += 1;
|
|
7232
|
+
else if (pad[2] === "thru_hole") pthPadCount += 1;
|
|
7233
|
+
const libId = typeof node[1] === "string" ? node[1] : "";
|
|
7234
|
+
const excluded = attr.some((entry) => entry === "exclude_from_bom" || entry === "board_only");
|
|
7235
|
+
if (libId !== "" && !excluded) {
|
|
7236
|
+
const footprint = libId.slice(libId.lastIndexOf(":") + 1);
|
|
7237
|
+
parts.add(`${footprintValue(node)}\u0000${footprint}`);
|
|
7238
|
+
}
|
|
7218
7239
|
continue;
|
|
7219
7240
|
}
|
|
7220
7241
|
if (name === "segment" || name === "arc") {
|
|
@@ -7262,6 +7283,11 @@ function readBoardFacts(text) {
|
|
|
7262
7283
|
4
|
|
7263
7284
|
]) },
|
|
7264
7285
|
...allPads === 0 ? {} : { padCount: smdPads > 0 ? smdPads : allPads },
|
|
7286
|
+
...allPads === 0 ? {} : {
|
|
7287
|
+
smdPadCount,
|
|
7288
|
+
pthPadCount
|
|
7289
|
+
},
|
|
7290
|
+
...parts.size === 0 ? {} : { partCount: parts.size },
|
|
7265
7291
|
...Object.keys(copperAliases).length === 0 ? {} : { copperAliases }
|
|
7266
7292
|
};
|
|
7267
7293
|
}
|
|
@@ -7624,21 +7650,90 @@ function apply$1(ctx) {
|
|
|
7624
7650
|
}), "workbench navigation tool");
|
|
7625
7651
|
}
|
|
7626
7652
|
//#endregion
|
|
7653
|
+
//#region src/bom-rows.ts
|
|
7654
|
+
const mpnFields = [
|
|
7655
|
+
"MPN",
|
|
7656
|
+
"Mpn",
|
|
7657
|
+
"Manufacturer Part Number",
|
|
7658
|
+
"制造商料号",
|
|
7659
|
+
"型号"
|
|
7660
|
+
];
|
|
7661
|
+
const manufacturerFields = ["Manufacturer", "品牌"];
|
|
7662
|
+
const descriptionFields = ["Description", "描述"];
|
|
7663
|
+
//#endregion
|
|
7664
|
+
//#region src/bom-snapshot.ts
|
|
7665
|
+
const object = (x) => typeof x === "object" && x !== null && !Array.isArray(x);
|
|
7666
|
+
const optionalNumber = (x) => x == null || typeof x === "number" && Number.isFinite(x);
|
|
7667
|
+
const optionalString = (x) => x == null || typeof x === "string";
|
|
7668
|
+
function candidate(x) {
|
|
7669
|
+
return object(x) && typeof x.mpn === "string" && typeof x.manufacturerId === "string" && optionalString(x.manufacturer) && optionalString(x.package) && optionalString(x.huaqiuPn) && optionalString(x.description) && Array.isArray(x.offers) && x.offers.every((o) => object(o) && optionalString(o.vendor) && optionalString(o.sku) && optionalNumber(o.stock) && optionalNumber(o.moq) && Array.isArray(o.priceBreaks) && o.priceBreaks.every((t) => object(t) && optionalNumber(t.breakMin) && optionalNumber(t.breakMax) && object(t.prices) && optionalNumber(t.prices.rmb) && optionalNumber(t.prices.cny)));
|
|
7670
|
+
}
|
|
7671
|
+
function validRow(r) {
|
|
7672
|
+
return object(r) && Array.isArray(r.references) && r.references.every((v) => typeof v === "string") && typeof r.value === "string" && typeof r.footprint === "string" && typeof r.dnp === "boolean" && typeof r.quantity === "number" && Number.isSafeInteger(r.quantity) && object(r.fields) && Object.values(r.fields).every((v) => typeof v === "string");
|
|
7673
|
+
}
|
|
7674
|
+
function validSnapshot(x) {
|
|
7675
|
+
if (!object(x) || x.schema !== 1 || typeof x.quantity !== "number" || !Number.isInteger(x.quantity) || x.quantity < 1 || x.quantity > 1e5 || typeof x.queriedAt !== "string" || typeof x.boardKey !== "string" || !object(x.quotes) || typeof x.quotes.pcb !== "string" || typeof x.quotes.smt !== "string" || !Array.isArray(x.lines)) return false;
|
|
7676
|
+
return x.lines.every((line) => {
|
|
7677
|
+
if (!object(line) || !validRow(line.row)) return false;
|
|
7678
|
+
const r = line.row;
|
|
7679
|
+
return (r.manual === void 0 || r.manual === true && r.references.length === 1 && r.quantity >= 1 && r.quantity <= 1e5) && (r.source === void 0 || !r.manual && validRow(r.source)) && optionalString(line.error) && (line.candidates === void 0 ? line.pending === void 0 : Array.isArray(line.candidates) && line.candidates.every(candidate) && typeof line.selection === "number" && Number.isInteger(line.selection) && line.selection >= -1 && line.selection < line.candidates.length && (line.pending === void 0 || typeof line.pending === "number" && Number.isInteger(line.pending) && line.pending >= 0 && line.pending < line.candidates.length && line.selection === -1));
|
|
7680
|
+
});
|
|
7681
|
+
}
|
|
7682
|
+
//#endregion
|
|
7627
7683
|
//#region src/manufacturing-host.mjs
|
|
7628
7684
|
const run = promisify(execFile);
|
|
7629
7685
|
const route = "/api/v1/engineering-workbench/manufacture";
|
|
7630
7686
|
const isLayer = (name) => /\.(gbr|ger|g[bt][clmops]|gko|gm\d+|g\d+|drl|xln)$/i.test(name);
|
|
7631
7687
|
const fields = [
|
|
7632
|
-
|
|
7633
|
-
|
|
7634
|
-
|
|
7635
|
-
"型号",
|
|
7636
|
-
"制造商料号",
|
|
7637
|
-
"Manufacturer",
|
|
7638
|
-
"品牌",
|
|
7688
|
+
...mpnFields,
|
|
7689
|
+
...manufacturerFields,
|
|
7690
|
+
...descriptionFields,
|
|
7639
7691
|
"Huaqiu PN",
|
|
7640
7692
|
"华秋料号"
|
|
7641
7693
|
];
|
|
7694
|
+
const pendingSaves = /* @__PURE__ */ new Map();
|
|
7695
|
+
async function readSavedBom(file) {
|
|
7696
|
+
let info;
|
|
7697
|
+
try {
|
|
7698
|
+
info = await lstat(file);
|
|
7699
|
+
} catch (e) {
|
|
7700
|
+
if (e.code === "ENOENT") return null;
|
|
7701
|
+
throw e;
|
|
7702
|
+
}
|
|
7703
|
+
if (!info.isFile() || info.size > 25165824) throw new Error("BOM 保存文件无效或过大。");
|
|
7704
|
+
const saved = JSON.parse(await readFile(file, "utf8"));
|
|
7705
|
+
if (!validSnapshot(saved) || typeof saved.version !== "string" || typeof saved.savedAt !== "string") throw new Error("BOM 保存文件格式无效。");
|
|
7706
|
+
return saved;
|
|
7707
|
+
}
|
|
7708
|
+
async function saveBom(file, snapshot, expectedVersion) {
|
|
7709
|
+
if (!validSnapshot(snapshot)) throw new Error("BOM 数据格式无效,请刷新并重试。");
|
|
7710
|
+
const key = process.platform === "win32" ? file.toLowerCase() : file;
|
|
7711
|
+
const write = (pendingSaves.get(key) ?? Promise.resolve()).catch(() => {}).then(async () => {
|
|
7712
|
+
if (((await readSavedBom(file))?.version ?? null) !== expectedVersion) throw new Error("此 BOM 已在其他窗口更新,请重新打开后再保存。");
|
|
7713
|
+
const version = randomUUID(), savedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
7714
|
+
const temp = file + "." + version + ".tmp";
|
|
7715
|
+
try {
|
|
7716
|
+
await writeFile(temp, JSON.stringify({
|
|
7717
|
+
...snapshot,
|
|
7718
|
+
version,
|
|
7719
|
+
savedAt
|
|
7720
|
+
}), "utf8");
|
|
7721
|
+
await rename(temp, file);
|
|
7722
|
+
} finally {
|
|
7723
|
+
await rm(temp, { force: true });
|
|
7724
|
+
}
|
|
7725
|
+
return {
|
|
7726
|
+
version,
|
|
7727
|
+
savedAt
|
|
7728
|
+
};
|
|
7729
|
+
});
|
|
7730
|
+
pendingSaves.set(key, write);
|
|
7731
|
+
try {
|
|
7732
|
+
return await write;
|
|
7733
|
+
} finally {
|
|
7734
|
+
if (pendingSaves.get(key) === write) pendingSaves.delete(key);
|
|
7735
|
+
}
|
|
7736
|
+
}
|
|
7642
7737
|
async function exportText(service, source, kind, signal) {
|
|
7643
7738
|
const cli = service.installations().kicad?.cli;
|
|
7644
7739
|
if (!cli) throw new Error("请在「设置 → 硬件工程」配置 KiCad。");
|
|
@@ -7718,6 +7813,7 @@ async function searchOffers(tools, query, signal) {
|
|
|
7718
7813
|
manufacturerId: p.manufacturer.id,
|
|
7719
7814
|
package: p.package,
|
|
7720
7815
|
huaqiuPn: p.huaqiuPn,
|
|
7816
|
+
description: p.description,
|
|
7721
7817
|
offers: offers.filter((o) => o.manufacturerId === p.manufacturer.id && o.mpn.toUpperCase() === p.mpn.toUpperCase()).map((o) => ({
|
|
7722
7818
|
vendor: o.vendorName || o.vendor,
|
|
7723
7819
|
sku: o.sku,
|
|
@@ -7767,7 +7863,30 @@ async function manufacture(ctx, input, signal) {
|
|
|
7767
7863
|
artifactPath: path,
|
|
7768
7864
|
signal
|
|
7769
7865
|
});
|
|
7770
|
-
if (
|
|
7866
|
+
if (source.kind === "schematic" && (operation === "bom" || operation === "save-bom")) {
|
|
7867
|
+
const file = source.path + ".hq-bom.json";
|
|
7868
|
+
if (operation === "save-bom") return saveBom(file, input.snapshot, input.version);
|
|
7869
|
+
let saved = null, warning = "";
|
|
7870
|
+
try {
|
|
7871
|
+
saved = await readSavedBom(file);
|
|
7872
|
+
} catch (e) {
|
|
7873
|
+
warning = "无法读取已保存的 BOM。" + e.message;
|
|
7874
|
+
}
|
|
7875
|
+
try {
|
|
7876
|
+
return {
|
|
7877
|
+
...await exportText(hardware, source, "bom", signal),
|
|
7878
|
+
saved,
|
|
7879
|
+
warning
|
|
7880
|
+
};
|
|
7881
|
+
} catch (e) {
|
|
7882
|
+
if (!saved || signal.aborted) throw e;
|
|
7883
|
+
return {
|
|
7884
|
+
rows: saved.lines.filter((l) => !l.row.manual).map((l) => l.row.source ?? l.row),
|
|
7885
|
+
saved,
|
|
7886
|
+
warning: "无法重新生成原理图 BOM,当前显示上次保存的版本。" + e.message
|
|
7887
|
+
};
|
|
7888
|
+
}
|
|
7889
|
+
}
|
|
7771
7890
|
if (source.kind !== "pcb") throw new Error("请选择 PCB 文件。");
|
|
7772
7891
|
if (operation === "positions") return exportText(hardware, source, "positions", signal);
|
|
7773
7892
|
if (["pcb", "smt"].includes(operation) && Number.isSafeInteger(quantity) && quantity >= 1 && quantity <= 1e5) return quoteBoard(operation, source.text, quantity, signal);
|
|
@@ -7806,4 +7925,4 @@ function apply(ctx) {
|
|
|
7806
7925
|
}), "manufacturing preview and quotes"));
|
|
7807
7926
|
}
|
|
7808
7927
|
//#endregion
|
|
7809
|
-
export { apply, inject, manufacture, name, searchOffers };
|
|
7928
|
+
export { apply, inject, manufacture, name, saveBom, searchOffers };
|
package/package.json
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@huaqiu/dsh-engineering-workbench",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.30",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "华秋工程工作台 · 设计、评审与制造",
|
|
6
|
+
"license": "MIT",
|
|
6
7
|
"main": "./lib/host.mjs",
|
|
7
8
|
"exports": {
|
|
8
9
|
".": "./lib/host.mjs",
|
|
@@ -24,9 +25,13 @@
|
|
|
24
25
|
]
|
|
25
26
|
}
|
|
26
27
|
},
|
|
28
|
+
"peerDependencies": {
|
|
29
|
+
"react": "^18"
|
|
30
|
+
},
|
|
27
31
|
"files": [
|
|
28
32
|
"lib/client.js",
|
|
29
33
|
"lib/host.mjs",
|
|
34
|
+
"src",
|
|
30
35
|
"cordis.patch.yml",
|
|
31
36
|
"README.md"
|
|
32
37
|
],
|
|
@@ -39,5 +44,15 @@
|
|
|
39
44
|
"react": "^18.3.1",
|
|
40
45
|
"react-dom": "^18.3.1"
|
|
41
46
|
},
|
|
42
|
-
"
|
|
47
|
+
"publishConfig": {
|
|
48
|
+
"access": "public"
|
|
49
|
+
},
|
|
50
|
+
"dependencies": {
|
|
51
|
+
"@huaqiu/dsh-plugin-utils": "0.7.30"
|
|
52
|
+
},
|
|
53
|
+
"scripts": {
|
|
54
|
+
"typecheck": "tsc --noEmit",
|
|
55
|
+
"build": "tsdown",
|
|
56
|
+
"test": "vitest run"
|
|
57
|
+
}
|
|
43
58
|
}
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
import { useEffect, useId, useRef, useState, type FormEvent, type ReactNode } from 'react'
|
|
2
|
+
import {
|
|
3
|
+
descriptionFields, descriptionOf, manufacturerFields, manufacturerOf, modelOf, mpnFields,
|
|
4
|
+
originalMpn, referencesLabel, type BomLine,
|
|
5
|
+
} from './bom-rows'
|
|
6
|
+
import { identity, manufacturingRequest, searchTerm, type Candidate } from './procurement'
|
|
7
|
+
|
|
8
|
+
function Dialog({ title, close, children }: { title: string; close: () => void; children: ReactNode }) {
|
|
9
|
+
const ref = useRef<HTMLDialogElement>(null)
|
|
10
|
+
const id = useId()
|
|
11
|
+
useEffect(() => {
|
|
12
|
+
const dialog = ref.current!
|
|
13
|
+
if (typeof dialog.showModal === 'function') dialog.showModal()
|
|
14
|
+
else dialog.setAttribute('open', '')
|
|
15
|
+
dialog.querySelector<HTMLInputElement>('[data-bom-autofocus]')?.focus()
|
|
16
|
+
return () => {
|
|
17
|
+
if (typeof dialog.close === 'function') dialog.close()
|
|
18
|
+
}
|
|
19
|
+
}, [])
|
|
20
|
+
|
|
21
|
+
return <dialog ref={ref} className="ew-bom-dialog" aria-labelledby={id} onCancel={event => {
|
|
22
|
+
event.preventDefault()
|
|
23
|
+
close()
|
|
24
|
+
}}>
|
|
25
|
+
<div className="ew-bom-dialog-title">
|
|
26
|
+
<h3 id={id}>{title}</h3>
|
|
27
|
+
<button type="button" aria-label="关闭" onClick={close}>×</button>
|
|
28
|
+
</div>
|
|
29
|
+
{children}
|
|
30
|
+
</dialog>
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const valueOf = (form: FormData, key: string) => String(form.get(key) ?? '').trim()
|
|
34
|
+
|
|
35
|
+
function readMaterial(form: FormData, row?: BomLine) {
|
|
36
|
+
const value = valueOf(form, 'value')
|
|
37
|
+
const fields = { ...row?.fields }
|
|
38
|
+
for (const [names, name, current] of [
|
|
39
|
+
[mpnFields, 'mpn', row && originalMpn(row)],
|
|
40
|
+
[manufacturerFields, 'manufacturer', row && manufacturerOf(row)],
|
|
41
|
+
[descriptionFields, 'description', row && descriptionOf(row)],
|
|
42
|
+
] as const) {
|
|
43
|
+
const edited = valueOf(form, name)
|
|
44
|
+
if (edited === (current ?? '')) continue
|
|
45
|
+
for (const key of names) delete fields[key]
|
|
46
|
+
if (edited) fields[names[0]!] = edited
|
|
47
|
+
}
|
|
48
|
+
if (row && (originalMpn({fields}) !== originalMpn(row) || (!originalMpn(row) && value !== row.value))) {
|
|
49
|
+
delete fields['Huaqiu PN']
|
|
50
|
+
delete fields['华秋料号']
|
|
51
|
+
}
|
|
52
|
+
return { value, footprint: valueOf(form, 'footprint'), fields }
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function MaterialFields({ row }: { row?: BomLine }) {
|
|
56
|
+
return <>
|
|
57
|
+
<label>型号 <input name="value" defaultValue={row?.value} maxLength={200} autoFocus data-bom-autofocus /></label>
|
|
58
|
+
<label>原厂型号 <input name="mpn" defaultValue={row && originalMpn(row)} maxLength={200} /></label>
|
|
59
|
+
<label>制造商 <input name="manufacturer" defaultValue={row && manufacturerOf(row)} maxLength={200} /></label>
|
|
60
|
+
<label>封装 <input name="footprint" defaultValue={row?.footprint} maxLength={512} /></label>
|
|
61
|
+
<label className="ew-bom-description">描述 <textarea name="description" defaultValue={row && descriptionOf(row)} rows={2} maxLength={2000} /></label>
|
|
62
|
+
</>
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function usedReferences(rows: readonly BomLine[]) {
|
|
66
|
+
return new Set(rows.flatMap(row => row.references.map(ref => ref.toUpperCase())))
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const validRef = (ref: string) => /^[A-Z0-9][A-Z0-9._-]{0,39}$/.test(ref)
|
|
70
|
+
|
|
71
|
+
export function AddPartForm({ rows, add, cancel }: {
|
|
72
|
+
rows: readonly BomLine[]
|
|
73
|
+
add?: (row: BomLine) => void
|
|
74
|
+
cancel: () => void
|
|
75
|
+
}) {
|
|
76
|
+
const [error, setError] = useState('')
|
|
77
|
+
|
|
78
|
+
function submit(event: FormEvent<HTMLFormElement>) {
|
|
79
|
+
event.preventDefault()
|
|
80
|
+
if (!add) return
|
|
81
|
+
const form = new FormData(event.currentTarget)
|
|
82
|
+
const material = readMaterial(form)
|
|
83
|
+
const quantity = Number(form.get('quantity'))
|
|
84
|
+
if (!modelOf(material) || !Number.isInteger(quantity) || quantity < 1 || quantity > 100000) {
|
|
85
|
+
setError('请填写型号或原厂型号,并输入有效的每套用量。')
|
|
86
|
+
return
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const used = usedReferences(rows)
|
|
90
|
+
let reference = valueOf(form, 'reference').toUpperCase()
|
|
91
|
+
if (!reference) {
|
|
92
|
+
let index = 1
|
|
93
|
+
while (used.has('BOM-' + index)) index++
|
|
94
|
+
reference = 'BOM-' + index
|
|
95
|
+
}
|
|
96
|
+
if (!validRef(reference) || used.has(reference)) {
|
|
97
|
+
setError('请输入未使用的单个位号,例如 R12 或 BOM-1。')
|
|
98
|
+
return
|
|
99
|
+
}
|
|
100
|
+
add({ ...material, manual: true, references: [reference], quantity, dnp: false })
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
return <form className="ew-bom-add" onSubmit={submit} aria-label="新增器件">
|
|
104
|
+
<MaterialFields />
|
|
105
|
+
<label>每套用量 <input name="quantity" type="number" min={1} max={100000} defaultValue={1} required /></label>
|
|
106
|
+
<label>位号 <input name="reference" maxLength={40} placeholder="留空自动编号" /></label>
|
|
107
|
+
{error && <span role="alert">{error}</span>}
|
|
108
|
+
<div className="ew-bom-add-actions">
|
|
109
|
+
<button type="button" onClick={cancel}>取消</button>
|
|
110
|
+
<button type="submit" disabled={!add}>加入 BOM</button>
|
|
111
|
+
</div>
|
|
112
|
+
</form>
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function EditPartDialog({ kind, rows, row, close, apply }: {
|
|
116
|
+
kind: 'references' | 'material'
|
|
117
|
+
rows: readonly BomLine[]
|
|
118
|
+
row: BomLine
|
|
119
|
+
close: () => void
|
|
120
|
+
apply: (next: BomLine) => void
|
|
121
|
+
}) {
|
|
122
|
+
const [error, setError] = useState('')
|
|
123
|
+
const editingRefs = kind === 'references'
|
|
124
|
+
|
|
125
|
+
function submit(event: FormEvent<HTMLFormElement>) {
|
|
126
|
+
event.preventDefault()
|
|
127
|
+
const form = new FormData(event.currentTarget)
|
|
128
|
+
if (!editingRefs) {
|
|
129
|
+
const next = { ...row, ...readMaterial(form, row) }
|
|
130
|
+
if (!modelOf(next)) {
|
|
131
|
+
setError('请填写型号或原厂型号。')
|
|
132
|
+
return
|
|
133
|
+
}
|
|
134
|
+
apply(next)
|
|
135
|
+
return
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const refs = valueOf(form, 'reference').toUpperCase().split(/[,,;;\s]+/).filter(Boolean)
|
|
139
|
+
const used = usedReferences(rows.filter(line => line !== row))
|
|
140
|
+
if (!refs.length || (row.manual && refs.length !== 1) || new Set(refs).size !== refs.length ||
|
|
141
|
+
refs.some(ref => !validRef(ref) || used.has(ref))) {
|
|
142
|
+
setError(row.manual ? '请输入未使用的单个位号。' : '请输入有效且互不重复的位号,用逗号分隔。')
|
|
143
|
+
return
|
|
144
|
+
}
|
|
145
|
+
apply({ ...row, references: refs, quantity: row.manual ? row.quantity : refs.length })
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
return <Dialog title={editingRefs ? '编辑位号' : '编辑需求物料'} close={close}>
|
|
149
|
+
<form className="ew-bom-edit" onSubmit={submit}>
|
|
150
|
+
{editingRefs ? <label>位号
|
|
151
|
+
<input name="reference" defaultValue={referencesLabel(row)} required data-bom-autofocus />
|
|
152
|
+
</label> : <MaterialFields row={row} />}
|
|
153
|
+
{error && <span role="alert">{error}</span>}
|
|
154
|
+
<div className="ew-bom-add-actions">
|
|
155
|
+
<button type="button" onClick={close}>取消</button>
|
|
156
|
+
<button type="submit">应用</button>
|
|
157
|
+
</div>
|
|
158
|
+
</form>
|
|
159
|
+
</Dialog>
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export function SearchPartDialog({ row, candidates, close, pick }: {
|
|
163
|
+
row: BomLine
|
|
164
|
+
candidates: Candidate[]
|
|
165
|
+
close: () => void
|
|
166
|
+
pick: (part: Candidate, results: Candidate[]) => void
|
|
167
|
+
}) {
|
|
168
|
+
const [query, setQuery] = useState(() => searchTerm(row))
|
|
169
|
+
const [results, setResults] = useState(candidates)
|
|
170
|
+
const [message, setMessage] = useState('')
|
|
171
|
+
const [busy, setBusy] = useState(false)
|
|
172
|
+
const request = useRef<AbortController>()
|
|
173
|
+
useEffect(() => () => request.current?.abort(), [])
|
|
174
|
+
|
|
175
|
+
async function search(event: FormEvent<HTMLFormElement>) {
|
|
176
|
+
event.preventDefault()
|
|
177
|
+
const term = query.trim()
|
|
178
|
+
if (!term) return
|
|
179
|
+
request.current?.abort()
|
|
180
|
+
const controller = new AbortController()
|
|
181
|
+
request.current = controller
|
|
182
|
+
setBusy(true)
|
|
183
|
+
setMessage('')
|
|
184
|
+
try {
|
|
185
|
+
const reply = await manufacturingRequest<{ candidates: Candidate[] }>('parts', { query: term }, controller.signal)
|
|
186
|
+
if (!controller.signal.aborted) {
|
|
187
|
+
setResults(reply.candidates)
|
|
188
|
+
setMessage(reply.candidates.length ? '' : '没有找到匹配物料。')
|
|
189
|
+
}
|
|
190
|
+
} catch (error) {
|
|
191
|
+
if (!controller.signal.aborted) {
|
|
192
|
+
setResults([])
|
|
193
|
+
setMessage(error instanceof Error ? error.message : String(error))
|
|
194
|
+
}
|
|
195
|
+
} finally {
|
|
196
|
+
if (!controller.signal.aborted) setBusy(false)
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
return <Dialog title={'搜索匹配物料 · ' + referencesLabel(row)} close={close}>
|
|
201
|
+
<form className="ew-bom-part-search" onSubmit={search}>
|
|
202
|
+
<input type="search" aria-label="搜索型号或华秋料号" placeholder="输入型号或华秋料号"
|
|
203
|
+
maxLength={200} value={query} onChange={event => setQuery(event.target.value)} data-bom-autofocus />
|
|
204
|
+
<button type="submit" disabled={!query.trim() || busy}>搜索</button>
|
|
205
|
+
</form>
|
|
206
|
+
{busy ? <p role="status">正在搜索…</p> : message && <p role="status">{message}</p>}
|
|
207
|
+
{!!results.length && <ul className="ew-bom-search-results">
|
|
208
|
+
{results.map((part, index) => <li key={identity(part) + ':' + index}>
|
|
209
|
+
<div className="ew-bom-result-text">
|
|
210
|
+
<strong title={part.mpn}>{part.mpn}</strong>
|
|
211
|
+
<small title={[part.manufacturer, part.package, part.huaqiuPn].filter(Boolean).join(' · ')}>
|
|
212
|
+
{[part.manufacturer, part.package, part.huaqiuPn].filter(Boolean).join(' · ')}
|
|
213
|
+
</small>
|
|
214
|
+
{part.description && <small title={part.description}>{part.description}</small>}
|
|
215
|
+
</div>
|
|
216
|
+
<button type="button" disabled={busy} aria-label={'设为候选 ' + part.mpn} onClick={() => pick(part, results)}>设为候选</button>
|
|
217
|
+
</li>)}
|
|
218
|
+
</ul>}
|
|
219
|
+
</Dialog>
|
|
220
|
+
}
|
package/src/BomGrid.tsx
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { useState, type ReactNode } from 'react'
|
|
2
|
+
import { AddPartForm, EditPartDialog, SearchPartDialog } from './BomDialogs'
|
|
3
|
+
import { basket, bestOffer, type Candidate, type MatchTable } from './procurement'
|
|
4
|
+
import { boardReferences, demandFor, descriptionOf, manufacturerOf, modelOf, originalMpn, referencesLabel, rowKey, type BomLine } from './bom-rows'
|
|
5
|
+
|
|
6
|
+
const groups = [
|
|
7
|
+
['selected', '已选型'],
|
|
8
|
+
['pending', '待匹配'],
|
|
9
|
+
['dnp', '不装配'],
|
|
10
|
+
] as const
|
|
11
|
+
const filters = [['all', '全部器件'], ...groups] as const
|
|
12
|
+
const columns = ['位号', '需求物料', '匹配物料', '用量', '库存 / 单价', '选型结果']
|
|
13
|
+
const number = new Intl.NumberFormat('zh-CN')
|
|
14
|
+
const money = new Intl.NumberFormat('zh-CN', {
|
|
15
|
+
style: 'currency', currency: 'CNY', minimumFractionDigits: 2, maximumFractionDigits: 6,
|
|
16
|
+
})
|
|
17
|
+
|
|
18
|
+
interface Props {
|
|
19
|
+
rows: readonly BomLine[]
|
|
20
|
+
matches: MatchTable
|
|
21
|
+
reference: string
|
|
22
|
+
quantity: number
|
|
23
|
+
busy: boolean
|
|
24
|
+
editable: boolean
|
|
25
|
+
summary: ReturnType<typeof basket>
|
|
26
|
+
select: (ref: string) => void
|
|
27
|
+
choose: (key: string, part: Candidate) => void
|
|
28
|
+
nominate: (key: string, part: Candidate, results: Candidate[]) => void
|
|
29
|
+
edit: (row: BomLine, next: BomLine) => void
|
|
30
|
+
add?: (row: BomLine) => void
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function Details({ fields }: { fields: readonly (readonly [string, ReactNode])[] }) {
|
|
34
|
+
return <dl className="ew-bom-details">
|
|
35
|
+
{fields.map(([label, value]) => <div key={label}>
|
|
36
|
+
<dt>{label}</dt>
|
|
37
|
+
<dd title={typeof value === 'string' ? value : undefined}>
|
|
38
|
+
{value === undefined || value === '' ? <span className="ew-bom-empty">—</span> : value}
|
|
39
|
+
</dd>
|
|
40
|
+
</div>)}
|
|
41
|
+
</dl>
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function BomGrid({ rows, matches, reference, quantity, busy, editable, summary, select, choose, nominate, edit, add }: Props) {
|
|
45
|
+
const [filter, setFilter] = useState<(typeof filters)[number][0]>('all')
|
|
46
|
+
const [query, setQuery] = useState('')
|
|
47
|
+
const [adding, setAdding] = useState(false)
|
|
48
|
+
const [dialog, setDialog] = useState<{row: BomLine; kind: 'references' | 'material' | 'search'}>()
|
|
49
|
+
const close = () => setDialog(undefined)
|
|
50
|
+
const term = query.trim().toLowerCase()
|
|
51
|
+
const entries = rows.map(row => {
|
|
52
|
+
const match = matches[rowKey(row)]
|
|
53
|
+
const group: (typeof groups)[number][0] = row.dnp ? 'dnp' : match?.selected ? 'selected' : 'pending'
|
|
54
|
+
return { row, match, group }
|
|
55
|
+
})
|
|
56
|
+
const counts = { all: rows.length, selected: 0, pending: 0, dnp: 0 }
|
|
57
|
+
for (const { group } of entries) counts[group]++
|
|
58
|
+
const visible = entries.filter(({ row, match, group }) =>
|
|
59
|
+
(filter === 'all' || group === filter) && (!term || [
|
|
60
|
+
modelOf(row), referencesLabel(row), row.footprint, originalMpn(row), manufacturerOf(row), descriptionOf(row),
|
|
61
|
+
...(match?.candidates.flatMap(part => [
|
|
62
|
+
part.mpn, part.huaqiuPn, part.manufacturer, part.package, part.description, ...part.offers.map(offer => offer.sku),
|
|
63
|
+
]) ?? []),
|
|
64
|
+
].some(value => value?.toLowerCase().includes(term))),
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
return <div className="ew-bom-grid">
|
|
68
|
+
<div className="ew-bom-bar">
|
|
69
|
+
<div className="ew-bom-filters" role="group" aria-label="BOM 器件分类">
|
|
70
|
+
{filters.map(([id, label]) => <button type="button" key={id} aria-pressed={filter === id} onClick={() => setFilter(id)}>
|
|
71
|
+
{label} <span>{counts[id]}</span>
|
|
72
|
+
</button>)}
|
|
73
|
+
</div>
|
|
74
|
+
<div className="ew-bom-search">
|
|
75
|
+
<input type="search" value={query} aria-label="筛选 BOM" placeholder="位号、型号、封装、描述、料号" onChange={e => setQuery(e.target.value)} />
|
|
76
|
+
<button type="button" disabled={!add} aria-expanded={adding} onClick={() => setAdding(open => !open)}>新增器件</button>
|
|
77
|
+
</div>
|
|
78
|
+
</div>
|
|
79
|
+
{adding && <AddPartForm rows={rows} add={add && (row => {
|
|
80
|
+
add(row)
|
|
81
|
+
setAdding(false)
|
|
82
|
+
setFilter('all')
|
|
83
|
+
setQuery('')
|
|
84
|
+
})} cancel={() => setAdding(false)} />}
|
|
85
|
+
<div className="ew-bom-scroll" tabIndex={0} aria-label="物料清单,可横向滚动">
|
|
86
|
+
<table className="ew-bom-table" aria-label="BOM 明细">
|
|
87
|
+
<colgroup><col className="ew-bom-refs" /><col className="ew-bom-material" /><col className="ew-bom-match" />
|
|
88
|
+
<col className="ew-bom-usage" /><col className="ew-bom-offer" /><col className="ew-bom-result" /></colgroup>
|
|
89
|
+
<thead><tr>{columns.map(column => <th key={column} scope="col">{column}</th>)}</tr></thead>
|
|
90
|
+
{groups.map(([group, label]) => {
|
|
91
|
+
const section = visible.filter(entry => entry.group === group)
|
|
92
|
+
if (!section.length) return null
|
|
93
|
+
return <tbody key={group}>
|
|
94
|
+
{filter === 'all' && <tr className="ew-bom-section"><th scope="rowgroup" colSpan={columns.length}>{label}</th></tr>}
|
|
95
|
+
{section.map(({ row, match }) => {
|
|
96
|
+
const key = rowKey(row)
|
|
97
|
+
const refs = referencesLabel(row)
|
|
98
|
+
const chosen = row.dnp ? undefined : match?.selected
|
|
99
|
+
const demand = demandFor(row, quantity)
|
|
100
|
+
const options = row.dnp ? [] : (match?.candidates ?? []).map(part => ({ part, price: bestOffer(part, demand) }))
|
|
101
|
+
const preview = chosen ? undefined : options.find(option => option.part === match?.pending)
|
|
102
|
+
?? options.find(option => option.price) ?? options[0]
|
|
103
|
+
const candidate = chosen ?? preview?.part
|
|
104
|
+
const price = summary.priceFor(chosen) ?? preview?.price
|
|
105
|
+
const status = row.dnp ? '不装配' : match?.error ? '查询失败' : chosen ? (price ? '已匹配' : '未报价')
|
|
106
|
+
: candidate ? '待确认' : match ? '无匹配' : busy ? '匹配中' : '待查询'
|
|
107
|
+
const selected = !row.manual && boardReferences(row).some(ref => ref.toUpperCase() === reference.toUpperCase())
|
|
108
|
+
const model = modelOf(row)
|
|
109
|
+
const mpn = originalMpn(row)
|
|
110
|
+
|
|
111
|
+
return <tr key={key} data-selected={selected} data-bom-row>
|
|
112
|
+
<td>
|
|
113
|
+
<div className="ew-bom-cell-head">
|
|
114
|
+
{row.manual ? <strong className="ew-bom-clip" title={refs}>{refs}</strong> :
|
|
115
|
+
<button type="button" className="ew-bom-ref ew-bom-clip" title={refs}
|
|
116
|
+
onClick={() => select(boardReferences(row)[0] ?? '')}>{refs}</button>}
|
|
117
|
+
<button type="button" className="ew-bom-inline" disabled={!editable} title="编辑位号"
|
|
118
|
+
aria-label={'编辑位号 ' + refs} onClick={() => setDialog({row,kind:'references'})}>✎</button>
|
|
119
|
+
</div>
|
|
120
|
+
{row.manual && <small>手动新增</small>}
|
|
121
|
+
</td>
|
|
122
|
+
<td>
|
|
123
|
+
<div className="ew-bom-cell-head">
|
|
124
|
+
<Details fields={[[ '型号', model ]]} />
|
|
125
|
+
<button type="button" className="ew-bom-inline" disabled={!editable} title="编辑需求物料"
|
|
126
|
+
aria-label={'编辑需求物料 ' + refs} onClick={() => setDialog({row,kind:'material'})}>✎</button>
|
|
127
|
+
</div>
|
|
128
|
+
<Details fields={[
|
|
129
|
+
...(mpn && mpn !== model ? [['原厂型号', mpn]] as const : []),
|
|
130
|
+
['制造商', manufacturerOf(row)], ['封装', row.footprint], ['描述', descriptionOf(row)],
|
|
131
|
+
]} />
|
|
132
|
+
</td>
|
|
133
|
+
<td>
|
|
134
|
+
<div className="ew-bom-cell-head">
|
|
135
|
+
{candidate ? <Details fields={[[ '型号', candidate.mpn ]]} /> : <span className="ew-bom-empty">—</span>}
|
|
136
|
+
{!row.dnp && <button type="button" className="ew-bom-inline" disabled={!editable}
|
|
137
|
+
aria-label={'搜索匹配物料 ' + refs} onClick={() => setDialog({row,kind:'search'})}>搜索</button>}
|
|
138
|
+
</div>
|
|
139
|
+
{candidate && <Details fields={[
|
|
140
|
+
['华秋料号', candidate.huaqiuPn], ['制造商', candidate.manufacturer], ['封装', candidate.package],
|
|
141
|
+
['描述', candidate.description],
|
|
142
|
+
]} />}
|
|
143
|
+
</td>
|
|
144
|
+
<td><Details fields={[
|
|
145
|
+
['每套', number.format(row.quantity)], ['套数', number.format(quantity)], ['总量', <strong>{number.format(demand)}</strong>],
|
|
146
|
+
]} /></td>
|
|
147
|
+
<td>{price ? <Details fields={[
|
|
148
|
+
['库存', price.offer.stock === undefined ? undefined : number.format(price.offer.stock)],
|
|
149
|
+
['起订量', number.format(price.offer.moq || 1)], ['单价', money.format(price.unit)],
|
|
150
|
+
]} /> : <span className="ew-bom-empty">—</span>}</td>
|
|
151
|
+
<td>
|
|
152
|
+
<span className="ew-bom-status" title={match?.error || (chosen && !price ? '库存不足或缺少人民币阶梯价' : undefined)}
|
|
153
|
+
data-state={status}>{status}</span>
|
|
154
|
+
{status === '待确认' && candidate && <button type="button" className="ew-bom-inline ew-bom-confirm"
|
|
155
|
+
aria-label={'确认采购型号 ' + refs} disabled={!editable} onClick={() => choose(key,candidate)}>确认</button>}
|
|
156
|
+
{chosen && price && <Details fields={[
|
|
157
|
+
['合购数量', number.format(price.count)], ['合购金额', money.format(price.cost)],
|
|
158
|
+
]} />}
|
|
159
|
+
</td>
|
|
160
|
+
</tr>
|
|
161
|
+
})}
|
|
162
|
+
</tbody>
|
|
163
|
+
})}
|
|
164
|
+
</table>
|
|
165
|
+
{rows.length > 0 && !visible.length && <p role="status">没有符合当前筛选条件的器件。</p>}
|
|
166
|
+
</div>
|
|
167
|
+
{dialog?.kind === 'search' && <SearchPartDialog row={dialog.row} candidates={matches[rowKey(dialog.row)]?.candidates ?? []}
|
|
168
|
+
close={close} pick={(part,results) => {nominate(rowKey(dialog.row),part,results); close()}} />}
|
|
169
|
+
{dialog && dialog.kind !== 'search' && <EditPartDialog kind={dialog.kind} row={dialog.row} rows={rows}
|
|
170
|
+
close={close} apply={next => {edit(dialog.row,next); close()}} />}
|
|
171
|
+
</div>
|
|
172
|
+
}
|