dsh-ap-three-way 0.1.0-alpha.8 → 0.1.0
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/CHANGELOG.md +25 -1
- package/README-zh.md +80 -11
- package/THIRD-PARTY-NOTICES +0 -1
- package/TROUBLESHOOTING.md +29 -29
- package/docs/assets/dsh-ap-three-way-capability2.png +0 -0
- package/docs/assets/quickstart.png +0 -0
- package/lib/core/ap.d.ts +22 -2
- package/lib/core/ap.js +67 -16
- package/lib/core/safe-path.d.ts +12 -0
- package/lib/core/safe-path.js +31 -0
- package/lib/core/tolerance.js +2 -2
- package/lib/core/xlsx-lite.d.ts +30 -0
- package/lib/core/xlsx-lite.js +245 -0
- package/lib/plugin/tools.js +24 -10
- package/package.json +29 -7
- package/samples/quickstart/expected/result.json +74 -0
- package/samples/quickstart/input/grn.csv +5 -0
- package/samples/quickstart/input/invoice-sample.xml +14 -0
- package/samples/quickstart/input/invoices-duplicate.csv +4 -0
- package/samples/quickstart/input/invoices.csv +5 -0
- package/samples/quickstart/input/po.csv +5 -0
- package/samples/quickstart/run.mjs +135 -0
- package/screenshots.json +17 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,6 +1,30 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
-
## [0.1.0
|
|
3
|
+
## [0.1.0] — 2026-11-03
|
|
4
|
+
|
|
5
|
+
### Stable
|
|
6
|
+
|
|
7
|
+
- First non-alpha release: tool names and the CLI surface are covered by a
|
|
8
|
+
compatibility promise (breaking changes require a minor bump).
|
|
9
|
+
- Ships a quickstart sample, a one-line prompt, a permission block and real captures.
|
|
10
|
+
|
|
11
|
+
## [0.1.0] — 2026-11-01
|
|
12
|
+
|
|
13
|
+
### Packaging
|
|
14
|
+
|
|
15
|
+
- Package Standard v1: shipped `samples/quickstart/` (synthetic invoice/PO/GRN CSV + invoice XML + real-output gold `expected/result.json` + runner), `dsh.demo` metadata, README-zh eight blocks (including the demo prompt and permission lines), `docs/assets/quickstart.png` rendered from a real run, and a `PS1-QS01` acceptance row. `npm pack --dry-run` contains `samples/quickstart/*`; `node --test test/*.test.mjs` 26/26.
|
|
16
|
+
- The three most common errors now read `<what happened>(E_XXX)|下一步:<action>`; `TROUBLESHOOTING.md` lists the three cases with symptom/cause/action.
|
|
17
|
+
|
|
18
|
+
### Security / Fixes
|
|
19
|
+
|
|
20
|
+
- Path-traversal guard, content-hashed invoice ids, header validation for PO/GRN, idempotent import.
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
### Added
|
|
24
|
+
|
|
25
|
+
- `ap.duplicate_check`: duplicate invoice-line detection (same supplier, PO line, quantity and amount) before matching; supplier names are compared case- and space-insensitively. Verified by `node --test test/*.test.mjs` (11/11).
|
|
26
|
+
|
|
27
|
+
## [Unreleased]
|
|
4
28
|
|
|
5
29
|
### Added
|
|
6
30
|
|
package/README-zh.md
CHANGED
|
@@ -37,6 +37,76 @@ dsh plugin --profile <profile> add dsh-ap-three-way
|
|
|
37
37
|
|
|
38
38
|
*本地真实测试运行;不调用模型或网络。*
|
|
39
39
|
|
|
40
|
+
## 一句话
|
|
41
|
+
|
|
42
|
+
把发票、采购单与收货单逐行比对,列出可过账行和全部例外。
|
|
43
|
+
|
|
44
|
+
## 适合 / 不适合
|
|
45
|
+
|
|
46
|
+
- **适合**:几十到几百行的发票、采购单(PO)、收货单(GRN)CSV;需要按容差给出「可过账 / 例外」清单并留底稿的应付对账。
|
|
47
|
+
- **不适合**:需要自动过账、修改供应商主数据或替代审批的场景;本包只做本地匹配,不改任何单据。
|
|
48
|
+
|
|
49
|
+
## 输入
|
|
50
|
+
|
|
51
|
+
- 发票 CSV:UTF-8,表头 `supplier,invoice_no,po_no,line_no,qty,unit_price,amount`(`invoice_no` 可省略)。
|
|
52
|
+
- 采购单 CSV:`po_no,line_no,qty,unit_price,amount`;收货单 CSV:`po_no,line_no,qty`。
|
|
53
|
+
- 发票 XML:根节点 `<Invoice>`,含 `Seller/Name` 与 `Items/Item`(`Quantity` / `UnitPrice` / `Amount`)。
|
|
54
|
+
- 金额最多两位小数;建议单个文件 ≤5 MB。自带样例在 `samples/quickstart/input/`(合成数据,远小于 500 KB)。
|
|
55
|
+
|
|
56
|
+
## 输出
|
|
57
|
+
|
|
58
|
+
- 终端摘要:可过账几行、例外几行,默认价格容差 1%。
|
|
59
|
+
- 底稿:`$DSH_HOME/storages/dsh-ap-three-way/exports/ap-<时间戳>.xlsx`,工作表 `Matches` / `Exceptions`。
|
|
60
|
+
- 原文件不会被修改。
|
|
61
|
+
|
|
62
|
+
## 示例
|
|
63
|
+
|
|
64
|
+
直接复制这句话:
|
|
65
|
+
|
|
66
|
+
> 帮我用自带样例做一次发票、采购单、收货单三单匹配,把能过的和例外分别列出来。
|
|
67
|
+
|
|
68
|
+
也可以自己跑(真实运行,截图即来自这条命令):
|
|
69
|
+
|
|
70
|
+
```sh
|
|
71
|
+
node samples/quickstart/run.mjs
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+

|
|
75
|
+
|
|
76
|
+
*合成样例 → 金标 `samples/quickstart/expected/result.json`;命令与哈希见 `screenshots.json`。*
|
|
77
|
+
|
|
78
|
+
## 权限
|
|
79
|
+
|
|
80
|
+
- 读:你指定的发票 / 采购单 / 收货单 CSV 与发票 XML(由会话读取后作为参数传入);不读其他目录
|
|
81
|
+
- 写:`$DSH_HOME/storages/dsh-ap-three-way`(匹配状态与 `exports/*.xlsx`);不改原文件
|
|
82
|
+
- 联网:否(源码中没有 HTTP / DNS / WebSocket 调用)
|
|
83
|
+
- 外部系统:无(不连接 ERP / 供应商系统,不上传数据)
|
|
84
|
+
|
|
85
|
+
写文件的工具标 **R1(本地写)**,只读工具标 **R0**;逐项见下方工具表。
|
|
86
|
+
|
|
87
|
+
## FAQ
|
|
88
|
+
|
|
89
|
+
### 装不上怎么办?
|
|
90
|
+
|
|
91
|
+
确认 DSH `>=0.2.1-rc.3 <0.4.0`、Node `>=24.9 <25`,并用全新的 `DSH_HOME` 重试;完整步骤见 `TROUBLESHOOTING.md`。
|
|
92
|
+
|
|
93
|
+
### 价格在 1% 以内,为什么还是例外?
|
|
94
|
+
|
|
95
|
+
默认容差只放宽「单价」,数量超过收货单(`qty_over_grn`)仍然算例外;需要放宽时可显式传 `price_bps` / `qty_bps` 调容差,并保留策略参数。
|
|
96
|
+
|
|
97
|
+
### 能处理我的真实发票吗?
|
|
98
|
+
|
|
99
|
+
可以本地运行,但本包是 alpha、只用公开/合成数据验证,不构成审计或付款结论;使用真实数据前请脱敏,并保留复核人。
|
|
100
|
+
|
|
101
|
+
### 会联网或上传数据吗?
|
|
102
|
+
|
|
103
|
+
不会。工具、样例和导出都在本机完成。
|
|
104
|
+
|
|
105
|
+
## 版本
|
|
106
|
+
|
|
107
|
+
- 当前版本:`0.1.0`(与 `package.json` 一致)
|
|
108
|
+
- 测试:`node --test test/*.test.mjs` 全绿(26 个用例,0 失败)
|
|
109
|
+
|
|
40
110
|
## 安装
|
|
41
111
|
|
|
42
112
|
安装并验证:
|
|
@@ -76,8 +146,10 @@ dsh plugin --profile <profile> remove dsh-ap-three-way
|
|
|
76
146
|
|---|---|---|
|
|
77
147
|
| `ap.import` | 导入发票、PO 和 GRN 行 | R1 local write |
|
|
78
148
|
| `ap.import_invoice_xml` | 导入发票 XML 测试样例 | R1 local write |
|
|
79
|
-
| `ap.match` | 执行三单匹配,默认价格容差 1
|
|
149
|
+
| `ap.match` | 执行三单匹配,默认价格容差 1%,并校验数量(写入匹配与例外) | R1 local write |
|
|
80
150
|
| `ap.export` | 导出 Matches/Exceptions xlsx | R1 local write |
|
|
151
|
+
| `ap.tolerance_match` | 按可配置容差(bps)重算三单匹配,只读 | R0 |
|
|
152
|
+
| `ap.duplicate_check` | 检测重复发票行,只读 | R0 |
|
|
81
153
|
|
|
82
154
|
## 快速开始
|
|
83
155
|
|
|
@@ -86,21 +158,18 @@ dsh plugin --profile <profile> add dsh-ap-three-way
|
|
|
86
158
|
dsh --profile <profile> --dump-config | grep dsh-ap-three-way
|
|
87
159
|
```
|
|
88
160
|
|
|
89
|
-
##
|
|
90
|
-
|
|
91
|
-
### fixture 支撑的示例
|
|
92
|
-
|
|
93
|
-
输入: [`fixtures/public/mit/invoice-github-sample.xml`](https://github.com/PerryLink/dsh-ap-three-way/blob/main/fixtures/public/mit/invoice-github-sample.xml)
|
|
94
|
-
|
|
95
|
-
命令: `pnpm test`
|
|
161
|
+
## 验收示例(fixture + 快速开始)
|
|
96
162
|
|
|
97
|
-
|
|
163
|
+
- 快速开始:`samples/quickstart/`(合成数据)→ `node samples/quickstart/run.mjs`,金标 `samples/quickstart/expected/result.json`。
|
|
164
|
+
- fixture:`fixtures/public/mit/invoice-github-sample.xml`(公开 MIT 样本)。
|
|
165
|
+
- 验收:`node scripts/acceptance.mjs`,明细见 `ACCEPTANCE.csv`。
|
|
98
166
|
|
|
99
167
|
| req_id | metric | threshold | actual | pass | source | counted |
|
|
100
168
|
|---|---|---|---|---|---|---|
|
|
101
169
|
| SKU-05-A01 | 发票行解析 | 20/20 | 20 | true | public/synthetic | false |
|
|
170
|
+
| PS1-QS01 | quickstart 样例与金标一致 | 1/1 | 1 | true | synthetic/quickstart | true |
|
|
102
171
|
|
|
103
|
-
|
|
172
|
+
*SKU 行是公开/合成 fixture 检查;PS1-QS01 是随包样例的本地复现,均非客户运行。*
|
|
104
173
|
|
|
105
174
|
## 边界
|
|
106
175
|
|
|
@@ -111,7 +180,7 @@ dsh --profile <profile> --dump-config | grep dsh-ap-three-way
|
|
|
111
180
|
|
|
112
181
|
## 公开样例
|
|
113
182
|
|
|
114
|
-
公开/合成 fixture 在 `fixtures
|
|
183
|
+
公开/合成 fixture 在 `fixtures/`;自带快速开始样例在 `samples/quickstart/`(随包发布,≤500 KB)。`ACCEPTANCE.csv` 中 SKU 行 `counted=false`,PS1-QS01 为样例本地复现 `counted=true`。
|
|
115
184
|
|
|
116
185
|
## 开发
|
|
117
186
|
|
package/THIRD-PARTY-NOTICES
CHANGED
package/TROUBLESHOOTING.md
CHANGED
|
@@ -1,45 +1,45 @@
|
|
|
1
|
-
#
|
|
1
|
+
# 排错指南 — dsh-ap-three-way
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
> 错误信息统一为 `<一句人话>(E_XXX)|下一步:<动作>`。完整报错与堆栈只写日志,不打印内部路径。
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
- Run `dsh --version` and `node --version`, then retry with a fresh `DSH_HOME`:
|
|
5
|
+
## 1. 金额列读不懂
|
|
7
6
|
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
dsh --profile <profile> --dump-config | grep dsh-ap-three-way
|
|
12
|
-
```
|
|
13
|
-
|
|
14
|
-
## The tool cannot find an input
|
|
7
|
+
- **症状**:导入后提示「金额“abc”读不懂(E_AP_CSV_INVALID)|下一步:把金额改成 1234.56 这样的纯数字,最多两位小数」。
|
|
8
|
+
- **原因**:`unit_price` / `amount` 列出现空值、字母、三位以上小数,或把负数写成了括号。
|
|
9
|
+
- **动作**:把该列改成 `1234.56` 这样的纯数字后重跑。
|
|
15
10
|
|
|
16
|
-
|
|
17
|
-
- The public samples under `fixtures/` are repository-only; they are not shipped in the npm tarball. Download them from the GitHub repository if needed.
|
|
18
|
-
- Supported material: invoice/PO/GRN CSV or XML rows.
|
|
11
|
+
## 2. CSV 缺少必需列
|
|
19
12
|
|
|
20
|
-
|
|
13
|
+
- **症状**:导入后提示「CSV 缺少 supplier 列(E_AP_CSV_INVALID)|下一步:按 README 的列名补齐第一行表头后重跑」。
|
|
14
|
+
- **原因**:发票 / PO / GRN 三个 CSV 的表头与文档不一致,或有中文列名、空格拼写差异。
|
|
15
|
+
- **动作**:按 README 的表头补齐:发票 `supplier,invoice_no,po_no,line_no,qty,unit_price,amount`,PO `po_no,line_no,qty,unit_price,amount`,GRN `po_no,line_no,qty`。
|
|
21
16
|
|
|
22
|
-
|
|
23
|
-
- Remove a UTF-8 BOM if the first header is reported as unknown.
|
|
24
|
-
- Check that invoice, PO and GRN rows share the keys the tool expects; the default price tolerance is 1%.
|
|
17
|
+
## 3. 容差参数超出范围
|
|
25
18
|
|
|
26
|
-
|
|
19
|
+
- **症状**:提示「容差参数 price_bps 超出范围(E_AP_POLICY)|下一步:把 price_bps 设为 0–10000 的整数」。
|
|
20
|
+
- **原因**:`price_bps` / `qty_bps` / `amount_bps` 传了小数、负数或大于 10000 的值(10000 bps = 100%)。
|
|
21
|
+
- **动作**:改成 0–10000 的整数后重跑;例如 1% = `100`,12% = `1200`。
|
|
27
22
|
|
|
28
|
-
|
|
29
|
-
- For tests, point `DSH_HOME` at a temporary directory; do not write into a real profile.
|
|
23
|
+
## 安装或激活失败
|
|
30
24
|
|
|
31
|
-
|
|
25
|
+
- DSH 需满足 `>=0.2.1-rc.3 <0.4.0`,Node 需满足 `>=24.9 <25`。
|
|
26
|
+
- 用临时 `DSH_HOME` 排除旧配置干扰:
|
|
32
27
|
|
|
33
|
-
|
|
34
|
-
|
|
28
|
+
```sh
|
|
29
|
+
export DSH_HOME="$(mktemp -d)"
|
|
30
|
+
dsh plugin --profile <profile> add dsh-ap-three-way
|
|
31
|
+
dsh --profile <profile> --dump-config | grep dsh-ap-three-way
|
|
32
|
+
```
|
|
35
33
|
|
|
36
|
-
##
|
|
34
|
+
## 自己复现
|
|
37
35
|
|
|
38
36
|
```sh
|
|
39
|
-
pnpm
|
|
40
|
-
|
|
37
|
+
pnpm build
|
|
38
|
+
node samples/quickstart/run.mjs # 合成样例,应输出 quickstart ok
|
|
39
|
+
node --test test/*.test.mjs # 全绿
|
|
41
40
|
```
|
|
42
41
|
|
|
43
|
-
##
|
|
42
|
+
## 报告问题
|
|
44
43
|
|
|
45
|
-
|
|
44
|
+
请附版本号、最小合成输入和完整工具调用;**不要上传客户数据**。
|
|
45
|
+
<https://github.com/PerryLink/dsh-ap-three-way/issues>
|
|
Binary file
|
|
Binary file
|
package/lib/core/ap.d.ts
CHANGED
|
@@ -31,12 +31,26 @@ export interface ApMatch {
|
|
|
31
31
|
reason: string;
|
|
32
32
|
created_at: string;
|
|
33
33
|
}
|
|
34
|
-
export type ApErrorCode = 'E_AP_CSV_INVALID' | 'E_AP_MATCH_FAILED' | 'E_AP_EXPORT_FAILED';
|
|
34
|
+
export type ApErrorCode = 'E_AP_CSV_INVALID' | 'E_AP_MATCH_FAILED' | 'E_AP_EXPORT_FAILED' | 'E_AP_PATH_INVALID' | 'E_AP_PATH_NOT_ALLOWED';
|
|
35
35
|
export declare class ApError extends Error {
|
|
36
36
|
readonly code: ApErrorCode;
|
|
37
|
-
constructor(code: ApErrorCode, message: string);
|
|
37
|
+
constructor(code: ApErrorCode, message: string, next?: string);
|
|
38
38
|
}
|
|
39
39
|
export declare function cents(raw: string): number;
|
|
40
|
+
/**
|
|
41
|
+
* Stable invoice-line primary key: `inv-` + the first 16 hex of
|
|
42
|
+
* sha256(supplier|invoice_no|line_no|qty|unit_price|amount).
|
|
43
|
+
* Re-importing the same file yields the same ids, so rows are skipped instead of
|
|
44
|
+
* silently overwritten; different lines/amounts no longer collide across imports.
|
|
45
|
+
*/
|
|
46
|
+
export declare function invoiceLineId(line: {
|
|
47
|
+
supplier: string;
|
|
48
|
+
invoice_no: string;
|
|
49
|
+
line_no: string;
|
|
50
|
+
qty: number;
|
|
51
|
+
unit_price_cents: number;
|
|
52
|
+
amount_cents: number;
|
|
53
|
+
}): string;
|
|
40
54
|
export declare function parseInvoices(text: string, sha: string): InvoiceLine[];
|
|
41
55
|
export declare function parsePo(text: string): PoLine[];
|
|
42
56
|
export declare function parseGrn(text: string): GrnLine[];
|
|
@@ -47,3 +61,9 @@ export declare function matchLine(inv: InvoiceLine, po: PoLine | undefined, grn:
|
|
|
47
61
|
price_delta_cents: number;
|
|
48
62
|
};
|
|
49
63
|
export declare function parseInvoiceXml(text: string, poNo?: string): InvoiceLine[];
|
|
64
|
+
export interface DuplicateInvoiceLine {
|
|
65
|
+
line: InvoiceLine;
|
|
66
|
+
occurrences: number;
|
|
67
|
+
}
|
|
68
|
+
/** Duplicate detection over imported invoice lines: the same supplier, PO line, quantity and amount twice. */
|
|
69
|
+
export declare function duplicateInvoiceLines(lines: InvoiceLine[]): DuplicateInvoiceLine[];
|
package/lib/core/ap.js
CHANGED
|
@@ -1,15 +1,48 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
1
2
|
export class ApError extends Error {
|
|
2
3
|
code;
|
|
3
|
-
constructor(code, message) { super(`${code}:
|
|
4
|
+
constructor(code, message, next) { super(next ? `${message}(${code})|下一步:${next}` : `${message}(${code})`); this.name = 'ApError'; this.code = code; }
|
|
4
5
|
}
|
|
5
6
|
export function cents(raw) { const v = raw.trim().replace(/[¥¥,\s]/g, ''); const m = /^(-?)(\d+)(?:\.(\d{1,2}))?$/.exec(v); if (!m)
|
|
6
|
-
throw new ApError('E_AP_CSV_INVALID',
|
|
7
|
+
throw new ApError('E_AP_CSV_INVALID', `金额“${raw}”读不懂`, '把金额改成 1234.56 这样的纯数字,最多两位小数'); return (m[1] === '-' ? -1 : 1) * (Number(m[2]) * 100 + Number((m[3] ?? '').padEnd(2, '0'))); }
|
|
8
|
+
/**
|
|
9
|
+
* Stable invoice-line primary key: `inv-` + the first 16 hex of
|
|
10
|
+
* sha256(supplier|invoice_no|line_no|qty|unit_price|amount).
|
|
11
|
+
* Re-importing the same file yields the same ids, so rows are skipped instead of
|
|
12
|
+
* silently overwritten; different lines/amounts no longer collide across imports.
|
|
13
|
+
*/
|
|
14
|
+
export function invoiceLineId(line) {
|
|
15
|
+
const digest = createHash('sha256').update([line.supplier, line.invoice_no, line.line_no, line.qty, line.unit_price_cents, line.amount_cents].join('|')).digest('hex');
|
|
16
|
+
return `inv-${digest.slice(0, 16)}`;
|
|
17
|
+
}
|
|
7
18
|
function rows(text) { const l = text.trim().split(/\r?\n/).filter(Boolean); if (l.length < 2)
|
|
8
19
|
throw new ApError('E_AP_CSV_INVALID', 'CSV needs header+rows'); return l.map(x => x.split(',').map(y => y.trim())); }
|
|
9
|
-
export function parseInvoices(text, sha) {
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
20
|
+
export function parseInvoices(text, sha) {
|
|
21
|
+
const r = rows(text);
|
|
22
|
+
const h = r[0].map(x => x.toLowerCase());
|
|
23
|
+
const ix = (n) => { const i = h.indexOf(n); if (i < 0)
|
|
24
|
+
throw new ApError('E_AP_CSV_INVALID', `CSV 缺少 ${n} 列`, '按 README 的列名补齐第一行表头后重跑'); return i; };
|
|
25
|
+
const si = ix('supplier'), pi = ix('po_no'), li = ix('line_no'), qi = ix('qty'), pi2 = ix('unit_price'), ai = ix('amount');
|
|
26
|
+
// invoice_no is optional; when the CSV has no such column the PO number identifies the document.
|
|
27
|
+
const ni = h.indexOf('invoice_no');
|
|
28
|
+
return r.slice(1).map((c) => { const supplier = c[si] ?? ''; const po_no = c[pi] ?? ''; const line_no = c[li] ?? ''; const qty = Number(c[qi]); const unit_price_cents = cents(c[pi2] ?? ''); const amount_cents = cents(c[ai] ?? ''); const invoice_no = ni >= 0 ? (c[ni] ?? '') : po_no; return { id: invoiceLineId({ supplier, invoice_no, line_no, qty, unit_price_cents, amount_cents }), supplier, po_no, line_no, qty, unit_price_cents, amount_cents, evidence_sha256: sha }; });
|
|
29
|
+
}
|
|
30
|
+
export function parsePo(text) {
|
|
31
|
+
const r = rows(text);
|
|
32
|
+
const h = r[0].map(x => x.toLowerCase());
|
|
33
|
+
const ix = (n) => { const i = h.indexOf(n); if (i < 0)
|
|
34
|
+
throw new ApError('E_AP_CSV_INVALID', `CSV 缺少 ${n} 列`, '按 README 的列名补齐第一行表头后重跑'); return i; };
|
|
35
|
+
const pi = ix('po_no'), li = ix('line_no'), qi = ix('qty'), ui = ix('unit_price'), ai = ix('amount');
|
|
36
|
+
return r.slice(1).map(c => ({ po_no: c[pi] ?? '', line_no: c[li] ?? '', qty: Number(c[qi]), unit_price_cents: cents(c[ui] ?? ''), amount_cents: cents(c[ai] ?? '') }));
|
|
37
|
+
}
|
|
38
|
+
export function parseGrn(text) {
|
|
39
|
+
const r = rows(text);
|
|
40
|
+
const h = r[0].map(x => x.toLowerCase());
|
|
41
|
+
const ix = (n) => { const i = h.indexOf(n); if (i < 0)
|
|
42
|
+
throw new ApError('E_AP_CSV_INVALID', `CSV 缺少 ${n} 列`, '按 README 的列名补齐第一行表头后重跑'); return i; };
|
|
43
|
+
const pi = ix('po_no'), li = ix('line_no'), qi = ix('qty');
|
|
44
|
+
return r.slice(1).map(c => ({ po_no: c[pi] ?? '', line_no: c[li] ?? '', qty: Number(c[qi]) }));
|
|
45
|
+
}
|
|
13
46
|
export function matchLine(inv, po, grn) { if (!po)
|
|
14
47
|
return { state: 'exception', reason: 'po_missing', qty_delta: 0, price_delta_cents: 0 }; if (!grn)
|
|
15
48
|
return { state: 'exception', reason: 'grn_missing', qty_delta: 0, price_delta_cents: inv.unit_price_cents - po.unit_price_cents }; const qtyDelta = inv.qty - grn.qty; const priceDelta = inv.unit_price_cents - po.unit_price_cents; const tolerance = Math.max(1, Math.round(po.unit_price_cents * 0.01)); if (qtyDelta > 0)
|
|
@@ -28,14 +61,32 @@ export function parseInvoiceXml(text, poNo = '') {
|
|
|
28
61
|
const items = Array.isArray(invoice.Items?.Item) ? invoice.Items.Item : invoice.Items?.Item ? [invoice.Items.Item] : [];
|
|
29
62
|
if (items.length === 0)
|
|
30
63
|
throw new ApError('E_AP_CSV_INVALID', 'XML invoice has no Items/Item');
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
64
|
+
const invoiceNo = String(invoice.InvoiceNo ?? '').trim();
|
|
65
|
+
return items.map((item, index) => {
|
|
66
|
+
const line_no = String(index + 1);
|
|
67
|
+
const qty = Number(item.Quantity ?? 1);
|
|
68
|
+
const unit_price_cents = cents(String(item.UnitPrice ?? '0'));
|
|
69
|
+
const amount_cents = cents(String(item.Amount ?? '0'));
|
|
70
|
+
return {
|
|
71
|
+
id: invoiceLineId({ supplier, invoice_no: invoiceNo, line_no, qty, unit_price_cents, amount_cents }),
|
|
72
|
+
supplier,
|
|
73
|
+
po_no: poNo,
|
|
74
|
+
line_no,
|
|
75
|
+
qty,
|
|
76
|
+
unit_price_cents,
|
|
77
|
+
amount_cents,
|
|
78
|
+
evidence_sha256: '',
|
|
79
|
+
};
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
/** Duplicate detection over imported invoice lines: the same supplier, PO line, quantity and amount twice. */
|
|
83
|
+
export function duplicateInvoiceLines(lines) {
|
|
84
|
+
const buckets = new Map();
|
|
85
|
+
for (const line of lines) {
|
|
86
|
+
const key = [line.supplier.trim().toLowerCase(), line.po_no, line.line_no, line.qty, line.unit_price_cents, line.amount_cents].join('|');
|
|
87
|
+
const bucket = buckets.get(key) ?? [];
|
|
88
|
+
bucket.push(line);
|
|
89
|
+
buckets.set(key, bucket);
|
|
90
|
+
}
|
|
91
|
+
return [...buckets.values()].filter((b) => b.length > 1).map((b) => ({ line: b[0], occurrences: b.length }));
|
|
41
92
|
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** A single export filename component: no separators, no whitespace, max 120 chars. */
|
|
2
|
+
export declare const SAFE_EXPORT_FILENAME: RegExp;
|
|
3
|
+
/**
|
|
4
|
+
* Resolve a caller-supplied export filename inside a base directory.
|
|
5
|
+
*
|
|
6
|
+
* 1. the filename must be one safe component (`[A-Za-z0-9._-]{1,120}`);
|
|
7
|
+
* 2. the resolved path must stay below `resolve(baseDir) + sep`;
|
|
8
|
+
* 3. the directory is created with `mkdir -p` and the path is re-anchored on
|
|
9
|
+
* `realpath(baseDir)` so a symlinked directory cannot redirect the write
|
|
10
|
+
* outside the canonical base.
|
|
11
|
+
*/
|
|
12
|
+
export declare function safeExportPath(baseDir: string, filename: string): Promise<string>;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { mkdir, realpath } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { ApError } from './ap.js';
|
|
4
|
+
/** A single export filename component: no separators, no whitespace, max 120 chars. */
|
|
5
|
+
export const SAFE_EXPORT_FILENAME = /^[A-Za-z0-9._-]{1,120}$/;
|
|
6
|
+
/**
|
|
7
|
+
* Resolve a caller-supplied export filename inside a base directory.
|
|
8
|
+
*
|
|
9
|
+
* 1. the filename must be one safe component (`[A-Za-z0-9._-]{1,120}`);
|
|
10
|
+
* 2. the resolved path must stay below `resolve(baseDir) + sep`;
|
|
11
|
+
* 3. the directory is created with `mkdir -p` and the path is re-anchored on
|
|
12
|
+
* `realpath(baseDir)` so a symlinked directory cannot redirect the write
|
|
13
|
+
* outside the canonical base.
|
|
14
|
+
*/
|
|
15
|
+
export async function safeExportPath(baseDir, filename) {
|
|
16
|
+
if (!SAFE_EXPORT_FILENAME.test(filename)) {
|
|
17
|
+
throw new ApError('E_AP_PATH_INVALID', `unsafe export filename: ${JSON.stringify(filename)}`);
|
|
18
|
+
}
|
|
19
|
+
const base = path.resolve(baseDir);
|
|
20
|
+
const candidate = path.resolve(base, filename);
|
|
21
|
+
if (!candidate.startsWith(base + path.sep)) {
|
|
22
|
+
throw new ApError('E_AP_PATH_NOT_ALLOWED', `export path escapes base directory: ${JSON.stringify(filename)}`);
|
|
23
|
+
}
|
|
24
|
+
await mkdir(base, { recursive: true });
|
|
25
|
+
const realBase = await realpath(base);
|
|
26
|
+
const realCandidate = path.resolve(realBase, filename);
|
|
27
|
+
if (!realCandidate.startsWith(realBase + path.sep)) {
|
|
28
|
+
throw new ApError('E_AP_PATH_NOT_ALLOWED', `export path escapes base directory after realpath: ${JSON.stringify(filename)}`);
|
|
29
|
+
}
|
|
30
|
+
return realCandidate;
|
|
31
|
+
}
|
package/lib/core/tolerance.js
CHANGED
|
@@ -4,11 +4,11 @@ export function validatePolicy(policy) {
|
|
|
4
4
|
for (const key of ['price_bps', 'qty_bps', 'amount_bps']) {
|
|
5
5
|
const value = policy[key];
|
|
6
6
|
if (!Number.isInteger(value) || value < 0 || value > 10000) {
|
|
7
|
-
throw new Error(
|
|
7
|
+
throw new Error(`容差参数 ${key} 超出范围(E_AP_POLICY)|下一步:把 ${key} 设为 0–10000 的整数`);
|
|
8
8
|
}
|
|
9
9
|
}
|
|
10
10
|
if (!Number.isInteger(policy.min_price_cents) || policy.min_price_cents < 0) {
|
|
11
|
-
throw new Error('E_AP_POLICY
|
|
11
|
+
throw new Error('最小价格容差不能为负(E_AP_POLICY)|下一步:把 min_price_cents 设为 0 或正整数');
|
|
12
12
|
}
|
|
13
13
|
}
|
|
14
14
|
export function matchWithTolerance(inv, po, grn, policy = DEFAULT_TOLERANCE) {
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* xlsx-lite — clean-room minimal xlsx writer/reader (fflate only).
|
|
3
|
+
*
|
|
4
|
+
* This is not a general-purpose spreadsheet library. It implements the exact
|
|
5
|
+
* subset this package needs for local workpaper exports and for the acceptance
|
|
6
|
+
* checks that read those exports back:
|
|
7
|
+
* - write: inline strings + numbers, N sheets, caller-supplied header rows
|
|
8
|
+
* - read: files produced by writeWorkbook (inline strings and numbers)
|
|
9
|
+
* Shared strings, formulas, dates, merged cells and styling are not supported.
|
|
10
|
+
* No third-party spreadsheet code is included.
|
|
11
|
+
*/
|
|
12
|
+
import { Buffer } from 'node:buffer';
|
|
13
|
+
export type Cell = string | number;
|
|
14
|
+
export interface SheetInput {
|
|
15
|
+
name: string;
|
|
16
|
+
rows: Cell[][];
|
|
17
|
+
}
|
|
18
|
+
export interface SheetData {
|
|
19
|
+
name: string;
|
|
20
|
+
rows: Cell[][];
|
|
21
|
+
}
|
|
22
|
+
export interface WorkbookData {
|
|
23
|
+
sheets: SheetData[];
|
|
24
|
+
}
|
|
25
|
+
/** Write a minimal, valid xlsx file containing the supplied sheets (in order). */
|
|
26
|
+
export declare function writeWorkbook(sheets: SheetInput[]): Buffer;
|
|
27
|
+
/** Return the raw worksheet XML for a sheet (by name, or by 0-based position). */
|
|
28
|
+
export declare function readSheetText(buffer: Uint8Array | Buffer, sheet: string | number): string;
|
|
29
|
+
/** Read back a workbook written by writeWorkbook (inline strings and numbers). */
|
|
30
|
+
export declare function readWorkbook(buffer: Uint8Array | Buffer): WorkbookData;
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* xlsx-lite — clean-room minimal xlsx writer/reader (fflate only).
|
|
3
|
+
*
|
|
4
|
+
* This is not a general-purpose spreadsheet library. It implements the exact
|
|
5
|
+
* subset this package needs for local workpaper exports and for the acceptance
|
|
6
|
+
* checks that read those exports back:
|
|
7
|
+
* - write: inline strings + numbers, N sheets, caller-supplied header rows
|
|
8
|
+
* - read: files produced by writeWorkbook (inline strings and numbers)
|
|
9
|
+
* Shared strings, formulas, dates, merged cells and styling are not supported.
|
|
10
|
+
* No third-party spreadsheet code is included.
|
|
11
|
+
*/
|
|
12
|
+
import { Buffer } from 'node:buffer';
|
|
13
|
+
import { strFromU8, strToU8, unzipSync, zipSync } from 'fflate';
|
|
14
|
+
const XML_DECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
|
|
15
|
+
const NS_MAIN = 'http://schemas.openxmlformats.org/spreadsheetml/2006/main';
|
|
16
|
+
const NS_REL = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships';
|
|
17
|
+
const NS_PKG_REL = 'http://schemas.openxmlformats.org/package/2006/relationships';
|
|
18
|
+
const NS_CONTENT_TYPES = 'http://schemas.openxmlformats.org/package/2006/content-types';
|
|
19
|
+
const CT_SHEET = 'application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml';
|
|
20
|
+
const CT_WORKBOOK = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml';
|
|
21
|
+
const CT_STYLES = 'application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml';
|
|
22
|
+
const ESCAPES = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };
|
|
23
|
+
function escapeXml(value) {
|
|
24
|
+
return value.replace(/[&<>"']/g, (char) => ESCAPES[char] ?? char);
|
|
25
|
+
}
|
|
26
|
+
function decodeXml(value) {
|
|
27
|
+
return value.replace(/&(?:amp|lt|gt|quot|apos|#\d+|#x[0-9a-fA-F]+);/g, (entity) => {
|
|
28
|
+
switch (entity) {
|
|
29
|
+
case '&': return '&';
|
|
30
|
+
case '<': return '<';
|
|
31
|
+
case '>': return '>';
|
|
32
|
+
case '"': return '"';
|
|
33
|
+
case ''': return "'";
|
|
34
|
+
default: {
|
|
35
|
+
const code = entity.startsWith('&#x') ? Number.parseInt(entity.slice(3, -1), 16) : Number.parseInt(entity.slice(2, -1), 10);
|
|
36
|
+
return Number.isFinite(code) ? String.fromCodePoint(code) : entity;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
function columnName(index) {
|
|
42
|
+
let name = '';
|
|
43
|
+
let value = index + 1;
|
|
44
|
+
while (value > 0) {
|
|
45
|
+
const remainder = (value - 1) % 26;
|
|
46
|
+
name = String.fromCharCode(65 + remainder) + name;
|
|
47
|
+
value = Math.floor((value - 1) / 26);
|
|
48
|
+
}
|
|
49
|
+
return name;
|
|
50
|
+
}
|
|
51
|
+
function columnIndex(reference) {
|
|
52
|
+
const letters = /^([A-Z]+)/.exec(reference)?.[1];
|
|
53
|
+
if (!letters)
|
|
54
|
+
return -1;
|
|
55
|
+
let index = 0;
|
|
56
|
+
for (const letter of letters)
|
|
57
|
+
index = index * 26 + (letter.charCodeAt(0) - 64);
|
|
58
|
+
return index - 1;
|
|
59
|
+
}
|
|
60
|
+
function validateSheetName(name) {
|
|
61
|
+
if (typeof name !== 'string' || name.length === 0)
|
|
62
|
+
throw new Error('xlsx-lite: sheet name must be a non-empty string');
|
|
63
|
+
if (name.length > 31)
|
|
64
|
+
throw new Error(`xlsx-lite: sheet name too long: ${name}`);
|
|
65
|
+
if (['[', ']', ':', '*', '?', '/', '\\'].some((char) => name.includes(char)))
|
|
66
|
+
throw new Error(`xlsx-lite: invalid sheet name: ${name}`);
|
|
67
|
+
if (name.startsWith("'") || name.endsWith("'"))
|
|
68
|
+
throw new Error(`xlsx-lite: invalid sheet name: ${name}`);
|
|
69
|
+
}
|
|
70
|
+
function cellXml(cell, reference) {
|
|
71
|
+
if (typeof cell === 'number') {
|
|
72
|
+
if (!Number.isFinite(cell))
|
|
73
|
+
throw new Error(`xlsx-lite: non-finite number at ${reference}`);
|
|
74
|
+
return `<c r="${reference}"><v>${cell}</v></c>`;
|
|
75
|
+
}
|
|
76
|
+
return `<c r="${reference}" t="inlineStr"><is><t xml:space="preserve">${escapeXml(String(cell))}</t></is></c>`;
|
|
77
|
+
}
|
|
78
|
+
function sheetXml(rows) {
|
|
79
|
+
const body = rows.map((row, rowIndex) => {
|
|
80
|
+
const cells = row.map((cell, cellIndex) => cellXml(cell, `${columnName(cellIndex)}${rowIndex + 1}`)).join('');
|
|
81
|
+
return `<row r="${rowIndex + 1}">${cells}</row>`;
|
|
82
|
+
}).join('');
|
|
83
|
+
return `${XML_DECL}<worksheet xmlns="${NS_MAIN}"><sheetData>${body}</sheetData></worksheet>`;
|
|
84
|
+
}
|
|
85
|
+
function contentTypesXml(sheets) {
|
|
86
|
+
const overrides = sheets.map((_sheet, index) => `<Override PartName="/xl/worksheets/sheet${index + 1}.xml" ContentType="${CT_SHEET}"/>`).join('');
|
|
87
|
+
return `${XML_DECL}<Types xmlns="${NS_CONTENT_TYPES}">`
|
|
88
|
+
+ '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>'
|
|
89
|
+
+ '<Default Extension="xml" ContentType="application/xml"/>'
|
|
90
|
+
+ `<Override PartName="/xl/workbook.xml" ContentType="${CT_WORKBOOK}"/>`
|
|
91
|
+
+ overrides
|
|
92
|
+
+ `<Override PartName="/xl/styles.xml" ContentType="${CT_STYLES}"/>`
|
|
93
|
+
+ '</Types>';
|
|
94
|
+
}
|
|
95
|
+
function packageRelsXml() {
|
|
96
|
+
return `${XML_DECL}<Relationships xmlns="${NS_PKG_REL}">`
|
|
97
|
+
+ `<Relationship Id="rId1" Type="${NS_REL}/officeDocument" Target="xl/workbook.xml"/>`
|
|
98
|
+
+ '</Relationships>';
|
|
99
|
+
}
|
|
100
|
+
function workbookXml(sheets) {
|
|
101
|
+
const entries = sheets.map((sheet, index) => `<sheet name="${escapeXml(sheet.name)}" sheetId="${index + 1}" r:id="rId${index + 1}"/>`).join('');
|
|
102
|
+
return `${XML_DECL}<workbook xmlns="${NS_MAIN}" xmlns:r="${NS_REL}"><sheets>${entries}</sheets></workbook>`;
|
|
103
|
+
}
|
|
104
|
+
function workbookRelsXml(sheets) {
|
|
105
|
+
const sheetRels = sheets.map((_sheet, index) => `<Relationship Id="rId${index + 1}" Type="${NS_REL}/worksheet" Target="worksheets/sheet${index + 1}.xml"/>`).join('');
|
|
106
|
+
const stylesRel = `<Relationship Id="rId${sheets.length + 1}" Type="${NS_REL}/styles" Target="styles.xml"/>`;
|
|
107
|
+
return `${XML_DECL}<Relationships xmlns="${NS_PKG_REL}">${sheetRels}${stylesRel}</Relationships>`;
|
|
108
|
+
}
|
|
109
|
+
function stylesXml() {
|
|
110
|
+
return `${XML_DECL}<styleSheet xmlns="${NS_MAIN}">`
|
|
111
|
+
+ '<fonts count="1"><font><sz val="11"/><name val="Calibri"/></font></fonts>'
|
|
112
|
+
+ '<fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills>'
|
|
113
|
+
+ '<borders count="1"><border/></borders>'
|
|
114
|
+
+ '<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>'
|
|
115
|
+
+ '<cellXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/></cellXfs>'
|
|
116
|
+
+ '</styleSheet>';
|
|
117
|
+
}
|
|
118
|
+
/** Write a minimal, valid xlsx file containing the supplied sheets (in order). */
|
|
119
|
+
export function writeWorkbook(sheets) {
|
|
120
|
+
if (!Array.isArray(sheets) || sheets.length === 0)
|
|
121
|
+
throw new Error('xlsx-lite: at least one sheet is required');
|
|
122
|
+
const names = new Set();
|
|
123
|
+
for (const sheet of sheets) {
|
|
124
|
+
validateSheetName(sheet.name);
|
|
125
|
+
if (names.has(sheet.name))
|
|
126
|
+
throw new Error(`xlsx-lite: duplicate sheet name: ${sheet.name}`);
|
|
127
|
+
names.add(sheet.name);
|
|
128
|
+
}
|
|
129
|
+
const files = {
|
|
130
|
+
'[Content_Types].xml': strToU8(contentTypesXml(sheets)),
|
|
131
|
+
'_rels/.rels': strToU8(packageRelsXml()),
|
|
132
|
+
'xl/workbook.xml': strToU8(workbookXml(sheets)),
|
|
133
|
+
'xl/_rels/workbook.xml.rels': strToU8(workbookRelsXml(sheets)),
|
|
134
|
+
'xl/styles.xml': strToU8(stylesXml()),
|
|
135
|
+
};
|
|
136
|
+
sheets.forEach((sheet, index) => {
|
|
137
|
+
files[`xl/worksheets/sheet${index + 1}.xml`] = strToU8(sheetXml(sheet.rows));
|
|
138
|
+
});
|
|
139
|
+
return Buffer.from(zipSync(files));
|
|
140
|
+
}
|
|
141
|
+
function attribute(tag, name) {
|
|
142
|
+
const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
143
|
+
const match = new RegExp(`(?:^|\\s)${escaped}="([^"]*)"`).exec(tag);
|
|
144
|
+
return match ? decodeXml(match[1] ?? '') : undefined;
|
|
145
|
+
}
|
|
146
|
+
function resolveTarget(target) {
|
|
147
|
+
const base = target.startsWith('/') ? target.slice(1) : `xl/${target}`;
|
|
148
|
+
const parts = [];
|
|
149
|
+
for (const part of base.split('/')) {
|
|
150
|
+
if (part === '..')
|
|
151
|
+
parts.pop();
|
|
152
|
+
else if (part !== '' && part !== '.')
|
|
153
|
+
parts.push(part);
|
|
154
|
+
}
|
|
155
|
+
return parts.join('/');
|
|
156
|
+
}
|
|
157
|
+
function readSheetEntries(buffer) {
|
|
158
|
+
const zip = unzipSync(buffer);
|
|
159
|
+
const workbook = zip['xl/workbook.xml'];
|
|
160
|
+
const rels = zip['xl/_rels/workbook.xml.rels'];
|
|
161
|
+
if (!workbook)
|
|
162
|
+
throw new Error('xlsx-lite: missing xl/workbook.xml');
|
|
163
|
+
if (!rels)
|
|
164
|
+
throw new Error('xlsx-lite: missing xl/_rels/workbook.xml.rels');
|
|
165
|
+
const pathById = new Map();
|
|
166
|
+
for (const match of strFromU8(rels).matchAll(/<Relationship\b[^>]*>/g)) {
|
|
167
|
+
const id = attribute(match[0], 'Id');
|
|
168
|
+
const target = attribute(match[0], 'Target');
|
|
169
|
+
if (id && target)
|
|
170
|
+
pathById.set(id, resolveTarget(target));
|
|
171
|
+
}
|
|
172
|
+
const entries = [];
|
|
173
|
+
for (const match of strFromU8(workbook).matchAll(/<sheet\b[^>]*>/g)) {
|
|
174
|
+
const name = attribute(match[0], 'name');
|
|
175
|
+
const relationId = attribute(match[0], 'r:id');
|
|
176
|
+
if (!name || !relationId)
|
|
177
|
+
continue;
|
|
178
|
+
const path = pathById.get(relationId);
|
|
179
|
+
if (!path)
|
|
180
|
+
throw new Error(`xlsx-lite: missing relationship for sheet: ${name}`);
|
|
181
|
+
const data = zip[path];
|
|
182
|
+
if (!data)
|
|
183
|
+
throw new Error(`xlsx-lite: missing worksheet part: ${path}`);
|
|
184
|
+
entries.push({ name, path, xml: strFromU8(data) });
|
|
185
|
+
}
|
|
186
|
+
return entries;
|
|
187
|
+
}
|
|
188
|
+
function numericText(value) {
|
|
189
|
+
return /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(value);
|
|
190
|
+
}
|
|
191
|
+
function parseSheetRows(xml) {
|
|
192
|
+
const rows = [];
|
|
193
|
+
for (const rowMatch of xml.matchAll(/<row\b([^>]*?)(?:\/>|>([\s\S]*?)<\/row>)/g)) {
|
|
194
|
+
const rowAttributes = rowMatch[1] ?? '';
|
|
195
|
+
const rowBody = rowMatch[2] ?? '';
|
|
196
|
+
const rowReference = attribute(rowAttributes, 'r');
|
|
197
|
+
const rowIndex = rowReference ? Number(rowReference) - 1 : rows.length;
|
|
198
|
+
if (!Number.isInteger(rowIndex) || rowIndex < 0)
|
|
199
|
+
throw new Error(`xlsx-lite: bad row reference: ${rowReference}`);
|
|
200
|
+
const cells = [];
|
|
201
|
+
let nextColumn = 0;
|
|
202
|
+
for (const cellMatch of rowBody.matchAll(/<c\b([^>]*?)(?:\/>|>([\s\S]*?)<\/c>)/g)) {
|
|
203
|
+
const cellAttributes = cellMatch[1] ?? '';
|
|
204
|
+
const cellBody = cellMatch[2] ?? '';
|
|
205
|
+
const reference = attribute(cellAttributes, 'r');
|
|
206
|
+
const index = reference ? columnIndex(reference) : nextColumn;
|
|
207
|
+
if (index < 0)
|
|
208
|
+
throw new Error(`xlsx-lite: bad cell reference: ${reference}`);
|
|
209
|
+
nextColumn = index + 1;
|
|
210
|
+
const type = attribute(cellAttributes, 't');
|
|
211
|
+
if (type === 's')
|
|
212
|
+
throw new Error('xlsx-lite: shared strings are not supported');
|
|
213
|
+
const inline = type === 'inlineStr' ? /<t(?:\s[^>]*)?>([\s\S]*?)<\/t>/.exec(cellBody) : undefined;
|
|
214
|
+
if (inline) {
|
|
215
|
+
cells[index] = decodeXml(inline[1] ?? '');
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
const literal = /<v(?:\s[^>]*)?>([\s\S]*?)<\/v>/.exec(cellBody);
|
|
219
|
+
if (literal) {
|
|
220
|
+
const raw = decodeXml(literal[1] ?? '');
|
|
221
|
+
cells[index] = numericText(raw) ? Number(raw) : raw;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
rows[rowIndex] = cells;
|
|
225
|
+
}
|
|
226
|
+
const normalized = [];
|
|
227
|
+
for (let index = 0; index < rows.length; index += 1)
|
|
228
|
+
normalized.push(rows[index] ?? []);
|
|
229
|
+
return normalized;
|
|
230
|
+
}
|
|
231
|
+
function asBytes(buffer) {
|
|
232
|
+
return buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
|
|
233
|
+
}
|
|
234
|
+
/** Return the raw worksheet XML for a sheet (by name, or by 0-based position). */
|
|
235
|
+
export function readSheetText(buffer, sheet) {
|
|
236
|
+
const entries = readSheetEntries(asBytes(buffer));
|
|
237
|
+
const found = typeof sheet === 'number' ? entries[sheet] : entries.find((entry) => entry.name === sheet);
|
|
238
|
+
if (!found)
|
|
239
|
+
throw new Error(`xlsx-lite: sheet not found: ${String(sheet)}`);
|
|
240
|
+
return found.xml;
|
|
241
|
+
}
|
|
242
|
+
/** Read back a workbook written by writeWorkbook (inline strings and numbers). */
|
|
243
|
+
export function readWorkbook(buffer) {
|
|
244
|
+
return { sheets: readSheetEntries(asBytes(buffer)).map((entry) => ({ name: entry.name, rows: parseSheetRows(entry.xml) })) };
|
|
245
|
+
}
|
package/lib/plugin/tools.js
CHANGED
|
@@ -1,19 +1,32 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
|
-
import {
|
|
2
|
+
import { writeFile } from 'node:fs/promises';
|
|
3
3
|
import path from 'node:path';
|
|
4
|
-
import * as XLSX from 'xlsx';
|
|
5
4
|
import { defineTool } from '@deepseek-ai/dsh-tools';
|
|
6
|
-
import { ApError, matchLine, parseGrn, parseInvoiceXml, parseInvoices, parsePo } from '../core/ap.js';
|
|
5
|
+
import { ApError, duplicateInvoiceLines, matchLine, parseGrn, parseInvoiceXml, parseInvoices, parsePo } from '../core/ap.js';
|
|
7
6
|
import { DEFAULT_TOLERANCE, matchWithTolerance } from '../core/tolerance.js';
|
|
7
|
+
import { safeExportPath } from '../core/safe-path.js';
|
|
8
|
+
import { writeWorkbook } from '../core/xlsx-lite.js';
|
|
8
9
|
const text = (t) => [{ type: 'text', text: t }];
|
|
9
10
|
const sha = (v) => createHash('sha256').update(v).digest('hex');
|
|
11
|
+
const toRows = (items) => { if (items.length === 0)
|
|
12
|
+
return []; const headers = Object.keys(items[0]); return [headers, ...items.map((item) => headers.map((key) => { const value = item[key]; return typeof value === 'number' ? value : String(value ?? ''); }))]; };
|
|
10
13
|
export function createTools(deps) {
|
|
11
|
-
const imp = defineTool({ name: 'ap.import', description: 'Import invoice, PO and GRN CSV lines (supplier,po_no,line_no,qty,unit_price,amount). Local R1 write.', parameters: { invoices_csv: { type: 'string', required: true }, po_csv: { type: 'string', required: true }, grn_csv: { type: 'string', required: true } }, output: { schema: { type: 'object', additionalProperties: false, properties: { invoices: { type: 'number', required: true }, po: { type: 'number', required: true }, grn: { type: 'number', required: true } } }, render: (_a, v) => text(`import inv=${v.invoices} po=${v.po} grn=${v.grn}`) }, async execute(a) { const inv = parseInvoices(a.invoices_csv, sha(a.invoices_csv)), po = parsePo(a.po_csv), grn = parseGrn(a.grn_csv); for (const x of inv)
|
|
12
|
-
|
|
14
|
+
const imp = defineTool({ name: 'ap.import', description: 'Import invoice, PO and GRN CSV lines (supplier,po_no,line_no,qty,unit_price,amount). Local R1 write.', parameters: { invoices_csv: { type: 'string', required: true }, po_csv: { type: 'string', required: true }, grn_csv: { type: 'string', required: true } }, output: { schema: { type: 'object', additionalProperties: false, properties: { invoices: { type: 'number', required: true }, po: { type: 'number', required: true }, grn: { type: 'number', required: true }, skipped: { type: 'number', required: true } } }, render: (_a, v) => text(`import inv=${v.invoices} po=${v.po} grn=${v.grn} skipped=${v.skipped}`) }, async execute(a) { const inv = parseInvoices(a.invoices_csv, sha(a.invoices_csv)), po = parsePo(a.po_csv), grn = parseGrn(a.grn_csv); let skipped = 0; for (const x of inv) {
|
|
15
|
+
if (deps.invoices.get(x.id)) {
|
|
16
|
+
skipped += 1;
|
|
17
|
+
continue;
|
|
18
|
+
}
|
|
19
|
+
await deps.invoices.put(x.id, x);
|
|
20
|
+
} for (const x of po)
|
|
13
21
|
await deps.po.put(`${x.po_no}|${x.line_no}`, x); for (const x of grn)
|
|
14
|
-
await deps.grn.put(`${x.po_no}|${x.line_no}`, x); return { invoices: inv.length, po: po.length, grn: grn.length }; } });
|
|
15
|
-
const invoiceXml = defineTool({ name: 'ap.import_invoice_xml', description: 'Import invoice line items from a local generic invoice XML (synthetic/public sample); optional PO reference. Local R1 write.', parameters: { xml_text: { type: 'string', required: true }, po_no: { type: 'string' } }, output: { schema: { type: 'object', additionalProperties: false, properties: { rows: { type: 'number', required: true }, supplier: { type: 'string', required: true } } }, render: (_a, v) => text(`XML invoice ${v.rows} lines`) }, async execute(a) { const rows = parseInvoiceXml(a.xml_text, a.po_no ?? ''); for (const r of rows)
|
|
16
|
-
|
|
22
|
+
await deps.grn.put(`${x.po_no}|${x.line_no}`, x); return { invoices: inv.length, po: po.length, grn: grn.length, skipped }; } });
|
|
23
|
+
const invoiceXml = defineTool({ name: 'ap.import_invoice_xml', description: 'Import invoice line items from a local generic invoice XML (synthetic/public sample); optional PO reference. Local R1 write.', parameters: { xml_text: { type: 'string', required: true }, po_no: { type: 'string' } }, output: { schema: { type: 'object', additionalProperties: false, properties: { rows: { type: 'number', required: true }, skipped: { type: 'number', required: true }, supplier: { type: 'string', required: true } } }, render: (_a, v) => text(`XML invoice ${v.rows} lines skipped=${v.skipped}`) }, async execute(a) { const rows = parseInvoiceXml(a.xml_text, a.po_no ?? ''); let skipped = 0; for (const r of rows) {
|
|
24
|
+
if (deps.invoices.get(r.id)) {
|
|
25
|
+
skipped += 1;
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
await deps.invoices.put(r.id, r);
|
|
29
|
+
} return { rows: rows.length, skipped, supplier: rows[0]?.supplier ?? '' }; } });
|
|
17
30
|
const match = defineTool({ name: 'ap.match', description: 'Three-way match invoice vs PO vs GRN with 1% unit-price tolerance; qty over GRN is an exception. Stores matches/exceptions.', parameters: {}, output: { schema: { type: 'object', additionalProperties: false, properties: { matched: { type: 'number', required: true }, exceptions: { type: 'number', required: true }, matched_ids: { type: 'array', items: { type: 'string' }, required: true } } }, render: (_a, v) => text(`matched=${v.matched} exceptions=${v.exceptions}`) }, async execute() { let matched = 0, exceptions = 0; const ids = []; for (const [_id, inv] of deps.invoices.entries()) {
|
|
18
31
|
const key = `${inv.po_no}|${inv.line_no}`;
|
|
19
32
|
const po = deps.po.get(key), grn = deps.grn.get(key);
|
|
@@ -27,7 +40,7 @@ export function createTools(deps) {
|
|
|
27
40
|
const m = { match_id: `m_${inv.id}`, invoice_id: inv.id, po_no: inv.po_no, line_no: inv.line_no, qty_delta: r.qty_delta, price_delta_cents: r.price_delta_cents, state: r.state, reason: r.reason, created_at: new Date().toISOString() };
|
|
28
41
|
await deps.matches.put(m.match_id, m);
|
|
29
42
|
} return { matched, exceptions, matched_ids: ids }; } });
|
|
30
|
-
const exp = defineTool({ name: 'ap.export', description: 'Export 2-sheet xlsx (Matches, Exceptions). Local R1 write.', parameters: {}, output: { schema: { type: 'object', additionalProperties: false, properties: { path: { type: 'string', required: true }, sha256: { type: 'string', required: true }, sheets: { type: 'number', required: true } } }, render: (_a, v) => text(`export ${v.sheets} sheets`) }, async execute() { const ms = [...deps.matches.entries()].map(([, v]) => v); const
|
|
43
|
+
const exp = defineTool({ name: 'ap.export', description: 'Export 2-sheet xlsx (Matches, Exceptions). Local R1 write.', parameters: {}, output: { schema: { type: 'object', additionalProperties: false, properties: { path: { type: 'string', required: true }, sha256: { type: 'string', required: true }, sheets: { type: 'number', required: true } } }, render: (_a, v) => text(`export ${v.sheets} sheets`) }, async execute() { const ms = [...deps.matches.entries()].map(([, v]) => v); const sheets = [{ name: 'Matches', rows: toRows(ms.filter(m => m.state === 'matched')) }, { name: 'Exceptions', rows: toRows(ms.filter(m => m.state === 'exception')) }]; const dir = path.join(deps.baseDir, 'exports'); const p = await safeExportPath(dir, `ap-${Date.now()}.xlsx`); const b = writeWorkbook(sheets); await writeFile(p, b); return { path: p, sha256: sha(b), sheets: sheets.length }; } });
|
|
31
44
|
const toleranceTool = defineTool({ name: 'ap.tolerance_match', description: 'Three-way match with a configurable tolerance policy (price/qty/amount in basis points); read-only, does not store matches.', parameters: { invoices_csv: { type: 'string', required: true }, po_csv: { type: 'string', required: true }, grn_csv: { type: 'string', required: true }, price_bps: { type: 'number' }, qty_bps: { type: 'number' }, amount_bps: { type: 'number' }, min_price_cents: { type: 'number' } }, output: { schema: { type: 'object', additionalProperties: false, properties: { lines: { type: 'number', required: true }, matched: { type: 'number', required: true }, exceptions: { type: 'number', required: true }, results: { type: 'array', required: true, items: { type: 'object', additionalProperties: false, properties: { po_no: { type: 'string', required: true }, line_no: { type: 'string', required: true }, state: { type: 'string', required: true }, reason: { type: 'string', required: true }, qty_delta: { type: 'number', required: true }, price_delta_cents: { type: 'number', required: true }, amount_delta_cents: { type: 'number', required: true } } } } } }, render: (_a, v) => text('tolerance match ' + v.matched + ' matched / ' + v.exceptions + ' exceptions') }, async execute(args) {
|
|
32
45
|
const policy = { ...DEFAULT_TOLERANCE, price_bps: args.price_bps ?? DEFAULT_TOLERANCE.price_bps, qty_bps: args.qty_bps ?? DEFAULT_TOLERANCE.qty_bps, amount_bps: args.amount_bps ?? DEFAULT_TOLERANCE.amount_bps, min_price_cents: args.min_price_cents ?? DEFAULT_TOLERANCE.min_price_cents };
|
|
33
46
|
const invoices = parseInvoices(args.invoices_csv, sha(args.invoices_csv));
|
|
@@ -40,5 +53,6 @@ export function createTools(deps) {
|
|
|
40
53
|
const matched = results.filter(r => r.state === 'matched').length;
|
|
41
54
|
return { lines: results.length, matched, exceptions: results.length - matched, results };
|
|
42
55
|
} });
|
|
43
|
-
return
|
|
56
|
+
const dupTool = defineTool({ name: 'ap.duplicate_check', description: 'Detect duplicate invoice lines by supplier, PO line, quantity and amount before matching. Read-only.', parameters: { invoices_csv: { type: 'string', required: true } }, output: { schema: { type: 'object', additionalProperties: false, properties: { lines: { type: 'number', required: true }, duplicates: { type: 'array', required: true, items: { type: 'object', additionalProperties: false, properties: { supplier: { type: 'string', required: true }, po_no: { type: 'string', required: true }, line_no: { type: 'string', required: true }, occurrences: { type: 'number', required: true } } } } } }, render: (_a, v) => text('duplicates=' + v.duplicates.length) }, async execute(a) { const lines = parseInvoices(a.invoices_csv, sha(a.invoices_csv)); const dups = duplicateInvoiceLines(lines); return { lines: lines.length, duplicates: dups.map((d) => ({ supplier: d.line.supplier, po_no: d.line.po_no, line_no: d.line.line_no, occurrences: d.occurrences })) }; } });
|
|
57
|
+
return [imp, invoiceXml, match, exp, toleranceTool, dupTool];
|
|
44
58
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-ap-three-way",
|
|
3
|
-
"version": "0.1.0
|
|
3
|
+
"version": "0.1.0",
|
|
4
4
|
"description": "AP invoice/PO/GRN three-way match with tolerance policy and exception workpaper.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./lib/plugin/index.js",
|
|
@@ -23,6 +23,7 @@
|
|
|
23
23
|
"README-pt.md",
|
|
24
24
|
"README-hi.md",
|
|
25
25
|
"docs/assets",
|
|
26
|
+
"samples",
|
|
26
27
|
"SECURITY.md",
|
|
27
28
|
"PRIVACY.md",
|
|
28
29
|
"CODE_OF_CONDUCT.md",
|
|
@@ -35,10 +36,24 @@
|
|
|
35
36
|
"dsh": {
|
|
36
37
|
"bundle": {
|
|
37
38
|
"patch": "./cordis.patch.yml"
|
|
39
|
+
},
|
|
40
|
+
"demo": {
|
|
41
|
+
"sample": "samples/quickstart/input",
|
|
42
|
+
"prompt": "帮我用自带样例做一次发票、采购单、收货单三单匹配,把能过的和例外分别列出来。",
|
|
43
|
+
"expect": "samples/quickstart/expected/result.json",
|
|
44
|
+
"screenshot": "docs/assets/quickstart.png",
|
|
45
|
+
"reads": [
|
|
46
|
+
"用户指定的发票/采购单/收货单 CSV 与发票 XML"
|
|
47
|
+
],
|
|
48
|
+
"writes": [
|
|
49
|
+
"$DSH_HOME/storages/dsh-ap-three-way"
|
|
50
|
+
],
|
|
51
|
+
"network": false,
|
|
52
|
+
"external": []
|
|
38
53
|
}
|
|
39
54
|
},
|
|
40
55
|
"engines": {
|
|
41
|
-
"dsh": ">=0.2.1-rc.3 <0.
|
|
56
|
+
"dsh": ">=0.2.1-rc.3 <0.4.0",
|
|
42
57
|
"node": ">=24.9.0 <25"
|
|
43
58
|
},
|
|
44
59
|
"packageManager": "pnpm@11.28.5",
|
|
@@ -71,14 +86,13 @@
|
|
|
71
86
|
"access": "public"
|
|
72
87
|
},
|
|
73
88
|
"peerDependencies": {
|
|
74
|
-
"@deepseek-ai/cordis": ">=4.0.5 <5",
|
|
75
|
-
"@deepseek-ai/dsh-storage-domain": ">=0.2.1-rc.3 <0.
|
|
76
|
-
"@deepseek-ai/dsh-tools": ">=0.2.1-rc.3 <0.
|
|
89
|
+
"@deepseek-ai/cordis": ">=4.0.5 <5.0.0",
|
|
90
|
+
"@deepseek-ai/dsh-storage-domain": ">=0.2.1-rc.3 <0.4.0",
|
|
91
|
+
"@deepseek-ai/dsh-tools": ">=0.2.1-rc.3 <0.4.0"
|
|
77
92
|
},
|
|
78
93
|
"dependencies": {
|
|
79
94
|
"fast-xml-parser": "5.11.2",
|
|
80
95
|
"fflate": "0.8.3",
|
|
81
|
-
"xlsx": "0.18.5",
|
|
82
96
|
"zod": "4.4.3"
|
|
83
97
|
},
|
|
84
98
|
"devDependencies": {
|
|
@@ -101,5 +115,13 @@
|
|
|
101
115
|
"bugs": {
|
|
102
116
|
"url": "https://github.com/PerryLink/dsh-ap-three-way/issues"
|
|
103
117
|
},
|
|
104
|
-
"icon": "icon.svg"
|
|
118
|
+
"icon": "icon.svg",
|
|
119
|
+
"peerDependenciesMeta": {
|
|
120
|
+
"@deepseek-ai/dsh-storage-domain": {
|
|
121
|
+
"optional": true
|
|
122
|
+
},
|
|
123
|
+
"@deepseek-ai/dsh-tools": {
|
|
124
|
+
"optional": true
|
|
125
|
+
}
|
|
126
|
+
}
|
|
105
127
|
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
{
|
|
2
|
+
"package": "dsh-ap-three-way",
|
|
3
|
+
"sample": "synthetic/quickstart",
|
|
4
|
+
"imported": {
|
|
5
|
+
"invoices": 4,
|
|
6
|
+
"po": 4,
|
|
7
|
+
"grn": 4,
|
|
8
|
+
"skipped": 0
|
|
9
|
+
},
|
|
10
|
+
"match": {
|
|
11
|
+
"matched": 2,
|
|
12
|
+
"exceptions": 2,
|
|
13
|
+
"exception_detail": [
|
|
14
|
+
{
|
|
15
|
+
"po_no": "PO-9002",
|
|
16
|
+
"line_no": "1",
|
|
17
|
+
"reason": "qty_over_grn",
|
|
18
|
+
"qty_delta": 2,
|
|
19
|
+
"price_delta_cents": 50
|
|
20
|
+
},
|
|
21
|
+
{
|
|
22
|
+
"po_no": "PO-9003",
|
|
23
|
+
"line_no": "1",
|
|
24
|
+
"reason": "price_tolerance",
|
|
25
|
+
"qty_delta": 0,
|
|
26
|
+
"price_delta_cents": 3000
|
|
27
|
+
}
|
|
28
|
+
]
|
|
29
|
+
},
|
|
30
|
+
"tolerance": {
|
|
31
|
+
"price_bps": 1200,
|
|
32
|
+
"matched": 3,
|
|
33
|
+
"exceptions": 1,
|
|
34
|
+
"exception_detail": [
|
|
35
|
+
{
|
|
36
|
+
"po_no": "PO-9002",
|
|
37
|
+
"line_no": "1",
|
|
38
|
+
"reason": "qty_over_grn"
|
|
39
|
+
}
|
|
40
|
+
]
|
|
41
|
+
},
|
|
42
|
+
"duplicates": {
|
|
43
|
+
"lines": 3,
|
|
44
|
+
"duplicates": [
|
|
45
|
+
{
|
|
46
|
+
"supplier": "ACME",
|
|
47
|
+
"po_no": "PO-9001",
|
|
48
|
+
"line_no": "1",
|
|
49
|
+
"occurrences": 2
|
|
50
|
+
}
|
|
51
|
+
]
|
|
52
|
+
},
|
|
53
|
+
"xml": {
|
|
54
|
+
"rows": 1,
|
|
55
|
+
"supplier": "DELTA SUPPLIES"
|
|
56
|
+
},
|
|
57
|
+
"workpaper": {
|
|
58
|
+
"sheets": [
|
|
59
|
+
"Matches",
|
|
60
|
+
"Exceptions"
|
|
61
|
+
],
|
|
62
|
+
"rows": [
|
|
63
|
+
3,
|
|
64
|
+
3
|
|
65
|
+
]
|
|
66
|
+
},
|
|
67
|
+
"input_sha256": {
|
|
68
|
+
"invoices.csv": "0337e4878830724b4e955a0a0aa6c04104d2e0c5265c036c87905471ddf6e925",
|
|
69
|
+
"po.csv": "07303b09e24168e8a3dba2aa78eb0b507ae1399b9878e1c3b53b547df93549b6",
|
|
70
|
+
"grn.csv": "e502b5121317533ec862031d42872f079a0c693009e4abbe79b5b88f44880a8b",
|
|
71
|
+
"invoices-duplicate.csv": "0538b901c452169413f93fd40e99a72f7c2c52b16f1eb60294af07a8d89e0bad",
|
|
72
|
+
"invoice-sample.xml": "6c64e9a9a0df235557f0fa224137bb319f5746761944637717795d1e40fa1e5c"
|
|
73
|
+
}
|
|
74
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
<?xml version="1.0" encoding="UTF-8"?>
|
|
2
|
+
<Invoice>
|
|
3
|
+
<InvoiceNo>INV-XML-5001</InvoiceNo>
|
|
4
|
+
<Seller>
|
|
5
|
+
<Name>DELTA SUPPLIES</Name>
|
|
6
|
+
</Seller>
|
|
7
|
+
<Items>
|
|
8
|
+
<Item>
|
|
9
|
+
<Quantity>2</Quantity>
|
|
10
|
+
<UnitPrice>50.00</UnitPrice>
|
|
11
|
+
<Amount>100.00</Amount>
|
|
12
|
+
</Item>
|
|
13
|
+
</Items>
|
|
14
|
+
</Invoice>
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Quickstart runner for the shipped synthetic sample.
|
|
4
|
+
*
|
|
5
|
+
* node samples/quickstart/run.mjs # human-readable transcript (screenshot source)
|
|
6
|
+
* node samples/quickstart/run.mjs --json # canonical result used as the gold file
|
|
7
|
+
*
|
|
8
|
+
* Everything runs locally against `samples/quickstart/input/`; nothing is uploaded and no
|
|
9
|
+
* customer data is involved. The export is written to a temporary directory that is removed
|
|
10
|
+
* afterwards, so the sample never writes into the checkout.
|
|
11
|
+
*/
|
|
12
|
+
import { createHash } from 'node:crypto'
|
|
13
|
+
import { mkdtemp, readFile, rm } from 'node:fs/promises'
|
|
14
|
+
import { readFileSync } from 'node:fs'
|
|
15
|
+
import os from 'node:os'
|
|
16
|
+
import path from 'node:path'
|
|
17
|
+
import { fileURLToPath } from 'node:url'
|
|
18
|
+
import { createTools } from '../../lib/plugin/tools.js'
|
|
19
|
+
import { readWorkbook } from '../../lib/core/xlsx-lite.js'
|
|
20
|
+
|
|
21
|
+
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..')
|
|
22
|
+
const readInput = (name) => readFileSync(path.join(root, 'samples', 'quickstart', 'input', name), 'utf8')
|
|
23
|
+
const sha = (value) => createHash('sha256').update(value).digest('hex')
|
|
24
|
+
|
|
25
|
+
class MemoryTable {
|
|
26
|
+
map = new Map()
|
|
27
|
+
get(key) { return this.map.get(key) }
|
|
28
|
+
entries() { return this.map.entries() }
|
|
29
|
+
async put(key, value) { this.map.set(key, value) }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async function run() {
|
|
33
|
+
const invoicesCsv = readInput('invoices.csv')
|
|
34
|
+
const poCsv = readInput('po.csv')
|
|
35
|
+
const grnCsv = readInput('grn.csv')
|
|
36
|
+
const duplicateCsv = readInput('invoices-duplicate.csv')
|
|
37
|
+
const invoiceXml = readInput('invoice-sample.xml')
|
|
38
|
+
|
|
39
|
+
const baseDir = await mkdtemp(path.join(os.tmpdir(), 'dsh-ap-quickstart-'))
|
|
40
|
+
try {
|
|
41
|
+
const tables = { invoices: new MemoryTable(), po: new MemoryTable(), grn: new MemoryTable(), matches: new MemoryTable(), baseDir }
|
|
42
|
+
const tools = Object.fromEntries(createTools(tables).map((tool) => [tool.name, tool]))
|
|
43
|
+
const call = (name, args) => tools[name].execute(args, { callId: 'quickstart' })
|
|
44
|
+
|
|
45
|
+
const imported = await call('ap.import', {
|
|
46
|
+
invoices_csv: invoicesCsv,
|
|
47
|
+
po_csv: poCsv,
|
|
48
|
+
grn_csv: grnCsv,
|
|
49
|
+
})
|
|
50
|
+
const match = await call('ap.match', {})
|
|
51
|
+
const exported = await call('ap.export', {})
|
|
52
|
+
const workbook = readWorkbook(await readFile(exported.path))
|
|
53
|
+
const tolerance = await call('ap.tolerance_match', {
|
|
54
|
+
invoices_csv: invoicesCsv,
|
|
55
|
+
po_csv: poCsv,
|
|
56
|
+
grn_csv: grnCsv,
|
|
57
|
+
price_bps: 1200,
|
|
58
|
+
})
|
|
59
|
+
const duplicates = await call('ap.duplicate_check', { invoices_csv: duplicateCsv })
|
|
60
|
+
const xml = await call('ap.import_invoice_xml', { xml_text: invoiceXml, po_no: 'PO-9001' })
|
|
61
|
+
|
|
62
|
+
const exceptions = [...tables.matches.entries()]
|
|
63
|
+
.map(([, record]) => record)
|
|
64
|
+
.filter((record) => record.state === 'exception')
|
|
65
|
+
.map((record) => ({
|
|
66
|
+
po_no: record.po_no,
|
|
67
|
+
line_no: record.line_no,
|
|
68
|
+
reason: record.reason,
|
|
69
|
+
qty_delta: record.qty_delta,
|
|
70
|
+
price_delta_cents: record.price_delta_cents,
|
|
71
|
+
}))
|
|
72
|
+
.sort((a, b) => `${a.po_no}|${a.line_no}`.localeCompare(`${b.po_no}|${b.line_no}`))
|
|
73
|
+
|
|
74
|
+
const toleranceExceptions = tolerance.results
|
|
75
|
+
.filter((record) => record.state === 'exception')
|
|
76
|
+
.map((record) => ({ po_no: record.po_no, line_no: record.line_no, reason: record.reason }))
|
|
77
|
+
.sort((a, b) => `${a.po_no}|${a.line_no}`.localeCompare(`${b.po_no}|${b.line_no}`))
|
|
78
|
+
|
|
79
|
+
const summary = {
|
|
80
|
+
package: 'dsh-ap-three-way',
|
|
81
|
+
sample: 'synthetic/quickstart',
|
|
82
|
+
imported: { invoices: imported.invoices, po: imported.po, grn: imported.grn, skipped: imported.skipped },
|
|
83
|
+
match: { matched: match.matched, exceptions: match.exceptions, exception_detail: exceptions },
|
|
84
|
+
tolerance: {
|
|
85
|
+
price_bps: 1200,
|
|
86
|
+
matched: tolerance.matched,
|
|
87
|
+
exceptions: tolerance.exceptions,
|
|
88
|
+
exception_detail: toleranceExceptions,
|
|
89
|
+
},
|
|
90
|
+
duplicates: {
|
|
91
|
+
lines: duplicates.lines,
|
|
92
|
+
duplicates: duplicates.duplicates.map((item) => ({
|
|
93
|
+
supplier: item.supplier,
|
|
94
|
+
po_no: item.po_no,
|
|
95
|
+
line_no: item.line_no,
|
|
96
|
+
occurrences: item.occurrences,
|
|
97
|
+
})),
|
|
98
|
+
},
|
|
99
|
+
xml: { rows: xml.rows, supplier: xml.supplier },
|
|
100
|
+
workpaper: {
|
|
101
|
+
sheets: workbook.sheets.map((sheet) => sheet.name),
|
|
102
|
+
rows: workbook.sheets.map((sheet) => sheet.rows.length),
|
|
103
|
+
},
|
|
104
|
+
input_sha256: {
|
|
105
|
+
'invoices.csv': sha(invoicesCsv),
|
|
106
|
+
'po.csv': sha(poCsv),
|
|
107
|
+
'grn.csv': sha(grnCsv),
|
|
108
|
+
'invoices-duplicate.csv': sha(duplicateCsv),
|
|
109
|
+
'invoice-sample.xml': sha(invoiceXml),
|
|
110
|
+
},
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
if (process.argv.includes('--json')) {
|
|
114
|
+
process.stdout.write(`${JSON.stringify(summary, null, 2)}\n`)
|
|
115
|
+
return
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const lines = [
|
|
119
|
+
'dsh-ap-three-way quickstart - synthetic sample, not customer data',
|
|
120
|
+
`[1/5] import invoice/PO/GRN CSV .... inv=${imported.invoices} po=${imported.po} grn=${imported.grn}`,
|
|
121
|
+
`[2/5] three-way match (1% price) ... matched=${match.matched} exceptions=${match.exceptions}`,
|
|
122
|
+
`[3/5] export workpaper ............ ${workbook.sheets.map((sheet) => sheet.name).join('/')} rows=${workbook.sheets.map((sheet) => sheet.rows.length).join('/')}`,
|
|
123
|
+
`[4/5] tolerance match (12%) ....... matched=${tolerance.matched} exceptions=${tolerance.exceptions}`,
|
|
124
|
+
`[5/5] duplicate lines / XML import ${duplicates.duplicates.length} duplicate / ${xml.rows} XML row`,
|
|
125
|
+
`result: matched=${match.matched} exceptions=${match.exceptions} tolerance_matched=${tolerance.matched}`,
|
|
126
|
+
`exceptions: ${exceptions.map((item) => `${item.po_no}#${item.line_no}:${item.reason}`).join(', ') || 'none'}`,
|
|
127
|
+
'quickstart ok',
|
|
128
|
+
]
|
|
129
|
+
process.stdout.write(`${lines.join('\n')}\n`)
|
|
130
|
+
} finally {
|
|
131
|
+
await rm(baseDir, { recursive: true, force: true })
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
await run()
|
package/screenshots.json
CHANGED
|
@@ -1,4 +1,15 @@
|
|
|
1
1
|
[
|
|
2
|
+
{
|
|
3
|
+
"path": "docs/assets/quickstart.png",
|
|
4
|
+
"kind": "quickstart",
|
|
5
|
+
"alt": "dsh-ap-three-way quickstart run on the shipped synthetic sample",
|
|
6
|
+
"caption": "Real run: node samples/quickstart/run.mjs on samples/quickstart/input; output matches samples/quickstart/expected/result.json.",
|
|
7
|
+
"command": "node samples/quickstart/run.mjs",
|
|
8
|
+
"run_at": "2026-11-02T20:31:15+08:00",
|
|
9
|
+
"output_sha256": "0ea9da77541b50a22e5316e1b0540785aac11ee3b00d66aaa97faf14ced577e2",
|
|
10
|
+
"log_sha256": "2bc7990976fafe5d136760926dd4d4da4411a9cecb2d0ae16b668a82b59e2404",
|
|
11
|
+
"log": "docs/assets/quickstart.txt"
|
|
12
|
+
},
|
|
2
13
|
{
|
|
3
14
|
"path": "docs/assets/dsh-ap-three-way-hero.png",
|
|
4
15
|
"kind": "hero",
|
|
@@ -16,5 +27,11 @@
|
|
|
16
27
|
"kind": "capability",
|
|
17
28
|
"alt": "dsh-ap-three-way real test run",
|
|
18
29
|
"caption": "Real command: node --test test/ap-tolerance.test.mjs — 4 tests passed, 0 failed (configurable price/quantity/amount tolerances). Run 2026-11-01; the image is rendered from the captured terminal output."
|
|
30
|
+
},
|
|
31
|
+
{
|
|
32
|
+
"path": "docs/assets/dsh-ap-three-way-capability2.png",
|
|
33
|
+
"kind": "capability",
|
|
34
|
+
"alt": "dsh-ap-three-way second capability run",
|
|
35
|
+
"caption": "Real command: node --test test/duplicates.test.mjs — 3 tests passed, 0 failed (Duplicate invoice line detection before matching.) Run 2026-11-01; rendered from the captured terminal output."
|
|
19
36
|
}
|
|
20
37
|
]
|