Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b49f25a2bc | ||
|
|
b1769d8a25 | ||
|
|
0582bc7898 | ||
|
|
6d310ba945 | ||
|
|
41e0bfba71 | ||
|
|
b5dd3560b6 | ||
|
|
ec513adf38 | ||
|
|
9e591cc146 | ||
|
|
05dbdb17af | ||
|
|
a2963c736c | ||
|
|
b017e1fc48 | ||
|
|
cbef6d0ef6 | ||
|
|
10852eb198 | ||
|
|
b21d92efae | ||
|
|
4b3a899e5a | ||
|
|
a83f78b140 | ||
|
|
05dfd0f5bb | ||
|
|
d40ab9648d | ||
|
|
b17f7ad722 | ||
|
|
9e7275f09b |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "seal-use",
|
||||
"version": "0.11.12",
|
||||
"version": "0.11.14",
|
||||
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
|
||||
"author": {
|
||||
"name": "yingqing"
|
||||
|
||||
@@ -7,6 +7,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.11.14] - 2026-10-22
|
||||
|
||||
### Added
|
||||
- 审核记录 `list/search` 新增 `--has-extra-risk`,按系统检测的 `warning/error` 筛选额外风险,返回风险明细、数量与无法判断的记录数;沿用现有查询条件和分页,100 条为共享单页上限,没有独立的总量限制(#257)。
|
||||
|
||||
### Fixed
|
||||
- 合思与 Seal 协助链接自动返回实际人员姓名及已核实的角色或权限;身份查询失败明确标记未核实,Skill 要求汇报人员姓名、目标系统、权限和有效期(#258)。
|
||||
|
||||
## [0.11.13] - 2026-10-20
|
||||
|
||||
### Added
|
||||
- Merge pull request #254 from yunyingk/mac15/safe-document-file-editing
|
||||
- Preserve auth exit codes when document readback fails
|
||||
- Add safe knowledge document file editing
|
||||
- Merge pull request #255 from yunyingk/mac15/expense-document-lookup
|
||||
- Fix platform-dependent config selection test
|
||||
- Add expense store lookup by document number
|
||||
- Merge pull request #242 from yunyingk/mac15/clean-report-templates-and-assets
|
||||
- Merge pull request #243 from yunyingk/mac15/invoices-flatten-and-conflict-trace
|
||||
|
||||
|
||||
## [0.11.12] - 2026-10-17
|
||||
|
||||
### Added
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "seal-use",
|
||||
"version": "0.11.12",
|
||||
"version": "0.11.14",
|
||||
"private": true,
|
||||
"description": "Seal tenant operations toolkit: approval-run diagnosis, rule remediation, Hose/合思 auth, plus a CLI and an optional MCP server.",
|
||||
"license": "MIT",
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
---
|
||||
name: seal-use
|
||||
description: "v0.11.12: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
|
||||
description: "v0.11.14: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
|
||||
metadata:
|
||||
version: 0.11.12
|
||||
short-description: Seal tenant and Hose approval automation (v0.11.12)
|
||||
version: 0.11.14
|
||||
short-description: Seal tenant and Hose approval automation (v0.11.14)
|
||||
---
|
||||
|
||||
# Seal Use
|
||||
@@ -123,14 +123,16 @@ Hose 专属命令应从命令名或选项中明确可见:`auth hose-*`、`appr
|
||||
| --- | --- | --- |
|
||||
| 第一次接入、不会找凭据、需要截图 | `references/first-time-user.md` | 用户交付材料后,再读 `enterprise-onboarding.md` 做来源决策 |
|
||||
| 判断材料来源、Token 边界、cURL、Hose 提权 | `references/enterprise-onboarding.md` | 需要具体域名/员工探测时,再读 `hose-enterprise-init.md` |
|
||||
| Hose 登录检查、认证失败、生成授权链接 | `references/hose-enterprise-auth.md` | 需要重新接入或判断材料类型时,先读 `enterprise-onboarding.md` |
|
||||
| Hose 登录检查、认证失败、合思/Seal 协助链接及登录人员身份 | `references/hose-enterprise-auth.md` | 需要重新接入或判断材料类型时,先读 `enterprise-onboarding.md` |
|
||||
| Hose 域名探测、角色/员工发现、管理员选择 | `references/hose-enterprise-init.md` | 不要先加载部署或规则文档 |
|
||||
| 配置、同步或排查发布到 HoseCloud | `references/hose-enterprise-deploy.md` | 涉及生产/测试配对或模拟时,再读 `staging-simulation-workflow.md` |
|
||||
| 生产草稿、测试同步、模拟、回归、发布 | `references/staging-simulation-workflow.md` | 需要客诉证据定界时,再读 `customer-feedback-rule-remediation.md` |
|
||||
| 按单号、SN、record ID 查审批、结论、引用规则或直达链接 | `references/approval-run-lightweight.md` | 明确涉及附件/OCR/发票争议时,转读 `approval-attachment-trace.md` |
|
||||
| 单号对应费用是否入库、数据管理费用明细、费用库检索或记录关联 | `references/expense-data.md` | 明确要求审批结论时,再读 `approval-run-lightweight.md` |
|
||||
| CLI 参数、退出码或命令语法 | `references/cli.md` | 只查业务流程时不要加载本文件 |
|
||||
| Webhook 资源包(ZIP/Excel 结构、附件校验、策略配置) | `references/webhook-resource-pack.md` | 只查命令语法时读 `cli.md`,不要加载本文件 |
|
||||
| 规则数量、摘要列表、历史规则、编号重排、制度文档(`documents`)或知识搜索 | `references/rule-lightweight.md` | 需要质量评分/模糊表述检查时,改读 `rule-lint.md` |
|
||||
| 规则数量、摘要列表、历史规则、编号重排或规则搜索 | `references/rule-lightweight.md` | 需要质量评分/模糊表述检查时,改读 `rule-lint.md` |
|
||||
| 制度/知识文档(`documents`)、正文文件导出编辑、文档更新/删除或本地快照 | `references/documents.md` | 只查命令参数时读 `cli.md` |
|
||||
| 规则质量评分、lint、发布前质检 | `references/rule-lint.md` | 不要把 lint 问题直接当成客诉根因 |
|
||||
| 客诉、截图/通知、预期业务行为,并要求诊断或修改规则 | `references/customer-feedback-rule-remediation.md` | 只有该流程明确要求附件追踪或测试发布时,才追加对应 reference |
|
||||
| Langfuse trace 检索、observation IO、session 大纲、规则/附件流追踪 | `references/langfuse-trace.md` | 已定位到 trace 后需要附件归因时,再读 `approval-attachment-trace.md` |
|
||||
|
||||
@@ -16,6 +16,31 @@ Default output is intentionally small: `recordId`, `sourceDocumentSN`, `sourceDo
|
||||
|
||||
If there are multiple candidates and `--latest` was not used, report the candidates and ask which one to inspect.
|
||||
|
||||
## Find Runs With Extra Risks
|
||||
|
||||
审核结果区分 `result.rulesResult[].findings`(绑定规则的检查发现)与 `result.otherFindings[]`(额外发现)。额外发现中的 `warning` / `error` 计为额外风险,`info` 仅为提示;不根据最终审批结论或摘要文本推断额外风险。
|
||||
|
||||
前端将规则内发现映射为 `source: "rule"`,额外发现映射为 `source: "system"` 并标注“系统检测”。这是展示层根据字段来源派生的分类,不是当前审核列表接口已接入的筛选参数。“系统检测”也可能是 `info`,因此不能将全部系统检测项都计为风险。原始等级枚举为 `info / warning / error`;页面的“需复核”还可能由规则的 `UNCERTAIN` 结论派生。
|
||||
|
||||
```bash
|
||||
# 从最近一页 100 条记录中筛出含额外风险的记录
|
||||
seal-use approval-runs list --has-extra-risk --limit 100 --corp <corpId>
|
||||
|
||||
# 在时间、运行状态、人工结果等条件下筛选
|
||||
seal-use approval-runs search --has-extra-risk --status completed --startDate 2026-10-01 --endDate 2026-10-22 --limit 100 --corp <corpId>
|
||||
|
||||
# 继续检查下一页;offset 按上游记录数推进,不按 matched 推进
|
||||
seal-use approval-runs list --has-extra-risk --limit 100 --offset 100 --corp <corpId>
|
||||
```
|
||||
|
||||
- `limit` 是筛选前读取的页大小(默认 50,最多 100),不会为凑满命中数自动翻页。`offset` 同样作用于上游结果集。
|
||||
- `scanned` 是本页上游返回的条数,`matched` 是所有本地筛选后的返回条数。`total` 保留上游筛选条件下的记录总数,**不是额外风险单据总数**。
|
||||
- 启用筛选时,`unknown` 是通过其他本地条件后,因结果缺失或格式异常而无法判断额外风险的条数。这些记录不混入命中列表;无筛选读取时,可通过 `extraFindingsStatus: "unknown"` 定位。
|
||||
- 记录摘要包含 `otherFindingCount`(含 info 的额外发现总数)、`extraRiskCount`、`hasExtraRisk`、`extraFindingsStatus`。空数组表示已知无额外发现;缺失/异常数据的数量和布尔值为 `null`。
|
||||
- 本筛选读取结构化的 `otherFindings`。前端还会转换旧版结果中的 `otherRisks` 等字段,但本筛选不推断旧版关联关系;未提供 `otherFindings` 的历史记录计为 `unknown`。
|
||||
- 启用筛选时,每条命中记录附带 `extraRisks`,含风险标题、等级和描述。一次审核可能有多个风险,`matched` 按审核记录计数;同一单据多次审核也可能返回多条记录。
|
||||
- `approval-runs result <recordId> --summary` 和 `get <recordId> --summary` 的 AI 结果也返回上述计数字段。查看全部额外发现可用 `get <recordId> --fields result.otherFindings`。
|
||||
|
||||
## Read Compact Run Detail
|
||||
|
||||
Use `--summary` for most diagnosis and support questions.
|
||||
|
||||
@@ -98,7 +98,7 @@ seal-use approval-runs stats [--since 3months] [--dedupe-by sourceDocumentSN|sou
|
||||
seal-use approval-runs count [--status APPROVED] [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>] [--corp <corpId>]
|
||||
seal-use approval-runs export [--sn <SN1,SN2>] [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>] [--force] [--status <status>] [--manual-status <status>] [--completed-only] [--limit <n>] [--downloads|--to-downloads] [--with-flow] [--out <file>] [--corp <corpId>]
|
||||
seal-use approval-runs hose-flow <recordId|SN> [--corp <corpId>]
|
||||
seal-use approval-runs list|search [--query text] [--humanResult 驳回] [--manualApprovalStatus TERMINATED] [--startDate ms] [--endDate ms] [--limit 20] [--includeBridge true] [--corp <corpId>]
|
||||
seal-use approval-runs list|search [--query text] [--humanResult 驳回] [--manualApprovalStatus TERMINATED] [--startDate ms] [--endDate ms] [--has-extra-risk] [--limit 20] [--includeBridge true] [--corp <corpId>]
|
||||
seal-use approval-runs pick --sn <documentSN> [--batch <batchId>] [--latest] [--fields recordId,status,aiDecision] [--corp <corpId>]
|
||||
seal-use approval-runs get <recordId> [--summary] [--fields metadata|document.fields,result.summary] [--full] [--output-file file.json] [--corp <corpId>]
|
||||
seal-use approval-runs cited-rules <recordId> [--corp <corpId>]
|
||||
@@ -183,8 +183,12 @@ seal-use contacts departments [<departmentId>] [--corp <corpId>]
|
||||
seal-use contacts children <departmentId> [--corp <corpId>]
|
||||
seal-use contacts users <departmentId> [--corp <corpId>]
|
||||
seal-use contacts sync-time [--corp <corpId>]
|
||||
seal-use data expenses [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--corp <corpId>]
|
||||
seal-use data invoices [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--corp <corpId>]
|
||||
seal-use data expenses [--sn <documentSN>|--record-id <recordId>|--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--max-scan <n>] [--corp <corpId>]
|
||||
seal-use data invoices [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--full] [--corp <corpId>]
|
||||
seal-use invoices [list] [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--full] [--corp <corpId>]
|
||||
seal-use invoices trace <invoiceNumber> [--corp <corpId>]
|
||||
seal-use invoices <invoiceNumber> [--corp <corpId>]
|
||||
seal-use expenses [list] [--sn <documentSN>|--record-id <recordId>|--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--max-scan <n>] [--corp <corpId>]
|
||||
seal-use llm config [--corp <corpId>]
|
||||
seal-use llm providers [--corp <corpId>]
|
||||
seal-use permissions available [--corp <corpId>]
|
||||
@@ -199,12 +203,12 @@ seal-use analytics analyze <recordId> [--corp <corpId>]
|
||||
seal-use analytics export [--downloads] [--out <file>] [--start-date <ISO>] [--end-date <ISO>] [--force] [--limit <n>] [--corp <corpId>]
|
||||
seal-use context [--ruleVersion <versionId|versionNumber|latest>] [--documentLimit 50] [--corp <corpId>]
|
||||
seal-use source config [--corp <corpId>]
|
||||
seal-use documents list [--scenarios <audit,fill>] [--limit 50] [--offset 0] [--corp <corpId>]
|
||||
seal-use documents get <documentId> [--corp <corpId>]
|
||||
seal-use documents list [--summary] [--fields <id,title,purpose,updatedAt>] [--scenarios <audit,fill>] [--limit 50] [--offset 0] [--corp <corpId>]
|
||||
seal-use documents get <documentId> [--out <path>] [--content-format raw] [--overwrite] [--corp <corpId>]
|
||||
seal-use documents search <keyword> [--maxResults 20] [--corp <corpId>]
|
||||
seal-use documents create --title <title> --purpose <purpose> [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]
|
||||
seal-use documents update <documentId> [--title <title>] [--purpose <purpose>] [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--enabled <true|false>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]
|
||||
seal-use documents delete <documentId> --yes [--corp <corpId>]
|
||||
seal-use documents create --title <title> --purpose <purpose> [--content <text>|--content-file <path>] [--content-format raw] [--allow-empty] [--type <policy|document|video|pdf|feishu_doc>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--dry-run|--yes|--confirm] [--corp <corpId>]
|
||||
seal-use documents update <documentId> [--title <title>] [--purpose <purpose>] [--content <text>|--content-file <path>] [--content-format raw] [--allow-empty] [--type <policy|document|video|pdf|feishu_doc>] [--enabled <true|false>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--dry-run|--yes|--confirm] [--corp <corpId>]
|
||||
seal-use documents delete <documentId> [--dry-run|--yes|--confirm] [--corp <corpId>]
|
||||
seal-use update [--check] [--force] [--version <v>]
|
||||
seal-use update check
|
||||
seal-use update changelog [--limit <n>]
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
# 知识文档:文件编辑与安全更新
|
||||
|
||||
## 列表与读取
|
||||
|
||||
```bash
|
||||
seal-use documents list --summary --corp <corpId>
|
||||
seal-use documents list --fields id,title,purpose,updatedAt --corp <corpId>
|
||||
seal-use documents get <documentId> --corp <corpId>
|
||||
```
|
||||
|
||||
`list` 默认保留既有完整 JSON;`--summary` 返回 id、title、purpose、contentType、status、enabled、scenarios、tags、updatedAt,不返回 content。显式 `--fields` 覆盖摘要字段,非法字段报 exit 2。分页、过滤、total 不变;投影在客户端完成,不能据此声称减少了上游网络流量,也不会逐篇请求详情。
|
||||
|
||||
`get` 默认输出完整文档 JSON,正文位于 `content`。`--output-file <path>` 保存整份 JSON;`--out <path>` 单独导出正文,两者互斥。
|
||||
|
||||
## 导出 → 编辑 → 预览 → 更新
|
||||
|
||||
```bash
|
||||
seal-use documents get <documentId> --out ./document.txt --corp <corpId>
|
||||
# 编辑 document.txt;保留相邻的 document.txt.seal-use.json
|
||||
seal-use documents update <documentId> --content-file ./document.txt --dry-run --corp <corpId>
|
||||
seal-use documents update <documentId> --content-file ./document.txt --yes --corp <corpId>
|
||||
```
|
||||
|
||||
导出产生三个本地文件:指定路径的 UTF-8 正文、相邻的 `.seal-use.json` 来源清单、配置目录 `document-history/` 下的原文快照。stdout 仍是 JSON 回执,包含路径、字节数、内容哈希和 snapshotId;文件权限为 0600,历史目录为 0700。正文不插入标题或 frontmatter,不 trim、不补末尾换行。扩展名可以是 `.md`,但不会改变编码行为。目标父目录须已存在;覆盖既有导出必须显式 `--overwrite`,目录和符号链接不可覆盖。
|
||||
|
||||
本期只支持 raw;`--content-format raw` 可显式指定。正文中的反斜杠、转义竖线、硬换行、代码与路径全部保持。Markdown 自动互转尚未开放,`--content-format markdown` 报 exit 2。不要批量替换 `\\` 或 `\|`:平台编码尚需真实脱敏样本证明可逆,JSON 显示转义也不能当作存储协议。
|
||||
|
||||
更新自动读取相邻来源清单,核对企业、Seal 服务地址与文档身份,并比较本次拟修改字段的导出基线哈希。远端变化返回 exit 1、`DOCUMENT_CONFLICT`,不会写入;`--yes` 不能绕过。重新导出并合并编辑后再预览。存在但损坏的清单报 exit 13,不会退化成无基线更新。
|
||||
|
||||
没有清单的旧 `--content-file` / `--content` 输入仍支持,但 preview、stderr 和回执明确 `baselineAvailable:false`,无法发现编辑期间发生的他人修改。不要为了绕过冲突删除清单。一次成功更新后,如需继续编辑,应重新导出新基线;保留本地修改前先自行留存,`--overwrite` 会覆盖正文。
|
||||
|
||||
仅传 `--content-file` 时,PATCH 只提交 content;title、purpose、status、enabled、scenarios、tags 保持。多个正文来源同时给出报 exit 2;非法 UTF-8、文件不可读或清单不可用报 exit 13。空或纯空白正文默认拒绝;明确要清空时加 `--allow-empty`。未变化的内容返回 `changed:false`,不写远端、不产生更新快照。
|
||||
|
||||
## 写入安全与兼容变化
|
||||
|
||||
所有 documents 创建、更新、删除正式执行均要求 `--yes` 或 `--confirm`,否则 exit 10。旧创建和更新脚本必须补确认标志。`--dry-run` 始终只读,即使同时提供确认标志也不写远端;预览不写历史快照。预览返回 `preview:true` 和结构化 `changesDiff`;内容过大时使用 `--output-file` 或有意选择 `--full`,仍遵守 exit 12 输出保护。
|
||||
|
||||
```bash
|
||||
seal-use documents create --title <title> --purpose <purpose> --content-file ./document.txt --dry-run --corp <corpId>
|
||||
seal-use documents create --title <title> --purpose <purpose> --content-file ./document.txt --yes --corp <corpId>
|
||||
seal-use documents delete <documentId> --dry-run --corp <corpId>
|
||||
seal-use documents delete <documentId> --yes --corp <corpId>
|
||||
```
|
||||
|
||||
创建/更新成功回执改为紧凑执行结果,不再输出整篇文档;需要全文时重新 `get`。正式更新和删除前先保存实际将被覆盖的完整文档快照,备份失败则不写远端。创建和更新后回读,只有正文及预期保留字段核对通过才返回 `verified:true`。写请求禁用自动重试。
|
||||
|
||||
更新错误同时返回 JSON 状态和非零退出码:
|
||||
|
||||
- `DOCUMENT_CONFLICT`:未执行写入,重新导出并审阅。
|
||||
- `DOCUMENT_WRITE_UNCERTAIN`:写入结果不确定,`executed:null`;先用返回的只读 next action 回读,不能盲目重跑。
|
||||
- `DOCUMENT_READBACK_FAILED`:已完成写请求,回读失败,`executed:true, verified:false`。
|
||||
- `DOCUMENT_VERIFICATION_FAILED`:回读和预期不符,保留 snapshotId / snapshotFile,核对当前状态后处理。
|
||||
- `DOCUMENT_AUTH_FAILED`:认证失败,exit 11;其他上述失败一般 exit 1。
|
||||
|
||||
创建请求失败时可能无法取得新文档 ID,应先查看列表,避免重复创建。删除成功表示服务端已接受删除;快照保留原对象,但重建不承诺保留原文档 ID。错误结果不会自动再次覆盖,也不会自动回滚。快照记录采集阶段,不能仅凭快照存在判断后续写入是否成功。
|
||||
|
||||
## 本地恢复、草稿和平台版本边界
|
||||
|
||||
历史默认位于当前配置文件所在目录的 `document-history/<来源哈希>/<snapshotId>.json`。包含正文和元数据,视为敏感业务数据,勿加入项目 Git。首期不自动清理快照,也没有快照浏览/一键恢复命令。
|
||||
|
||||
需要恢复时先回读当前文档,读取快照的 `document.content` 写成独立正文文件,再预览并确认更新;标题/状态等仅在明确需要时逐项传入。不要把整个快照当 PATCH 上传,不要覆盖作者、时间戳等系统字段。恢复本身是一次新更新,仍需备份与回读。
|
||||
|
||||
当前 CLI 有 `--status draft` 输入,但未验证其是否允许“旧发布版继续生效,同时编辑新草稿”。不要为了获得本地编辑稿而修改线上 status。文档更新可能立即影响生产;已发布版本与草稿并存、跨设备完整版本历史、原生回滚和原子条件写入属于待验证的平台能力。
|
||||
|
||||
客户端 GET→PATCH 之间仍有竞态窗口;哈希检查不能替代服务端 If-Match/修订号条件更新。本地快照只覆盖本机 CLI 留存过的内容,不能称为平台原生版本历史。
|
||||
@@ -0,0 +1,60 @@
|
||||
# 费用明细:按单号核验入库
|
||||
|
||||
## 首选入口
|
||||
|
||||
用户问“某单据的费用明细是否进入 SealAI 数据管理 → 费用明细”时,先确定目标企业,再运行:
|
||||
|
||||
```bash
|
||||
seal-use expenses --sn <documentSN> --corp <corpId>
|
||||
```
|
||||
|
||||
这是只读查询,使用同一个 `sealExpensesList` 内部能力和既有 MCP 网关,不触发同步、审批或费用写入。`data expenses --sn` 与该入口等价。不要把查询扩大为自动补录或重新审核。
|
||||
|
||||
## 已验证的关联路径
|
||||
|
||||
2026-10-20 对测试站点公开前端契约和测试企业进行只读往返验证:费用列表支持 `filter.recordId`,返回 `id`、`documentId`、`recordId` 等字段;普通文本搜索用于费用类型、描述、金额。同一已存在费用对应的原单号作为普通搜索词时未命中,按关联审批记录 ID 筛选则命中。因此不能用 `--search <单号>` 的空结果判断未入库,也不能仅因审批记录存在就说费用已入库。
|
||||
|
||||
CLI 先分页查询单号候选审批记录,对 `sourceDocumentSN` 做精确相等匹配,再对每个匹配记录调用费用列表的 `filter[recordId]`。返回的费用必须与请求记录 ID 一致;若双方都有 documentId,还必须一致。重审/重放产生的多个记录均纳入查询,不默认只查最新一次;费用按稳定费用 ID 去重,不按单号去重。
|
||||
|
||||
单号对应多个不同来源单据时返回 `ambiguous_source_documents`,不混合归因。费用列表本身没有已验证的单号直接过滤;找不到关联审批记录时返回 `approval_link_not_found` 和“无法确定”,无法凭该路径排除孤立费用记录。必要时取得明确关联记录 ID,用下面的原始列表入口补查。
|
||||
|
||||
## 结论判定
|
||||
|
||||
- `status:found, found:true`:至少一条费用已从费用库读取并通过关联校验。`matchedCount` 是已观察到的去重条数,`complete:false` 时仅为下限。
|
||||
- `status:not_found, found:false, complete:true`:单号匹配到的可见审批记录及其费用分页均已查完,指定费用日期范围内未找到关联费用。对外表述“关联范围内未找到”,不要断言该单据从未入库或推断入库失败根因。
|
||||
- `status:unknown, found:null, complete:false`:没有足够证据确认存在或不存在。常见原因包括没有审批关联、同号多原单据、扫描上限、分页重复/变化、关联字段不符或接口失败。
|
||||
|
||||
所有结果都有 `source:seal_expense_store`、`verification:existence_only`、查询时间、queryScope、scanned、关联记录及费用摘要;摘要不输出员工手机号和邮箱。不得把存在性查询解释成“所有原始费用明细均完整入库”;逐项完整性对账需另有原单明细和稳定行标识。
|
||||
|
||||
## 日期、分页和上限
|
||||
|
||||
单号查询不自动添加本月或最近一年范围;显式日期只过滤费用列表,不过滤用于定位的审批记录创建日期:
|
||||
|
||||
```bash
|
||||
seal-use expenses --sn <documentSN> --start-date 2025-01-01 --end-date 2025-12-31T23:59:59+08:00 --corp <corpId>
|
||||
seal-use expenses --sn <documentSN> --limit 100 --max-scan 10000 --corp <corpId>
|
||||
```
|
||||
|
||||
queryScope.startDate/endDate 是规范化毫秒时间戳,null 表示未显式传入;不代表服务端所有历史数据都永久可见。费用记录时间戳和 checkedAt 使用北京时间 ISO 秒级格式。
|
||||
|
||||
单号查询中 `--limit` 为每页大小(1–100,默认 100),不是最多返回匹配条数。审批候选扫描和费用扫描各最多 `--max-scan` 条(默认 5000,最高 10000);整个流程最多发起 100 次业务分页调用。命中上限保留已发现证据,标记 `complete:false`,不会以不完整查询得出否定结论。HTTP 层安全 GET 重试不包含在业务分页调用计数中。
|
||||
|
||||
总数缺失或变化、重复页、过早空页、记录变化、响应超出页大小都不能认为查询完整。分页不是数据库快照,`complete:true` 只表示当前观察到的相关分页已遍历,不是对并发写入的事务保证。
|
||||
|
||||
`--sn` 与 `--search`、`--record-id`、`--offset` 互斥;`--max-scan` 仅用于 `--sn`。非法组合报 exit 2,扫描范围参数未通过 schema 校验报 exit 13。
|
||||
|
||||
## 普通费用列表
|
||||
|
||||
```bash
|
||||
seal-use expenses list --search <text> --offset 0 --limit 50 --corp <corpId>
|
||||
seal-use expenses list --record-id <recordId> --corp <corpId>
|
||||
seal-use data expenses --record-id <recordId> --corp <corpId>
|
||||
```
|
||||
|
||||
不传 `--sn` 时继续返回原始 `{expenses,total}`,不进行入库判定;`--record-id` 透传精确关联过滤,普通列表由调用者控制分页。列表请求始终包含平台要求的 filter 对象,未指定筛选时发送空搜索值。日期支持 ISO 或时间戳,并转换为接口所需毫秒值。未知子命令和裸位置单号会报用法错误,不会被忽略后返回无关列表。
|
||||
|
||||
## 失败和大结果
|
||||
|
||||
单号查询接口失败时 stdout 保留结构化查询状态,stderr 说明不完整,进程返回非零:认证失败 exit 11,其他上游/响应格式失败 exit 1。已有确切匹配仍保留 `found:true`,但 `complete:false`;没有匹配证据时保持 unknown。不能把失败当作未入库。
|
||||
|
||||
大结果可使用 `--output-file <path>` 保存 JSON,或有意选择 `--full` 放开现有输出保护;默认超过输出限制返回 exit 12。原始费用列表和结构化单号查询均遵守 stdout 纯 JSON。
|
||||
@@ -67,8 +67,21 @@ Important:
|
||||
- `seal-use auth check` proves this stage works but redacts the token, so it is not enough when the user needs the actual clickable Hose link.
|
||||
- **Dedicated CLI Command**: Use `seal-use auth hose-link --corp <corpId> [--expire <duration>] [--force]`. This command directly generates an independent provisional auth link without reading or mutating internal CLI session cache. It supports `--expire` (default `2h`, e.g. `7d` or `7200`).
|
||||
- **Formatting Requirement**: When returning a Hose authorization link (`auth hose-link`) to the user, directly use the CLI JSON output:
|
||||
1. The operator identity: directly display the returned `staffId` (or `staffName` if present in output; do NOT make additional network calls or auth checks to search for personal names),
|
||||
1. The operator identity: **always report the person's name from `staffName`**. The CLI automatically looks up the exact Hose employee for `auth hose-link`, and the actual Seal session user for `auth link`. Do not use `staffId` as a person's name, infer a name from an ID, or assume both systems use the same person. If `identityStatus` is `unresolved` (`staffName: null`), explicitly report that the identity name could not be verified; do not silently omit it or guess,
|
||||
2. The exact expiration time in Beijing time (`expiresAt`),
|
||||
3. BOTH a code block (` ```text ... ``` `) for easy copying without accidental default browser redirection, AND a clickable hyperlink.
|
||||
- **Seal AI Platform Direct Link**: If the user needs a delegation link for the Seal AI audit platform (`https://*.sealai.cc`) instead of Hose/易快报, use `seal-use auth link --corp <corpId> [--note <note>]`.
|
||||
|
||||
## Assistance link identity and reporting contract
|
||||
|
||||
This contract applies to both `auth hose-link` and `auth link`, including `auth link --from-link`.
|
||||
|
||||
- `staffName` is the verified person's name, or `null`; `identityStatus` is `resolved` / `unresolved`. Identity lookups do not switch the configured employee, modify enterprise configuration, reset a password, or request additional privileges.
|
||||
- Hose links return `roleNames` from that exact employee's role assignments. `null` means role names could not be verified; an empty array means the employee response explicitly contained no roles. Never infer “主管理员” merely because the CLI can generate a link.
|
||||
- Seal links return the actual session user's `isAdmin` and `permissions`. Report administrative access only when confirmed by those fields; `null` means the lookup failed. Seal permissions describe Seal access and must not be presented as Hose permissions.
|
||||
- If an identity lookup fails, the generated link remains usable, the command returns `staffName: null` / `identityStatus: "unresolved"`, and a diagnostic is written to `stderr`. Additional role-lookup failure preserves a verified name but returns `roleNames: null`. Never claim that an unresolved identity is an administrator.
|
||||
- A user-facing link report must include **enterprise name, person's name, verified role/permissions (or explicitly unknown), target system, and exact Beijing expiration time**. Include both a code block and a clickable link. If returning Hose and Seal links together, report identity and permissions separately for each.
|
||||
- Do not show raw tokens, full phone numbers, or internal IDs as explanatory prose. Do not fetch or list unrelated administrator candidates just to describe the identity of an existing link.
|
||||
|
||||
Example presentation: “企业:示例公司;合思登录身份:张三(主管理员);有效期至北京时间 …”;“Seal 登录身份:李四(依据 CLI 返回的管理员标记及权限说明);有效期至北京时间 …”。The names may differ; use each command's actual output.
|
||||
|
||||
@@ -167,30 +167,33 @@ sequenceDiagram
|
||||
Agent->>CLI: 4. seal-use report validate 报告.md
|
||||
CLI-->>Agent: 门禁通过 (valid: true)
|
||||
|
||||
Agent->>CLI: 5. seal-use report render 报告.md --out build/报告/
|
||||
Agent->>CLI: 5. seal-use report render 报告.md --out <输出目录>/报告/
|
||||
CLI-->>User: 交付单文件 HTML、A4 PDF 与长图 PNG
|
||||
```
|
||||
|
||||
#### 具体操作指令:
|
||||
```bash
|
||||
# 步骤 1:一键拉取指定周期的全量明细台账(含 AI 完整意见与人工批注)
|
||||
seal-use report ledger --start-date 2026-08-12 --end-date 2026-09-18 --corp <corpId> --out reports/明细台账.xlsx
|
||||
seal-use report ledger --start-date 2026-08-12 --end-date 2026-09-18 --corp <corpId> --out <输出目录>/明细台账.xlsx
|
||||
|
||||
# 步骤 2:Agent 或用户在 Excel 中自由裁量,增删模板行并填入裁决;
|
||||
|
||||
# 步骤 3:严格以修改后的台账为唯一事实源,出具报告草稿
|
||||
seal-use report generate --ledger reports/明细台账.xlsx --corp <corpId> --out reports/审核报告.md
|
||||
seal-use report generate --ledger <输出目录>/明细台账.xlsx --corp <corpId> --out <输出目录>/审核报告.md
|
||||
|
||||
# 步骤 4:严格门禁校验(必须通过)
|
||||
seal-use report validate reports/审核报告.md
|
||||
seal-use report validate <输出目录>/审核报告.md
|
||||
|
||||
# 步骤 5:本地全格式编译渲染
|
||||
seal-use report render reports/审核报告.md --out build/审核报告/
|
||||
seal-use report render <输出目录>/审核报告.md --out <输出目录>/审核报告/
|
||||
```
|
||||
|
||||
> [!TIP]
|
||||
> **全量取数与分页控制**:`seal-use report ledger`、`report data` 与 `report generate` 默认自动分页拉取所选时间区间内的**全部审批单据**(内置 100,000 笔安全防死循环上限),无任何 500 条的人工截断限制。如需做小样本分析或限定抓取笔数,可传入 `--limit <n>`(别名 `--max-runs <n>` / `-n <n>`,例如 `--limit 2000`)。
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **落盘位置红线(代码仓零污染)**:`seal-use` 是全局 CLI,输出目录与执行目录解耦。最终交付物以客户/用户要求为最高准则,放用户指定目录或系统下载目录(如 `~/Downloads/<企业名>-<YYYYMM>/`),**严禁在代码仓库根目录(如 `Code/seal-use/reports/`)生成或留存业务报告文件**。会话内供 Agent 快速读取的只读快照落在全局缓存 `~/.cache/seal-use/reports/<corpId>/<YYYY-MM>/`,缓存天然可丢弃、可随时清理,且不占用 `~/.config/`。
|
||||
|
||||
---
|
||||
|
||||
### 模式 B:CLI 命令行实时研讨驱动
|
||||
@@ -232,7 +235,7 @@ seal-use report render reports/审核报告.md --out build/审核报告/
|
||||
4. **离线台账批量导入**:
|
||||
若线下已在 Excel 台账中集中批量评审完毕,可一键导入持久化存储:
|
||||
```bash
|
||||
seal-use report review import reports/明细台账.xlsx --corp <corpId>
|
||||
seal-use report review import <输出目录>/明细台账.xlsx --corp <corpId>
|
||||
```
|
||||
|
||||
---
|
||||
@@ -265,6 +268,7 @@ seal-use report render reports/审核报告.md --out build/审核报告/
|
||||
- **准确率严密计算公式**(必须在正文中由 LaTeX 公式呈现):
|
||||
$$\text{AI 准确率} = \frac{D_1 + D_4}{S} = \frac{\text{双方同向一致通过数} + \text{AI 依规正确拦截数}}{\text{样本总量}}$$
|
||||
- 动态内嵌维恩图(`图 1:AI 与人工审核准确率对比.svg`),直观呈现两者的交集与重合度。
|
||||
- **图表纯粹性**:标准模板只保留这一张数据驱动维恩图;旧版图二(综合效益耗时直方图)与图三(截图占位)已全面废弃并清理,严禁再引入冗余图表或相关死代码。
|
||||
|
||||
### 3. §2 AI 判定误判分析
|
||||
- **2.1 误判构成总览**:总结在分歧复核中判定为“人工正确 / AI 判定误判”的单据总量及在全样本中的占比。
|
||||
@@ -322,7 +326,7 @@ seal-use report render reports/审核报告.md --out build/审核报告/
|
||||
|
||||
在执行最终渲染交付前,Agent **必须**执行门禁校验命令:
|
||||
```bash
|
||||
seal-use report validate reports/审核报告.md
|
||||
seal-use report validate <输出目录>/审核报告.md
|
||||
```
|
||||
|
||||
若存在任何格式或数学勾稽问题,命令将以 **退出码 1** 阻断导出,并输出带有错误代码的 JSON。Agent 必须根据报错信息自主编辑修正。
|
||||
@@ -351,10 +355,10 @@ seal-use report validate reports/审核报告.md
|
||||
|
||||
```bash
|
||||
# 一键编译全套产物(单文件 HTML、A4 PDF、超清拼接长图 PNG)
|
||||
seal-use report render reports/审核报告.md --out build/审核报告/ --format all
|
||||
seal-use report render <输出目录>/审核报告.md --out <输出目录>/审核报告/ --format all
|
||||
|
||||
# 整包打包归档(产出 ZIP / 完整文件夹,自动收拢 Markdown、配图与明细台账)
|
||||
seal-use report export reports/审核报告.md --out build/交付整包/
|
||||
seal-use report export <输出目录>/审核报告.md --out <输出目录>/交付整包/
|
||||
```
|
||||
|
||||
### 交付产物技术特性与适用场景:
|
||||
|
||||
+3
-2
@@ -107,12 +107,13 @@ describe("CLI version & help handling", () => {
|
||||
expect(result.stderr).toContain("Usage: seal-use documents get <documentId>");
|
||||
});
|
||||
|
||||
test("requires --yes confirmation on documents delete", () => {
|
||||
test("requires explicit confirmation on documents delete", () => {
|
||||
const env = makeConfigEnv();
|
||||
const result = runCli(["documents", "delete", "doc-123", "--corp", "corp-a"], env);
|
||||
|
||||
expect(result.status).toBe(10);
|
||||
expect(result.stderr).toContain("Refusing to delete document 'doc-123' without --yes.");
|
||||
expect(result.stderr).toContain("documents delete requires --yes or --confirm");
|
||||
expect(result.stderr).toContain("--dry-run");
|
||||
});
|
||||
|
||||
test("does not hijack --version option when passed to subcommands like rules", () => {
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { AREA_ALIASES, UPDATE_ALIASES, normalizeCliArea } from "./area-aliases.js";
|
||||
import { KNOWN_AREAS } from "./runner.js";
|
||||
|
||||
/**
|
||||
* Drift guard for the shared alias table.
|
||||
*
|
||||
* `read-only.ts` once hand-copied the alias pairs from `runner.ts` and the two
|
||||
* silently diverged — the exact class of bug the 2026-10-17 architecture
|
||||
* review called "two sources of truth". The tables now live in one module and
|
||||
* are imported by dispatch, help, and the read-only gateway; these tests make
|
||||
* the remaining cross-module contract explicit: an alias may only point at an
|
||||
* area the dispatcher actually handles, may not chain into another alias, and
|
||||
* must not shadow a real area name.
|
||||
*/
|
||||
|
||||
describe("area alias integrity", () => {
|
||||
test("every alias resolves to a dispatchable area", () => {
|
||||
const dangling = Object.entries(AREA_ALIASES)
|
||||
.filter(([, target]) => !KNOWN_AREAS.has(target))
|
||||
.map(([alias, target]) => `${alias} -> ${target}`);
|
||||
|
||||
expect(dangling).toEqual([]);
|
||||
});
|
||||
|
||||
test("no alias chains into another alias", () => {
|
||||
// normalizeCliArea applies one lookup; a chained alias would dispatch the
|
||||
// raw alias spelling as a command area and fail with "Unknown command".
|
||||
const chained = Object.values(AREA_ALIASES).filter((target) => target in AREA_ALIASES);
|
||||
|
||||
expect(chained).toEqual([]);
|
||||
});
|
||||
|
||||
test("alias spellings never shadow a real area name", () => {
|
||||
// KNOWN_AREAS is the handler tables plus the alias keys; subtracting the
|
||||
// alias keys recovers the real dispatch areas. An alias colliding with
|
||||
// one of them would be dead weight at best and ambiguous at worst.
|
||||
const realAreas = new Set([...KNOWN_AREAS].filter((area) => !(area in AREA_ALIASES)));
|
||||
const shadowing = Object.keys(AREA_ALIASES).filter((alias) => realAreas.has(alias));
|
||||
|
||||
expect(shadowing).toEqual([]);
|
||||
});
|
||||
|
||||
test("every update spelling normalizes onto the real update area", () => {
|
||||
for (const spelling of UPDATE_ALIASES) {
|
||||
expect(normalizeCliArea(spelling)).toBe("update");
|
||||
}
|
||||
expect(KNOWN_AREAS.has("update")).toBe(true);
|
||||
});
|
||||
|
||||
test("normalization is idempotent and case-insensitive", () => {
|
||||
expect(normalizeCliArea(normalizeCliArea("corp"))).toBe("corps");
|
||||
expect(normalizeCliArea("CORP")).toBe("corps");
|
||||
expect(normalizeCliArea("Self-Update")).toBe("update");
|
||||
});
|
||||
|
||||
test("every alias and update spelling resolves through KNOWN_AREAS", () => {
|
||||
// Alias keys must be members outright: help lookup and the read-only
|
||||
// gateway resolve the raw spelling before any normalization. Update
|
||||
// spellings are normalized first, so their canonical target is the
|
||||
// dispatchable name.
|
||||
for (const alias of Object.keys(AREA_ALIASES)) {
|
||||
expect(KNOWN_AREAS.has(alias)).toBe(true);
|
||||
}
|
||||
for (const spelling of UPDATE_ALIASES) {
|
||||
expect(KNOWN_AREAS.has(normalizeCliArea(spelling))).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,9 @@ export const AREA_ALIASES: Readonly<Record<string, string>> = {
|
||||
corp: "corps",
|
||||
webhooks: "webhook",
|
||||
preferences: "preference",
|
||||
server: "mcp"
|
||||
server: "mcp",
|
||||
invoice: "invoices",
|
||||
expense: "expenses"
|
||||
}
|
||||
|
||||
export const UPDATE_ALIASES = new Set([
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test"
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import { runCli } from "../runner.js"
|
||||
|
||||
const envKeys = ["SEAL_USE_ENTERPRISES_DIR", "SEAL_USE_CONFIG_FILE", "SEAL_USE_TOKEN_STORE", "SEAL_USE_USAGE_FILE", "SEAL_DISABLE_BG_UPDATE"] as const
|
||||
const oldEnv = Object.fromEntries(envKeys.map(key => [key, process.env[key]]))
|
||||
const oldFetch = globalThis.fetch
|
||||
let dir: string
|
||||
let requests: Request[]
|
||||
|
||||
const fixtures = [
|
||||
{ id: "warning", result: { decision: "APPROVE", otherFindings: [
|
||||
{ title: "说明", description: "仅说明", level: "info" },
|
||||
{ title: "主体差异", description: "付款主体与销方不同", level: "warning" }
|
||||
] } },
|
||||
{ id: "error", result: { decision: "REJECT", otherFindings: [{ title: "金额差异", description: "金额不一致", level: "error" }] } },
|
||||
{ id: "info", result: { otherFindings: [{ title: "说明", description: "无需处理", level: "info" }] } },
|
||||
{ id: "rule-only", result: { rulesResult: [{ id: "rule-1", findings: [{ level: "error" }] }], otherFindings: [] } },
|
||||
{ id: "missing", result: {} },
|
||||
{ id: "malformed", result: { otherFindings: "bad" } }
|
||||
].map((record, index) => ({
|
||||
...record, sourceDocumentSN: `SN-${index}`, status: "completed", createdAt: 1792639007830 - index,
|
||||
pipelineData: { humanResult: index === 0 ? "驳回" : "通过" },
|
||||
sourceExtendData: { _langfuseTraceId: `trace-${index}` }
|
||||
}))
|
||||
|
||||
beforeEach(() => {
|
||||
dir = mkdtempSync(join(tmpdir(), "seal-extra-risk-cli-"))
|
||||
const enterprises = join(dir, "enterprises")
|
||||
mkdirSync(enterprises)
|
||||
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises
|
||||
process.env.SEAL_USE_CONFIG_FILE = join(dir, "config.json")
|
||||
process.env.SEAL_USE_TOKEN_STORE = join(dir, "tokens.json")
|
||||
process.env.SEAL_USE_USAGE_FILE = join(dir, "usage.json")
|
||||
process.env.SEAL_DISABLE_BG_UPDATE = "1"
|
||||
writeFileSync(join(enterprises, "extra-risk-test.json"), JSON.stringify({
|
||||
id: "extra-risk-test", name: "Extra Risk Test", environment: "test",
|
||||
seal: { url: "https://extra-risk.example.test" },
|
||||
source: { type: "seal", token: "test-token", sealUrl: "https://extra-risk.example.test", staffId: "fixture" }
|
||||
}))
|
||||
requests = []
|
||||
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const request = new Request(input, init)
|
||||
requests.push(request)
|
||||
const url = new URL(request.url)
|
||||
if (request.method !== "GET") return Response.json({ error: "unexpected mutation" }, { status: 405 })
|
||||
if (url.pathname === "/api/v1/approvals") {
|
||||
const offset = Number(url.searchParams.get("offset") ?? 0)
|
||||
const limit = Number(url.searchParams.get("limit") ?? 50)
|
||||
return Response.json({ data: { records: fixtures.slice(offset, offset + limit), total: 1000 } })
|
||||
}
|
||||
const record = fixtures.find(item => url.pathname === `/api/v1/approvals/${item.id}`)
|
||||
return record ? Response.json({ data: record }) : Response.json({ error: "unexpected read" }, { status: 404 })
|
||||
}) as typeof fetch
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
for (const key of envKeys) {
|
||||
if (oldEnv[key] === undefined) delete process.env[key]
|
||||
else process.env[key] = oldEnv[key]
|
||||
}
|
||||
globalThis.fetch = oldFetch
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
function cli(...argv: string[]) { return runCli(["approval-runs", ...argv, "--corp", "extra-risk-test"]) }
|
||||
|
||||
describe("approval run extra risk CLI", () => {
|
||||
test("filters the fetched page, preserves upstream totals and aligns bridge to matches", async () => {
|
||||
const response = await cli("list", "--has-extra-risk", "--limit", "100", "--includeBridge")
|
||||
expect(response.exitCode).toBe(0)
|
||||
const data = JSON.parse(response.stdout)
|
||||
expect(data).toMatchObject({ scanned: 6, matched: 2, unknown: 2, total: 1000 })
|
||||
expect(data.records.map((record: { id: string }) => record.id)).toEqual(["warning", "error"])
|
||||
expect(data.records[0]).toMatchObject({
|
||||
otherFindingCount: 2, extraRiskCount: 1, hasExtraRisk: true, extraFindingsStatus: "known",
|
||||
extraRisks: [{ title: "主体差异", description: "付款主体与销方不同", level: "warning" }]
|
||||
})
|
||||
expect(data.bridge).toHaveLength(2)
|
||||
expect(requests).toHaveLength(1)
|
||||
const url = new URL(requests[0]!.url)
|
||||
expect(url.searchParams.get("limit")).toBe("100")
|
||||
expect(url.searchParams.has("hasExtraRisk")).toBe(false)
|
||||
expect(requests.every(request => request.method === "GET")).toBe(true)
|
||||
})
|
||||
|
||||
test("limit and offset apply before filtering without fetching more pages", async () => {
|
||||
const response = await cli("search", "--has-extra-risk", "--limit", "2", "--offset", "2")
|
||||
expect(response.exitCode).toBe(0)
|
||||
expect(JSON.parse(response.stdout)).toMatchObject({ scanned: 2, matched: 0, unknown: 0, total: 1000, records: [] })
|
||||
expect(requests).toHaveLength(1)
|
||||
expect(new URL(requests[0]!.url).searchParams.get("offset")).toBe("2")
|
||||
})
|
||||
|
||||
test("combines with human-result filtering and forwards time and status conditions", async () => {
|
||||
const response = await cli("search", "--has-extra-risk", "--humanResult", "驳回", "--status", "completed", "--startDate", "2026-10-01", "--endDate", "2026-10-22")
|
||||
expect(response.exitCode).toBe(0)
|
||||
const data = JSON.parse(response.stdout)
|
||||
expect(data).toMatchObject({ scanned: 6, matched: 1, unknown: 0 })
|
||||
expect(data.records.map((record: { id: string }) => record.id)).toEqual(["warning"])
|
||||
const params = new URL(requests[0]!.url).searchParams
|
||||
expect(params.get("status[0]")).toBe("completed")
|
||||
expect(params.get("manualApprovalStatus[0]")).toBe("TERMINATED")
|
||||
expect(params.get("startDate")).toBe(String(Date.parse("2026-10-01T00:00:00+08:00")))
|
||||
expect(params.get("endDate")).toBe(String(Date.parse("2026-10-22T23:59:59.999+08:00")))
|
||||
})
|
||||
|
||||
test("unfiltered lists preserve unknown and negative records with compact counts", async () => {
|
||||
const response = await cli("list")
|
||||
expect(response.exitCode).toBe(0)
|
||||
const data = JSON.parse(response.stdout)
|
||||
expect(data).toMatchObject({ scanned: 6, matched: 6, total: 1000 })
|
||||
expect(data).not.toHaveProperty("unknown")
|
||||
expect(data.records[2]).toMatchObject({ otherFindingCount: 1, extraRiskCount: 0, hasExtraRisk: false })
|
||||
expect(data.records[3]).toMatchObject({ otherFindingCount: 0, extraRiskCount: 0, hasExtraRisk: false })
|
||||
expect(data.records[4]).toMatchObject({ extraFindingsStatus: "unknown", otherFindingCount: null, extraRiskCount: null, hasExtraRisk: null })
|
||||
expect(data.records[0]).not.toHaveProperty("extraRisks")
|
||||
})
|
||||
|
||||
test("result and detail summaries expose extra risk counts without replacing existing counts", async () => {
|
||||
const result = await cli("result", "warning", "--summary")
|
||||
expect(result.exitCode).toBe(0)
|
||||
expect(JSON.parse(result.stdout)).toMatchObject({ decision: "APPROVE", extraRiskCount: 1, otherFindingCount: 2, hasExtraRisk: true })
|
||||
const detail = await cli("get", "warning", "--summary")
|
||||
expect(detail.exitCode).toBe(0)
|
||||
expect(JSON.parse(detail.stdout).aiResult).toMatchObject({ extraRiskCount: 1, hasExtraRisk: true })
|
||||
})
|
||||
|
||||
test("supports the camelCase alias and explicit false without filtering", async () => {
|
||||
const filtered = await cli("list", "--hasExtraRisk")
|
||||
expect(filtered.exitCode).toBe(0)
|
||||
expect(JSON.parse(filtered.stdout).matched).toBe(2)
|
||||
const unfiltered = await cli("list", "--has-extra-risk=false")
|
||||
expect(unfiltered.exitCode).toBe(0)
|
||||
expect(JSON.parse(unfiltered.stdout).matched).toBe(6)
|
||||
})
|
||||
})
|
||||
@@ -125,6 +125,7 @@ export async function handleApprovalRunsCommand(
|
||||
sourceDocumentSN: stringOption(args.options.sourceDocumentSN),
|
||||
sourceDocumentId: stringOption(args.options.sourceDocumentId),
|
||||
humanResult: stringOption(args.options.humanResult),
|
||||
hasExtraRisk: booleanOption(args.options["has-extra-risk"]) ?? booleanOption(args.options.hasExtraRisk),
|
||||
query: stringOption(args.options.query),
|
||||
includeBridge: booleanOption(args.options.includeBridge)
|
||||
},
|
||||
|
||||
@@ -62,6 +62,12 @@ describe("auth links", () => {
|
||||
? input.toString()
|
||||
: input.url;
|
||||
const url = new URL(requestUrl);
|
||||
if (url.pathname === "/api/v1/auth/me") {
|
||||
return Response.json({ data: {
|
||||
user: { id: "session-user", tenantId: "tenant", name: "当前Seal人员", isAdmin: true, permissions: ["*"] },
|
||||
tenant: { id: "tenant", name: "原生 Seal 企业" }
|
||||
} });
|
||||
}
|
||||
if (url.pathname === "/api/v1/delegation/create") {
|
||||
return new Response(JSON.stringify({
|
||||
data: {
|
||||
@@ -86,10 +92,15 @@ describe("auth links", () => {
|
||||
corpId: "native-corp",
|
||||
corpName: "原生 Seal 企业",
|
||||
staffId: "native-staff",
|
||||
staffName: "当前Seal人员",
|
||||
identityStatus: "resolved",
|
||||
isAdmin: true,
|
||||
permissions: ["*"],
|
||||
link: "https://native.seal.test/delegation?token=delegation-token",
|
||||
token: "delegation-token"
|
||||
});
|
||||
expect(parsed.url).toBeUndefined();
|
||||
expect(result.stderr).not.toContain("未能核实");
|
||||
expect(parsed.expiresAt).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+08:00$/);
|
||||
});
|
||||
|
||||
@@ -163,6 +174,8 @@ describe("auth links", () => {
|
||||
expiresInHours: 1
|
||||
});
|
||||
expect(floorResult.stderr).toContain("已自动向下取整为 1 小时 (1h)");
|
||||
expect(JSON.parse(floorResult.stdout)).toMatchObject({ staffName: null, identityStatus: "unresolved", isAdmin: null, permissions: null });
|
||||
expect(floorResult.stderr).toContain("未能核实实际登录人员姓名");
|
||||
|
||||
// Test reject exceeding 7 days (168 hours)
|
||||
const invalidResult = await runCli(["auth", "link", "--corp", "native-seal", "--expire", "8d"]);
|
||||
@@ -220,6 +233,12 @@ describe("auth links", () => {
|
||||
{ status: 200, headers: { "content-type": "application/json" } }
|
||||
);
|
||||
}
|
||||
if (url.pathname === "/api/openapi/v1/staffs/getStaffIds") {
|
||||
return Response.json({ items: [{ id: "HOSE-CORP:STAFF-1", name: "当前合思人员", active: true, roles: [{ roleDefId: "HOSE-CORP:admin" }] }] });
|
||||
}
|
||||
if (url.pathname === "/api/openapi/v1/roleDefGroups") {
|
||||
return Response.json({ items: [{ id: "system", name: "系统", roleDefs: [{ id: "HOSE-CORP:admin", name: "主管理员" }] }] });
|
||||
}
|
||||
return new Response(JSON.stringify({ error: `Unexpected request: ${url.pathname}` }), {
|
||||
status: 404,
|
||||
headers: { "content-type": "application/json" }
|
||||
@@ -234,6 +253,9 @@ describe("auth links", () => {
|
||||
corpId: "HOSE-CORP",
|
||||
corpName: "合思测试企业",
|
||||
staffId: "HOSE-CORP:STAFF-1",
|
||||
staffName: "当前合思人员",
|
||||
identityStatus: "resolved",
|
||||
roleNames: ["主管理员"],
|
||||
link: "https://app.ekuaibao.com/web/thirdparty.html?accessToken=provisional-token-xyz",
|
||||
token: "provisional-token-xyz"
|
||||
});
|
||||
@@ -315,6 +337,8 @@ describe("auth links", () => {
|
||||
expireDate: 7200
|
||||
});
|
||||
expect(result2.stderr).toContain("已按 2 小时 (7200s) 自动换算");
|
||||
expect(JSON.parse(result2.stdout)).toMatchObject({ staffName: null, identityStatus: "unresolved", roleNames: null });
|
||||
expect(result2.stderr).toContain("未能核实实际登录人员姓名");
|
||||
});
|
||||
|
||||
test("runs auth check and hidden aliases (status, diagnose, test)", async () => {
|
||||
|
||||
@@ -12,6 +12,7 @@ import { CliError, validationError, usageError } from "../../core/errors.js";
|
||||
import { createSealClient, createSealClientForUrl } from "../../core/http/factory.js";
|
||||
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
|
||||
import { createDelegation, getMe } from "../../domains/seal/api.js";
|
||||
import { resolveHoseLinkIdentity, resolveSealLinkIdentity, summarizeSealLinkIdentity } from "../../domains/seal/enterprise/assist-identity.js";
|
||||
import {
|
||||
booleanOption,
|
||||
parseDelegationExpireHours,
|
||||
@@ -59,6 +60,7 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
|
||||
const delegation = await createDelegation(client, { note, expiresInHours });
|
||||
|
||||
printJson({
|
||||
...summarizeSealLinkIdentity(me.user),
|
||||
tenant: {
|
||||
id: me.tenant.id,
|
||||
name: me.tenant.name,
|
||||
@@ -115,14 +117,15 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
|
||||
console.error(`👉 提示: 企业「${corp.name}」源类型为 Seal 原生测试环境,已自动为您生成委托免登直达链接。`);
|
||||
}
|
||||
const delegationRecord = delegation as Record<string, unknown>;
|
||||
const staffName = "staffName" in corp.source && typeof corp.source.staffName === "string" ? corp.source.staffName : undefined;
|
||||
const expiresAt = formatBeijingIso(Date.now() + expiresInHours * 3600 * 1000);
|
||||
const identity = await resolveSealLinkIdentity(client);
|
||||
if (identity.identityStatus === "unresolved") console.error("提示:链接已生成,但未能核实实际登录人员姓名;请勿将 staffId 当作姓名或推断管理员身份。");
|
||||
printJson({
|
||||
id: delegationRecord.id,
|
||||
corpId: corp.source.corpId ?? corp.id,
|
||||
corpName: corp.name,
|
||||
staffId: corp.source.staffId,
|
||||
...(staffName ? { staffName } : {}),
|
||||
...identity,
|
||||
link: delegationRecord.link,
|
||||
expiresAt,
|
||||
token: delegationRecord.token
|
||||
@@ -138,13 +141,14 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
|
||||
booleanOption(args.options.refresh) === true ||
|
||||
booleanOption(args.options.f) === true;
|
||||
const provisional = await getHoseProvisionalAuthLink(corp, expiresIn, { force });
|
||||
const staffName = "staffName" in corp.source && typeof corp.source.staffName === "string" ? corp.source.staffName : undefined;
|
||||
const expiresAt = formatBeijingIso(Date.now() + expiresIn * 1000);
|
||||
const identity = await resolveHoseLinkIdentity(corp);
|
||||
if (identity.identityStatus === "unresolved") console.error("提示:链接已生成,但未能核实实际登录人员姓名;请勿将 staffId 当作姓名或推断管理员身份。");
|
||||
printJson({
|
||||
corpId: corp.source.corpId ?? corp.id,
|
||||
corpName: corp.name,
|
||||
staffId: corp.source.staffId,
|
||||
...(staffName ? { staffName } : {}),
|
||||
...identity,
|
||||
link: provisional.url,
|
||||
expiresAt,
|
||||
token: provisional.token
|
||||
|
||||
@@ -80,6 +80,8 @@ describe("corps link onboarding", () => {
|
||||
|
||||
expect(result.isError).toBe(false);
|
||||
expect(JSON.parse(result.stdout)).toMatchObject({
|
||||
staffName: "Support User",
|
||||
identityStatus: "resolved",
|
||||
tenant: {
|
||||
corpId: "acme-01",
|
||||
tenantSlug: "acme-01"
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import { usageError } from "../../core/errors.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import type { createSealClient } from "../../core/http/factory.js";
|
||||
import { runCapability } from "../helpers.js";
|
||||
import { numberOption, stringOption } from "../parser.js";
|
||||
import { outputOptions } from "../printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
|
||||
export async function handleDataCommand(
|
||||
@@ -12,21 +9,17 @@ export async function handleDataCommand(
|
||||
corp: CorpConfig,
|
||||
args: ParsedArgs
|
||||
) {
|
||||
const params = {
|
||||
offset: numberOption(args.options.offset),
|
||||
limit: numberOption(args.options.limit),
|
||||
startDate: stringOption(args.options.startDate) ?? stringOption(args.options["start-date"]),
|
||||
endDate: stringOption(args.options.endDate) ?? stringOption(args.options["end-date"]),
|
||||
search: stringOption(args.options.search) ?? stringOption(args.options.query)
|
||||
};
|
||||
|
||||
if (action === "expenses" || action === "expense") {
|
||||
await runCapability("sealExpensesList", client, corp, params, outputOptions(args.options));
|
||||
const { handleExpensesCommand } = await import("./expenses.js");
|
||||
await handleExpensesCommand(args.command[2], client, corp, args);
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "invoices" || action === "invoice") {
|
||||
await runCapability("sealInvoicesList", client, corp, params, outputOptions(args.options));
|
||||
const subAction = args.command[2];
|
||||
const maybeTarget = args.command[3];
|
||||
const { handleInvoicesCommand } = await import("./invoices.js");
|
||||
await handleInvoicesCommand(subAction, maybeTarget, client, corp, args);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test"
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import { runCli } from "../runner.js"
|
||||
|
||||
const envKeys = ["SEAL_USE_ENTERPRISES_DIR", "SEAL_USE_CONFIG_FILE", "SEAL_USE_TOKEN_STORE", "SEAL_USE_USAGE_FILE"] as const
|
||||
const oldEnv = Object.fromEntries(envKeys.map(key => [key, process.env[key]]))
|
||||
const oldFetch = globalThis.fetch
|
||||
let dir: string
|
||||
let document = { id: "doc-1", title: "Fixture policy", purpose: "Testing", content: "Line one\\\r\n| a \\| b |", status: "published", enabled: true, scenarios: ["audit"], tags: ["test"] }
|
||||
let requests: Array<{ method: string; path: string; query: string; body?: Record<string, unknown> }>
|
||||
let failReadback: boolean
|
||||
let failReadbackStatus: number
|
||||
const original = structuredClone(document)
|
||||
|
||||
beforeEach(() => {
|
||||
dir = mkdtempSync(join(tmpdir(), "seal-documents-cli-"))
|
||||
const enterprises = join(dir, "enterprises")
|
||||
mkdirSync(enterprises)
|
||||
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises
|
||||
process.env.SEAL_USE_CONFIG_FILE = join(dir, "config.json")
|
||||
process.env.SEAL_USE_TOKEN_STORE = join(dir, "tokens.json")
|
||||
process.env.SEAL_USE_USAGE_FILE = join(dir, "usage.json")
|
||||
writeFileSync(join(enterprises, "document-cli-test.json"), JSON.stringify({
|
||||
id: "document-cli-test", name: "Document Test", environment: "test",
|
||||
seal: { url: "https://documents.example.test" },
|
||||
source: { type: "seal", token: "test-token", sealUrl: "https://documents.example.test", staffId: "fixture" }
|
||||
}))
|
||||
document = structuredClone(original)
|
||||
requests = []
|
||||
failReadback = false
|
||||
failReadbackStatus = 400
|
||||
let writeCount = 0
|
||||
let readbackWrites = 0
|
||||
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const request = new Request(input, init)
|
||||
const url = new URL(request.url)
|
||||
const method = request.method
|
||||
const body = ["PATCH", "POST"].includes(method) ? JSON.parse(await request.text()) as Record<string, unknown> : undefined
|
||||
requests.push({ method, path: url.pathname, query: url.searchParams.toString(), body })
|
||||
if (failReadback && method === "GET" && writeCount > readbackWrites) {
|
||||
readbackWrites = writeCount
|
||||
return Response.json({ error: "offline" }, { status: failReadbackStatus })
|
||||
}
|
||||
if (method === "PATCH") {
|
||||
writeCount++
|
||||
document = { ...document, ...(body?.attributes as object) }
|
||||
}
|
||||
if (method === "POST") document = { ...document, ...body }
|
||||
return Response.json({ data: url.pathname.endsWith("/articles") && method === "GET" ? { articles: [document], total: 115 } : document })
|
||||
}) as typeof fetch
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
for (const key of envKeys) {
|
||||
if (oldEnv[key] === undefined) delete process.env[key]
|
||||
else process.env[key] = oldEnv[key]
|
||||
}
|
||||
globalThis.fetch = oldFetch
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
function cli(...argv: string[]) { return runCli(["documents", ...argv, "--corp", "document-cli-test"]) }
|
||||
const writes = () => requests.filter(request => request.method !== "GET")
|
||||
|
||||
describe("documents CLI", () => {
|
||||
test("exports body plus baseline, previews edits, and updates only body with JSON receipts", async () => {
|
||||
const out = join(dir, "body.txt")
|
||||
const exported = await cli("get", "doc-1", "--out", out)
|
||||
expect(exported.exitCode).toBe(0)
|
||||
expect(JSON.parse(exported.stdout)).toMatchObject({ contentFile: out, contentFormat: "raw" })
|
||||
expect(readFileSync(out, "utf8")).toBe(original.content)
|
||||
writeFileSync(out, "edited content")
|
||||
const preview = await cli("update", "doc-1", "--content-file", out, "--dry-run", "--yes")
|
||||
expect(preview.exitCode).toBe(0)
|
||||
expect(JSON.parse(preview.stdout)).toMatchObject({ preview: true, executed: false, baselineAvailable: true, changedFields: ["content"] })
|
||||
expect(writes()).toHaveLength(0)
|
||||
const result = await cli("update", "doc-1", "--content-file", out, "--yes")
|
||||
expect(result.exitCode).toBe(0)
|
||||
const payload = JSON.parse(result.stdout)
|
||||
expect(payload).toMatchObject({ verified: true, executed: true, baselineAvailable: true })
|
||||
expect(JSON.parse(readFileSync(payload.snapshotFile, "utf8")).document.content).toBe(original.content)
|
||||
expect(writes()).toHaveLength(1)
|
||||
expect(writes()[0]?.body).toEqual({ attributes: { content: "edited content" } })
|
||||
expect(document.title).toBe(original.title)
|
||||
expect(document.status).toBe("published")
|
||||
})
|
||||
|
||||
test("plain get and output-file still produce whole document JSON", async () => {
|
||||
expect(JSON.parse((await cli("get", "doc-1")).stdout)).toMatchObject(original)
|
||||
const path = join(dir, "document.json")
|
||||
const result = await cli("get", "doc-1", "--output-file", path)
|
||||
expect(JSON.parse(result.stdout)).toMatchObject({ outputFile: path })
|
||||
expect(JSON.parse(readFileSync(path, "utf8"))).toMatchObject(original)
|
||||
})
|
||||
|
||||
test("lightweight list and explicit fields do not request per-document details", async () => {
|
||||
const summary = await cli("list", "--summary", "--limit", "2", "--offset", "1")
|
||||
expect(summary.exitCode).toBe(0)
|
||||
expect(JSON.parse(summary.stdout).articles[0]).not.toHaveProperty("content")
|
||||
expect(new URLSearchParams(requests[0]?.query).get("limit")).toBe("2")
|
||||
expect(new URLSearchParams(requests[0]?.query).get("offset")).toBe("1")
|
||||
const fields = await cli("list", "--summary", "--fields", "id,title")
|
||||
expect(JSON.parse(fields.stdout)).toEqual({ total: 115, articles: [{ id: "doc-1", title: original.title }] })
|
||||
expect(requests.every(request => request.path === "/api/v1/knowledge/articles")).toBe(true)
|
||||
expect((await cli("list", "--fields", "typo")).exitCode).toBe(2)
|
||||
})
|
||||
|
||||
test("all write commands require confirmation and all previews remain read-only", async () => {
|
||||
const variants = [
|
||||
["create", "--title", "new", "--purpose", "test", "--content", "new"],
|
||||
["update", "doc-1", "--content", "new"],
|
||||
["delete", "doc-1"]
|
||||
]
|
||||
for (const argv of variants) {
|
||||
expect((await cli(...argv)).exitCode).toBe(10)
|
||||
for (const flag of ["--dry-run", "--dryRun"]) {
|
||||
const result = await cli(...argv, flag, "--confirm")
|
||||
expect(result.exitCode).toBe(0)
|
||||
expect(JSON.parse(result.stdout)).toMatchObject({ preview: true, executed: false })
|
||||
}
|
||||
}
|
||||
expect(writes()).toHaveLength(0)
|
||||
expect(existsSync(join(dir, "document-history"))).toBe(false)
|
||||
})
|
||||
|
||||
test("conflicts and failed readback return JSON state with nonzero exit codes", async () => {
|
||||
const path = join(dir, "body")
|
||||
await cli("get", "doc-1", "--out", path)
|
||||
writeFileSync(path, "my edit")
|
||||
document.content = "remote edit"
|
||||
const conflict = await cli("update", "doc-1", "--content-file", path, "--yes")
|
||||
expect(conflict.exitCode).toBe(1)
|
||||
expect(JSON.parse(conflict.stdout)).toMatchObject({ code: "DOCUMENT_CONFLICT", executed: false })
|
||||
expect(writes()).toHaveLength(0)
|
||||
failReadback = true
|
||||
const uncertain = await cli("update", "doc-1", "--content", "new", "--yes")
|
||||
expect(uncertain.exitCode).toBe(1)
|
||||
expect(JSON.parse(uncertain.stdout)).toMatchObject({ code: "DOCUMENT_READBACK_FAILED", executed: true, verified: false })
|
||||
expect(uncertain.stderr).toContain("Next action:")
|
||||
|
||||
failReadbackStatus = 401
|
||||
const authFailed = await cli("update", "doc-1", "--content", "newer", "--yes")
|
||||
expect(authFailed.exitCode).toBe(11)
|
||||
expect(JSON.parse(authFailed.stdout)).toMatchObject({ code: "DOCUMENT_READBACK_FAILED", executed: true, verified: false })
|
||||
})
|
||||
|
||||
test("unsupported format and path/input conflicts fail before requests or file changes", async () => {
|
||||
const path = join(dir, "body")
|
||||
writeFileSync(path, "keep")
|
||||
for (const argv of [
|
||||
["get", "doc-1", "--out", path, "--content-format", "markdown"],
|
||||
["get", "doc-1", "--out", path, "--output-file", path],
|
||||
["update", "doc-1", "--content-file", path, "--content", "other", "--yes"],
|
||||
["update", "doc-1", "--content-file", path, "--output-file", path, "--yes"],
|
||||
["update", "doc-1", "--content-file", path, "--output-file", `${path}.seal-use.json`, "--yes"]
|
||||
]) expect((await cli(...argv)).exitCode).toBe(2)
|
||||
expect(readFileSync(path, "utf8")).toBe("keep")
|
||||
expect(requests).toHaveLength(0)
|
||||
})
|
||||
|
||||
test("invalid UTF-8, missing file and damaged baseline fail with exit 13 and zero writes", async () => {
|
||||
const path = join(dir, "body")
|
||||
expect((await cli("update", "doc-1", "--content-file", path, "--yes")).exitCode).toBe(13)
|
||||
writeFileSync(path, Buffer.from([0xff]))
|
||||
expect((await cli("update", "doc-1", "--content-file", path, "--yes")).exitCode).toBe(13)
|
||||
writeFileSync(path, "new")
|
||||
writeFileSync(`${path}.seal-use.json`, "{}")
|
||||
expect((await cli("update", "doc-1", "--content-file", path, "--yes")).exitCode).toBe(13)
|
||||
expect(writes()).toHaveLength(0)
|
||||
})
|
||||
|
||||
test("legacy raw input is supported and discloses absence of an editing baseline", async () => {
|
||||
const result = await cli("update", "doc-1", "--content", "new", "--confirm")
|
||||
expect(result.exitCode).toBe(0)
|
||||
expect(JSON.parse(result.stdout)).toMatchObject({ verified: true, baselineAvailable: false })
|
||||
expect(result.stderr).toContain("baselineAvailable:false")
|
||||
})
|
||||
})
|
||||
@@ -1,8 +1,11 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import type { createSealClient } from "../../core/http/factory.js";
|
||||
import { confirmationRequired, usageError } from "../../core/errors.js";
|
||||
import { runCapability } from "../helpers.js";
|
||||
import { usageError } from "../../core/errors.js";
|
||||
import { runCapability, runCapabilityResult } from "../helpers.js";
|
||||
import { exportDocument, readDocumentBaseline, readDocumentText } from "../../domains/seal/documents/files.js";
|
||||
import { DocumentMutationError } from "../../domains/seal/documents/service.js";
|
||||
import { ApprovalDocumentSchema } from "../../domains/seal/types.js";
|
||||
import {
|
||||
booleanOption,
|
||||
jsonObject,
|
||||
@@ -10,17 +13,25 @@ import {
|
||||
splitOption,
|
||||
stringOption
|
||||
} from "../parser.js";
|
||||
import { outputOptions } from "../printer.js";
|
||||
import { outputOptions, printJson } from "../printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
|
||||
function readContentInput(args: ParsedArgs, payload: Record<string, unknown>): string | undefined {
|
||||
const filePath =
|
||||
function contentFilePath(args: ParsedArgs): string | undefined {
|
||||
return (
|
||||
stringOption(args.options.contentFile) ??
|
||||
stringOption(args.options["content-file"]) ??
|
||||
stringOption(args.options.file) ??
|
||||
stringOption(args.options.f);
|
||||
stringOption(args.options.f)
|
||||
);
|
||||
}
|
||||
|
||||
function readContentInput(args: ParsedArgs, payload: Record<string, unknown>): string | undefined {
|
||||
const filePath = contentFilePath(args);
|
||||
const fileInputs = ["contentFile", "content-file", "file", "f"].filter(key => args.options[key] !== undefined).length;
|
||||
const sources = fileInputs + Number(args.options.content !== undefined) + Number(payload.content !== undefined);
|
||||
if (sources > 1) throw usageError("Specify exactly one document content source: --content-file, --content, or JSON content");
|
||||
if (filePath) {
|
||||
return readFileSync(filePath, "utf8");
|
||||
return readDocumentText(filePath);
|
||||
}
|
||||
const direct = stringOption(args.options.content);
|
||||
if (direct !== undefined) return direct;
|
||||
@@ -34,6 +45,33 @@ export async function handleDocumentsCommand(
|
||||
corp: CorpConfig,
|
||||
args: ParsedArgs
|
||||
) {
|
||||
const out = stringOption(args.options.out);
|
||||
const format = stringOption(args.options["content-format"]) ?? stringOption(args.options.contentFormat);
|
||||
if (format !== undefined && format !== "raw") throw usageError("--content-format supports raw only; Markdown conversion requires a verified platform codec");
|
||||
if (out && action !== "get") throw usageError("--out is supported only by documents get");
|
||||
if (format !== undefined && !["get", "create", "update"].includes(action ?? "")) throw usageError("--content-format is supported only by documents get/create/update");
|
||||
if (out && outputOptions(args.options).outputFile) throw usageError("--out (body) and --output-file (JSON) are mutually exclusive");
|
||||
if (booleanOption(args.options.overwrite) && !out) throw usageError("--overwrite requires documents get --out");
|
||||
const contentPath = contentFilePath(args);
|
||||
const jsonOutput = outputOptions(args.options).outputFile;
|
||||
if (contentPath && jsonOutput && [resolve(contentPath), `${resolve(contentPath)}.seal-use.json`].includes(resolve(jsonOutput))) {
|
||||
throw usageError("--output-file must not overwrite the input body or its export baseline");
|
||||
}
|
||||
|
||||
const safety = {
|
||||
dryRun: booleanOption(args.options["dry-run"]) ?? booleanOption(args.options.dryRun),
|
||||
confirm: booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true,
|
||||
allowEmpty: booleanOption(args.options["allow-empty"]) ?? booleanOption(args.options.allowEmpty)
|
||||
};
|
||||
const mutate = async (name: string, params: Record<string, unknown>) => {
|
||||
try {
|
||||
printJson(await runCapabilityResult(name, client, corp, params), outputOptions(args.options));
|
||||
} catch (error) {
|
||||
if (error instanceof DocumentMutationError) printJson(error.payload, outputOptions(args.options));
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
if (!action || action === "list") {
|
||||
const scenarios = splitOption(args.options.scenarios);
|
||||
const limit = numberOption(args.options.limit);
|
||||
@@ -42,7 +80,7 @@ export async function handleDocumentsCommand(
|
||||
"sealApprovalDocumentsList",
|
||||
client,
|
||||
corp,
|
||||
{ scenarios, limit, offset },
|
||||
{ scenarios, limit, offset, summary: booleanOption(args.options.summary), fields: splitOption(args.options.fields) },
|
||||
outputOptions(args.options)
|
||||
);
|
||||
return;
|
||||
@@ -57,6 +95,11 @@ export async function handleDocumentsCommand(
|
||||
if (!documentId) {
|
||||
throw usageError("Usage: seal-use documents get <documentId> [--corp <corpId>]");
|
||||
}
|
||||
if (out) {
|
||||
const document = ApprovalDocumentSchema.parse(await runCapabilityResult("sealApprovalDocumentGet", client, corp, { documentId }));
|
||||
printJson(exportDocument(corp, document, out, booleanOption(args.options.overwrite)));
|
||||
return;
|
||||
}
|
||||
await runCapability(
|
||||
"sealApprovalDocumentGet",
|
||||
client,
|
||||
@@ -118,10 +161,8 @@ export async function handleDocumentsCommand(
|
||||
throw usageError("Usage: seal-use documents create --title <title> --purpose <purpose> [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]");
|
||||
}
|
||||
|
||||
await runCapability(
|
||||
await mutate(
|
||||
"sealApprovalDocumentCreate",
|
||||
client,
|
||||
corp,
|
||||
{
|
||||
title,
|
||||
purpose,
|
||||
@@ -130,9 +171,9 @@ export async function handleDocumentsCommand(
|
||||
status,
|
||||
enabled,
|
||||
scenarios,
|
||||
tags
|
||||
},
|
||||
outputOptions(args.options)
|
||||
tags,
|
||||
...safety
|
||||
}
|
||||
);
|
||||
return;
|
||||
}
|
||||
@@ -180,10 +221,11 @@ export async function handleDocumentsCommand(
|
||||
throw usageError("Usage: seal-use documents update <documentId> [--title <title>] [--purpose <purpose>] [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--enabled <true|false>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]");
|
||||
}
|
||||
|
||||
await runCapability(
|
||||
const filePath = contentFilePath(args);
|
||||
const baseline = filePath ? readDocumentBaseline(filePath) : undefined;
|
||||
if (content !== undefined && !baseline) console.error("Document input has no export baseline; changes made by others during editing cannot be detected (baselineAvailable:false).");
|
||||
await mutate(
|
||||
"sealApprovalDocumentUpdate",
|
||||
client,
|
||||
corp,
|
||||
{
|
||||
documentId,
|
||||
title,
|
||||
@@ -193,9 +235,10 @@ export async function handleDocumentsCommand(
|
||||
status,
|
||||
enabled,
|
||||
scenarios,
|
||||
tags
|
||||
},
|
||||
outputOptions(args.options)
|
||||
tags,
|
||||
baseline,
|
||||
...safety
|
||||
}
|
||||
);
|
||||
return;
|
||||
}
|
||||
@@ -209,19 +252,9 @@ export async function handleDocumentsCommand(
|
||||
if (!documentId) {
|
||||
throw usageError("Usage: seal-use documents delete <documentId> --yes [--corp <corpId>]");
|
||||
}
|
||||
const confirmed = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true;
|
||||
if (!confirmed) {
|
||||
throw confirmationRequired(
|
||||
`Refusing to delete document '${documentId}' without --yes.`,
|
||||
`seal-use documents delete ${documentId} --corp ${corp.id} --yes`
|
||||
);
|
||||
}
|
||||
await runCapability(
|
||||
await mutate(
|
||||
"sealApprovalDeleteDocument",
|
||||
client,
|
||||
corp,
|
||||
{ documentId },
|
||||
outputOptions(args.options)
|
||||
{ documentId, dryRun: safety.dryRun, confirm: safety.confirm }
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test"
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import { runCli } from "../runner.js"
|
||||
|
||||
const envKeys = ["SEAL_USE_CONFIG_FILE", "SEAL_USE_ENTERPRISES_DIR", "SEAL_USE_TOKEN_STORE", "SEAL_USE_USAGE_FILE"] as const
|
||||
const oldEnv = Object.fromEntries(envKeys.map(key => [key, process.env[key]]))
|
||||
const oldFetch = globalThis.fetch
|
||||
let dir: string
|
||||
let requests: Array<{ method: string; path: string; query: URLSearchParams }>
|
||||
let approvalSN: string
|
||||
let expenseCount: number
|
||||
let failureStatus: number | undefined
|
||||
let description: string
|
||||
const sn = "SN-CLI-FIXTURE"
|
||||
|
||||
beforeEach(() => {
|
||||
dir = mkdtempSync(join(tmpdir(), "seal-expense-cli-"))
|
||||
const enterprises = join(dir, "enterprises")
|
||||
mkdirSync(enterprises)
|
||||
process.env.SEAL_USE_CONFIG_FILE = join(dir, "config.json")
|
||||
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises
|
||||
process.env.SEAL_USE_TOKEN_STORE = join(dir, "tokens.json")
|
||||
process.env.SEAL_USE_USAGE_FILE = join(dir, "usage.json")
|
||||
writeFileSync(join(enterprises, "expense-cli-test.json"), JSON.stringify({
|
||||
id: "expense-cli-test", name: "Expense Test", environment: "test", seal: { url: "https://expense.example.test" },
|
||||
source: { type: "seal", token: "test-token", sealUrl: "https://expense.example.test", staffId: "fixture" }
|
||||
}))
|
||||
requests = []
|
||||
approvalSN = sn
|
||||
expenseCount = 2
|
||||
failureStatus = undefined
|
||||
description = "Fixture only"
|
||||
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const request = new Request(input, init)
|
||||
const url = new URL(request.url)
|
||||
requests.push({ method: request.method, path: url.pathname, query: url.searchParams })
|
||||
if (request.method !== "GET") throw new Error("Unexpected mutation")
|
||||
if (url.pathname === "/api/v1/approvals") return Response.json({ data: { records: [{ id: "record-1", sourceDocumentSN: approvalSN, sourceDocumentId: "source-1", documentId: "document-1" }], total: 1 } })
|
||||
if (failureStatus) return Response.json({ error: { message: "fixture failure" } }, { status: failureStatus })
|
||||
if (!url.searchParams.has("filter[search]") && !url.searchParams.has("filter[recordId]")) return Response.json({ error: "filter required" }, { status: 400 })
|
||||
const offset = Number(url.searchParams.get("offset"))
|
||||
const limit = Number(url.searchParams.get("limit"))
|
||||
const expenses = Array.from({ length: expenseCount }, (_, i) => ({ id: `expense-${i}`, recordId: "record-1", documentId: "document-1", type: "fixture", amount: i + 1, currency: "CNY", description, user: { mobile: "private-fixture" } }))
|
||||
return Response.json({ data: { expenses: expenses.slice(offset, offset + limit), total: expenses.length } })
|
||||
}) as typeof fetch
|
||||
})
|
||||
afterEach(() => {
|
||||
for (const key of envKeys) {
|
||||
if (oldEnv[key] === undefined) delete process.env[key]
|
||||
else process.env[key] = oldEnv[key]
|
||||
}
|
||||
globalThis.fetch = oldFetch
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
})
|
||||
function cli(...argv: string[]) { return runCli([...argv, "--corp", "expense-cli-test"]) }
|
||||
|
||||
describe("expense document lookup CLI", () => {
|
||||
test("canonical, singular, list and data entrances all execute the same read-only lookup", async () => {
|
||||
for (const prefix of [["expenses"], ["expense"], ["expenses", "list"], ["data", "expenses"], ["data", "expense", "list"]]) {
|
||||
const result = await cli(...prefix, "--sn", sn, "--limit", "1")
|
||||
expect(result.exitCode).toBe(0)
|
||||
expect(JSON.parse(result.stdout)).toMatchObject({ status: "found", found: true, complete: true, matchedCount: 2 })
|
||||
expect(result.stdout).not.toContain("private-fixture")
|
||||
}
|
||||
expect(requests.every(request => request.method === "GET")).toBe(true)
|
||||
expect(requests.filter(request => request.path.includes("expenses")).every(request => request.query.get("filter[recordId]") === "record-1")).toBe(true)
|
||||
})
|
||||
|
||||
test("raw list behavior stays compatible while bare list and record filters get a required filter object", async () => {
|
||||
const raw = await cli("expenses", "list")
|
||||
expect(raw.exitCode).toBe(0)
|
||||
expect(JSON.parse(raw.stdout)).toHaveProperty("expenses")
|
||||
expect(requests[0]?.query.get("filter[search]")).toBe("")
|
||||
expect(requests[0]?.query.has("filter[startDate]")).toBe(false)
|
||||
const byRecord = await cli("data", "expenses", "--record-id", "record-1")
|
||||
expect(byRecord.exitCode).toBe(0)
|
||||
expect(requests[1]?.query.get("filter[recordId]")).toBe("record-1")
|
||||
await cli("expenses", "--search", "交通", "--offset", "2")
|
||||
expect(requests[2]?.query.get("filter[search]")).toBe("交通")
|
||||
expect(requests[2]?.query.get("offset")).toBe("2")
|
||||
})
|
||||
|
||||
test("absence and unresolved linking have different JSON conclusions", async () => {
|
||||
expenseCount = 0
|
||||
expect(JSON.parse((await cli("expenses", "--sn", sn)).stdout)).toMatchObject({ status: "not_found", found: false, complete: true })
|
||||
approvalSN = `${sn}-UNRELATED`
|
||||
expect(JSON.parse((await cli("expenses", "--sn", sn)).stdout)).toMatchObject({ status: "unknown", found: null, complete: false, reason: "approval_link_not_found" })
|
||||
})
|
||||
|
||||
test("limits are explicit and partial scans cannot return not_found", async () => {
|
||||
const result = await cli("expenses", "--sn", sn, "--max-scan", "1")
|
||||
expect(result.exitCode).toBe(0)
|
||||
expect(JSON.parse(result.stdout)).toMatchObject({ status: "found", complete: false, reason: "scan_limit", matchedCount: 1 })
|
||||
})
|
||||
|
||||
test("bad selector combinations, unknown verbs and invalid scan budgets fail before requests", async () => {
|
||||
for (const argv of [
|
||||
["expenses", "delete"], ["expenses", "SN-as-unsupported-positional"], ["expenses", "list", sn], ["data", "expenses", "list", sn],
|
||||
["expenses", "--sn", sn, "--search", "text"], ["expenses", "--sn", sn, "--record-id", "record-1"],
|
||||
["expenses", "--sn", sn, "--offset", "0"], ["expenses", "--max-scan", "1"]
|
||||
]) expect((await cli(...argv)).exitCode).toBe(2)
|
||||
expect((await cli("expenses", "--sn", sn, "--max-scan", "0")).exitCode).toBe(13)
|
||||
expect(requests).toHaveLength(0)
|
||||
})
|
||||
|
||||
test("expense lookup failures retain JSON uncertainty and correct exit codes", async () => {
|
||||
for (const status of [400, 403]) {
|
||||
failureStatus = status
|
||||
const result = await cli("expenses", "--sn", sn)
|
||||
expect(result.exitCode).toBe(status === 403 ? 11 : 1)
|
||||
expect(JSON.parse(result.stdout)).toMatchObject({ status: "unknown", complete: false, found: null })
|
||||
expect(result.stderr).toContain("incomplete")
|
||||
}
|
||||
})
|
||||
|
||||
test("oversized reports retain existing output protection and can be exported as JSON", async () => {
|
||||
description = "x".repeat(210000)
|
||||
expect((await cli("expenses", "--sn", sn)).exitCode).toBe(12)
|
||||
const path = join(dir, "report.json")
|
||||
const result = await cli("expenses", "--sn", sn, "--output-file", path)
|
||||
expect(result.exitCode).toBe(0)
|
||||
expect(JSON.parse(result.stdout)).toMatchObject({ outputFile: path })
|
||||
expect(JSON.parse(readFileSync(path, "utf8"))).toMatchObject({ status: "found", complete: true, matchedCount: 2 })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,33 @@
|
||||
import type { CorpConfig } from "../../core/config/types.js"
|
||||
import type { createSealClient } from "../../core/http/factory.js"
|
||||
import { usageError } from "../../core/errors.js"
|
||||
import { ExpenseLookupError } from "../../domains/seal/expenses/lookup.js"
|
||||
import { runCapabilityResult } from "../helpers.js"
|
||||
import { numberOption, stringOption } from "../parser.js"
|
||||
import { outputOptions, printJson } from "../printer.js"
|
||||
import type { ParsedArgs } from "../types.js"
|
||||
|
||||
export async function handleExpensesCommand(action: string | undefined, client: Awaited<ReturnType<typeof createSealClient>>, corp: CorpConfig, args: ParsedArgs) {
|
||||
const prefixLength = args.command[0]?.toLowerCase() === "data" ? 2 : 1
|
||||
if ((action && action !== "list") || args.command.length > prefixLength + Number(Boolean(action))) {
|
||||
throw usageError("Usage: seal-use expenses [list] [--sn <documentSN>|--record-id <recordId>|--search <text>]")
|
||||
}
|
||||
const sn = stringOption(args.options.sn)
|
||||
const recordId = stringOption(args.options["record-id"]) ?? stringOption(args.options.recordId)
|
||||
const search = stringOption(args.options.search) ?? stringOption(args.options.query)
|
||||
const offset = numberOption(args.options.offset)
|
||||
const maxScan = numberOption(args.options["max-scan"]) ?? numberOption(args.options.maxScan)
|
||||
if (sn !== undefined && (recordId !== undefined || search !== undefined || offset !== undefined)) throw usageError("--sn cannot be combined with --search, --record-id, or --offset")
|
||||
if (maxScan !== undefined && sn === undefined) throw usageError("--max-scan requires --sn")
|
||||
try {
|
||||
const result = await runCapabilityResult("sealExpensesList", client, corp, {
|
||||
sn, recordId, search, offset, maxScan, limit: numberOption(args.options.limit),
|
||||
startDate: stringOption(args.options.startDate) ?? stringOption(args.options["start-date"]),
|
||||
endDate: stringOption(args.options.endDate) ?? stringOption(args.options["end-date"])
|
||||
})
|
||||
printJson(result, outputOptions(args.options))
|
||||
} catch (error) {
|
||||
if (error instanceof ExpenseLookupError) printJson(error.report, outputOptions(args.options))
|
||||
throw error
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import type { createSealClient } from "../../core/http/factory.js";
|
||||
import { traceInvoice } from "../../domains/seal/approval-runs/invoices.js";
|
||||
import { runCapability } from "../helpers.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import { outputOptions, printJson } from "../printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
|
||||
export async function handleInvoicesCommand(
|
||||
action: string | undefined,
|
||||
maybeTarget: string | undefined,
|
||||
client: Awaited<ReturnType<typeof createSealClient>>,
|
||||
corp: CorpConfig,
|
||||
args: ParsedArgs
|
||||
) {
|
||||
// Check if subcommand is "trace" or a positional invoice number
|
||||
const isTrace = action === "trace";
|
||||
const invoiceNumberToTrace = isTrace
|
||||
? (maybeTarget ?? stringOption(args.options.number) ?? stringOption(args.options.invoice))
|
||||
: (action && /^\d{10,25}$/.test(action) ? action : undefined);
|
||||
|
||||
if (invoiceNumberToTrace) {
|
||||
const report = await traceInvoice(client, invoiceNumberToTrace, corp.id);
|
||||
if (!report) {
|
||||
printJson(
|
||||
{
|
||||
found: false,
|
||||
invoiceNumber: invoiceNumberToTrace,
|
||||
message: `未在进项发票库中找到发票号码为 ${invoiceNumberToTrace} 的记录。`
|
||||
},
|
||||
outputOptions(args.options)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (report.conflictStatus === "MULTIPLE_DOCUMENTS_ATTACHED") {
|
||||
console.error(
|
||||
`\n💡 [CLI 辅助溯源指引](注:此指引由 seal-use CLI 基于进项发票库关联数据自动提炼,非后端大模型生成):\n` +
|
||||
`• 发票 ${report.invoice.invoiceNumber}(${report.invoice.sellerName},¥${report.invoice.totalAmount})在 ${report.associatedDocuments.length} 笔单据中均有挂载记录:\n` +
|
||||
report.associatedDocuments.map((d) => ` - 单号: ${d.sourceDocumentSN}(已占 ¥${d.usedAmount ?? 0})👉 诊断命令: ${d.nextDiagnose}`).join("\n") +
|
||||
`\n`
|
||||
);
|
||||
}
|
||||
|
||||
printJson(report, outputOptions(args.options));
|
||||
return;
|
||||
}
|
||||
|
||||
// Otherwise, default to list / search
|
||||
const searchQuery =
|
||||
stringOption(args.options.search) ??
|
||||
stringOption(args.options.query) ??
|
||||
(action && action !== "list" ? action : undefined);
|
||||
|
||||
const params = {
|
||||
offset: numberOption(args.options.offset),
|
||||
limit: numberOption(args.options.limit),
|
||||
startDate: stringOption(args.options.startDate) ?? stringOption(args.options["start-date"]),
|
||||
endDate: stringOption(args.options.endDate) ?? stringOption(args.options["end-date"]),
|
||||
search: searchQuery,
|
||||
full: booleanOption(args.options.full) === true
|
||||
};
|
||||
|
||||
await runCapability("sealInvoicesList", client, corp, params, outputOptions(args.options));
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { readFileSync, readdirSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { parseArgs } from "./parser.js";
|
||||
import { KNOWN_AREAS, UPDATE_ALIASES } from "./runner.js";
|
||||
|
||||
/**
|
||||
@@ -67,3 +68,79 @@ describe("documentation references live commands", () => {
|
||||
expect(stale).toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Usage-level closure for the generated cli.md block.
|
||||
*
|
||||
* `verify:cli-md` proves the block byte-matches what HELP_REGISTRY renders,
|
||||
* and parser.test.ts proves registry usage flags are registered — but nothing
|
||||
* fed the rendered lines back through the real parser. That is exactly the
|
||||
* hole the 2026-10-17 review found in the opposite direction: 22 parser tests
|
||||
* green while nine documented flags were rejected at runtime. Rendering is
|
||||
* code too, so the doc reader's copy-paste path gets its own parse.
|
||||
*/
|
||||
|
||||
const CLI_DOC_PATH = join(REPO_ROOT, "skills/seal-use/references/cli.md");
|
||||
|
||||
function generatedUsageLines(markdown: string): string[] {
|
||||
const block = markdown.match(
|
||||
/<!-- BEGIN GENERATED CLI COMMANDS -->([\s\S]*?)<!-- END GENERATED CLI COMMANDS -->/
|
||||
);
|
||||
if (!block?.[1]) throw new Error(`generated command block missing in ${CLI_DOC_PATH}`);
|
||||
return block[1].split("\n").filter((line) => line.startsWith("seal-use "));
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn a documented usage line into argv the way a reader would type it:
|
||||
* keep one alternative of each `a|b` group, unwrap `[...]` optionality, and
|
||||
* replace `<value hints>` with a neutral placeholder token. Single quotes are
|
||||
* respected so `--json '{...}'` payloads survive as one argument.
|
||||
*/
|
||||
function usageToArgv(line: string): string[] {
|
||||
// `--json '{...}'` is a fill-in placeholder in the docs, not literal JSON;
|
||||
// substitute a valid empty object so the parser sees a well-formed payload.
|
||||
const hinted = line.slice("seal-use ".length)
|
||||
.replace(/<[^<>]*>/g, " __HINT__ ")
|
||||
.replace(/'\{\.\.\.\}'/g, "'{}'");
|
||||
const unbracketed = hinted.replace(/[[\]]/g, " ");
|
||||
|
||||
const tokens: string[] = [];
|
||||
let current = "";
|
||||
let quoted = false;
|
||||
for (const char of unbracketed) {
|
||||
if (char === "'") {
|
||||
quoted = !quoted;
|
||||
continue;
|
||||
}
|
||||
if (!quoted && /\s/.test(char)) {
|
||||
if (current) tokens.push(current);
|
||||
current = "";
|
||||
continue;
|
||||
}
|
||||
current += char;
|
||||
}
|
||||
if (current) tokens.push(current);
|
||||
|
||||
return tokens.map((token) => token.split("|")[0]!).filter((token) => token.length > 0);
|
||||
}
|
||||
|
||||
describe("generated cli.md usage lines parse", () => {
|
||||
test("every documented usage line is accepted by parseArgs", () => {
|
||||
const lines = generatedUsageLines(readFileSync(CLI_DOC_PATH, "utf8"));
|
||||
// Format guard: if the markers or the `seal-use ` line convention change,
|
||||
// the extraction silently yields nothing and this suite would pass while
|
||||
// checking zero lines.
|
||||
expect(lines.length).toBeGreaterThan(100);
|
||||
|
||||
const rejected: Record<string, string> = {};
|
||||
for (const line of lines) {
|
||||
try {
|
||||
parseArgs(usageToArgv(line));
|
||||
} catch (error) {
|
||||
rejected[line] = error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
}
|
||||
|
||||
expect(rejected).toEqual({});
|
||||
});
|
||||
});
|
||||
+12
-1
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { extractHelpRequest, renderHelp } from "./help.js";
|
||||
import { extractHelpRequest, HELP_REGISTRY, renderHelp } from "./help.js";
|
||||
import { KNOWN_AREAS, runCli } from "./runner.js";
|
||||
|
||||
describe("extractHelpRequest", () => {
|
||||
@@ -210,6 +210,17 @@ describe("help coverage", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("every help registry area is dispatchable", () => {
|
||||
// The forward direction is checked above. The reverse catches a registry
|
||||
// area that renders help but no longer reaches a handler table — the
|
||||
// "documented for two releases after the dispatcher dropped it" failure
|
||||
// mode this suite exists to prevent, applied to `seal-use help` itself.
|
||||
const dead = HELP_REGISTRY.map((entry) => entry.area)
|
||||
.filter((area) => !KNOWN_AREAS.has(area));
|
||||
|
||||
expect(dead).toEqual([]);
|
||||
});
|
||||
|
||||
test("stop shortcut and server alias resolve to help", () => {
|
||||
expect(renderHelp(["server"])).toContain("seal-use mcp");
|
||||
});
|
||||
|
||||
+58
-17
@@ -515,7 +515,12 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
name: "list",
|
||||
aliases: ["search"],
|
||||
summary: "Search approval records by keyword, dates, or decision status",
|
||||
usage: ["seal-use approval-runs list|search [--query text] [--humanResult 驳回] [--manualApprovalStatus TERMINATED] [--startDate ms] [--endDate ms] [--limit 20] [--includeBridge true] [--corp <corpId>]"]
|
||||
usage: ["seal-use approval-runs list|search [--query text] [--humanResult 驳回] [--manualApprovalStatus TERMINATED] [--startDate ms] [--endDate ms] [--has-extra-risk] [--limit 20] [--includeBridge true] [--corp <corpId>]"],
|
||||
options: [
|
||||
{ flag: "--has-extra-risk", description: "Filter the fetched page to records with warning/error in result.otherFindings; info is excluded. Includes extraRisks with titles, levels and descriptions." },
|
||||
{ flag: "--limit <n>", description: "Records to scan before local filtering (default 50, maximum 100); no automatic pagination to fill matches" },
|
||||
{ flag: "--offset <n>", description: "Offset in the upstream result set before local filtering" }
|
||||
]
|
||||
},
|
||||
{
|
||||
name: "pick",
|
||||
@@ -1032,7 +1037,7 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
{ flag: "--from-link <url>", description: "直接由合思协助链接换取 Seal 委托直达链接" }
|
||||
],
|
||||
description:
|
||||
"生成访问当前企业 Seal AI 智能审核后台 (https://<tenant>.sealai.cc/delegate) 的免密直达链接。主体作用于 Seal 审核后台。"
|
||||
"生成访问当前企业 Seal AI 智能审核后台 (https://<tenant>.sealai.cc/delegate) 的免密直达链接。返回实际会话人员 staffName、identityStatus、isAdmin 和 permissions;姓名查询失败时明确标记为未核实。主体作用于 Seal 审核后台。"
|
||||
},
|
||||
{
|
||||
name: "link list",
|
||||
@@ -1054,7 +1059,7 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
{ flag: "--force, --refresh, -f", description: "强制向合思 OpenAPI 申请全新临时凭证" }
|
||||
],
|
||||
description:
|
||||
"专用于合思 (Hose) 来源企业。向合思申请临时 ticket,生成直达外部合思/易快报主站 (https://app.ekuaibao.com/web/thirdparty.html) 的免密登录链接。若需生成 Seal 自身的审核后台访问链接,请使用 'seal-use auth link'。"
|
||||
"专用于合思 (Hose) 来源企业。向合思申请临时 ticket,生成直达外部合思/易快报主站 (https://app.ekuaibao.com/web/thirdparty.html) 的免密登录链接。自动查询绑定员工的 staffName、identityStatus 和 roleNames;未能核实的姓名或角色明确标记为未知。若需生成 Seal 自身的审核后台访问链接,请使用 'seal-use auth link'。"
|
||||
},
|
||||
{
|
||||
name: "hose-openapi-token",
|
||||
@@ -1169,13 +1174,49 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
commands: [
|
||||
{
|
||||
name: "expenses",
|
||||
summary: "Search raw expense items",
|
||||
usage: ["seal-use data expenses [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--corp <corpId>]"]
|
||||
summary: "List expenses, or verify expense-store membership by exact document number with --sn",
|
||||
usage: ["seal-use data expenses [--sn <documentSN>|--record-id <recordId>|--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--max-scan <n>] [--corp <corpId>]"]
|
||||
},
|
||||
{
|
||||
name: "invoices",
|
||||
summary: "Search raw invoice records",
|
||||
usage: ["seal-use data invoices [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--corp <corpId>]"]
|
||||
summary: "Search raw invoice records (also available as 'seal-use invoices')",
|
||||
usage: ["seal-use data invoices [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--full] [--corp <corpId>]"]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
area: "invoices",
|
||||
title: "进项发票查询与溯源",
|
||||
description: "查看已审批单据中出现的进项发票,支持单据关联穿透、跨单据重复占用排查与扁平化业务视图。",
|
||||
commands: [
|
||||
{
|
||||
name: "list",
|
||||
summary: "分页查询进项发票(默认输出扁平化业务字段,对齐控制台表格)",
|
||||
usage: [
|
||||
"seal-use invoices [list] [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--full] [--corp <corpId>]"
|
||||
]
|
||||
},
|
||||
{
|
||||
name: "trace",
|
||||
summary: "穿透溯源指定发票,排查在哪些报销单据中被使用及是否存在跨单重复占用",
|
||||
usage: [
|
||||
"seal-use invoices trace <invoiceNumber> [--corp <corpId>]",
|
||||
"seal-use invoices <invoiceNumber> [--corp <corpId>]"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
area: "expenses",
|
||||
title: "费用明细查询",
|
||||
description: "查询历史费用明细;--sn 按单号关联审批记录并核验费用库存在性,区分找到、关联范围内未找到和无法确定。",
|
||||
commands: [
|
||||
{
|
||||
name: "list",
|
||||
summary: "普通查询分页返回原始记录;--sn 自动翻页核验,--limit 为页大小,--max-scan 默认为 5000",
|
||||
usage: [
|
||||
"seal-use expenses [list] [--sn <documentSN>|--record-id <recordId>|--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--max-scan <n>] [--corp <corpId>]"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -1311,13 +1352,13 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
commands: [
|
||||
{
|
||||
name: "list",
|
||||
summary: "List approval knowledge documents",
|
||||
usage: ["seal-use documents list [--scenarios <audit,fill>] [--limit 50] [--offset 0] [--corp <corpId>]"]
|
||||
summary: "List knowledge documents; --summary omits body, --fields selects explicit fields",
|
||||
usage: ["seal-use documents list [--summary] [--fields <id,title,purpose,updatedAt>] [--scenarios <audit,fill>] [--limit 50] [--offset 0] [--corp <corpId>]"]
|
||||
},
|
||||
{
|
||||
name: "get",
|
||||
summary: "Get approval knowledge document details by ID",
|
||||
usage: ["seal-use documents get <documentId> [--corp <corpId>]"]
|
||||
summary: "Get document JSON, or export exact UTF-8 body plus baseline with --out; --output-file saves JSON",
|
||||
usage: ["seal-use documents get <documentId> [--out <path>] [--content-format raw] [--overwrite] [--corp <corpId>]"]
|
||||
},
|
||||
{
|
||||
name: "search",
|
||||
@@ -1326,22 +1367,22 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
},
|
||||
{
|
||||
name: "create",
|
||||
summary: "Create a new approval knowledge document",
|
||||
summary: "Preview with --dry-run; --yes/--confirm creates and verifies a knowledge document",
|
||||
usage: [
|
||||
"seal-use documents create --title <title> --purpose <purpose> [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]"
|
||||
"seal-use documents create --title <title> --purpose <purpose> [--content <text>|--content-file <path>] [--content-format raw] [--allow-empty] [--type <policy|document|video|pdf|feishu_doc>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--dry-run|--yes|--confirm] [--corp <corpId>]"
|
||||
]
|
||||
},
|
||||
{
|
||||
name: "update",
|
||||
summary: "Update an approval knowledge document by ID",
|
||||
summary: "Preview changes; confirmed updates check export baseline, snapshot and verify readback",
|
||||
usage: [
|
||||
"seal-use documents update <documentId> [--title <title>] [--purpose <purpose>] [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--enabled <true|false>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]"
|
||||
"seal-use documents update <documentId> [--title <title>] [--purpose <purpose>] [--content <text>|--content-file <path>] [--content-format raw] [--allow-empty] [--type <policy|document|video|pdf|feishu_doc>] [--enabled <true|false>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--dry-run|--yes|--confirm] [--corp <corpId>]"
|
||||
]
|
||||
},
|
||||
{
|
||||
name: "delete",
|
||||
summary: "Delete an approval knowledge document by ID",
|
||||
usage: ["seal-use documents delete <documentId> --yes [--corp <corpId>]"]
|
||||
summary: "Preview deletion; --yes/--confirm snapshots the document before deleting it",
|
||||
usage: ["seal-use documents delete <documentId> [--dry-run|--yes|--confirm] [--corp <corpId>]"]
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
+4
-4
@@ -23,13 +23,13 @@ import { usageError, validationError } from "../core/errors.js";
|
||||
|
||||
// Read with booleanOption(...) / Boolean(...) / presence check.
|
||||
export const BOOLEAN_FLAGS = new Set([
|
||||
"clear", "clear-max-file-size", "clearMaxFileSize", "latest", "show-secret", "showSecret",
|
||||
"allow-empty", "allowEmpty", "clear", "clear-max-file-size", "clearMaxFileSize", "latest", "show-secret", "showSecret",
|
||||
"V", "add", "all", "allow-unreviewed", "allowUnreviewed", "as-hose", "attachments", "auto",
|
||||
"auto-login", "autoLogin", "bg-save", "changelog", "check", "check-only",
|
||||
"completed-only", "completedOnly", "confirm", "count", "disable-attachment-cache", "disableAttachmentCache",
|
||||
"download", "downloads", "dry-run", "dryRun", "elevate-hose", "enabled",
|
||||
"exclude-deleted", "extract", "extract-expenses", "extractExpenses", "fail-on-flips", "flow", "force", "full", "glossary", "has-input", "has-output", "help",
|
||||
"hose", "hose-outbound", "hose-sso", "hoseOutbound", "hoseSso", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
|
||||
"has-extra-risk", "hasExtraRisk", "hose", "hose-outbound", "hose-sso", "hoseOutbound", "hoseSso", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
|
||||
"includeBridge", "includeSimulation", "includeUnchanged", "local", "no-attachments", "no-flow", "no-glossary",
|
||||
"no-wait", "noWait", "outbound", "overwrite", "plain", "publish", "quiet",
|
||||
"r", "recode", "refresh", "refresh-if-missing", "reveal", "rotate-secret", "rotateSecret",
|
||||
@@ -47,7 +47,7 @@ export const VALUE_FLAGS = new Set([
|
||||
"access-token", "accessToken", "action", "add-approver-ids", "addApproverIds", "ai", "ai-accuracy", "aiAccuracy", "app-key", "app-security", "appKey", "appSecurity",
|
||||
"base-url", "batch", "batch-id", "batchId", "both", "both-accurate", "bothAccurate", "business-codes", "businessCodes",
|
||||
"channel", "chrome", "code", "comment", "concurrency", "confirm-code", "confirmCode", "content", "content-file", "content-hints", "content-type", "contentFile",
|
||||
"contentType", "context-chars", "contextLines", "corp", "corp-id", "corpId", "corporation-id", "corporationId", "date",
|
||||
"content-format", "contentFormat", "contentType", "context-chars", "contextLines", "corp", "corp-id", "corpId", "corporation-id", "corporationId", "date",
|
||||
"dedupe-by", "dedupeBy", "default", "departmentId", "dept", "desc",
|
||||
"description", "description-file", "descriptionFile", "dir", "doc-id-prefix", "doc-id-suffix",
|
||||
"docIdPrefix", "docIdSuffix", "document-id", "document-sn", "document-sns", "document-type",
|
||||
@@ -59,7 +59,7 @@ export const VALUE_FLAGS = new Set([
|
||||
"json", "json-path", "key-id", "keyId", "keyword", "ledger", "level", "limit",
|
||||
"lines", "link", "linter", "manual-status", "manualApprovalStatus", "manualStatus",
|
||||
"max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "message-id", "messageId", "metadata", "metadata-key", "min-score", "minScore", "mode",
|
||||
"max-runs",
|
||||
"max-runs", "max-scan", "maxScan",
|
||||
"month",
|
||||
"n", "name", "name-contains", "node-id", "nodeId", "note", "observation-id", "observation-types", "o", "offset", "out",
|
||||
"out-dir", "outDir", "outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file",
|
||||
|
||||
@@ -27,7 +27,8 @@ describe("CLI read-only classification", () => {
|
||||
"auth test",
|
||||
"auth doctor",
|
||||
"auth seal-link list",
|
||||
"doctor auth"
|
||||
"doctor auth",
|
||||
"expenses "
|
||||
]);
|
||||
|
||||
test("every allow-listed command exists in the help registry", () => {
|
||||
@@ -55,7 +56,13 @@ describe("CLI read-only classification", () => {
|
||||
["corp", "list"],
|
||||
["corp", "get", "corp-a"],
|
||||
["documents", "list", "--corp", "corp-a"],
|
||||
["expenses", "--sn", "SN-FIXTURE", "--corp", "corp-a"],
|
||||
["expenses", "list", "--record-id", "run-1", "--corp", "corp-a"],
|
||||
["expense", "--sn", "SN-FIXTURE", "--corp", "corp-a"],
|
||||
["data", "expenses", "--sn", "SN-FIXTURE", "--corp", "corp-a"],
|
||||
["documents", "get", "doc-1", "--corp", "corp-a"],
|
||||
["documents", "get", "doc-1", "--out", "./body.txt", "--corp", "corp-a"],
|
||||
["documents", "list", "--summary", "--fields", "id,title", "--corp", "corp-a"],
|
||||
["documents", "search", "差旅", "--corp", "corp-a"],
|
||||
["approval-runs", "get", "01a09dac-c688-767b-8eb4-37b945095585"],
|
||||
["approval-runs", "list", "--corp", "corp-a"],
|
||||
@@ -89,6 +96,7 @@ describe("CLI read-only classification", () => {
|
||||
["rules", "clear"],
|
||||
["documents", "create"],
|
||||
["documents", "update", "doc-1"],
|
||||
["documents", "update", "doc-1", "--content-file", "body.txt", "--dry-run", "--yes"],
|
||||
["documents", "delete", "doc-1"],
|
||||
["simulation", "create", "--mode", "hosecloud"],
|
||||
["deploy", "hosecloud", "sync", "sign-key"],
|
||||
|
||||
@@ -70,6 +70,7 @@ const READ_ONLY_COMMANDS: Record<string, string[]> = {
|
||||
users: ["search", "get"],
|
||||
contacts: ["departments", "children", "users", "sync-time"],
|
||||
data: ["expenses", "invoices"],
|
||||
expenses: ["", "list"],
|
||||
llm: ["config", "providers"],
|
||||
permissions: ["available", "configs"],
|
||||
billing: ["status", "plans", "features"],
|
||||
|
||||
@@ -65,6 +65,8 @@ const CLIENT_COMMANDS: Record<string, ClientCommand> = {
|
||||
"users": async (args, corp, client) => (await import("./commands/users.js")).handleUsersCommand(args.command[1], args.command[2], client, corp, args),
|
||||
"contacts": async (args, corp, client) => (await import("./commands/contacts.js")).handleContactsCommand(args.command[1], args.command[2], client, corp, args),
|
||||
"data": async (args, corp, client) => (await import("./commands/data.js")).handleDataCommand(args.command[1], client, corp, args),
|
||||
"invoices": async (args, corp, client) => (await import("./commands/invoices.js")).handleInvoicesCommand(args.command[1], args.command[2], client, corp, args),
|
||||
"expenses": async (args, corp, client) => (await import("./commands/expenses.js")).handleExpensesCommand(args.command[1], client, corp, args),
|
||||
"llm": async (args, corp, client) => (await import("./commands/llm.js")).handleLlmCommand(args.command[1], client, corp, args),
|
||||
"permissions": async (args, corp, client) => (await import("./commands/permissions.js")).handlePermissionsCommand(args.command[1], client, corp, args),
|
||||
"billing": async (args, corp, client) => (await import("./commands/billing.js")).handleBillingCommand(args.command[1], client, corp, args),
|
||||
|
||||
@@ -142,14 +142,22 @@ describe("loadCorpConfigs", () => {
|
||||
test("same-directory duplicates and invalid shadows use the selected valid file", () => {
|
||||
const dir = makeTempDir();
|
||||
process.env.SEAL_USE_ENTERPRISES_DIR = dir;
|
||||
writeCorpConfig(join(dir, "a.json"), "duplicate", "First");
|
||||
const selected = join(dir, "b.json");
|
||||
writeCorpConfig(selected, "duplicate", "Second");
|
||||
const first = join(dir, "a.json");
|
||||
const second = join(dir, "b.json");
|
||||
writeCorpConfig(first, "duplicate", "First");
|
||||
writeCorpConfig(second, "duplicate", "Second");
|
||||
writeFileSync(join(dir, "z-invalid.json"), JSON.stringify({ id: "duplicate" }));
|
||||
// Filesystem enumeration order differs across platforms; writes must follow reads.
|
||||
const selectedName = loadCorpConfigs()[0]?.name;
|
||||
expect(["First", "Second"]).toContain(selectedName ?? "");
|
||||
const selected = selectedName === "First" ? first : second;
|
||||
const untouched = selectedName === "First" ? second : first;
|
||||
const untouchedName = JSON.parse(readFileSync(untouched, "utf8")).name;
|
||||
expect(findCorpConfigFile("duplicate")).toBe(selected);
|
||||
updateCorpConfig("duplicate", { name: "Updated" });
|
||||
expect(loadCorpConfigs()[0]?.name).toBe("Updated");
|
||||
expect(JSON.parse(readFileSync(join(dir, "a.json"), "utf8")).name).toBe("First");
|
||||
expect(JSON.parse(readFileSync(selected, "utf8")).name).toBe("Updated");
|
||||
expect(JSON.parse(readFileSync(untouched, "utf8")).name).toBe(untouchedName);
|
||||
});
|
||||
|
||||
test.skipIf(process.platform === "win32")("credential updates and overwrites tighten existing files", () => {
|
||||
|
||||
@@ -13,17 +13,19 @@ import file9 from "../../skills/seal-use/references/approval-bad-cases.md" with
|
||||
import file10 from "../../skills/seal-use/references/approval-run-lightweight.md" with { type: "text" };
|
||||
import file11 from "../../skills/seal-use/references/cli.md" with { type: "text" };
|
||||
import file12 from "../../skills/seal-use/references/customer-feedback-rule-remediation.md" with { type: "text" };
|
||||
import file13 from "../../skills/seal-use/references/enterprise-onboarding.md" with { type: "text" };
|
||||
import file14 from "../../skills/seal-use/references/first-time-user.md" with { type: "text" };
|
||||
import file15 from "../../skills/seal-use/references/hose-enterprise-auth.md" with { type: "text" };
|
||||
import file16 from "../../skills/seal-use/references/hose-enterprise-deploy.md" with { type: "text" };
|
||||
import file17 from "../../skills/seal-use/references/hose-enterprise-init.md" with { type: "text" };
|
||||
import file18 from "../../skills/seal-use/references/langfuse-trace.md" with { type: "text" };
|
||||
import file19 from "../../skills/seal-use/references/report-templates.md" with { type: "text" };
|
||||
import file20 from "../../skills/seal-use/references/rule-lightweight.md" with { type: "text" };
|
||||
import file21 from "../../skills/seal-use/references/rule-lint.md" with { type: "text" };
|
||||
import file22 from "../../skills/seal-use/references/staging-simulation-workflow.md" with { type: "text" };
|
||||
import file23 from "../../skills/seal-use/references/webhook-resource-pack.md" with { type: "text" };
|
||||
import file13 from "../../skills/seal-use/references/documents.md" with { type: "text" };
|
||||
import file14 from "../../skills/seal-use/references/enterprise-onboarding.md" with { type: "text" };
|
||||
import file15 from "../../skills/seal-use/references/expense-data.md" with { type: "text" };
|
||||
import file16 from "../../skills/seal-use/references/first-time-user.md" with { type: "text" };
|
||||
import file17 from "../../skills/seal-use/references/hose-enterprise-auth.md" with { type: "text" };
|
||||
import file18 from "../../skills/seal-use/references/hose-enterprise-deploy.md" with { type: "text" };
|
||||
import file19 from "../../skills/seal-use/references/hose-enterprise-init.md" with { type: "text" };
|
||||
import file20 from "../../skills/seal-use/references/langfuse-trace.md" with { type: "text" };
|
||||
import file21 from "../../skills/seal-use/references/report-templates.md" with { type: "text" };
|
||||
import file22 from "../../skills/seal-use/references/rule-lightweight.md" with { type: "text" };
|
||||
import file23 from "../../skills/seal-use/references/rule-lint.md" with { type: "text" };
|
||||
import file24 from "../../skills/seal-use/references/staging-simulation-workflow.md" with { type: "text" };
|
||||
import file25 from "../../skills/seal-use/references/webhook-resource-pack.md" with { type: "text" };
|
||||
|
||||
export const EMBEDDED_SKILL_TEXT_FILES: Record<string, string> = {
|
||||
"SKILL.md": file0,
|
||||
@@ -33,17 +35,19 @@ export const EMBEDDED_SKILL_TEXT_FILES: Record<string, string> = {
|
||||
"references/approval-run-lightweight.md": file10,
|
||||
"references/cli.md": file11,
|
||||
"references/customer-feedback-rule-remediation.md": file12,
|
||||
"references/enterprise-onboarding.md": file13,
|
||||
"references/first-time-user.md": file14,
|
||||
"references/hose-enterprise-auth.md": file15,
|
||||
"references/hose-enterprise-deploy.md": file16,
|
||||
"references/hose-enterprise-init.md": file17,
|
||||
"references/langfuse-trace.md": file18,
|
||||
"references/report-templates.md": file19,
|
||||
"references/rule-lightweight.md": file20,
|
||||
"references/rule-lint.md": file21,
|
||||
"references/staging-simulation-workflow.md": file22,
|
||||
"references/webhook-resource-pack.md": file23,
|
||||
"references/documents.md": file13,
|
||||
"references/enterprise-onboarding.md": file14,
|
||||
"references/expense-data.md": file15,
|
||||
"references/first-time-user.md": file16,
|
||||
"references/hose-enterprise-auth.md": file17,
|
||||
"references/hose-enterprise-deploy.md": file18,
|
||||
"references/hose-enterprise-init.md": file19,
|
||||
"references/langfuse-trace.md": file20,
|
||||
"references/report-templates.md": file21,
|
||||
"references/rule-lightweight.md": file22,
|
||||
"references/rule-lint.md": file23,
|
||||
"references/staging-simulation-workflow.md": file24,
|
||||
"references/webhook-resource-pack.md": file25,
|
||||
};
|
||||
|
||||
export const EMBEDDED_SKILL_ASSET_PATHS: Record<string, string> = {
|
||||
@@ -69,7 +73,9 @@ export const EMBEDDED_SKILL_ALL_PATHS = [
|
||||
"references/approval-run-lightweight.md",
|
||||
"references/cli.md",
|
||||
"references/customer-feedback-rule-remediation.md",
|
||||
"references/documents.md",
|
||||
"references/enterprise-onboarding.md",
|
||||
"references/expense-data.md",
|
||||
"references/first-time-user.md",
|
||||
"references/hose-enterprise-auth.md",
|
||||
"references/hose-enterprise-deploy.md",
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { writeSecureFile } from "./secure-file.js";
|
||||
|
||||
/**
|
||||
* Direct unit tests for the credential write path.
|
||||
*
|
||||
* Indirect coverage exists through loader/token-store mode assertions, but
|
||||
* this helper is the single choke point that keeps existing world-readable
|
||||
* credential files from staying world-readable — the P0 from the 2026-10-17
|
||||
* architecture review. Its guarantees deserve their own colocated tests so a
|
||||
* refactor of either caller cannot silently drop them.
|
||||
*/
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
function tempDir(): string {
|
||||
const dir = mkdtempSync(join(tmpdir(), "seal-secure-file-"));
|
||||
tempDirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of tempDirs.splice(0)) {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
function fileMode(path: string): number {
|
||||
return statSync(path).mode & 0o777;
|
||||
}
|
||||
|
||||
describe("writeSecureFile", () => {
|
||||
test("creates a new credential file as 0600 with exact content", () => {
|
||||
const dir = tempDir();
|
||||
const target = join(dir, "tokens.json");
|
||||
|
||||
writeSecureFile(target, '{"token":"secret"}\n');
|
||||
|
||||
expect(fileMode(target)).toBe(0o600);
|
||||
expect(readFileSync(target, "utf8")).toBe('{"token":"secret"}\n');
|
||||
});
|
||||
|
||||
test("tightens a pre-existing 0644 file to 0600 on write", () => {
|
||||
const dir = tempDir();
|
||||
const target = join(dir, "corp.json");
|
||||
writeFileSync(target, '{"old":"legacy-inherited"}', { mode: 0o644 });
|
||||
chmodSync(target, 0o644);
|
||||
expect(fileMode(target)).toBe(0o644);
|
||||
|
||||
writeSecureFile(target, '{"new":"rotated-secret"}');
|
||||
|
||||
expect(fileMode(target)).toBe(0o600);
|
||||
expect(readFileSync(target, "utf8")).toBe('{"new":"rotated-secret"}');
|
||||
});
|
||||
|
||||
test("truncates longer previous content so no secret residue survives", () => {
|
||||
const dir = tempDir();
|
||||
const target = join(dir, "tokens.json");
|
||||
writeSecureFile(target, '{"access":"a","refresh":"b","extra":"padding-padding"}');
|
||||
|
||||
writeSecureFile(target, "{}");
|
||||
|
||||
expect(readFileSync(target, "utf8")).toBe("{}");
|
||||
});
|
||||
|
||||
test("accepts binary content such as embedded skill assets", () => {
|
||||
const dir = tempDir();
|
||||
const target = join(dir, "asset.png");
|
||||
const bytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x00, 0xff]);
|
||||
|
||||
writeSecureFile(target, bytes);
|
||||
|
||||
expect(fileMode(target)).toBe(0o600);
|
||||
expect(new Uint8Array(readFileSync(target))).toEqual(bytes);
|
||||
});
|
||||
|
||||
test("creates missing parent directories as 0700", () => {
|
||||
const dir = tempDir();
|
||||
const target = join(dir, "nested", "deeper", "tokens.json");
|
||||
|
||||
writeSecureFile(target, "{}");
|
||||
|
||||
expect(fileMode(target)).toBe(0o600);
|
||||
expect(fileMode(join(dir, "nested"))).toBe(0o700);
|
||||
expect(fileMode(join(dir, "nested", "deeper"))).toBe(0o700);
|
||||
});
|
||||
|
||||
test("does not rewrite the mode of a user-owned parent directory", () => {
|
||||
const dir = tempDir();
|
||||
const shared = join(dir, "shared");
|
||||
mkdirSync(shared, { mode: 0o755 });
|
||||
chmodSync(shared, 0o755);
|
||||
|
||||
writeSecureFile(join(shared, "corp.json"), "{}");
|
||||
|
||||
expect(fileMode(shared)).toBe(0o755);
|
||||
expect(fileMode(join(shared, "corp.json"))).toBe(0o600);
|
||||
});
|
||||
});
|
||||
@@ -280,6 +280,23 @@ describe("Seal contact API", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
test("expenses always sends a filter object and supports recordId plus normalized dates", async () => {
|
||||
const queries: URLSearchParams[] = [];
|
||||
const client = {
|
||||
get: (_url: string, options: { searchParams: URLSearchParams }) => {
|
||||
queries.push(options.searchParams);
|
||||
return { json: async () => ({ data: { expenses: [], total: 0 } }) };
|
||||
}
|
||||
} as unknown as KyInstance;
|
||||
await listExpenses(client);
|
||||
expect(queries[0]?.has("filter[search]")).toBe(true);
|
||||
expect(queries[0]?.get("filter[search]")).toBe("");
|
||||
expect(queries[0]?.has("filter[startDate]")).toBe(false);
|
||||
await listExpenses(client, { recordId: "record-fixture", startDate: "2025-01-01T00:00:00+08:00" });
|
||||
expect(queries[1]?.get("filter[recordId]")).toBe("record-fixture");
|
||||
expect(queries[1]?.get("filter[startDate]")).toBe("1735660800000");
|
||||
});
|
||||
|
||||
test("lists Feishu simulation approval definitions", async () => {
|
||||
let requestedUrl = "";
|
||||
const client = {
|
||||
|
||||
+18
-4
@@ -10,7 +10,7 @@ import { CorpConfig } from "../../core/config/types.js";
|
||||
import { ensureHoseOpenapiToken, fetchHoseCloseApiToken, defaultSealUrl, normalizeBaseUrl } from "../../core/auth/hose.js";
|
||||
import { createSealClientForUrl } from "../../core/http/factory.js";
|
||||
import { redactSensitiveText } from "../../core/redact.js";
|
||||
import { safetyBlocked } from "../../core/errors.js";
|
||||
import { safetyBlocked, validationError } from "../../core/errors.js";
|
||||
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
|
||||
import {
|
||||
ApprovalDocumentListData,
|
||||
@@ -245,6 +245,7 @@ export async function createApprovalDocument(
|
||||
) {
|
||||
return unwrap(
|
||||
await client.post("api/v1/knowledge/articles", {
|
||||
retry: 0,
|
||||
json: {
|
||||
...params,
|
||||
contentType: params.contentType ?? "policy",
|
||||
@@ -278,6 +279,7 @@ export async function updateApprovalDocument(
|
||||
|
||||
return unwrap(
|
||||
await client.patch(`api/v1/knowledge/articles/${documentId}`, {
|
||||
retry: 0,
|
||||
json: { attributes }
|
||||
}),
|
||||
ApprovalDocumentSchema
|
||||
@@ -288,7 +290,7 @@ export async function deleteApprovalDocument(
|
||||
client: KyInstance,
|
||||
documentId: string
|
||||
): Promise<{ success: boolean; id: string }> {
|
||||
await client.delete(`api/v1/knowledge/articles/${documentId}`);
|
||||
await client.delete(`api/v1/knowledge/articles/${documentId}`, { retry: 0 });
|
||||
return { success: true, id: documentId };
|
||||
}
|
||||
|
||||
@@ -1123,6 +1125,8 @@ export type DataListParams = {
|
||||
search?: string;
|
||||
};
|
||||
|
||||
export type ExpenseListParams = DataListParams & { recordId?: string };
|
||||
|
||||
function dataListSearchParams(params: DataListParams): URLSearchParams {
|
||||
const searchParams = new URLSearchParams();
|
||||
setOptional(searchParams, "filter[startDate]", params.startDate);
|
||||
@@ -1135,10 +1139,20 @@ function dataListSearchParams(params: DataListParams): URLSearchParams {
|
||||
|
||||
export async function listExpenses(
|
||||
client: KyInstance,
|
||||
params: DataListParams = {}
|
||||
params: ExpenseListParams = {}
|
||||
): Promise<ExpenseListData> {
|
||||
// The expense endpoint requires a filter object even for an unfiltered list.
|
||||
const searchParams = dataListSearchParams(params);
|
||||
searchParams.set("filter[search]", params.search ?? "");
|
||||
setOptional(searchParams, "filter[recordId]", params.recordId);
|
||||
for (const [key, value] of [["startDate", params.startDate], ["endDate", params.endDate]] as const) {
|
||||
if (value !== undefined) {
|
||||
try { searchParams.set(`filter[${key}]`, String(normalizeToTimestamp(value))); }
|
||||
catch { throw validationError(`Invalid expense ${key}: expected ISO date or timestamp`); }
|
||||
}
|
||||
}
|
||||
return unwrap(
|
||||
await client.get("api/v1/expenses/list", { searchParams: dataListSearchParams(params) }),
|
||||
await client.get("api/v1/expenses/list", { searchParams }),
|
||||
ExpenseListDataSchema
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { summarizeExtraFindings } from "./extra-findings.js"
|
||||
|
||||
describe("extra findings", () => {
|
||||
test("counts warning/error separately from info and ignores rule-bound findings", () => {
|
||||
const summary = summarizeExtraFindings({
|
||||
id: "run-1",
|
||||
result: {
|
||||
decision: "APPROVE",
|
||||
rulesResult: [{ id: "rule-1", findings: [{ level: "error" }] }],
|
||||
otherFindings: [
|
||||
{ title: "说明", description: "仅作说明", level: "info" },
|
||||
{ title: "待核实", description: "凭证主体不同", level: "warning", location: { scope: "FORM", refId: "" } },
|
||||
{ title: "异常", description: "金额不符", level: "error" }
|
||||
]
|
||||
}
|
||||
}, true)
|
||||
expect(summary).toEqual({
|
||||
extraFindingsStatus: "known", otherFindingCount: 3, extraRiskCount: 2, hasExtraRisk: true,
|
||||
extraRisks: [
|
||||
{ title: "待核实", description: "凭证主体不同", level: "warning" },
|
||||
{ title: "异常", description: "金额不符", level: "error" }
|
||||
]
|
||||
})
|
||||
})
|
||||
|
||||
test("empty arrays and info-only findings are known negatives regardless of decision", () => {
|
||||
for (const otherFindings of [[], [{ title: "说明", description: "无需处理", level: "info" }]]) {
|
||||
expect(summarizeExtraFindings({ id: "run", result: { decision: "REJECT", otherFindings } }, true)).toEqual({
|
||||
extraFindingsStatus: "known", otherFindingCount: otherFindings.length,
|
||||
extraRiskCount: 0, hasExtraRisk: false, extraRisks: []
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
test("missing, unsupported and partially malformed results remain unknown", () => {
|
||||
for (const result of [
|
||||
undefined, null, "{}", [], {}, { riskPoints: ["风险"] },
|
||||
{ otherFindings: null }, { otherFindings: {} }, { otherFindings: [null] },
|
||||
{ otherFindings: [{ title: "标题", description: "内容", level: "critical" }] },
|
||||
{ otherFindings: [{ level: "warning" }] },
|
||||
{ otherFindings: [{ title: "标题", description: "内容", level: "warning" }, "bad"] }
|
||||
]) {
|
||||
expect(summarizeExtraFindings({ id: "run", result }, true)).toEqual({
|
||||
extraFindingsStatus: "unknown", otherFindingCount: null,
|
||||
extraRiskCount: null, hasExtraRisk: null, extraRisks: null
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
test("default summaries omit risk detail", () => {
|
||||
expect(summarizeExtraFindings({ id: "run", result: { otherFindings: [] } })).not.toHaveProperty("extraRisks")
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,46 @@
|
||||
import { z } from "zod"
|
||||
import type { ApprovalRun } from "../types.js"
|
||||
|
||||
const extraFindingSchema = z.object({
|
||||
title: z.string(),
|
||||
description: z.string(),
|
||||
level: z.enum(["info", "warning", "error"])
|
||||
})
|
||||
const extraFindingsSchema = z.array(extraFindingSchema)
|
||||
|
||||
export type ExtraRisk = z.infer<typeof extraFindingSchema>
|
||||
|
||||
export type ExtraFindingsSummary = {
|
||||
extraFindingsStatus: "known" | "unknown";
|
||||
otherFindingCount: number | null;
|
||||
extraRiskCount: number | null;
|
||||
hasExtraRisk: boolean | null;
|
||||
extraRisks?: ExtraRisk[] | null;
|
||||
}
|
||||
|
||||
/** Only otherFindings classifies rule-independent discoveries; missing data is not a negative. */
|
||||
export function summarizeExtraFindings(record: ApprovalRun, includeRisks = false): ExtraFindingsSummary {
|
||||
const result = record.result
|
||||
const raw = result && typeof result === "object" && !Array.isArray(result)
|
||||
? (result as Record<string, unknown>).otherFindings
|
||||
: undefined
|
||||
const parsed = extraFindingsSchema.safeParse(raw)
|
||||
if (!parsed.success) {
|
||||
return {
|
||||
extraFindingsStatus: "unknown",
|
||||
otherFindingCount: null,
|
||||
extraRiskCount: null,
|
||||
hasExtraRisk: null,
|
||||
...(includeRisks ? { extraRisks: null } : {})
|
||||
}
|
||||
}
|
||||
|
||||
const risks = parsed.data.filter(finding => finding.level === "warning" || finding.level === "error")
|
||||
return {
|
||||
extraFindingsStatus: "known",
|
||||
otherFindingCount: parsed.data.length,
|
||||
extraRiskCount: risks.length,
|
||||
hasExtraRisk: risks.length > 0,
|
||||
...(includeRisks ? { extraRisks: risks } : {})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import {
|
||||
flattenInvoiceRecord,
|
||||
extractDocumentInvoices,
|
||||
detectInvoiceConflicts,
|
||||
normalizeInvoiceDate,
|
||||
normalizeInvoiceStatus
|
||||
} from "./invoices.js";
|
||||
import type { ApprovalRun } from "../types.js";
|
||||
|
||||
describe("invoices domain module", () => {
|
||||
test("normalizeInvoiceDate formats 8-digit and slash dates to YYYY-MM-DD", () => {
|
||||
expect(normalizeInvoiceDate("20260617")).toBe("2026-06-17");
|
||||
expect(normalizeInvoiceDate("2026/06/17")).toBe("2026-06-17");
|
||||
expect(normalizeInvoiceDate("2026-06-17")).toBe("2026-06-17");
|
||||
expect(normalizeInvoiceDate("")).toBe("");
|
||||
});
|
||||
|
||||
test("normalizeInvoiceStatus correctly normalizes verified status", () => {
|
||||
expect(normalizeInvoiceStatus(undefined, "NORMAL_BLUE")).toBe("已验真 (verified)");
|
||||
expect(normalizeInvoiceStatus("verified", undefined)).toBe("已验真 (verified)");
|
||||
expect(normalizeInvoiceStatus(undefined, undefined, "NORMAL_BLUE")).toBe("已验真 (verified)");
|
||||
});
|
||||
|
||||
test("flattenInvoiceRecord flattens nested verifyResult and fileInfo into 8 core business fields", () => {
|
||||
const raw = {
|
||||
id: "inv-1",
|
||||
invoiceNumber: "26957000000102316227",
|
||||
sourceDocumentSN: "B26002404",
|
||||
totalAmount: 500,
|
||||
usedAmount: 409.02,
|
||||
verifyStatus: "verified",
|
||||
verifyResult: {
|
||||
invoiceType: "电子发票(普通发票)",
|
||||
sellerName: "深圳石油公明加油站",
|
||||
buyerName: "钰泰半导体股份有限公司",
|
||||
invoiceDate: "2026-06-17"
|
||||
},
|
||||
fileInfo: {
|
||||
fileName: "test.pdf",
|
||||
ossSignedUrl: "https://oss.example.com/test.pdf"
|
||||
},
|
||||
relatedDocuments: [
|
||||
{
|
||||
sourceDocumentSN: "B26002404",
|
||||
sourceDocumentId: "ID01WfOdmKUHyT",
|
||||
approvalRecordId: "rec-1",
|
||||
relatedAt: 1790001624549
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
const flattened = flattenInvoiceRecord(raw);
|
||||
|
||||
expect(flattened.sourceDocumentSN).toBe("B26002404");
|
||||
expect(flattened.invoiceNumber).toBe("26957000000102316227");
|
||||
expect(flattened.invoiceType).toBe("电子发票(普通发票)");
|
||||
expect(flattened.invoiceDate).toBe("2026-06-17");
|
||||
expect(flattened.sellerName).toBe("深圳石油公明加油站");
|
||||
expect(flattened.buyerName).toBe("钰泰半导体股份有限公司");
|
||||
expect(flattened.totalAmount).toBe(500);
|
||||
expect(flattened.usedAmount).toBe(409.02);
|
||||
expect(flattened.status).toBe("已验真 (verified)");
|
||||
expect(flattened.fileName).toBe("test.pdf");
|
||||
expect(flattened.attachmentUrl).toBe("https://oss.example.com/test.pdf");
|
||||
expect(flattened.relatedDocuments).toHaveLength(1);
|
||||
expect(flattened.relatedDocuments[0]?.sourceDocumentSN).toBe("B26002404");
|
||||
});
|
||||
|
||||
test("detectInvoiceConflicts identifies cross-document invoice reuse and attributes to CLI", () => {
|
||||
const mockRun = {
|
||||
id: "run-2570",
|
||||
sourceDocumentSN: "B26002570",
|
||||
sourceDocumentId: "doc-2570",
|
||||
document: {
|
||||
fields: [
|
||||
{
|
||||
label: "明细",
|
||||
value: [
|
||||
{
|
||||
invoice: {
|
||||
invoiceNumber: "26957000000102316227",
|
||||
totalAmount: 500,
|
||||
usedAmount: 409.02,
|
||||
sellerName: "深圳石油公明加油站",
|
||||
relatedDocuments: [
|
||||
{
|
||||
sourceDocumentSN: "B26002404",
|
||||
sourceDocumentId: "doc-2404",
|
||||
approvalRecordId: "run-2404"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
} as unknown as ApprovalRun;
|
||||
|
||||
const conflicts = detectInvoiceConflicts(mockRun, "testCorp");
|
||||
expect(conflicts).toHaveLength(1);
|
||||
const c = conflicts[0]!;
|
||||
expect(c.source).toBe("cli_analysis");
|
||||
expect(c.detectedBy).toContain("seal-use CLI");
|
||||
expect(c.invoiceNumber).toBe("26957000000102316227");
|
||||
expect(c.conflictingSN).toBe("B26002404");
|
||||
expect(c.usedAmount).toBe(409.02);
|
||||
expect(c.nextCommand).toBe("seal-use approval-runs diagnose --sn B26002404 --corp testCorp");
|
||||
});
|
||||
|
||||
test("detectInvoiceConflicts returns empty array when invoices only relate to current document", () => {
|
||||
const mockRun = {
|
||||
id: "run-2570",
|
||||
sourceDocumentSN: "B26002570",
|
||||
sourceDocumentId: "doc-2570",
|
||||
document: {
|
||||
fields: [
|
||||
{
|
||||
invoice: {
|
||||
invoiceNumber: "26952000000810724261",
|
||||
totalAmount: 400,
|
||||
relatedDocuments: [
|
||||
{
|
||||
sourceDocumentSN: "B26002570",
|
||||
sourceDocumentId: "doc-2570",
|
||||
approvalRecordId: "run-2570"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
} as unknown as ApprovalRun;
|
||||
|
||||
const conflicts = detectInvoiceConflicts(mockRun, "testCorp");
|
||||
expect(conflicts).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("extractDocumentInvoices extracts and normalizes unique invoices from document fields", () => {
|
||||
const mockRun = {
|
||||
id: "run-2570",
|
||||
sourceDocumentSN: "B26002570",
|
||||
document: {
|
||||
fields: [
|
||||
{
|
||||
invoice: {
|
||||
invoiceNumber: "26957000000102316227",
|
||||
totalAmount: 500
|
||||
}
|
||||
},
|
||||
{
|
||||
// duplicate invoice reference in another field
|
||||
invoice: {
|
||||
invoiceNumber: "26957000000102316227",
|
||||
totalAmount: 500
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
} as unknown as ApprovalRun;
|
||||
|
||||
const invoices = extractDocumentInvoices(mockRun);
|
||||
expect(invoices).toHaveLength(1);
|
||||
expect(invoices[0]?.invoiceNumber).toBe("26957000000102316227");
|
||||
expect(invoices[0]?.totalAmount).toBe(500);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,290 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import * as api from "../api.js";
|
||||
import type { ApprovalRun } from "../types.js";
|
||||
|
||||
export interface NormalizedInvoice {
|
||||
sourceDocumentSN: string;
|
||||
sourceDocumentId?: string;
|
||||
approvalRecordId?: string;
|
||||
invoiceNumber: string;
|
||||
invoiceType: string;
|
||||
invoiceDate: string;
|
||||
sellerName: string;
|
||||
buyerName: string;
|
||||
totalAmount: number;
|
||||
taxAmount: number;
|
||||
usedAmount: number;
|
||||
status: string;
|
||||
fileName: string;
|
||||
attachmentUrl?: string;
|
||||
relatedDocuments: Array<{
|
||||
sourceDocumentSN?: string;
|
||||
sourceDocumentId?: string;
|
||||
approvalRecordId?: string;
|
||||
relatedAt?: number;
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface InvoiceConflict {
|
||||
source: "cli_analysis";
|
||||
detectedBy: "seal-use CLI (基于单据原始发票关联数据自动提炼,非后端大模型生成)";
|
||||
invoiceNumber: string;
|
||||
sellerName?: string;
|
||||
invoiceDate?: string;
|
||||
totalAmount?: number;
|
||||
usedAmount?: number;
|
||||
conflictingSN: string;
|
||||
conflictingDocumentId?: string;
|
||||
conflictingRecordId?: string;
|
||||
explanation: string;
|
||||
nextCommand: string;
|
||||
}
|
||||
|
||||
export interface InvoiceTraceReport {
|
||||
invoice: NormalizedInvoice;
|
||||
associatedDocuments: Array<{
|
||||
sourceDocumentSN: string;
|
||||
sourceDocumentId?: string;
|
||||
approvalRecordId?: string;
|
||||
usedAmount?: number;
|
||||
relatedAt?: number;
|
||||
nextDiagnose: string;
|
||||
}>;
|
||||
conflictStatus: "NONE" | "MULTIPLE_DOCUMENTS_ATTACHED";
|
||||
guidance: {
|
||||
source: "cli_analysis";
|
||||
detectedBy: "seal-use CLI (基于进项发票库关联数据提炼,非后端大模型生成)";
|
||||
summary: string;
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeInvoiceDate(rawDate?: unknown): string {
|
||||
if (!rawDate) return "";
|
||||
const str = String(rawDate).trim();
|
||||
if (/^\d{8}$/.test(str)) {
|
||||
return `${str.slice(0, 4)}-${str.slice(4, 6)}-${str.slice(6, 8)}`;
|
||||
}
|
||||
if (/^\d{4}[-/]\d{1,2}[-/]\d{1,2}/.test(str)) {
|
||||
return str.replace(/\//g, "-").slice(0, 10);
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
export function normalizeInvoiceStatus(status?: unknown, verifyStatus?: unknown, verifyCode?: unknown): string {
|
||||
const combined = `${status ?? ""} ${verifyStatus ?? ""} ${verifyCode ?? ""}`.toLowerCase();
|
||||
if (combined.includes("verified") || combined.includes("normal_blue") || combined.includes("已验真")) {
|
||||
return "已验真 (verified)";
|
||||
}
|
||||
if (combined.includes("fail") || combined.includes("不合规")) {
|
||||
return "验真失败 (failed)";
|
||||
}
|
||||
return String(status ?? verifyStatus ?? "未知");
|
||||
}
|
||||
|
||||
export function flattenInvoiceRecord(raw: Record<string, unknown>): NormalizedInvoice {
|
||||
const verifyResult = (raw.verifyResult && typeof raw.verifyResult === "object" ? raw.verifyResult : {}) as Record<string, unknown>;
|
||||
const rawForm = (verifyResult.form && typeof verifyResult.form === "object" ? verifyResult.form : {}) as Record<string, unknown>;
|
||||
const fileInfo = (raw.fileInfo && typeof raw.fileInfo === "object" ? raw.fileInfo : {}) as Record<string, unknown>;
|
||||
const relatedDocs = Array.isArray(raw.relatedDocuments) ? raw.relatedDocuments : [];
|
||||
|
||||
const invoiceNumber = String(raw.invoiceNumber ?? verifyResult.invoiceNumber ?? rawForm["发票号码"] ?? "");
|
||||
const invoiceDate = normalizeInvoiceDate(verifyResult.invoiceDate ?? raw.invoiceDate ?? rawForm["发票日期"]);
|
||||
const invoiceType = String(verifyResult.invoiceType ?? raw.invoiceType ?? rawForm["发票类别"] ?? rawForm["发票类型"] ?? "");
|
||||
const sellerName = String(verifyResult.sellerName ?? raw.sellerName ?? rawForm["销售方名称"] ?? "");
|
||||
const buyerName = String(verifyResult.buyerName ?? raw.buyerName ?? rawForm["购买方名称"] ?? "");
|
||||
|
||||
const totalAmount = typeof raw.totalAmount === "number"
|
||||
? raw.totalAmount
|
||||
: Number(verifyResult.totalAmount ?? (rawForm["价税合计"] as string)?.replace(/[^0-9.]/g, "") ?? 0);
|
||||
|
||||
const taxAmount = typeof raw.taxAmount === "number"
|
||||
? raw.taxAmount
|
||||
: Number(verifyResult.taxAmount ?? (rawForm["税额"] as string)?.replace(/[^0-9.]/g, "") ?? 0);
|
||||
|
||||
const usedAmount = typeof raw.usedAmount === "number" ? raw.usedAmount : Number(raw.usedAmount ?? 0);
|
||||
|
||||
const status = normalizeInvoiceStatus(raw.status, raw.verifyStatus ?? verifyResult.verify, rawForm["发票状态"]);
|
||||
|
||||
const fileName = String(fileInfo.fileName ?? fileInfo.name ?? raw.fileName ?? "");
|
||||
const attachmentUrl = String(fileInfo.ossSignedUrl ?? fileInfo.fileUrl ?? raw.fileUrl ?? "");
|
||||
|
||||
const sourceDocumentSN = String(
|
||||
raw.sourceDocumentSN ??
|
||||
(relatedDocs[0] as Record<string, unknown>)?.sourceDocumentSN ??
|
||||
""
|
||||
);
|
||||
|
||||
return {
|
||||
sourceDocumentSN,
|
||||
sourceDocumentId: raw.sourceDocumentId ? String(raw.sourceDocumentId) : undefined,
|
||||
approvalRecordId: raw.approvalRecordId ? String(raw.approvalRecordId) : undefined,
|
||||
invoiceNumber,
|
||||
invoiceType,
|
||||
invoiceDate,
|
||||
sellerName,
|
||||
buyerName,
|
||||
totalAmount,
|
||||
taxAmount,
|
||||
usedAmount,
|
||||
status,
|
||||
fileName,
|
||||
attachmentUrl: attachmentUrl || undefined,
|
||||
relatedDocuments: relatedDocs.map((item) => {
|
||||
const doc = item as Record<string, unknown>;
|
||||
return {
|
||||
sourceDocumentSN: doc.sourceDocumentSN ? String(doc.sourceDocumentSN) : undefined,
|
||||
sourceDocumentId: doc.sourceDocumentId ? String(doc.sourceDocumentId) : undefined,
|
||||
approvalRecordId: doc.approvalRecordId ? String(doc.approvalRecordId) : undefined,
|
||||
relatedAt: typeof doc.relatedAt === "number" ? doc.relatedAt : undefined
|
||||
};
|
||||
})
|
||||
};
|
||||
}
|
||||
|
||||
export function extractDocumentInvoices(record: ApprovalRun): NormalizedInvoice[] {
|
||||
const rawInvoices: Array<Record<string, unknown>> = [];
|
||||
|
||||
function traverse(obj: unknown) {
|
||||
if (!obj) return;
|
||||
if (Array.isArray(obj)) {
|
||||
obj.forEach(traverse);
|
||||
return;
|
||||
}
|
||||
if (typeof obj === "object") {
|
||||
const r = obj as Record<string, unknown>;
|
||||
if (r.invoice && typeof r.invoice === "object") {
|
||||
rawInvoices.push(r.invoice as Record<string, unknown>);
|
||||
} else if (r.invoiceNumber) {
|
||||
rawInvoices.push(r);
|
||||
}
|
||||
for (const val of Object.values(r)) {
|
||||
traverse(val);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
traverse(record.document);
|
||||
|
||||
const seen = new Set<string>();
|
||||
const uniqueNormalized: NormalizedInvoice[] = [];
|
||||
|
||||
for (const raw of rawInvoices) {
|
||||
const normalized = flattenInvoiceRecord(raw);
|
||||
if (!normalized.invoiceNumber) continue;
|
||||
if (seen.has(normalized.invoiceNumber)) continue;
|
||||
seen.add(normalized.invoiceNumber);
|
||||
uniqueNormalized.push(normalized);
|
||||
}
|
||||
|
||||
return uniqueNormalized;
|
||||
}
|
||||
|
||||
export function detectInvoiceConflicts(detail: ApprovalRun, corpId?: string): InvoiceConflict[] {
|
||||
const invoices = extractDocumentInvoices(detail);
|
||||
const conflicts: InvoiceConflict[] = [];
|
||||
const currentSN = detail.sourceDocumentSN ?? "";
|
||||
const currentDocId = detail.sourceDocumentId ?? "";
|
||||
const currentRunId = detail.id ?? "";
|
||||
|
||||
for (const inv of invoices) {
|
||||
const conflictingDocs = inv.relatedDocuments.filter((doc) => {
|
||||
const sameSN = currentSN && doc.sourceDocumentSN === currentSN;
|
||||
const sameDocId = currentDocId && doc.sourceDocumentId === currentDocId;
|
||||
const sameRunId = currentRunId && doc.approvalRecordId === currentRunId;
|
||||
return !(sameSN || sameDocId || sameRunId);
|
||||
});
|
||||
|
||||
if (conflictingDocs.length > 0) {
|
||||
for (const cDoc of conflictingDocs) {
|
||||
const conflictingSN = cDoc.sourceDocumentSN ?? cDoc.sourceDocumentId ?? "未知单据";
|
||||
const corpArg = corpId ? ` --corp ${corpId}` : "";
|
||||
const nextCommand = cDoc.sourceDocumentSN
|
||||
? `seal-use approval-runs diagnose --sn ${cDoc.sourceDocumentSN}${corpArg}`
|
||||
: `seal-use approval-runs diagnose ${cDoc.approvalRecordId ?? ""}${corpArg}`;
|
||||
|
||||
const usedNote = inv.usedAmount > 0 ? `,历史占用/报销金额 ¥${inv.usedAmount}` : "";
|
||||
conflicts.push({
|
||||
source: "cli_analysis",
|
||||
detectedBy: "seal-use CLI (基于单据原始发票关联数据自动提炼,非后端大模型生成)",
|
||||
invoiceNumber: inv.invoiceNumber,
|
||||
sellerName: inv.sellerName,
|
||||
invoiceDate: inv.invoiceDate,
|
||||
totalAmount: inv.totalAmount,
|
||||
usedAmount: inv.usedAmount,
|
||||
conflictingSN,
|
||||
conflictingDocumentId: cDoc.sourceDocumentId,
|
||||
conflictingRecordId: cDoc.approvalRecordId,
|
||||
explanation: `发票 ${inv.invoiceNumber}(${inv.sellerName || "销售方"},¥${inv.totalAmount})曾被历史单据 ${conflictingSN} 挂载${usedNote}。请核实是否为重复报销。`,
|
||||
nextCommand
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return conflicts;
|
||||
}
|
||||
|
||||
export async function traceInvoice(
|
||||
client: KyInstance,
|
||||
invoiceNumber: string,
|
||||
corpId?: string
|
||||
): Promise<InvoiceTraceReport | null> {
|
||||
const cleanNumber = invoiceNumber.trim();
|
||||
if (!cleanNumber) return null;
|
||||
|
||||
const data = await api.listInvoices(client, { search: cleanNumber, limit: 10 });
|
||||
if (!data.invoices || data.invoices.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const matched = data.invoices.find((item) => {
|
||||
const num = String(item.invoiceNumber ?? (item.verifyResult as any)?.invoiceNumber ?? "");
|
||||
return num === cleanNumber;
|
||||
}) ?? data.invoices[0]!;
|
||||
|
||||
const invoice = flattenInvoiceRecord(matched as Record<string, unknown>);
|
||||
|
||||
const associatedDocuments: InvoiceTraceReport["associatedDocuments"] = [];
|
||||
const corpArg = corpId ? ` --corp ${corpId}` : "";
|
||||
|
||||
if (invoice.sourceDocumentSN) {
|
||||
associatedDocuments.push({
|
||||
sourceDocumentSN: invoice.sourceDocumentSN,
|
||||
sourceDocumentId: invoice.sourceDocumentId,
|
||||
approvalRecordId: invoice.approvalRecordId,
|
||||
usedAmount: invoice.usedAmount,
|
||||
nextDiagnose: `seal-use approval-runs diagnose --sn ${invoice.sourceDocumentSN}${corpArg}`
|
||||
});
|
||||
}
|
||||
|
||||
for (const doc of invoice.relatedDocuments) {
|
||||
if (doc.sourceDocumentSN && !associatedDocuments.some((d) => d.sourceDocumentSN === doc.sourceDocumentSN)) {
|
||||
associatedDocuments.push({
|
||||
sourceDocumentSN: doc.sourceDocumentSN,
|
||||
sourceDocumentId: doc.sourceDocumentId,
|
||||
approvalRecordId: doc.approvalRecordId,
|
||||
relatedAt: doc.relatedAt,
|
||||
nextDiagnose: `seal-use approval-runs diagnose --sn ${doc.sourceDocumentSN}${corpArg}`
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const hasMultiple = associatedDocuments.length > 1;
|
||||
const conflictStatus = hasMultiple ? "MULTIPLE_DOCUMENTS_ATTACHED" : "NONE";
|
||||
|
||||
const docListStr = associatedDocuments.map((d) => d.sourceDocumentSN).join("、");
|
||||
const summary = hasMultiple
|
||||
? `发票 ${invoice.invoiceNumber} 在 ${associatedDocuments.length} 笔单据(${docListStr})中均有挂载记录。若其中有单据已被驳回或删票,请确认合思发票池是否释放;若均在审批或已核销,则属于真实重复报销。`
|
||||
: `发票 ${invoice.invoiceNumber} 当前仅关联单据 ${invoice.sourceDocumentSN || "未知"},未检测到跨单据重复挂载冲突。`;
|
||||
|
||||
return {
|
||||
invoice,
|
||||
associatedDocuments,
|
||||
conflictStatus,
|
||||
guidance: {
|
||||
source: "cli_analysis",
|
||||
detectedBy: "seal-use CLI (基于进项发票库关联数据提炼,非后端大模型生成)",
|
||||
summary
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { ensureHoseCloseApiToken } from "../../../core/auth/hose.js";
|
||||
import { formatBeijingIso } from "../../../core/config/timestamps.js";
|
||||
import { extractApprovalRunAttachments } from "../approval-runs/attachments.js";
|
||||
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../approval-runs/export.js";
|
||||
import { summarizeExtraFindings } from "../approval-runs/extra-findings.js";
|
||||
import {
|
||||
alignApprovalRunsWithHoseFlow,
|
||||
createHoseOpenClient,
|
||||
@@ -14,6 +15,7 @@ import {
|
||||
import {
|
||||
type ApprovalRun
|
||||
} from "../types.js";
|
||||
import { detectInvoiceConflicts } from "../approval-runs/invoices.js";
|
||||
import type {
|
||||
CapabilityContext
|
||||
} from "./helpers.js";
|
||||
@@ -63,6 +65,7 @@ export const approvalRunsCapabilities = [
|
||||
sourceDocumentSN: z.string().optional(),
|
||||
sourceDocumentId: z.string().optional(),
|
||||
humanResult: z.string().optional().describe("按人工审批结果做本地包含匹配,如 驳回、通过、reject"),
|
||||
hasExtraRisk: z.boolean().optional().describe("读取当前页后筛选 otherFindings 含 warning/error 的记录;limit 是扫描条数,缺失或异常结果计入 unknown"),
|
||||
query: z.string().optional().describe("在 id、sourceDocumentSN、sourceDocumentId、documentId、Langfuse traceId 中做本地包含匹配"),
|
||||
includeBridge: z.boolean().optional().describe("是否返回完整 bridge 数组;默认 false,避免长输出")
|
||||
}),
|
||||
@@ -81,6 +84,7 @@ export const approvalRunsCapabilities = [
|
||||
sourceDocumentSN?: string;
|
||||
sourceDocumentId?: string;
|
||||
humanResult?: string;
|
||||
hasExtraRisk?: boolean;
|
||||
query?: string;
|
||||
includeBridge?: boolean;
|
||||
}
|
||||
@@ -92,13 +96,21 @@ export const approvalRunsCapabilities = [
|
||||
endDate: normalizeTimestamp(params.endDate, true),
|
||||
search: query
|
||||
}));
|
||||
const records = await prepareApprovalRuns(client, data.records, {
|
||||
const prepared = await prepareApprovalRuns(client, data.records, {
|
||||
humanResult: params.humanResult
|
||||
});
|
||||
const analyzed = prepared.map(record => ({ record, findings: summarizeExtraFindings(record, params.hasExtraRisk === true) }));
|
||||
const selected = params.hasExtraRisk
|
||||
? analyzed.filter(({ findings }) => findings.hasExtraRisk === true)
|
||||
: analyzed;
|
||||
const records = selected.map(({ record }) => record);
|
||||
|
||||
return {
|
||||
...data,
|
||||
records: records.map(summarizeApprovalRun),
|
||||
scanned: data.records.length,
|
||||
matched: records.length,
|
||||
...(params.hasExtraRisk ? { unknown: analyzed.filter(({ findings }) => findings.extraFindingsStatus === "unknown").length } : {}),
|
||||
records: selected.map(({ record, findings }) => ({ ...summarizeApprovalRun(record), ...findings })),
|
||||
...(params.includeBridge ? { bridge: summarizeRunBridge(records) } : {})
|
||||
};
|
||||
}
|
||||
@@ -717,6 +729,16 @@ export const approvalRunsCapabilities = [
|
||||
}
|
||||
}
|
||||
|
||||
const invoiceConflicts = detectInvoiceConflicts(detail, context.corp.id);
|
||||
|
||||
if (invoiceConflicts.length > 0) {
|
||||
console.error(
|
||||
`\n💡 [CLI 辅助诊断指引](注:此冲突指引由 seal-use CLI 基于单据原始发票关联数据自动分析提炼,非后端大模型生成):\n` +
|
||||
invoiceConflicts.map((c) => `• 发票 ${c.invoiceNumber}(${c.sellerName || "销售方"},¥${c.totalAmount})曾被单据 ${c.conflictingSN} 挂载${c.usedAmount ? `(已占报销金额 ¥${c.usedAmount})` : ""}\n 👉 诊断冲突原单:${c.nextCommand}`).join("\n") +
|
||||
`\n`
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
recordId: detail.id,
|
||||
sourceDocumentSN: detail.sourceDocumentSN,
|
||||
@@ -727,10 +749,13 @@ export const approvalRunsCapabilities = [
|
||||
result: params.full === true ? detail.result : resultSummary,
|
||||
citedRules,
|
||||
ruleVersion,
|
||||
invoiceConflicts: invoiceConflicts.length > 0 ? invoiceConflicts : undefined,
|
||||
bridge: summarizeRunBridge([detail]),
|
||||
next: {
|
||||
url: `seal-use approval-runs url ${detail.id} --corp ${context.corp.id}`,
|
||||
hoseDocument: `seal-use approval-runs url ${detail.id} --type hose-document --corp ${context.corp.id}`,
|
||||
diagnoseConflict: invoiceConflicts[0]?.nextCommand,
|
||||
traceInvoice: invoiceConflicts[0] ? `seal-use invoices trace ${invoiceConflicts[0].invoiceNumber} --corp ${context.corp.id}` : undefined,
|
||||
replay: `seal-use approval-runs replay ${detail.id} --dry-run --corp ${context.corp.id}`
|
||||
}
|
||||
};
|
||||
|
||||
@@ -24,6 +24,7 @@ import type {
|
||||
WebhookIntegration
|
||||
} from "../types.js";
|
||||
import { extractApprovalRunAttachments } from "../approval-runs/attachments.js";
|
||||
import { summarizeExtraFindings, type ExtraFindingsSummary } from "../approval-runs/extra-findings.js";
|
||||
import type { LocalRuleItem } from "../rules/local.js";
|
||||
import { loadRuleMappingSnapshot } from "../rules/mapping.js";
|
||||
import { formatBeijingIso, normalizeBeijingIso } from "../../../core/config/timestamps.js";
|
||||
@@ -55,7 +56,7 @@ export function getConfiguredSealBaseUrl(corp: CorpConfig): string {
|
||||
return corp.source.sealUrl;
|
||||
}
|
||||
|
||||
export type ApprovalRunSummary = {
|
||||
export type ApprovalRunSummary = ExtraFindingsSummary & {
|
||||
id: string;
|
||||
tenantId?: string;
|
||||
agentId?: string;
|
||||
@@ -500,6 +501,7 @@ export function summarizeApprovalRun(record: ApprovalRun): ApprovalRunSummary {
|
||||
humanResultPath: humanResult?.path,
|
||||
aiDecision: ai.decision,
|
||||
aiSummary: ai.summary,
|
||||
...summarizeExtraFindings(record),
|
||||
createdAt: record.createdAt,
|
||||
updatedAt: record.updatedAt
|
||||
};
|
||||
@@ -596,6 +598,7 @@ export function summarizeApprovalRunDetail(record: ApprovalRun) {
|
||||
export function summarizeApprovalRunResult(record: ApprovalRun) {
|
||||
const result = asRecord(record.result);
|
||||
return {
|
||||
...summarizeExtraFindings(record),
|
||||
recordId: record.id,
|
||||
sourceDocumentSN: record.sourceDocumentSN,
|
||||
sourceDocumentId: record.sourceDocumentId,
|
||||
|
||||
@@ -6,6 +6,10 @@ import type {
|
||||
CapabilityContext
|
||||
} from "./helpers.js";
|
||||
|
||||
import { flattenInvoiceRecord } from "../approval-runs/invoices.js";
|
||||
import { lookupDocumentExpenses } from "../expenses/lookup.js";
|
||||
import { usageError } from "../../../core/errors.js";
|
||||
|
||||
export const insightCapabilities = [
|
||||
{
|
||||
name: "sealInsightStatsGet",
|
||||
@@ -75,26 +79,46 @@ export const insightCapabilities = [
|
||||
},
|
||||
{
|
||||
name: "sealExpensesList",
|
||||
description: "分页查询费用明细",
|
||||
description: "分页查询费用明细;传 sn 时精确关联审批记录、分页核验费用库并返回存在性证据",
|
||||
parameters: z.object({
|
||||
offset: z.number().int().nonnegative().optional(),
|
||||
limit: z.number().int().positive().max(100).optional(),
|
||||
startDate: z.string().optional().describe("开始时间"),
|
||||
endDate: z.string().optional().describe("结束时间"),
|
||||
search: z.string().optional().describe("搜索费用类型、描述或金额")
|
||||
search: z.string().optional().describe("搜索费用类型、描述或金额"),
|
||||
recordId: z.string().trim().min(1).optional().describe("按关联审批记录 ID 精确筛选"),
|
||||
sn: z.string().trim().min(1).optional().describe("按源单号核验入库;不能与 search、offset 或 recordId 同传"),
|
||||
maxScan: z.number().int().positive().max(10000).optional().describe("单号核验每阶段最多扫描条数,默认 5000")
|
||||
}),
|
||||
handler: async (client: KyInstance, params: api.DataListParams) => api.listExpenses(client, params)
|
||||
handler: async (client: KyInstance, params: api.ExpenseListParams & { sn?: string; maxScan?: number }) => {
|
||||
if (params.sn !== undefined) {
|
||||
if (params.search !== undefined || params.offset !== undefined || params.recordId !== undefined) throw usageError("--sn cannot be combined with search, offset, or recordId");
|
||||
return lookupDocumentExpenses(client, { ...params, sn: params.sn });
|
||||
}
|
||||
if (params.maxScan !== undefined) throw usageError("maxScan requires sn");
|
||||
return api.listExpenses(client, params);
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "sealInvoicesList",
|
||||
description: "分页查询进项发票",
|
||||
description: "分页查询进项发票(默认输出扁平化业务字段,对齐控制台表格)",
|
||||
parameters: z.object({
|
||||
offset: z.number().int().nonnegative().optional(),
|
||||
limit: z.number().int().positive().max(100).optional(),
|
||||
startDate: z.string().optional().describe("开始时间"),
|
||||
endDate: z.string().optional().describe("结束时间"),
|
||||
search: z.string().optional().describe("搜索发票号码或销售方")
|
||||
search: z.string().optional().describe("搜索发票号码或销售方"),
|
||||
full: z.boolean().optional().describe("是否返回未扁平化的后端原始数据,默认 false (扁平化)")
|
||||
}),
|
||||
handler: async (client: KyInstance, params: api.DataListParams) => api.listInvoices(client, params)
|
||||
handler: async (client: KyInstance, params: api.DataListParams & { full?: boolean }) => {
|
||||
const result = await api.listInvoices(client, params);
|
||||
if (params.full === true) {
|
||||
return result;
|
||||
}
|
||||
return {
|
||||
...result,
|
||||
invoices: (result.invoices ?? []).map((inv) => flattenInvoiceRecord(inv as Record<string, unknown>))
|
||||
};
|
||||
}
|
||||
}
|
||||
];
|
||||
@@ -1,6 +1,7 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import * as api from "../api.js";
|
||||
import { createDocument, deleteDocument, documentCreateSchema, documentDeleteSchema, documentListSchema, documentUpdateSchema, listDocuments, updateDocument } from "../documents/service.js";
|
||||
import { recodeRules, type RecodeOptions } from "../rules/recode.js";
|
||||
import { executeRulePush } from "../rules/push.js";
|
||||
import { formatBeijingIso } from "../../../core/config/timestamps.js";
|
||||
@@ -679,15 +680,11 @@ export const rulesCapabilities = [
|
||||
{
|
||||
name: "sealApprovalDocumentsList",
|
||||
description: "列出 Seal 审批知识文档",
|
||||
parameters: z.object({
|
||||
scenarios: z.array(z.string()).optional().describe("场景过滤"),
|
||||
offset: z.number().int().nonnegative().optional(),
|
||||
limit: z.number().int().positive().optional()
|
||||
}),
|
||||
parameters: documentListSchema,
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: { scenarios?: string[]; offset?: number; limit?: number }
|
||||
) => api.listApprovalDocuments(client, params)
|
||||
params: z.infer<typeof documentListSchema>
|
||||
) => listDocuments(client, params)
|
||||
},
|
||||
{
|
||||
name: "sealApprovalDocumentGet",
|
||||
@@ -701,70 +698,29 @@ export const rulesCapabilities = [
|
||||
{
|
||||
name: "sealApprovalDocumentCreate",
|
||||
description: "新建 Seal 审批知识文档",
|
||||
parameters: z.object({
|
||||
title: z.string(),
|
||||
purpose: z.string(),
|
||||
content: z.string().describe("正文,通常为 Markdown"),
|
||||
contentType: z.string().optional(),
|
||||
status: z.string().optional(),
|
||||
enabled: z.boolean().optional(),
|
||||
scenarios: z.array(z.string()).optional(),
|
||||
tags: z.array(z.string()).optional()
|
||||
}),
|
||||
parameters: documentCreateSchema,
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: {
|
||||
title: string;
|
||||
purpose: string;
|
||||
content: string;
|
||||
contentType?: string;
|
||||
status?: string;
|
||||
enabled?: boolean;
|
||||
scenarios?: string[];
|
||||
tags?: string[];
|
||||
}
|
||||
) => api.createApprovalDocument(client, params)
|
||||
params: z.infer<typeof documentCreateSchema>,
|
||||
context: CapabilityContext
|
||||
) => createDocument(client, context.corp, params)
|
||||
},
|
||||
{
|
||||
name: "sealApprovalDocumentUpdate",
|
||||
description: "更新 Seal 审批知识文档",
|
||||
parameters: z.object({
|
||||
documentId: z.string(),
|
||||
title: z.string().optional(),
|
||||
purpose: z.string().optional(),
|
||||
content: z.string().optional(),
|
||||
contentType: z.string().optional(),
|
||||
status: z.string().optional(),
|
||||
enabled: z.boolean().optional(),
|
||||
scenarios: z.array(z.string()).optional(),
|
||||
tags: z.array(z.string()).optional()
|
||||
}),
|
||||
parameters: documentUpdateSchema,
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: {
|
||||
documentId: string;
|
||||
title?: string;
|
||||
purpose?: string;
|
||||
content?: string;
|
||||
contentType?: string;
|
||||
status?: string;
|
||||
enabled?: boolean;
|
||||
scenarios?: string[];
|
||||
tags?: string[];
|
||||
}
|
||||
) => {
|
||||
const { documentId, ...rest } = params;
|
||||
return api.updateApprovalDocument(client, documentId, rest);
|
||||
}
|
||||
params: z.infer<typeof documentUpdateSchema>,
|
||||
context: CapabilityContext
|
||||
) => updateDocument(client, context.corp, params)
|
||||
},
|
||||
{
|
||||
name: "sealApprovalDeleteDocument",
|
||||
description: "删除 Seal 审批知识文档",
|
||||
parameters: z.object({
|
||||
documentId: z.string().describe("知识文档 ID")
|
||||
}),
|
||||
handler: (client: KyInstance, params: { documentId: string }) =>
|
||||
api.deleteApprovalDocument(client, params.documentId)
|
||||
parameters: documentDeleteSchema,
|
||||
handler: (client: KyInstance, params: z.infer<typeof documentDeleteSchema>, context: CapabilityContext) =>
|
||||
deleteDocument(client, context.corp, params)
|
||||
},
|
||||
{
|
||||
name: "sealApprovalSearch",
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
import { createHash, randomUUID } from "node:crypto"
|
||||
import { chmodSync, closeSync, existsSync, fsyncSync, linkSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"
|
||||
import { dirname, join, resolve } from "node:path"
|
||||
import { z } from "zod"
|
||||
import type { CorpConfig } from "../../../core/config/types.js"
|
||||
import { resolveGlobalConfigFile } from "../../../core/config/loader.js"
|
||||
import { formatBeijingIso } from "../../../core/config/timestamps.js"
|
||||
import { validationError } from "../../../core/errors.js"
|
||||
import type { ApprovalDocument } from "../types.js"
|
||||
|
||||
export const DOCUMENT_EDITABLE_FIELDS = ["title", "purpose", "content", "contentType", "status", "enabled", "scenarios", "tags"] as const
|
||||
export type DocumentField = typeof DOCUMENT_EDITABLE_FIELDS[number]
|
||||
const hashSchema = z.string().regex(/^[a-f0-9]{64}$/)
|
||||
const sourceSchema = z.object({ corpId: z.string(), sealUrl: z.string().url(), documentId: z.string() })
|
||||
export const documentBaselineSchema = z.object({
|
||||
schemaVersion: z.literal(1),
|
||||
contentFormat: z.literal("raw"),
|
||||
source: sourceSchema,
|
||||
exportedAt: z.string(),
|
||||
contentHash: hashSchema,
|
||||
fieldHashes: z.record(z.enum(DOCUMENT_EDITABLE_FIELDS), hashSchema),
|
||||
snapshotId: z.string()
|
||||
}).refine(value => value.contentHash === value.fieldHashes.content, "Baseline content hash is inconsistent")
|
||||
export type DocumentBaseline = z.infer<typeof documentBaselineSchema>
|
||||
|
||||
export function documentHash(value: unknown): string {
|
||||
return createHash("sha256").update(typeof value === "string" ? value : JSON.stringify(value)).digest("hex")
|
||||
}
|
||||
|
||||
export function documentSource(corp: CorpConfig, documentId: string) {
|
||||
const sealUrl = corp.seal.url ?? corp.source.sealUrl
|
||||
if (!sealUrl) throw validationError("Document operations require a Seal service URL")
|
||||
const url = new URL(sealUrl)
|
||||
url.username = ""
|
||||
url.password = ""
|
||||
url.search = ""
|
||||
url.hash = ""
|
||||
return { corpId: corp.id, sealUrl: url.toString().replace(/\/+$/, ""), documentId }
|
||||
}
|
||||
|
||||
export function documentFieldHashes(document: ApprovalDocument) {
|
||||
return Object.fromEntries(DOCUMENT_EDITABLE_FIELDS.map(field => [field, documentHash(document[field])])) as Record<DocumentField, string>
|
||||
}
|
||||
|
||||
function localFileError(path: string, error: unknown): never {
|
||||
const reason = error instanceof Error ? error.message : String(error)
|
||||
throw validationError(`Cannot use document file ${path}: ${reason}`)
|
||||
}
|
||||
|
||||
export function readDocumentText(path: string): string {
|
||||
try {
|
||||
// ignoreBOM preserves a leading U+FEFF instead of silently stripping it.
|
||||
return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(readFileSync(path))
|
||||
} catch (error) {
|
||||
return localFileError(path, error)
|
||||
}
|
||||
}
|
||||
|
||||
export function readDocumentBaseline(contentFile: string): DocumentBaseline | undefined {
|
||||
const path = `${resolve(contentFile)}.seal-use.json`
|
||||
// lstat also detects a dangling symlink, which must not silently disable protection.
|
||||
try {
|
||||
lstatSync(path)
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined
|
||||
return localFileError(path, error)
|
||||
}
|
||||
try {
|
||||
return documentBaselineSchema.parse(JSON.parse(readDocumentText(path)))
|
||||
} catch (error) {
|
||||
return localFileError(path, error)
|
||||
}
|
||||
}
|
||||
|
||||
export function saveDocumentSnapshot(corp: CorpConfig, document: ApprovalDocument, operation: "export" | "update" | "delete") {
|
||||
const source = documentSource(corp, document.id)
|
||||
const history = join(dirname(resolveGlobalConfigFile()), "document-history")
|
||||
const dir = join(history, documentHash(source))
|
||||
const snapshotId = randomUUID()
|
||||
const snapshotFile = join(dir, `${snapshotId}.json`)
|
||||
try {
|
||||
mkdirSync(dir, { recursive: true, mode: 0o700 })
|
||||
chmodSync(history, 0o700)
|
||||
chmodSync(dir, 0o700)
|
||||
const fd = openSync(snapshotFile, "wx", 0o600)
|
||||
try {
|
||||
writeFileSync(fd, `${JSON.stringify({ schemaVersion: 1, snapshotId, source, capturedAt: formatBeijingIso(), operation, phase: "captured", document }, null, 2)}\n`)
|
||||
fsyncSync(fd)
|
||||
} finally { closeSync(fd) }
|
||||
} catch (error) {
|
||||
return localFileError(snapshotFile, error)
|
||||
}
|
||||
return { snapshotId, snapshotFile }
|
||||
}
|
||||
|
||||
export function exportDocument(corp: CorpConfig, document: ApprovalDocument, outputPath: string, overwrite = false) {
|
||||
const contentFile = resolve(outputPath)
|
||||
const manifestFile = `${contentFile}.seal-use.json`
|
||||
const destinations = [contentFile, manifestFile]
|
||||
let staging: string | undefined
|
||||
const previous: Array<{ destination: string; backup: string }> = []
|
||||
const published: string[] = []
|
||||
let preserveStaging = false
|
||||
try {
|
||||
for (const path of destinations) {
|
||||
let stat
|
||||
try { stat = lstatSync(path) } catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error
|
||||
}
|
||||
if (stat && (!overwrite || !stat.isFile() || stat.isSymbolicLink())) {
|
||||
throw new Error(`Refusing to replace ${path}; use --overwrite only for regular export files`)
|
||||
}
|
||||
}
|
||||
staging = mkdtempSync(join(dirname(contentFile), ".seal-document-"))
|
||||
const snapshot = saveDocumentSnapshot(corp, document, "export")
|
||||
const baseline: DocumentBaseline = {
|
||||
schemaVersion: 1, contentFormat: "raw", source: documentSource(corp, document.id), exportedAt: formatBeijingIso(),
|
||||
contentHash: documentHash(document.content), fieldHashes: documentFieldHashes(document), snapshotId: snapshot.snapshotId
|
||||
}
|
||||
const contents = [document.content, `${JSON.stringify(baseline, null, 2)}\n`]
|
||||
for (const [index, content] of contents.entries()) {
|
||||
writeFileSync(join(staging, String(index)), content, { flag: "wx", mode: 0o600 })
|
||||
}
|
||||
for (const [index, destination] of destinations.entries()) {
|
||||
if (overwrite && existsSync(destination)) {
|
||||
if (!lstatSync(destination).isFile() || lstatSync(destination).isSymbolicLink()) throw new Error(`Export destination changed during publication: ${destination}`)
|
||||
const backup = join(staging, `before-${index}`)
|
||||
renameSync(destination, backup)
|
||||
previous.push({ destination, backup })
|
||||
}
|
||||
// Exclusive publication: never truncate a destination created after preflight.
|
||||
linkSync(join(staging, String(index)), destination)
|
||||
published.push(destination)
|
||||
}
|
||||
return { contentFile, manifestFile, contentFormat: "raw", bytes: Buffer.byteLength(document.content, "utf8"), contentHash: baseline.contentHash, ...snapshot }
|
||||
} catch (error) {
|
||||
try {
|
||||
for (const path of published.reverse()) rmSync(path)
|
||||
for (const { destination, backup } of previous.reverse()) renameSync(backup, destination)
|
||||
} catch {
|
||||
preserveStaging = true
|
||||
throw validationError(`Document export failed; original files retained for recovery in ${staging}`)
|
||||
}
|
||||
return localFileError(contentFile, error)
|
||||
} finally {
|
||||
if (staging && !preserveStaging) rmSync(staging, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test"
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import type { KyInstance } from "ky"
|
||||
import type { CorpConfig } from "../../../core/config/types.js"
|
||||
import { classifyCliError } from "../../../core/errors.js"
|
||||
import { ApprovalDocumentSchema } from "../types.js"
|
||||
import { documentFieldHashes, documentHash, documentSource, exportDocument, readDocumentBaseline, readDocumentText } from "./files.js"
|
||||
import { createDocument, deleteDocument, DocumentMutationError, listDocuments, updateDocument } from "./service.js"
|
||||
|
||||
const originalConfig = process.env.SEAL_USE_CONFIG_FILE
|
||||
let dir: string
|
||||
const corp = { id: "corp-fixture", seal: { url: "https://seal.example.test" }, source: { type: "seal" } } as CorpConfig
|
||||
const initial = () => ApprovalDocumentSchema.parse({ id: "doc-1", title: "测试名单", purpose: "制度", content: "\uFEFF| 姓名 \\| 资格 |\\\r\n| --- | --- |\r\n\\path\\file \r\n末行", status: "published", enabled: true, tags: ["名单"], scenarios: ["audit"], updatedAt: 123 })
|
||||
|
||||
function fixture() {
|
||||
let document = initial()
|
||||
const requests: Array<{ method: string; path: string; options?: { json?: unknown; retry?: unknown } }> = []
|
||||
let reads = 0
|
||||
let failWrite = false
|
||||
let failReadback = false
|
||||
let readbackError: unknown = undefined
|
||||
let corruptReadback = false
|
||||
const client = {
|
||||
get(path: string) {
|
||||
requests.push({ method: "GET", path })
|
||||
return { json: async () => {
|
||||
if (path === "api/v1/knowledge/articles") return { data: { articles: [document], total: 115 } }
|
||||
reads++
|
||||
if (failReadback && reads > 1) throw (readbackError ?? new Error("readback unavailable"))
|
||||
return { data: structuredClone(corruptReadback && reads > 1 ? { ...document, status: "draft" } : document) }
|
||||
} }
|
||||
},
|
||||
patch(path: string, options: { json: { attributes: Record<string, unknown> }; retry: unknown }) {
|
||||
requests.push({ method: "PATCH", path, options })
|
||||
document = ApprovalDocumentSchema.parse({ ...document, ...options.json.attributes })
|
||||
if (failWrite) throw new Error("timeout after sending request")
|
||||
return { json: async () => ({ data: document }) }
|
||||
},
|
||||
post(path: string, options: { json: Record<string, unknown>; retry: unknown }) {
|
||||
requests.push({ method: "POST", path, options })
|
||||
document = ApprovalDocumentSchema.parse({ ...options.json, id: "created-1" })
|
||||
return { json: async () => ({ data: document }) }
|
||||
},
|
||||
async delete(path: string, options: { retry: unknown }) { requests.push({ method: "DELETE", path, options }) }
|
||||
} as unknown as KyInstance
|
||||
return {
|
||||
client, requests, get document() { return document },
|
||||
set document(value) { document = value },
|
||||
set failWrite(value: boolean) { failWrite = value },
|
||||
set failReadback(value: boolean) { failReadback = value },
|
||||
set readbackError(value: unknown) { readbackError = value },
|
||||
set corruptReadback(value: boolean) { corruptReadback = value },
|
||||
writes: () => requests.filter(request => request.method !== "GET")
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
dir = mkdtempSync(join(tmpdir(), "seal-document-test-"))
|
||||
process.env.SEAL_USE_CONFIG_FILE = join(dir, "config.json")
|
||||
})
|
||||
afterEach(() => {
|
||||
if (originalConfig === undefined) delete process.env.SEAL_USE_CONFIG_FILE
|
||||
else process.env.SEAL_USE_CONFIG_FILE = originalConfig
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
describe("document files", () => {
|
||||
test("exports exact UTF-8 content, a source manifest, and private original snapshot", () => {
|
||||
const document = initial()
|
||||
const result = exportDocument(corp, document, join(dir, "名单.md"))
|
||||
expect(readFileSync(result.contentFile)).toEqual(Buffer.from(document.content, "utf8"))
|
||||
expect(readDocumentText(result.contentFile)).toBe(document.content)
|
||||
expect(readDocumentBaseline(result.contentFile)).toMatchObject({ source: documentSource(corp, document.id), fieldHashes: documentFieldHashes(document), contentFormat: "raw" })
|
||||
const snapshot = JSON.parse(readFileSync(result.snapshotFile, "utf8"))
|
||||
expect(snapshot.document).toEqual(document)
|
||||
expect(snapshot.capturedAt).toMatch(/\+08:00$/)
|
||||
for (const path of [result.contentFile, result.manifestFile, result.snapshotFile]) expect(statSync(path).mode & 0o777).toBe(0o600)
|
||||
expect(statSync(join(dir, "document-history")).mode & 0o777).toBe(0o700)
|
||||
})
|
||||
|
||||
test("existing exports require overwrite and both files are replaced together", () => {
|
||||
const out = join(dir, "body.txt")
|
||||
const result = exportDocument(corp, initial(), out)
|
||||
writeFileSync(out, "local changes")
|
||||
expect(() => exportDocument(corp, initial(), out)).toThrow("--overwrite")
|
||||
expect(readFileSync(out, "utf8")).toBe("local changes")
|
||||
exportDocument(corp, { ...initial(), content: "new" }, out, true)
|
||||
expect(readDocumentText(out)).toBe("new")
|
||||
expect(readDocumentBaseline(out)?.contentHash).toBe(documentHash("new"))
|
||||
expect(JSON.parse(readFileSync(result.snapshotFile, "utf8")).document.content).toBe(initial().content)
|
||||
})
|
||||
|
||||
test("invalid destinations and symlinks do not damage existing files", () => {
|
||||
const out = join(dir, "body.txt")
|
||||
writeFileSync(out, "keep")
|
||||
mkdirSync(`${out}.seal-use.json`)
|
||||
expect(() => exportDocument(corp, initial(), out, true)).toThrow()
|
||||
expect(readFileSync(out, "utf8")).toBe("keep")
|
||||
const link = join(dir, "link")
|
||||
symlinkSync(out, link)
|
||||
expect(() => exportDocument(corp, initial(), link, true)).toThrow()
|
||||
expect(readFileSync(out, "utf8")).toBe("keep")
|
||||
})
|
||||
|
||||
test("partial export publication rolls back only its own body and preserves a racing file", () => {
|
||||
const out = join(dir, "body.txt")
|
||||
const document = initial()
|
||||
Object.defineProperty(document, "content", { enumerable: true, get() {
|
||||
if (!existsSync(`${out}.seal-use.json`)) writeFileSync(`${out}.seal-use.json`, "another writer")
|
||||
return initial().content
|
||||
} })
|
||||
expect(() => exportDocument(corp, document, out)).toThrow()
|
||||
expect(existsSync(out)).toBe(false)
|
||||
expect(readFileSync(`${out}.seal-use.json`, "utf8")).toBe("another writer")
|
||||
})
|
||||
|
||||
test("invalid UTF-8 and damaged or dangling manifests fail instead of losing baseline protection", () => {
|
||||
const out = join(dir, "body")
|
||||
writeFileSync(out, Buffer.from([0xff]))
|
||||
expect(() => readDocumentText(out)).toThrow("Cannot use document file")
|
||||
expect(readDocumentBaseline(out)).toBeUndefined()
|
||||
writeFileSync(`${out}.seal-use.json`, "{}")
|
||||
expect(() => readDocumentBaseline(out)).toThrow()
|
||||
rmSync(`${out}.seal-use.json`)
|
||||
symlinkSync(join(dir, "missing"), `${out}.seal-use.json`)
|
||||
expect(() => readDocumentBaseline(out)).toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
describe("document mutations", () => {
|
||||
for (const confirm of [true, false]) {
|
||||
test(`all dry-runs avoid writes and history even with confirm=${confirm}`, async () => {
|
||||
const f = fixture()
|
||||
const create = await createDocument(f.client, corp, { title: "new", purpose: "policy", content: "body", dryRun: true, confirm })
|
||||
const update = await updateDocument(f.client, corp, { documentId: "doc-1", content: "changed", dryRun: true, confirm })
|
||||
const remove = await deleteDocument(f.client, corp, { documentId: "doc-1", dryRun: true, confirm })
|
||||
for (const result of [create, update, remove]) expect(result).toMatchObject({ preview: true, executed: false })
|
||||
expect(f.writes()).toHaveLength(0)
|
||||
expect(existsSync(join(dir, "document-history"))).toBe(false)
|
||||
})
|
||||
}
|
||||
|
||||
test("all live mutations without confirmation fail with exit 10 before HTTP", async () => {
|
||||
const f = fixture()
|
||||
for (const operation of [
|
||||
() => createDocument(f.client, corp, { title: "new", purpose: "policy", content: "body" }),
|
||||
() => updateDocument(f.client, corp, { documentId: "doc-1", content: "new" }),
|
||||
() => deleteDocument(f.client, corp, { documentId: "doc-1" })
|
||||
]) {
|
||||
try { await operation(); throw new Error("expected rejection") } catch (error) { expect(classifyCliError(error).exitCode).toBe(10) }
|
||||
}
|
||||
expect(f.requests).toHaveLength(0)
|
||||
})
|
||||
|
||||
test("updates only requested attributes, saves actual prior state, and verifies preserved metadata", async () => {
|
||||
const f = fixture()
|
||||
const out = join(dir, "body.txt")
|
||||
exportDocument(corp, f.document, out)
|
||||
const baseline = readDocumentBaseline(out)
|
||||
const result = await updateDocument(f.client, corp, { documentId: "doc-1", content: "new content", baseline, confirm: true })
|
||||
expect(result).toMatchObject({ executed: true, verified: true, baselineAvailable: true, changedFields: ["content"] })
|
||||
expect(f.writes()).toEqual([{ method: "PATCH", path: "api/v1/knowledge/articles/doc-1", options: { json: { attributes: { content: "new content" } }, retry: 0 } }])
|
||||
expect(f.document.title).toBe(initial().title)
|
||||
expect(f.document.status).toBe("published")
|
||||
expect("snapshotFile" in result).toBe(true)
|
||||
if ("snapshotFile" in result) expect(JSON.parse(readFileSync(result.snapshotFile!, "utf8")).document).toEqual(initial())
|
||||
})
|
||||
|
||||
test("unchanged upload is a no-op with no write or history", async () => {
|
||||
const f = fixture()
|
||||
expect(await updateDocument(f.client, corp, { documentId: "doc-1", content: f.document.content, confirm: true })).toMatchObject({ executed: false, changed: false, verified: true })
|
||||
expect(f.writes()).toHaveLength(0)
|
||||
expect(existsSync(join(dir, "document-history"))).toBe(false)
|
||||
})
|
||||
|
||||
test("remote changes conflict even with confirmation", async () => {
|
||||
const f = fixture()
|
||||
const out = join(dir, "body.txt")
|
||||
exportDocument(corp, f.document, out)
|
||||
f.document = { ...f.document, content: "someone else edited" }
|
||||
try {
|
||||
await updateDocument(f.client, corp, { documentId: "doc-1", content: "my edit", baseline: readDocumentBaseline(out), confirm: true })
|
||||
throw new Error("expected rejection")
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(DocumentMutationError)
|
||||
expect((error as DocumentMutationError).payload).toMatchObject({ code: "DOCUMENT_CONFLICT", executed: false, conflictingFields: ["content"] })
|
||||
}
|
||||
expect(f.writes()).toHaveLength(0)
|
||||
})
|
||||
|
||||
test("a baseline cannot be uploaded into another enterprise or service", async () => {
|
||||
const f = fixture()
|
||||
const out = join(dir, "body.txt")
|
||||
exportDocument(corp, f.document, out)
|
||||
for (const target of [{ ...corp, id: "other-corp" }, { ...corp, seal: { ...corp.seal, url: "https://other.test" } }]) {
|
||||
await expect(updateDocument(f.client, target, { documentId: "doc-1", content: "my edit", baseline: readDocumentBaseline(out), confirm: true })).rejects.toThrow("different enterprise")
|
||||
}
|
||||
expect(f.requests).toHaveLength(0)
|
||||
})
|
||||
|
||||
test("empty content requires an explicit allow-empty flag", async () => {
|
||||
const f = fixture()
|
||||
await expect(updateDocument(f.client, corp, { documentId: "doc-1", content: " ", confirm: true })).rejects.toThrow("--allow-empty")
|
||||
expect(f.requests).toHaveLength(0)
|
||||
expect(await updateDocument(f.client, corp, { documentId: "doc-1", content: "", confirm: true, allowEmpty: true })).toMatchObject({ verified: true })
|
||||
})
|
||||
|
||||
test("snapshot failure prevents PATCH and DELETE", async () => {
|
||||
const f = fixture()
|
||||
writeFileSync(join(dir, "document-history"), "not a directory")
|
||||
await expect(updateDocument(f.client, corp, { documentId: "doc-1", content: "new", confirm: true })).rejects.toThrow("Cannot use document file")
|
||||
await expect(deleteDocument(f.client, corp, { documentId: "doc-1", confirm: true })).rejects.toThrow("Cannot use document file")
|
||||
expect(f.writes()).toHaveLength(0)
|
||||
})
|
||||
|
||||
for (const mode of ["timeout", "readback", "mismatch"] as const) {
|
||||
test(`reports ${mode} with recovery snapshot and no blind retry`, async () => {
|
||||
const f = fixture()
|
||||
f.failWrite = mode === "timeout"
|
||||
f.failReadback = mode === "readback"
|
||||
f.corruptReadback = mode === "mismatch"
|
||||
try {
|
||||
await updateDocument(f.client, corp, { documentId: "doc-1", content: "new", confirm: true })
|
||||
throw new Error("expected rejection")
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(DocumentMutationError)
|
||||
const payload = (error as DocumentMutationError).payload
|
||||
expect(payload.code).toBe({ timeout: "DOCUMENT_WRITE_UNCERTAIN", readback: "DOCUMENT_READBACK_FAILED", mismatch: "DOCUMENT_VERIFICATION_FAILED" }[mode])
|
||||
expect(payload.executed).toBe(mode === "timeout" ? null : true)
|
||||
expect(payload.verified).toBe(false)
|
||||
expect(existsSync(String(payload.snapshotFile))).toBe(true)
|
||||
}
|
||||
expect(f.writes()).toHaveLength(1)
|
||||
})
|
||||
}
|
||||
|
||||
test("readback authentication failure retains exit code 11", async () => {
|
||||
const f = fixture()
|
||||
f.failReadback = true
|
||||
f.readbackError = Object.assign(new Error("unauthorized"), { response: { status: 401 } })
|
||||
try {
|
||||
await updateDocument(f.client, corp, { documentId: "doc-1", content: "new", confirm: true })
|
||||
throw new Error("expected rejection")
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(DocumentMutationError)
|
||||
const err = error as DocumentMutationError
|
||||
expect(err.exitCode).toBe(11)
|
||||
expect(err.payload.code).toBe("DOCUMENT_READBACK_FAILED")
|
||||
expect(err.payload.executed).toBe(true)
|
||||
expect(err.payload.verified).toBe(false)
|
||||
}
|
||||
})
|
||||
|
||||
test("create and delete also disable transport retries", async () => {
|
||||
const f = fixture()
|
||||
expect(await createDocument(f.client, corp, { title: "new", purpose: "policy", content: "body", confirm: true })).toMatchObject({ verified: true })
|
||||
await deleteDocument(f.client, corp, { documentId: "created-1", confirm: true })
|
||||
expect(f.writes().map(request => [request.method, request.options?.retry])).toEqual([["POST", 0], ["DELETE", 0]])
|
||||
})
|
||||
})
|
||||
|
||||
describe("document lists", () => {
|
||||
test("summary and explicit fields preserve totals while default retains content", async () => {
|
||||
const f = fixture()
|
||||
expect((await listDocuments(f.client, {})).articles[0]).toHaveProperty("content")
|
||||
const summary = await listDocuments(f.client, { summary: true })
|
||||
expect(summary.total).toBe(115)
|
||||
expect(summary.articles[0]).not.toHaveProperty("content")
|
||||
expect((await listDocuments(f.client, { summary: true, fields: ["id", "title"] })).articles).toEqual([{ id: "doc-1", title: "测试名单" }])
|
||||
expect(f.requests.every(request => request.path === "api/v1/knowledge/articles")).toBe(true)
|
||||
})
|
||||
|
||||
test("invalid projection fields fail before HTTP", async () => {
|
||||
const f = fixture()
|
||||
await expect(listDocuments(f.client, { fields: ["typo"] })).rejects.toThrow("Unknown document field")
|
||||
expect(f.requests).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,133 @@
|
||||
import { z } from "zod"
|
||||
import type { KyInstance } from "ky"
|
||||
import type { CorpConfig } from "../../../core/config/types.js"
|
||||
import { CliError, classifyCliError, confirmationRequired, usageError, validationError } from "../../../core/errors.js"
|
||||
import * as api from "../api.js"
|
||||
import { ApprovalDocumentSchema, type ApprovalDocument } from "../types.js"
|
||||
import { DOCUMENT_EDITABLE_FIELDS, documentBaselineSchema, documentFieldHashes, documentHash, documentSource, saveDocumentSnapshot, type DocumentField } from "./files.js"
|
||||
|
||||
export const DOCUMENT_SUMMARY_FIELDS = ["id", "title", "purpose", "contentType", "status", "enabled", "scenarios", "tags", "updatedAt"]
|
||||
const documentFields = Object.keys(ApprovalDocumentSchema.shape)
|
||||
export const documentListSchema = z.object({
|
||||
scenarios: z.array(z.string()).optional().describe("场景过滤"), offset: z.number().int().nonnegative().optional(), limit: z.number().int().positive().optional(),
|
||||
summary: z.boolean().optional(), fields: z.array(z.string()).optional()
|
||||
})
|
||||
const attributesSchema = z.object({
|
||||
title: z.string(), purpose: z.string(), content: z.string().describe("正文,通常为 Markdown;raw 原样传输"), contentType: z.string().optional(), status: z.string().optional(),
|
||||
enabled: z.boolean().optional(), scenarios: z.array(z.string()).optional(), tags: z.array(z.string()).optional()
|
||||
})
|
||||
const safetyShape = { dryRun: z.boolean().optional(), confirm: z.boolean().optional(), allowEmpty: z.boolean().optional() }
|
||||
export const documentCreateSchema = attributesSchema.extend(safetyShape)
|
||||
export const documentUpdateSchema = attributesSchema.partial().extend({
|
||||
documentId: z.string().describe("知识文档 ID"), ...safetyShape, baseline: documentBaselineSchema.optional()
|
||||
})
|
||||
export const documentDeleteSchema = z.object({ documentId: z.string().describe("知识文档 ID"), dryRun: z.boolean().optional(), confirm: z.boolean().optional() })
|
||||
type DocumentAttributes = z.infer<typeof attributesSchema>
|
||||
|
||||
export class DocumentMutationError extends CliError {
|
||||
constructor(readonly payload: Record<string, unknown>, message: string, exitCode: 1 | 11 = 1, nextAction?: string) {
|
||||
super(message, exitCode, nextAction)
|
||||
this.name = "DocumentMutationError"
|
||||
}
|
||||
}
|
||||
|
||||
export async function listDocuments(client: KyInstance, params: z.infer<typeof documentListSchema>) {
|
||||
const fields = params.fields ?? (params.summary ? DOCUMENT_SUMMARY_FIELDS : undefined)
|
||||
if (fields?.some(field => !documentFields.includes(field))) throw usageError(`Unknown document field; allowed: ${documentFields.join(", ")}`)
|
||||
const result = await api.listApprovalDocuments(client, params)
|
||||
return fields ? { ...result, articles: result.articles.map(document => Object.fromEntries(fields.map(field => [field, document[field as keyof ApprovalDocument]]))) } : result
|
||||
}
|
||||
|
||||
function quote(value: string) { return `'${value.replace(/'/g, "'\\''")}'` }
|
||||
function nextRead(corp: CorpConfig, id: string) { return `seal-use documents get ${quote(id)} --corp ${quote(corp.id)}` }
|
||||
|
||||
function requireConfirmation(action: string, params: { dryRun?: boolean; confirm?: boolean }) {
|
||||
if (!params.dryRun && !params.confirm) {
|
||||
throw confirmationRequired(`documents ${action} requires --yes or --confirm. Inspect --dry-run first.`, `seal-use help documents ${action}`)
|
||||
}
|
||||
}
|
||||
|
||||
function validateContent(content: string | undefined, allowEmpty?: boolean) {
|
||||
if (content !== undefined && !content.trim() && !allowEmpty) throw validationError("Empty document content requires --allow-empty")
|
||||
}
|
||||
|
||||
function changes(before: ApprovalDocument | undefined, patch: Partial<DocumentAttributes>) {
|
||||
return DOCUMENT_EDITABLE_FIELDS.filter(field => patch[field] !== undefined && (!before || documentHash(before[field]) !== documentHash(patch[field])))
|
||||
}
|
||||
|
||||
function preview(corp: CorpConfig, id: string, before: ApprovalDocument | undefined, patch: Partial<DocumentAttributes>, fields: DocumentField[], baselineAvailable = false) {
|
||||
return {
|
||||
source: documentSource(corp, id), preview: true, executed: false, changed: fields.length > 0, changedFields: fields, baselineAvailable,
|
||||
changesDiff: Object.fromEntries(fields.map(field => [field, { before: before?.[field] ?? null, after: patch[field] }])),
|
||||
contentStats: patch.content === undefined ? undefined : {
|
||||
beforeBytes: Buffer.byteLength(before?.content ?? "", "utf8"), afterBytes: Buffer.byteLength(patch.content, "utf8"),
|
||||
beforeLines: before?.content.split(/\r?\n/).length ?? 0, afterLines: patch.content.split(/\r?\n/).length
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function failedWrite(error: unknown, payload: Record<string, unknown>, nextAction?: string): never {
|
||||
const auth = classifyCliError(error).exitCode === 11
|
||||
throw new DocumentMutationError({ ...payload, code: auth ? "DOCUMENT_AUTH_FAILED" : "DOCUMENT_WRITE_UNCERTAIN", executed: auth ? false : null, verified: false }, "Document write did not complete with a verified response; inspect current state before retrying.", auth ? 11 : 1, nextAction)
|
||||
}
|
||||
|
||||
export async function createDocument(client: KyInstance, corp: CorpConfig, params: z.infer<typeof documentCreateSchema>) {
|
||||
validateContent(params.content, params.allowEmpty)
|
||||
requireConfirmation("create", params)
|
||||
const { dryRun, confirm: _confirm, allowEmpty: _allowEmpty, ...attributes } = params
|
||||
const patch = { ...attributes, contentType: attributes.contentType ?? "policy", status: attributes.status ?? "published", enabled: attributes.enabled ?? true, scenarios: attributes.scenarios?.length ? attributes.scenarios : ["audit"], tags: attributes.tags ?? [] }
|
||||
if (dryRun) return preview(corp, "(new)", undefined, patch, changes(undefined, patch))
|
||||
let created: ApprovalDocument
|
||||
try { created = await api.createApprovalDocument(client, patch) } catch (error) {
|
||||
return failedWrite(error, { source: { corpId: corp.id }, preview: false, operation: "create" })
|
||||
}
|
||||
return verifyDocument(client, corp, created.id, patch, changes(undefined, patch), false)
|
||||
}
|
||||
|
||||
async function verifyDocument(client: KyInstance, corp: CorpConfig, id: string, expected: Partial<DocumentAttributes>, changedFields: DocumentField[], baselineAvailable: boolean, snapshot?: { snapshotId: string; snapshotFile: string }) {
|
||||
const receipt = { source: documentSource(corp, id), preview: false, executed: true, changed: true, changedFields, baselineAvailable, ...snapshot }
|
||||
let after: ApprovalDocument
|
||||
try { after = await api.getApprovalDocument(client, id) } catch (error) {
|
||||
const auth = classifyCliError(error).exitCode === 11
|
||||
throw new DocumentMutationError({ ...receipt, code: "DOCUMENT_READBACK_FAILED", verified: false }, "Document was written, but readback failed.", auth ? 11 : 1, nextRead(corp, id))
|
||||
}
|
||||
const mismatchedFields = changes(after, expected)
|
||||
if (mismatchedFields.length) throw new DocumentMutationError({ ...receipt, code: "DOCUMENT_VERIFICATION_FAILED", verified: false, mismatchedFields }, "Document readback differs from the expected state.", 1, nextRead(corp, id))
|
||||
return { ...receipt, verified: true, contentHash: documentHash(after.content) }
|
||||
}
|
||||
|
||||
export async function updateDocument(client: KyInstance, corp: CorpConfig, params: z.infer<typeof documentUpdateSchema>) {
|
||||
const { documentId, dryRun, confirm: _confirm, allowEmpty, baseline, ...rawPatch } = params
|
||||
const patch = Object.fromEntries(Object.entries(rawPatch).filter(([, value]) => value !== undefined)) as Partial<DocumentAttributes>
|
||||
if (!Object.keys(patch).length) throw usageError("documents update requires at least one changed field")
|
||||
validateContent(patch.content, allowEmpty)
|
||||
requireConfirmation("update", params)
|
||||
const source = documentSource(corp, documentId)
|
||||
if (baseline && JSON.stringify(baseline.source) !== JSON.stringify(source)) throw validationError("Document baseline belongs to a different enterprise, service, or document")
|
||||
const before = await api.getApprovalDocument(client, documentId)
|
||||
const changedFields = changes(before, patch)
|
||||
if (baseline && changedFields.length) {
|
||||
const hashes = documentFieldHashes(before)
|
||||
const conflicts = DOCUMENT_EDITABLE_FIELDS.filter(field => patch[field] !== undefined && baseline.fieldHashes[field] !== hashes[field])
|
||||
if (conflicts.length) throw new DocumentMutationError({ source, code: "DOCUMENT_CONFLICT", preview: Boolean(dryRun), executed: false, verified: false, conflictingFields: conflicts }, "Document changed since export; export and review again.", 1, nextRead(corp, documentId))
|
||||
}
|
||||
if (dryRun) return preview(corp, documentId, before, patch, changedFields, Boolean(baseline))
|
||||
if (!changedFields.length) return { source, preview: false, executed: false, changed: false, changedFields, verified: true, baselineAvailable: Boolean(baseline), contentHash: documentHash(before.content) }
|
||||
const snapshot = saveDocumentSnapshot(corp, before, "update")
|
||||
try { await api.updateApprovalDocument(client, documentId, patch) } catch (error) {
|
||||
return failedWrite(error, { source, preview: false, operation: "update", baselineAvailable: Boolean(baseline), ...snapshot }, nextRead(corp, documentId))
|
||||
}
|
||||
return verifyDocument(client, corp, documentId, { ...before, ...patch }, changedFields, Boolean(baseline), snapshot)
|
||||
}
|
||||
|
||||
export async function deleteDocument(client: KyInstance, corp: CorpConfig, params: z.infer<typeof documentDeleteSchema>) {
|
||||
requireConfirmation("delete", params)
|
||||
const before = await api.getApprovalDocument(client, params.documentId)
|
||||
const source = documentSource(corp, params.documentId)
|
||||
if (params.dryRun) return { source, preview: true, executed: false, changesDiff: { before, after: null } }
|
||||
const snapshot = saveDocumentSnapshot(corp, before, "delete")
|
||||
try { await api.deleteApprovalDocument(client, params.documentId) } catch (error) {
|
||||
return failedWrite(error, { source, preview: false, operation: "delete", ...snapshot }, nextRead(corp, params.documentId))
|
||||
}
|
||||
return { source, preview: false, executed: true, deleted: true, ...snapshot }
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test"
|
||||
import { mkdtempSync, rmSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import type { KyInstance } from "ky"
|
||||
import { CorpConfigSchema } from "../../../core/config/types.js"
|
||||
import { resolveHoseLinkIdentity, resolveSealLinkIdentity } from "./assist-identity.js"
|
||||
|
||||
const originalFetch = globalThis.fetch
|
||||
const originalStore = process.env.SEAL_USE_TOKEN_STORE
|
||||
let dir: string
|
||||
let requests: Array<{ path: string; body?: unknown }>
|
||||
let staffItems: unknown[]
|
||||
let roleResponseFails: boolean
|
||||
let staffResponseFails: boolean
|
||||
|
||||
beforeEach(() => {
|
||||
dir = mkdtempSync(join(tmpdir(), "seal-assist-identity-"))
|
||||
process.env.SEAL_USE_TOKEN_STORE = join(dir, "tokens.json")
|
||||
requests = []
|
||||
staffItems = [{ id: "CORP:STAFF", name: "实际合思员工", roles: [{ roleDefId: "CORP:admin" }] }]
|
||||
roleResponseFails = false
|
||||
staffResponseFails = false
|
||||
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const request = new Request(input, init)
|
||||
const path = new URL(request.url).pathname
|
||||
const body = request.method === "POST" ? await request.json() : undefined
|
||||
requests.push({ path, body })
|
||||
if (path === "/api/openapi/v1/auth/getAccessToken") return Response.json({ value: { accessToken: "test-openapi", expireTime: 7200 } })
|
||||
if (path === "/api/openapi/v1/staffs/getStaffIds") {
|
||||
return staffResponseFails ? Response.json({ error: "unavailable" }, { status: 403 }) : Response.json({ items: staffItems })
|
||||
}
|
||||
if (path === "/api/openapi/v1/roleDefGroups") {
|
||||
return roleResponseFails ? Response.json({ error: "unavailable" }, { status: 403 }) : Response.json({ items: [
|
||||
{ id: "roles", name: "系统角色", roleDefs: [{ id: "CORP:admin", name: "主管理员" }] }
|
||||
] })
|
||||
}
|
||||
throw new Error(`Unexpected identity request: ${path}`)
|
||||
}) as typeof fetch
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
globalThis.fetch = originalFetch
|
||||
if (originalStore === undefined) delete process.env.SEAL_USE_TOKEN_STORE
|
||||
else process.env.SEAL_USE_TOKEN_STORE = originalStore
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
function hoseCorp(staffId = "STAFF") {
|
||||
return CorpConfigSchema.parse({
|
||||
id: "identity-test", name: "Fixture", seal: {},
|
||||
source: { type: "hose", corpId: "CORP", staffId, domain: "https://hose.example.test", appKey: "key", appSecurity: "secret" }
|
||||
})
|
||||
}
|
||||
|
||||
describe("assistance link identity", () => {
|
||||
test("resolves the exact Hose employee and verified role, without unrelated staff or link requests", async () => {
|
||||
const identity = await resolveHoseLinkIdentity(hoseCorp())
|
||||
expect(identity).toEqual({ staffName: "实际合思员工", identityStatus: "resolved", roleNames: ["主管理员"] })
|
||||
expect(requests.find(request => request.path.endsWith("getStaffIds"))?.body).toEqual({ type: "STAFFID", conditionIds: ["CORP:STAFF"] })
|
||||
expect(requests.map(request => request.path)).toEqual([
|
||||
"/api/openapi/v1/auth/getAccessToken", "/api/openapi/v1/staffs/getStaffIds", "/api/openapi/v1/roleDefGroups"
|
||||
])
|
||||
})
|
||||
|
||||
test("canonicalizes bare and qualified staff IDs but rejects other companies and ambiguous matches", async () => {
|
||||
staffItems = [{ id: "STAFF", name: "短ID员工", roles: [] }]
|
||||
expect(await resolveHoseLinkIdentity(hoseCorp("CORP:STAFF"))).toMatchObject({ staffName: "短ID员工", roleNames: [] })
|
||||
for (const items of [
|
||||
[{ id: "OTHER:STAFF", name: "其他企业员工" }],
|
||||
[{ id: "CORP:OTHER", name: "其他管理员" }],
|
||||
[{ id: "STAFF", name: "甲" }, { id: "CORP:STAFF", name: "乙" }],
|
||||
[{ id: "STAFF", name: " " }]
|
||||
]) {
|
||||
staffItems = items
|
||||
expect(await resolveHoseLinkIdentity(hoseCorp())).toEqual({ staffName: null, identityStatus: "unresolved", roleNames: null })
|
||||
}
|
||||
})
|
||||
|
||||
test("role lookup failure and unknown role IDs preserve a verified name without inventing permissions", async () => {
|
||||
roleResponseFails = true
|
||||
expect(await resolveHoseLinkIdentity(hoseCorp())).toEqual({ staffName: "实际合思员工", identityStatus: "resolved", roleNames: null })
|
||||
roleResponseFails = false
|
||||
staffItems = [{ id: "STAFF", name: "员工", roles: [{ roleDefId: "not-visible" }] }]
|
||||
expect(await resolveHoseLinkIdentity(hoseCorp())).toEqual({ staffName: "员工", identityStatus: "resolved", roleNames: null })
|
||||
})
|
||||
|
||||
test("missing staff visibility is explicitly unresolved", async () => {
|
||||
staffResponseFails = true
|
||||
expect(await resolveHoseLinkIdentity(hoseCorp())).toEqual({ staffName: null, identityStatus: "unresolved", roleNames: null })
|
||||
})
|
||||
|
||||
test("Seal identity comes from the actual session and includes its own permission scope", async () => {
|
||||
const client = { get: () => ({ json: async () => ({ data: {
|
||||
user: { id: "seal-user", tenantId: "tenant", name: "Seal实际人员", isAdmin: true, permissions: ["*"] },
|
||||
tenant: { id: "tenant", name: "企业" }
|
||||
} }) }) } as unknown as KyInstance
|
||||
expect(await resolveSealLinkIdentity(client)).toEqual({
|
||||
staffName: "Seal实际人员", identityStatus: "resolved", isAdmin: true, permissions: ["*"]
|
||||
})
|
||||
})
|
||||
|
||||
test("Seal identity failure returns unknown values, not a guessed employee or administrator", async () => {
|
||||
const client = { get: () => { throw new Error("private upstream details") } } as unknown as KyInstance
|
||||
expect(await resolveSealLinkIdentity(client)).toEqual({
|
||||
staffName: null, identityStatus: "unresolved", isAdmin: null, permissions: null
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,64 @@
|
||||
import type { KyInstance } from "ky"
|
||||
import { ensureHoseOpenapiToken, fetchHoseRoleDefGroups, fetchHoseStaffDetails } from "../../../core/auth/hose.js"
|
||||
import type { CorpConfig } from "../../../core/config/types.js"
|
||||
import { getMe } from "../api.js"
|
||||
import type { MeData } from "../types.js"
|
||||
|
||||
type LinkIdentity = {
|
||||
staffName: string | null;
|
||||
identityStatus: "resolved" | "unresolved";
|
||||
}
|
||||
|
||||
/** Use the actual Seal session user, which may differ from the configured Hose employee. */
|
||||
export function summarizeSealLinkIdentity(user: MeData["user"]) {
|
||||
const staffName = user.name.trim() || null
|
||||
return {
|
||||
staffName,
|
||||
identityStatus: staffName ? "resolved" as const : "unresolved" as const,
|
||||
isAdmin: user.isAdmin,
|
||||
permissions: user.permissions
|
||||
}
|
||||
}
|
||||
|
||||
export async function resolveSealLinkIdentity(client: KyInstance) {
|
||||
try {
|
||||
return summarizeSealLinkIdentity((await getMe(client)).user)
|
||||
} catch {
|
||||
// Identity enrichment must not discard an otherwise valid assistance link.
|
||||
return { staffName: null, identityStatus: "unresolved" as const, isAdmin: null, permissions: null }
|
||||
}
|
||||
}
|
||||
|
||||
export async function resolveHoseLinkIdentity(corp: CorpConfig): Promise<LinkIdentity & { roleNames: string[] | null }> {
|
||||
const unresolved = { staffName: null, identityStatus: "unresolved" as const, roleNames: null }
|
||||
if (corp.source.type !== "hose") return unresolved
|
||||
const source = corp.source
|
||||
const canonicalId = (id: string) => id.includes(":") ? id : `${source.corpId}:${id}`
|
||||
const targetId = canonicalId(source.staffId)
|
||||
try {
|
||||
const token = await ensureHoseOpenapiToken(corp)
|
||||
const staffs = await fetchHoseStaffDetails(source.domain, token, [targetId])
|
||||
const matches = staffs.filter(staff => typeof staff.id === "string" && canonicalId(staff.id) === targetId)
|
||||
const staff = matches.length === 1 ? matches[0] : undefined
|
||||
if (!staff || typeof staff.name !== "string" || !staff.name.trim()) return unresolved
|
||||
|
||||
let roleNames: string[] | null = null
|
||||
if (Array.isArray(staff.roles)) {
|
||||
if (staff.roles.length === 0) roleNames = []
|
||||
else {
|
||||
try {
|
||||
const roles = (await fetchHoseRoleDefGroups(source.domain, token)).flatMap(group => group.roleDefs)
|
||||
const names = staff.roles.map(role => roles.find(item => item.id === role.roleDefId)?.name)
|
||||
if (names.every((name): name is string => typeof name === "string" && name.trim().length > 0)) {
|
||||
roleNames = [...new Set(names)]
|
||||
}
|
||||
} catch {
|
||||
// Missing role visibility does not make a verified employee name unknown.
|
||||
}
|
||||
}
|
||||
}
|
||||
return { staffName: staff.name.trim(), identityStatus: "resolved", roleNames }
|
||||
} catch {
|
||||
return unresolved
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import type { KyInstance } from "ky"
|
||||
import { classifyCliError } from "../../../core/errors.js"
|
||||
import { lookupDocumentExpenses, ExpenseLookupError } from "./lookup.js"
|
||||
|
||||
const sn = "SN-FIXTURE"
|
||||
const run = (id = "run-1", overrides: Record<string, unknown> = {}) => ({
|
||||
id, sourceDocumentSN: sn, sourceDocumentId: "source-1", sourceSystem: "hose", documentId: `document-${id}`, ...overrides
|
||||
})
|
||||
const expense = (id = "expense-1", recordId = "run-1", overrides: Record<string, unknown> = {}) => ({
|
||||
id, recordId, documentId: `document-${recordId}`, type: "交通费", amount: 12.5, currency: "CNY", description: "Fixture expense",
|
||||
createdAt: "2025-01-01T00:00:00Z", user: { mobile: "not-for-output", name: "Fixture Person" }, ...overrides
|
||||
})
|
||||
type Reply = (path: string, query: URLSearchParams) => unknown
|
||||
function mockClient(reply: Reply) {
|
||||
const requests: Array<{ path: string; query: URLSearchParams }> = []
|
||||
const client = { get(path: string, options: { searchParams: URLSearchParams }) {
|
||||
const query = options.searchParams
|
||||
requests.push({ path, query })
|
||||
return { json: async () => ({ data: reply(path, query) }) }
|
||||
} } as unknown as KyInstance
|
||||
return { client, requests }
|
||||
}
|
||||
function pages(records: ReturnType<typeof run>[], expenses: ReturnType<typeof expense>[]) {
|
||||
return mockClient((path, query) => {
|
||||
const offset = Number(query.get("offset"))
|
||||
const limit = Number(query.get("limit"))
|
||||
if (path === "api/v1/approvals") return { records: records.slice(offset, offset + limit), total: records.length }
|
||||
const selected = expenses.filter(row => row.recordId === query.get("filter[recordId]"))
|
||||
return { expenses: selected.slice(offset, offset + limit), total: selected.length }
|
||||
})
|
||||
}
|
||||
|
||||
describe("expense lookup by document number", () => {
|
||||
test("joins every exact run across pages, verifies expense links and does not collapse document lines", async () => {
|
||||
const f = pages([run(), run("run-2"), run("run-unrelated", { sourceDocumentSN: `${sn}-EXTRA` })], [expense(), expense("expense-2"), expense("expense-3", "run-2")])
|
||||
const result = await lookupDocumentExpenses(f.client, { sn, limit: 1 })
|
||||
expect(result).toMatchObject({ status: "found", found: true, complete: true, matchedCount: 3, verification: "existence_only", scanned: { approvalRecords: 3, expenseRecords: 3, requests: 6 } })
|
||||
expect(result.approvalRecords.map(row => row.recordId)).toEqual(["run-1", "run-2"])
|
||||
expect(result.expenses.map(row => row.id)).toEqual(["expense-1", "expense-2", "expense-3"])
|
||||
expect(result.expenses[0]).toMatchObject({ amount: 12.5, currency: "CNY", sourceDocumentSN: sn, createdAt: "2025-01-01T08:00:00+08:00" })
|
||||
expect(result.expenses[0]).not.toHaveProperty("user")
|
||||
for (const request of f.requests) {
|
||||
expect(request.query.has("filter[startDate]")).toBe(false)
|
||||
expect(request.query.has("startDate")).toBe(false)
|
||||
if (request.path.includes("expenses")) expect(request.query.get("filter[search]")).toBe("")
|
||||
}
|
||||
})
|
||||
|
||||
test("only exhaustive linked expense queries may report not_found", async () => {
|
||||
const f = pages([run(), run("run-2")], [])
|
||||
const result = await lookupDocumentExpenses(f.client, { sn, limit: 1 })
|
||||
expect(result).toMatchObject({ status: "not_found", found: false, complete: true, matchedCount: 0, queryScope: { association: "visible_approval_records", approvalRecordsComplete: true } })
|
||||
expect(f.requests.filter(request => request.path.includes("expenses"))).toHaveLength(2)
|
||||
})
|
||||
|
||||
test("missing run links and substring matches never prove absence", async () => {
|
||||
for (const records of [[], [run("other", { sourceDocumentSN: `${sn}-OTHER` })]]) {
|
||||
const f = pages(records, [])
|
||||
expect(await lookupDocumentExpenses(f.client, { sn })).toMatchObject({ status: "unknown", found: null, complete: false, reason: "approval_link_not_found" })
|
||||
expect(f.requests.every(request => request.path.includes("approvals"))).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
test("the same SN pointing to different source documents is ambiguous", async () => {
|
||||
const f = pages([run(), run("run-2", { sourceDocumentId: "another-source" })], [expense()])
|
||||
expect(await lookupDocumentExpenses(f.client, { sn })).toMatchObject({ status: "unknown", found: null, reason: "ambiguous_source_documents" })
|
||||
expect(f.requests).toHaveLength(1)
|
||||
})
|
||||
|
||||
test("a foreign or missing record link cannot be counted as a match", async () => {
|
||||
for (const invalid of [expense("bad", "foreign"), expense("bad", "run-1", { documentId: "foreign" }), { id: "bad" }]) {
|
||||
const f = mockClient(path => path.includes("approvals") ? { records: [run()], total: 1 } : { expenses: [invalid], total: 1 })
|
||||
expect(await lookupDocumentExpenses(f.client, { sn })).toMatchObject({ status: "unknown", found: null, reason: "association_mismatch", matchedCount: 0 })
|
||||
}
|
||||
})
|
||||
|
||||
test("repeated pages stop without producing a negative conclusion", async () => {
|
||||
const f = mockClient(path => path.includes("approvals") ? { records: [run()], total: 2 } : { expenses: [], total: 0 })
|
||||
expect(await lookupDocumentExpenses(f.client, { sn, limit: 1 })).toMatchObject({ status: "unknown", found: null, reason: "repeated_page", complete: false })
|
||||
expect(f.requests).toHaveLength(3)
|
||||
})
|
||||
|
||||
test("overlapping expense pages deduplicate IDs while retaining distinct expense lines", async () => {
|
||||
const f = mockClient((path, query) => {
|
||||
if (path.includes("approvals")) return { records: [run()], total: 1 }
|
||||
const offset = Number(query.get("offset"))
|
||||
return { expenses: offset === 0 ? [expense(), expense("expense-2")] : offset === 2 ? [expense("expense-2"), expense("expense-3")] : [], total: 3 }
|
||||
})
|
||||
expect(await lookupDocumentExpenses(f.client, { sn, limit: 2 })).toMatchObject({ status: "found", complete: true, matchedCount: 3 })
|
||||
})
|
||||
|
||||
for (const stage of ["approval", "expense"] as const) {
|
||||
test(`${stage} scan limits retain positive evidence but cannot assert completeness`, async () => {
|
||||
const f = pages(stage === "approval" ? [run(), run("run-2")] : [run()], [expense(), expense("expense-2")])
|
||||
expect(await lookupDocumentExpenses(f.client, { sn, maxScan: 1 })).toMatchObject({ status: "found", found: true, complete: false, reason: "scan_limit", matchedCount: 1 })
|
||||
})
|
||||
}
|
||||
|
||||
test("missing totals, changing totals, and premature empty pages remain inconclusive", async () => {
|
||||
for (const mode of ["missing", "changing", "empty", "oversized"] as const) {
|
||||
const f = mockClient((path, query) => {
|
||||
if (path.includes("approvals")) return { records: [run()], total: 1 }
|
||||
const offset = Number(query.get("offset"))
|
||||
if (mode === "missing") return { expenses: [] }
|
||||
if (mode === "oversized") return { expenses: [expense(), expense("extra")], total: 2 }
|
||||
return { expenses: offset === 0 ? [expense()] : [], total: mode === "changing" && offset ? 3 : 2 }
|
||||
})
|
||||
const result = await lookupDocumentExpenses(f.client, { sn, limit: 1 })
|
||||
expect(result.complete).toBe(false)
|
||||
expect(result.found).not.toBe(false)
|
||||
expect(result.reason).toBe({ missing: "missing_total", changing: "total_changed", empty: "inconsistent_page", oversized: "inconsistent_page" }[mode])
|
||||
}
|
||||
})
|
||||
|
||||
test("request count is bounded independently of repeated or empty candidate histories", async () => {
|
||||
const f = mockClient((_path, query) => ({ records: [run(`run-${query.get("offset")}`)], total: 1000 }))
|
||||
const result = await lookupDocumentExpenses(f.client, { sn, limit: 1 })
|
||||
expect(result).toMatchObject({ status: "unknown", complete: false, reason: "request_limit" })
|
||||
expect(f.requests).toHaveLength(100)
|
||||
})
|
||||
|
||||
test("explicit dates filter expenses, not approval creation dates", async () => {
|
||||
const f = pages([run()], [expense()])
|
||||
const result = await lookupDocumentExpenses(f.client, { sn, startDate: "2025-01-01T00:00:00+08:00", endDate: "2025-12-31T23:59:59+08:00" })
|
||||
expect(result.queryScope.startDate).toBe("1735660800000")
|
||||
expect(f.requests[0]?.query.has("startDate")).toBe(false)
|
||||
expect(f.requests[1]?.query.get("filter[startDate]")).toBe("1735660800000")
|
||||
})
|
||||
|
||||
test("malformed dates and reversed ranges fail before HTTP", async () => {
|
||||
const f = pages([], [])
|
||||
for (const input of [{ startDate: "bad" }, { startDate: "2026-02-01", endDate: "2026-01-01" }]) {
|
||||
try { await lookupDocumentExpenses(f.client, { sn, ...input }); throw new Error("expected rejection") }
|
||||
catch (error) { expect(classifyCliError(error).exitCode).toBe(2) }
|
||||
}
|
||||
expect(f.requests).toHaveLength(0)
|
||||
})
|
||||
|
||||
test("query failures preserve partial matches and distinguish auth errors", async () => {
|
||||
for (const auth of [true, false]) {
|
||||
const f = mockClient((path, query) => {
|
||||
if (path.includes("approvals")) return { records: [run()], total: 1 }
|
||||
if (query.get("offset") === "0") return { expenses: [expense()], total: 2 }
|
||||
throw Object.assign(new Error("secret upstream body must not be printed"), { response: { status: auth ? 403 : 500 } })
|
||||
})
|
||||
try { await lookupDocumentExpenses(f.client, { sn, limit: 1 }); throw new Error("expected rejection") }
|
||||
catch (error) {
|
||||
expect(error).toBeInstanceOf(ExpenseLookupError)
|
||||
const failure = error as ExpenseLookupError
|
||||
expect(failure.exitCode).toBe(auth ? 11 : 1)
|
||||
expect(failure.report).toMatchObject({ status: "found", found: true, complete: false, matchedCount: 1, reason: auth ? "authentication_required" : "expense_query_failed" })
|
||||
expect(JSON.stringify(failure.report)).not.toContain("secret upstream")
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
test("invalid upstream expense shapes do not default to an empty successful page", async () => {
|
||||
for (const data of [{ total: 0 }, { expenses: [{}], total: 1 }]) {
|
||||
const f = mockClient(path => path.includes("approvals") ? { records: [run()], total: 1 } : data)
|
||||
await expect(lookupDocumentExpenses(f.client, { sn })).rejects.toMatchObject({ report: { status: "unknown", reason: "expense_query_failed", complete: false } })
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,182 @@
|
||||
import { z } from "zod"
|
||||
import type { KyInstance } from "ky"
|
||||
import { CliError, classifyCliError, usageError } from "../../../core/errors.js"
|
||||
import { formatBeijingIso } from "../../../core/config/timestamps.js"
|
||||
import * as api from "../api.js"
|
||||
import type { ApprovalRun } from "../types.js"
|
||||
|
||||
export const expenseLookupOptionsSchema = z.object({
|
||||
sn: z.string().trim().min(1),
|
||||
limit: z.number().int().positive().max(100).optional(),
|
||||
maxScan: z.number().int().positive().max(10000).optional(),
|
||||
startDate: z.string().optional(),
|
||||
endDate: z.string().optional()
|
||||
})
|
||||
const expenseSchema = z.object({
|
||||
id: z.string().min(1), recordId: z.string().optional(), documentId: z.string().optional()
|
||||
}).passthrough()
|
||||
type Expense = z.infer<typeof expenseSchema>
|
||||
type ScanReason = "scan_limit" | "request_limit" | "missing_total" | "total_changed" | "repeated_page" | "inconsistent_page"
|
||||
type Scan<T> = { rows: T[]; complete: boolean; reason?: ScanReason }
|
||||
type Budget = { requests: number; maxRequests: number }
|
||||
|
||||
// Local to expense lookup: both links must be exhaustive before asserting absence.
|
||||
async function scanPages<T extends { id: string }>(
|
||||
fetchPage: (offset: number, limit: number) => Promise<{ rows: T[]; total?: number }>,
|
||||
pageSize: number,
|
||||
maxScan: number,
|
||||
budget: Budget,
|
||||
onRows: (rows: T[]) => void
|
||||
): Promise<Scan<T>> {
|
||||
const seen = new Map<string, T>()
|
||||
let offset = 0
|
||||
let expectedTotal: number | undefined
|
||||
const result = (reason?: ScanReason): Scan<T> => ({ rows: [...seen.values()], complete: !reason, ...(reason ? { reason } : {}) })
|
||||
while (offset < maxScan) {
|
||||
if (budget.requests >= budget.maxRequests) return result("request_limit")
|
||||
const limit = Math.min(pageSize, maxScan - offset)
|
||||
budget.requests++
|
||||
const page = await fetchPage(offset, limit)
|
||||
const rows = page.rows.slice(0, limit)
|
||||
onRows(rows)
|
||||
let newCount = 0
|
||||
let changedRow = false
|
||||
for (const row of rows) {
|
||||
const previous = seen.get(row.id)
|
||||
if (previous && JSON.stringify(previous) !== JSON.stringify(row)) changedRow = true
|
||||
if (!previous) { seen.set(row.id, row); newCount++ }
|
||||
}
|
||||
if (page.total === undefined) return result("missing_total")
|
||||
if (expectedTotal !== undefined && expectedTotal !== page.total) return result("total_changed")
|
||||
expectedTotal = page.total
|
||||
if (changedRow || page.rows.length > limit || seen.size > expectedTotal) return result("inconsistent_page")
|
||||
if (rows.length && newCount === 0) return result("repeated_page")
|
||||
if (seen.size === expectedTotal) return result()
|
||||
if (!rows.length) return result("inconsistent_page")
|
||||
offset += rows.length
|
||||
}
|
||||
return result("scan_limit")
|
||||
}
|
||||
|
||||
export class ExpenseLookupError extends CliError {
|
||||
constructor(readonly report: ExpenseLookupReport, auth: boolean) {
|
||||
super("Expense lookup is incomplete; inspect the JSON query state before drawing a conclusion.", auth ? 11 : 1)
|
||||
this.name = "ExpenseLookupError"
|
||||
}
|
||||
}
|
||||
|
||||
function isoTimestamp(value: unknown): string | undefined {
|
||||
const ms = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : NaN
|
||||
return Number.isFinite(new Date(ms).getTime()) ? formatBeijingIso(ms) : undefined
|
||||
}
|
||||
|
||||
function projectExpense(expense: Expense, record: ApprovalRun) {
|
||||
return {
|
||||
id: expense.id, recordId: expense.recordId, documentId: expense.documentId,
|
||||
sourceDocumentSN: record.sourceDocumentSN, sourceDocumentId: record.sourceDocumentId,
|
||||
type: typeof expense.type === "string" ? expense.type : undefined,
|
||||
amount: typeof expense.amount === "number" ? expense.amount : undefined,
|
||||
currency: typeof expense.currency === "string" ? expense.currency : undefined,
|
||||
description: typeof expense.description === "string" ? expense.description : undefined,
|
||||
startTime: isoTimestamp(expense.startTime), endTime: isoTimestamp(expense.endTime),
|
||||
createdAt: isoTimestamp(expense.createdAt), updatedAt: isoTimestamp(expense.updatedAt)
|
||||
}
|
||||
}
|
||||
|
||||
export type ExpenseLookupReport = {
|
||||
source: "seal_expense_store"
|
||||
sourceDocumentSN: string
|
||||
status: "found" | "not_found" | "unknown"
|
||||
found: boolean | null
|
||||
complete: boolean
|
||||
matchedCount: number
|
||||
reason?: string
|
||||
checkedAt: string
|
||||
verification: "existence_only"
|
||||
queryScope: {
|
||||
association: "visible_approval_records"
|
||||
startDate: string | null
|
||||
endDate: string | null
|
||||
approvalRecordsComplete: boolean
|
||||
maxScan: number
|
||||
maxRequests: number
|
||||
}
|
||||
scanned: { approvalRecords: number; expenseRecords: number; requests: number }
|
||||
approvalRecords: Array<{ recordId: string; documentId?: string; sourceDocumentId?: string; sourceSystem?: string }>
|
||||
expenses: ReturnType<typeof projectExpense>[]
|
||||
}
|
||||
|
||||
export async function lookupDocumentExpenses(client: KyInstance, input: z.infer<typeof expenseLookupOptionsSchema>): Promise<ExpenseLookupReport> {
|
||||
const params = expenseLookupOptionsSchema.parse(input)
|
||||
// Dates only constrain expenses, never the creation time of the linking approval.
|
||||
const dateValue = (value: string | undefined): string | null => {
|
||||
if (value === undefined) return null
|
||||
const parsed = /^\d+$/.test(value) ? Number(value) * (Number(value) < 1e11 ? 1000 : 1) : Date.parse(value)
|
||||
if (!Number.isFinite(parsed) || parsed < 0 || parsed > 8.64e15) throw usageError("Invalid expense date: expected ISO date or timestamp")
|
||||
return String(parsed)
|
||||
}
|
||||
const startDate = dateValue(params.startDate)
|
||||
const endDate = dateValue(params.endDate)
|
||||
if (startDate !== null && endDate !== null && Number(startDate) > Number(endDate)) throw usageError("Expense start date must not be after end date")
|
||||
const pageSize = params.limit ?? 100
|
||||
const maxScan = params.maxScan ?? 5000
|
||||
const budget: Budget = { requests: 0, maxRequests: 100 }
|
||||
const matched = new Map<string, ReturnType<typeof projectExpense>>()
|
||||
const records = new Map<string, ApprovalRun>()
|
||||
let approvalComplete = false
|
||||
let approvalScanned = 0
|
||||
let expenseScanned = 0
|
||||
let phase: "approval" | "expense" = "approval"
|
||||
const report = (complete: boolean, reason?: string): ExpenseLookupReport => {
|
||||
const found = matched.size > 0 ? true : complete ? false : null
|
||||
return {
|
||||
source: "seal_expense_store", sourceDocumentSN: params.sn, status: found === true ? "found" : found === false ? "not_found" : "unknown",
|
||||
found, complete, matchedCount: matched.size, ...(reason ? { reason } : {}), checkedAt: formatBeijingIso(), verification: "existence_only",
|
||||
queryScope: { association: "visible_approval_records", startDate, endDate, approvalRecordsComplete: approvalComplete, maxScan, maxRequests: budget.maxRequests },
|
||||
scanned: { approvalRecords: approvalScanned, expenseRecords: expenseScanned, requests: budget.requests },
|
||||
approvalRecords: [...records.values()].map(record => ({ recordId: record.id, documentId: record.documentId, sourceDocumentId: record.sourceDocumentId, sourceSystem: record.sourceSystem })),
|
||||
expenses: [...matched.values()]
|
||||
}
|
||||
}
|
||||
try {
|
||||
const approvals = await scanPages(async (offset, limit) => {
|
||||
// The deployed route supports search; SN equality is checked locally.
|
||||
const data = await api.listApprovalRuns(client, { search: params.sn, offset, limit })
|
||||
return { rows: data.records, total: data.total }
|
||||
}, pageSize, maxScan, budget, rows => {
|
||||
approvalScanned += rows.length
|
||||
for (const row of rows) if (row.sourceDocumentSN === params.sn) records.set(row.id, row)
|
||||
})
|
||||
approvalComplete = approvals.complete
|
||||
if (!records.size) return report(false, approvals.reason ?? "approval_link_not_found")
|
||||
const documents = new Set([...records.values()].map(record => JSON.stringify([record.sourceSystem, record.sourceDocumentId ?? record.documentId ?? record.id])))
|
||||
if (documents.size > 1) return report(false, "ambiguous_source_documents")
|
||||
phase = "expense"
|
||||
let reason: string | undefined = approvals.reason
|
||||
for (const record of records.values()) {
|
||||
if (expenseScanned >= maxScan) { reason ??= "scan_limit"; break }
|
||||
const expenses = await scanPages(async (offset, limit) => {
|
||||
const data = await api.listExpenses(client, { recordId: record.id, startDate: params.startDate, endDate: params.endDate, offset, limit })
|
||||
return { rows: z.array(expenseSchema).parse(data.expenses), total: data.total }
|
||||
}, pageSize, maxScan - expenseScanned, budget, rows => {
|
||||
expenseScanned += rows.length
|
||||
for (const row of rows) {
|
||||
if (row.recordId !== record.id || (row.documentId && record.documentId && row.documentId !== record.documentId)) {
|
||||
reason ??= "association_mismatch"
|
||||
continue
|
||||
}
|
||||
const previous = matched.get(row.id)
|
||||
const projected = projectExpense(row, record)
|
||||
if (previous && JSON.stringify(previous) !== JSON.stringify(projected)) reason ??= "expense_changed_during_scan"
|
||||
else matched.set(row.id, projected)
|
||||
}
|
||||
})
|
||||
reason ??= expenses.reason
|
||||
if (expenses.reason === "request_limit") break
|
||||
}
|
||||
return report(!reason && approvalComplete, reason)
|
||||
} catch (error) {
|
||||
const auth = classifyCliError(error).exitCode === 11
|
||||
throw new ExpenseLookupError(report(false, auth ? "authentication_required" : `${phase}_query_failed`), auth)
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,6 @@
|
||||
src/domains/seal/reports/
|
||||
├── charts/ # 图表生成子模块(100% 纯 TS 数据驱动矢量计算)
|
||||
│ ├── venn.ts # 图 1:AI 与人工审核准确率对比维恩图
|
||||
│ ├── duration-histogram.ts # 图 2:多模板单据审核耗时分布对比堆叠直方图
|
||||
│ └── index.ts # 图表模块出口
|
||||
├── pipeline/ # 取数、推断与组装流水线
|
||||
│ ├── describe.ts # 解析 Markdown 标题并反推各章节数据需求
|
||||
@@ -37,8 +36,7 @@ src/domains/seal/reports/
|
||||
│ ├── monthly.md # 标准月度报告 Markdown 模板
|
||||
│ ├── report.css # 报告排版与 A4 打印样式表
|
||||
│ ├── resources.ts # Bun 编译期静态资源嵌入定义
|
||||
│ ├── assets/ # 内置图表矢量资产
|
||||
│ └── examples/ # 真实脱敏报告示例
|
||||
│ └── assets/ # 内置图 1 矢量图表资产
|
||||
├── index.ts # 报告域对外统一门面出口 (Barrel)
|
||||
└── README.md # 架构与开发指南
|
||||
```
|
||||
@@ -1,66 +0,0 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { renderDurationHistogramPng, renderDurationHistogramSvg, DEFAULT_EEKA_DURATION_SERIES } from "./duration-histogram.js";
|
||||
import { pngDimensions } from "../render/png.js";
|
||||
import { writeFileSync, unlinkSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
|
||||
describe("renderDurationHistogramSvg", () => {
|
||||
test("generates valid SVG with default EEKA 240-sample series and average line", () => {
|
||||
const svg = renderDurationHistogramSvg();
|
||||
|
||||
expect(svg).toStartWith("<svg");
|
||||
expect(svg).toEndWith("</svg>\n");
|
||||
expect(svg).toContain("各单据模板审核耗时分布对比");
|
||||
expect(svg).toContain("总体平均耗时: 445.4秒");
|
||||
expect(svg).toContain("审核耗时(秒)");
|
||||
expect(svg).toContain("单据数量");
|
||||
expect(svg).toContain("采购付款单-月结款 (15单)");
|
||||
expect(DEFAULT_EEKA_DURATION_SERIES).toHaveLength(7);
|
||||
const totalSamples = DEFAULT_EEKA_DURATION_SERIES.reduce((acc, s) => acc + s.count, 0);
|
||||
expect(totalSamples).toBe(240);
|
||||
expect(svg).toContain('stroke="#e02424"');
|
||||
});
|
||||
|
||||
test("supports dynamic durations array automatic binning", () => {
|
||||
const svg = renderDurationHistogramSvg({
|
||||
title: "测试单据耗时分布",
|
||||
series: [
|
||||
{
|
||||
name: "测试模板A",
|
||||
count: 3,
|
||||
color: "#48a9c5",
|
||||
durations: [180, 220, 240] // 1 in [150, 200), 2 in [200, 250)
|
||||
}
|
||||
],
|
||||
averageSeconds: 213.3,
|
||||
averageLabel: "平均: 213.3秒"
|
||||
});
|
||||
|
||||
expect(svg).toContain("测试单据耗时分布");
|
||||
expect(svg).toContain("平均: 213.3秒");
|
||||
expect(svg).toContain("测试模板A (3单)");
|
||||
expect(svg).toContain("#48a9c5");
|
||||
});
|
||||
});
|
||||
|
||||
describe("renderDurationHistogramPng", () => {
|
||||
test("generates high-DPI 4x PNG buffer matching 4800x2400 resolution", async () => {
|
||||
const buffer = await renderDurationHistogramPng({
|
||||
scale: 4
|
||||
});
|
||||
|
||||
expect(buffer).toBeDefined();
|
||||
expect(buffer.length).toBeGreaterThan(50_000);
|
||||
|
||||
const tmpFile = join(tmpdir(), `test-hist-${Date.now()}.png`);
|
||||
try {
|
||||
writeFileSync(tmpFile, buffer);
|
||||
const dims = pngDimensions(tmpFile);
|
||||
expect(dims.width).toBe(4800);
|
||||
expect(dims.height).toBe(2400);
|
||||
} finally {
|
||||
try { unlinkSync(tmpFile); } catch {}
|
||||
}
|
||||
}, 15000);
|
||||
});
|
||||
@@ -1,248 +0,0 @@
|
||||
import { renderHtmlToImageBuffer } from "../render/browser.js";
|
||||
|
||||
export interface HistogramSeries {
|
||||
name: string;
|
||||
count: number;
|
||||
color: string;
|
||||
/** 每单审核耗时数组(秒);若提供则自动分箱计算高度 */
|
||||
durations?: number[];
|
||||
/** 直接提供的各分箱频数数组(长度对应 bins 数量) */
|
||||
binCounts?: number[];
|
||||
}
|
||||
|
||||
export interface DurationHistogramOptions {
|
||||
title?: string;
|
||||
series: HistogramSeries[];
|
||||
averageSeconds?: number;
|
||||
averageLabel?: string;
|
||||
binWidth?: number;
|
||||
binStart?: number;
|
||||
binEnd?: number;
|
||||
width?: number;
|
||||
height?: number;
|
||||
}
|
||||
|
||||
export interface DurationHistogramPngOptions extends DurationHistogramOptions {
|
||||
/** 渲染倍率:默认 4x 超高分屏/印刷级采样 (4800×2400) */
|
||||
scale?: number;
|
||||
chrome?: string;
|
||||
}
|
||||
|
||||
/** 赢家时尚 (EEKA) 2026年8月全量 240 单样本的真实审核耗时分布基线数据 */
|
||||
export const DEFAULT_EEKA_DURATION_SERIES: HistogramSeries[] = [
|
||||
{
|
||||
name: "采购付款单-月结款",
|
||||
count: 15,
|
||||
color: "#48a9c5",
|
||||
binCounts: [2, 2, 0, 1, 0, 1, 2, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
|
||||
},
|
||||
{
|
||||
name: "其他报销及业务单据",
|
||||
count: 12,
|
||||
color: "#b19cd9",
|
||||
binCounts: [0, 0, 0, 0, 1, 0, 0, 1, 2, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0]
|
||||
},
|
||||
{
|
||||
name: "差旅报销单-定额",
|
||||
count: 22,
|
||||
color: "#f7a072",
|
||||
binCounts: [0, 0, 6, 3, 2, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]
|
||||
},
|
||||
{
|
||||
name: "采购申请与预付款类单据",
|
||||
count: 24,
|
||||
color: "#fed766",
|
||||
binCounts: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0]
|
||||
},
|
||||
{
|
||||
name: "一般费用报销单【收据】- 个人报销",
|
||||
count: 33,
|
||||
color: "#a8d5ba",
|
||||
binCounts: [0, 0, 0, 0, 0, 0, 2, 1, 0, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0]
|
||||
},
|
||||
{
|
||||
name: "一般费用报销单【发票】- 对外支付",
|
||||
count: 64,
|
||||
color: "#f5a9b8",
|
||||
binCounts: [0, 0, 1, 1, 2, 2, 2, 0, 4, 3, 4, 0, 0, 0, 1, 3, 0, 1, 1, 0]
|
||||
},
|
||||
{
|
||||
name: "一般费用报销单【发票】- 个人报销",
|
||||
count: 70,
|
||||
color: "#7fe3d7",
|
||||
binCounts: [0, 2, 2, 5, 5, 4, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
|
||||
}
|
||||
];
|
||||
|
||||
/**
|
||||
* 自动生成各单据模板审核耗时分布对比的多系列堆叠直方图 (SVG)。
|
||||
* 100% 纯代码矢量计算,数据驱动自动分箱,支持 7 组模板色彩层次堆叠与平均值虚线标注。
|
||||
*/
|
||||
export function renderDurationHistogramSvg(options?: Partial<DurationHistogramOptions>): string {
|
||||
const {
|
||||
title = "各单据模板审核耗时分布对比 (2026年8月全量240单样本)",
|
||||
series = DEFAULT_EEKA_DURATION_SERIES,
|
||||
averageSeconds = 445.4,
|
||||
averageLabel = "总体平均耗时: 445.4秒 (约7.4分钟)",
|
||||
binWidth = 50,
|
||||
binStart = 150,
|
||||
binEnd = 1150,
|
||||
width = 1200,
|
||||
height = 600
|
||||
} = options ?? {};
|
||||
|
||||
const numBins = Math.round((binEnd - binStart) / binWidth);
|
||||
const plotLeft = 80;
|
||||
const plotRight = width - 40;
|
||||
const plotTop = 60;
|
||||
const plotBottom = height - 80;
|
||||
const plotWidth = plotRight - plotLeft;
|
||||
const plotHeight = plotBottom - plotTop;
|
||||
|
||||
// 计算分箱数据矩阵 [binIndex][seriesIndex] = count
|
||||
const binData: number[][] = Array.from({ length: numBins }, () => Array(series.length).fill(0));
|
||||
|
||||
series.forEach((s, sIdx) => {
|
||||
if (s.binCounts && s.binCounts.length >= numBins) {
|
||||
for (let b = 0; b < numBins; b++) binData[b]![sIdx] = s.binCounts[b] ?? 0;
|
||||
} else if (s.durations) {
|
||||
for (const d of s.durations) {
|
||||
if (d >= binStart && d < binEnd) {
|
||||
const b = Math.min(numBins - 1, Math.floor((d - binStart) / binWidth));
|
||||
binData[b]![sIdx] = (binData[b]![sIdx] ?? 0) + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 计算最大 Y 轴高度(默认向上取整到偶数,至少 11)
|
||||
const maxStack = Math.max(11, ...binData.map((counts) => counts.reduce((acc, c) => acc + c, 0)));
|
||||
const yDomainMax = Math.ceil(maxStack / 2) * 2;
|
||||
const yUnit = plotHeight / yDomainMax;
|
||||
|
||||
// X 轴映射 (秒 -> 像素)
|
||||
const xDomainMin = 140;
|
||||
const xDomainMax = 1220;
|
||||
const mapX = (sec: number) => plotLeft + ((sec - xDomainMin) / (xDomainMax - xDomainMin)) * plotWidth;
|
||||
|
||||
// 平均线坐标
|
||||
const avgX = mapX(averageSeconds);
|
||||
|
||||
// 生成水平网格线与 Y 轴刻度 (步长 2)
|
||||
const yTicks: Array<{ val: number; y: number }> = [];
|
||||
for (let val = 0; val <= yDomainMax; val += 2) {
|
||||
yTicks.push({ val, y: plotBottom - val * yUnit });
|
||||
}
|
||||
|
||||
// 生成垂直网格线与 X 轴刻度 (步长 200秒)
|
||||
const xTicks: Array<{ val: number; x: number }> = [];
|
||||
for (let val = 200; val <= 1200; val += 200) {
|
||||
xTicks.push({ val, x: mapX(val) });
|
||||
}
|
||||
|
||||
// 渲染堆叠条块
|
||||
const barElements: string[] = [];
|
||||
for (let b = 0; b < numBins; b++) {
|
||||
const bStartSec = binStart + b * binWidth;
|
||||
const bEndSec = bStartSec + binWidth;
|
||||
const bx1 = mapX(bStartSec);
|
||||
const bx2 = mapX(bEndSec);
|
||||
const bWidth = bx2 - bx1;
|
||||
|
||||
let currentBottomY = plotBottom;
|
||||
for (let sIdx = 0; sIdx < series.length; sIdx++) {
|
||||
const count = binData[b]![sIdx] ?? 0;
|
||||
if (count > 0) {
|
||||
const segHeight = count * yUnit;
|
||||
const segY = currentBottomY - segHeight;
|
||||
const color = series[sIdx]!.color;
|
||||
barElements.push(
|
||||
`<rect x="${bx1.toFixed(1)}" y="${segY.toFixed(1)}" width="${bWidth.toFixed(1)}" height="${segHeight.toFixed(1)}" fill="${color}" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>`
|
||||
);
|
||||
currentBottomY = segY;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 图例项目(按业务重要性逆序排在右上角图例框中)
|
||||
const legendItems = [...series].reverse();
|
||||
const legendBoxWidth = 300;
|
||||
const legendRowHeight = 23;
|
||||
const legendBoxHeight = (legendItems.length + 1) * legendRowHeight + 16;
|
||||
const legendBoxX = plotRight - legendBoxWidth - 12;
|
||||
const legendBoxY = plotTop + 12;
|
||||
|
||||
return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" font-family="-apple-system, BlinkMacSystemFont, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', Arial, sans-serif">
|
||||
<rect width="${width}" height="${height}" fill="#ffffff"/>
|
||||
|
||||
<!-- Title -->
|
||||
<text x="${(width / 2).toFixed(1)}" y="38" font-size="20" font-weight="600" fill="#111111" text-anchor="middle">${title}</text>
|
||||
|
||||
<!-- Horizontal Gridlines -->
|
||||
<g stroke="#f0f0f0" stroke-width="1">
|
||||
${yTicks.filter((t) => t.val > 0).map((t) => `<line x1="${plotLeft}" y1="${t.y.toFixed(1)}" x2="${plotRight}" y2="${t.y.toFixed(1)}"/>`).join("\n ")}
|
||||
</g>
|
||||
|
||||
<!-- Vertical Gridlines -->
|
||||
<g stroke="#f5f5f5" stroke-width="1">
|
||||
${xTicks.map((t) => `<line x1="${t.x.toFixed(1)}" y1="${plotTop}" x2="${t.x.toFixed(1)}" y2="${plotBottom}"/>`).join("\n ")}
|
||||
</g>
|
||||
|
||||
<!-- Stacked Bars -->
|
||||
<g>
|
||||
${barElements.join("\n ")}
|
||||
</g>
|
||||
|
||||
<!-- Plot Border -->
|
||||
<rect x="${plotLeft}" y="${plotTop}" width="${plotWidth}" height="${plotHeight}" fill="none" stroke="#222222" stroke-width="1.2"/>
|
||||
|
||||
<!-- Red Average Line -->
|
||||
<line x1="${avgX.toFixed(1)}" y1="${plotTop}" x2="${avgX.toFixed(1)}" y2="${plotBottom}" stroke="#e02424" stroke-width="2.4" stroke-dasharray="6,4"/>
|
||||
|
||||
<!-- Y-axis Ticks & Labels -->
|
||||
<g font-size="14" fill="#222222" text-anchor="end">
|
||||
${yTicks.map((t) => `<line x1="${plotLeft - 5}" y1="${t.y.toFixed(1)}" x2="${plotLeft}" y2="${t.y.toFixed(1)}" stroke="#222222" stroke-width="1.2"/><text x="${plotLeft - 10}" y="${(t.y + 5).toFixed(1)}">${t.val}</text>`).join("\n ")}
|
||||
</g>
|
||||
<text x="25" y="${(plotTop + plotHeight / 2).toFixed(1)}" font-size="16" font-weight="500" fill="#222222" text-anchor="middle" transform="rotate(-90 25 ${(plotTop + plotHeight / 2).toFixed(1)})">单据数量</text>
|
||||
|
||||
<!-- X-axis Ticks & Labels -->
|
||||
<g font-size="14" fill="#222222" text-anchor="middle">
|
||||
${xTicks.map((t) => `<line x1="${t.x.toFixed(1)}" y1="${plotBottom}" x2="${t.x.toFixed(1)}" y2="${plotBottom + 5}" stroke="#222222" stroke-width="1.2"/><text x="${t.x.toFixed(1)}" y="${plotBottom + 24}">${t.val}</text>`).join("\n ")}
|
||||
</g>
|
||||
<text x="${(plotLeft + plotWidth / 2).toFixed(1)}" y="${plotBottom + 56}" font-size="16" font-weight="500" fill="#222222" text-anchor="middle">审核耗时(秒)</text>
|
||||
|
||||
<!-- Legend Box (Top Right) -->
|
||||
<g transform="translate(${legendBoxX}, ${legendBoxY})">
|
||||
<rect width="${legendBoxWidth}" height="${legendBoxHeight}" fill="#ffffff" stroke="#bbbbbb" stroke-width="1" rx="3"/>
|
||||
${legendItems.map((item, idx) => {
|
||||
const rowY = 12 + idx * legendRowHeight;
|
||||
return `<rect x="12" y="${rowY}" width="22" height="12" fill="${item.color}" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<text x="42" y="${rowY + 10}" font-size="12" fill="#222222">${item.name} (${item.count}单)</text>`;
|
||||
}).join("\n ")}
|
||||
<!-- Average Line in Legend -->
|
||||
<line x1="12" y1="${12 + legendItems.length * legendRowHeight + 6}" x2="34" y2="${12 + legendItems.length * legendRowHeight + 6}" stroke="#e02424" stroke-width="2.4" stroke-dasharray="5,3"/>
|
||||
<text x="42" y="${12 + legendItems.length * legendRowHeight + 10}" font-size="12" fill="#222222">${averageLabel}</text>
|
||||
</g>
|
||||
</svg>
|
||||
`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 采用本地 Headless Chrome 原生渲染管线输出高清晰度耗时分布直方图 PNG 图片。
|
||||
* 默认 4x 超高分采样 (4800×2400),完美匹配 24 寸 4K 屏与高精度 PDF 导出。
|
||||
*/
|
||||
export async function renderDurationHistogramPng(options?: Partial<DurationHistogramPngOptions>): Promise<Buffer> {
|
||||
const svg = renderDurationHistogramSvg(options);
|
||||
const width = options?.width ?? 1200;
|
||||
const height = options?.height ?? 600;
|
||||
const scale = options?.scale ?? 4;
|
||||
const html = `<!DOCTYPE html><html><head><meta charset="utf-8"><style>* { box-sizing: border-box; margin: 0; padding: 0; } body { width: ${width}px; height: ${height}px; background: #ffffff; display: flex; justify-content: center; align-items: center; font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", Arial, sans-serif; -webkit-font-smoothing: antialiased; }</style></head><body>${svg}</body></html>`;
|
||||
|
||||
return renderHtmlToImageBuffer({
|
||||
html,
|
||||
width,
|
||||
height,
|
||||
scale,
|
||||
chrome: options?.chrome
|
||||
});
|
||||
}
|
||||
@@ -1,2 +1 @@
|
||||
export * from "./venn.js";
|
||||
export * from "./duration-histogram.js";
|
||||
@@ -51,7 +51,7 @@ export function saveReportMarkdown(
|
||||
const cleanBase = basename(path).replace(/^\d+-/, "");
|
||||
target = `${assetDir}/${images.size + 1}-${cleanBase}`;
|
||||
const dynamic = dynamicAssets?.[path] ?? dynamicAssets?.[basename(path)] ?? dynamicAssets?.[cleanBase];
|
||||
const bundled = templatePath === BUILTIN_TEMPLATE_PATH ? REPORT_ASSETS[path] : undefined;
|
||||
const bundled = REPORT_ASSETS[path] ?? (templatePath === BUILTIN_TEMPLATE_PATH ? REPORT_ASSETS[path] : undefined);
|
||||
const data = dynamic ?? bundled ?? readFileSync(inputFile(resolve(dirname(templatePath), path)));
|
||||
files.set(resolve(dirname(file), target), data);
|
||||
images.set(path, target);
|
||||
|
||||
@@ -5,8 +5,7 @@
|
||||
| 文件 | 用途 |
|
||||
| --- | --- |
|
||||
| `monthly.md` | 模板本体。**可变的皮**:章节标题、表格结构允许增删改名——填充逻辑从标题反推数据需求(`src/domains/seal/reports/describe.ts`),改这里通常不用改代码 |
|
||||
| `assets/` | 报告配图(图 1 数据图、图 2/3 占位图),相对引用,渲染时随 md 一起解析 |
|
||||
| `examples/` | 填充真实数据的成品示例(结构参考 + 测试夹具) |
|
||||
| `assets/` | 报告核心配图(图 1 准确率维恩图),相对引用,渲染时随 md 一起解析 |
|
||||
| `report.css` | HTML、长图和 A4 PDF 共用的版式,随 CLI 内嵌 |
|
||||
|
||||
模板纪律见模板仓库 README:不引入 frontmatter/占位符标记(结构即契约)、正文不含 HTML 注释、表格只换数据行。
|
||||
|
||||
@@ -1,123 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="600" viewBox="0 0 1200 600" font-family="-apple-system, BlinkMacSystemFont, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', Arial, sans-serif">
|
||||
<rect width="1200" height="600" fill="#ffffff"/>
|
||||
|
||||
<!-- Title -->
|
||||
<text x="600.0" y="38" font-size="20" font-weight="600" fill="#111111" text-anchor="middle">各单据模板审核耗时分布对比 (2026年8月全量240单样本)</text>
|
||||
|
||||
<!-- Horizontal Gridlines -->
|
||||
<g stroke="#f0f0f0" stroke-width="1">
|
||||
<line x1="80" y1="443.3" x2="1160" y2="443.3"/>
|
||||
<line x1="80" y1="366.7" x2="1160" y2="366.7"/>
|
||||
<line x1="80" y1="290.0" x2="1160" y2="290.0"/>
|
||||
<line x1="80" y1="213.3" x2="1160" y2="213.3"/>
|
||||
<line x1="80" y1="136.7" x2="1160" y2="136.7"/>
|
||||
<line x1="80" y1="60.0" x2="1160" y2="60.0"/>
|
||||
</g>
|
||||
|
||||
<!-- Vertical Gridlines -->
|
||||
<g stroke="#f5f5f5" stroke-width="1">
|
||||
<line x1="140.0" y1="60" x2="140.0" y2="520"/>
|
||||
<line x1="340.0" y1="60" x2="340.0" y2="520"/>
|
||||
<line x1="540.0" y1="60" x2="540.0" y2="520"/>
|
||||
<line x1="740.0" y1="60" x2="740.0" y2="520"/>
|
||||
<line x1="940.0" y1="60" x2="940.0" y2="520"/>
|
||||
<line x1="1140.0" y1="60" x2="1140.0" y2="520"/>
|
||||
</g>
|
||||
|
||||
<!-- Stacked Bars -->
|
||||
<g>
|
||||
<rect x="90.0" y="443.3" width="50.0" height="76.7" fill="#48a9c5" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="140.0" y="443.3" width="50.0" height="76.7" fill="#48a9c5" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="140.0" y="366.7" width="50.0" height="76.7" fill="#7fe3d7" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="190.0" y="290.0" width="50.0" height="230.0" fill="#f7a072" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="190.0" y="251.7" width="50.0" height="38.3" fill="#f5a9b8" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="190.0" y="175.0" width="50.0" height="76.7" fill="#7fe3d7" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="240.0" y="481.7" width="50.0" height="38.3" fill="#48a9c5" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="240.0" y="366.7" width="50.0" height="115.0" fill="#f7a072" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="240.0" y="328.3" width="50.0" height="38.3" fill="#f5a9b8" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="240.0" y="136.7" width="50.0" height="191.7" fill="#7fe3d7" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="290.0" y="481.7" width="50.0" height="38.3" fill="#b19cd9" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="290.0" y="405.0" width="50.0" height="76.7" fill="#f7a072" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="290.0" y="328.3" width="50.0" height="76.7" fill="#f5a9b8" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="290.0" y="136.7" width="50.0" height="191.7" fill="#7fe3d7" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="340.0" y="481.7" width="50.0" height="38.3" fill="#48a9c5" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="340.0" y="443.3" width="50.0" height="38.3" fill="#f7a072" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="340.0" y="366.7" width="50.0" height="76.7" fill="#f5a9b8" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="340.0" y="213.3" width="50.0" height="153.3" fill="#7fe3d7" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="390.0" y="443.3" width="50.0" height="76.7" fill="#48a9c5" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="390.0" y="366.7" width="50.0" height="76.7" fill="#a8d5ba" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="390.0" y="290.0" width="50.0" height="76.7" fill="#f5a9b8" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="440.0" y="481.7" width="50.0" height="38.3" fill="#b19cd9" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="440.0" y="443.3" width="50.0" height="38.3" fill="#a8d5ba" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="440.0" y="405.0" width="50.0" height="38.3" fill="#7fe3d7" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="490.0" y="443.3" width="50.0" height="76.7" fill="#b19cd9" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="490.0" y="290.0" width="50.0" height="153.3" fill="#f5a9b8" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="540.0" y="481.7" width="50.0" height="38.3" fill="#48a9c5" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="540.0" y="443.3" width="50.0" height="38.3" fill="#a8d5ba" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="540.0" y="328.3" width="50.0" height="115.0" fill="#f5a9b8" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="590.0" y="481.7" width="50.0" height="38.3" fill="#b19cd9" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="590.0" y="328.3" width="50.0" height="153.3" fill="#f5a9b8" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="640.0" y="481.7" width="50.0" height="38.3" fill="#fed766" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="640.0" y="405.0" width="50.0" height="76.7" fill="#a8d5ba" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="690.0" y="481.7" width="50.0" height="38.3" fill="#f7a072" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="740.0" y="481.7" width="50.0" height="38.3" fill="#fed766" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="790.0" y="481.7" width="50.0" height="38.3" fill="#b19cd9" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="790.0" y="443.3" width="50.0" height="38.3" fill="#f5a9b8" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="840.0" y="405.0" width="50.0" height="115.0" fill="#f5a9b8" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="890.0" y="481.7" width="50.0" height="38.3" fill="#7fe3d7" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="940.0" y="481.7" width="50.0" height="38.3" fill="#f5a9b8" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="990.0" y="481.7" width="50.0" height="38.3" fill="#fed766" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<rect x="990.0" y="443.3" width="50.0" height="38.3" fill="#f5a9b8" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
</g>
|
||||
|
||||
<!-- Plot Border -->
|
||||
<rect x="80" y="60" width="1080" height="460" fill="none" stroke="#222222" stroke-width="1.2"/>
|
||||
|
||||
<!-- Red Average Line -->
|
||||
<line x1="385.4" y1="60" x2="385.4" y2="520" stroke="#e02424" stroke-width="2.4" stroke-dasharray="6,4"/>
|
||||
|
||||
<!-- Y-axis Ticks & Labels -->
|
||||
<g font-size="14" fill="#222222" text-anchor="end">
|
||||
<line x1="75" y1="520.0" x2="80" y2="520.0" stroke="#222222" stroke-width="1.2"/><text x="70" y="525.0">0</text>
|
||||
<line x1="75" y1="443.3" x2="80" y2="443.3" stroke="#222222" stroke-width="1.2"/><text x="70" y="448.3">2</text>
|
||||
<line x1="75" y1="366.7" x2="80" y2="366.7" stroke="#222222" stroke-width="1.2"/><text x="70" y="371.7">4</text>
|
||||
<line x1="75" y1="290.0" x2="80" y2="290.0" stroke="#222222" stroke-width="1.2"/><text x="70" y="295.0">6</text>
|
||||
<line x1="75" y1="213.3" x2="80" y2="213.3" stroke="#222222" stroke-width="1.2"/><text x="70" y="218.3">8</text>
|
||||
<line x1="75" y1="136.7" x2="80" y2="136.7" stroke="#222222" stroke-width="1.2"/><text x="70" y="141.7">10</text>
|
||||
<line x1="75" y1="60.0" x2="80" y2="60.0" stroke="#222222" stroke-width="1.2"/><text x="70" y="65.0">12</text>
|
||||
</g>
|
||||
<text x="25" y="290.0" font-size="16" font-weight="500" fill="#222222" text-anchor="middle" transform="rotate(-90 25 290.0)">单据数量</text>
|
||||
|
||||
<!-- X-axis Ticks & Labels -->
|
||||
<g font-size="14" fill="#222222" text-anchor="middle">
|
||||
<line x1="140.0" y1="520" x2="140.0" y2="525" stroke="#222222" stroke-width="1.2"/><text x="140.0" y="544">200</text>
|
||||
<line x1="340.0" y1="520" x2="340.0" y2="525" stroke="#222222" stroke-width="1.2"/><text x="340.0" y="544">400</text>
|
||||
<line x1="540.0" y1="520" x2="540.0" y2="525" stroke="#222222" stroke-width="1.2"/><text x="540.0" y="544">600</text>
|
||||
<line x1="740.0" y1="520" x2="740.0" y2="525" stroke="#222222" stroke-width="1.2"/><text x="740.0" y="544">800</text>
|
||||
<line x1="940.0" y1="520" x2="940.0" y2="525" stroke="#222222" stroke-width="1.2"/><text x="940.0" y="544">1000</text>
|
||||
<line x1="1140.0" y1="520" x2="1140.0" y2="525" stroke="#222222" stroke-width="1.2"/><text x="1140.0" y="544">1200</text>
|
||||
</g>
|
||||
<text x="620.0" y="576" font-size="16" font-weight="500" fill="#222222" text-anchor="middle">审核耗时(秒)</text>
|
||||
|
||||
<!-- Legend Box (Top Right) -->
|
||||
<g transform="translate(848, 72)">
|
||||
<rect width="300" height="200" fill="#ffffff" stroke="#bbbbbb" stroke-width="1" rx="3"/>
|
||||
<rect x="12" y="12" width="22" height="12" fill="#7fe3d7" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<text x="42" y="22" font-size="12" fill="#222222">一般费用报销单【发票】- 个人报销 (70单)</text>
|
||||
<rect x="12" y="35" width="22" height="12" fill="#f5a9b8" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<text x="42" y="45" font-size="12" fill="#222222">一般费用报销单【发票】- 对外支付 (64单)</text>
|
||||
<rect x="12" y="58" width="22" height="12" fill="#a8d5ba" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<text x="42" y="68" font-size="12" fill="#222222">一般费用报销单【收据】- 个人报销 (33单)</text>
|
||||
<rect x="12" y="81" width="22" height="12" fill="#fed766" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<text x="42" y="91" font-size="12" fill="#222222">采购申请与预付款类单据 (24单)</text>
|
||||
<rect x="12" y="104" width="22" height="12" fill="#f7a072" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<text x="42" y="114" font-size="12" fill="#222222">差旅报销单-定额 (22单)</text>
|
||||
<rect x="12" y="127" width="22" height="12" fill="#b19cd9" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<text x="42" y="137" font-size="12" fill="#222222">其他报销及业务单据 (12单)</text>
|
||||
<rect x="12" y="150" width="22" height="12" fill="#48a9c5" fill-opacity="0.8" stroke="#333333" stroke-width="0.75"/>
|
||||
<text x="42" y="160" font-size="12" fill="#222222">采购付款单-月结款 (15单)</text>
|
||||
<!-- Average Line in Legend -->
|
||||
<line x1="12" y1="179" x2="34" y2="179" stroke="#e02424" stroke-width="2.4" stroke-dasharray="5,3"/>
|
||||
<text x="42" y="183" font-size="12" fill="#222222">总体平均耗时: 445.4秒 (约7.4分钟)</text>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 11 KiB |
@@ -1,5 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="880" height="360" viewBox="0 0 880 360">
|
||||
<rect x="4" y="4" width="872" height="352" rx="10" fill="#f6f8fa" stroke="#c9d1d9" stroke-width="2" stroke-dasharray="8 6"/>
|
||||
<text x="440" y="168" text-anchor="middle" font-family="PingFang SC, Hiragino Sans GB, sans-serif" font-size="22" fill="#8b949e">配图占位:示例单据截图(可多张)</text>
|
||||
<text x="440" y="202" text-anchor="middle" font-family="PingFang SC, Hiragino Sans GB, sans-serif" font-size="14" fill="#adb5bd">实际报告替换为正式图表</text>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 581 B |
@@ -1,265 +0,0 @@
|
||||
# 【赢家】8月AI审核准确率报告
|
||||
|
||||
| 报告信息 | 内容 |
|
||||
| --- | --- |
|
||||
| 报告编号 | eeka-ai-audit-2026-08 |
|
||||
| 客户名称 | 赢家时尚 |
|
||||
| 统计期间 | 2026-08-01 ~ 2026-08-31 |
|
||||
| 报告状态 | 草稿 |
|
||||
| 生成日期 | 2026-09-23 |
|
||||
|
||||
> **摘要**:以赢家时尚授权的 **240 笔**历史审批单据(2026-08-01 ~ 2026-08-31)为样本,对合思 AI 审核结论与人工审核结论做全量复核。AI 审核准确率 **92.08%**,人工审核准确率 **83.33%**;系统全月成功审核率近 **90%**,自 8 月 8 日迭代后稳定在 **96.07%**。AI 在人工已同意的单据中额外识别出 **40 笔**存在风险的凭证。
|
||||
|
||||
---
|
||||
|
||||
## 1. 审核测试结果
|
||||
|
||||
### 1.1 数据来源与范围
|
||||
|
||||
| 项目 | 内容 |
|
||||
| --- | --- |
|
||||
| 数据来源 | 赢家时尚授权的已完成历史审批单据 |
|
||||
| 统计期间 | 2026-08-01 ~ 2026-08-31 期间单据 |
|
||||
| 单据模板 | 涵盖一般费用报销单【发票】-个人报销、一般费用报销单【发票】-对外支付、一般费用报销单【收据】-个人报销、差旅报销单-定额、采购付款单等 **16 类**业务单据模板 |
|
||||
| 样本总量 | **240 张**(100 张同意 + 100 张驳回 + 40 张建议复核) |
|
||||
|
||||
### 1.2 核心准确率结论
|
||||
|
||||
基于已经给定的规则库:
|
||||
|
||||
| 审核方式 | 准确率 |
|
||||
| --- | --- |
|
||||
| 合思 AI 审核 | **92.08%** |
|
||||
| 人工审核 | **83.33%** |
|
||||
|
||||
AI 审核准确率的计算方式:
|
||||
|
||||
$$ \text{AI 审核准确率} = \frac{\text{依规判定正确单数}}{\text{样本总量}} = \frac{221}{240} = 92.08\% $$
|
||||
|
||||

|
||||
|
||||
*图 1 · AI 与人工审核准确率对比*
|
||||
|
||||
### 1.3 系统稳定性
|
||||
|
||||
| 项目 | 内容 |
|
||||
| --- | --- |
|
||||
| 全月成功审核率 | 近 **90%** |
|
||||
| 迭代影响 | 8 月第一周失败率较高;自 8 月 8 日迭代后,系统稳定性升至 **96.07%** 的稳定运行常态 |
|
||||
|
||||
> **注**:“审核失败”是产品侧的保护机制:当 AI 对单据内容无法形成可靠判断,系统会将该次审核标记为失败,以避免错误影响实际审批。
|
||||
|
||||
---
|
||||
|
||||
## 2. AI 失准分析(学习优化空间)
|
||||
|
||||
在全量 **240 单**的深度稽核中,合思 AI 依规综合正确 **221 单(92.08%)**,综合失准共 **19 单(7.92%)**。失准主要由以下三个维度构成。
|
||||
|
||||
### 2.1 失准构成总览
|
||||
|
||||
| 维度 | 失准类型 | 占比 | 单数 |
|
||||
| --- | --- | --- | --- |
|
||||
| TOP 1 | 规则执行与判定偏差 | 47.4% | 9 张 |
|
||||
| TOP 2 | 数据与附件识别问题 | 26.3% | 5 张 |
|
||||
| TOP 3 | 费用明细查重冲突 | 26.3% | 5 张 |
|
||||
| 合计 | — | 100% | 19 张 |
|
||||
|
||||
### 2.2 TOP 1 · 规则执行与判定偏差(9 张 / 47.4%)
|
||||
|
||||
**解决方案**:严格校准规则触发后动作,按规则执行。
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| FP2609671 | rule-125 仅核验支付凭证金额一致性,不要求个人代垫的收款方必须是公司,AI 误要求 |
|
||||
| CD2625928 | 8 月 3 日至 8 月 5 日均为工作日(周一至周三),AI 误认为有周末未扣减问题 |
|
||||
| FP2609370 | 费用承担主体命中 rule-40 / rule-99 豁免白名单,AI 未执行豁免逻辑导致驳回 |
|
||||
|
||||
*(节选 3 例,全量 9 张)*
|
||||
|
||||
### 2.3 TOP 2 · 数据与附件识别问题(5 张 / 26.3%)
|
||||
|
||||
**解决方案**:持续优化识别模型,提升多附件文字解析稳定性。
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| SJ2661735 | 手写收据金额 243 元被 OCR 误识别为 2433 元,导致金额不符误驳回 |
|
||||
| FP2611200 | 微信红包支付记录清晰完整,AI 误判定为无关凭据导致误驳回 |
|
||||
| SG2619081 | 已完整包含中秋节福利品发放人员统计表 Excel 文件,AI 因多附件漏提取误判缺件驳回 |
|
||||
|
||||
*(节选 3 例,全量 5 张)*
|
||||
|
||||
### 2.4 TOP 3 · 费用明细查重冲突(5 张 / 26.3%)
|
||||
|
||||
**解决方案**:已去掉跨批次相似费用冲突的默认判定,客户可按需配置此功能。
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| CGD260875 | AI 因跨批次存在历史同类辅料费用提示疑似冲突转人工 |
|
||||
| FP2607495 | AI 因跨批次云产品疑似同类费用冲突转人工 |
|
||||
| FP2608432 | 发票金额 180 元(1% 普票),远未达到 500 元专票强制门槛,AI 因过度怀疑是否存在专票协议转人工 |
|
||||
|
||||
*(节选 3 例,全量 5 张)*
|
||||
|
||||
---
|
||||
|
||||
## 3. AI 发现的潜在风险
|
||||
|
||||
在人工审核同意的单据中,有部分单据被 AI 发现存在风险,问题 TOP 3 如下。
|
||||
|
||||
### 3.1 风险构成总览
|
||||
|
||||
| 维度 | 风险类型 | 占比 | 单数 |
|
||||
| --- | --- | --- | --- |
|
||||
| TOP 1 | 缺失要求凭证 | 57.5% | 23 张 |
|
||||
| TOP 2 | 大额预付与采购口径偏差 | 22.5% | 9 张 |
|
||||
| TOP 3 | 票据合规与专票强制违规 | 20.0% | 8 张 |
|
||||
| 合计 | — | 100% | 40 张 |
|
||||
|
||||
### 3.2 TOP 1 · 缺失要求凭证(23 张 / 57.5%)
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| FP2610941 | 改衣费未附改衣明细表 |
|
||||
| FP2610735 | 咨询费报销资料不全 |
|
||||
| FP2608630 | 专利代理费未列明发明名称且缺少缴费通知书 |
|
||||
|
||||
*(节选 3 例,全量 23 张)*
|
||||
|
||||
### 3.3 TOP 2 · 大额预付与采购口径偏差(9 张 / 22.5%)
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| YF2616524 | 大额预付款单未关联申购单 / 申请单 |
|
||||
| CGA260211 | 采购预付款单明细采购订单号与合同号不一致 |
|
||||
| CGD261254 | 采购付款单品类为上装类但发票明细为服装加工费,业务勾稽不符 |
|
||||
|
||||
*(节选 3 例,全量 9 张)*
|
||||
|
||||
### 3.4 TOP 3 · 票据合规与专票强制违规(8 张 / 20.0%)
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| FP2609850 / FP2610235 / FP2610631 | 发票类对外支付模板未上传正规发票,上传非正规微信截图或洗衣取衣单据 |
|
||||
| FP2610206 | 高税率业务金额超 500 元未开具增值税专用发票且无免专票佐证 |
|
||||
| FP2609582 | 完税证明纳税人名称与费用承担公司主体不一致 |
|
||||
|
||||
*(节选 3 条,全量 8 张)*
|
||||
|
||||
---
|
||||
|
||||
## 4. 综合效益
|
||||
|
||||
| 维度 | 结论 | 关键数据 |
|
||||
| --- | --- | --- |
|
||||
| 准确度 | 除去 AI 无法形成可靠判断而转失败的单据,AI 在既定规则范围内的准确率已赶超人工审批 | **92.08%** |
|
||||
| 时效 | AI 审核单张单据平均耗时赶超人工处理时效 | 平均 **445.4 秒** |
|
||||
| 风险拦截 | 在人工审核通过的单据中,合思 AI 有效防堵无票支付、大额无合同预付、税票违规等税务与资金安全隐患 | 40 笔 |
|
||||
| 工作量 | 协助财务人员弥补遗漏、关注单据重点信息,大幅释放财务人员精力,专注于更有价值的工作 | — |
|
||||
|
||||

|
||||
|
||||
*图 2 · 各单据模板审核耗时分布对比*
|
||||
|
||||
---
|
||||
|
||||
## 5. AI 与人工审核一致性示例
|
||||
|
||||
| 示例单号 | 单据模板 | 合思 AI 审核驳回意见 | 人工实际退回说明 | 双方一致性 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| **FP2609372** | 一般费用报销单【发票】- 个人报销 | 帕森墨镜发票(776.15元,税率13%)仅开具普通发票,单笔超500元未按规定开具增值税专用发票且无免专票佐证,违反专票管控要求,建议驳回换开专票。 | `4、发票不合规:普票替换成专票` | **专票合规要求100%对齐**:均严格执行超500元13%高税率发票必须开具专票的硬性管控。 |
|
||||
| **FP2610941** | 一般费用报销单【发票】- 个人报销 | 对应规则129:改衣明细表未上传,必备核心附件缺失,不符合改衣费报销要求,AI建议【驳回单据】。 | `2、附件不合规:未提供改衣费明细表` | **必备明细表缺失一致**:AI 精准拦截缺件,人工直接依据未提供改衣费明细表退回。 |
|
||||
| **FP2610780** | 一般费用报销单【发票】- 对外支付 | 版布开发费对外支付报销,对账单未上传至专项附件且未检出双方盖章,违反规则69,建议驳回单据、补充合规盖章对账单。 | `2、附件不合规:盖章对账单及送货单没有上传附件` | **公对公盖章凭据一致**:对外支付缺少双方盖章对账单,AI 提前拦截,人工随后同样驳回。 |
|
||||
| **CD2625843** | 差旅报销单-定额 | 差旅定额补助消费日期(8月10日)与关联出差申请单行程(7月31日)不符,超出合理出差区间,建议驳回。 | `3、表单填写错误:结余补贴时间与出差时间不一致` | **行程时间勾稽一致**:双方均敏锐识别出补贴申请时间与实际行程脱节。 |
|
||||
| **FP2611220** | 一般费用报销单【发票】- 个人报销 | 费用类型选用错误:报销内容为清洁耗材(鸡毛掸子、刮水器、除尘滚轮等),错选为“门店环保费(仅限清洁人工及绿植)”,建议驳回。 | `3、表单填写错误:费用明细选择办公费` | **科目填报纠错一致**:AI 指出错选环保费,人工直接打回要求改选办公费。 |
|
||||
| **FP2611191** | 一般费用报销单【发票】- 个人报销 | 活动表格内费用金额与实际报销金额不一致;未按要求上传金额匹配的一一对应支付记录,建议驳回。 | `支付记录与报销金额不一致,请把不相关的支付记录删除只保留与报销单相关的金额。` | **支付凭证与金额一致性**:双方均发现支付凭据与报销金额脱节、混入无关凭据。 |
|
||||
| **YS2600603** | 预提类非生产物料采购申请 | FS成本中心不符合品推费要求(应选品推组,实选两广事业部),二级费用类型与业务场景不匹配,建议驳回。 | `3、表单填写错误:成本中心、预算项目有误` | **预算与成本中心纠错一致**:AI 与人工退回均直指成本中心与预算项目选错。 |
|
||||
| **SJ2661686** | 一般费用报销单【收据】- 个人报销 | 存在2项高风险:收据模板错传正规发票;且改衣费报销缺少必备的改衣明细表,建议驳回。 | `未上传改衣费明细表` | **硬性合规项一致**:人工直接依据缺少改衣明细表退回。 |
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
*图 3 ~ 6 · 上述示例单对应的单据截图*
|
||||
|
||||
---
|
||||
|
||||
## 6. AI 通过 / 人工驳回单据明细
|
||||
|
||||
| 单据编号 | 单据模板 | AI 审批决策 | 人工审批参考结论 | 原因分类 | 复核结论 | 截图 |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| **FP2608010** | 发票-个人报销 | 同意 | 终止 (改衣费超标) | **依规正确 (计入 D4)** | 单据改衣费发票、支付凭证及Excel改衣明细表齐全且金额均为1195元完全一致,收款人即申请人免营业执照,完全符合rule-129合规要求。人工以口头“改衣费超标”为由终止(规则库中无此超标阻断线),AI依规放行完全正确。 |  |
|
||||
| **FP2608464** | 发票-对外支付 | 同意 | 终止 (2、附件不合规:账单抬头错误) | **AI失准 (不计入分子)** | 附件对账单买方抬头存在错误,未匹配费用承担主体,命中rule-13对账单买方校验风险。人工退单指出账单抬头错误依规有据,AI未能识别出对账单抬头瑕疵直接放行,属于数据/附件识别失误。 |  |
|
||||
| **YS2600514** | 预提类采购申请 | 同意 | 终止 (请核对“确认采购金额”;请补充附件费用计划。) | **依规正确 (计入 D4)** | 现行规则库中对于该类申请单的检查规则不包含“采购金额/费用计划附件”的强制校验卡口,单据字段与基础凭证合规,AI依既定规则放行正确。 |  |
|
||||
| **SJ2661226** | 收据-个人报销 | 同意 | 终止 (无理由) | **依规正确 (计入 D4)** | 单据收据、明细表、支付记录及收据袋编码均齐全且金额完全一致,符合rule-129各项规定。单据本身合规,AI依规放行正确。 |  |
|
||||
| **SJ2661313** | 收据-个人报销 | 同意 | 终止 (无理由) | **AI失准 (不计入分子)** | 单据费用为“商场附加费”,依rule-128必须提供正规发票,本单仅附收据无发票,不符合科目票据规范。AI误判放行,属于规则执行错误。 |  |
|
||||
| **FP2609210** | 发票-对外支付 | 同意 | 终止 (无理由终止/撤回) | **依规正确 (计入 D4)** | 专柜小额维修费1236元,发票真实合规,依据rule-177区域部门5000元以下免关联申购单,万元以下免合同,单据在线上规则下无违规。AI放行正确。 |  |
|
||||
| **FP2609105** | 发票-个人报销 | 同意 | 终止 (未提供活动实际销售情况,费用占销比说明) | **依规正确 (计入 D4)** | 单据发票验真一致,电子发票PDF源文件齐全,收款人匹配。人工以“未提供费用占销比说明”退回,但规则库未将占销比设为必填附件,AI依规放行正确。 |  |
|
||||
| **SJ2661468** | 收据-个人报销 | 同意 | 终止 | **依规正确 (计入 D4)** | 门店改衣费报销260元,改衣清单与收据袋完整合规,无违规或缺件。AI按既定规则核验通过正确。 |  |
|
||||
| **SJ2661540** | 收据-个人报销 | 同意 | 终止 | **依规正确 (计入 D4)** | 单据模板及收据票据核验合规,无拦截风险。AI依规放行判定正确。 |  |
|
||||
| **FP2610213** | 发票-对外支付 | 同意 | 终止 | **依规正确 (计入 D4)** | 单据各项附件(增值税专票、盖章合同、核销单)齐全完整,金额准确无瑕疵。AI依规放行判定正确。 |  |
|
||||
| **FP2610610** | 发票-个人报销 | 同意 | 终止 (电话网络费由人事统一报销) | **依规正确 (计入 D4)** | 门店电话网络费330元,发票及支付记录完全合规。人工以公司内部口头行政口径“人事统一报销”退单,规则库未配置该项排除规则,AI依规放行正确。 |  |
|
||||
| **SJ2661469** | 收据-对外支付 | 同意 | 终止 | **依规正确 (计入 D4)** | 改衣费250元,改衣明细表及票据齐全合规,收款人为合规备案人员。AI依规判定正确。 |  |
|
||||
| **FP2610689** | 发票-对外支付 | 同意 | 终止 (结算单应按公司区分,不能合并一起) | **依规正确 (计入 D4)** | 员工体检福利费,体检合同、发票及人员名单齐全,分摊成本中心同属一区域。人工要求拆分公司结算单退回,规则库未配置该项规则,AI依规放行判定正确。 |  |
|
||||
| **FP2610431** | 发票-对外支付 | 同意 | 终止 | **依规正确 (计入 D4)** | 单据全维度核验合规,发票、收款主体、成本中心均无风险。AI依规放行判定正确。 |  |
|
||||
| **SJ2661828** | 收据-个人报销 | 同意 | 终止 | **依规正确 (计入 D4)** | 收据类单据表单与票据均符合规则要求,无风险项。AI依规放行判定正确。 |  |
|
||||
|
||||
在上述 **15 笔**单据中:
|
||||
|
||||
1. **86.7%(13 / 15 笔)属于依规正确(计入 D4)**:单据在线上凭证与 196 条规则库完全合规,退单主要由于经办人撤回、无理由终止,或财务人员在执行尚未纳入线上规则库的其他规则。**AI 线上放行依据规则库正确。**
|
||||
|
||||
2. **仅有 2 笔属于 AI 真实失准(占全量样本 0.83%)**,已如实扣除准确率,未计入分子:`FP2608464`(对账单抬头瑕疵未能检出)、`SJ2661313`(商场附加费无专票放行)。
|
||||
|
||||
---
|
||||
|
||||
## 7. 支撑数据与材料
|
||||
|
||||
### 7.1 分模板准确率与自动审批率
|
||||
|
||||
全量 N = 240:
|
||||
|
||||
| 单据模板 | AI 准确率 | 人工准确率 | 自动审批率 | 人工同意:驳回 | AI&人工都准确比例 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| 一般费用报销单【发票】- 个人报销 | 92.86% | 87.14% | 45.71% | 70(57:13) | 80.00% |
|
||||
| 一般费用报销单【发票】- 对外支付 | 92.19% | 75.00% | 42.19% | 64(50:14) | 67.19% |
|
||||
| 一般费用报销单【收据】- 个人报销 | 93.94% | 93.94% | 48.48% | 33(20:13) | 87.88% |
|
||||
| 差旅报销单-定额 | 81.82% | 100.00% | 31.82% | 22(19:3) | 81.82% |
|
||||
| 采购付款单-月结款 | 93.33% | 93.33% | 66.67% | 15(15:0) | 86.67% |
|
||||
| 预提类非生产物料采购申请 | 85.71% | 100.00% | 28.57% | 7(2:5) | 85.71% |
|
||||
| 预付款单 | 100.00% | 42.86% | 14.29% | 7(7:0) | 42.86% |
|
||||
| 一般费用报销单【收据】- 对外支付 | 100.00% | 100.00% | 40.00% | 5(2:3) | 100.00% |
|
||||
| 一般费用报销单【云账户及银行代扣】- 对外支付 | 100.00% | 50.00% | 25.00% | 4(3:1) | 50.00% |
|
||||
| 采购付款单-预付款 | 100.00% | 0.00% | 0.00% | 4(4:0) | 0.00% |
|
||||
| 非生产物料采购申请(不需预提) | 75.00% | 100.00% | 0.00% | 4(2:2) | 75.00% |
|
||||
| 装修报销单 | 100.00% | 0.00% | 0.00% | 1(1:0) | 0.00% |
|
||||
| 立项费用报销单 | 100.00% | 0.00% | 0.00% | 1(1:0) | 0.00% |
|
||||
| 预提类非生产物料采购报销单 | 100.00% | 100.00% | 0.00% | 1(0:1) | 100.00% |
|
||||
| 一般费用报销单【物流中心-运费专用】 | 100.00% | 100.00% | 100.00% | 1(1:0) | 100.00% |
|
||||
| 采购付款「负数」单-预付款 | 100.00% | 100.00% | 100.00% | 1(1:0) | 100.00% |
|
||||
| **全量样本总体 (N=240)** | **92.08%** | **83.33%** | **41.67%** | **240(185:55)** | **75.42%** |
|
||||
|
||||
### 7.2 跑批原始数据
|
||||
|
||||
[请至钉钉文档查看附件《赢家时尚2026年8月单据审批质量审计报告\_全量看板.xlsx》。](https://alidocs.dingtalk.com/i/nodes/kDnRL6jAJM6GyZPZI99mZ0gX8yMoPYe1?iframeQuery=anchorId%3DX02mu3v6grnsfbr1tvg7m)
|
||||
|
||||
### 7.3 抽样方法与可复现性
|
||||
|
||||
本次复核共抽取 240 笔样本,抽样规则如下:
|
||||
|
||||
| # | 抽样规则 |
|
||||
| --- | --- |
|
||||
| 1 | 时间全月均衡覆盖(8 月 1 日—31 日) |
|
||||
| 2 | 100 笔 AI 同意 + 100 笔 AI 驳回 + 40 笔 AI 复核 |
|
||||
| 3 | 保底 30 笔大额采购与预付款单据(上中下旬各 10 笔),其余 170 笔按企业当期各报销模板的实际发生比例加权分配 |
|
||||
| 4 | 固定随机种子抽样算法基于截止日固定随机种子(Seed: 20260831)自动执行,且全流程清单支持任何第三方精准复现核验 |
|
||||
|
||||
抽样基于账期截止日的固定随机种子执行,全过程可由第三方复现,完整可执行代码随报告附件交付。
|
||||
|
||||
**抽样算法说明**
|
||||
|
||||
1. **输入数据池**:2026 年 8 月全量 6,573 笔已归档业务单据。
|
||||
2. **随机数与排序稳定性**:采用 Python 标准库与 `hashlib.sha256(f"{seed}_{bill_no}")` 双重散列锁死序列,第三方执行该代码,所得出的 240 笔单据清单、顺序及样本编号都会与本数据集完全一致。
|
||||
3. **输出样本集**:程序精确生成 240 笔单据,时间分布严格为 **80 : 80 : 80(1:1:1)**,决策分布严格为 **100(同意): 100(驳回): 40(建议复核)**,采购大额单据共 **39 笔(满足 >= 30 笔保底要求)**,达到要求。
|
||||
@@ -1,8 +1,6 @@
|
||||
import monthly from "./monthly.md" with { type: "text" };
|
||||
import css from "./report.css" with { type: "text" };
|
||||
import accuracy from "./assets/图1-准确率对比.svg" with { type: "text" };
|
||||
import benefits from "./assets/图2-综合效益.svg" with { type: "text" };
|
||||
import screenshot from "./assets/图3-示例截图.svg" with { type: "text" };
|
||||
|
||||
// Git owns the source files; Bun embeds these imports in both developer and release binaries.
|
||||
// Loading the built-in template never depends on cwd, a checkout, or skill installation.
|
||||
@@ -10,7 +8,5 @@ export const BUILTIN_TEMPLATE_PATH = "builtin:reports/templates/monthly.md";
|
||||
export const BUILTIN_MONTHLY_TEMPLATE = monthly;
|
||||
export const REPORT_CSS = css;
|
||||
export const REPORT_ASSETS: Record<string, string> = {
|
||||
"assets/图1-准确率对比.svg": accuracy,
|
||||
"assets/图2-综合效益.svg": benefits,
|
||||
"assets/图3-示例截图.svg": screenshot
|
||||
"assets/图1-准确率对比.svg": accuracy
|
||||
};
|
||||
@@ -385,8 +385,8 @@ export const InsightPerformanceSchema = z.object({
|
||||
const DataRecordSchema = z.record(z.string(), z.unknown());
|
||||
|
||||
export const ExpenseListDataSchema = z.object({
|
||||
expenses: z.array(DataRecordSchema).default([]),
|
||||
total: z.number().optional()
|
||||
expenses: z.array(DataRecordSchema),
|
||||
total: z.number().int().nonnegative().optional()
|
||||
}).passthrough();
|
||||
|
||||
export const InvoiceListDataSchema = z.object({
|
||||
|
||||
+11
-1
@@ -141,6 +141,8 @@ describe("seal-use MCP server", () => {
|
||||
"seal-use rules push",
|
||||
"seal-use rules create --description test --scope all",
|
||||
"seal-use documents create --title t --purpose p --content c",
|
||||
"seal-use documents update doc-1 --content c --dry-run --yes",
|
||||
"seal-use documents delete doc-1 --dry-run",
|
||||
"seal-use simulation create --mode hosecloud",
|
||||
"seal-use deploy hosecloud sync sign-key",
|
||||
"seal-use users reset-password corp-a:u1",
|
||||
@@ -156,7 +158,15 @@ describe("seal-use MCP server", () => {
|
||||
|
||||
// Read-only commands must get past the policy; `version` is a top-level command with no
|
||||
// registry row, and `corp` is an area alias the CLI dispatches as `corps`.
|
||||
for (const command of ["seal-use version", "seal-use corps list", "seal-use corp list", "seal-use documents list --corp corp-a"]) {
|
||||
for (const command of [
|
||||
"seal-use version",
|
||||
"seal-use corps list",
|
||||
"seal-use corp list",
|
||||
"seal-use documents list --corp corp-a",
|
||||
"seal-use documents list --summary --corp corp-a",
|
||||
"seal-use documents get doc-1 --out ./body.txt --corp corp-a",
|
||||
"seal-use expenses --sn SN-FIXTURE --corp missing-fixture-corp"
|
||||
]) {
|
||||
const allowed = await callRead(command);
|
||||
expect({ command, refusedByPolicy: allowed.text.includes("only runs read-only commands") }).toEqual({
|
||||
command,
|
||||
|
||||
Reference in new issue
Block a user