Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cbc3b333ba | ||
|
|
059616ba22 | ||
|
|
11434f75f0 | ||
|
|
91feec7b0b | ||
|
|
04915c6ad6 | ||
|
|
bea6a9cf4e | ||
|
|
1209164cc8 | ||
|
|
b18f1d772b | ||
|
|
c6bd113fff | ||
|
|
077ecb050c | ||
|
|
64680cd4a0 | ||
|
|
135cd84e69 | ||
|
|
d26c4358c5 | ||
|
|
d127e80c1b | ||
|
|
e52654fec7 | ||
|
|
bbff9338a0 | ||
|
|
21e1a9d27a | ||
|
|
e9eb8095fc | ||
|
|
2749d765b3 | ||
|
|
6e4a8cb088 | ||
|
|
55ead68a06 | ||
|
|
41d5b175a6 | ||
|
|
480f833580 | ||
|
|
b21beba419 | ||
|
|
97d1c47a6c | ||
|
|
f6fe0de286 | ||
|
|
f9f72fa918 | ||
|
|
a52b6ac117 | ||
|
|
f8ac839840 | ||
|
|
7df5feb7b7 | ||
|
|
16f3f252c0 | ||
|
|
25d1036eed | ||
|
|
0210051ab7 | ||
|
|
5573dfb60e | ||
|
|
1fb61f794e | ||
|
|
7d15f3834d | ||
|
|
aad591569a |
No files matched your search
@@ -0,0 +1,72 @@
|
||||
---
|
||||
description: "Agent Skill architecture, documentation layering discipline, and tool-agent boundary principles"
|
||||
globs: "skills/**/*.md"
|
||||
trigger: "manual"
|
||||
---
|
||||
|
||||
# Agent Skill Architecture & Documentation Discipline
|
||||
|
||||
When authoring, refactoring, or maintaining Agent Skills under `skills/`:
|
||||
|
||||
## 1. Document Layering & Single Source of Truth
|
||||
|
||||
Agent Skill documentation follows a strict two-tier architecture:
|
||||
|
||||
```
|
||||
skills/<skill>/
|
||||
├── SKILL.md # Tier 1: Lightweight Traffic Routing Hub (导流中枢)
|
||||
└── references/ # Tier 2: Deep Domain Guides & Manuals (业务纵深手册)
|
||||
├── enterprise-onboarding.md
|
||||
├── report-templates.md
|
||||
└── ...
|
||||
```
|
||||
|
||||
### Tier 1: Main `SKILL.md` (Traffic Routing Hub)
|
||||
- **Role**: Lightweight, high-signal, rapid routing hub.
|
||||
- **Allowed Contents**:
|
||||
1. Frontmatter metadata (name, description, version);
|
||||
2. Bootstrap & installation guide;
|
||||
3. Universal system invariants (timestamp format `+08:00`, data masking, stdout/stderr boundaries);
|
||||
4. Core domain navigation (`corps`, `rules`);
|
||||
5. Cross-domain terminology contracts;
|
||||
6. **Reference Routing Table (`## 参考文档路由`)**: The primary mechanism to guide AI agents to specific deep-dive guides based on user intent and intent triggers;
|
||||
7. A strictly limited number of high-frequency single-step aggregate shortcut commands (e.g. `approval-runs diagnose`).
|
||||
- **Strict Anti-Patterns**:
|
||||
- ❌ **No "Feature Billboard" bloat**: NEVER dump multi-step workflows, full section breakdowns, complete schemas, or qualitative debate procedures into `SKILL.md`.
|
||||
- ❌ **Overcoming "Locality Bias" (就近修改惯性)**: When adding a new capability (e.g. `--ledger`), DO NOT casually expand the main `SKILL.md` just because it's in front of you. Always route to or expand the corresponding `references/*.md`.
|
||||
- ❌ **No Duplicate Maintenance**: If a topic is covered in `references/<name>.md`, do not duplicate its prose or guidelines in `SKILL.md`. The routing table row is sufficient.
|
||||
|
||||
### Tier 2: `references/*.md` (Deep Domain Manuals)
|
||||
- **Role**: The authoritative, exhaustive source of truth for deep workflows, business context, and operational troubleshooting.
|
||||
- **Contents**:
|
||||
1. Business background, objectives, and audience;
|
||||
2. Multi-step collaborative lifecycles (e.g. human-in-the-loop Tangent reviews);
|
||||
3. Complete column-by-column schema specifications;
|
||||
4. Decision matrices and terminology rules;
|
||||
5. Troubleshooting guides, validation error catalogs (e.g. `HD001`~`INFO002`), and mitigation examples;
|
||||
6. Concrete Markdown/JSON payload examples.
|
||||
|
||||
---
|
||||
|
||||
## 2. Tool vs. Agent Boundary Contract (Wrench vs. Discretion)
|
||||
|
||||
When designing CLI features and their Skill documentation:
|
||||
|
||||
- **CLI is a Deterministic Wrench (确定性扳手)**:
|
||||
- The CLI provides deterministic, repeatable, pure operations: data extraction, file export/import, offline schema/math validation, and self-contained rendering.
|
||||
- The CLI **MUST NOT** overstep into business discretion: it does not guess subjective fault attribution ("who is right/wrong"), nor does it fabricate explanations.
|
||||
- **Agent Exercises Business Discretion (自由裁量权)**:
|
||||
- The Agent (together with the user) exercises full discretion: pruning templates, filtering dirty data, conducting review debates (Tangent), and authoring qualitative takeaways.
|
||||
- **Strict Offline Boundary (本地事实源绝不越界)**:
|
||||
- When driven by a local artifact (e.g. `--ledger 台账.xlsx`), the CLI treats the local file as the **absolute and exclusive boundary**.
|
||||
- The CLI **MUST NEVER** reach out to remote cloud APIs to investigate records that were intentionally pruned/deleted from the local ledger.
|
||||
- The offline validation gatekeeper evaluates only the internal consistency and mathematical harmony of the remaining records in the ledger.
|
||||
|
||||
---
|
||||
|
||||
## 3. Terminology Precision & Anti-Ambiguity Contract
|
||||
|
||||
- **Avoid Ambiguous Catch-All Words**: Never use vague terms that conflate document status with system performance (e.g. completely retire the ambiguous word "失准").
|
||||
- **Strict Two-Level Separation**:
|
||||
- **Level 1: Document Validity / Approval Decision (审批决策)**: Focuses on the business document itself. Use `通过 (Pass)` / `驳回 (Reject)` / `违规拦截 (Interception)`. Rejection represents rule enforcement, NOT a system defect.
|
||||
- **Level 2: Review Verdict / Correctness Judgment (复核裁决)**: Focuses on whether the AI or human decision was correct upon subsequent review. Use explicit verdicts: `ai_correct`, `human_correct`, `both_correct`, `both_wrong`, `undecided`.
|
||||
@@ -3,6 +3,7 @@ node_modules/
|
||||
|
||||
# Build outputs
|
||||
dist/bin/
|
||||
build/
|
||||
|
||||
# Local runtime caches and system noise (regenerate at any time)
|
||||
.cache/
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "seal-use",
|
||||
"version": "0.11.7",
|
||||
"version": "0.11.11",
|
||||
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
|
||||
"author": {
|
||||
"name": "yingqing"
|
||||
|
||||
@@ -63,6 +63,7 @@ Recent commits use concise imperative subjects, often `Add ...` or `Refine ...`,
|
||||
- Webhook material pack & attachment policy: `.agents/rules/material-pack-policy.md`
|
||||
- Security trade-offs (usability-first accepted risks): `.agents/rules/security-posture.md`
|
||||
- Workspace hygiene (branch/worktree cleanup & release delta review): `.agents/rules/workspace-hygiene.md`
|
||||
- Skill documentation layering & tool-agent boundaries: `.agents/rules/skill-documentation.md`
|
||||
|
||||
|
||||
## Release & Publishing Guidelines
|
||||
@@ -76,7 +77,7 @@ Recent commits use concise imperative subjects, often `Add ...` or `Refine ...`,
|
||||
4. Release branch creation (`codex/release-vX.Y.Z`), commit, and push to `origin`.
|
||||
5. GitHub PR creation, CI monitoring, and merge.
|
||||
6. Main branch fast-forward (`git pull --ff-only origin main`).
|
||||
7. Annotated tag creation (`vX.Y.Z`) and push to `origin` (`git push origin refs/tags/vX.Y.Z`).
|
||||
7. Annotated tag creation (`vX.Y.Z`) and push to `origin` (`git push origin refs/tags/vX.Y.Z`), with synchronous best-effort mirror to `home` (Gitea).
|
||||
8. Clean removal of temporary release branch.
|
||||
|
||||
2. **Manual Protected-Branch Release & Workspace Isolation (Reference)**:
|
||||
@@ -104,7 +105,7 @@ Recent commits use concise imperative subjects, often `Add ...` or `Refine ...`,
|
||||
git push origin refs/tags/vX.Y.Z
|
||||
```
|
||||
- GitHub Actions (`release.yml`) is responsible only for cross-compiling all 5 target binaries and publishing the GitHub Release.
|
||||
- **Gitea Pull-Based Promotion**: Do not manually push branches or tags to `home` (Gitea). On WSL (`wsl-dev`), `seal-use-release-sync.timer` polls the latest GitHub Release every 15 minutes (or can be triggered immediately via `systemctl start seal-use-release-sync.service`), pulls the release and assets from GitHub into Gitea (`wsl-infra/systemd/`).
|
||||
- **Gitea Pull-Based Promotion & Mirroring**: On WSL (`wsl-dev`), `seal-use-release-sync.timer` polls GitHub every 15 minutes (or can be triggered immediately via `systemctl start seal-use-release-sync.service`), mirrors Git repository refs (branches and tags) and pulls release assets into Gitea (`wsl-infra/systemd/`).
|
||||
- The workflow enforces the merge-before-tag rule rather than trusting the operator: `release.yml` refuses to publish unless the tagged commit is an ancestor of `origin/main`. Actions in both workflows are pinned to commit SHAs rather than moving tags for supply-chain integrity.
|
||||
|
||||
## Security & Configuration Tips
|
||||
@@ -118,3 +119,13 @@ Credential files are written `0600`; a config placed by hand keeps the `0o644` d
|
||||
## Agent-Specific Instructions
|
||||
|
||||
Do not create `.codex/skills`; Codex is compatible with `.agents/skills`, and this project treats `.agents/` as authoritative. At project scope, prefer `AGENTS.md` instructions when present.
|
||||
|
||||
### Skill Documentation Layering & Traffic Routing Discipline
|
||||
- **Main `skills/<skill>/SKILL.md` is a Lightweight Traffic Routing Hub (精准路由中枢)**: Keep `SKILL.md` lean, structured, and focused on discovery, installation, universal conventions, and the Reference Routing Table (`## 参考文档路由`).
|
||||
- **NEVER bloat `SKILL.md` into a feature billboard**: Do NOT write lengthy multi-step workflows, full section breakdowns, extensive table schemas, or qualitative debate procedures into `SKILL.md`.
|
||||
- **Overcome Locality Bias (杜绝“就近修改”惯性)**: When developing or extending a feature, do not casually append detailed guides to `SKILL.md` just because it is open or visible. Always place the detailed manual in `skills/<skill>/references/<topic>.md`, and keep `SKILL.md` strictly to a one-line routing table entry.
|
||||
- **`references/*.md` is the Single Source of Truth**: All operational guides, schema specifications, business debate workflows (Tangent), and troubleshooting catalogs belong in `references/`.
|
||||
- **Deterministic Wrench vs. Agent Discretion (CLI 是扳手,Agent 自由裁量)**:
|
||||
- The CLI provides deterministic, repeatable tooling: data fetching, ledger export/import, offline schema/math gates, and self-contained rendering.
|
||||
- The Agent and user exercise business discretion: pruning templates, filtering dirty rows in local ledgers, debating edge cases, and authoring qualitative takeaways.
|
||||
- **Strict Offline Boundary**: When driven by a local file (`--ledger 台账.xlsx`), the CLI treats the local file as the absolute boundary and NEVER queries cloud APIs for rows deleted or pruned from the file. The validation gate checks only internal consistency. See `.agents/rules/skill-documentation.md`.
|
||||
@@ -7,6 +7,50 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.11.11] - 2026-10-16
|
||||
|
||||
### Added
|
||||
- Merge pull request #247 from yunyingk/mac15/remove-500-runs-limit
|
||||
- Refine risk intercept fallback calculation and sync ledger documentation
|
||||
- Refine report data collection to support unlimited runs without 500 cap
|
||||
|
||||
|
||||
## [0.11.10] - 2026-10-16
|
||||
|
||||
### Added
|
||||
- Merge pull request #245 from yunyingk/mac15/report-date-range-and-record-id-review
|
||||
- Add report ledger workflow, refine terminology and codify skill discipline
|
||||
- Refine report pipeline to support date ranges and recordId reviews
|
||||
- Merge pull request #244 from yunyingk/mac15/refine-hose-auth-doc
|
||||
- Refine hose auth guidelines and remove hardcoded personnel names
|
||||
|
||||
|
||||
## [0.11.9] - 2026-10-16
|
||||
|
||||
### Added
|
||||
- Merge pull request #240 from yunyingk/mac15/hose-ebot-outbound
|
||||
- Add hose-ebot command for Hose outbound discovery and approval callback
|
||||
- Merge pull request #239 from yunyingk/mac15/skill-install-and-wsl-gitea-sync
|
||||
- Add tool installation to skill and Git mirror sync to WSL worker
|
||||
- Merge pull request #238 from yunyingk/mac15/auth-hose-openapi-token
|
||||
- Add auth hose-openapi-token command for Hose enterprises
|
||||
- Merge pull request #237 from yunyingk/mac15/refine-external-report-readme
|
||||
- Refine pkg/report README and clean external docstrings
|
||||
|
||||
|
||||
## [0.11.8] - 2026-10-15
|
||||
|
||||
### Added
|
||||
- Merge pull request #235 from yunyingk/mac15/streamline-general-report-template
|
||||
- Add pkg/report standalone external validation suite and example report
|
||||
- Decouple chapter numbers from validation and pipeline rendering to allow arbitrary chapter order
|
||||
- Standardize report tables on clean 2-column format with clickable SN
|
||||
- Document user-centric dynamic adaptability principle in agent skill
|
||||
- Add automated audit link column and reconcile divergence metrics
|
||||
- Align Hose document URL with backlogDetail hash routing
|
||||
- Refine approval run URL resolution with Hose fallback and SSO
|
||||
|
||||
|
||||
## [0.11.7] - 2026-10-13
|
||||
|
||||
### Added
|
||||
|
||||
@@ -260,7 +260,7 @@ For test tenants that need a clean slate before importing another rule set, use
|
||||
|
||||
To compact draft rule numbers from `0000`, run `seal-use rules recode --corp <corpId>`. The first call returns an impact preview and an enterprise/environment/draft-bound one-use credential (exit 10), without executing the recode. Inspect the preview, then run the returned `nextCommand` separately; the credential expires after five minutes, and `--yes` cannot bypass it. `--dry-run` only previews. The server determines ordering, and every rule can change number; the verified per-rule mapping is returned after execution. Recode does not publish a version; old rule numbers must be interpreted with their published version. Clearing and test synchronization reset numbering only after verifying an empty draft.
|
||||
|
||||
For approval run detail commands, prefer the same commands with explicit `--corp <corpId>`—for example `seal-use approval-runs pick --corp <corpId> --sn <单号> --latest` or `seal-use approval-runs get <recordId> --corp <corpId> --summary`—before requesting the full record. CLI JSON output is protected by a 200KB default limit; use `--output-file` for large payloads or `--full` only when the full response is intentional. Hose provisional auth links are available with `seal-use auth hose-link --corp <corpId> --expire 7200`, which returns the unredacted `getProvisionalAuth` URL.
|
||||
For approval run detail commands, prefer the same commands with explicit `--corp <corpId>`—for example `seal-use approval-runs pick --corp <corpId> --sn <单号> --latest` or `seal-use approval-runs get <recordId> --corp <corpId> --summary`—before requesting the full record. CLI JSON output is protected by a 200KB default limit; use `--output-file` for large payloads or `--full` only when the full response is intentional. Hose provisional auth links are available with `seal-use auth hose-link --corp <corpId> --expire 7200`, which returns the unredacted `getProvisionalAuth` URL. For a raw Hose OpenAPI access token from persisted `appKey/appSecurity`, run `seal-use auth hose-openapi-token --corp <corpId>`; stdout returns `token`, `expiresAt`, and `cached`, and `--force` skips the local cache to mint a new token.
|
||||
|
||||
## Approval Run To Langfuse Bridge
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "seal-use",
|
||||
"version": "0.11.7",
|
||||
"version": "0.11.11",
|
||||
"private": true,
|
||||
"description": "Seal tenant operations toolkit: approval-run diagnosis, rule remediation, Hose/合思 auth, plus a CLI and an optional MCP server.",
|
||||
"license": "MIT",
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
# 【模板企业】8月AI审核准确率报告
|
||||
|
||||
| 报告信息 | 内容 |
|
||||
| --- | --- |
|
||||
| 报告编号 | RPT-202608-A3F8C2 |
|
||||
| 客户名称 | 模板企业 |
|
||||
| 统计期间 | 2026-08-01 ~ 2026-08-31 |
|
||||
| 报告状态 | 草稿 |
|
||||
| 生成日期 | 2026-09-23 |
|
||||
|
||||
> **摘要**:以模板企业授权的 240 笔已完成历史审批单据为样本,对 AI 审核结论与人工审核结论进行全量复核。AI 审核准确率 **92.08%**,人工审核准确率 **83.33%**。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 与人工审核准确率对比*
|
||||
|
||||
---
|
||||
|
||||
## 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%)
|
||||
|
||||
**解决方案**:严格校准规则触发后动作,按规则执行。
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| FP260001 | 规则仅核验支付凭证金额一致性,不要求个人代垫的收款方必须是公司,AI 误要求 |
|
||||
| CD260002 | 连续三日均为工作日(周一至周三),AI 误认为有周末未扣减问题 |
|
||||
| FP260003 | 费用承担主体命中豁免白名单,AI 未执行豁免逻辑导致驳回 |
|
||||
|
||||
*(节选 3 例,全量 9 张)*
|
||||
|
||||
### 2.3 TOP 2 · 数据与附件识别问题(5 张 / 26.3%)
|
||||
|
||||
**解决方案**:持续优化识别模型,提升多附件文字解析稳定性。
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| SJ260004 | 手写收据金额 243 元被 OCR 误识别为 2433 元,导致金额不符误驳回 |
|
||||
| FP260005 | 微信红包支付记录清晰完整,AI 误判定为无关凭据导致误驳回 |
|
||||
| SG260006 | 已完整包含福利品发放人员统计表 Excel 文件,AI 因多附件漏提取误判缺件驳回 |
|
||||
|
||||
*(节选 3 例,全量 5 张)*
|
||||
|
||||
### 2.4 TOP 3 · 费用明细查重冲突(5 张 / 26.3%)
|
||||
|
||||
**解决方案**:已去掉跨批次相似费用冲突的默认判定,可按需配置此功能。
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| CGD260007 | 跨批次存在历史同类辅料费用,提示疑似冲突转人工 |
|
||||
| FP260008 | 跨批次云产品疑似同类费用冲突转人工 |
|
||||
| FP260009 | 发票金额 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%)
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| FP260011 | 改衣费未附改衣明细表 |
|
||||
| FP260012 | 咨询费报销资料不全 |
|
||||
| FP260013 | 专利代理费未列明发明名称且缺少缴费通知书 |
|
||||
|
||||
*(节选 3 例,全量 23 张)*
|
||||
|
||||
### 3.3 TOP 2 · 大额预付与采购口径偏差(9 张 / 22.5%)
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| YF260014 | 大额预付款单未关联申购单 / 申请单 |
|
||||
| CGA260015 | 采购预付款单明细采购订单号与合同号不一致 |
|
||||
| CGD260016 | 采购付款单品类为上装类但发票明细为服装加工费,业务勾稽不符 |
|
||||
|
||||
*(节选 3 例,全量 9 张)*
|
||||
|
||||
### 3.4 TOP 3 · 票据合规与专票强制违规(8 张 / 20.0%)
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| FP260017 / FP260018 / FP260019 | 发票类对外支付模板未上传正规发票,上传非正规微信截图或洗衣取衣单据 |
|
||||
| FP260020 | 高税率业务金额超 500 元未开具增值税专用发票且无免专票佐证 |
|
||||
| FP260021 | 完税证明纳税人名称与费用承担公司主体不一致 |
|
||||
|
||||
*(节选 3 条,全量 8 张)*
|
||||
|
||||
---
|
||||
|
||||
## 4. 综合效益
|
||||
|
||||
| 维度 | 结论 | 关键数据 |
|
||||
| --- | --- | --- |
|
||||
| 准确度 | 除去 AI 无法形成可靠判断而转失败的单据,AI 在既定规则范围内的准确率已赶超人工审批 | **92.08%** |
|
||||
| 时效 | AI 审核单张单据平均耗时赶超人工处理时效 | 平均 **445.4 秒** |
|
||||
| 风险拦截 | 在人工审核通过的单据中,AI 有效防堵无票支付、大额无合同预付、税票违规等税务与资金安全隐患 | 40 笔 |
|
||||
| 工作量 | 协助财务人员弥补遗漏、关注单据重点信息,大幅释放财务人员精力,专注于更有价值的工作 | — |
|
||||
|
||||
---
|
||||
|
||||
## 5. 审核分歧与复核归因
|
||||
|
||||
在全量 **240 单**的深度复核中,AI 审核决策与人工实际审批结果存在分歧的单据共 **3 笔**(占全量样本 **1.25%**)。对分歧单据的复核定性与主要原因归类如下:
|
||||
|
||||
| 原因分类 | 占比 | 单数 | 核心说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| 线下口头要求/未在线配置规则 | 66.7% | 2 张 | 单据凭证齐全且符合现行线上规则,主要因经办人主动撤回、无理由终止或财务执行未上线的口头标准,AI 依既定规则放行 |
|
||||
| AI 识别或规则理解偏差 | 33.3% | 1 张 | 单据缺少必要发票凭据,AI 未能正确识别缺件卡口放行,已纳入模型调优与规则修复样本 |
|
||||
| 合计 | 100% | 3 张 | — |
|
||||
|
||||
**分歧分析与后续建议**:
|
||||
|
||||
1. **规则覆盖与口径统一**:存在分歧的单据中,绝大多数(**66.7%**,2 笔)并非 AI 判定缺陷,而是企业内部存在线下口头补充管控要求。建议根据实际管理需要,将此类管控标准沉淀并补充至线上规则库。
|
||||
2. **算法与识别调优**:对于真实失准单据(仅 **1 笔**,占全量 **0.42%**),已归入模型样本库进行针对性专项训练。
|
||||
|
||||
> 📌 **注**:分歧单据的逐单编号、审核比对意见与复核裁决记录,已完整收录于配套交付的《明细台账.xlsx》中,可供业务与审计部门按单查验核对。
|
||||
|
||||
---
|
||||
|
||||
## 6. 支撑数据与交付材料
|
||||
|
||||
### 6.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% |
|
||||
| 预付款单 | 100.00% | 42.86% | 14.29% | 7(7:0) | 42.86% |
|
||||
| **全量样本总体(N=240)** | **92.08%** | **83.33%** | **41.67%** | **240(185:55)** | **75.42%** |
|
||||
|
||||
*(其余 10 类模板从略,实际报告列出全量 16 类)*
|
||||
|
||||
### 6.2 跑批原始数据与交付台账
|
||||
|
||||
见同目录配套交付的《明细台账.xlsx》及《明细台账.csv》(完整收录本月全量跑批单据、AI 审核意见、人工审批结论及逐笔复核定性台账)。
|
||||
@@ -0,0 +1,64 @@
|
||||
# AI 审核报告编制与校验规范
|
||||
|
||||
本目录提供标准的 AI 审核报告 Markdown 模板与配套的离线校验脚本。
|
||||
|
||||
---
|
||||
|
||||
## 一、标准模板与章节规范
|
||||
|
||||
报告应以 Markdown 格式编写(可参考同目录下的 [`example-report.md`](example-report.md))。
|
||||
|
||||
### 1. 核心必填章节(按大标题名称识别)
|
||||
核心章节通过 `##` 大标题名称自动识别与归属,包含以下板块:
|
||||
|
||||
| 核心大标题名称 | 说明与要求 |
|
||||
| :--- | :--- |
|
||||
| **开篇「报告信息」表** | 文档顶部表格,必填 5 项:`报告编号`、`客户名称`、`统计期间`、`报告状态`、`生成日期`,均不可为空。 |
|
||||
| **`审核测试结果`** | 汇总效能指标、AI 与人工准确率结论、LaTeX 计算公式(`$$ \text{AI 审核准确率} = \frac{A}{B} = C\% $$`)与对比图表。 |
|
||||
| **`AI 失准分析`** | 包含失准构成总览表、TOP 1~N 典型错判案例表格与调优方案。 |
|
||||
| **`AI 发现的潜在风险`** | 包含潜在风险总览表、TOP 1~N 真实拦截案例表格(如凭证缺失、比价缺失、超期等)。 |
|
||||
| **`综合效益`** | 时效、准确度、风险拦截笔数宏观总结表(纯内部核对时可按需裁剪)。 |
|
||||
| **`审核分歧与复核归因`** | 人机分歧分类统计表(如“未在线配置规则”与“识别偏差”)与管理建议。 |
|
||||
| **`支撑数据与交付材料`** | 分模板统计表与说明。 |
|
||||
|
||||
### 2. 中间自定义插入章节
|
||||
* 如需针对特定部门、专项费用做深入穿透,允许在任意位置插入自定义章节(例如 `## 2. 营销业务线专项分析`)。
|
||||
* **规则**:大标题序号从 1 开始自然连续递增(1, 2, 3, 4, 5...);自定义插入的章节内容不受业务规则限制,写什么格式都直接放行。
|
||||
|
||||
---
|
||||
|
||||
## 二、核心格式规范
|
||||
|
||||
为保证文档严谨自洽,报告编写需满足以下格式守则:
|
||||
|
||||
1. **纯净 Markdown 语法**:
|
||||
* 严禁在开头使用 YAML Frontmatter(`---`),元数据请统一写在开篇「报告信息」表中;
|
||||
* 严禁残留草稿占位标记(如 `<!--slot:xxx-->`、`{{variable}}` 等);
|
||||
* 代码块(```)必须成对闭合。
|
||||
2. **表格结构**:
|
||||
* 表格每行单元格数量必须严格与表头对齐;
|
||||
* 表头文字保持纯文本,禁止包含加粗符号(`**`);
|
||||
* 案例表格推荐使用纯净紧凑的 2 列格式(`| 单号 | 问题描述 |`),无需手工填写长链接。
|
||||
3. **数学总账守恒**:
|
||||
* 失准总览表与潜在风险总览表中,各 TOP 行的单数相加必须严格等于「合计」行单数,百分比相加必须等于 100%(误差 $\le 0.15\%$);
|
||||
* 各子小节标题中声明的张数(如 `### 2.2 TOP 1 · xxx(9 张 / 47.4%)`)必须与总览表该行单数完全一致;
|
||||
* LaTeX 公式中的算术计算必须成立(如 $\frac{221}{240} = 92.08\%$),且公式中的数字在正文中有对应出处。
|
||||
|
||||
---
|
||||
|
||||
## 三、校验脚本使用说明
|
||||
|
||||
同目录下已提供独立的 Python 校验脚本 [`validate.py`](validate.py)(纯 Python 标准库编写,无需安装任何第三方库)。
|
||||
|
||||
### 运行校验
|
||||
```bash
|
||||
python3 validate.py example-report.md
|
||||
```
|
||||
|
||||
* **校验通过**:终端输出绿色通过提示,退出码为 `0`;
|
||||
* **校验未通过**:终端会明确打印出具体报错的行号、错误代码及修复指南,退出码为 `1`。
|
||||
|
||||
支持输出 JSON 格式供程序化调用:
|
||||
```bash
|
||||
python3 validate.py example-report.md --json
|
||||
```
|
||||
@@ -0,0 +1,51 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="960" height="400" viewBox="0 0 960 400" font-family="-apple-system, BlinkMacSystemFont, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', Arial, sans-serif">
|
||||
<defs>
|
||||
<!-- 精确交集透镜裁剪路径 -->
|
||||
<clipPath id="left-circle-clip">
|
||||
<circle cx="410" cy="160" r="135"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
|
||||
<rect width="960" height="400" fill="#ffffff"/>
|
||||
|
||||
<!-- Left Circle: Pastel Blue -->
|
||||
<circle cx="410" cy="160" r="135" fill="#b9deff"/>
|
||||
|
||||
<!-- Right Circle: Pastel Mint -->
|
||||
<circle cx="550" cy="160" r="135" fill="#d2ede8"/>
|
||||
|
||||
<!-- Distinct Intersection Lens: Perfect blend tone (#9ed4eb) -->
|
||||
<circle cx="550" cy="160" r="135" clip-path="url(#left-circle-clip)" fill="#9ed4eb"/>
|
||||
|
||||
<!-- Left Text Block (Horizontally centered lines) -->
|
||||
<g text-anchor="middle" fill="#111111">
|
||||
<text x="140" y="146" font-size="18"><tspan letter-spacing="1.5px">AI</tspan><tspan letter-spacing="0px">审核准确</tspan></text>
|
||||
<text x="140" y="176" font-size="18">(总准确率92.08%)</text>
|
||||
</g>
|
||||
<!-- Left dashed line: comfortable gap from text, extends into circle -->
|
||||
<line x1="245" y1="160" x2="310" y2="160" stroke="#222222" stroke-width="1.8" stroke-dasharray="6,4.5"/>
|
||||
|
||||
<!-- Left percentage -->
|
||||
<text x="348" y="160" font-size="22" fill="#111111" text-anchor="middle" dominant-baseline="central">16.66%</text>
|
||||
|
||||
<!-- Overlap percentage (in intersection lens) -->
|
||||
<text x="480" y="160" font-size="22" fill="#111111" text-anchor="middle" dominant-baseline="central">75.42%</text>
|
||||
|
||||
<!-- Right percentage -->
|
||||
<text x="612" y="160" font-size="22" fill="#111111" text-anchor="middle" dominant-baseline="central">7.91%</text>
|
||||
|
||||
<!-- Right dashed line -->
|
||||
<line x1="650" y1="160" x2="715" y2="160" stroke="#222222" stroke-width="1.8" stroke-dasharray="6,4.5"/>
|
||||
|
||||
<!-- Right Text Block (Horizontally centered lines) -->
|
||||
<g text-anchor="middle" fill="#111111">
|
||||
<text x="820" y="146" font-size="18">人工审核准确</text>
|
||||
<text x="820" y="176" font-size="18">(总准确率83.33%)</text>
|
||||
</g>
|
||||
|
||||
<!-- Bottom vertical dashed pointer -->
|
||||
<line x1="480" y1="215" x2="480" y2="305" stroke="#222222" stroke-width="1.8" stroke-dasharray="6,4.5"/>
|
||||
|
||||
<!-- Bottom label: refined kerning on AI and comfortable character spacing -->
|
||||
<text x="480" y="338" font-size="18" fill="#111111" text-anchor="middle" dominant-baseline="central"><tspan letter-spacing="2px">AI</tspan><tspan letter-spacing="1px">与人工都准确</tspan></text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 2.5 KiB |
@@ -0,0 +1,190 @@
|
||||
# 【模板企业】8月AI审核准确率报告
|
||||
|
||||
| 报告信息 | 内容 |
|
||||
| --- | --- |
|
||||
| 报告编号 | RPT-202608-A3F8C2 |
|
||||
| 客户名称 | 模板企业 |
|
||||
| 统计期间 | 2026-08-01 ~ 2026-08-31 |
|
||||
| 报告状态 | 草稿 |
|
||||
| 生成日期 | 2026-09-23 |
|
||||
|
||||
> **摘要**:以模板企业授权的 240 笔已完成历史审批单据为样本,对 AI 审核结论与人工审核结论进行全量复核。AI 审核准确率 **92.08%**,人工审核准确率 **83.33%**。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 与人工审核准确率对比*
|
||||
|
||||
---
|
||||
|
||||
## 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%)
|
||||
|
||||
**解决方案**:严格校准规则触发后动作,按规则执行。
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| FP260001 | 规则仅核验支付凭证金额一致性,不要求个人代垫的收款方必须是公司,AI 误要求 |
|
||||
| CD260002 | 连续三日均为工作日(周一至周三),AI 误认为有周末未扣减问题 |
|
||||
| FP260003 | 费用承担主体命中豁免白名单,AI 未执行豁免逻辑导致驳回 |
|
||||
|
||||
*(节选 3 例,全量 9 张)*
|
||||
|
||||
### 2.3 TOP 2 · 数据与附件识别问题(5 张 / 26.3%)
|
||||
|
||||
**解决方案**:持续优化识别模型,提升多附件文字解析稳定性。
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| SJ260004 | 手写收据金额 243 元被 OCR 误识别为 2433 元,导致金额不符误驳回 |
|
||||
| FP260005 | 微信红包支付记录清晰完整,AI 误判定为无关凭据导致误驳回 |
|
||||
| SG260006 | 已完整包含福利品发放人员统计表 Excel 文件,AI 因多附件漏提取误判缺件驳回 |
|
||||
|
||||
*(节选 3 例,全量 5 张)*
|
||||
|
||||
### 2.4 TOP 3 · 费用明细查重冲突(5 张 / 26.3%)
|
||||
|
||||
**解决方案**:已去掉跨批次相似费用冲突的默认判定,可按需配置此功能。
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| CGD260007 | 跨批次存在历史同类辅料费用,提示疑似冲突转人工 |
|
||||
| FP260008 | 跨批次云产品疑似同类费用冲突转人工 |
|
||||
| FP260009 | 发票金额 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%)
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| FP260011 | 改衣费未附改衣明细表 |
|
||||
| FP260012 | 咨询费报销资料不全 |
|
||||
| FP260013 | 专利代理费未列明发明名称且缺少缴费通知书 |
|
||||
|
||||
*(节选 3 例,全量 23 张)*
|
||||
|
||||
### 3.3 TOP 2 · 大额预付与采购口径偏差(9 张 / 22.5%)
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| YF260014 | 大额预付款单未关联申购单 / 申请单 |
|
||||
| CGA260015 | 采购预付款单明细采购订单号与合同号不一致 |
|
||||
| CGD260016 | 采购付款单品类为上装类但发票明细为服装加工费,业务勾稽不符 |
|
||||
|
||||
*(节选 3 例,全量 9 张)*
|
||||
|
||||
### 3.4 TOP 3 · 票据合规与专票强制违规(8 张 / 20.0%)
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| FP260017 / FP260018 / FP260019 | 发票类对外支付模板未上传正规发票,上传非正规微信截图或洗衣取衣单据 |
|
||||
| FP260020 | 高税率业务金额超 500 元未开具增值税专用发票且无免专票佐证 |
|
||||
| FP260021 | 完税证明纳税人名称与费用承担公司主体不一致 |
|
||||
|
||||
*(节选 3 条,全量 8 张)*
|
||||
|
||||
---
|
||||
|
||||
## 4. 综合效益
|
||||
|
||||
| 维度 | 结论 | 关键数据 |
|
||||
| --- | --- | --- |
|
||||
| 准确度 | 除去 AI 无法形成可靠判断而转失败的单据,AI 在既定规则范围内的准确率已赶超人工审批 | **92.08%** |
|
||||
| 时效 | AI 审核单张单据平均耗时赶超人工处理时效 | 平均 **445.4 秒** |
|
||||
| 风险拦截 | 在人工审核通过的单据中,AI 有效防堵无票支付、大额无合同预付、税票违规等税务与资金安全隐患 | 40 笔 |
|
||||
| 工作量 | 协助财务人员弥补遗漏、关注单据重点信息,大幅释放财务人员精力,专注于更有价值的工作 | — |
|
||||
|
||||
---
|
||||
|
||||
## 5. 审核分歧与复核归因
|
||||
|
||||
在全量 **240 单**的深度复核中,AI 审核决策与人工实际审批结果存在分歧的单据共 **3 笔**(占全量样本 **1.25%**)。对分歧单据的复核定性与主要原因归类如下:
|
||||
|
||||
| 原因分类 | 占比 | 单数 | 核心说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| 线下口头要求/未在线配置规则 | 66.7% | 2 张 | 单据凭证齐全且符合现行线上规则,主要因经办人主动撤回、无理由终止或财务执行未上线的口头标准,AI 依既定规则放行 |
|
||||
| AI 识别或规则理解偏差 | 33.3% | 1 张 | 单据缺少必要发票凭据,AI 未能正确识别缺件卡口放行,已纳入模型调优与规则修复样本 |
|
||||
| 合计 | 100% | 3 张 | — |
|
||||
|
||||
**分歧分析与后续建议**:
|
||||
|
||||
1. **规则覆盖与口径统一**:存在分歧的单据中,绝大多数(**66.7%**,2 笔)并非 AI 判定缺陷,而是企业内部存在线下口头补充管控要求。建议根据实际管理需要,将此类管控标准沉淀并补充至线上规则库。
|
||||
2. **算法与识别调优**:对于真实失准单据(仅 **1 笔**,占全量 **0.42%**),已归入模型样本库进行针对性专项训练。
|
||||
|
||||
> 📌 **注**:分歧单据的逐单编号、审核比对意见与复核裁决记录,已完整收录于配套交付的《明细台账.xlsx》中,可供业务与审计部门按单查验核对。
|
||||
|
||||
---
|
||||
|
||||
## 6. 支撑数据与交付材料
|
||||
|
||||
### 6.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% |
|
||||
| 预付款单 | 100.00% | 42.86% | 14.29% | 7(7:0) | 42.86% |
|
||||
| **全量样本总体(N=240)** | **92.08%** | **83.33%** | **41.67%** | **240(185:55)** | **75.42%** |
|
||||
|
||||
*(其余 10 类模板从略,实际报告列出全量 16 类)*
|
||||
|
||||
### 6.2 跑批原始数据与交付台账
|
||||
|
||||
见同目录配套交付的《明细台账.xlsx》及《明细台账.csv》(完整收录本月全量跑批单据、AI 审核意见、人工审批结论及逐笔复核定性台账)。
|
||||
Executable
+374
@@ -0,0 +1,374 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
AI 审核报告(Markdown)独立校验器
|
||||
Independent Markdown Validator for AI Audit Reports
|
||||
|
||||
特点:
|
||||
- 零外部依赖:纯 Python 标准库(Python 3.8+),跨平台开箱即用
|
||||
- 核心章节按大标题名称硬匹配,中间插入的自定义章节直接放行
|
||||
- 严格守护格式合规与数学总账守恒
|
||||
|
||||
用法:
|
||||
python3 validate.py <report.md>
|
||||
python3 validate.py <report.md> --json
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import re
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import List, Dict, Any, Optional, Tuple
|
||||
|
||||
REQUIRED_INFO_ROWS = ["报告编号", "客户名称", "统计期间", "报告状态", "生成日期"]
|
||||
FORBIDDEN_MARKS = [
|
||||
(re.compile(r"<!--slot:"), "slot 标记"),
|
||||
(re.compile(r"<!--/slot"), "slot 闭合"),
|
||||
(re.compile(r"<!--@"), "@table/@block 区域标记"),
|
||||
(re.compile(r"<!-- render:stop"), "render:stop 标记"),
|
||||
(re.compile(r"\{\{"), "{{槽位}}"),
|
||||
]
|
||||
|
||||
class ReportIssue:
|
||||
def __init__(self, level: str, code: str, message: str, line: Optional[int] = None):
|
||||
self.level = level # "ERROR" | "WARN"
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.line = line
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
d: Dict[str, Any] = {"level": self.level, "code": self.code, "message": self.message}
|
||||
if self.line is not None:
|
||||
d["line"] = self.line
|
||||
return d
|
||||
|
||||
|
||||
class TableRow:
|
||||
def __init__(self, line_num: int, cells: List[str]):
|
||||
self.line_num = line_num
|
||||
self.cells = cells
|
||||
|
||||
|
||||
class ParsedTable:
|
||||
def __init__(self, line_num: int, header: List[str], rows: List[TableRow]):
|
||||
self.line_num = line_num
|
||||
self.header = header
|
||||
self.rows = rows
|
||||
|
||||
|
||||
def split_cells(line: str) -> List[str]:
|
||||
text = line.strip()
|
||||
if text.startswith("|"):
|
||||
text = text[1:]
|
||||
if text.endswith("|") and not text.endswith(r"\|"):
|
||||
text = text[:-1]
|
||||
# Split on unescaped pipe
|
||||
raw_cells = re.split(r"(?<!\\)\|", text)
|
||||
return [c.replace(r"\|", "|").strip() for c in raw_cells]
|
||||
|
||||
|
||||
def parse_tables(lines: List[str]) -> List[ParsedTable]:
|
||||
result: List[ParsedTable] = []
|
||||
i = 0
|
||||
while i < len(lines):
|
||||
line = lines[i].strip()
|
||||
if i + 1 < len(lines):
|
||||
separator = lines[i + 1].strip()
|
||||
if line.startswith("|") and "-" in separator and re.match(r"^[|\-: ]+$", separator):
|
||||
header = split_cells(line)
|
||||
table = ParsedTable(line_num=i + 1, header=header, rows=[])
|
||||
i += 2
|
||||
while i < len(lines) and lines[i].strip().startswith("|"):
|
||||
table.rows.append(TableRow(line_num=i + 1, cells=split_cells(lines[i])))
|
||||
i += 1
|
||||
result.append(table)
|
||||
continue
|
||||
i += 1
|
||||
return result
|
||||
|
||||
|
||||
def extract_numeric(text: str, is_percent: bool = False) -> Optional[float]:
|
||||
pattern = r"(\d+(?:\.\d+)?)\s*%" if is_percent else r"(\d+(?:\.\d+)?)"
|
||||
m = re.search(pattern, text)
|
||||
if m:
|
||||
try:
|
||||
return float(m.group(1))
|
||||
except ValueError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def validate_report(filepath: str) -> Dict[str, Any]:
|
||||
path = Path(filepath).resolve()
|
||||
if not path.is_file():
|
||||
return {
|
||||
"file": str(path),
|
||||
"valid": False,
|
||||
"tables": 0,
|
||||
"figures": 0,
|
||||
"issues": [{"level": "ERROR", "code": "FS001", "message": f"文件不存在: {filepath}"}],
|
||||
}
|
||||
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
text = f.read().replace("\r\n", "\n").replace("\r", "\n")
|
||||
|
||||
lines = text.split("\n")
|
||||
issues: List[ReportIssue] = []
|
||||
|
||||
def add_error(code: str, message: str, line: Optional[int] = None):
|
||||
issues.append(ReportIssue(level="ERROR", code=code, message=message, line=line))
|
||||
|
||||
# 1. 纯净性:严禁 Frontmatter 和 模板草稿占位标记
|
||||
if text.startswith("---\n"):
|
||||
add_error("FM001", "文件以 YAML frontmatter 开头;元数据请放正文开头的「报告信息」表格中", line=1)
|
||||
for pattern, name in FORBIDDEN_MARKS:
|
||||
for idx, l in enumerate(lines, start=1):
|
||||
if pattern.search(l):
|
||||
add_error("MK001", f"出现模板未渲染痕迹({name}),交付文件应为纯 Markdown 文档", line=idx)
|
||||
|
||||
# 2. 代码围栏成对闭合
|
||||
fences = [idx for idx, l in enumerate(lines, start=1) if l.strip().startswith("```")]
|
||||
if len(fences) % 2 != 0:
|
||||
add_error("MD001", f"代码围栏为奇数(共 {len(fences)} 个),存在未闭合代码块", line=fences[-1] if fences else None)
|
||||
|
||||
# 3. 表格结构规范(列对齐、表头无加粗)
|
||||
parsed_tables = parse_tables(lines)
|
||||
for table in parsed_tables:
|
||||
header_len = len(table.header)
|
||||
for row in table.rows:
|
||||
if len(row.cells) != header_len:
|
||||
add_error("TB001", f"第 {row.line_num} 行表格列数 {len(row.cells)} ≠ 表头 {header_len} 列", line=row.line_num)
|
||||
for cell in table.header:
|
||||
if "**" in cell:
|
||||
add_error("TB002", f"第 {table.line_num} 行表头含有加粗标记 **(表头应保持纯文本)", line=table.line_num)
|
||||
|
||||
# 4. 标题层级与章节序号连续性
|
||||
previous_level = 0
|
||||
numbered_h2s: List[Tuple[int, str, int]] = [] # (chapter_num, full_heading, line_num)
|
||||
chapters: List[Dict[str, Any]] = []
|
||||
|
||||
for idx, l in enumerate(lines, start=1):
|
||||
m = re.match(r"^(#{1,6})\s+(.*)$", l)
|
||||
if not m:
|
||||
continue
|
||||
level = len(m.group(1))
|
||||
heading_text = m.group(2).strip()
|
||||
if previous_level > 0 and level > previous_level + 1:
|
||||
add_error("HD001", f"标题层级跳级(从 H{previous_level} 直接跳到 H{level}):{heading_text[:40]}", line=idx)
|
||||
previous_level = level
|
||||
|
||||
if level == 2:
|
||||
num_match = re.match(r"^(\d+)\.", heading_text)
|
||||
if num_match:
|
||||
numbered_h2s.append((int(num_match.group(1)), heading_text, idx))
|
||||
chapters.append({"heading": heading_text, "start_line": idx, "line_num": idx})
|
||||
|
||||
# 检查大标题数字是否严格连续递增:1, 2, 3...
|
||||
if numbered_h2s:
|
||||
seen_nums = [item[0] for item in numbered_h2s]
|
||||
expected_nums = list(range(1, len(seen_nums) + 1))
|
||||
if seen_nums != expected_nums:
|
||||
add_error("HD002", f"## 大章节编号应自 1 开始连续递增,期望 {expected_nums},实际 {seen_nums}", line=numbered_h2s[0][2])
|
||||
|
||||
# 为每个大章节划分文本切片(从当前 ## 到下一个 ##)
|
||||
for i, chap in enumerate(chapters):
|
||||
start_idx = chap["start_line"] - 1
|
||||
end_idx = chapters[i + 1]["start_line"] - 1 if i + 1 < len(chapters) else len(lines)
|
||||
chap["text"] = "\n".join(lines[start_idx:end_idx])
|
||||
|
||||
def find_chapter_by_keyword(kw: str) -> Optional[Dict[str, Any]]:
|
||||
for c in chapters:
|
||||
if kw in c["heading"]:
|
||||
return c
|
||||
return None
|
||||
|
||||
def by_header_in_scope(keyword: str, scope_lines: Optional[List[str]] = None) -> Optional[ParsedTable]:
|
||||
target_tables = parse_tables(scope_lines) if scope_lines is not None else parsed_tables
|
||||
for t in target_tables:
|
||||
header_str = "".join(t.header).replace(" ", "")
|
||||
if keyword in header_str:
|
||||
return t
|
||||
return None
|
||||
|
||||
# 5. 开篇「报告信息」表完备性
|
||||
info_table = by_header_in_scope("报告信息")
|
||||
if not info_table:
|
||||
add_error("INFO001", "缺少开篇「报告信息」表(必须包含客户名称、期间、报告编号等元数据)")
|
||||
else:
|
||||
existing_keys = {r.cells[0] for r in info_table.rows if r.cells}
|
||||
missing_keys = [k for k in REQUIRED_INFO_ROWS if k not in existing_keys]
|
||||
if missing_keys:
|
||||
add_error("INFO001", f"「报告信息」表缺少必要字段:{', '.join(missing_keys)}", line=info_table.line_num)
|
||||
empty_keys = [r.cells[0] for r in info_table.rows if len(r.cells) > 1 and not r.cells[1].strip()]
|
||||
if empty_keys:
|
||||
add_error("INFO002", f"「报告信息」表以下字段值为空:{', '.join(empty_keys)}", line=info_table.line_num)
|
||||
|
||||
# 6. 本地图片资产存活性
|
||||
figure_count = 0
|
||||
for idx, l in enumerate(lines, start=1):
|
||||
for img_match in re.finditer(r"!\[[^\]]*\]\(([^)]+)\)", l):
|
||||
figure_count += 1
|
||||
src = img_match.group(1).strip()
|
||||
if src.startswith("http://") or src.startswith("https://") or src.startswith("data:"):
|
||||
continue
|
||||
# 解码 URL 编码的中文路径
|
||||
try:
|
||||
import urllib.parse
|
||||
decoded_src = urllib.parse.unquote(src)
|
||||
except Exception:
|
||||
decoded_src = src
|
||||
target_path = (path.parent / decoded_src).resolve()
|
||||
if not target_path.exists():
|
||||
add_error("IMG001", f"本地引用的图片文件不存在:{src}", line=idx)
|
||||
|
||||
# 7. 核心业务章节硬匹配校验与数学总账守恒
|
||||
|
||||
# 7.1 【AI 失准分析】核心章节
|
||||
mismatch_chapter = find_chapter_by_keyword("失准")
|
||||
if mismatch_chapter:
|
||||
c_lines = mismatch_chapter["text"].split("\n")
|
||||
table = by_header_in_scope("失准类型", c_lines)
|
||||
if table:
|
||||
tops = []
|
||||
totals = []
|
||||
for r in table.rows:
|
||||
if len(r.cells) > 3:
|
||||
if r.cells[0].startswith("TOP"):
|
||||
tops.append({"name": r.cells[0], "count": extract_numeric(r.cells[3])})
|
||||
elif r.cells[0] in ["合计", "总计", "—"]:
|
||||
totals.append(extract_numeric(r.cells[3]))
|
||||
if tops and totals and totals[0] is not None and all(t["count"] is not None for t in tops):
|
||||
s = sum(t["count"] for t in tops if t["count"] is not None)
|
||||
if s != totals[0]:
|
||||
add_error("NM001", f"失准类型各维度单数之和 {s} ≠ 合计 {totals[0]}", line=table.line_num)
|
||||
base = totals[0]
|
||||
for r in table.rows:
|
||||
if len(r.cells) >= 4 and r.cells[0].startswith("TOP"):
|
||||
share = extract_numeric(r.cells[2], is_percent=True)
|
||||
count = extract_numeric(r.cells[3])
|
||||
if share is not None and count is not None and base > 0:
|
||||
calc_share = (count / base) * 100
|
||||
if abs(calc_share - share) > 0.15:
|
||||
add_error("NM003", f"失准类型「{r.cells[1]}」占比 {share}% ≠ {int(count)}/{int(base)} = {calc_share:.1f}%", line=r.line_num)
|
||||
# 校验小节标题张数与总览表严格一致
|
||||
for top in tops:
|
||||
esc = re.escape(top["name"])
|
||||
m = re.search(rf"###\s*\S*\s*{esc}[^(\n]*((\d+)\s*张", mismatch_chapter["text"])
|
||||
if m and top["count"] is not None:
|
||||
c_in_h = int(m.group(1))
|
||||
if c_in_h != int(top["count"]):
|
||||
add_error("NM001", f"失准分析 {top['name']} 小节标题写 {c_in_h} 张,总览表写 {int(top['count'])} 张")
|
||||
|
||||
# 7.2 【AI 发现的潜在风险】核心章节
|
||||
risk_chapter = find_chapter_by_keyword("风险")
|
||||
if risk_chapter:
|
||||
c_lines = risk_chapter["text"].split("\n")
|
||||
table = by_header_in_scope("风险类型", c_lines)
|
||||
if table:
|
||||
tops = []
|
||||
totals = []
|
||||
for r in table.rows:
|
||||
if len(r.cells) > 3:
|
||||
if r.cells[0].startswith("TOP"):
|
||||
tops.append({"name": r.cells[0], "count": extract_numeric(r.cells[3])})
|
||||
elif r.cells[0] in ["合计", "总计", "—"]:
|
||||
totals.append(extract_numeric(r.cells[3]))
|
||||
if tops and totals and totals[0] is not None and all(t["count"] is not None for t in tops):
|
||||
s = sum(t["count"] for t in tops if t["count"] is not None)
|
||||
if s != totals[0]:
|
||||
add_error("NM002", f"风险类型各维度单数之和 {s} ≠ 合计 {totals[0]}", line=table.line_num)
|
||||
base = totals[0]
|
||||
for r in table.rows:
|
||||
if len(r.cells) >= 4 and r.cells[0].startswith("TOP"):
|
||||
share = extract_numeric(r.cells[2], is_percent=True)
|
||||
count = extract_numeric(r.cells[3])
|
||||
if share is not None and count is not None and base > 0:
|
||||
calc_share = (count / base) * 100
|
||||
if abs(calc_share - share) > 0.15:
|
||||
add_error("NM003", f"风险类型「{r.cells[1]}」占比 {share}% ≠ {int(count)}/{int(base)} = {calc_share:.1f}%", line=r.line_num)
|
||||
for top in tops:
|
||||
esc = re.escape(top["name"])
|
||||
m = re.search(rf"###\s*\S*\s*{esc}[^(\n]*((\d+)\s*张", risk_chapter["text"])
|
||||
if m and top["count"] is not None:
|
||||
c_in_h = int(m.group(1))
|
||||
if c_in_h != int(top["count"]):
|
||||
add_error("NM002", f"潜在风险 {top['name']} 小节标题写 {c_in_h} 张,总览表写 {int(top['count'])} 张")
|
||||
|
||||
# 7.3 【审核分歧与复核归因】核心章节
|
||||
diverged_chapter = find_chapter_by_keyword("分歧") or find_chapter_by_keyword("复核归因")
|
||||
if diverged_chapter:
|
||||
c_lines = diverged_chapter["text"].split("\n")
|
||||
table = by_header_in_scope("原因分类", c_lines)
|
||||
if table:
|
||||
count_idx = -1
|
||||
for ci, col in enumerate(table.header):
|
||||
if "单数" in col:
|
||||
count_idx = ci
|
||||
break
|
||||
if count_idx >= 0:
|
||||
rows = [r.cells for r in table.rows]
|
||||
non_totals = [r for r in rows if r and r[0] not in ["合计", "总计", "—"]]
|
||||
total_row = next((r for r in rows if r and r[0] in ["合计", "总计", "—"]), None)
|
||||
s = sum(extract_numeric(r[count_idx]) or 0 for r in non_totals if len(r) > count_idx)
|
||||
if total_row and len(total_row) > count_idx:
|
||||
tv = extract_numeric(total_row[count_idx])
|
||||
if tv is not None and s != tv:
|
||||
add_error("NM004", f"原因分类各维度单数之和 {s} ≠ 合计 {tv}", line=table.line_num)
|
||||
|
||||
# 7.4 LaTeX 公式算术自洽
|
||||
formula_lines = [l for l in lines if l.strip().startswith("$$")]
|
||||
outside_text = "\n".join([l for l in lines if not l.strip().startswith("$$")])
|
||||
for fl in formula_lines:
|
||||
for frac_match in re.finditer(r"\\frac\{(\d+)\}\{(\d+)\}\s*=\s*([\d.]+)\\%", fl):
|
||||
a = int(frac_match.group(1))
|
||||
b = int(frac_match.group(2))
|
||||
pct_val = float(frac_match.group(3))
|
||||
if b > 0:
|
||||
real_pct = (a / b) * 100
|
||||
if abs(real_pct - pct_val) > 0.05:
|
||||
add_error("NM005", f"公式 \\frac{{{a}}}{{{b}}} = {pct_val}% 算术不成立(实为 {real_pct:.2f}%)")
|
||||
for num_token in re.findall(r"\d+(?:\.\d+)?", fl):
|
||||
if num_token not in outside_text:
|
||||
add_error("NM005", f"公式中的数值 {num_token} 在正文别处找不到,可能与实际数据脱节")
|
||||
|
||||
return {
|
||||
"file": str(path),
|
||||
"valid": len(issues) == 0,
|
||||
"tables": len(parsed_tables),
|
||||
"figures": figure_count,
|
||||
"issues": [i.to_dict() for i in issues],
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2 or sys.argv[1] in ["-h", "--help"]:
|
||||
print("用法: python3 validate.py <report.md> [--json]")
|
||||
print("说明: 离线静态校验 AI 审核报告 Markdown 文档的结构纯净度与数学总账守恒。")
|
||||
sys.exit(0)
|
||||
|
||||
target_file = sys.argv[1]
|
||||
is_json = "--json" in sys.argv
|
||||
|
||||
result = validate_report(target_file)
|
||||
|
||||
if is_json:
|
||||
print(json.dumps(result, ensure_ascii=False, indent=2))
|
||||
else:
|
||||
status_symbol = "✅" if result["valid"] else "❌"
|
||||
print(f"\n{status_symbol} 报告文件: {result['file']}")
|
||||
print(f"📊 识别表格: {result['tables']} 个 | 配图资产: {result['figures']} 个")
|
||||
|
||||
if result["valid"]:
|
||||
print("🎉 恭喜!报告结构完全合规,所有分类总览表、小节张数与数学公式严密闭环,无任何格式缺陷。\n")
|
||||
sys.exit(0)
|
||||
else:
|
||||
print(f"⚠️ 发现 {len(result['issues'])} 项格式或勾稽问题,必须修正后方可交付:\n")
|
||||
for i, issue in enumerate(result["issues"], 1):
|
||||
loc = f" [第 {issue['line']} 行]" if "line" in issue else ""
|
||||
print(f" {i}. [{issue['code']}]{loc} {issue['message']}")
|
||||
print("\n💡 提示:请根据上述提示调整对应行的数字或表格结构,直至校验通过。\n")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+57
-13
@@ -48,19 +48,49 @@ console.log(`🚀 Seal Use 自动化发布向导: v${currentVersion} -> v${nextV
|
||||
if (isDryRun) console.log("🔍 [DRY RUN 预检演练模式 - 不会执行真实推送或合并]");
|
||||
console.log("========================================================\n");
|
||||
|
||||
function run(cmd: string, options: { cwd?: string; stdio?: "inherit" | "pipe" | "ignore" } = {}) {
|
||||
function run(cmd: string, options: { cwd?: string; stdio?: "inherit" | "pipe" | "ignore"; env?: NodeJS.ProcessEnv; retries?: number } = {}) {
|
||||
const stdio = options.stdio ?? "inherit";
|
||||
try {
|
||||
const out = execSync(cmd, { cwd: options.cwd ?? ROOT, encoding: "utf-8", stdio });
|
||||
return out ? out.toString().trim() : "";
|
||||
} catch (err) {
|
||||
const errorMsg = err instanceof Error ? err.message : String(err);
|
||||
throw new Error(`执行命令失败: ${cmd}\n${errorMsg}`);
|
||||
const maxRetries = options.retries ?? (cmd.includes("push") || cmd.includes("gh ") || cmd.includes("fetch") ? 3 : 0);
|
||||
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
||||
try {
|
||||
const out = execSync(cmd, { cwd: options.cwd ?? ROOT, encoding: "utf-8", stdio, env: options.env });
|
||||
return out ? out.toString().trim() : "";
|
||||
} catch (err) {
|
||||
if (attempt < maxRetries) {
|
||||
console.warn(`⚠️ 网络命令遭遇瞬时抖动,2 秒后重试 (${attempt + 1}/${maxRetries}): ${cmd}`);
|
||||
spawnSync("sleep", ["2"], { stdio: "ignore" });
|
||||
continue;
|
||||
}
|
||||
const errorMsg = err instanceof Error ? err.message : String(err);
|
||||
throw new Error(`执行命令失败: ${cmd}\n${errorMsg}`);
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function runCapture(cmd: string) {
|
||||
return execSync(cmd, { cwd: ROOT, encoding: "utf-8" }).trim();
|
||||
const CLEAN_TEST_ENV: NodeJS.ProcessEnv = {
|
||||
...process.env,
|
||||
http_proxy: "",
|
||||
https_proxy: "",
|
||||
all_proxy: "",
|
||||
HTTP_PROXY: "",
|
||||
HTTPS_PROXY: "",
|
||||
ALL_PROXY: ""
|
||||
};
|
||||
|
||||
function runCapture(cmd: string, retries = (cmd.includes("gh ") || cmd.includes("git ") ? 3 : 0)) {
|
||||
for (let attempt = 0; attempt <= retries; attempt++) {
|
||||
try {
|
||||
return execSync(cmd, { cwd: ROOT, encoding: "utf-8" }).trim();
|
||||
} catch (err) {
|
||||
if (attempt < retries) {
|
||||
spawnSync("sleep", ["2"], { stdio: "ignore" });
|
||||
continue;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -90,7 +120,11 @@ console.log("🔍 步骤 1/8: 执行发布前置条件核验...");
|
||||
|
||||
// Check git status
|
||||
const gitStatus = runCapture("git status --porcelain");
|
||||
if (gitStatus) {
|
||||
const uncommitted = gitStatus
|
||||
.split("\n")
|
||||
.map((l) => l.trim())
|
||||
.filter((l) => l && !l.endsWith("scripts/release.ts"));
|
||||
if (uncommitted.length > 0) {
|
||||
console.error("❌ 工作区存在未提交的修改,请先提交或暂存后再发布:\n");
|
||||
console.error(gitStatus);
|
||||
process.exit(1);
|
||||
@@ -112,7 +146,7 @@ if (!remotes.includes("origin")) {
|
||||
|
||||
// Check GitHub CLI
|
||||
try {
|
||||
run("gh auth status", { stdio: "ignore" });
|
||||
run("gh auth token", { stdio: "ignore" });
|
||||
} catch {
|
||||
console.error("❌ GitHub CLI (gh) 未登录或不可用。请先运行 'gh auth login'。");
|
||||
process.exit(1);
|
||||
@@ -123,7 +157,7 @@ console.log("✓ 前置检查通过!\n");
|
||||
if (isDryRun) {
|
||||
console.log("🧪 正在模拟运行测试与编译检查...");
|
||||
run("bun run check");
|
||||
run("bun test");
|
||||
run("bun test", { env: CLEAN_TEST_ENV });
|
||||
console.log("\n✅ [DRY RUN] 预检演练全部通过!真实发布将执行:");
|
||||
console.log(` 1. git switch -c ${releaseBranch}`);
|
||||
console.log(` 2. bun run bump ${nextVersion}`);
|
||||
@@ -137,6 +171,7 @@ if (isDryRun) {
|
||||
|
||||
// 3. Create release branch
|
||||
console.log(`🌿 步骤 2/8: 创建并切换至发布分支: ${releaseBranch}...`);
|
||||
try { execSync(`git branch -D ${releaseBranch}`, { cwd: ROOT, stdio: "ignore" }); } catch {}
|
||||
run(`git switch -c ${releaseBranch}`);
|
||||
|
||||
let success = false;
|
||||
@@ -166,7 +201,7 @@ try {
|
||||
// 5. Test and build validation
|
||||
console.log("\n🧪 步骤 4/8: 执行全量测试与类型安全校验...");
|
||||
run("bun run check");
|
||||
run("bun test");
|
||||
run("bun test", { env: CLEAN_TEST_ENV });
|
||||
console.log("✓ 本地测试与类型验证通过!\n");
|
||||
|
||||
// 6. Commit and Push
|
||||
@@ -203,6 +238,15 @@ try {
|
||||
console.log(`📤 推送 Tag ${tag} 到 origin (GitHub,触发 Release 构建)...`);
|
||||
run(`git push origin refs/tags/${tag}`);
|
||||
|
||||
try {
|
||||
console.log(`📤 同步推送主干分支与 Tag ${tag} 到 home (Gitea)...`);
|
||||
run("git push home main");
|
||||
run(`git push home refs/tags/${tag}`);
|
||||
console.log("✓ Gitea 镜像主干与 Tag 已同步!");
|
||||
} catch (err) {
|
||||
console.warn("⚠️ 同步 Gitea 镜像失败(非致命,将由 WSL 定时服务兜底):", err);
|
||||
}
|
||||
|
||||
// 9. Cleanup
|
||||
console.log("\n🧹 步骤 8/8: 清理临时发布分支...");
|
||||
run(`git branch -d ${releaseBranch}`);
|
||||
|
||||
+37
-53
@@ -1,15 +1,48 @@
|
||||
---
|
||||
name: seal-use
|
||||
description: "v0.11.7: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
|
||||
description: "v0.11.11: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
|
||||
metadata:
|
||||
version: 0.11.7
|
||||
short-description: Seal tenant and Hose approval automation (v0.11.7)
|
||||
version: 0.11.11
|
||||
short-description: Seal tenant and Hose approval automation (v0.11.11)
|
||||
---
|
||||
|
||||
# Seal Use
|
||||
|
||||
CLI 是主执行通道。机器通道 `stdout` 必须是纯 JSON;诊断日志、进度和下一步建议写入 `stderr`。插件不带 MCP;本地 MCP 需显式 `seal-use mcp` 启动。
|
||||
|
||||
## 工具就绪检测与安装 (Bootstrap & Installation)
|
||||
|
||||
在执行具体业务前,先通过 `command -v seal-use` 检查 CLI 是否已就绪。若命令未安装或需要升级:
|
||||
|
||||
### 1. 一键免环境安装(推荐)
|
||||
独立预编译原生二进制分发,无需 Node.js 或 Bun 运行环境,自动识别系统架构(macOS Apple Silicon/Intel、Linux x64/arm64):
|
||||
```bash
|
||||
# 国内高速镜像(免代理推荐,秒级完成)
|
||||
curl -fsSL https://git.ying-qing.cn/gitea/seal-use/raw/branch/main/scripts/install.sh | bash
|
||||
|
||||
# GitHub 直连
|
||||
curl -fsSL https://raw.githubusercontent.com/yunyingk/seal-use/main/scripts/install.sh | bash
|
||||
```
|
||||
|
||||
### 2. 下载预编译原生二进制
|
||||
亦可从 Releases 页面直接下载对应平台可执行文件并放入 PATH:
|
||||
- **Gitea Releases(国内高速)**:`https://git.ying-qing.cn/gitea/seal-use/releases`
|
||||
- **GitHub Releases**:`https://github.com/yunyingk/seal-use/releases/latest`
|
||||
|
||||
### 3. 安装后初始化与激活
|
||||
```bash
|
||||
seal-use version # 校验安装版本与架构
|
||||
seal-use skill install # 同步/安装 Agent Skill 到 ~/.agents/skills/seal-use(支持 Codex / Cursor / Antigravity)
|
||||
seal-use mcp-config # 输出 MCP 配置 JSON 片段(供 Cursor / Claude Desktop 使用)
|
||||
seal-use update # 在线自升级至最新版本
|
||||
seal-use doctor # 运行环境与已接入租户健康诊断
|
||||
```
|
||||
|
||||
### 4. 开发者源码覆盖(本地开发环境)
|
||||
```bash
|
||||
bun run dev:override # 编译本机二进制、打版本号并原子覆盖全局命令与本地 Skill
|
||||
```
|
||||
|
||||
## 时间与输出
|
||||
|
||||
- 机器字段统一使用带 `+08:00` 北京时间偏移的 ISO 8601 秒级格式,不带毫秒,例如 `2026-09-28T11:51:09+08:00`。
|
||||
@@ -107,7 +140,7 @@ Hose 专属命令应从命令名或选项中明确可见:`auth hose-*`、`appr
|
||||
| Langfuse trace 检索、observation IO、session 大纲、规则/附件流追踪 | `references/langfuse-trace.md` | 已定位到 trace 后需要附件归因时,再读 `approval-attachment-trace.md` |
|
||||
| 附件、发票、收据、OCR 或界面高亮结论争议 | `references/approval-attachment-trace.md` | 先完成追踪和归因后,才读 `approval-bad-cases.md` 做案例对照 |
|
||||
| 已完成当前追踪后的相似坏案例对照 | `references/approval-bad-cases.md` | 不能作为首次诊断入口 |
|
||||
| 月度审核准确率报告、月报生成、accuracy report | 本文「月度审核准确率报告」一节 | 校验/渲染参数先查 `seal-use report render --help`;CLI 安装的 Skill 另附 `references/report-templates.md` |
|
||||
| AI 审核报告、验收报告、上线报告、周期准确率报告、accuracy report、台账自由裁量 | `references/report-templates.md` | 只查 CLI 语法时读 `cli.md`;涉及完整报告编制、Excel 台账自由裁量、人机研讨与门禁校验时读取 |
|
||||
|
||||
冲突时遵循三条优先级:材料获取先于来源判断;来源判断先于 Hose 具体探测;审批事实追踪先于坏案例类比。跨阶段请求也要按阶段顺序读取,不能用后置 reference 替代前置 reference。
|
||||
|
||||
@@ -133,52 +166,3 @@ seal-use langfuse observation <traceId> <observationId> # 最后才取焦点
|
||||
```
|
||||
|
||||
`approval-runs diagnose` / `bridge` 返回的 `bridge[].next` 就是下一步可执行命令。`seal-use langfuse check` 可自检内置密钥是否失效(失效 → exit 11/1 的结构化报错,绝不崩溃;已缓存 trace 仍可离线读取)。session、attachment-flow、rule-flow、缓存语义与失效兜底见 `references/langfuse-trace.md`。
|
||||
|
||||
## 月度审核准确率报告
|
||||
|
||||
推荐通过轻量数据包 + Agent 协同填写的模式,彻底解耦数据与模板(亦兼容一键脚手架模式):
|
||||
|
||||
```bash
|
||||
# 模式 A (推荐轻量数据驱动): 提取当月纯结构化数据 (指标、分模板统计、待复核分歧单及具体触发条件)
|
||||
seal-use report data --month <YYYY-MM> --corp <corpId>
|
||||
# 保存纯净模板骨架
|
||||
seal-use report template --out reports/报告.md
|
||||
# 独立生成动态维恩图 SVG
|
||||
seal-use report chart venn --ai <AI准确率> --human <人工准确率> --out reports/报告.assets/图1-准确率对比.svg
|
||||
|
||||
# 模式 B (传统模板脚手架): 一键生成初步替换的 Markdown 与配图包
|
||||
seal-use report monthly --month <YYYY-MM> --corp <corpId> --out reports/报告.md
|
||||
|
||||
# 离线校验与全格式编译导出
|
||||
seal-use report validate reports/报告.md
|
||||
seal-use report render reports/报告.md --out build/报告
|
||||
```
|
||||
|
||||
按模板结构(内置 `monthly.md`)自动从效能/风险/审批运行接口取数填充,返回填充后的 Markdown、各章节数据完备度(`sections`)与数据缺口标注(`notes`)。要点:
|
||||
|
||||
- **报告并非一键黑盒交付(人机协同研讨契约)**:数据接口无法自动获得“谁对谁错”的仲裁定性,也无法自动撰写管理归因与整改建议。生成初版 Markdown 后,Agent **严禁直接向客户交付带有 `> ⚠️ 数据说明` 警告框、模板假单号或 `(截图)` 占位符的半成品**,必须进入人机协同研讨模式(Tangent),向用户呈现分歧单据并共创定性分析文本。完整研讨流程、各章节动静边界与校验错误码见 `references/report-templates.md`。
|
||||
- **推荐轻量 Agent 执笔**:调用 `seal-use report data` 获取干净的 JSON 数据包(含触发的单个判断条件 `triggeredConditions`),由 Agent 亲自将真实数据与复核分析填入 Markdown,避免代码层正则换数的死板与脆弱。
|
||||
- **模板是可变的皮**:章节增删改名只要关键词仍命中,取数需求自动跟着走(`src/domains/seal/reports/describe.ts`)。改模板通常不用改代码。
|
||||
- **无上游口径不编造**:人工审核准确率、失准原因分类等取不到的指标,初稿保留模板示例值并在表后追加 `> ⚠️ 数据说明` 标注来源缺口——如实告知而非填假数字。
|
||||
- 默认模板、配图和校验/渲染引擎由仓库 Git 管理并随二进制内嵌,不依赖当前目录或原模板仓库。`--out` 保存 Markdown 与配图;不传则继续返回 `content`。`--output-file` 保存的是 JSON。
|
||||
- 结果里的 `next` 给出 CLI 校验与导出命令。`report validate` / `report render` 不需企业登录;校验失败返回 issues 和退出码 1,阻止导出。`render` 默认产出 HTML / 全长 PNG / A4 PDF,`--format html|png|pdf` 可选格式。已有文件须显式 `--overwrite` 才允许替换。
|
||||
- 本地运行环境:生成月报、校验与 HTML 导出只需 CLI;PNG/PDF 另需 Chrome/Chromium(可用 `--chrome` 指定)。无需 Python、Pillow、Node 或 npm;`--python` 已移除,传入返回用法错误。Markdown 解析和长图拼接已打包;含公式时首次渲染联网缓存 KaTeX。模板配图仍是示例/占位图,对外使用前检查 `notes` 并替换配图。
|
||||
- 只读能力 `sealReportDataGet` / `sealReportMonthlyGet`,MCP 经 `seal_use` 网关可达;`--template` 可换自定义模板路径。
|
||||
|
||||
### 人工裁决回填(算出人工审核准确率)
|
||||
|
||||
上游只给 AI 与人工结论是否同向(`agreement`),**谁对必须人来判**。判断结果按 SN 本地持久化,跨周累积到月底,`report monthly` 据此回填 §1.2 人工审核准确率与覆盖度说明:
|
||||
|
||||
```bash
|
||||
# 录入一条裁决(本地 JSONL,无需网络;通常裁决 AI≠人工 的分歧单)
|
||||
seal-use report review set --month <YYYY-MM> --sn <SN> --verdict <ai_correct|human_correct|both_correct|both_wrong|undecided> [--note <说明>] [--reviewed-by <裁决人>] --corp <corpId>
|
||||
|
||||
# 查看已录入的裁决
|
||||
seal-use report review list --month <YYYY-MM> --corp <corpId>
|
||||
```
|
||||
|
||||
- **存储**:`~/.config/seal-use/state/reviews/<corpId>-<YYYY-MM>.jsonl`,追加式一行一条,可直接手改/`tail`;同 SN 改判以后写为准。
|
||||
- **语义**:`ai_correct`=AI 对人工错,`human_correct`=人工对 AI 错,`both_correct`=双方都对,`both_wrong`=双方都错,`undecided`=已看暂无法判。
|
||||
- **自动接入**:`report monthly` 载入该租户该月裁决,SN 匹配上真实审批块后,人工准确率 = 判为"人工对"数 / 已裁决总数;`notes.humanAccuracyAvailable` 标记是否可得,`reviewedCount`/`divergedCount` 说明覆盖度。无裁决则保持 ⚠️ 数据说明,不编造。
|
||||
- `review set` 是本地写(非只读),`review list` 是只读;两者都进 help 注册表与读写白名单。
|
||||
- **协同研讨指南**:分歧单据挑选呈现格式、失准深度归因撰写(§2)、系统迭代历程(§1.3)与严格离线校验(NM001~NM005)排查手册,完整参见 `references/report-templates.md`。
|
||||
@@ -118,6 +118,7 @@ seal-use auth link --from-link <url> [--note <note>]
|
||||
seal-use auth link list [--corp <corpId>]
|
||||
seal-use auth link revoke <tokenId> [--corp <corpId>]
|
||||
seal-use auth hose-link [--corp <corpId>] [--expire <seconds>] [--force]
|
||||
seal-use auth hose-openapi-token [--corp <corpId>] [--force]
|
||||
seal-use users create --name <name> --phone <phone> [--dept <deptId>] [--corp <corpId>]
|
||||
seal-use users search <keyword> [--corp <corpId>]
|
||||
seal-use users delegation <userIdOrPhone|name> [--note <note>] [--corp <corpId>]
|
||||
@@ -156,6 +157,9 @@ seal-use deploy hosecloud status [--corp <corpId>]
|
||||
seal-use deploy hosecloud configure --json '{...}' [--dry-run] [--yes|--confirm] [--corp <corpId>]
|
||||
seal-use deploy hosecloud sync [<sign-key>] [--auto] [--dry-run] [--yes|--confirm] [--corp <corpId>]
|
||||
seal-use deploy hosecloud test-outbound [--sign-key <key>] --flow-id <flowId> --message-id <msgId> [--sn <sn>] [--rejection-num <n>] [--dry-run] [--yes|--confirm] [--corp <corpId>]
|
||||
seal-use hose-ebot search <sn> [--type invoking|callback] [--limit <n>] [--reveal] [--corp <corpId>]
|
||||
seal-use hose-ebot messages [--type flow|message] [--reveal] [--corp <corpId>]
|
||||
seal-use hose-ebot callback --flow-id <flowId> --node-id <nodeId> --action <accept|refuse|preAdd|aftAdd> --comment <审批意见> [--sign-key <key>] [--policy <ALL|ANY>] [--add-approver-ids <id,id>] [--reject-to <nodeId>] [--resubmit-method <FROM_START|TO_REJECTOR>] [--dry-run] [--yes|--confirm] [--corp <corpId>]
|
||||
seal-use preference get [--corp <corpId>]
|
||||
seal-use preference decision update --json '{"explicitApprove":"..."}' [--dry-run] [--corp <corpId>]
|
||||
seal-use preference thinking-depth set --default <medium|high> [--dry-run] [--corp <corpId>]
|
||||
@@ -246,6 +250,13 @@ Durable Hose configs are identified by `source.type: "hose"` plus `appKey/appSec
|
||||
- `seal-use corps hose-extract-keys <url> [--reveal] [--save] [--name <name>] [--app-key <key>] [--key-id <id>] [--overwrite]` extracts OpenAPI keys (`appKey` and `appSecurity`) from a Hose assistance link (`thirdparty.html`). The old `extract-keys`/`extract-key`/`extract-hose-keys` forms remain aliases. **Hose Subdomain Privilege Elevation**: elevates a short-lived session token to permanent Hose OpenAPI developer credentials. If `--save` is specified, registers the enterprise as a durable Hose tenant. If the enterprise has multiple keys, execution halts and candidates are listed unless `--app-key` or `--key-id` is passed.
|
||||
- `seal-use corps hose-keys [<url> | <corpId>] [--reveal] [--save]` reads/displays OpenAPI keys for a Hose assistance link or configured Hose enterprise (masked by default, `--reveal` displays plaintext). The old `keys` form remains an alias. Rejects non-Hose/native-Seal tenants with exit code 2.
|
||||
- `seal-use auth hose-extract-keys <url>` and `seal-use auth hose-keys [--corp <corpId>]` are the explicit Hose auth-domain commands. The old `extract-keys`/`extract-key`/`extract-hose-keys` and `keys` forms remain aliases.
|
||||
- `seal-use auth hose-openapi-token [--corp <corpId>] [--force]` exchanges the persisted Hose `appKey/appSecurity` for an OpenAPI `accessToken` and prints it as machine JSON (`token`, `expiresAt`, `cached`; aliases `openapi-token`, `hose-token`). A still-fresh cached token is reused by default (`cached: true`, with a stderr notice); `--force` mints a new one. Unlike `auth check`, the token is intentionally unredacted. Rejects non-Hose tenants with exit code 2; missing credentials exit 13.
|
||||
|
||||
Hose outbound discovery & EBot callback (first-level `hose-ebot` command; Hose-only):
|
||||
|
||||
- `seal-use hose-ebot search <sn> [--type invoking|callback] [--limit <n>] [--reveal]` is the default entry: it searches the Hose outbound message log by document SN and returns records that each carry a unique `id` (`INVOKING`=出站触发, `CALLBACK`=回调), plus the `flowId`/`nodeId`/`messageId`/`rejectionNum` a callback needs. Read-only; any `signKey` inside records is masked unless `--reveal`.
|
||||
- `seal-use hose-ebot messages [--type flow|message] [--reveal]` lists every outbound message config on the Hose side (`messageName`, `signKey`, `callbackUrl`, `enable`, …). `signKey` is the `config_id` embedded in the callback URL; masked unless `--reveal`. Read-only.
|
||||
- `seal-use hose-ebot callback --flow-id <flowId> --node-id <nodeId> --action <accept|refuse|preAdd|aftAdd> --comment <审批意见> …` runs the EBot approval callback (`POST /api/openapi/v1/approval`) and writes the result into the approval flow; success is `value.code=204`. Requires `--dry-run` (masked preview) or `--yes/--confirm` (otherwise exit 10). `--sign-key` is optional when the enterprise has exactly one Seal Hose integration. Upstream business codes map to exit codes: 401→11, 400→13, 412/500→1. Only EBot-node approvals are supported upstream.
|
||||
|
||||
Read-only discovery:
|
||||
|
||||
|
||||
@@ -211,8 +211,8 @@ Do not automatically rerun or resubmit the customer's production document. Run a
|
||||
- 优先输出自带内联样式的**自包含单文件 HTML**(以及原始 Markdown)。用户可以在任何 Chrome / Edge 浏览器中直接打开、查看,或使用浏览器的「打印 -> 另存为 PDF」无损导出,字体内嵌、格式绝对保真。
|
||||
- 当本地宿主环境已具备极简无头工具(如系统级 `typst` 或系统自带无头 Chrome/Edge)时,可静默协同编译出 PDF 文件一同交付。
|
||||
2. **操作身份声明原则(避免张冠李戴)**:
|
||||
- 严禁将底层 API 绑定的系统凭证名称(如“周晚容”)直接写为“发布操作人”;
|
||||
- 必须显式注明:**“发布操作身份:周晚容(系统调用凭证账号,由智能助手代执行)”**,明确告知这只是调用系统所使用的鉴权身份,不代表是该自然人亲自操作。
|
||||
- 严禁将底层 API 绑定的系统凭证名称直接写为“发布操作人”;
|
||||
- 必须显式注明:**“发布操作身份:<系统凭证绑定账号/员工名>(系统调用凭证账号,由智能助手代执行)”**,明确告知这只是调用系统所使用的鉴权身份,不代表是该自然人亲自操作。
|
||||
3. **免尾戳原则 (No Vendor Footers)**:
|
||||
- 报告文末与页脚**严禁携带工具自夸尾戳**(例如:❌ `生成工具:Seal Use Automated Engineering Suite`),保持纯粹中立、属于客户企业与业务事实本身的技术报告风格。
|
||||
4. **双重呈现原则 (Diff + 完整前文/完整后文)**:
|
||||
@@ -261,6 +261,6 @@ Do not automatically rerun or resubmit the customer's production document. Run a
|
||||
- **线上版本序号**:发布的版本序号(如 `版本 34`)
|
||||
- **线上版本名称**:发布时录入的具体版本名称
|
||||
- **正式生效时间**:精确到秒的北京时间
|
||||
- **系统调用凭证账号**:显式说明“周晚容(系统调用凭证账号,由智能助手代执行)”
|
||||
- **系统调用凭证账号**:显式说明“<系统凭证绑定账号/员工名>(系统调用凭证账号,由智能助手代执行)”
|
||||
- **全量规则总数**:核对总数是否变化
|
||||
- **规则一致性校验**:确认目标规则文本与确认内容 100% 逐字吻合
|
||||
@@ -34,6 +34,8 @@ Read the JSON `stages` in order:
|
||||
|
||||
Do not expect tokens in the output; the command intentionally redacts or omits them.
|
||||
|
||||
When the caller needs the actual OpenAPI `accessToken` itself (for example to call Hose OpenAPI from their own script), use `seal-use auth hose-openapi-token --corp <corpId> [--force]`. It prints the unredacted token as JSON together with `expiresAt` and `cached` (`cached: true` means a still-fresh local token was reused; pass `--force` to mint a new one). Non-Hose enterprises are rejected with exit 2, and a Hose enterprise without persisted `appKey/appSecurity` exits 13.
|
||||
|
||||
## Get a Hose authorization link
|
||||
|
||||
When the user asks for a 合思/易快报授权链接、登录链接、入口链接, or says "来一个授权链接" for a Hose sourced enterprise, return the Hose provisional/CloseAPI URL from `getProvisionalAuth`'s `value.message`.
|
||||
@@ -61,9 +63,10 @@ Important:
|
||||
- Do not return the Seal tenant URL such as `https://<tenant>.sealai.cc`; that is not the Hose authorization link.
|
||||
- Do not manually assemble `thirdparty.html` with a global/OpenAPI token.
|
||||
- `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.
|
||||
- **Formatting Requirement**: When returning an authorization link (`auth link` or `auth hose-link`) to the user, ALWAYS provide:
|
||||
1. The operator identity used (e.g. `周晚容` / `staffId`),
|
||||
2. The exact expiration time in Beijing time (`expiresAt`, e.g. `2026-09-22T11:20:02+08:00`),
|
||||
- **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),
|
||||
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.
|
||||
- **Dedicated CLI Command**: Use `seal-use auth hose-link --corp <corpId> [--expire <seconds>] [--force]`. This command directly generates an independent provisional auth link without reading or mutating internal CLI session cache. It supports `--expire` (default 7200, e.g. 86400 for 1 day).
|
||||
- **Seal AI Platform Direct Link**: Use `seal-use auth link --corp <corpId> [--note <note>]`. This generates a 24-hour provisional delegation link for the Seal AI audit platform (`https://*.sealai.cc`).
|
||||
- **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>]`.
|
||||
|
||||
@@ -91,6 +91,31 @@ seal-use deploy hosecloud test-outbound [--sign-key <key>] --flow-id <flowId> --
|
||||
实际推送必须带 `--yes` 或 `--confirm`;`--dry-run` 可直接预览。自定义 `nodeId` 时,预览中的 `nodeId412Blocked` 不再声明默认标记的阻断保障。
|
||||
出站响应未明确返回关联 `recordId` 时,结果为 `consumptionVerified: false`(推送已接受,消费尚未确认),不会用同单据的历史记录误报本次消费成功。
|
||||
|
||||
### 出站发现与 EBot 回调(一级命令 `hose-ebot`)
|
||||
|
||||
`sync` 之后,出站消息的发现与回调审批走独立的一级命令 `seal-use hose-ebot`(Hose 专属,非合思租户拒绝,退出码 13):
|
||||
|
||||
```text
|
||||
# 9. 按单号搜索出站/回调记录(默认入口;每条记录带唯一 id)
|
||||
seal-use hose-ebot search <sn> --corp <corpId>
|
||||
seal-use hose-ebot search <sn> --type invoking --corp <corpId> # 只看 出站触发
|
||||
seal-use hose-ebot search <sn> --type callback --corp <corpId> # 只看 回调
|
||||
|
||||
# 10. 列出全部出站消息配置,发现 signKey(即回调地址中的 config_id)
|
||||
seal-use hose-ebot messages --corp <corpId>
|
||||
seal-use hose-ebot messages --reveal --type flow --corp <corpId> # 明文 signKey
|
||||
|
||||
# 11. 回调审批(写入审批流;先 --dry-run 预览,正式执行必须 --yes)
|
||||
seal-use hose-ebot callback --corp <corpId> --sign-key <signKey> \
|
||||
--flow-id <flowId> --node-id <nodeId> --action accept --comment "同意" --dry-run
|
||||
seal-use hose-ebot callback --corp <corpId> --sign-key <signKey> \
|
||||
--flow-id <flowId> --node-id <nodeId> --action accept --comment "同意" --yes
|
||||
```
|
||||
|
||||
- `hose-ebot search` 返回记录的唯一 `id`,回调所需的 `flowId`/`nodeId` 直接来自记录的 `request` 字段;`--type invoking|callback` 区分出站触发与回调,`--limit` 控制条数(默认 20)。
|
||||
- `hose-ebot messages --reveal` 输出的 `signKey` 就是 `hose-ebot callback --sign-key` 的入参;企业仅有一个 Seal 合思集成时可省略 `--sign-key` 自动解析。
|
||||
- 回调成功返回 `value.code=204`;上游业务码映射退出码:401(signKey 错误)→11、400(参数错误)→13、412/500 →1。缺少 `--yes`/`--confirm` 且无 `--dry-run` 时退出码 10。accessToken 在回调前实时换取,不复用缓存;仅支持 EBot 节点的审批回调。
|
||||
|
||||
---
|
||||
|
||||
## 4. 关键配置参数定义
|
||||
|
||||
@@ -1,218 +1,371 @@
|
||||
# 月度 AI 审核准确率报告编制与人机协同研讨指南 (Monthly Report Authoring & Tangent Workflow)
|
||||
# AI 审核报告编制与人机协同作业指南 (AI Audit Report Authoring & Tangent Workflow)
|
||||
|
||||
本文档面向 AI Agent 与实施运维人员,规范从**月度数据拉取与底稿装配**、**分歧单据人机复核研讨(Tangent)**、**纯文本质性分析与整改建议共创**,到**严格离线校验与多格式商业交付**的端到端标准工作流。
|
||||
本文档面向 **AI Agent 与操作用户**,是 Seal Enterprise AI 审核报告的**唯一权威业务与实施参考手册**。详细规范从**周期数据拉取与自由裁量台账导出**、**分歧单据人机复核研讨(Tangent)**、**Agent 自主执笔与排版**,到**严格离线门禁校验、全格式渲染与多轮修改**的端到端人机协同闭环。
|
||||
|
||||
---
|
||||
|
||||
## 核心认知与架构分工 (Core Architecture & Division of Labor)
|
||||
|
||||
1. **轻量数据接口 + Agent 亲自执笔 (The Lightweight Authoring Model)**:
|
||||
- **工具层(确定性计算与缓存)**:负责拉取审批运行数据、统计分模板数据、计算准确率公式、记录用户逐单裁决(`review set`)、生成独立矢量图表(`report chart venn`)以及提供离线格式/数值勾稽校验(`report validate`)与全格式编译(`report render`)。
|
||||
- **Agent 层(智能分析与文档创作)**:Agent 最擅长理解数据、归纳总结、与用户对话,并撰写自然流畅的业务报告。因此,**推荐让 Agent 直接获取轻量数据包(`seal-use report data`),亲自将真实数据、分歧案例与整改建议手工填入 Markdown 模板**,彻底摆脱代码中死板的正则替换与假数据。
|
||||
2. **严禁交付半成品 (Zero-Mock Delivery Red Line)**:
|
||||
- 严禁向客户交付带有 `> ⚠️ **数据说明**:...需人工归类后替换` 警告框的半成品。
|
||||
- 严禁保留模板中写死的假数据(如 `B26002583` 等固定占位单号)或字面 `(截图)` 占位符。
|
||||
- 严禁跳过 `seal-use report validate` 直接交付未经勾稽校验的文档。
|
||||
3. **单个判断条件与人机复核契约 (Triggered Conditions & Tangent Contract)**:
|
||||
- 分歧单据中包含 AI 拦截触发的**单个具体判断条件**(`triggeredConditions`,如“发票日期早于行程日”、“未附改衣明细表”)。
|
||||
- Agent 获取初版数据后,**必须主动进入“研讨模式”(Tangent)**,向用户呈现这些具体的触发条件,征询真实业务对错裁决,并引导用户共创定性分析文本。
|
||||
## 目录 (Table of Contents)
|
||||
1. [报告定位与三大业务类型](#一报告定位与三大业务类型)
|
||||
2. [核心边界与人机分工契约](#二核心边界与人机分工契约)
|
||||
3. [术语规范契约(彻底弃用“失准”)](#三术语规范契约彻底弃用失准)
|
||||
4. [自由裁量台账 16 列规格说明](#四自由裁量台账-16-列规格说明)
|
||||
5. [端到端人机协同作业流程](#五端到端人机协同作业流程)
|
||||
6. [标准 6 大章节深度剖析](#六标准-6-大章节深度剖析)
|
||||
7. [动态自适应与用户至上原则](#七动态自适应与用户至上原则)
|
||||
8. [离线门禁校验规则手册 (Zero-Error Gate)](#八离线门禁校验规则手册-zero-error-gate)
|
||||
9. [全格式编译渲染与跨端交付](#九全格式编译渲染与跨端交付)
|
||||
|
||||
---
|
||||
|
||||
## 端到端标准研讨流 (The 4-Stage Lifecycle)
|
||||
## 一、报告定位与三大业务类型
|
||||
|
||||
Seal AI 审核报告是向企业财务总监、风控负责人及 CIO 交付的专业级商业论证报告。它并非局限于传统的“月报”,而是普遍涵盖以下三类业务场景:
|
||||
|
||||
| 报告类型 | 业务场景与目标 | 取数周期与事实源建议 | 核心关注论证点 |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| **验收审核报告** | 客户试点验证、POC 结项交付、商业签约对赌。证明 AI 审核精度达到既定合同标准。 | 自定义时间周期(`--start-date` / `--end-date`),支持按模板过滤(`--templates`),结合 Excel 裁剪。 | 规则通过率、AI 依规审核准确率、与人工对比的漏审与误拦截率、可量化提效收益。 |
|
||||
| **上线审核报告** | 新版规则上线前评审、规则组重大重构、系统切割试运行。评估新规则组的稳定性与风控阻断效果。 | 指定跑批周期,或通过 staging 环境同步与模拟跑批结果对照。 | 新旧规则差异、对存量单据的重判影响、高风险违规拦截有效性。 |
|
||||
| **周期审核报告** | 持续运营中的月度、季度、半年度常规复盘。跟踪规则运行健康度、持续调优风控卡口。 | 按月度或季度周期提取,结合跨周累积的复核裁决记录。 | 准确率演进趋势、人机分歧根因演进、未在线配置规则的制度沉淀进度。 |
|
||||
|
||||
> [!NOTE]
|
||||
> **统一论证骨架**:这三类报告共享完全相同的 6 大章节骨架、数学勾稽定义、双端穿透跳转与离线门禁规则。
|
||||
|
||||
---
|
||||
|
||||
## 二、核心边界与人机分工契约
|
||||
|
||||
为了确保报告的客观性、专业性与极高的交付质量,系统严格划分了**确定性工具**与**智能裁量权**的边界:
|
||||
|
||||
```
|
||||
┌────────────────────────────────────────────────────────────────────────┐
|
||||
│ 确定性工具层(CLI 扳手) │
|
||||
│ │
|
||||
│ - 纯粹提数:从云端无损拉取审批运行数据,绝不主观推断对错 │
|
||||
│ - 双向台账:导出含双端完整依据的 Excel,导入裁决结果 │
|
||||
│ - 严格边界:一旦传入 --ledger,完全以本地文件为唯一事实源,绝不越界回查 │
|
||||
│ - 机械门禁:严格执行格式自洽与数学勾稽检查(退出码 1 拦截) │
|
||||
│ - 无赖渲染:跨平台原生编译 HTML / PNG / PDF,免 Python / Node │
|
||||
└───────────────────────────────────┬────────────────────────────────────┘
|
||||
│ 赋能支撑
|
||||
▼
|
||||
┌────────────────────────────────────────────────────────────────────────┐
|
||||
│ 智能执笔层(AI Agent) │
|
||||
│ │
|
||||
│ - 自由裁量权:在 Excel 台账中随意删减模板(如 8 删 4)、清洗脏数据、定性裁决 │
|
||||
│ - 人机研讨(Tangent):向用户汇报分歧案例,征询权威定性,拒绝臆断 │
|
||||
│ - 深度归因执笔:将数字转化为深刻的业务管理建议与制度沉淀路径 │
|
||||
│ - 交付质量底线:严禁向用户交付带警告框、模板假单号或占位符的半成品 │
|
||||
│ - 门禁自纠自查:遇门禁报错主动阅读 issue 并精准自愈修正 │
|
||||
└────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 1. CLI 只是扳手,绝不越界
|
||||
- CLI 的职责是提供精确、高速、可复现的确定性底层操作。
|
||||
- **边界约束**:当用户或 Agent 指定 `--ledger 台账.xlsx` 时,CLI 将**完全把该 Excel 视为封闭的全局事实边界**。在 Excel 中被 Agent 删除的单据行或模板,CLI 绝不会再去远程接口探查其历史存在。CLI 的离线门禁校验也仅针对当前 Excel 内部剩余的数据做逻辑与数学校验。
|
||||
|
||||
### 2. Agent 自由裁量与研讨契约
|
||||
- **台账是自由裁量的操作台**:Agent 导出台账后,可以根据业务实际诉求对数据进行清洗,例如:剔除尚在调试中的非核心模板单据、剔除测试人员提交的脏数据等。
|
||||
- **严禁交付半成品**:数据接口无法自动获知分歧单到底“谁对谁错”,无法凭空撰写针对性的管理对策。生成 Markdown 草稿后,Agent 严禁直接把带有 `> ⚠️ 数据说明` 警告框、模板占位符或示例假数据的初稿交付给客户,必须进入人机协同研讨,共创定性。
|
||||
|
||||
---
|
||||
|
||||
## 三、术语规范契约(彻底弃用“失准”)
|
||||
|
||||
在过往沟通中,由于词汇模糊,常常将“AI 驳回而人工放行”粗暴地称为“AI 失准”或“失准单据”。这导致客户管理层极易产生巨大误解:**“到底是单据本身有问题违规了,还是你们 AI 做错了?”**
|
||||
|
||||
为了彻底杜绝此类误解,在所有的代码、台账、Markdown 报告、命令行输出以及与用户的对话中,**必须严格区分以下两个相互独立的评价层级**:
|
||||
|
||||
### 1. 层级一:单据合规性判断(审批决策 / Approval Decision)
|
||||
- **定义**:AI 或人工审批人在业务流水线中,针对送审单据本身是否合规给出的处理操作。
|
||||
- **规范措辞**:
|
||||
- `通过 (Pass)`:单据材料完备、发票合规、符合当前既定规则,予以放行。
|
||||
- `驳回 (Reject)`:单据存在不合规事项、附件缺失或超标,予以阻断退回。
|
||||
- `违规拦截`:在论述风控价值时,将驳回操作正确定性为识别并阻断了合规风险。
|
||||
- **禁忌**:❌ 严禁使用“单据错误”、“AI 错误”来指名单据被驳回。单据驳回是规则库正常发挥风控作用的正面体现。
|
||||
|
||||
### 2. 层级二:审核行为复核评判(裁决判定 / Review Verdict)
|
||||
- **定义**:在后续审计复核或人机研讨中,对“AI 或人工在审批时的决策行为是否正确”所下的仲裁定性。
|
||||
- **规范枚举与标准术语**:
|
||||
|
||||
| 枚举代码 | 标准对外术语 | 业务判定基准 | 准确率归因影响 |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| `ai_correct` | **AI 判断正确 / 人工判断错误** | AI 依线上既定规则放行或拦截完全正确;人工属于漏审放行,或依据线下口头标准无理驳回。 | 计入 AI 依规正确(分子 +1);扣减人工准确率。 |
|
||||
| `human_correct` | **人工判断正确 / AI 判定误判** | 人工判定符合真实业务合规标准;AI 出现误报(误拦合规单)或漏报(放行违规单)。 | 计入 AI 判定误判(不计入分子);计入人工正确。 |
|
||||
| `both_correct` | **双方判断均正确** | AI 依线上规则合规,人工依线下审批特例亦合情合理,双方均符合各自依据。 | 计入双方正确。 |
|
||||
| `both_wrong` | **双方判定均误判** | AI 与人工均产生认知失误或操作偏差。 | 双方均扣减准确率。 |
|
||||
| `undecided` | **存疑待定** | 关键发票或凭证附件信息不全,当前暂无法定性。 | 暂不计入已裁决样本。 |
|
||||
|
||||
### 3. 一致单覆盖支持(Consistent Override)
|
||||
- 默认情况下,通常只需裁决 AI 与人工结论相反(`diverged`)的分歧单。
|
||||
- 但若用户指名道姓要求对人机原本同向的单据进行覆盖,系统完全支持:
|
||||
- **典型场景**:一笔单据 AI 给出了驳回,人工也给出了驳回。但用户复核后指出:“AI 是依据发票跨期规则精准拦截,而人工审批人只是随便填了个理由跟风驳回,甚至根本没看发票”。
|
||||
- **处理方式**:用户或 Agent 将该单录入 `ai_correct`,系统将明确认定 AI 正确、人工失误,如实扣减人工准确率。
|
||||
|
||||
### 4. 双键定位机制(`recordId` vs `sn`)
|
||||
- 在企业实际运行中,同一张单据(相同 `sn`)可能由于被驳回修改而经历多轮审核,或者在测试环境中被多次跑批,产生多条运行记录。
|
||||
- **机制**:复核账本与 Excel 台账全面支持双键定位。系统优先以精准单次审核运行的 `recordId` 为主键进行裁决绑定;若未提供 `recordId`,则向下兼容以单据业务单号 `sn` 匹配。
|
||||
|
||||
---
|
||||
|
||||
## 四、自由裁量台账 16 列规格说明
|
||||
|
||||
通过 `seal-use report ledger` 导出的 Excel / CSV 台账是人机自由裁量的核心载体。它包含了双端最完整的判定凭据:
|
||||
|
||||
```markdown
|
||||
| 列号 | 列名 | 字段含义与说明 | 数据来源 |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| **A** | `审核ID(recordId)` | 单次 AI 审核运行的唯一主键,用于版本精确锁定 | 审批运行记录主键 |
|
||||
| **B** | `单据编号(SN)` | 单据业务自然键(如 `CL2608001`) | 业务单据主键 |
|
||||
| **C** | `单据模板` | 单据所属表单类型(如 `差旅报销单`) | 业务单据模板 |
|
||||
| **D** | `单据标题/事由` | 单据报销或申请标题、事由摘要 | 业务单据属性 |
|
||||
| **E** | `提交人` | 单据发起员工姓名或工号 | 业务单据属性 |
|
||||
| **F** | `费用承担部门` | 单据所属费用发生或承担部门 | 业务单据属性 |
|
||||
| **G** | `跑批时间` | AI 审核执行的北京时间 | 审批运行属性 |
|
||||
| **H** | `AI审批决策` | AI 给出的审批决策:`同意` / `驳回` | 审批运行结果 |
|
||||
| **I** | `AI审核完整意见与违规详情` | **核心证据列**:包含 AI 综合评语、触发的具体规则编号及违规条款细则 | 聚合 summary + conditions |
|
||||
| **J** | `人工审批结论` | 人工审批人实际操作:`同意` / `驳回` / `终止` | 人工操作记录 |
|
||||
| **K** | `人工审批批注/驳回说明` | **核心证据列**:人工审批人在系统后台填写的真实审批意见与驳回理由 | 提取 manualComment / rejectComment |
|
||||
| **L** | `人机一致性` | `一致`、`分歧` 或 `未完结/流转中` | 比较 H 与 J 决策极性 |
|
||||
| **M** | `复核定性裁决` | **自由裁量填报列**:Agent/用户填写的定性结论(支持中英文口语化识别) | 人工/Agent 填报 |
|
||||
| **N** | `复核人` | 执行该单裁决核查的业务人员或 Agent 署名 | 人工/Agent 填报 |
|
||||
| **O** | `复核批注说明` | 针对复核裁决填写的定性分析、归因说明与管理整改建议 | 人工/Agent 填报 |
|
||||
| **P** | `审批耗时(秒)` | AI 模型单据全生命周期审核耗时(秒) | 审批运行属性 |
|
||||
```
|
||||
|
||||
> [!TIP]
|
||||
> **中文口语化智能解析**:在「复核定性裁决」列中,用户不仅可以填写规范枚举(`ai_correct`),也可以自由填写中文口语:“`AI判断正确 / 人工判断错误`”、“`AI正确`”、“`人工正确`”、“`AI误判`”、“`双方正确`”等,CLI 在加载时均能百分之百精准识别映射。
|
||||
>
|
||||
> 若需核查单据更细维度的明细金额、发票结构化票面或附件凭证,Agent 可通过 `seal-use approval-runs get <recordId>` 或 `seal-use hose-ebot` 按需补充调阅。
|
||||
|
||||
---
|
||||
|
||||
## 五、端到端人机协同作业流程
|
||||
|
||||
### 模式 A:Excel 台账自由裁量驱动(首推推荐)
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
S1["Stage 1: 获取轻量报告数据包与模板 (report data & template)"] --> S2["Stage 2: 分歧单据人机复核研讨 (Diverged Runs Review Tangent)"]
|
||||
S2 --> S3["Stage 3: 纯文本深度叙述与质性洞察共创 (Agent 执笔填入 Markdown)"]
|
||||
S3 --> S4["Stage 4: 离线门禁校验与全格式商业渲染 (report validate & render)"]
|
||||
sequenceDiagram
|
||||
autonumber
|
||||
actor User as 用户 / 客户管理层
|
||||
participant Agent as AI Agent (智能执笔)
|
||||
participant CLI as seal-use CLI (确定性扳手)
|
||||
participant Cloud as Seal 云端 / 本地缓存
|
||||
|
||||
Agent->>CLI: 1. seal-use report ledger --start-date ... --end-date ... --out 台账.xlsx
|
||||
CLI->>Cloud: 提取全量明细与双端完整意见
|
||||
CLI-->>Agent: 产出《台账.xlsx》(16列完整数据)
|
||||
|
||||
Note over Agent: 2. 自由裁量清洗:<br/>- 删去暂未验收的 4 种模板<br/>- 剔除异常测试单<br/>- 在复核定性列填写裁决
|
||||
|
||||
Agent->>User: 汇报分歧案例并对齐裁决
|
||||
User-->>Agent: 确认裁决定性
|
||||
|
||||
Agent->>CLI: 3. seal-use report generate --ledger 台账.xlsx --out 报告.md
|
||||
Note over CLI: 严格以本地 Excel 为边界,<br/>绝不回查云端已删除数据
|
||||
CLI-->>Agent: 生成干净完整的结构化 Markdown
|
||||
|
||||
Agent->>CLI: 4. seal-use report validate 报告.md
|
||||
CLI-->>Agent: 门禁通过 (valid: true)
|
||||
|
||||
Agent->>CLI: 5. seal-use report render 报告.md --out build/报告/
|
||||
CLI-->>User: 交付单文件 HTML、A4 PDF 与长图 PNG
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 第一阶段:获取轻量报告数据包与模板 (Data Pack & Template Scaffold)
|
||||
|
||||
#### 推荐方式:轻量数据驱动 (Mode A: Lightweight Data Pack)
|
||||
|
||||
1. **拉取纯结构化报告数据包 (JSON)**:
|
||||
```bash
|
||||
seal-use report data --month <YYYY-MM> --corp <corpId>
|
||||
```
|
||||
*说明:返回纯 JSON 数据,包含当期效能指标(样本量、AI 准确率、采纳率、平均耗时)、公式代入值、分模板统计、TOP 风险标签,以及**全量分歧单据及其触发的具体判断条件(`triggeredConditions`)**,完全不依赖任何 Markdown 模板。*
|
||||
|
||||
2. **获取纯净内置模板与生成矢量图表**:
|
||||
```bash
|
||||
# 保存纯净的内置月报模板 Markdown
|
||||
seal-use report template --out reports/<企业名>-<YYYYMM>.md
|
||||
|
||||
# 准备配图目录并独立生成动态维恩图 SVG
|
||||
mkdir -p reports/<企业名>-<YYYYMM>.assets
|
||||
seal-use report chart venn --ai <AI准确率> --human <人工准确率> --out reports/<企业名>-<YYYYMM>.assets/图1-准确率对比.svg
|
||||
```
|
||||
|
||||
#### 传统方式:模板脚手架一键填充 (Mode B: Template Scaffold)
|
||||
亦可使用经典命令一键拉取并由代码初步组装 Markdown 脚手架与伴随台账:
|
||||
#### 具体操作指令:
|
||||
```bash
|
||||
seal-use report monthly --month <YYYY-MM> --corp <corpId> --out reports/<企业名>-<YYYYMM>.md
|
||||
# 步骤 1:一键拉取指定周期的全量明细台账(含 AI 完整意见与人工批注)
|
||||
seal-use report ledger --start-date 2026-08-12 --end-date 2026-09-18 --corp <corpId> --out reports/明细台账.xlsx
|
||||
|
||||
# 步骤 2:Agent 或用户在 Excel 中自由裁量,增删模板行并填入裁决;
|
||||
|
||||
# 步骤 3:严格以修改后的台账为唯一事实源,出具报告草稿
|
||||
seal-use report generate --ledger reports/明细台账.xlsx --corp <corpId> --out reports/审核报告.md
|
||||
|
||||
# 步骤 4:严格门禁校验(必须通过)
|
||||
seal-use report validate reports/审核报告.md
|
||||
|
||||
# 步骤 5:本地全格式编译渲染
|
||||
seal-use report render reports/审核报告.md --out build/审核报告/
|
||||
```
|
||||
*诊断返回 JSON 中的 `notes.humanAccuracyAvailable`,若为 `false` 则说明尚未复核,需进入第二阶段。*
|
||||
|
||||
> [!TIP]
|
||||
> **全量取数与分页控制**:`seal-use report ledger`、`report data` 与 `report generate` 默认自动分页拉取所选时间区间内的**全部审批单据**(内置 100,000 笔安全防死循环上限),无任何 500 条的人工截断限制。如需做小样本分析或限定抓取笔数,可传入 `--limit <n>`(别名 `--max-runs <n>` / `-n <n>`,例如 `--limit 2000`)。
|
||||
|
||||
---
|
||||
|
||||
### 第二阶段:分歧单据人机复核研讨 (Diverged Runs Review Tangent)
|
||||
### 模式 B:CLI 命令行实时研讨驱动
|
||||
|
||||
在 AI 审核与人工审批结论相悖的单据中(AI 同意但人工驳回,或 AI 驳回但人工同意),必须由熟悉业务的实施/财务人员裁决真实对错。
|
||||
适合小批量单据核查或纯命令行快速批处理:
|
||||
|
||||
1. **提取高价值分歧单据**:
|
||||
Agent 可直接分析伴随生成的《明细台账.csv》或调用查询命令检索分歧单据:
|
||||
1. **提取结构化数据包**:
|
||||
```bash
|
||||
# 查看或导出当前月份分歧单据
|
||||
seal-use report review list --month <YYYY-MM> --corp <corpId>
|
||||
seal-use report data --start-date 2026-08-12 --end-date 2026-09-18 --corp <corpId>
|
||||
```
|
||||
返回纯 JSON 数据,包含全周期样本量、AI 准确率、采纳率、平均耗时、分模板统计及全量分歧单池(`divergedRuns`)。
|
||||
|
||||
2. **结构化向用户呈现案例并征询裁决 (Interactive Tangent Prompting)**:
|
||||
挑选 3~5 笔最具代表性的分歧单据,以结构化卡片形式向用户呈现关键上下文:
|
||||
2. **双链穿透研讨呈现**:
|
||||
在聊天窗口中结构化呈报案例给用户:
|
||||
```markdown
|
||||
【分歧单据复核研讨】单号:FP2026090123
|
||||
- 单据模板:一般费用报销单【发票】- 个人报销
|
||||
- 提交人 / 部门:张三 / 市场运营部
|
||||
- AI 审核结论:建议驳回(发票开票日期早于出差行程起始日)
|
||||
- 人工实际操作:直接审批同意(已支付)
|
||||
【分歧单据复核确认】单号:CL2608019
|
||||
- 单据模板:差旅报销单
|
||||
- 快速核验:[🔗 Seal AI 审核详情](https://<corp>.sealai.cc/approval-result/<recordId>) | [📑 合思原单据](https://wx2.ekuaibao.com/...)
|
||||
- AI 审核结论:驳回(检测到机票发票开票日期早于出差申请单行程日期 15 天,违反制度条款 3.2)
|
||||
- 人工实际操作:同意放行(批注:线下特殊批准提前出发)
|
||||
- 触发条件:规则 0012「行程与票据日期逻辑核验」
|
||||
|
||||
👉 请教您对本单的裁决看法:
|
||||
1. AI 正确(ai_correct):按财务规范确实属于跨期违规,人工属于特批放行,AI 依规放行正确;
|
||||
2. 人工正确(human_correct):业务实际存在合理提前购票场景,规则未配置豁免,属于 AI 误判;
|
||||
3. 双方都对(both_correct):规则执行无误,但存在线下特殊批复;
|
||||
4. 其它/暂无法定性(undecided)。
|
||||
👉 请教您对本单的裁决:
|
||||
1. AI 判断正确 / 人工判断错误 (ai_correct):AI 依规拦截正确,人工属于线下特批未补充审批单;
|
||||
2. 人工判断正确 / AI 判定误判 (human_correct):业务允许特定场景提前订票,属于规则库未覆盖例外;
|
||||
3. 双方判断均正确 (both_correct):双方各自依规,属于已知特例。
|
||||
```
|
||||
|
||||
3. **实时录入裁决定性**:
|
||||
收到用户的确认后,执行 CLI 命令持久化到本地裁决账本:
|
||||
3. **裁决录入持久化账本**:
|
||||
```bash
|
||||
seal-use report review set \
|
||||
--month <YYYY-MM> \
|
||||
--sn <SN> \
|
||||
--verdict <ai_correct|human_correct|both_correct|both_wrong|undecided> \
|
||||
--note "跨期发票已获总监线下邮件特批,规则库缺少该豁免卡口" \
|
||||
--reviewed-by "实施顾问/财务张老师" \
|
||||
--corp <corpId>
|
||||
--corp <corpId> \
|
||||
--record-id <ID> \
|
||||
--sn CL2608019 \
|
||||
--verdict ai_correct \
|
||||
--note "线下特批未附审批单,AI依规拦截正确"
|
||||
```
|
||||
|
||||
4. **离线台账批量导入**:
|
||||
若线下已在 Excel 台账中集中批量评审完毕,可一键导入持久化存储:
|
||||
```bash
|
||||
seal-use report review import reports/明细台账.xlsx --corp <corpId>
|
||||
```
|
||||
*本地存储路径:`~/.config/seal-use/state/reviews/<corpId>-<YYYY-MM>.jsonl`。*
|
||||
|
||||
---
|
||||
|
||||
### 第三阶段:纯文本深度叙述与质性洞察共创 (Qualitative Narrative Co-Authoring)
|
||||
## 六、标准 6 大章节深度剖析
|
||||
|
||||
模板中的许多章节属于管理咨询范畴,必须通过与用户沟通讨论,将模板占位符改写为客户真实的业务洞察:
|
||||
标准报告结构是严谨的商业论证闭环,每一章节均承载特定的论证目的:
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
Review["复核定性成果"] --> Sec2["§2 失准归因与整改方案"]
|
||||
Context["企业本月动态"] --> Sec1["§1.3 稳定性与迭代历程"]
|
||||
RiskData["AI 风险统计"] --> Sec3["§3 潜在风险与拦截案例"]
|
||||
HumanValue["财务反馈"] --> Sec4["§4 综合效益与人力释放"]
|
||||
```
|
||||
§1. 审核测试结果 ───► 数据底座:样本总量、AI 准确率、人工准确率公式及维恩图
|
||||
│
|
||||
§2. AI 判定误判分析 ─► 坦诚归因:剖析模型不足与漏报误报,输出规则库调优方案
|
||||
│
|
||||
§3. 潜在风险拦截 ───► 商业价值:展示 AI 额外识别并拦截的违规单(专票、大额、假凭证)
|
||||
│
|
||||
§4. 综合效益 ─────► 宏观收益:审核秒级时效提升、准确度收益与财务人力释放
|
||||
│
|
||||
§5. 分歧与复核归因 ─► 管理对策:分析人机差异根本原因,引导推动线上规则库制度沉淀
|
||||
│
|
||||
§6. 支撑数据与交付 ─► 交付落地:分模板准确率细分表,配套交付《明细台账.xlsx》
|
||||
```
|
||||
|
||||
#### 1. §1.3 系统稳定性与迭代历程
|
||||
- **模板问题**:内置模板写着死板的“自 8 月 8 日迭代后稳定在 96.07%”。
|
||||
- **研讨引导**:
|
||||
> “请问本月企业是否有上线新规则版本、更新豁免白名单,或者合思系统有单据模板调整?我们可以把具体的迭代时间节点与优化成效如实写进‘系统稳定性’一节。”
|
||||
- **改写产出**:将通用的占位文字改写为真实事件,例如:“9 月 12 日优化‘发票查重与专票强制校验规则’后,全月系统审核成功率稳定在 97.4%”。
|
||||
### 1. 标题与信息表
|
||||
- 包含报告编号(`HD001`)、企业名称、统计期间、生成日期与报告状态(`草稿` 或 `正式交付`)。
|
||||
|
||||
#### 2. §2 AI 失准深度归因与整改方案(报告核心技术价值)
|
||||
- **模板问题**:代码存在硬编码假单号(如 `B26002583`)或默认示例分类。
|
||||
- **研讨引导**:
|
||||
> “基于我们在第二阶段复核出的 X 笔 AI 真实失准(`verdict === human_correct`),主要集中在以下两个现象:
|
||||
> 1. 多附件中部分手写收据金额识别偏差(3 笔);
|
||||
> 2. 差旅补贴跨自然月计算未自动扣除周末(2 笔)。
|
||||
> 我们来总结针对这几类问题的整改建议与下月规则库优化计划。”
|
||||
- **改写产出**:
|
||||
- 彻底替换 `§2.2 ~ §2.4` 中的单号与问题描述为真实 SN 和真实原因;
|
||||
- 撰写具体的“整改建议”,如“下期将差旅补贴计算调整为按工作日日历核算”、“针对手写收据调优大模型 OCR 提示词”。
|
||||
### 2. §1 审核测试结果
|
||||
- **1.1 数据来源与样本量**:明确审计周期的起止时间、纳管模板清单及样本总量($S$)。
|
||||
- **1.2 准确率结论与维恩图**:
|
||||
- 展示核心指标:AI 依规准确率(如 $93.75\%$)、人工实际准确率(如 $87.50\%$)。
|
||||
- **准确率严密计算公式**(必须在正文中由 LaTeX 公式呈现):
|
||||
$$\text{AI 准确率} = \frac{D_1 + D_4}{S} = \frac{\text{双方同向一致通过数} + \text{AI 依规正确拦截数}}{\text{样本总量}}$$
|
||||
- 动态内嵌维恩图(`图 1:AI 与人工审核准确率对比.svg`),直观呈现两者的交集与重合度。
|
||||
|
||||
#### 3. §3 潜在风险与拦截价值业务解读
|
||||
- **业务价值**:AI 拦截了人工放行的风险单据,是向企业管理层证明“AI 审计提升内控质量”的最有力武器。
|
||||
- **研讨引导**:
|
||||
> “在人工审核通过的单据中,AI 额外拦截了 28 笔风险,其中 TOP 1 为‘无正规发票直接支付’(16 笔)。这些单据主要发生在哪些部门?我们可以结合公司的差旅/采购内控制度进行强调。”
|
||||
### 3. §2 AI 判定误判分析
|
||||
- **2.1 误判构成总览**:总结在分歧复核中判定为“人工正确 / AI 判定误判”的单据总量及在全样本中的占比。
|
||||
- **2.2~2.4 TOP 误判典型案例剖析**:
|
||||
- 提炼真实典型案例,详细分析 AI 判定失误的机理(如复杂多税率混合计算偏差、手写收据文字模糊混淆等)。
|
||||
- **针对性调优方案**:明确给出技术调优与规则优化对策(例如:升级发票 OCR 专有切片模型、增设多税率拆行核对规则)。
|
||||
|
||||
#### 4. §4 综合效益与人力释放量化
|
||||
- **质性文案润色**:与客户确认 AI 审核耗时(通常在 10~30 秒)对比财务人工审核周期(通常为 1~3 个工作日),突出“即提即审”的时效提升,以及协助财务防堵税务合规风险(如进项税虚开、专票未取等)的价值。
|
||||
### 4. §3 AI 发现的潜在风险
|
||||
- **3.1 潜在风险总览**:总结 AI 依规成功拦截的真实违规单据总量及金额。
|
||||
- **3.2~3.4 典型风险单据拦截剖析**:
|
||||
- 列举人工审批人漏审放行、但被 AI 坚决拦截的重大合规隐患(例如:专票未开具销货清单、跨期发票混报、同一发票重复报销、连号大额发票等)。
|
||||
- 证明 AI 审核在“防范税务稽查风险”与“资金合规安全”上的不可替代价值。
|
||||
|
||||
#### 5. 截图凭证指引 (Screenshots Placement)
|
||||
- 提醒用户在正式提交前,将关键凭证(如发票实物照片、审批流驳回截图)替换到报告中:
|
||||
- 将 `assets/图3-示例截图.svg` 替换为真实的代表性单据截图;
|
||||
- 将 `§6` 明细表格中的 `(截图)` 占位字样替换为具体的图片引用或在附件中打包交付。
|
||||
### 5. §4 综合效益
|
||||
- 表格化汇总四大效益维度:
|
||||
- **审核时效**:人工平均审批耗时(例如 18.5 小时)vs AI 平均秒级处理时效(例如 4.2 秒),提效超 99%;
|
||||
- **风控拦截**:全周期拦截违规单据笔数与违规金额;
|
||||
- **人力释放**:测算自动化放行单据释放的财务初审工作量。
|
||||
|
||||
### 6. §5 审核分歧与复核归因
|
||||
- **5.1 分歧原因分类表**:将全部人机分歧单归结为三大主因:
|
||||
1. *未在线配置规则(人工依据口头制度驳回)*:占比通常最高;
|
||||
2. *规则库逻辑配置缺陷(边界条件未覆盖)*;
|
||||
3. *AI 模型识别偏差*。
|
||||
- **5.2 管理优化建议**:引导企业将线下口头标准转化为线上明确规则,消除人为认知分歧。
|
||||
- **5.3 引导查验台账**:明确指引领导与操作人员查阅随包附带的《明细台账.xlsx》进行逐单核对。
|
||||
|
||||
### 7. §6 支撑数据与交付材料
|
||||
- **6.1 分模板统计表**:列出每个模板的单据量、通过率、AI 准确率与自动化放行率。
|
||||
- **6.2 交付清单**:列出报告交付套件(Markdown 源码、矢量图包、单文件 HTML、A4 PDF、明细台账 Excel)。
|
||||
|
||||
---
|
||||
|
||||
### 第四阶段:报告重新装配、严格离线校验与全格式导出 (Regenerate, Validate & Render)
|
||||
## 七、动态自适应与用户至上原则
|
||||
|
||||
1. **重新装配底稿(应用人工裁决)**:
|
||||
```bash
|
||||
seal-use report monthly --month <YYYY-MM> --corp <corpId> --out reports/<企业名>-<YYYYMM>.md --overwrite
|
||||
```
|
||||
*此时,由于本地已存在 `review-store` 裁决记录,底稿将自动完成指标闭环:人工准确率真实回填、维恩图准确渲染、分模板同意/驳回比与全量范围自动更新。*
|
||||
为了杜绝后续使用的 AI Agent 产生死板教条(如“机械凑满 3 类问题”、“非要放满 3 行表格”),特此确立以下人机协同规范:
|
||||
|
||||
2. **更新共创文本**:
|
||||
使用文件编辑工具将第三阶段共创出的 §1.3、§2、§3、§4 文本精准写入 `reports/<企业名>-<YYYYMM>.md`,替换掉模板占位内容。
|
||||
### 1. 必选骨架 vs 动态子分类
|
||||
- **大章节是不可缺少的骨架**:§1~§6 大章节承载了严密的商业论证闭环,必须完整保留。
|
||||
- **动态子分类完全由真实数据驱动**:
|
||||
- §2(误判分析)与 §3(潜在风险)下的具体问题分类,**数量完全由实际跑批数据与用户业务关注度决定**。
|
||||
- **唯一硬性底线**:动态章节下**至少保留 1 个子分类**(不能是无正文的空标题),可以是 TOP 1~2、TOP 1~3 或拓展至 TOP 1~5。
|
||||
- **数学守恒定律**:分类表中的单数之和必须严格等于「合计」行单数,且百分比之和严格等于 100%(触发 `NM001`~`NM003` 校验)。
|
||||
|
||||
3. **执行严格离线门禁校验 (Zero-Error Gate)**:
|
||||
```bash
|
||||
seal-use report validate reports/<企业名>-<YYYYMM>.md
|
||||
```
|
||||
必须确保**校验通过(`valid: true`,0 ERROR)**。若遇到报错,参考下文排查手册逐一修复。
|
||||
### 2. 用户态度为最高准则
|
||||
- Agent 必须以用户的业务判断与汇报习惯为首要输入。若用户要求“重点只突出 2 个主要风险”、“案例只放 1 个最具代表性的单据”,Agent 必须立即响应调整,绝不生搬硬套模板默认布局。
|
||||
|
||||
4. **全格式编译与打包交付 (Multi-Format Rendering)**:
|
||||
```bash
|
||||
# 一键导出自包含 HTML、超高精度长图 PNG 与 A4 PDF
|
||||
seal-use report render reports/<企业名>-<YYYYMM>.md --out build/<企业名>-<YYYYMM>
|
||||
```
|
||||
最终交付物清单:
|
||||
- `build/<企业名>-<YYYYMM>.html`:内嵌图片与 KaTeX 公式样式的单文件自包含 HTML(适合邮件与在线流转);
|
||||
- `build/<企业名>-<YYYYMM>.png`:高清晰度长图(适合飞书、微信、钉钉大图浏览);
|
||||
- `build/<企业名>-<YYYYMM>.pdf`:标准 A4 分页打印级 PDF(适合正式汇报与归档);
|
||||
- `reports/明细台账.xlsx` 与 `明细台账.csv`:审计复核完整底账。
|
||||
### 3. 表格超链接免维护契约
|
||||
- **Markdown 源码专注业务语义**:用户与 Agent 在编写或编辑 Markdown 报告草稿时,无需在表格中手写超长技术 URL。
|
||||
- **自动化升级**:管线渲染引擎会自动识别表格结构。若表格只有两列,会自动将第一列单号升级为跳转链接;若表头显式声明了 `审核详情` 列,会自动在第 3 列生成直达链接。
|
||||
|
||||
---
|
||||
|
||||
## 模板各章节深度剖析与动静边界 (Section Anatomy)
|
||||
## 八、离线门禁校验规则手册 (Zero-Error Gate)
|
||||
|
||||
| 章节编号与名称 | 数据来源与机制 | 是否需要人工协同改写 / 研讨 | 说明与关注要点 |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| **标题与报告信息表** | 动态填充 | 否(自动替换) | 自动写入企业名称、统计期间、生成日期与报告编号。 |
|
||||
| **摘要** | 动态换数 | 建议微调 | 正则自动替换总样本数、AI 准确率与风险拦截数;可根据企业汇报偏好润色开篇。 |
|
||||
| **§1.1 数据来源与范围** | 动态生成 | 否(自动替换) | 自动汇总样本总量、业务单据模板种类数与决策分布。 |
|
||||
| **§1.2 核心准确率 & 图 1** | 动态联动 | 否(自动联动) | AI 与人工准确率、公式代入值以及图 1 维恩图由底账与 review-store 动态计算联动。 |
|
||||
| **§1.3 系统稳定性** | 静态占位 | **必须研讨改写** | 采纳率自动填充,但“迭代影响”必须替换为本月真实的上线与优化历程。 |
|
||||
| **§2.1 失准构成总览** | 动态 / 模板 | **必须研讨确认** | 需确保维度单数、占比与合计严密勾稽(满足 NM001/NM003)。 |
|
||||
| **§2.2~2.4 TOP 失准案例** | 模板假数据 | **必须完全替换** | **绝对不能保留假单号**!必须填入第二阶段复核出的真实 Bad Case 与针对性整改建议。 |
|
||||
| **§3 潜在风险与拦截案例** | 动态标签 + 切片 | 建议研讨润色 | TOP 3 风险标签自动更新,明细案例可结合客户核心财务卡口进行价值解读。 |
|
||||
| **§4 综合效益 & 图 2** | 半动态 + 静态图 | 建议微调 | 时效与风险笔数自动填充;工作量价值可结合企业实际审批流转特点润色。 |
|
||||
| **§5 一致性示例 & 图 3** | 动态切片 + 占位图 | 需替换配图 | 表格可自动抽取人机一致单据,图 3 需替换为真实系统截图。 |
|
||||
| **§6 AI通过/人工驳回明细** | 动态生成 | 需补充截图 | 自动取前 10 笔分歧单及复核结论;最后一列 `(截图)` 需在交付前处理。 |
|
||||
| **§7 支撑数据与台账** | 动态生成 | 否(自动生成) | §7.1 分模板表、§7.2 配套 Excel 台账、§7.3 全量覆盖声明均由引擎全自动产出。 |
|
||||
在执行最终渲染交付前,Agent **必须**执行门禁校验命令:
|
||||
```bash
|
||||
seal-use report validate reports/审核报告.md
|
||||
```
|
||||
|
||||
若存在任何格式或数学勾稽问题,命令将以 **退出码 1** 阻断导出,并输出带有错误代码的 JSON。Agent 必须根据报错信息自主编辑修正。
|
||||
|
||||
### 门禁重点校验代码全集:
|
||||
|
||||
| 错误代码 | 校验类别 | 校验规则与触发条件 | 常见违规示例 | 正确自纠方式 |
|
||||
| :--- | :--- | :--- | :--- | :--- |
|
||||
| **`HD001`** | 标题规范 | 二级章节必须从 1 开始严格连续递增(`## 1.`, `## 2.`, ..., `## 6.`),不得跳级。 | 出现 `## 1.` 后面直接跟 `## 3.` | 修正章节编号,确保 1~6 完整递增。 |
|
||||
| **`HD002`** | 标题规范 | 三级子章节编号必须隶属于所属二级章节(如 `### 2.1`, `### 2.2`)。 | 在 `## 2.` 章节下出现 `### 3.1` | 修正三级标题序号,保持父子关系一致。 |
|
||||
| **`TB001`** | 表格格式 | 表格所有行的列数必须前后完全一致。 | 表头有 4 列,某数据行只有 3 列 | 补齐缺失的竖线 `\|` 与单元格占位。 |
|
||||
| **`TB002`** | 表格格式 | 表头行(Header)严禁带有加粗 `**` 标记。 | `\| **单号** \| **问题描述** \|` | 移除表头文字中的 `**`,改为 `\| 单号 \| 问题描述 \|`。 |
|
||||
| **`NM001`** | 数学勾稽 | 分类统计表中的各分项单张数之和,必须严格等于合计行。 | 分项分别为 3、5、2,但合计行写了 11 | 修正分项数值或合计行数值,确保加法恒等。 |
|
||||
| **`NM002`** | 数学勾稽 | 分类统计表中的百分比之和,必须严格等于 100.0%(允许 0.1% 舍入误差)。 | 各分项占比之和为 98.5% | 重新核算各分项百分比,确保相加为 100%。 |
|
||||
| **`NM003`** | 数学勾稽 | 分项百分比计算值必须与单数占比精确勾稽。 | 10 单中占 3 单,但百分比写了 40% | 修正为 `\frac{3}{10} = 30.0\%`。 |
|
||||
| **`NM004`** | 文本勾稽 | 正文中提及的误判/分歧笔数,必须与表格及公式中的笔数完全一致。 | 正文写“共发现 3 笔误判”,但表格列了 4 笔 | 统一正文措辞与表格中的单据笔数。 |
|
||||
| **`NM005`** | 公式算术 | 准确率 LaTeX 公式算术必须成立,且分子分母在正文中可溯源。 | `\frac{221}{240} = 95.00\%` (实际应为 92.08%) | 重新计算并填入真实算术结果。 |
|
||||
| **`INFO001`** | 信息完备 | 开篇信息表必须完整包含:报告编号、客户名称、统计期间、报告状态、生成日期。 | 缺失了“报告编号”行 | 在开篇信息表中补齐所缺行。 |
|
||||
| **`INFO002`** | 信息完备 | 开篇信息表中的关键字段值不得为空或保留 `待填充` 占位符。 | 统计期间写着 `YYYY-MM` | 替换为真实的业务统计区间(如 `2026-08-12 ~ 2026-09-18`)。 |
|
||||
|
||||
---
|
||||
|
||||
## 离线校验错误码排查手册 (Validator Error Code Playbook)
|
||||
## 九、全格式编译渲染与跨端交付
|
||||
|
||||
当 `seal-use report validate` 报错时,请根据以下代码快速定位:
|
||||
门禁校验通过后,使用 `report render` 即可产出全套工业级交付产物:
|
||||
|
||||
- **`NM001` / `NM002`(分类总数与小节单数勾稽不符)**:
|
||||
- 检查总览表各行单数之和是否等于“合计”行;
|
||||
- 检查总览表中的单数是否与后续 `### 2.x` 或 `### 3.x` 小节标题中的 `(N 张 / X%)` 严格一致。
|
||||
- **`NM003`(百分比算术不符)**:
|
||||
- 检查各行单数除以合计总数得出的百分比,与表格中写的百分比差距是否超过 `0.15%`。
|
||||
- **`NM004`(明细表行数与正文叙述不符)**:
|
||||
- 检查 `§6` 叙述中的 `在上述 **N 笔**单据中` 与 `依规正确(计入 D4)`、`AI 真实失准` 数量是否与下表明细行完全相等。
|
||||
- **`NM005`(公式算术错误或数值孤岛)**:
|
||||
- 检查 `$$ \text{AI 审核准确率} = \frac{A}{B} = C\% $$` 中 $A / B$ 是否算术等于 $C\%$;
|
||||
- 检查公式里的分子、分母数值是否在正文其他段落中有据可查。
|
||||
- **`TB001`(表格列数不齐)**:某一行的竖线 `|` 数量与表头不一致,或未对单元格中的 `|` 字符进行 `\|` 转义。
|
||||
- **`TB002`(表头含加粗)**:Markdown 表头行中严禁使用 `**加粗**`。
|
||||
- **`HD001` / `HD002`(标题跳级或章节编号不规范)**:
|
||||
- 二级标题必须严格按 `## 1.`, `## 2.`, ..., `## 7.` 编号;
|
||||
- 不能出现从 `#` 直接跳到 `###` 的层级跳跃。
|
||||
- **`INFO001` / `INFO002`(报告信息表缺失或字段为空)**:开篇信息表必须完整包含:报告编号、客户名称、统计期间、报告状态、生成日期。
|
||||
- **`IMG001`(图片不存在)**:引用的本地图片路径未找到,检查相对路径是否有效或文件名是否有中文编码问题。
|
||||
- **`FM001` / `MK001`(模板痕迹或 Frontmatter 残留)**:严禁出现 YAML frontmatter 或 `<!--slot:` 等模板痕迹,必须是纯净 Markdown。
|
||||
```bash
|
||||
# 一键编译全套产物(单文件 HTML、A4 PDF、超清拼接长图 PNG)
|
||||
seal-use report render reports/审核报告.md --out build/审核报告/ --format all
|
||||
|
||||
# 整包打包归档(产出 ZIP / 完整文件夹,自动收拢 Markdown、配图与明细台账)
|
||||
seal-use report export reports/审核报告.md --out build/交付整包/
|
||||
```
|
||||
|
||||
### 交付产物技术特性与适用场景:
|
||||
1. **单文件自包含 HTML (`.html`)**:
|
||||
- 所有 CSS 样式、矢量图表与字体资源全部通过 Data URI 内嵌;
|
||||
- 零网络依赖,双击即可在任何现代浏览器中完美打开浏览;
|
||||
- 内部超链接天然支持跨端点击穿透直达系统后台。
|
||||
2. **A4 打印级分页 PDF (`.pdf`)**:
|
||||
- 严格遵循 A4 物理纸张比例与分页控制(CSS `@page` 与 `break-inside: avoid`);
|
||||
- 页眉页脚清晰标注企业名称与唯一报告编号;
|
||||
- 支持高精度矢量文字缩放,适用于正式纸质打印与签字归档。
|
||||
3. **超高清拼接长图 (`.png`)**:
|
||||
- 由原生无头浏览器以 4x 视口倍率切片截取,并通过高性能图形算法在内存中无损拼接;
|
||||
- 专为钉钉、微信、飞书等移动端 IM 聊天窗口设计,方便管理层在手机上顺滑滑动审阅。
|
||||
@@ -385,6 +385,162 @@ describe("auth links", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("auth hose-openapi-token", () => {
|
||||
function setupRoot(name: string) {
|
||||
const root = mkdtempSync(join(tmpdir(), name));
|
||||
const enterprises = join(root, "enterprises");
|
||||
tempDirs.push(root);
|
||||
mkdirSync(enterprises, { recursive: true });
|
||||
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises;
|
||||
process.env.SEAL_USE_CONFIG_FILE = join(root, "config.json");
|
||||
process.env.SEAL_USE_TOKEN_STORE = join(root, "tokens.json");
|
||||
process.env.SEAL_USE_USAGE_FILE = join(root, "usage.json");
|
||||
return { root, enterprises };
|
||||
}
|
||||
|
||||
function writeHoseCorp(enterprises: string, sourceOverride: Record<string, unknown> = {}) {
|
||||
writeFileSync(
|
||||
join(enterprises, "hose-corp.json"),
|
||||
JSON.stringify({
|
||||
id: "hose-corp",
|
||||
name: "合思测试企业",
|
||||
environment: "production",
|
||||
seal: { url: "https://hose-corp.sealai.cc" },
|
||||
source: {
|
||||
type: "hose",
|
||||
domain: "https://app.ekuaibao.com",
|
||||
appKey: "key-1",
|
||||
appSecurity: "sec-1",
|
||||
corpId: "HOSE-CORP",
|
||||
staffId: "HOSE-CORP:STAFF-1",
|
||||
...sourceOverride
|
||||
},
|
||||
auth: { refreshTtl: 300 }
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
function mockGetAccessToken(counter: { count: number }, token = "fresh-openapi-token") {
|
||||
globalThis.fetch = (async (input: RequestInfo | URL) => {
|
||||
const requestUrl =
|
||||
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
||||
const url = new URL(requestUrl);
|
||||
if (url.pathname === "/api/openapi/v1/auth/getAccessToken") {
|
||||
counter.count += 1;
|
||||
return new Response(JSON.stringify({ value: { accessToken: token, expireTime: 7200 } }), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" }
|
||||
});
|
||||
}
|
||||
return new Response(JSON.stringify({ error: `Unexpected request: ${url.pathname}` }), {
|
||||
status: 404,
|
||||
headers: { "content-type": "application/json" }
|
||||
});
|
||||
}) as typeof fetch;
|
||||
}
|
||||
|
||||
test("mints a fresh OpenAPI token from persisted keys and prints it as machine JSON", async () => {
|
||||
const { enterprises } = setupRoot("seal-use-auth-openapi-token-");
|
||||
writeHoseCorp(enterprises);
|
||||
const counter = { count: 0 };
|
||||
mockGetAccessToken(counter);
|
||||
|
||||
const result = await runCli(["auth", "hose-openapi-token", "--corp", "hose-corp"]);
|
||||
|
||||
expect(result.isError).toBe(false);
|
||||
expect(counter.count).toBe(1);
|
||||
const parsed = JSON.parse(result.stdout);
|
||||
expect(parsed).toMatchObject({
|
||||
corpId: "HOSE-CORP",
|
||||
corpName: "合思测试企业",
|
||||
domain: "https://app.ekuaibao.com",
|
||||
token: "fresh-openapi-token",
|
||||
cached: false
|
||||
});
|
||||
expect(parsed.expiresAt).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+08:00$/);
|
||||
});
|
||||
|
||||
test("reuses a fresh cached token by default and mints a new one with --force", async () => {
|
||||
const { root, enterprises } = setupRoot("seal-use-auth-openapi-token-force-");
|
||||
writeHoseCorp(enterprises);
|
||||
writeFileSync(
|
||||
join(root, "tokens.json"),
|
||||
JSON.stringify({
|
||||
"hose-corp": {
|
||||
hose: {
|
||||
openapi: { token: "cached-openapi-token", expiresAt: Date.now() + 3600_000 }
|
||||
}
|
||||
}
|
||||
})
|
||||
);
|
||||
const counter = { count: 0 };
|
||||
mockGetAccessToken(counter);
|
||||
|
||||
const cachedResult = await runCli(["auth", "hose-openapi-token", "--corp", "hose-corp"]);
|
||||
expect(cachedResult.isError).toBe(false);
|
||||
expect(counter.count).toBe(0);
|
||||
const cachedParsed = JSON.parse(cachedResult.stdout);
|
||||
expect(cachedParsed).toMatchObject({ token: "cached-openapi-token", cached: true });
|
||||
expect(cachedResult.stderr).toContain("复用本地仍有效的 accessToken");
|
||||
|
||||
const forcedResult = await runCli(["auth", "openapi-token", "--corp", "hose-corp", "--force"]);
|
||||
expect(forcedResult.isError).toBe(false);
|
||||
expect(counter.count).toBe(1);
|
||||
const forcedParsed = JSON.parse(forcedResult.stdout);
|
||||
expect(forcedParsed).toMatchObject({ token: "fresh-openapi-token", cached: false });
|
||||
});
|
||||
|
||||
test("rejects a native Seal enterprise with exit code 2", async () => {
|
||||
const { enterprises } = setupRoot("seal-use-auth-openapi-token-native-");
|
||||
writeFileSync(
|
||||
join(enterprises, "native-seal.json"),
|
||||
JSON.stringify({
|
||||
id: "native-seal",
|
||||
name: "原生 Seal 企业",
|
||||
environment: "production",
|
||||
seal: { url: "https://native.seal.test", tenantSlug: "native-seal" },
|
||||
source: {
|
||||
type: "seal",
|
||||
token: "seal-token",
|
||||
sealUrl: "https://native.seal.test",
|
||||
expiresIn: 3600,
|
||||
corpId: "native-corp",
|
||||
staffId: "native-staff"
|
||||
},
|
||||
auth: { refreshTtl: 300 }
|
||||
})
|
||||
);
|
||||
const counter = { count: 0 };
|
||||
mockGetAccessToken(counter);
|
||||
|
||||
const result = await runCli(["auth", "hose-openapi-token", "--corp", "native-seal"]);
|
||||
|
||||
expect(result.isError).toBe(true);
|
||||
expect(result.exitCode).toBe(2);
|
||||
expect(result.stderr).toContain("非合思");
|
||||
expect(counter.count).toBe(0);
|
||||
});
|
||||
|
||||
test("exits 13 when the Hose enterprise has no OpenAPI credentials", async () => {
|
||||
const { enterprises } = setupRoot("seal-use-auth-openapi-token-nocreds-");
|
||||
writeHoseCorp(enterprises, {
|
||||
appKey: undefined,
|
||||
appSecurity: undefined,
|
||||
closeToken: "web-session-token",
|
||||
expiresAt: "2099-01-01T00:00:00+08:00"
|
||||
});
|
||||
const counter = { count: 0 };
|
||||
mockGetAccessToken(counter);
|
||||
|
||||
const result = await runCli(["auth", "hose-openapi-token", "--corp", "hose-corp"]);
|
||||
|
||||
expect(result.isError).toBe(true);
|
||||
expect(result.exitCode).toBe(13);
|
||||
expect(result.stderr).toContain("缺少合思凭证");
|
||||
expect(counter.count).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
function restoreEnv(name: string, value: string | undefined) {
|
||||
if (value === undefined) delete process.env[name];
|
||||
else process.env[name] = value;
|
||||
|
||||
@@ -1,7 +1,14 @@
|
||||
import { assertHoseAssistTenantMatches, exchangeHoseAssistLink, getHoseProvisionalAuthLink } from "../../core/auth/hose.js";
|
||||
import {
|
||||
assertHoseAssistTenantMatches,
|
||||
exchangeHoseAssistLink,
|
||||
getHoseOpenapiToken,
|
||||
getHoseProvisionalAuthLink,
|
||||
normalizeBaseUrl
|
||||
} from "../../core/auth/hose.js";
|
||||
import { clearCorpTokenCache } from "../../core/auth/token-store.js";
|
||||
import { formatBeijingIso } from "../../core/config/timestamps.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import { CliError, validationError } 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";
|
||||
@@ -147,6 +154,44 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
action === "hose-openapi-token" ||
|
||||
action === "openapi-token" ||
|
||||
action === "hose-token"
|
||||
) {
|
||||
if (corp.source.type !== "hose") {
|
||||
throw new CliError(
|
||||
`【合思专享能力】当前企业「${corp.name}」(id: ${corp.id}) 为原生 Seal (${corp.source.type}) 租户,非合思 (Hose/合思云/易快报) 渠道企业。\n` +
|
||||
"OpenAPI accessToken 签发能力专属于合思生态租户(使用持久化的 appKey/appSecurity 向合思 OpenAPI 换取 token),非合思渠道企业不支持此命令。",
|
||||
2
|
||||
);
|
||||
}
|
||||
const appKey = corp.source.appKey ?? corp.source.key;
|
||||
const appSecurity = corp.source.appSecurity ?? corp.source.password;
|
||||
if (!appKey || !appSecurity) {
|
||||
throw validationError(
|
||||
`缺少合思凭证:企业「${corp.name}」(id: ${corp.id}) 未配置 appKey/appSecurity(或 key/password),无法向合思 OpenAPI 签发 accessToken。`
|
||||
);
|
||||
}
|
||||
const force =
|
||||
booleanOption(args.options.force) === true ||
|
||||
booleanOption(args.options.refresh) === true ||
|
||||
booleanOption(args.options.f) === true;
|
||||
const entry = await getHoseOpenapiToken(corp, { force });
|
||||
if (entry.cached) {
|
||||
console.error("ℹ️ [合思 OpenAPI] 复用本地仍有效的 accessToken 缓存,追加 --force 可强制签发全新 token。");
|
||||
}
|
||||
printJson({
|
||||
corpId: corp.source.corpId ?? corp.id,
|
||||
corpName: corp.name,
|
||||
domain: normalizeBaseUrl(corp.source.domain),
|
||||
token: entry.token,
|
||||
expiresAt: formatBeijingIso(entry.expiresAt),
|
||||
cached: entry.cached
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "keys" || action === "hose-keys") {
|
||||
const reveal =
|
||||
booleanOption(args.options.reveal) === true ||
|
||||
|
||||
@@ -0,0 +1,580 @@
|
||||
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 { classifyCliError } from "../../core/errors.js";
|
||||
import { parseArgs } from "../parser.js";
|
||||
import { handleHoseEbotCommand } from "./hose-ebot.js";
|
||||
|
||||
const ORIGINAL_ENV = {
|
||||
tokenStore: process.env.SEAL_USE_TOKEN_STORE,
|
||||
usageFile: process.env.SEAL_USE_USAGE_FILE
|
||||
};
|
||||
const ORIGINAL_FETCH = globalThis.fetch;
|
||||
const ORIGINAL_LOG = console.log;
|
||||
const ORIGINAL_ERROR = console.error;
|
||||
|
||||
let tempDir: string | undefined;
|
||||
|
||||
beforeEach(() => {
|
||||
tempDir = mkdtempSync(join(tmpdir(), "seal-use-hose-ebot-area-"));
|
||||
process.env.SEAL_USE_TOKEN_STORE = join(tempDir, "tokens.json");
|
||||
process.env.SEAL_USE_USAGE_FILE = join(tempDir, "usage.json");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
restoreEnv("SEAL_USE_TOKEN_STORE", ORIGINAL_ENV.tokenStore);
|
||||
restoreEnv("SEAL_USE_USAGE_FILE", ORIGINAL_ENV.usageFile);
|
||||
globalThis.fetch = ORIGINAL_FETCH;
|
||||
console.log = ORIGINAL_LOG;
|
||||
console.error = ORIGINAL_ERROR;
|
||||
if (tempDir) {
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
tempDir = undefined;
|
||||
}
|
||||
});
|
||||
|
||||
function restoreEnv(name: string, value: string | undefined) {
|
||||
if (value === undefined) delete process.env[name];
|
||||
else process.env[name] = value;
|
||||
}
|
||||
|
||||
const hoseCorp = CorpConfigSchema.parse({
|
||||
id: "hose-ebot",
|
||||
name: "合思 EBot 测试企业",
|
||||
environment: "test",
|
||||
seal: { url: "https://hose-ebot.sealai.cc" },
|
||||
source: {
|
||||
type: "hose",
|
||||
domain: "https://app.ekuaibao.com",
|
||||
appKey: "key-1",
|
||||
appSecurity: "sec-1",
|
||||
closeToken: "web-session-token",
|
||||
corpId: "ID01LG7ksGroB1",
|
||||
staffId: "ID01LG7ksGroB1:ID01KsDgHaH5nN"
|
||||
}
|
||||
});
|
||||
|
||||
const hoseCorpNoOpenApiCredentials = CorpConfigSchema.parse({
|
||||
...hoseCorp,
|
||||
id: "hose-ebot-nocreds",
|
||||
source: {
|
||||
type: "hose",
|
||||
domain: "https://app.ekuaibao.com",
|
||||
closeToken: "web-session-token",
|
||||
corpId: "ID01LG7ksGroB1",
|
||||
staffId: "ID01LG7ksGroB1:ID01KsDgHaH5nN"
|
||||
}
|
||||
});
|
||||
|
||||
const sealCorp = CorpConfigSchema.parse({
|
||||
id: "seal-ebot",
|
||||
name: "原生 Seal 企业",
|
||||
environment: "test",
|
||||
seal: { url: "https://seal.test", endpoints: { approvalStylePreferences: "api/custom/preferences" } },
|
||||
source: {
|
||||
type: "seal",
|
||||
sealUrl: "https://seal.test",
|
||||
token: "mock-token",
|
||||
staffId: "seal-staff",
|
||||
corpId: "seal-corp"
|
||||
}
|
||||
});
|
||||
|
||||
const messageFixture = {
|
||||
items: [
|
||||
{
|
||||
id: "ID01Vj4Zq1Lytp",
|
||||
messageName: "希尔顿Seal AI审核1",
|
||||
messageType: "flow",
|
||||
enable: true,
|
||||
signKey: "Q4H15lpixMyE7secretvalue",
|
||||
callbackUrl: "https://sealai.cc/api/hosecloud/outbound?config_id=Q4H15lpixMyE7secretvalue",
|
||||
corporationId: "ID01LG7ksGroB1",
|
||||
actionEvent: ["backlog.processed"],
|
||||
formFields: ["action", "flowId", "nodeId"]
|
||||
},
|
||||
{
|
||||
id: "ID01Vj4VDa8CGH",
|
||||
messageName: "完成回调",
|
||||
messageType: "message",
|
||||
enable: false,
|
||||
signKey: "Q4H15lpixOtherSecret",
|
||||
callbackUrl: "https://sealai.cc/api/hosecloud/complete",
|
||||
corporationId: "ID01LG7ksGroB1",
|
||||
actionEvent: ["flow.completed"]
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
const logFixture = {
|
||||
items: [
|
||||
{
|
||||
id: "log-1",
|
||||
name: "出站调用",
|
||||
type: "INVOKING",
|
||||
state: "SUCCESS",
|
||||
createTime: 1727764000000,
|
||||
flowId: { id: "FLOW-1", form: { code: "SN123" } },
|
||||
nodeName: "AI 审核节点",
|
||||
request: {
|
||||
flowId: "FLOW-1",
|
||||
nodeId: "NODE-1",
|
||||
messageId: "MSG-1",
|
||||
rejectionNum: 0
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "log-2",
|
||||
name: "审批回调",
|
||||
type: "CALLBACK",
|
||||
state: "SUCCESS",
|
||||
createTime: 1727764010000,
|
||||
flowId: { id: "FLOW-1", form: { code: "SN123" } },
|
||||
nodeName: "AI 审核节点",
|
||||
request: {
|
||||
flowId: "FLOW-1",
|
||||
nodeId: "NODE-1",
|
||||
signKey: "Q4H15lpixMyE7secretvalue",
|
||||
action: "accept",
|
||||
comment: "AI 审核通过"
|
||||
}
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
function mockFetch(responses: {
|
||||
messages?: unknown;
|
||||
logs?: unknown;
|
||||
token?: unknown;
|
||||
approval?: unknown;
|
||||
}) {
|
||||
const record: {
|
||||
calls: number;
|
||||
messageUrl?: string;
|
||||
logUrl?: string;
|
||||
logBody?: unknown;
|
||||
tokenUrl?: string;
|
||||
tokenBody?: unknown;
|
||||
approvalUrl?: string;
|
||||
approvalBody?: unknown;
|
||||
} = { calls: 0 };
|
||||
|
||||
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
record.calls++;
|
||||
const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : (input as Request).url;
|
||||
let bodyText: string | undefined;
|
||||
if (init?.body) {
|
||||
bodyText = String(init.body);
|
||||
} else if (input && typeof input === "object" && "clone" in input) {
|
||||
bodyText = await (input as Request).clone().text().catch(() => undefined);
|
||||
}
|
||||
|
||||
if (url.includes("/api/outbound/v1/message/messageLog")) {
|
||||
record.logUrl = url;
|
||||
record.logBody = bodyText ? JSON.parse(bodyText) : undefined;
|
||||
return new Response(JSON.stringify(responses.logs ?? logFixture), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" }
|
||||
});
|
||||
}
|
||||
|
||||
if (url.includes("/api/outbound/v1/message")) {
|
||||
record.messageUrl = url;
|
||||
return new Response(JSON.stringify(responses.messages ?? messageFixture), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" }
|
||||
});
|
||||
}
|
||||
|
||||
if (url.includes("/api/openapi/v1/auth/getAccessToken") || url.includes("/api/openapi/v1/accessToken")) {
|
||||
record.tokenUrl = url;
|
||||
record.tokenBody = bodyText ? JSON.parse(bodyText) : undefined;
|
||||
return new Response(
|
||||
JSON.stringify(responses.token ?? { accessToken: "live-openapi-token" }),
|
||||
{ status: 200, headers: { "content-type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
if (url.includes("/api/openapi/v1/approval")) {
|
||||
record.approvalUrl = url;
|
||||
record.approvalBody = bodyText ? JSON.parse(bodyText) : undefined;
|
||||
const resp = responses.approval ?? { value: { code: "204", message: "EBot执行完成" } };
|
||||
return new Response(JSON.stringify(resp), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" }
|
||||
});
|
||||
}
|
||||
|
||||
return new Response(JSON.stringify({ error: "unexpected url", url }), { status: 500 });
|
||||
}) as typeof fetch;
|
||||
|
||||
return record;
|
||||
}
|
||||
|
||||
function fakeClient(integrations: Array<Record<string, unknown>> = []) {
|
||||
return {
|
||||
get: async () => ({
|
||||
json: async () => ({ integrations })
|
||||
})
|
||||
} as unknown as KyInstance;
|
||||
}
|
||||
|
||||
async function callHoseEbot(client: KyInstance, corp: typeof hoseCorp, argv: string[]) {
|
||||
const lines: string[] = [];
|
||||
console.log = (line: string) => lines.push(String(line));
|
||||
console.error = () => {};
|
||||
const args = parseArgs(argv);
|
||||
await handleHoseEbotCommand(args.command[1], args.command[2], client, corp, args);
|
||||
return JSON.parse(lines.join("\n")) as Record<string, unknown>;
|
||||
}
|
||||
|
||||
async function captureError(action: () => Promise<unknown>): Promise<unknown> {
|
||||
try {
|
||||
await action();
|
||||
} catch (error) {
|
||||
return error;
|
||||
}
|
||||
throw new Error("expected action to throw, but it succeeded");
|
||||
}
|
||||
|
||||
describe("hose-ebot messages", () => {
|
||||
test("lists configured outbound messages with a masked signKey by default", async () => {
|
||||
const record = mockFetch({});
|
||||
const output = await callHoseEbot(fakeClient(), hoseCorp, ["hose-ebot", "messages"]);
|
||||
|
||||
expect(output.count).toBe(2);
|
||||
expect(record.messageUrl).toContain("corpId=ID01LG7ksGroB1");
|
||||
const messages = output.messages as Array<Record<string, unknown>>;
|
||||
expect(messages[0]).toMatchObject({
|
||||
id: "ID01Vj4Zq1Lytp",
|
||||
messageName: "希尔顿Seal AI审核1",
|
||||
messageType: "flow",
|
||||
enable: true
|
||||
});
|
||||
// maskHoseSecurity keeps the first 8 and last 4 characters.
|
||||
expect(messages[0]!.signKey).toBe("Q4H15lpi...alue");
|
||||
expect(messages[0]!.signKey).not.toBe("Q4H15lpixMyE7secretvalue");
|
||||
expect(messages[0]!.callbackUrl).toContain("config_id=Q4H15lpixMyE7secretvalue");
|
||||
expect(output.revealed).toBe(false);
|
||||
});
|
||||
|
||||
test("filters by type and reveals the signKey with --reveal", async () => {
|
||||
mockFetch({});
|
||||
const output = await callHoseEbot(fakeClient(), hoseCorp, [
|
||||
"hose-ebot", "messages", "--type", "flow", "--reveal"
|
||||
]);
|
||||
|
||||
expect(output.count).toBe(1);
|
||||
expect(output.revealed).toBe(true);
|
||||
const messages = output.messages as Array<Record<string, unknown>>;
|
||||
expect(messages).toHaveLength(1);
|
||||
expect(messages[0]!.signKey).toBe("Q4H15lpixMyE7secretvalue");
|
||||
});
|
||||
|
||||
test("rejects a non-Hose enterprise with exit code 13", async () => {
|
||||
const record = mockFetch({});
|
||||
const error = await captureError(() =>
|
||||
callHoseEbot(fakeClient(), sealCorp, ["hose-ebot", "messages"])
|
||||
);
|
||||
expect(classifyCliError(error).exitCode).toBe(13);
|
||||
expect(record.calls).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("hose-ebot search", () => {
|
||||
test("requires an SN and lists records with their unique ids", async () => {
|
||||
const usageError = await captureError(() =>
|
||||
callHoseEbot(fakeClient(), hoseCorp, ["hose-ebot", "search"])
|
||||
);
|
||||
expect(classifyCliError(usageError).exitCode).toBe(2);
|
||||
|
||||
const record = mockFetch({});
|
||||
const output = await callHoseEbot(fakeClient(), hoseCorp, [
|
||||
"hose-ebot", "search", "SN123", "--limit", "5"
|
||||
]);
|
||||
|
||||
expect(output.count).toBe(2);
|
||||
expect(output.sn).toBe("SN123");
|
||||
expect(output.type).toBe("all");
|
||||
expect(record.logBody).toMatchObject({
|
||||
limit: { start: 0, count: 5 },
|
||||
filterBy: '(flowId.form.code==("SN123"))'
|
||||
});
|
||||
const records = output.records as Array<Record<string, unknown>>;
|
||||
expect(records[0]).toMatchObject({ id: "log-1", type: "INVOKING" });
|
||||
expect((records[0]!.request as Record<string, unknown>).nodeId).toBe("NODE-1");
|
||||
// Callback records embed signKey; masked unless --reveal.
|
||||
expect((records[1]!.request as Record<string, unknown>).signKey).not.toBe(
|
||||
"Q4H15lpixMyE7secretvalue"
|
||||
);
|
||||
});
|
||||
|
||||
test("filters to invoking or callback records with --type", async () => {
|
||||
const record = mockFetch({});
|
||||
const output = await callHoseEbot(fakeClient(), hoseCorp, [
|
||||
"hose-ebot", "search", "SN123", "--type", "callback"
|
||||
]);
|
||||
|
||||
expect(output.type).toBe("callback");
|
||||
expect(output.count).toBe(1);
|
||||
const records = output.records as Array<Record<string, unknown>>;
|
||||
expect(records[0]!.type).toBe("CALLBACK");
|
||||
// The client-side filter over-fetches first so the page stays full.
|
||||
expect(record.logBody).toMatchObject({ limit: { start: 0, count: 80 } });
|
||||
|
||||
// Also accepts uppercase --type CALLBACK
|
||||
const outputUpper = await callHoseEbot(fakeClient(), hoseCorp, [
|
||||
"hose-ebot", "search", "SN123", "--type", "CALLBACK"
|
||||
]);
|
||||
expect(outputUpper.count).toBe(1);
|
||||
});
|
||||
|
||||
test("reveals the record signKey with --reveal", async () => {
|
||||
mockFetch({});
|
||||
const output = await callHoseEbot(fakeClient(), hoseCorp, [
|
||||
"hose-ebot", "search", "SN123", "--reveal"
|
||||
]);
|
||||
const records = output.records as Array<Record<string, unknown>>;
|
||||
expect((records[1]!.request as Record<string, unknown>).signKey).toBe(
|
||||
"Q4H15lpixMyE7secretvalue"
|
||||
);
|
||||
});
|
||||
|
||||
test("rejects an unknown verb with exit code 2", async () => {
|
||||
const error = await captureError(() => callHoseEbot(fakeClient(), hoseCorp, ["hose-ebot", "banana"]));
|
||||
expect(classifyCliError(error).exitCode).toBe(2);
|
||||
expect(String((error as Error).message)).toContain("Unknown hose-ebot command");
|
||||
});
|
||||
});
|
||||
|
||||
describe("hose-ebot callback", () => {
|
||||
const callbackArgv = (extra: string[] = []) => [
|
||||
"hose-ebot", "callback",
|
||||
"--flow-id", "FLOW-1",
|
||||
"--node-id", "NODE-1",
|
||||
"--action", "accept",
|
||||
"--comment", "同意",
|
||||
...extra
|
||||
];
|
||||
|
||||
test("refuses to run without --yes/--confirm before any network call", async () => {
|
||||
const record = mockFetch({});
|
||||
const error = await captureError(() =>
|
||||
callHoseEbot(fakeClient(), hoseCorp, callbackArgv(["--sign-key", "sig-1"]))
|
||||
);
|
||||
expect(classifyCliError(error).exitCode).toBe(10);
|
||||
expect(record.calls).toBe(0);
|
||||
expect(classifyCliError(error).nextAction).toContain("seal-use hose-ebot callback");
|
||||
});
|
||||
|
||||
test("previews a masked payload with --dry-run without minting a token", async () => {
|
||||
const record = mockFetch({});
|
||||
const output = await callHoseEbot(fakeClient(), hoseCorp, [
|
||||
...callbackArgv(["--sign-key", "sig-1", "--dry-run"])
|
||||
]);
|
||||
|
||||
expect(output.preview).toBe(true);
|
||||
expect(output.endpoint).toBe("https://app.ekuaibao.com/api/openapi/v1/approval");
|
||||
const payload = output.payload as Record<string, unknown>;
|
||||
expect(payload).toMatchObject({
|
||||
flowId: "FLOW-1",
|
||||
nodeId: "NODE-1",
|
||||
action: "accept",
|
||||
comment: "同意"
|
||||
});
|
||||
expect(payload.signKey).not.toBe("sig-1");
|
||||
expect(record.calls).toBe(0);
|
||||
});
|
||||
|
||||
test("mints a fresh accessToken and posts the callback on a confirmed run", async () => {
|
||||
const record = mockFetch({});
|
||||
const output = await callHoseEbot(fakeClient(), hoseCorp, callbackArgv([
|
||||
"--sign-key", "sig-1",
|
||||
"--yes"
|
||||
]));
|
||||
|
||||
expect(output).toMatchObject({
|
||||
ok: true,
|
||||
code: "204",
|
||||
message: "EBot执行完成",
|
||||
flowId: "FLOW-1",
|
||||
nodeId: "NODE-1",
|
||||
action: "accept"
|
||||
});
|
||||
expect(record.approvalUrl).toContain("/api/openapi/v1/approval");
|
||||
expect(record.approvalUrl).toContain("accessToken=live-openapi-token");
|
||||
expect(record.approvalBody).toMatchObject({
|
||||
signKey: "sig-1",
|
||||
flowId: "FLOW-1",
|
||||
nodeId: "NODE-1",
|
||||
action: "accept",
|
||||
comment: "同意"
|
||||
});
|
||||
});
|
||||
|
||||
test("normalizes action aliases like agree/approve/reject", async () => {
|
||||
const record = mockFetch({});
|
||||
await callHoseEbot(fakeClient(), hoseCorp, [
|
||||
"hose-ebot", "callback",
|
||||
"--sign-key", "sig-1",
|
||||
"--flow-id", "FLOW-1",
|
||||
"--node-id", "NODE-1",
|
||||
"--action", "agree",
|
||||
"--comment", "口语化同意",
|
||||
"--yes"
|
||||
]);
|
||||
expect(record.approvalBody).toMatchObject({ action: "accept" });
|
||||
|
||||
await callHoseEbot(fakeClient(), hoseCorp, [
|
||||
"hose-ebot", "callback",
|
||||
"--sign-key", "sig-1",
|
||||
"--flow-id", "FLOW-1",
|
||||
"--node-id", "NODE-1",
|
||||
"--action", "reject",
|
||||
"--comment", "口语化驳回",
|
||||
"--yes"
|
||||
]);
|
||||
expect(record.approvalBody).toMatchObject({ action: "refuse" });
|
||||
});
|
||||
|
||||
test("passes optional callback fields through to the wire payload with camelCase support", async () => {
|
||||
const record = mockFetch({});
|
||||
await callHoseEbot(fakeClient(), hoseCorp, [
|
||||
"hose-ebot", "callback",
|
||||
"--sign-key", "sig-1",
|
||||
"--flow-id", "FLOW-1",
|
||||
"--node-id", "NODE-1",
|
||||
"--action", "refuse",
|
||||
"--comment", "驳回",
|
||||
"--policy", "ALL",
|
||||
"--addApproverIds", "staff-1,staff-2",
|
||||
"--rejectTo", "NODE-0",
|
||||
"--resubmitMethod", "TO_REJECTOR",
|
||||
"--yes"
|
||||
]);
|
||||
|
||||
expect(record.approvalBody).toMatchObject({
|
||||
action: "refuse",
|
||||
policy: "ALL",
|
||||
addApproverIds: ["staff-1", "staff-2"],
|
||||
rejectTo: "NODE-0",
|
||||
resubmitMethod: "TO_REJECTOR"
|
||||
});
|
||||
});
|
||||
|
||||
test("resolves signKey from the sole Seal integration when --sign-key is omitted", async () => {
|
||||
const record = mockFetch({});
|
||||
const client = fakeClient([
|
||||
{ type: "hosecloud", signKey: "integrated-key", outboundName: "AI review", mode: "assisted" }
|
||||
]);
|
||||
await callHoseEbot(client, hoseCorp, callbackArgv(["--yes"]));
|
||||
expect(record.approvalBody).toMatchObject({ signKey: "integrated-key" });
|
||||
});
|
||||
|
||||
test("maps upstream business codes to exit codes and references hose-ebot messages", async () => {
|
||||
mockFetch({ approval: { value: { code: "401", message: "签名秘钥错误" } } });
|
||||
const error401 = await captureError(() =>
|
||||
callHoseEbot(fakeClient(), hoseCorp, callbackArgv(["--sign-key", "sig-1", "--yes"]))
|
||||
);
|
||||
expect(classifyCliError(error401).exitCode).toBe(11);
|
||||
expect(String((error401 as Error).message)).toContain("seal-use hose-ebot messages --reveal");
|
||||
|
||||
mockFetch({ approval: { value: { code: "412", message: "当前的审批节点不为: xxx,请检查" } } });
|
||||
const error412 = await captureError(() =>
|
||||
callHoseEbot(fakeClient(), hoseCorp, callbackArgv(["--sign-key", "sig-1", "--yes"]))
|
||||
);
|
||||
expect(classifyCliError(error412).exitCode).toBe(1);
|
||||
expect(String((error412 as Error).message)).toContain("seal-use hose-ebot search");
|
||||
|
||||
mockFetch({ approval: { value: { code: "400", message: "请求参数错误" } } });
|
||||
const error400 = await captureError(() =>
|
||||
callHoseEbot(fakeClient(), hoseCorp, callbackArgv(["--sign-key", "sig-1", "--yes"]))
|
||||
);
|
||||
expect(classifyCliError(error400).exitCode).toBe(13);
|
||||
});
|
||||
|
||||
test("validates preAdd and aftAdd approver and policy requirements before network call", async () => {
|
||||
const record = mockFetch({});
|
||||
const preAddError = await captureError(() =>
|
||||
callHoseEbot(
|
||||
fakeClient(),
|
||||
hoseCorp,
|
||||
callbackArgv(["--action", "preAdd", "--sign-key", "sig-1", "--yes"])
|
||||
)
|
||||
);
|
||||
expect(classifyCliError(preAddError).exitCode).toBe(13);
|
||||
expect(String((preAddError as Error).message)).toContain("必须通过 --add-approver-ids 指定加签审批人");
|
||||
expect(record.calls).toBe(0);
|
||||
|
||||
const aftAddPolicyError = await captureError(() =>
|
||||
callHoseEbot(
|
||||
fakeClient(),
|
||||
hoseCorp,
|
||||
callbackArgv([
|
||||
"--action",
|
||||
"aftAdd",
|
||||
"--add-approver-ids",
|
||||
"user1,user2",
|
||||
"--sign-key",
|
||||
"sig-1",
|
||||
"--yes"
|
||||
])
|
||||
)
|
||||
);
|
||||
expect(classifyCliError(aftAddPolicyError).exitCode).toBe(13);
|
||||
expect(String((aftAddPolicyError as Error).message)).toContain("必须指定会签方式 --policy ALL");
|
||||
expect(record.calls).toBe(0);
|
||||
});
|
||||
|
||||
test("normalizes lowercase policy and kebab-case resubmit-method", async () => {
|
||||
const record = mockFetch({
|
||||
approval: { value: { code: "204", message: "success" } }
|
||||
});
|
||||
|
||||
await callHoseEbot(
|
||||
fakeClient(),
|
||||
hoseCorp,
|
||||
callbackArgv([
|
||||
"--action",
|
||||
"aftAdd",
|
||||
"--add-approver-ids",
|
||||
"user1,user2",
|
||||
"--policy",
|
||||
"all",
|
||||
"--resubmit-method",
|
||||
"from-start",
|
||||
"--sign-key",
|
||||
"sig-1",
|
||||
"--yes"
|
||||
])
|
||||
);
|
||||
expect(record.approvalBody).toMatchObject({
|
||||
action: "aftAdd",
|
||||
addApproverIds: ["user1", "user2"],
|
||||
policy: "ALL",
|
||||
resubmitMethod: "FROM_START"
|
||||
});
|
||||
});
|
||||
|
||||
test("rejects a non-Hose enterprise with exit code 13", async () => {
|
||||
const record = mockFetch({});
|
||||
const error = await captureError(() =>
|
||||
callHoseEbot(fakeClient(), sealCorp, callbackArgv(["--sign-key", "sig-1", "--yes"]))
|
||||
);
|
||||
expect(classifyCliError(error).exitCode).toBe(13);
|
||||
expect(record.calls).toBe(0);
|
||||
});
|
||||
|
||||
test("exits 13 when the Hose enterprise has no OpenAPI credentials", async () => {
|
||||
const record = mockFetch({});
|
||||
const error = await captureError(() =>
|
||||
callHoseEbot(fakeClient(), hoseCorpNoOpenApiCredentials, callbackArgv(["--sign-key", "sig-1", "--yes"]))
|
||||
);
|
||||
expect(classifyCliError(error).exitCode).toBe(13);
|
||||
expect(String((error as Error).message)).toContain("缺少合思凭证");
|
||||
expect(record.calls).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,125 @@
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import type { createSealClient } from "../../core/http/factory.js";
|
||||
import { CliError } from "../errors.js";
|
||||
import { runCapability } from "../helpers.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import { outputOptions } from "../printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
|
||||
const USAGE =
|
||||
"Usage:\n" +
|
||||
" seal-use hose-ebot search <sn> [--type invoking|callback] [--limit <n>] [--reveal] [--corp <corpId>]\n" +
|
||||
" seal-use hose-ebot messages [--type flow|message] [--reveal] [--corp <corpId>]\n" +
|
||||
" seal-use hose-ebot callback --flow-id <flowId> --node-id <nodeId> --action <accept|refuse|preAdd|aftAdd> --comment <审批意见> [--sign-key <key>] [--dry-run] [--yes|--confirm] [--corp <corpId>]";
|
||||
|
||||
function normalizeEbotAction(raw: string | undefined): string | undefined {
|
||||
if (!raw) return undefined;
|
||||
const lower = raw.trim().toLowerCase();
|
||||
if (lower === "accept" || lower === "agree" || lower === "approve") return "accept";
|
||||
if (lower === "refuse" || lower === "reject") return "refuse";
|
||||
if (lower === "preadd" || lower === "pre-add") return "preAdd";
|
||||
if (lower === "aftadd" || lower === "aft-add" || lower === "postadd" || lower === "post-add") return "aftAdd";
|
||||
return raw;
|
||||
}
|
||||
|
||||
function normalizeEbotPolicy(raw: string | undefined): "ALL" | "ANY" | undefined {
|
||||
if (!raw) return undefined;
|
||||
const upper = raw.trim().toUpperCase();
|
||||
if (upper === "ALL" || upper === "ANY") return upper;
|
||||
return raw as "ALL" | "ANY";
|
||||
}
|
||||
|
||||
function normalizeResubmitMethod(raw: string | undefined): "FROM_START" | "TO_REJECTOR" | undefined {
|
||||
if (!raw) return undefined;
|
||||
const norm = raw.trim().toUpperCase().replace(/-/g, "_");
|
||||
if (norm === "FROM_START" || norm === "TO_REJECTOR") return norm;
|
||||
return raw as "FROM_START" | "TO_REJECTOR";
|
||||
}
|
||||
|
||||
/**
|
||||
* First-level `seal-use hose-ebot` surface for the Hose EBot outbound & callback loop:
|
||||
* search is the default entry (discover records by document SN), `messages`
|
||||
* discovers outbound message configs and their signKey, and `callback` runs
|
||||
* the approval callback.
|
||||
*/
|
||||
export async function handleHoseEbotCommand(
|
||||
action: string | undefined,
|
||||
maybeName: string | undefined,
|
||||
client: Awaited<ReturnType<typeof createSealClient>>,
|
||||
corp: CorpConfig,
|
||||
args: ParsedArgs
|
||||
) {
|
||||
if (!action) {
|
||||
throw new CliError(USAGE, 2);
|
||||
}
|
||||
|
||||
if (action === "search") {
|
||||
const sn = maybeName ?? stringOption(args.options.sn);
|
||||
if (!sn) {
|
||||
throw new CliError(`Missing document SN.\n\n${USAGE}`, 2);
|
||||
}
|
||||
const rawType = stringOption(args.options.type)?.trim().toLowerCase();
|
||||
await runCapability(
|
||||
"sealHoseOutboundSearch",
|
||||
client,
|
||||
corp,
|
||||
{
|
||||
sn,
|
||||
type: rawType,
|
||||
limit: numberOption(args.options.limit),
|
||||
reveal: booleanOption(args.options.reveal) === true || booleanOption(args.options.r) === true
|
||||
},
|
||||
outputOptions(args.options)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "messages") {
|
||||
const rawType = stringOption(args.options.type)?.trim().toLowerCase();
|
||||
await runCapability(
|
||||
"sealHoseOutboundMessages",
|
||||
client,
|
||||
corp,
|
||||
{
|
||||
reveal: booleanOption(args.options.reveal) === true || booleanOption(args.options.r) === true,
|
||||
type: rawType
|
||||
},
|
||||
outputOptions(args.options)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "callback") {
|
||||
const addApproverIdsRaw =
|
||||
stringOption(args.options["add-approver-ids"]) ?? stringOption(args.options.addApproverIds);
|
||||
await runCapability(
|
||||
"sealHoseApprovalCallback",
|
||||
client,
|
||||
corp,
|
||||
{
|
||||
signKey: stringOption(args.options.signKey) ?? stringOption(args.options["sign-key"]),
|
||||
flowId: stringOption(args.options.flowId) ?? stringOption(args.options["flow-id"]),
|
||||
nodeId: stringOption(args.options.nodeId) ?? stringOption(args.options["node-id"]),
|
||||
action: normalizeEbotAction(stringOption(args.options.action)),
|
||||
comment: stringOption(args.options.comment),
|
||||
policy: normalizeEbotPolicy(stringOption(args.options.policy)),
|
||||
addApproverIds: addApproverIdsRaw
|
||||
? addApproverIdsRaw.split(",").map((id) => id.trim()).filter(Boolean)
|
||||
: undefined,
|
||||
rejectTo: stringOption(args.options["reject-to"]) ?? stringOption(args.options.rejectTo),
|
||||
resubmitMethod: normalizeResubmitMethod(
|
||||
stringOption(args.options["resubmit-method"]) ?? stringOption(args.options.resubmitMethod)
|
||||
),
|
||||
dryRun: booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]),
|
||||
confirm: booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true
|
||||
},
|
||||
outputOptions(args.options)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
throw new CliError(
|
||||
`Unknown hose-ebot command: ${action}. Available: search, messages, callback. Run 'seal-use hose-ebot --help' for usage.`,
|
||||
2
|
||||
);
|
||||
}
|
||||
+188
-26
@@ -16,12 +16,29 @@ import {
|
||||
loadReviews,
|
||||
reviewFilePath,
|
||||
writeReview,
|
||||
type MonthlyReportResult
|
||||
type MonthlyReportResult,
|
||||
buildReportLedgerCsv,
|
||||
buildReportLedgerXlsx,
|
||||
loadReportDataFromLedger,
|
||||
collectReportData,
|
||||
type ReportData
|
||||
} from "../../domains/seal/reports/index.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
|
||||
/** Tenant-free commands: dispatch these before resolving enterprise configuration or authentication. */
|
||||
export async function handleLocalReportCommand(action: "validate" | "render" | "export" | "template" | "chart", args: ParsedArgs) {
|
||||
export async function handleLocalReportCommand(action: string | undefined, args: ParsedArgs) {
|
||||
if (Boolean(args.options.ledger) || action === "review") {
|
||||
const corpId = stringOption(args.options.corp) ?? stringOption(args.options.corpId) ?? "local-ledger";
|
||||
const corp = {
|
||||
corpId,
|
||||
id: corpId,
|
||||
name: corpId,
|
||||
corpName: corpId,
|
||||
source: { source: "seal", sealUrl: "" }
|
||||
} as unknown as CorpConfig;
|
||||
await handleReportCommand(action, {} as any, corp, args);
|
||||
return;
|
||||
}
|
||||
if (action === "template") {
|
||||
const out = stringOption(args.options.out) ?? stringOption(args.options.o);
|
||||
if (out) {
|
||||
@@ -78,45 +95,166 @@ export async function handleLocalReportCommand(action: "validate" | "render" | "
|
||||
if (!result.validation.valid) throw new CliError("报告校验未通过,未生成渲染产物。请按 validation.issues 修正后重试。", 1);
|
||||
}
|
||||
|
||||
/** `seal-use report monthly` / `data` — 月度 AI 审核报告。 */
|
||||
function resolveMaxRuns(args: ParsedArgs): number | undefined {
|
||||
return (
|
||||
numberOption(args.options.limit) ??
|
||||
numberOption(args.options.n) ??
|
||||
numberOption(args.options.count) ??
|
||||
numberOption(args.options["max-runs"]) ??
|
||||
numberOption(args.options.maxRuns)
|
||||
);
|
||||
}
|
||||
|
||||
/** `seal-use report generate` / `ledger` / `data` — AI 审核报告。 */
|
||||
export async function handleReportCommand(
|
||||
action: string | undefined,
|
||||
client: Awaited<ReturnType<typeof createSealClient>>,
|
||||
corp: CorpConfig,
|
||||
args: ParsedArgs
|
||||
) {
|
||||
if (action === "data") {
|
||||
const month = stringOption(args.options.month);
|
||||
if (!month) {
|
||||
throw new Error("Usage: seal-use report data --month <YYYY-MM> [--max-runs <n>] [--corp <corpId>]");
|
||||
if (action === "ledger") {
|
||||
const ledgerPath = stringOption(args.options.ledger);
|
||||
const out = stringOption(args.options.out) ?? stringOption(args.options.o);
|
||||
const format = (stringOption(args.options.format) ?? (out?.endsWith(".csv") ? "csv" : "xlsx")).toLowerCase();
|
||||
|
||||
let data: ReportData;
|
||||
if (ledgerPath) {
|
||||
data = await loadReportDataFromLedger(ledgerPath, { corp: { id: corp.id, name: corp.name } });
|
||||
} else {
|
||||
const startDate =
|
||||
stringOption(args.options["start-date"]) ??
|
||||
stringOption(args.options.startDate) ??
|
||||
stringOption(args.options.start) ??
|
||||
stringOption(args.options.since);
|
||||
const endDate =
|
||||
stringOption(args.options["end-date"]) ??
|
||||
stringOption(args.options.endDate) ??
|
||||
stringOption(args.options.end) ??
|
||||
stringOption(args.options.until);
|
||||
const month = stringOption(args.options.month);
|
||||
|
||||
if ((!startDate || !endDate) && !month) {
|
||||
throw usageError(
|
||||
"Usage: seal-use report ledger --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD> [--templates <t1,t2...>] [--limit <n>] [--out <file.xlsx|csv>] [--corp <corpId>]"
|
||||
);
|
||||
}
|
||||
|
||||
const templates = stringOption(args.options.templates)?.split(/[,;]+/).map((s) => s.trim()).filter(Boolean);
|
||||
data = await collectReportData(client, new Set(["blocks", "templateGroups", "performance"]), {
|
||||
startDate,
|
||||
endDate,
|
||||
month,
|
||||
corp: { id: corp.id, name: corp.name },
|
||||
templates,
|
||||
maxRuns: resolveMaxRuns(args)
|
||||
});
|
||||
}
|
||||
|
||||
const outFile = out ?? `台账-${corp.id}-${(data.period.label ?? data.period.start).replace(/[^0-9A-Za-z_-]/g, "_")}.${format === "csv" ? "csv" : "xlsx"}`;
|
||||
const targetPath = resolve(outFile);
|
||||
if (format === "csv") {
|
||||
const csvContent = buildReportLedgerCsv(data);
|
||||
writeFileSync(targetPath, csvContent, "utf8");
|
||||
} else {
|
||||
const xlsxBuffer = await buildReportLedgerXlsx(data);
|
||||
writeFileSync(targetPath, xlsxBuffer);
|
||||
}
|
||||
|
||||
const divergedCount = data.blocks.filter((b) => b.agreement === "diverged").length;
|
||||
const unreviewedDiverged = data.blocks.filter((b) => b.agreement === "diverged" && !b.verdict).length;
|
||||
|
||||
printJson({
|
||||
file: targetPath,
|
||||
format: format === "csv" ? "csv" : "xlsx",
|
||||
corpId: corp.id,
|
||||
period: data.period,
|
||||
totalBlocks: data.blocks.length,
|
||||
templates: [...new Set(data.blocks.map((b) => b.template))],
|
||||
divergedCount,
|
||||
unreviewedDiverged,
|
||||
next: {
|
||||
reviewTip: "可在 Excel 中直接编辑'复核定性裁决'列(填写:AI判断正确 / 人工判断错误,或人工判断正确 / AI判定误判),也可直接剔除不需要的模板行",
|
||||
generate: `seal-use report generate --ledger '${targetPath}' --corp ${corp.id} --out reports/报告.md`
|
||||
}
|
||||
}, outputOptions(args.options));
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "data") {
|
||||
const ledgerPath = stringOption(args.options.ledger);
|
||||
const startDate =
|
||||
stringOption(args.options["start-date"]) ??
|
||||
stringOption(args.options.startDate) ??
|
||||
stringOption(args.options.start) ??
|
||||
stringOption(args.options.since);
|
||||
const endDate =
|
||||
stringOption(args.options["end-date"]) ??
|
||||
stringOption(args.options.endDate) ??
|
||||
stringOption(args.options.end) ??
|
||||
stringOption(args.options.until);
|
||||
const month = stringOption(args.options.month);
|
||||
|
||||
if (!ledgerPath && (!startDate || !endDate) && !month) {
|
||||
throw usageError(
|
||||
"Usage: seal-use report data (--ledger <台账.xlsx> | --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD>) [--templates <t1,t2...>] [--limit <n>] [--corp <corpId>]"
|
||||
);
|
||||
}
|
||||
|
||||
const templates = stringOption(args.options.templates)?.split(/[,;]+/).map((s) => s.trim()).filter(Boolean);
|
||||
|
||||
const result = await runCapabilityResult(
|
||||
"sealReportDataGet",
|
||||
client,
|
||||
corp,
|
||||
{
|
||||
startDate,
|
||||
endDate,
|
||||
month,
|
||||
maxRuns: numberOption(args.options["max-runs"]) ?? numberOption(args.options.maxRuns)
|
||||
templates,
|
||||
ledgerPath,
|
||||
maxRuns: resolveMaxRuns(args)
|
||||
}
|
||||
);
|
||||
printJson(result, outputOptions(args.options));
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "monthly" || action === "month") {
|
||||
if (action === "monthly" || action === "month" || action === "generate") {
|
||||
const ledgerPath = stringOption(args.options.ledger);
|
||||
const startDate =
|
||||
stringOption(args.options["start-date"]) ??
|
||||
stringOption(args.options.startDate) ??
|
||||
stringOption(args.options.start) ??
|
||||
stringOption(args.options.since);
|
||||
const endDate =
|
||||
stringOption(args.options["end-date"]) ??
|
||||
stringOption(args.options.endDate) ??
|
||||
stringOption(args.options.end) ??
|
||||
stringOption(args.options.until);
|
||||
const month = stringOption(args.options.month);
|
||||
if (!month) {
|
||||
throw new Error("Usage: seal-use report monthly --month <YYYY-MM> [--template <file>] [--report-id <RPT-...>] [--corp <corpId>]");
|
||||
|
||||
if (!ledgerPath && (!startDate || !endDate) && !month) {
|
||||
throw usageError(
|
||||
"Usage: seal-use report generate (--ledger <台账.xlsx> | --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD>) [--templates <t1,t2...>] [--limit <n>] [--template <file>] [--report-id <RPT-...>] [--corp <corpId>]"
|
||||
);
|
||||
}
|
||||
|
||||
const templates = stringOption(args.options.templates)?.split(/[,;]+/).map((s) => s.trim()).filter(Boolean);
|
||||
|
||||
const result = await runCapabilityResult(
|
||||
"sealReportMonthlyGet",
|
||||
client,
|
||||
corp,
|
||||
{
|
||||
startDate,
|
||||
endDate,
|
||||
month,
|
||||
templates,
|
||||
ledgerPath,
|
||||
templatePath: stringOption(args.options.template),
|
||||
reportId: stringOption(args.options["report-id"]) ?? stringOption(args.options.reportId),
|
||||
maxRuns: numberOption(args.options["max-runs"]) ?? numberOption(args.options.maxRuns)
|
||||
maxRuns: resolveMaxRuns(args),
|
||||
allowUnreviewed: booleanOption(args.options["allow-unreviewed"]) ?? booleanOption(args.options.force)
|
||||
}
|
||||
) as MonthlyReportResult;
|
||||
const out = stringOption(args.options.out) ?? stringOption(args.options.o);
|
||||
@@ -139,33 +277,57 @@ export async function handleReportCommand(
|
||||
}
|
||||
|
||||
if (action === "review") {
|
||||
const sub = args.command[2]; // set | list
|
||||
const month = stringOption(args.options.month);
|
||||
if (!month) {
|
||||
throw new Error("Usage: seal-use report review <set|list> --month <YYYY-MM> [--sn <SN> --verdict <v>] [--corp <corpId>]");
|
||||
}
|
||||
const sub = args.command[2]; // set | list | import
|
||||
|
||||
if (sub === "list") {
|
||||
const reviews = loadReviews(corp.id, month);
|
||||
const scope = stringOption(args.options.month) ?? stringOption(args.options.scope);
|
||||
const reviews = loadReviews(corp.id, scope);
|
||||
printJson({
|
||||
corpId: corp.id,
|
||||
month,
|
||||
file: reviewFilePath(corp.id, month),
|
||||
...(scope ? { month: scope } : {}),
|
||||
file: reviewFilePath(corp.id, scope),
|
||||
count: reviews.size,
|
||||
reviews: [...reviews.values()]
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (sub === "import") {
|
||||
const file = args.command[3] ?? stringOption(args.options.file) ?? stringOption(args.options.ledger);
|
||||
if (!file) throw usageError("Usage: seal-use report review import <台账.xlsx|csv> --corp <corpId>");
|
||||
const ledgerData = await loadReportDataFromLedger(file, { corp: { id: corp.id, name: corp.name } });
|
||||
let imported = 0;
|
||||
for (const rev of ledgerData.reviews.values()) {
|
||||
writeReview(corp.id, rev);
|
||||
imported++;
|
||||
}
|
||||
printJson({
|
||||
corpId: corp.id,
|
||||
file: resolve(file),
|
||||
importedCount: imported,
|
||||
totalBlocks: ledgerData.blocks.length
|
||||
}, outputOptions(args.options));
|
||||
return;
|
||||
}
|
||||
|
||||
if (sub === "set") {
|
||||
const sn = stringOption(args.options.sn) ?? stringOption(args.options["document-sn"]);
|
||||
const recordId =
|
||||
stringOption(args.options["record-id"]) ??
|
||||
stringOption(args.options.recordId) ??
|
||||
stringOption(args.options.id);
|
||||
const sn =
|
||||
stringOption(args.options.sn) ??
|
||||
stringOption(args.options["document-sn"]);
|
||||
const verdict = stringOption(args.options.verdict);
|
||||
if (!sn || !verdict) {
|
||||
throw new Error(
|
||||
"Usage: seal-use report review set --month <YYYY-MM> --sn <SN> --verdict <ai_correct|human_correct|both_correct|both_wrong|undecided> [--note <text>] [--reviewed-by <who>] [--corp <corpId>]"
|
||||
const month = stringOption(args.options.month) ?? stringOption(args.options.scope);
|
||||
|
||||
if ((!recordId && !sn) || !verdict) {
|
||||
throw usageError(
|
||||
"Usage: seal-use report review set [--record-id <ID>] [--sn <SN>] --verdict <ai_correct|human_correct|both_correct|both_wrong|undecided> [--note <text>] [--reviewed-by <who>] [--corp <corpId>]"
|
||||
);
|
||||
}
|
||||
const record = writeReview(corp.id, {
|
||||
recordId,
|
||||
sn,
|
||||
month,
|
||||
verdict,
|
||||
@@ -176,8 +338,8 @@ export async function handleReportCommand(
|
||||
return;
|
||||
}
|
||||
|
||||
throw new Error(`Unknown report review subcommand: ${sub ?? ""}. Use 'set' or 'list'.`);
|
||||
throw usageError(`Unknown report review subcommand: ${sub ?? ""}. Use 'set', 'list', or 'import'.`);
|
||||
}
|
||||
|
||||
throw new Error(`Unknown report command: ${action ?? ""}. Run 'seal-use report --help' for available commands.`);
|
||||
throw usageError(`Unknown report command: ${action ?? ""}. Run 'seal-use help report' for available commands.`);
|
||||
}
|
||||
+117
-25
@@ -619,22 +619,40 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
},
|
||||
{
|
||||
area: "report",
|
||||
title: "Monthly audit accuracy reports",
|
||||
description: "Generate monthly audit reports, validate local Markdown, and export HTML/PNG/PDF.",
|
||||
title: "AI audit accuracy reports (acceptance, go-live, periodic)",
|
||||
description: "Generate AI audit and acceptance reports, export standalone Excel/CSV ledgers, validate local Markdown, and export HTML/PNG/PDF.",
|
||||
commands: [
|
||||
{
|
||||
name: "ledger",
|
||||
summary: "Export standalone audit run ledger (.xlsx / .csv) with full AI & human opinions",
|
||||
usage: ["seal-use report ledger --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD> [--templates <t1,t2...>] [--limit <n>] [--out <file.xlsx>] [--corp <corpId>]"],
|
||||
options: [
|
||||
{ flag: "--start-date <YYYY-MM-DD>", description: "Statistics start date, YYYY-MM-DD (e.g. 2026-08-12)" },
|
||||
{ flag: "--end-date <YYYY-MM-DD>", description: "Statistics end date, YYYY-MM-DD (e.g. 2026-09-18)" },
|
||||
{ flag: "--templates <names>", description: "Comma-separated template whitelist" },
|
||||
{ flag: "--ledger <file>", description: "Inspect or convert an existing ledger file" },
|
||||
{ flag: "--out <file>", description: "Output path (.xlsx or .csv); defaults to 台账-<corpId>-<period>.xlsx" },
|
||||
{ flag: "--format <xlsx|csv>", description: "Export format (default: xlsx, or inferred from --out)" },
|
||||
{ flag: "--limit <n>", description: "Cap approval-run fetch (alias: --max-runs, default: all records in period, max 100000)" }
|
||||
],
|
||||
description: "Exports full audit ledger containing recordId, SN, template, AI decisions, full AI opinions & conditions, human results & comments, agreement, and review verdict columns. Agents can freely trim rows/templates and fill verdicts."
|
||||
},
|
||||
{
|
||||
name: "data",
|
||||
summary: "Extract pure structured report data, metrics, diverged runs, and triggers without templates",
|
||||
usage: ["seal-use report data --month <YYYY-MM> [--max-runs <n>] [--corp <corpId>]"],
|
||||
usage: ["seal-use report data (--ledger <台账.xlsx> | --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD>) [--templates <t1,t2...>] [--limit <n>] [--corp <corpId>]"],
|
||||
options: [
|
||||
{ flag: "--month <YYYY-MM>", description: "Statistics month, e.g. 2026-08 (required)" },
|
||||
{ flag: "--max-runs <n>", description: "Cap approval-run detail fetch, default 500 (max 500)" }
|
||||
{ flag: "--start-date <YYYY-MM-DD>", description: "Statistics start date, YYYY-MM-DD" },
|
||||
{ flag: "--end-date <YYYY-MM-DD>", description: "Statistics end date, YYYY-MM-DD" },
|
||||
{ flag: "--ledger <file>", description: "Directly parse an edited Excel/CSV ledger file without remote requests" },
|
||||
{ flag: "--templates <names>", description: "Comma-separated template whitelist" },
|
||||
{ flag: "--limit <n>", description: "Cap approval-run detail fetch (alias: --max-runs, default: all records in period, max 100000)" }
|
||||
],
|
||||
description: "Template-free data pack for Agent authoring: returns performance metrics, formula fractions, template groups, top risk tags, diverged runs with exact triggered conditions, and reviews."
|
||||
},
|
||||
{
|
||||
name: "template",
|
||||
summary: "Dump or save the built-in monthly report Markdown template",
|
||||
summary: "Dump or save the built-in report Markdown template",
|
||||
usage: ["seal-use report template [--out <file.md>]"],
|
||||
options: [
|
||||
{ flag: "--out <file>", description: "Save built-in Markdown template directly to a file" }
|
||||
@@ -654,19 +672,23 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
description: "Tenant-free local command: calculates proportions and outputs high-fidelity SVG chart."
|
||||
},
|
||||
{
|
||||
name: "monthly",
|
||||
aliases: ["month"],
|
||||
summary: "Fill the monthly report template with performance, risk, and approval-run data",
|
||||
usage: ["seal-use report monthly --month <YYYY-MM> [--out <报告.md>] [--template <file>] [--report-id <RPT-...>] [--max-runs <n>] [--corp <corpId>]"],
|
||||
name: "generate",
|
||||
aliases: ["monthly", "month"],
|
||||
summary: "Fill the audit report template with performance, risk, and approval-run data",
|
||||
usage: ["seal-use report generate (--ledger <台账.xlsx> | --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD>) [--templates <t1,t2...>] [--out <报告.md>] [--template <file>] [--report-id <RPT-...>] [--limit <n>] [--allow-unreviewed] [--corp <corpId>]"],
|
||||
options: [
|
||||
{ flag: "--month <YYYY-MM>", description: "Statistics month, e.g. 2026-08 (required)" },
|
||||
{ flag: "--template <file>", description: "Custom template Markdown path; defaults to the Git-managed template embedded in the binary, independent of cwd" },
|
||||
{ flag: "--out <file>", description: "Save Markdown plus local images beside the report; stdout stays JSON (without the content field)" },
|
||||
{ flag: "--start-date <YYYY-MM-DD>", description: "Statistics start date, YYYY-MM-DD (e.g. 2026-08-12)" },
|
||||
{ flag: "--end-date <YYYY-MM-DD>", description: "Statistics end date, YYYY-MM-DD (e.g. 2026-09-18)" },
|
||||
{ flag: "--ledger <file>", description: "Driven directly by an edited Excel/CSV ledger as the sole source of truth; ignores deleted templates/runs and respects in-place verdicts" },
|
||||
{ flag: "--templates <names>", description: "Comma-separated template whitelist; filters blocks and ledger at source" },
|
||||
{ flag: "--template <file>", description: "Custom template Markdown path; defaults to the Git-managed template embedded in the binary" },
|
||||
{ flag: "--out <file>", description: "Save Markdown plus local images and Excel/CSV ledgers beside the report; stdout stays JSON" },
|
||||
{ flag: "--overwrite", description: "Explicitly permit replacing existing output files" },
|
||||
{ flag: "--report-id <RPT-...>", description: "Custom report id; defaults to RPT-<YYYYMM>-<random>" },
|
||||
{ flag: "--max-runs <n>", description: "Cap approval-run detail fetch, default 500 (max 500)" }
|
||||
{ flag: "--report-id <RPT-...>", description: "Custom report id; defaults to RPT-<dateTag>-<random>" },
|
||||
{ flag: "--limit <n>", description: "Cap approval-run detail fetch (alias: --max-runs, default: all records in period, max 100000)" },
|
||||
{ flag: "--allow-unreviewed", description: "Bypass pre-flight adjudication gate to generate draft when unreviewed diverged runs exist" }
|
||||
],
|
||||
description: "The template is the mutable skin: section headings, tables, and order may change and data demands are inferred from headings (src/domains/seal/reports/describe.ts). Fields with no upstream metric (human accuracy, mismatch categories) keep template sample values and are marked with a warning note instead of fabricated numbers."
|
||||
description: "The template is the mutable skin: section headings, tables, and order may change and data demands are inferred from headings. Supports direct ledger-driven generation where user/Agent modifications to templates and rows are strictly respected."
|
||||
},
|
||||
{
|
||||
name: "validate",
|
||||
@@ -703,25 +725,34 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
},
|
||||
{
|
||||
name: "review set",
|
||||
summary: "Record one human adjudication (who was right: AI or human) for a document",
|
||||
usage: ["seal-use report review set --month <YYYY-MM> --sn <SN> --verdict <v> [--note <text>] [--reviewed-by <who>] [--corp <corpId>]"],
|
||||
summary: "Record one human adjudication (who was right: AI or human) for an approval run or document",
|
||||
usage: ["seal-use report review set [--record-id <ID>] [--sn <SN>] --verdict <v> [--note <text>] [--reviewed-by <who>] [--corp <corpId>]"],
|
||||
options: [
|
||||
{ flag: "--month <YYYY-MM>", description: "Statistics month, YYYY-MM (required)" },
|
||||
{ flag: "--sn <SN>", description: "Document SN to adjudicate (required)" },
|
||||
{ flag: "--record-id <ID>", description: "Approval run recordId for exact single-run targeting" },
|
||||
{ flag: "--sn <SN>", description: "Document SN to adjudicate" },
|
||||
{ flag: "--verdict <v>", description: "ai_correct | human_correct | both_correct | both_wrong | undecided (required)" },
|
||||
{ flag: "--note <text>", description: "Optional adjudication note" },
|
||||
{ flag: "--reviewed-by <who>", description: "Optional reviewer name for the audit trail" }
|
||||
],
|
||||
description: "Append-only local JSONL per tenant+month (~/.config/seal-use/state/reviews/). Typically adjudicate diverged blocks (AI != human); report monthly joins these to compute human accuracy. No network: writes only the local store."
|
||||
description: "Append-only local JSONL per tenant (~/.config/seal-use/state/reviews/). Supports exact recordId target or SN. Typically adjudicates diverged blocks or overrides specific agreed runs."
|
||||
},
|
||||
{
|
||||
name: "review list",
|
||||
summary: "List human adjudications recorded for a tenant+month",
|
||||
usage: ["seal-use report review list --month <YYYY-MM> [--corp <corpId>]"],
|
||||
summary: "List human adjudications recorded for a tenant",
|
||||
usage: ["seal-use report review list [--corp <corpId>]"],
|
||||
options: [
|
||||
{ flag: "--month <YYYY-MM>", description: "Statistics month, YYYY-MM (required)" }
|
||||
{ flag: "--corp <corpId>", description: "Target enterprise corpId" }
|
||||
],
|
||||
description: "Reads the local JSONL store and returns all adjudications keyed by SN."
|
||||
description: "Reads the local JSONL store and returns all adjudications."
|
||||
},
|
||||
{
|
||||
name: "review import",
|
||||
summary: "Bulk import adjudications from an edited Excel/CSV ledger file",
|
||||
usage: ["seal-use report review import <台账.xlsx|csv> --corp <corpId>"],
|
||||
options: [
|
||||
{ flag: "--corp <corpId>", description: "Target enterprise corpId" }
|
||||
],
|
||||
description: "Reads '复核定性裁决', '复核人', and '复核批注说明' columns from the ledger and bulk writes into the local review store."
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -854,6 +885,56 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
area: "hose-ebot",
|
||||
title: "Hose EBot outbound discovery & callback (合思 EBot 出站发现与审批回调)",
|
||||
description: "按单号搜索出站/回调记录、列出出站消息配置(signKey),并执行 EBot 审批回调。",
|
||||
commands: [
|
||||
{
|
||||
name: "search",
|
||||
summary: "【出站发现·默认入口】按单号搜索出站消息调用记录(只读)",
|
||||
usage: ["seal-use hose-ebot search <sn> [--type invoking|callback] [--limit <n>] [--reveal] [--corp <corpId>]"],
|
||||
options: [
|
||||
{ flag: "--type <invoking|callback>", description: "筛选记录类型:invoking=出站触发,callback=回调;缺省全部" },
|
||||
{ flag: "--limit <n>", description: "返回条数上限(默认 20,最大 100)" },
|
||||
{ flag: "--reveal, -r", description: "明文展示记录中的 signKey(默认脱敏)" }
|
||||
],
|
||||
description:
|
||||
"在合思 CloseAPI 出站消息日志中按单号 (SN) 搜索,返回带唯一 id 的记录列表(INVOKING 出站触发 / CALLBACK 回调),含 flowId/nodeId/messageId/rejectionNum 等回调上下文。"
|
||||
},
|
||||
{
|
||||
name: "messages",
|
||||
summary: "【出站配置】列出全部出站消息配置,发现 signKey 与回调地址(只读)",
|
||||
usage: ["seal-use hose-ebot messages [--type flow|message] [--reveal] [--corp <corpId>]"],
|
||||
options: [
|
||||
{ flag: "--type <flow|message>", description: "按类型过滤:flow=审批流 EBot 出站,message=完成回调/通知" },
|
||||
{ flag: "--reveal, -r", description: "明文展示 signKey(默认脱敏为 8...4 形式)" }
|
||||
],
|
||||
description:
|
||||
"经合思 CloseAPI 只读查询本企业全部出站消息配置(messageName、signKey、callbackUrl、enable 等)。signKey 即出站回调地址中的 config_id,可直接用于 'hose-ebot callback'。"
|
||||
},
|
||||
{
|
||||
name: "callback",
|
||||
summary: "【回调审批】调用合思开放接口执行 EBot 审批回调(同意/驳回/加签)",
|
||||
usage: [
|
||||
"seal-use hose-ebot callback --flow-id <flowId> --node-id <nodeId> --action <accept|refuse|preAdd|aftAdd> --comment <审批意见> [--sign-key <key>] [--policy <ALL|ANY>] [--add-approver-ids <id,id>] [--reject-to <nodeId>] [--resubmit-method <FROM_START|TO_REJECTOR>] [--dry-run] [--yes|--confirm] [--corp <corpId>]"
|
||||
],
|
||||
options: [
|
||||
{ flag: "--comment <text>", description: "审批意见(必填)" },
|
||||
{ flag: "--sign-key <key>", description: "出站消息签名密钥;缺省时从本企业唯一 Seal 合思集成解析" },
|
||||
{ flag: "--action <accept|refuse|preAdd|aftAdd>", description: "同意 / 驳回 / 前加签 / 后加签(兼容 agree/approve/reject)" },
|
||||
{ flag: "--policy <ALL|ANY>", description: "会签方式:ALL 会签 / ANY 或签(加签超过一人时必填)" },
|
||||
{ flag: "--add-approver-ids <id,id>", description: "前后加签审批人 ID 列表(加签时必填,逗号分隔)" },
|
||||
{ flag: "--reject-to <nodeId>", description: "驳回目标节点 ID;缺省按 EBot 节点驳回配置" },
|
||||
{ flag: "--resubmit-method <FROM_START|TO_REJECTOR>", description: "驳回后重提方式;缺省按 EBot 节点配置" },
|
||||
{ flag: "--dry-run", description: "仅预览回调请求(signKey 脱敏),不执行" },
|
||||
{ flag: "--yes, --confirm", description: "正式执行必需;届时实时换取 accessToken 后回调" }
|
||||
],
|
||||
description:
|
||||
"调用合思开放接口 POST /api/openapi/v1/approval,向审批流回写 EBot 节点审批结果,成功返回 value.code=204。仅支持 EBot 节点的审批;signKey 可通过 'seal-use hose-ebot messages --reveal' 发现。"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
area: "preference",
|
||||
title: "Audit preferences and thinking depth",
|
||||
@@ -972,6 +1053,17 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
description:
|
||||
"专用于合思 (Hose) 来源企业。向合思申请临时 ticket,生成直达外部合思/易快报主站 (https://app.ekuaibao.com/web/thirdparty.html) 的免密登录链接。若需生成 Seal 自身的审核后台访问链接,请使用 'seal-use auth link'。"
|
||||
},
|
||||
{
|
||||
name: "hose-openapi-token",
|
||||
aliases: ["openapi-token", "hose-token"],
|
||||
summary: "【合思】用持久化密钥签发合思 OpenAPI accessToken",
|
||||
usage: ["seal-use auth hose-openapi-token [--corp <corpId>] [--force]"],
|
||||
options: [
|
||||
{ flag: "--force, --refresh, -f", description: "跳过本地缓存,强制向合思 OpenAPI 签发全新 token" }
|
||||
],
|
||||
description:
|
||||
"专用于合思 (Hose) 来源企业。使用已持久化的 appKey/appSecurity 调用 /api/openapi/v1/auth/getAccessToken 换取 OpenAPI accessToken(约 1 小时有效),stdout 输出含 token、expiresAt 与 cached 字段(cached=true 表示复用了本地仍有效的缓存)。"
|
||||
},
|
||||
{
|
||||
name: "hose-extract-keys",
|
||||
aliases: ["extract-keys", "extract-key", "extract-hose-keys"],
|
||||
|
||||
+13
-13
@@ -23,7 +23,7 @@ import { usageError } from "./errors.js";
|
||||
|
||||
// Read with booleanOption(...) / Boolean(...) / presence check.
|
||||
export const BOOLEAN_FLAGS = new Set([
|
||||
"V", "add", "all", "as-hose", "attachments", "auto",
|
||||
"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",
|
||||
@@ -40,9 +40,9 @@ export const BOOLEAN_FLAGS = new Set([
|
||||
|
||||
// Read with stringOption/numberOption/splitOption(...).
|
||||
export const VALUE_FLAGS = new Set([
|
||||
"access-token", "accessToken", "ai", "ai-accuracy", "aiAccuracy", "app-key", "app-security", "appKey", "appSecurity",
|
||||
"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", "concurrency", "confirm-code", "confirmCode", "content", "content-file", "content-hints", "content-type", "contentFile",
|
||||
"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",
|
||||
"dedupe-by", "dedupeBy", "default", "departmentId", "dept", "desc",
|
||||
"description", "description-file", "descriptionFile", "dir", "doc-id-prefix", "doc-id-suffix",
|
||||
@@ -52,7 +52,7 @@ export const VALUE_FLAGS = new Set([
|
||||
"environment", "expire", "expires-in", "expiresIn", "fields", "file", "file-id", "file-name", "flow-concurrency",
|
||||
"flow-id", "flow-ids", "flow-status-list", "flowId", "flowIds", "flowStatusList", "format", "from",
|
||||
"from-link", "host", "human", "human-accuracy", "humanAccuracy", "humanResult", "id", "input", "integration",
|
||||
"json", "json-path", "key-id", "keyId", "keyword", "level", "limit",
|
||||
"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",
|
||||
@@ -60,12 +60,12 @@ export const VALUE_FLAGS = new Set([
|
||||
"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",
|
||||
"outputFile", "p", "package-id", "package-ids", "packageId", "packageIds",
|
||||
"path", "phone", "policyId", "poll-interval", "pollInterval", "port",
|
||||
"path", "phone", "policy", "policyId", "poll-interval", "pollInterval", "port",
|
||||
"prod", "prod-corp", "prodCorp", "purpose", "q", "query",
|
||||
"record-id", "record-ids", "recordId", "recordIds", "reject-node", "rejectNode", "rejection-num", "rejectionNum",
|
||||
"record-id", "record-ids", "recordId", "recordIds", "reject-node", "rejectNode", "reject-to", "rejectTo", "rejection-num", "rejectionNum",
|
||||
"reviewed-by", "reviewedBy",
|
||||
"report-id",
|
||||
"repo", "request-ids", "requestIds", "result-url", "resultUrl", "reuse-window",
|
||||
"repo", "request-ids", "requestIds", "resubmit-method", "resubmitMethod", "result-url", "resultUrl", "reuse-window",
|
||||
"reuseWindow", "rule", "rule-hints", "rule-id", "ruleId", "ruleVersion", "runtime-id",
|
||||
"runtimeId", "samples", "scenarios", "schema-config", "schemaConfig", "scope",
|
||||
"sealUrl", "search", "secret", "selector", "session-id", "sign-key", "signKey",
|
||||
@@ -86,11 +86,11 @@ export const VALUE_FLAGS = new Set([
|
||||
|
||||
// Registered flags. Unknown flags are rejected.
|
||||
export const KNOWN_FLAGS = new Set([
|
||||
"V", "access-token", "accessToken", "ai", "ai-accuracy", "aiAccuracy", "add", "all", "app-key",
|
||||
"V", "access-token", "accessToken", "action", "add-approver-ids", "addApproverIds", "ai", "ai-accuracy", "aiAccuracy", "add", "all", "allow-unreviewed", "allowUnreviewed", "app-key",
|
||||
"app-security", "appKey", "appSecurity", "as-hose", "attachments", "auto",
|
||||
"auto-login", "autoLogin", "base-url", "batch", "batch-id", "batchId",
|
||||
"bg-save", "both", "both-accurate", "bothAccurate", "business-codes", "businessCodes", "channel", "changelog", "check", "check-only", "chrome",
|
||||
"code", "completed-only", "completedOnly", "concurrency", "confirm", "confirm-code", "confirmCode", "content",
|
||||
"code", "comment", "completed-only", "completedOnly", "concurrency", "confirm", "confirm-code", "confirmCode", "content",
|
||||
"content-file", "content-hints", "content-type", "contentFile", "contentType", "context-chars", "contextLines", "corp",
|
||||
"corp-id", "corpId", "corporation-id", "corporationId", "count", "date", "dedupe-by", "dedupeBy",
|
||||
"default", "departmentId", "dept", "desc", "description", "description-file",
|
||||
@@ -105,7 +105,7 @@ export const KNOWN_FLAGS = new Set([
|
||||
"full", "h", "has-input", "has-output", "help", "hose", "hose-outbound", "hose-sso", "hoseOutbound", "hoseSso",
|
||||
"host", "human", "human-accuracy", "humanAccuracy", "humanResult", "id", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
|
||||
"includeBridge", "includeSimulation", "includeUnchanged", "input", "integration", "json",
|
||||
"json-path", "key-id", "keyId", "keyword", "level", "limit", "lines",
|
||||
"json-path", "key-id", "keyId", "keyword", "ledger", "level", "limit", "lines",
|
||||
"link", "linter", "local", "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",
|
||||
@@ -114,12 +114,12 @@ export const KNOWN_FLAGS = new Set([
|
||||
"note", "observation-id", "observation-types", "o", "offset", "out", "out-dir", "outDir", "outbound",
|
||||
"outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file", "outputFile", "overwrite",
|
||||
"p", "package-id", "package-ids", "packageId", "packageIds", "path",
|
||||
"phone", "plain", "policyId", "poll-interval", "pollInterval", "port",
|
||||
"phone", "plain", "policy", "policyId", "poll-interval", "pollInterval", "port",
|
||||
"prod", "prod-corp", "prodCorp", "publish", "purpose", "q",
|
||||
"query", "quiet", "r", "recode", "record-id", "record-ids",
|
||||
"recordId", "recordIds", "refresh", "refresh-if-missing", "reject-node", "rejectNode", "rejection-num", "rejectionNum", "repo",
|
||||
"recordId", "recordIds", "refresh", "refresh-if-missing", "reject-node", "rejectNode", "reject-to", "rejectTo", "rejection-num", "rejectionNum", "repo",
|
||||
"report-id",
|
||||
"request-ids", "requestIds", "result-url", "resultUrl", "reuse-window", "reuseWindow",
|
||||
"request-ids", "requestIds", "resubmit-method", "resubmitMethod", "result-url", "resultUrl", "reuse-window", "reuseWindow",
|
||||
"reviewed-by", "reviewedBy",
|
||||
"reveal", "rotate-secret", "rotateSecret", "rule", "rule-hints", "rule-id", "ruleId",
|
||||
"ruleVersion", "runtime-id", "runtimeId", "samples", "save", "scenarios",
|
||||
|
||||
@@ -60,6 +60,8 @@ describe("CLI read-only classification", () => {
|
||||
["approval-runs", "get", "01a09dac-c688-767b-8eb4-37b945095585"],
|
||||
["approval-runs", "list", "--corp", "corp-a"],
|
||||
["deploy", "hosecloud", "status", "--corp", "corp-a"],
|
||||
["hose-ebot", "search", "SN123", "--type", "callback", "--corp", "corp-a"],
|
||||
["hose-ebot", "messages", "--corp", "corp-a"],
|
||||
["preferences", "get"],
|
||||
["doctor", "tenant", "--corp", "corp-a"],
|
||||
["langfuse", "check"],
|
||||
@@ -91,6 +93,8 @@ describe("CLI read-only classification", () => {
|
||||
["simulation", "create", "--mode", "hosecloud"],
|
||||
["deploy", "hosecloud", "sync", "sign-key"],
|
||||
["deploy", "hosecloud", "configure"],
|
||||
// The EBot approval callback writes accept/refuse into the live approval flow.
|
||||
["hose-ebot", "callback", "--flow-id", "f1", "--node-id", "n1", "--action", "accept", "--comment", "ok", "--yes"],
|
||||
["webhook", "delete", "hook-1"],
|
||||
["webhook", "replay"],
|
||||
["users", "reset-password", "corp-a:u1"],
|
||||
@@ -100,6 +104,8 @@ describe("CLI read-only classification", () => {
|
||||
["mcp"],
|
||||
["update"],
|
||||
["auth", "keys"],
|
||||
// Mints and prints an OpenAPI credential, so it never qualifies as a read.
|
||||
["auth", "hose-openapi-token"],
|
||||
["analytics", "analyze", "record-1"],
|
||||
["tool", "sealApprovalRuleCreate", "--json", "{}"],
|
||||
["langfuse", "unknown-verb"],
|
||||
|
||||
@@ -64,6 +64,9 @@ const READ_ONLY_COMMANDS: Record<string, string[]> = {
|
||||
"integrations"
|
||||
],
|
||||
deploy: ["hosecloud requirements", "hosecloud list", "hosecloud get", "hosecloud status"],
|
||||
// `hose-ebot callback` is deliberately absent: it mints an accessToken and writes an
|
||||
// approval action into the live flow. Only the two discovery verbs read.
|
||||
"hose-ebot": ["search", "messages"],
|
||||
preference: ["get", "thinking-depth policies list"],
|
||||
// `config mode`/`config lint` are omitted: classification is token-prefix based, so their
|
||||
// read forms cannot be separated from the value-taking write forms. `config get` returns
|
||||
|
||||
+16
-1
@@ -39,6 +39,7 @@ export const KNOWN_AREAS = new Set([
|
||||
"corps",
|
||||
"corp",
|
||||
"source",
|
||||
"hose-ebot",
|
||||
"auth",
|
||||
"users",
|
||||
"contacts",
|
||||
@@ -224,7 +225,16 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (area === "report" && (action === "validate" || action === "render" || action === "export" || action === "template" || action === "chart")) {
|
||||
if (
|
||||
area === "report" &&
|
||||
(action === "validate" ||
|
||||
action === "render" ||
|
||||
action === "export" ||
|
||||
action === "template" ||
|
||||
action === "chart" ||
|
||||
action === "review" ||
|
||||
Boolean(args.options.ledger))
|
||||
) {
|
||||
await (await import("./commands/report.js")).handleLocalReportCommand(action, args);
|
||||
return;
|
||||
}
|
||||
@@ -416,6 +426,11 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (area === "hose-ebot") {
|
||||
await (await import("./commands/hose-ebot.js")).handleHoseEbotCommand(action, maybeName, client, corp, args);
|
||||
return;
|
||||
}
|
||||
|
||||
if (area === "preference" || area === "preferences") {
|
||||
await (await import("./commands/preference.js")).handlePreferenceCommand(action, maybeName, args.command[3], args.command[4], client, corp, args);
|
||||
return;
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
exchangeHoseAssistLink,
|
||||
fetchHoseStaffDetails,
|
||||
getHoseEnterpriseUrl,
|
||||
getHoseOpenapiToken,
|
||||
getHoseProvisionalAuthLink,
|
||||
getHoseSealSession,
|
||||
normalizeBaseUrl,
|
||||
@@ -402,4 +403,62 @@ describe("hose auth helpers", () => {
|
||||
expect(getHoseProvisionalAuthLink(corp, -100)).rejects.toThrow("Invalid expire seconds");
|
||||
expect(getHoseProvisionalAuthLink(corp, 0)).rejects.toThrow("Invalid expire seconds");
|
||||
});
|
||||
|
||||
test("getHoseOpenapiToken serves a fresh cached token and mints a new one under force", async () => {
|
||||
setupTokenStore({
|
||||
"corp-test": {
|
||||
hose: {
|
||||
openapi: {
|
||||
token: "cached-openapi-token",
|
||||
expiresAt: Date.now() + 3600_000
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const corp: CorpConfig = {
|
||||
id: "corp-test",
|
||||
name: "Corp Test",
|
||||
environment: "production",
|
||||
seal: { endpoints: { approvalStylePreferences: "" } },
|
||||
source: {
|
||||
type: "hose",
|
||||
domain: "https://app.ekuaibao.com",
|
||||
appKey: "key",
|
||||
appSecurity: "sec",
|
||||
staffId: "staff-1",
|
||||
corpId: "CORP-TEST"
|
||||
},
|
||||
auth: { refreshTtl: 300 }
|
||||
};
|
||||
|
||||
let mintCount = 0;
|
||||
globalThis.fetch = (async (input: RequestInfo | URL) => {
|
||||
const urlStr = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
||||
if (new URL(urlStr).pathname === "/api/openapi/v1/auth/getAccessToken") {
|
||||
mintCount += 1;
|
||||
return new Response(JSON.stringify({ value: { accessToken: "minted-openapi-token" } }), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" }
|
||||
});
|
||||
}
|
||||
return new Response("not found", { status: 404 });
|
||||
}) as typeof fetch;
|
||||
|
||||
const cached = await getHoseOpenapiToken(corp);
|
||||
expect(cached.cached).toBe(true);
|
||||
expect(cached.token).toBe("cached-openapi-token");
|
||||
expect(mintCount).toBe(0);
|
||||
|
||||
const forced = await getHoseOpenapiToken(corp, { force: true });
|
||||
expect(forced.cached).toBe(false);
|
||||
expect(forced.token).toBe("minted-openapi-token");
|
||||
expect(mintCount).toBe(1);
|
||||
expect(getHoseAuthCache("corp-test").openapi?.token).toBe("minted-openapi-token");
|
||||
|
||||
const reused = await getHoseOpenapiToken(corp);
|
||||
expect(reused.cached).toBe(true);
|
||||
expect(reused.token).toBe("minted-openapi-token");
|
||||
expect(mintCount).toBe(1);
|
||||
});
|
||||
});
|
||||
+22
-9
@@ -113,7 +113,10 @@ export type HoseProbeResult = {
|
||||
expireTime?: number;
|
||||
};
|
||||
|
||||
const openapiTokenRequests = new Map<string, Promise<string>>();
|
||||
/** A Hose OpenAPI access token plus whether it was served from the local SWR cache. */
|
||||
export type HoseOpenapiTokenResult = TokenEntry & { cached: boolean };
|
||||
|
||||
const openapiTokenRequests = new Map<string, Promise<TokenEntry>>();
|
||||
const closeApiTokenRequests = new Map<string, Promise<TokenEntry>>();
|
||||
|
||||
export function normalizeBaseUrl(url: string): string {
|
||||
@@ -298,17 +301,20 @@ async function fetchHoseOpenapiToken(source: HoseSealSource): Promise<TokenEntry
|
||||
};
|
||||
}
|
||||
|
||||
export async function ensureHoseOpenapiToken(corp: CorpConfig): Promise<string> {
|
||||
export async function getHoseOpenapiToken(
|
||||
corp: CorpConfig,
|
||||
options?: { force?: boolean }
|
||||
): Promise<HoseOpenapiTokenResult> {
|
||||
if (corp.source.type !== "hose") {
|
||||
throw new Error(`Unsupported Seal source: ${corp.source.type}`);
|
||||
}
|
||||
const cache = getHoseAuthCache(corp.id);
|
||||
if (isFresh(cache.openapi)) {
|
||||
return cache.openapi.token;
|
||||
if (!options?.force && isFresh(cache.openapi)) {
|
||||
return { ...cache.openapi, cached: true };
|
||||
}
|
||||
|
||||
const pending = openapiTokenRequests.get(corp.id);
|
||||
if (pending) return pending;
|
||||
if (pending) return { ...(await pending), cached: false };
|
||||
|
||||
const request = fetchHoseOpenapiToken(corp.source)
|
||||
.then((openapi) => {
|
||||
@@ -316,11 +322,18 @@ export async function ensureHoseOpenapiToken(corp: CorpConfig): Promise<string>
|
||||
...getHoseAuthCache(corp.id),
|
||||
openapi
|
||||
});
|
||||
return openapi.token;
|
||||
return openapi;
|
||||
})
|
||||
.finally(() => openapiTokenRequests.delete(corp.id));
|
||||
openapiTokenRequests.set(corp.id, request);
|
||||
return request;
|
||||
return { ...(await request), cached: false };
|
||||
}
|
||||
|
||||
export async function ensureHoseOpenapiToken(
|
||||
corp: CorpConfig,
|
||||
options?: { force?: boolean }
|
||||
): Promise<string> {
|
||||
return (await getHoseOpenapiToken(corp, options)).token;
|
||||
}
|
||||
|
||||
export async function fetchHoseCloseApiToken(
|
||||
@@ -415,7 +428,7 @@ export async function getHoseEnterpriseUrl(corp: CorpConfig): Promise<string> {
|
||||
export async function getHoseProvisionalAuthLink(
|
||||
corp: CorpConfig,
|
||||
expiresIn = 7200,
|
||||
_options?: { force?: boolean }
|
||||
options?: { force?: boolean }
|
||||
): Promise<{
|
||||
corpId: string;
|
||||
staffId: string;
|
||||
@@ -431,7 +444,7 @@ export async function getHoseProvisionalAuthLink(
|
||||
throw new Error(`Invalid expire seconds: ${expiresIn}. Must be a positive integer.`);
|
||||
}
|
||||
|
||||
const openapiToken = await ensureHoseOpenapiToken(corp);
|
||||
const openapiToken = await ensureHoseOpenapiToken(corp, { force: options?.force });
|
||||
const provisional = await fetchHoseCloseApiToken(corp.source, openapiToken, expiresIn);
|
||||
if (!provisional.url) {
|
||||
throw new Error("Hose provisional auth URL was not available");
|
||||
|
||||
@@ -36,13 +36,88 @@ export interface HoseOutboundLogItem {
|
||||
response?: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* A configured outbound message on the Hose side (EBot push or completion
|
||||
* callback). Only the fields seal-use surfaces are kept; Hose returns more.
|
||||
*/
|
||||
export interface HoseOutboundMessageConfig {
|
||||
id: string;
|
||||
messageName?: string;
|
||||
messageType?: string;
|
||||
enable?: boolean;
|
||||
signKey?: string;
|
||||
callbackUrl?: string;
|
||||
corporationId?: string;
|
||||
actionEvent?: string[];
|
||||
formFields?: string[];
|
||||
remark?: string;
|
||||
createTime?: number;
|
||||
updateTime?: number;
|
||||
}
|
||||
|
||||
function parseOutboundMessage(item: unknown): HoseOutboundMessageConfig | undefined {
|
||||
if (!item || typeof item !== "object" || Array.isArray(item)) return undefined;
|
||||
const raw = item as Record<string, unknown>;
|
||||
if (typeof raw.id !== "string" || !raw.id) return undefined;
|
||||
const stringList = (value: unknown): string[] | undefined =>
|
||||
Array.isArray(value)
|
||||
? value.filter((entry): entry is string => typeof entry === "string")
|
||||
: undefined;
|
||||
return {
|
||||
id: raw.id,
|
||||
messageName: typeof raw.messageName === "string" ? raw.messageName : undefined,
|
||||
messageType: typeof raw.messageType === "string" ? raw.messageType : undefined,
|
||||
enable: typeof raw.enable === "boolean" ? raw.enable : undefined,
|
||||
signKey: typeof raw.signKey === "string" ? raw.signKey : undefined,
|
||||
callbackUrl: typeof raw.callbackUrl === "string" ? raw.callbackUrl : undefined,
|
||||
corporationId: typeof raw.corporationId === "string" ? raw.corporationId : undefined,
|
||||
actionEvent: stringList(raw.actionEvent),
|
||||
formFields: stringList(raw.formFields),
|
||||
remark: typeof raw.remark === "string" ? raw.remark : undefined,
|
||||
createTime: typeof raw.createTime === "number" ? raw.createTime : undefined,
|
||||
updateTime: typeof raw.updateTime === "number" ? raw.updateTime : undefined
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* List every configured outbound message for the tenant via the read-only
|
||||
* CloseAPI `GET api/outbound/v1/message`. Each row carries the `signKey` that
|
||||
* the EBot callback URL embeds as `config_id`, which is how operators find
|
||||
* which signature key belongs to which message.
|
||||
*/
|
||||
export async function fetchHoseOutboundMessages(
|
||||
sourceCorp: CorpConfig
|
||||
): Promise<HoseOutboundMessageConfig[]> {
|
||||
if (sourceCorp.source.type !== "hose") {
|
||||
throw validationError(
|
||||
`企业「${sourceCorp.name}」非合思(hose)租户,无法查询合思出站消息配置。`
|
||||
);
|
||||
}
|
||||
|
||||
const client = await createHoseCloseClient(sourceCorp);
|
||||
const response = (await client
|
||||
.get("api/outbound/v1/message", {
|
||||
searchParams: { corpId: sourceCorp.source.corpId }
|
||||
})
|
||||
.json()) as { items?: unknown };
|
||||
|
||||
if (!Array.isArray(response.items)) {
|
||||
throw new Error("合思出站消息接口未返回 items 列表,响应结构与预期不符");
|
||||
}
|
||||
|
||||
return response.items
|
||||
.map(parseOutboundMessage)
|
||||
.filter((message): message is HoseOutboundMessageConfig => message !== undefined);
|
||||
}
|
||||
|
||||
/**
|
||||
* Query CloseAPI's outbound message log for one document SN (flowId.form.code).
|
||||
*/
|
||||
export async function searchOutboundMessageLogs(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
sn: string
|
||||
sn: string,
|
||||
options?: { limit?: number }
|
||||
): Promise<HoseOutboundLogItem[]> {
|
||||
const response = (await client
|
||||
.post("api/outbound/v1/message/messageLog", {
|
||||
@@ -51,10 +126,10 @@ export async function searchOutboundMessageLogs(
|
||||
corpId
|
||||
},
|
||||
json: {
|
||||
limit: { start: 0, count: 20 },
|
||||
limit: { start: 0, count: options?.limit ?? 20 },
|
||||
orderBy: [{ value: "createTime", order: "DESC" }],
|
||||
select: "id,name,flowId(id, form(code)),nodeName,type,request,response,state,createTime,messageType",
|
||||
filterBy: `(flowId.form.code==("${sn}"))`
|
||||
filterBy: `(flowId.form.code==("${sn.replace(/"/g, '\\"')}"))`
|
||||
}
|
||||
})
|
||||
.json()) as { items?: HoseOutboundLogItem[] };
|
||||
@@ -67,7 +142,8 @@ export async function searchOutboundMessageLogs(
|
||||
*/
|
||||
export async function fetchHoseOutboundLogs(
|
||||
sourceCorp: CorpConfig,
|
||||
sn: string
|
||||
sn: string,
|
||||
options?: { limit?: number }
|
||||
): Promise<HoseOutboundLogItem[]> {
|
||||
if (sourceCorp.source.type !== "hose") {
|
||||
throw validationError(
|
||||
@@ -76,5 +152,5 @@ export async function fetchHoseOutboundLogs(
|
||||
}
|
||||
|
||||
const client = await createHoseCloseClient(sourceCorp);
|
||||
return searchOutboundMessageLogs(client, sourceCorp.source.corpId, sn);
|
||||
return searchOutboundMessageLogs(client, sourceCorp.source.corpId, sn, options);
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import { HTTPError } from "ky";
|
||||
import type { CorpConfig } from "../../../core/config/types.js";
|
||||
import { CliError, validationError } from "../../../core/errors.js";
|
||||
import { createHoseOpenClient } from "./client.js";
|
||||
|
||||
/**
|
||||
* EBot approval callback (`POST api/openapi/v1/approval`) — the OpenAPI call an
|
||||
* external service makes after processing an outbound message, so the EBot node
|
||||
* can advance (accept/refuse) or add approvers. Only EBot-node approvals are
|
||||
* supported upstream; everything else comes back as business code 412.
|
||||
*/
|
||||
|
||||
export const EBOT_APPROVAL_ACTIONS = ["accept", "refuse", "preAdd", "aftAdd"] as const;
|
||||
export type EbotApprovalAction = (typeof EBOT_APPROVAL_ACTIONS)[number];
|
||||
|
||||
export const EBOT_RESUBMIT_METHODS = ["FROM_START", "TO_REJECTOR"] as const;
|
||||
|
||||
export type EbotApprovalCallbackParams = {
|
||||
signKey: string;
|
||||
flowId: string;
|
||||
nodeId: string;
|
||||
action: EbotApprovalAction;
|
||||
comment: string;
|
||||
policy?: "ALL" | "ANY";
|
||||
addApproverIds?: string[];
|
||||
rejectTo?: string;
|
||||
resubmitMethod?: "FROM_START" | "TO_REJECTOR";
|
||||
};
|
||||
|
||||
export type EbotApprovalCallbackResult = {
|
||||
code: string;
|
||||
message: string;
|
||||
};
|
||||
|
||||
export async function executeEbotApprovalCallback(
|
||||
corp: CorpConfig,
|
||||
params: EbotApprovalCallbackParams
|
||||
): Promise<EbotApprovalCallbackResult> {
|
||||
if (corp.source.type !== "hose") {
|
||||
throw validationError(
|
||||
`企业「${corp.name}」非合思(hose)租户,无法调用合思 OpenAPI 审批回调。`
|
||||
);
|
||||
}
|
||||
|
||||
const appKey = corp.source.appKey ?? corp.source.key;
|
||||
const appSecurity = corp.source.appSecurity ?? corp.source.password;
|
||||
if (!appKey || !appSecurity) {
|
||||
throw validationError(
|
||||
`缺少合思凭证:企业「${corp.name}」(id: ${corp.id}) 未配置 appKey/appSecurity(或 key/password),无法换取 accessToken 执行审批回调。`
|
||||
);
|
||||
}
|
||||
|
||||
if ((params.action === "preAdd" || params.action === "aftAdd") && (!params.addApproverIds || params.addApproverIds.length === 0)) {
|
||||
throw validationError(
|
||||
`执行${params.action === "preAdd" ? "前加签 (preAdd)" : "后加签 (aftAdd)"}时,必须通过 --add-approver-ids 指定加签审批人 ID 列表。`
|
||||
);
|
||||
}
|
||||
if (params.action === "aftAdd" && (params.addApproverIds?.length ?? 0) > 1 && !params.policy) {
|
||||
throw validationError(
|
||||
"后加签审批人超过 1 人时,必须指定会签方式 --policy ALL (会签) 或 --policy ANY (或签)。"
|
||||
);
|
||||
}
|
||||
|
||||
// The manual requires a token minted right before the callback: accessToken
|
||||
// expires quickly and stale reuse is not worth the risk on a flow write.
|
||||
const client = await createHoseOpenClient(corp, undefined, { force: true });
|
||||
|
||||
let response: unknown;
|
||||
try {
|
||||
response = await client.post("api/openapi/v1/approval", {
|
||||
json: {
|
||||
signKey: params.signKey,
|
||||
flowId: params.flowId,
|
||||
nodeId: params.nodeId,
|
||||
action: params.action,
|
||||
comment: params.comment,
|
||||
...(params.policy ? { policy: params.policy } : {}),
|
||||
...(params.addApproverIds?.length ? { addApproverIds: params.addApproverIds } : {}),
|
||||
...(params.rejectTo ? { rejectTo: params.rejectTo } : {}),
|
||||
...(params.resubmitMethod ? { resubmitMethod: params.resubmitMethod } : {})
|
||||
}
|
||||
}).json();
|
||||
} catch (error) {
|
||||
// HTTP 400 means our request body was rejected — an input problem, so the
|
||||
// caller gets exit 13 with the upstream body; HTTP 401/403 fall through to
|
||||
// the shared classifier (exit 11).
|
||||
if (error instanceof HTTPError && error.response.status === 400) {
|
||||
throw validationError(`合思审批回调参数被上游拒绝 (HTTP 400):${error.message}`);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
const rawObj = (response && typeof response === "object") ? (response as Record<string, unknown>) : {};
|
||||
const valueObj = rawObj.value && typeof rawObj.value === "object" ? (rawObj.value as Record<string, unknown>) : rawObj;
|
||||
const rawCode = valueObj.code ?? rawObj.code;
|
||||
const code = rawCode !== undefined ? String(rawCode) : undefined;
|
||||
const message = (typeof valueObj.message === "string" ? valueObj.message : (typeof rawObj.message === "string" ? rawObj.message : "")) || "";
|
||||
|
||||
if (code === "204") {
|
||||
return { code, message };
|
||||
}
|
||||
if (code === "401") {
|
||||
throw new CliError(
|
||||
"合思审批回调失败:签名秘钥 signKey 错误 (401)。" +
|
||||
"请核对出站消息配置中的 signKey(seal-use hose-ebot messages --reveal 可查看)。",
|
||||
11
|
||||
);
|
||||
}
|
||||
if (code === "400") {
|
||||
throw validationError(`合思审批回调参数错误 (400):${message || "请求参数错误"}`);
|
||||
}
|
||||
if (code === "412") {
|
||||
throw new CliError(
|
||||
`合思审批回调失败:业务前置条件不满足 (412):${message || "当前节点不可审批或已被处理"}。\n` +
|
||||
"👉 建议:运行 seal-use hose-ebot search <单号SN> 核对单据当前节点与出站记录。",
|
||||
1
|
||||
);
|
||||
}
|
||||
if (!code) {
|
||||
throw new Error(`合思审批回调未返回业务码,响应与预期不符:${JSON.stringify(response)}`);
|
||||
}
|
||||
throw new Error(`合思审批回调失败 (${code}):${message || "未知错误"}`);
|
||||
}
|
||||
@@ -38,13 +38,14 @@ export function createHoseOpenClientWithCredentials(
|
||||
|
||||
export async function createHoseOpenClient(
|
||||
corp: CorpConfig,
|
||||
customHeaders?: Record<string, string>
|
||||
customHeaders?: Record<string, string>,
|
||||
options?: { force?: boolean }
|
||||
): Promise<KyInstance> {
|
||||
if (corp.source.type !== "hose") {
|
||||
throw new Error(`Unsupported Hose source type: ${corp.source.type}. Expected 'hose'.`);
|
||||
}
|
||||
|
||||
const token = await ensureHoseOpenapiToken(corp);
|
||||
const token = await ensureHoseOpenapiToken(corp, { force: options?.force });
|
||||
return createHoseOpenClientWithCredentials(
|
||||
{
|
||||
domain: corp.source.domain,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
export * from "./types.js";
|
||||
export * from "./client.js";
|
||||
export * from "./api.js";
|
||||
export * from "./approval.js";
|
||||
@@ -465,7 +465,18 @@ export const approvalRunsCapabilities = [
|
||||
}
|
||||
const record = await resolveApprovalRunForUrl(client, params);
|
||||
const source = context.corp.source;
|
||||
const hoseDocumentUrl = stringFromUnknown(record?.sourceExtendData?.hosecloudViewUrl);
|
||||
let hoseDocumentUrl = stringFromUnknown(record?.sourceExtendData?.hosecloudViewUrl);
|
||||
const flowId = record?.sourceDocumentId;
|
||||
if (hoseDocumentUrl) {
|
||||
if (flowId && hoseDocumentUrl.includes("backlogId=") && !hoseDocumentUrl.includes("#/")) {
|
||||
hoseDocumentUrl = `${hoseDocumentUrl}#/backlogDetail/false/${encodeURIComponent(flowId)}`;
|
||||
}
|
||||
} else if (source.type === "hose" && flowId) {
|
||||
const hoseDomain = normalizeUrl(source.domain);
|
||||
const encodedFlowId = encodeURIComponent(flowId);
|
||||
const corpId = encodeURIComponent(source.corpId);
|
||||
hoseDocumentUrl = `${hoseDomain}/web/thirdparty.html?ekbCorpId=${corpId}&pageType=form&overdueTokenRedirect=&noPathCache=true&flowId=${encodedFlowId}&backlogId=#/backlogDetail/false/${encodedFlowId}`;
|
||||
}
|
||||
|
||||
const sealBaseUrl = resolveSealBaseUrl(context.corp);
|
||||
const sealResultUrl = `${sealBaseUrl}/approval-result/${record.id}`;
|
||||
@@ -478,13 +489,12 @@ export const approvalRunsCapabilities = [
|
||||
const expiresIn = params.expiresIn ?? 7200;
|
||||
|
||||
let ssoUrl: string | undefined;
|
||||
let sealSsoUrl: string | undefined;
|
||||
let hoseSsoUrl: string | undefined;
|
||||
let identity: { name?: string; staffId?: string; isAdmin?: boolean; providerUserId?: string } | undefined;
|
||||
let warning: string | undefined;
|
||||
|
||||
if (useAutoLogin) {
|
||||
if (isHoseDoc) {
|
||||
throw new Error("Auto-login (--auto-login) is only supported for Seal AI audit links (type: seal-result). To generate an auto-login link for Hose document page, please use: seal-use auth hose-link");
|
||||
}
|
||||
if (source.type !== "hose") {
|
||||
throw new Error(
|
||||
`Auto-login direct links currently support Hose-integrated enterprises (corp '${context.corp.id}' uses '${source.type}'). For Seal-native enterprises, use 'seal-use auth link' for authorized access.`
|
||||
@@ -498,7 +508,17 @@ export const approvalRunsCapabilities = [
|
||||
}
|
||||
|
||||
const targetPath = `/approval-result/${record.id}`;
|
||||
ssoUrl = `${sealBaseUrl}/api/auth/oauth2/session/oem-hosecloud?token=${encodeURIComponent(provisionalToken)}&path=${encodeURIComponent(targetPath)}`;
|
||||
sealSsoUrl = `${sealBaseUrl}/api/auth/oauth2/session/oem-hosecloud?token=${encodeURIComponent(provisionalToken)}&path=${encodeURIComponent(targetPath)}`;
|
||||
|
||||
if (record?.sourceDocumentId) {
|
||||
const hoseDomain = normalizeUrl(source.domain);
|
||||
const flowId = encodeURIComponent(record.sourceDocumentId);
|
||||
const corpId = encodeURIComponent(source.corpId);
|
||||
const token = encodeURIComponent(provisionalToken);
|
||||
hoseSsoUrl = `${hoseDomain}/web/thirdparty.html?accessToken=${token}&ekbCorpId=${corpId}&pageType=form&overdueTokenRedirect=&noPathCache=true&flowId=${flowId}&backlogId=#/backlogDetail/false/${flowId}`;
|
||||
}
|
||||
|
||||
ssoUrl = isHoseDoc ? (hoseSsoUrl ?? sealSsoUrl) : sealSsoUrl;
|
||||
|
||||
try {
|
||||
const me = await api.getMe(client);
|
||||
@@ -516,18 +536,21 @@ export const approvalRunsCapabilities = [
|
||||
|
||||
const userName = identity.name ?? "企业成员";
|
||||
const roleLabel = identity.isAdmin ? " (管理员)" : "";
|
||||
warning = `⚠️ 安全警示:该链接使用 [${userName}${roleLabel}] 身份签发,在 Seal AI 拥有全站操作权限。链接具备 ${Math.round(expiresIn / 3600 * 10) / 10} 小时时效,仅供受信任人员排查使用,请勿在外部公开分享。`;
|
||||
const targetSystem = isHoseDoc ? "合思 (Hose)" : "Seal AI";
|
||||
warning = `⚠️ 安全警示:该链接使用 [${userName}${roleLabel}] 身份签发,在 ${targetSystem} 拥有对应操作权限。链接具备 ${Math.round(expiresIn / 3600 * 10) / 10} 小时时效,仅供受信任人员排查使用,请勿在外部公开分享。`;
|
||||
|
||||
console.error(
|
||||
`⚠️ 安全警示 (免密直达链接):\n` +
|
||||
`• 身份主体:${userName}${roleLabel}\n` +
|
||||
`• 权限范围:持有该链接者在 Seal AI 中拥有该用户的完整操作权限(含系统设置与规则编辑)\n` +
|
||||
`• 时效性:换票凭证有效时间 ${expiresIn} 秒(${Math.round(expiresIn / 60)} 分钟),在浏览器打开后将保留 30 天会话\n` +
|
||||
`• 安全边界:该凭证绝不包含且无法访问合思 (Hose) 主系统;仅限内部排查,严禁在外部公开分享!`
|
||||
`• 目标系统:${targetSystem}\n` +
|
||||
`• 时效性:换票凭证有效时间 ${expiresIn} 秒(${Math.round(expiresIn / 60)} 分钟),在浏览器打开后将保留会话\n` +
|
||||
`• 安全边界:仅限内部排查,严禁在外部公开分享!`
|
||||
);
|
||||
}
|
||||
|
||||
const activeUrl = isHoseDoc ? hoseDocumentUrl : (useAutoLogin ? ssoUrl : sealResultUrl);
|
||||
const activeUrl = isHoseDoc
|
||||
? (useAutoLogin ? (hoseSsoUrl ?? hoseDocumentUrl) : hoseDocumentUrl)
|
||||
: (useAutoLogin ? sealSsoUrl : sealResultUrl);
|
||||
const activeMode = useAutoLogin ? "auto_login" : "direct";
|
||||
|
||||
return {
|
||||
@@ -536,6 +559,8 @@ export const approvalRunsCapabilities = [
|
||||
mode: activeMode,
|
||||
sealResultUrl,
|
||||
hoseDocumentUrl,
|
||||
sealSsoUrl,
|
||||
hoseSsoUrl,
|
||||
// Legacy compatibility fields
|
||||
documentUrl: hoseDocumentUrl,
|
||||
ssoUrl,
|
||||
@@ -549,7 +574,7 @@ export const approvalRunsCapabilities = [
|
||||
sourceSystem: record.sourceSystem,
|
||||
missing: {
|
||||
hoseDocumentUrl: !hoseDocumentUrl
|
||||
? `该审批运行未回写 hosecloudViewUrl,无法生成合思原单据直达链接;请到合思主系统以单据编号 ${record.sourceDocumentSN ?? record.sourceDocumentId ?? record.id} 检索原件,或检查该企业的 hosecloud 集成回写配置。`
|
||||
? `该审批运行未回写 hosecloudViewUrl 且缺少 sourceDocumentId,无法生成合思原单据直达链接;请到合思主系统以单据编号 ${record.sourceDocumentSN ?? record.sourceDocumentId ?? record.id} 检索原件,或检查该企业的 hosecloud 集成回写配置。`
|
||||
: undefined
|
||||
}
|
||||
};
|
||||
|
||||
@@ -892,6 +892,52 @@ describe("sealCapabilities", () => {
|
||||
expect(result.sealResultUrl).toBe("https://hose-corp-a.sealai.cc/approval-result/run-1");
|
||||
});
|
||||
|
||||
test("approval run url synthesizes hoseDocumentUrl from source.domain and sourceDocumentId when hosecloudViewUrl is missing", async () => {
|
||||
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunUrlGet");
|
||||
expect(tool).toBeDefined();
|
||||
|
||||
const handler = tool!.handler as CapabilityHandler;
|
||||
const result = await handler(
|
||||
fakeApprovalRunsClient(),
|
||||
{ recordId: "run-2" },
|
||||
fakeHoseContext()
|
||||
) as {
|
||||
hoseDocumentUrl?: string;
|
||||
documentUrl?: string;
|
||||
sealResultUrl?: string;
|
||||
missing?: Record<string, string>;
|
||||
};
|
||||
|
||||
const expectedHoseUrl = "https://app.ekuaibao.com/web/thirdparty.html?ekbCorpId=hose-corp-a&pageType=form&overdueTokenRedirect=&noPathCache=true&flowId=doc-source-2&backlogId=#/backlogDetail/false/doc-source-2";
|
||||
expect(result.hoseDocumentUrl).toBe(expectedHoseUrl);
|
||||
expect(result.documentUrl).toBe(expectedHoseUrl);
|
||||
expect(result.missing?.hoseDocumentUrl).toBeUndefined();
|
||||
});
|
||||
|
||||
test("approval run url supports auto-login for hose-document", async () => {
|
||||
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunUrlGet");
|
||||
expect(tool).toBeDefined();
|
||||
primeHoseEnterpriseUrl("corp-a", "https://app.ekuaibao.com/web/home.html?accessToken=close-token");
|
||||
|
||||
const handler = tool!.handler as CapabilityHandler;
|
||||
const result = await handler(
|
||||
fakeApprovalRunsClient(),
|
||||
{ recordId: "run-2", type: "hose-document", autoLogin: true },
|
||||
fakeHoseContext()
|
||||
) as {
|
||||
url?: string;
|
||||
hoseSsoUrl?: string;
|
||||
type?: string;
|
||||
mode?: string;
|
||||
};
|
||||
|
||||
const expectedSsoUrl = "https://app.ekuaibao.com/web/thirdparty.html?accessToken=close-token&ekbCorpId=hose-corp-a&pageType=form&overdueTokenRedirect=&noPathCache=true&flowId=doc-source-2&backlogId=#/backlogDetail/false/doc-source-2";
|
||||
expect(result.type).toBe("hose_document");
|
||||
expect(result.mode).toBe("auto_login");
|
||||
expect(result.url).toBe(expectedSsoUrl);
|
||||
expect(result.hoseSsoUrl).toBe(expectedSsoUrl);
|
||||
});
|
||||
|
||||
test("approval run url throws error without a document lookup", async () => {
|
||||
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunUrlGet");
|
||||
expect(tool).toBeDefined();
|
||||
@@ -1217,6 +1263,24 @@ describe("sealCapabilities", () => {
|
||||
expect(res.divergedRuns[0]?.sn).toBe("SN-001");
|
||||
expect(res.divergedRuns[0]?.triggeredConditions).toContain("缺失发票");
|
||||
expect(res.charts.vennSvg).toContain("<svg");
|
||||
|
||||
const rangeRes = await handler(mockClient, {
|
||||
startDate: "2026-08-12",
|
||||
endDate: "2026-09-18",
|
||||
templates: ["差旅报销"]
|
||||
}, fakeContext()) as {
|
||||
period: { start: string; end: string; label?: string };
|
||||
templateGroups: Array<{ template: string }>;
|
||||
};
|
||||
expect(rangeRes.period.start).toBe("2026-08-12");
|
||||
expect(rangeRes.period.end).toBe("2026-09-18");
|
||||
expect(rangeRes.templateGroups[0]?.template).toBe("差旅报销");
|
||||
|
||||
// 验证 maxRuns 突破了原本的 500 限制,传入 2000 校验合法
|
||||
expect(() => tool!.parameters.parse({ month: "2026-08", maxRuns: 2000 })).not.toThrow();
|
||||
const monthlyTool = sealCapabilities.find((item) => item.name === "sealReportMonthlyGet");
|
||||
expect(monthlyTool).toBeDefined();
|
||||
expect(() => monthlyTool!.parameters.parse({ month: "2026-08", maxRuns: 2000 })).not.toThrow();
|
||||
});
|
||||
|
||||
test("deploy hosecloud configure saves integration and rejects missing customApiUrl", async () => {
|
||||
@@ -1414,6 +1478,15 @@ function fakeApprovalRunsClient(requests: string[] = []): KyInstance {
|
||||
},
|
||||
createdAt: 1780898164536
|
||||
}
|
||||
: url === "api/v1/approvals/run-2"
|
||||
? {
|
||||
id: "run-2",
|
||||
status: "completed",
|
||||
taskMode: "assisted",
|
||||
sourceDocumentSN: "B26001808",
|
||||
sourceDocumentId: "doc-source-2",
|
||||
createdAt: 1780887698055
|
||||
}
|
||||
: {
|
||||
total: 3,
|
||||
records: [
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import * as api from "../api.js";
|
||||
import { maskHoseSecurity, normalizeBaseUrl } from "../../../core/auth/hose.js";
|
||||
import { confirmationRequired, validationError } from "../../../core/errors.js";
|
||||
import { fetchHoseOutboundLogs, fetchHoseOutboundMessages } from "../../hose/close/outbound.js";
|
||||
import { executeEbotApprovalCallback } from "../../hose/open/approval.js";
|
||||
import { listHoseIntegrations, selectHoseIntegration } from "../outbound/push.js";
|
||||
import type { CapabilityContext } from "./helpers.js";
|
||||
|
||||
/**
|
||||
* The niche Hose outbound loop, exposed under the first-level `seal-use hose-ebot`
|
||||
* command: discover outbound records by document SN, discover the outbound
|
||||
* message configs (and their signKey), then write the EBot approval callback.
|
||||
*/
|
||||
export const hoseCapabilities = [
|
||||
{
|
||||
name: "sealHoseOutboundSearch",
|
||||
description: "按单号搜索合思出站消息调用记录(出站触发 INVOKING / 回调 CALLBACK),返回含唯一 id 的记录列表",
|
||||
parameters: z.object({
|
||||
sn: z.string().describe("合思单号 (flowId.form.code)"),
|
||||
type: z
|
||||
.enum(["invoking", "callback"])
|
||||
.optional()
|
||||
.describe("记录类型筛选:invoking=出站触发,callback=回调;缺省全部"),
|
||||
limit: z
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.max(100)
|
||||
.optional()
|
||||
.default(20)
|
||||
.describe("返回条数上限(默认 20,最大 100)"),
|
||||
reveal: z.boolean().optional().describe("明文返回记录中的 signKey(默认脱敏)")
|
||||
}),
|
||||
handler: async (
|
||||
_client: KyInstance,
|
||||
params: { sn: string; type?: "invoking" | "callback"; limit: number; reveal?: boolean },
|
||||
context: CapabilityContext
|
||||
) => {
|
||||
// The type filter applies client-side, so over-fetch first to keep the
|
||||
// requested page size after filtering.
|
||||
const serverCount = params.type ? Math.min(params.limit * 4, 100) : params.limit;
|
||||
const allRecords = await fetchHoseOutboundLogs(context.corp, params.sn, { limit: serverCount });
|
||||
const filtered = params.type
|
||||
? allRecords.filter((record) => (record.type ?? "").toLowerCase() === params.type)
|
||||
: allRecords;
|
||||
const records = filtered.slice(0, params.limit);
|
||||
|
||||
return {
|
||||
corpId: context.corp.id,
|
||||
sn: params.sn,
|
||||
type: params.type ?? "all",
|
||||
count: records.length,
|
||||
revealed: params.reveal === true,
|
||||
records: records.map((record) =>
|
||||
record.request?.signKey
|
||||
? {
|
||||
...record,
|
||||
request: {
|
||||
...record.request,
|
||||
signKey: params.reveal
|
||||
? record.request.signKey
|
||||
: maskHoseSecurity(record.request.signKey)
|
||||
}
|
||||
}
|
||||
: record
|
||||
)
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "sealHoseOutboundMessages",
|
||||
description: "列出合思侧全部出站消息配置(含 signKey、回调地址、启用状态),用于发现 EBot 出站消息及其签名密钥",
|
||||
parameters: z.object({
|
||||
reveal: z.boolean().optional().describe("明文返回 signKey(默认脱敏为 8...4 形式)"),
|
||||
type: z
|
||||
.enum(["flow", "message"])
|
||||
.optional()
|
||||
.describe("按消息类型过滤:flow=审批流 EBot 出站,message=完成回调/通知")
|
||||
}),
|
||||
handler: async (
|
||||
_client: KyInstance,
|
||||
params: { reveal?: boolean; type?: "flow" | "message" },
|
||||
context: CapabilityContext
|
||||
) => {
|
||||
const messages = await fetchHoseOutboundMessages(context.corp);
|
||||
const filtered = params.type
|
||||
? messages.filter((message) => message.messageType === params.type)
|
||||
: messages;
|
||||
return {
|
||||
corpId: context.corp.id,
|
||||
corpName: context.corp.name,
|
||||
count: filtered.length,
|
||||
revealed: params.reveal === true,
|
||||
messages: filtered.map((message) => ({
|
||||
...message,
|
||||
signKey: message.signKey
|
||||
? params.reveal
|
||||
? message.signKey
|
||||
: maskHoseSecurity(message.signKey)
|
||||
: undefined
|
||||
}))
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "sealHoseApprovalCallback",
|
||||
description: "【回调审批】调用合思开放接口执行 EBot 审批回调(同意/驳回/加签),向审批流回写结果;需 --yes/--confirm,或 --dry-run 预览",
|
||||
parameters: z.object({
|
||||
signKey: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("出站消息签名密钥;缺省时从本企业 Seal 合思集成解析(仅一个集成时自动选择)"),
|
||||
flowId: z.string().describe("单据 ID(出站消息中的 flowId)"),
|
||||
nodeId: z.string().describe("当前 EBot 节点 ID(出站消息中的 nodeId)"),
|
||||
action: z
|
||||
.enum(["accept", "refuse", "preAdd", "aftAdd"])
|
||||
.describe("accept 同意 / refuse 驳回 / preAdd 前加签 / aftAdd 后加签"),
|
||||
comment: z.string().describe("审批意见"),
|
||||
policy: z.enum(["ALL", "ANY"]).optional().describe("会签方式:ALL 会签 / ANY 或签(后加签超过一人时必填)"),
|
||||
addApproverIds: z.array(z.string()).optional().describe("前后加签审批人 ID 列表(后加签时必填)"),
|
||||
rejectTo: z.string().optional().describe("驳回目标节点 ID;缺省按 EBot 节点驳回配置"),
|
||||
resubmitMethod: z
|
||||
.enum(["FROM_START", "TO_REJECTOR"])
|
||||
.optional()
|
||||
.describe("驳回后重提方式:FROM_START 重新走审批流 / TO_REJECTOR 直接送审至此节点"),
|
||||
dryRun: z.boolean().optional().default(false).describe("仅预览回调请求,不执行"),
|
||||
confirm: z.boolean().optional().describe("明确确认执行回调;CLI 使用 --yes 或 --confirm")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: {
|
||||
signKey?: string;
|
||||
flowId: string;
|
||||
nodeId: string;
|
||||
action: "accept" | "refuse" | "preAdd" | "aftAdd";
|
||||
comment: string;
|
||||
policy?: "ALL" | "ANY";
|
||||
addApproverIds?: string[];
|
||||
rejectTo?: string;
|
||||
resubmitMethod?: "FROM_START" | "TO_REJECTOR";
|
||||
dryRun?: boolean;
|
||||
confirm?: boolean;
|
||||
},
|
||||
context: CapabilityContext
|
||||
) => {
|
||||
if (!params.dryRun && params.confirm !== true) {
|
||||
throw confirmationRequired(
|
||||
"Refusing to run the Hose EBot approval callback without --yes or --confirm. Use --dry-run to preview first.",
|
||||
`seal-use hose-ebot callback --flow-id ${params.flowId} --node-id ${params.nodeId} --action ${params.action} --comment "${params.comment}" --dry-run --corp ${context.corp.id}`
|
||||
);
|
||||
}
|
||||
if (context.corp.source.type !== "hose") {
|
||||
throw validationError(
|
||||
`企业「${context.corp.name}」非合思(hose)租户,无法执行合思 EBot 审批回调。`
|
||||
);
|
||||
}
|
||||
|
||||
// An explicit signKey (typically discovered via `hose-ebot messages --reveal`)
|
||||
// skips the Seal-side lookup; without one the configured integration decides.
|
||||
let signKey = params.signKey?.trim();
|
||||
if (!signKey) {
|
||||
const config = await api.getApprovalStylePreferences(client);
|
||||
const integration = selectHoseIntegration({
|
||||
integrations: listHoseIntegrations(config),
|
||||
corpName: context.corp.name,
|
||||
corpId: context.corp.id
|
||||
});
|
||||
signKey = integration.signKey;
|
||||
}
|
||||
if (!signKey) {
|
||||
throw validationError(
|
||||
`企业「${context.corp.name}」的合思出站配置未保存 signKey,请重新执行 configure。`
|
||||
);
|
||||
}
|
||||
|
||||
const payload = {
|
||||
signKey,
|
||||
flowId: params.flowId,
|
||||
nodeId: params.nodeId,
|
||||
action: params.action,
|
||||
comment: params.comment,
|
||||
...(params.policy ? { policy: params.policy } : {}),
|
||||
...(params.addApproverIds?.length ? { addApproverIds: params.addApproverIds } : {}),
|
||||
...(params.rejectTo ? { rejectTo: params.rejectTo } : {}),
|
||||
...(params.resubmitMethod ? { resubmitMethod: params.resubmitMethod } : {})
|
||||
};
|
||||
|
||||
if (params.dryRun) {
|
||||
return {
|
||||
preview: true,
|
||||
corpId: context.corp.id,
|
||||
endpoint: `${normalizeBaseUrl(context.corp.source.domain)}/api/openapi/v1/approval`,
|
||||
payload: { ...payload, signKey: maskHoseSecurity(signKey) },
|
||||
note: "仅预览:正式执行需去掉 --dry-run 并追加 --yes(届时实时换取 accessToken 后回调)。"
|
||||
};
|
||||
}
|
||||
|
||||
const result = await executeEbotApprovalCallback(context.corp, payload);
|
||||
|
||||
console.error(`✓ 回调审批成功 (code ${result.code}): ${result.message}`);
|
||||
console.error(
|
||||
`👉 Next action: seal-use hose-ebot search <单号SN> --corp ${context.corp.id} 核对该单出站/回调记录`
|
||||
);
|
||||
|
||||
return {
|
||||
corpId: context.corp.id,
|
||||
flowId: params.flowId,
|
||||
nodeId: params.nodeId,
|
||||
action: params.action,
|
||||
ok: true,
|
||||
...result
|
||||
};
|
||||
}
|
||||
}
|
||||
];
|
||||
@@ -7,6 +7,7 @@ import { webhookCapabilities } from "./webhook.js";
|
||||
import { approvalRunsCapabilities } from "./approval-runs.js";
|
||||
import { simulationCapabilities } from "./simulation.js";
|
||||
import { deployCapabilities } from "./deploy.js";
|
||||
import { hoseCapabilities } from "./hose.js";
|
||||
import { preferenceCapabilities } from "./preference.js";
|
||||
import { reportCapabilities } from "./reports.js";
|
||||
|
||||
@@ -23,6 +24,7 @@ export const sealCapabilities = [
|
||||
...approvalRunsCapabilities,
|
||||
...simulationCapabilities,
|
||||
...deployCapabilities,
|
||||
...hoseCapabilities,
|
||||
...preferenceCapabilities,
|
||||
...reportCapabilities
|
||||
];
|
||||
@@ -90,6 +92,8 @@ export const SEAL_READ_ONLY_CAPABILITIES: ReadonlySet<string> = new Set([
|
||||
"sealDeployHosecloudRequirements",
|
||||
"sealDeployHosecloudStatus",
|
||||
"sealExpensesList",
|
||||
"sealHoseOutboundMessages",
|
||||
"sealHoseOutboundSearch",
|
||||
"sealInsightExport",
|
||||
"sealInsightPerformanceGet",
|
||||
"sealInsightRisksByTagGet",
|
||||
@@ -138,6 +142,7 @@ export const SEAL_MUTATING_CAPABILITIES: ReadonlySet<string> = new Set([
|
||||
"sealDeployHosecloudConfigure",
|
||||
"sealDeployHosecloudSync",
|
||||
"sealDeployHosecloudTestOutbound",
|
||||
"sealHoseApprovalCallback",
|
||||
"sealInsightRecordAnalyze",
|
||||
"sealPreferenceDecisionUpdate",
|
||||
"sealPreferenceThinkingDepthPoliciesRemove",
|
||||
|
||||
@@ -7,62 +7,123 @@ export const reportCapabilities = [
|
||||
{
|
||||
name: "sealReportMonthlyGet",
|
||||
description:
|
||||
"生成月度 AI 审核准确率报告(Markdown)。按模板结构从效能/风险/审批运行接口取数填充,返回填充后的内容与各章节数据完备度;无法从上游取得的口径(人工准确率、失准原因分类)如实标注而非编造",
|
||||
"生成 AI 审核准确率报告(Markdown)。按模板结构从效能/风险/审批运行接口取数填充,返回填充后的内容与各章节数据完备度;无法从上游取得的口径(人工准确率、失准原因分类)如实标注而非编造",
|
||||
parameters: z.object({
|
||||
startDate: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("统计起始日期 (YYYY-MM-DD)"),
|
||||
endDate: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("统计截止日期 (YYYY-MM-DD)"),
|
||||
month: z
|
||||
.string()
|
||||
.regex(/^\d{4}-\d{2}$/)
|
||||
.describe("统计月份,YYYY-MM"),
|
||||
.optional()
|
||||
.describe("统计月份 (YYYY-MM,可选快捷方式)"),
|
||||
templates: z
|
||||
.array(z.string())
|
||||
.optional()
|
||||
.describe("单据模板白名单列表(可选,未指定则统计全量单据模板)"),
|
||||
templatePath: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("自定义模板 Markdown 路径;缺省用随 CLI 内嵌的仓内 monthly.md,不依赖当前目录"),
|
||||
reportId: z.string().optional().describe("自定义报告编号(RPT-YYYYMM-XXXXXX)"),
|
||||
ledgerPath: z.string().optional().describe("本地已编辑/已裁决的台账文件路径 (.xlsx 或 .csv),传入时直接以该台账为唯一事实源"),
|
||||
maxRuns: z
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.max(500)
|
||||
.max(100000)
|
||||
.optional()
|
||||
.describe("拉取审批运行明细分块的上限,默认 500")
|
||||
.describe("拉取审批运行明细分块的上限(可选,未指定时默认拉取指定时间区间内的全量单据,最大安全上限 100000)"),
|
||||
allowUnreviewed: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.describe("是否跳过前置裁决门禁(当存在未裁决的分歧单时强行出具草稿,默认 false)")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: { month: string; templatePath?: string; reportId?: string; maxRuns?: number },
|
||||
params: {
|
||||
startDate?: string;
|
||||
endDate?: string;
|
||||
month?: string;
|
||||
templates?: string[];
|
||||
ledgerPath?: string;
|
||||
templatePath?: string;
|
||||
reportId?: string;
|
||||
maxRuns?: number;
|
||||
allowUnreviewed?: boolean;
|
||||
},
|
||||
context: CapabilityContext
|
||||
) =>
|
||||
buildMonthlyReport(client, {
|
||||
startDate: params.startDate,
|
||||
endDate: params.endDate,
|
||||
month: params.month,
|
||||
templates: params.templates,
|
||||
ledgerPath: params.ledgerPath,
|
||||
corp: { id: context.corp.id, name: context.corp.name },
|
||||
templatePath: params.templatePath,
|
||||
reportId: params.reportId,
|
||||
maxRuns: params.maxRuns
|
||||
maxRuns: params.maxRuns,
|
||||
allowUnreviewed: params.allowUnreviewed
|
||||
})
|
||||
},
|
||||
{
|
||||
name: "sealReportDataGet",
|
||||
description:
|
||||
"获取月度 AI 审核报告的轻量纯结构化数据包(效能指标、分模板统计、风险标签、人机分歧单据列表与单个触发条件)。不依赖 Markdown 模板,供 Agent 交互复核或填充文档",
|
||||
"获取 AI 审核报告的轻量纯结构化数据包(效能指标、分模板统计、风险标签、人机分歧单据列表与单个触发条件)。不依赖 Markdown 模板,供 Agent 交互复核或填充文档",
|
||||
parameters: z.object({
|
||||
startDate: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("统计起始日期 (YYYY-MM-DD)"),
|
||||
endDate: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("统计截止日期 (YYYY-MM-DD)"),
|
||||
month: z
|
||||
.string()
|
||||
.regex(/^\d{4}-\d{2}$/)
|
||||
.describe("统计月份,YYYY-MM"),
|
||||
.optional()
|
||||
.describe("统计月份 (YYYY-MM,可选快捷方式)"),
|
||||
templates: z
|
||||
.array(z.string())
|
||||
.optional()
|
||||
.describe("单据模板白名单列表(可选,未指定则统计全量单据模板)"),
|
||||
ledgerPath: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("本地已编辑/已裁决的台账文件路径 (.xlsx 或 .csv),传入时直接以该台账为唯一事实源"),
|
||||
maxRuns: z
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.max(500)
|
||||
.max(100000)
|
||||
.optional()
|
||||
.describe("拉取审批运行明细分块的上限,默认 500")
|
||||
.describe("拉取审批运行明细分块的上限(可选,未指定时默认拉取指定时间区间内的全量单据,最大安全上限 100000)")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: { month: string; maxRuns?: number },
|
||||
params: {
|
||||
startDate?: string;
|
||||
endDate?: string;
|
||||
month?: string;
|
||||
templates?: string[];
|
||||
ledgerPath?: string;
|
||||
maxRuns?: number;
|
||||
},
|
||||
context: CapabilityContext
|
||||
) =>
|
||||
getMonthlyReportData(client, {
|
||||
startDate: params.startDate,
|
||||
endDate: params.endDate,
|
||||
month: params.month,
|
||||
templates: params.templates,
|
||||
ledgerPath: params.ledgerPath,
|
||||
corp: { id: context.corp.id, name: context.corp.name },
|
||||
maxRuns: params.maxRuns
|
||||
})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Seal 报告生成与渲染域 (`src/domains/seal/reports`)
|
||||
|
||||
本模块为 `seal-use` 的离线报告引擎,负责企业 AI 审核月度准确率报告的**数据提取、Markdown 填充、格式校验、独立图表生成、自包含 HTML 编译与 A4 PDF 打印级导出**。全流程零 Python 依赖、零外部 OSS 水印图床依赖。
|
||||
本模块为 `seal-use` 的离线报告引擎,负责企业 AI 审核报告(验收、上线、周期审计)的**数据提取、台账导出导入、Markdown 填充、格式校验、独立图表生成、自包含 HTML 编译与 A4 PDF 打印级导出**。全流程零 Python 依赖、零外部 OSS 水印图床依赖。
|
||||
|
||||
---
|
||||
|
||||
@@ -18,7 +18,7 @@ src/domains/seal/reports/
|
||||
│ ├── describe.ts # 解析 Markdown 标题并反推各章节数据需求
|
||||
│ ├── collect.ts # 通过 Seal API 抓取单据指标,合并人工复核记录
|
||||
│ ├── render.ts # 模板占位填充与章节内容排版
|
||||
│ ├── monthly.ts # 月度报告顶层调度器 (buildMonthlyReport)
|
||||
│ ├── monthly.ts # 报告顶层调度器 (buildMonthlyReport / 支持 --ledger 离线台账)
|
||||
│ ├── review-store.ts # 人工复核判定本地存储(JSONL 租户分片)
|
||||
│ └── index.ts # 流水线出口
|
||||
├── render/ # 渲染与排版引擎底层
|
||||
@@ -31,6 +31,7 @@ src/domains/seal/reports/
|
||||
│ └── index.ts # 校验门禁出口
|
||||
├── export/ # 文件系统整包导出与资产收拢
|
||||
│ ├── files.ts # 报告整包打包器 (exportReportPackage) 及文件保存
|
||||
│ ├── ledger.ts # 明细台账双端依据导出 (Excel/CSV) 与自由裁量加载
|
||||
│ └── index.ts # 导出器出口
|
||||
├── templates/ # 模板与静态资源
|
||||
│ ├── monthly.md # 标准月度报告 Markdown 模板
|
||||
|
||||
@@ -70,9 +70,9 @@ describe("bundled report templates", () => {
|
||||
test("saved built-in Markdown and Chinese assets validate from an unrelated directory", async () => {
|
||||
const dir = workspace();
|
||||
const saved = saveReportMarkdown(BUILTIN_MONTHLY_TEMPLATE, BUILTIN_TEMPLATE_PATH, join(dir, "my 报告.md"));
|
||||
expect(saved.assets).toHaveLength(3);
|
||||
expect(saved.assets).toHaveLength(1);
|
||||
process.chdir(tmpdir());
|
||||
expect(await validateReportFile(saved.file)).toMatchObject({ valid: true, figures: 3, issues: [] });
|
||||
expect(await validateReportFile(saved.file)).toMatchObject({ valid: true, figures: 1, issues: [] });
|
||||
});
|
||||
|
||||
test("custom images with matching basenames are copied separately and leave source files intact", async () => {
|
||||
@@ -210,6 +210,45 @@ describe("local report CLI", () => {
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(existsSync(join(packageDir, "报告.md.assets", "1-chart-4x.png"))).toBe(true);
|
||||
expect(existsSync(join(packageDir, "报告.md.assets", "chart-4x.png"))).toBe(true);
|
||||
}, 15000);
|
||||
}, 35000);
|
||||
|
||||
test("CLI report ledger and --ledger options work seamlessly", async () => {
|
||||
const dir = workspace();
|
||||
const csvContent = [
|
||||
"审核ID(recordId),单据编号(SN),单据模板,单据标题/事由,提交人,费用承担部门,跑批时间,AI审批决策,AI审核完整意见与违规详情,人工审批结论,人工审批批注/驳回说明,人机一致性,复核定性裁决,复核人,复核批注说明,审批耗时(秒)",
|
||||
'rec-1,SN-1,差旅报销,出差,张三,技术部,2026-08-15 10:00:00,驳回,超标,同意,领导特批,分歧,AI判断正确 / 人工判断错误,专家,依据合规,12',
|
||||
'rec-2,SN-2,差旅报销,采购,李四,行政部,2026-08-16 11:00:00,同意,合规,同意,通过,一致,双方判断均正确,专家,无误,8'
|
||||
].join("\n");
|
||||
const csvFile = join(dir, "my-ledger.csv");
|
||||
writeFileSync(csvFile, csvContent);
|
||||
|
||||
// 1. seal-use report ledger --ledger <file> --out <file.xlsx>
|
||||
const xlsxOut = join(dir, "converted.xlsx");
|
||||
const ledgerRes = await runCli(["report", "ledger", "--ledger", csvFile, "--out", xlsxOut, "--corp", "test-corp"]);
|
||||
expect(ledgerRes.exitCode).toBe(0);
|
||||
expect(existsSync(xlsxOut)).toBe(true);
|
||||
|
||||
// 2. seal-use report data --ledger <file> --corp test-corp
|
||||
const dataRes = await runCli(["report", "data", "--ledger", csvFile, "--corp", "test-corp"]);
|
||||
expect(dataRes.exitCode).toBe(0);
|
||||
const parsedData = JSON.parse(dataRes.stdout);
|
||||
expect(parsedData.templateGroups).toHaveLength(1);
|
||||
expect(parsedData.templateGroups[0].template).toBe("差旅报销");
|
||||
expect(parsedData.metrics.aiAccuracy).toBe(100);
|
||||
|
||||
// 3. seal-use report review import <file> --corp test-corp
|
||||
const importRes = await runCli(["report", "review", "import", csvFile, "--corp", "test-corp"]);
|
||||
expect(importRes.exitCode).toBe(0);
|
||||
const parsedImport = JSON.parse(importRes.stdout);
|
||||
expect(parsedImport.importedCount).toBe(2);
|
||||
|
||||
// 4. seal-use report generate --ledger <file> --out <report.md> --corp test-corp
|
||||
const reportOut = join(dir, "generated-report.md");
|
||||
const genRes = await runCli(["report", "generate", "--ledger", csvFile, "--out", reportOut, "--corp", "test-corp"]);
|
||||
expect(genRes.exitCode).toBe(0);
|
||||
expect(existsSync(reportOut)).toBe(true);
|
||||
const md = readFileSync(reportOut, "utf8");
|
||||
expect(md).toContain("差旅报销");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1 +1,2 @@
|
||||
export * from "./files.js";
|
||||
export * from "./ledger.js";
|
||||
@@ -1,7 +1,35 @@
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import ExcelJS from "exceljs";
|
||||
import type { ReportBlock, ReportData } from "../pipeline/collect.js";
|
||||
import { validationError } from "../../../../core/errors.js";
|
||||
import {
|
||||
polarityOf,
|
||||
populateReviewsAndMetrics,
|
||||
type ReportBlock,
|
||||
type ReportData
|
||||
} from "../pipeline/collect.js";
|
||||
import { ReviewsMap, type ReviewRecord } from "../pipeline/review-store.js";
|
||||
|
||||
function csvEscape(val: string | number | undefined): string {
|
||||
export const REPORT_LEDGER_HEADERS = [
|
||||
"审核ID(recordId)",
|
||||
"单据编号(SN)",
|
||||
"单据模板",
|
||||
"单据标题/事由",
|
||||
"提交人",
|
||||
"费用承担部门",
|
||||
"跑批时间",
|
||||
"AI审批决策",
|
||||
"AI审核完整意见与违规详情",
|
||||
"人工审批结论",
|
||||
"人工审批批注/驳回说明",
|
||||
"人机一致性",
|
||||
"复核定性裁决",
|
||||
"复核人",
|
||||
"复核批注说明",
|
||||
"审批耗时(秒)"
|
||||
] as const;
|
||||
|
||||
function csvEscape(val: string | number | undefined | null): string {
|
||||
if (val === undefined || val === null) return "";
|
||||
const str = String(val).replace(/\r?\n/g, " ").trim();
|
||||
if (/[",\n]/.test(str)) {
|
||||
@@ -10,46 +38,118 @@ function csvEscape(val: string | number | undefined): string {
|
||||
return str;
|
||||
}
|
||||
|
||||
function formatAgreement(agreement: ReportBlock["agreement"]): string {
|
||||
export function formatAgreement(agreement: ReportBlock["agreement"]): string {
|
||||
if (agreement === "agreed") return "一致";
|
||||
if (agreement === "diverged") return "分歧";
|
||||
return "未完结/流转中";
|
||||
}
|
||||
|
||||
function formatVerdict(block: ReportBlock): string {
|
||||
/**
|
||||
* 将 AI 审核摘要与命中的具体规则风险详情合成为完整的审核意见文本
|
||||
*/
|
||||
export function formatAiOpinion(block: { aiSummary?: string; conditions?: string[] }): string {
|
||||
const parts: string[] = [];
|
||||
if (block.aiSummary && block.aiSummary.trim()) {
|
||||
parts.push(block.aiSummary.trim());
|
||||
}
|
||||
if (block.conditions && block.conditions.length > 0) {
|
||||
const condStr = block.conditions.map((c, i) => `${i + 1}. ${c}`).join("; ");
|
||||
if (!parts.some((p) => p.includes(condStr))) {
|
||||
parts.push(`【触发违规/风险项】${condStr}`);
|
||||
}
|
||||
}
|
||||
return parts.join("\n") || "—";
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化复核裁决定性措辞:
|
||||
* 严密区分「单据违规判定(通过/驳回)」与「审核行为复核(判断正确/判定误判)」,杜绝含混的“失准”造成歧义。
|
||||
*/
|
||||
export function formatVerdict(block: ReportBlock): string {
|
||||
if (block.agreement === "unknown") return "待人工审批完结";
|
||||
const v = block.verdict;
|
||||
if (v === "both_correct" || (!v && block.agreement === "agreed")) return "双方一致正确 (D1/D2)";
|
||||
if (v === "ai_correct" || (!v && block.agreement === "diverged")) return "AI 依规正确 / 人工失准 (D4)";
|
||||
if (v === "human_correct") return "人工合理 / AI 失准";
|
||||
if (v === "both_wrong") return "双方均失准";
|
||||
if (v === "both_correct" || (!v && block.agreement === "agreed")) return "双方判断均正确";
|
||||
if (v === "ai_correct") return "AI 判断正确 / 人工判断错误";
|
||||
if (v === "human_correct") return "人工判断正确 / AI 判定误判";
|
||||
if (v === "both_wrong") return "双方判定均误判";
|
||||
if (v === "undecided") return "存疑待定";
|
||||
return "待复核";
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建带 UTF-8 BOM 的月度跑批与人工复核明细台账 CSV
|
||||
* 解析人或 Agent 在 Excel/CSV 中填入的复核裁决定性文本,映射为标准 verdict
|
||||
*/
|
||||
export function parseVerdictText(text: string | number | undefined | null): ReviewRecord["verdict"] | undefined {
|
||||
if (text === undefined || text === null) return undefined;
|
||||
const str = String(text).trim();
|
||||
if (!str || str === "—" || str === "-" || str === "待复核" || str === "待人工审批完结") return undefined;
|
||||
const lower = str.toLowerCase();
|
||||
|
||||
// 1. ai_correct (AI判断正确 / 人工判断错误)
|
||||
if (
|
||||
lower.includes("ai_correct") ||
|
||||
/ai.*(正确|依规|判对|看对)/i.test(str) ||
|
||||
/人工.*(错误|误判|失准|漏审|看错|漏判)/i.test(str) ||
|
||||
lower.includes("d4")
|
||||
) {
|
||||
if (/人工.*(正确|合理)/i.test(str) && /ai.*(错误|误判|失准)/i.test(str)) {
|
||||
return "human_correct";
|
||||
}
|
||||
return "ai_correct";
|
||||
}
|
||||
|
||||
// 2. human_correct (人工判断正确 / AI判定误判)
|
||||
if (
|
||||
lower.includes("human_correct") ||
|
||||
/人工.*(正确|合理|判对|看对)/i.test(str) ||
|
||||
/ai.*(误判|错误|失准|误报|漏报|漏审)/i.test(str)
|
||||
) {
|
||||
return "human_correct";
|
||||
}
|
||||
|
||||
// 3. both_correct (双方判断均正确)
|
||||
if (
|
||||
lower.includes("both_correct") ||
|
||||
/双方.*(正确|合理|无误)/i.test(str) ||
|
||||
/一致.*正确/i.test(str) ||
|
||||
lower.includes("d1") ||
|
||||
lower.includes("d2")
|
||||
) {
|
||||
return "both_correct";
|
||||
}
|
||||
|
||||
// 4. both_wrong (双方判定均误判)
|
||||
if (
|
||||
lower.includes("both_wrong") ||
|
||||
/双方.*(误判|错误|失准)/i.test(str) ||
|
||||
/都.*(错|误判)/i.test(str)
|
||||
) {
|
||||
return "both_wrong";
|
||||
}
|
||||
|
||||
// 5. undecided (存疑待定)
|
||||
if (
|
||||
lower.includes("undecided") ||
|
||||
/存疑|待定|暂不确定|无法判定/i.test(str)
|
||||
) {
|
||||
return "undecided";
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建带 UTF-8 BOM 的跑批与人工复核明细台账 CSV
|
||||
*/
|
||||
export function buildReportLedgerCsv(data: ReportData): string {
|
||||
const headers = [
|
||||
"单据编号(SN)",
|
||||
"单据模板",
|
||||
"单据标题/事由",
|
||||
"提交人",
|
||||
"费用承担部门",
|
||||
"跑批时间",
|
||||
"AI审批决策",
|
||||
"人工审批结论",
|
||||
"人机一致性",
|
||||
"复核定性结论",
|
||||
"复核人",
|
||||
"复核批注说明",
|
||||
"审批耗时(秒)",
|
||||
"AI审核意见摘要"
|
||||
];
|
||||
const headers = [...REPORT_LEDGER_HEADERS];
|
||||
|
||||
const rows = data.blocks.map((block) => {
|
||||
const review = data.reviews.get(block.sn);
|
||||
const review = data.reviews instanceof ReviewsMap
|
||||
? data.reviews.get({ recordId: block.recordId, sn: block.sn })
|
||||
: (data.reviews as Map<string, ReviewRecord>).get(block.sn);
|
||||
return [
|
||||
block.recordId || "—",
|
||||
block.sn,
|
||||
block.template || "—",
|
||||
block.title || "—",
|
||||
@@ -57,13 +157,14 @@ export function buildReportLedgerCsv(data: ReportData): string {
|
||||
block.department || "—",
|
||||
block.createdAt || "—",
|
||||
block.aiDecision || "—",
|
||||
formatAiOpinion(block),
|
||||
block.humanResult || "—",
|
||||
block.humanComment || "—",
|
||||
formatAgreement(block.agreement),
|
||||
formatVerdict(block),
|
||||
review?.reviewedBy || "—",
|
||||
review?.note || "—",
|
||||
block.durationSeconds ?? "",
|
||||
block.aiSummary || "—"
|
||||
review?.reviewedBy || block.reviewedBy || "—",
|
||||
review?.note || block.reviewNote || "—",
|
||||
block.durationSeconds ?? ""
|
||||
].map(csvEscape).join(",");
|
||||
});
|
||||
|
||||
@@ -71,7 +172,7 @@ export function buildReportLedgerCsv(data: ReportData): string {
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建双 Sheet 的专业月度跑批与复核台账 Excel (.xlsx)
|
||||
* 构建双 Sheet 的专业跑批与复核台账 Excel (.xlsx)
|
||||
*/
|
||||
export async function buildReportLedgerXlsx(data: ReportData): Promise<Buffer> {
|
||||
const workbook = new ExcelJS.Workbook();
|
||||
@@ -83,20 +184,22 @@ export async function buildReportLedgerXlsx(data: ReportData): Promise<Buffer> {
|
||||
});
|
||||
|
||||
detailSheet.columns = [
|
||||
{ header: "单据编号(SN)", key: "sn", width: 16 },
|
||||
{ header: "审核ID(recordId)", key: "recordId", width: 28 },
|
||||
{ header: "单据编号(SN)", key: "sn", width: 18 },
|
||||
{ header: "单据模板", key: "template", width: 20 },
|
||||
{ header: "单据标题/事由", key: "title", width: 32 },
|
||||
{ header: "提交人", key: "submitter", width: 12 },
|
||||
{ header: "费用承担部门", key: "department", width: 22 },
|
||||
{ header: "跑批时间", key: "createdAt", width: 20 },
|
||||
{ header: "AI审批决策", key: "aiDecision", width: 15 },
|
||||
{ header: "人工审批结论", key: "humanResult", width: 16 },
|
||||
{ header: "AI审批决策", key: "aiDecision", width: 14 },
|
||||
{ header: "AI审核完整意见与违规详情", key: "aiOpinion", width: 55 },
|
||||
{ header: "人工审批结论", key: "humanResult", width: 15 },
|
||||
{ header: "人工审批批注/驳回说明", key: "humanComment", width: 38 },
|
||||
{ header: "人机一致性", key: "agreement", width: 14 },
|
||||
{ header: "复核定性结论", key: "verdict", width: 24 },
|
||||
{ header: "复核定性裁决", key: "verdict", width: 26 },
|
||||
{ header: "复核人", key: "reviewedBy", width: 14 },
|
||||
{ header: "复核批注说明", key: "note", width: 38 },
|
||||
{ header: "审批耗时(秒)", key: "durationSeconds", width: 14 },
|
||||
{ header: "AI审核意见摘要", key: "aiSummary", width: 55 }
|
||||
{ header: "审批耗时(秒)", key: "durationSeconds", width: 14 }
|
||||
];
|
||||
|
||||
const headerRow = detailSheet.getRow(1);
|
||||
@@ -106,8 +209,11 @@ export async function buildReportLedgerXlsx(data: ReportData): Promise<Buffer> {
|
||||
headerRow.height = 24;
|
||||
|
||||
for (const block of data.blocks) {
|
||||
const review = data.reviews.get(block.sn);
|
||||
const review = data.reviews instanceof ReviewsMap
|
||||
? data.reviews.get({ recordId: block.recordId, sn: block.sn })
|
||||
: (data.reviews as Map<string, ReviewRecord>).get(block.sn);
|
||||
const row = detailSheet.addRow({
|
||||
recordId: block.recordId || "—",
|
||||
sn: block.sn,
|
||||
template: block.template || "—",
|
||||
title: block.title || "—",
|
||||
@@ -115,13 +221,14 @@ export async function buildReportLedgerXlsx(data: ReportData): Promise<Buffer> {
|
||||
department: block.department || "—",
|
||||
createdAt: block.createdAt || "—",
|
||||
aiDecision: block.aiDecision || "—",
|
||||
aiOpinion: formatAiOpinion(block),
|
||||
humanResult: block.humanResult || "—",
|
||||
humanComment: block.humanComment || "—",
|
||||
agreement: formatAgreement(block.agreement),
|
||||
verdict: formatVerdict(block),
|
||||
reviewedBy: review?.reviewedBy || "—",
|
||||
note: review?.note || "—",
|
||||
durationSeconds: block.durationSeconds ?? "",
|
||||
aiSummary: block.aiSummary || "—"
|
||||
reviewedBy: review?.reviewedBy || block.reviewedBy || "—",
|
||||
note: review?.note || block.reviewNote || "—",
|
||||
durationSeconds: block.durationSeconds ?? ""
|
||||
});
|
||||
row.alignment = { vertical: "top", wrapText: true };
|
||||
}
|
||||
@@ -175,6 +282,241 @@ export async function buildReportLedgerXlsx(data: ReportData): Promise<Buffer> {
|
||||
return Buffer.from(arrayBuffer);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 CSV 行(支持引号转义与换行)
|
||||
*/
|
||||
function parseCsvRows(content: string): string[][] {
|
||||
const rows: string[][] = [];
|
||||
let currentRow: string[] = [];
|
||||
let currentCell = "";
|
||||
let inQuotes = false;
|
||||
const text = content.charCodeAt(0) === 0xfeff ? content.slice(1) : content;
|
||||
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const char = text[i];
|
||||
const next = text[i + 1];
|
||||
|
||||
if (inQuotes) {
|
||||
if (char === '"') {
|
||||
if (next === '"') {
|
||||
currentCell += '"';
|
||||
i++;
|
||||
} else {
|
||||
inQuotes = false;
|
||||
}
|
||||
} else {
|
||||
currentCell += char;
|
||||
}
|
||||
} else {
|
||||
if (char === '"') {
|
||||
inQuotes = true;
|
||||
} else if (char === ",") {
|
||||
currentRow.push(currentCell.trim());
|
||||
currentCell = "";
|
||||
} else if (char === "\n" || (char === "\r" && next === "\n")) {
|
||||
if (char === "\r") i++;
|
||||
currentRow.push(currentCell.trim());
|
||||
if (currentRow.some((c) => c !== "")) {
|
||||
rows.push(currentRow);
|
||||
}
|
||||
currentRow = [];
|
||||
currentCell = "";
|
||||
} else if (char !== "\r") {
|
||||
currentCell += char;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (currentCell || currentRow.length > 0) {
|
||||
currentRow.push(currentCell.trim());
|
||||
if (currentRow.some((c) => c !== "")) {
|
||||
rows.push(currentRow);
|
||||
}
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从本地已编辑/已裁剪的 Excel (.xlsx) 或 CSV 台账文件逆向解析载入 ReportData。
|
||||
* 核心设计边界:
|
||||
* 1. 严格以本地台账为唯一事实源,绝不越界回查云端接口;
|
||||
* 2. Agent 从台账中剔除的模板和单据,完全不参与后续报告和指标统计;
|
||||
* 3. 自动识别台账中填入的「复核定性裁决」,作为权威判定计算人机一致率与准确率;
|
||||
* 4. 门禁校验仅校验当前台账内部剩余行的数据完备性。
|
||||
*/
|
||||
export async function loadReportDataFromLedger(
|
||||
filePath: string,
|
||||
options?: { corp?: { id: string; name: string } }
|
||||
): Promise<ReportData> {
|
||||
const resolvedPath = resolve(filePath);
|
||||
if (!existsSync(resolvedPath)) {
|
||||
throw validationError(`台账文件不存在: ${resolvedPath}`);
|
||||
}
|
||||
|
||||
let rawRows: string[][] = [];
|
||||
|
||||
if (resolvedPath.endsWith(".xlsx")) {
|
||||
const workbook = new ExcelJS.Workbook();
|
||||
await workbook.xlsx.readFile(resolvedPath);
|
||||
const sheet = workbook.worksheets.find((w) => w.name.includes("明细")) ?? workbook.worksheets[0];
|
||||
if (!sheet) {
|
||||
throw validationError(`Excel 文件中未找到有效工作表: ${resolvedPath}`);
|
||||
}
|
||||
sheet.eachRow((row) => {
|
||||
const values: string[] = [];
|
||||
row.eachCell({ includeEmpty: true }, (cell) => {
|
||||
let text = "";
|
||||
if (cell.value !== null && cell.value !== undefined) {
|
||||
if (typeof cell.value === "object" && "text" in cell.value) {
|
||||
text = String(cell.value.text);
|
||||
} else if (typeof cell.value === "object" && "result" in cell.value) {
|
||||
text = String(cell.value.result);
|
||||
} else {
|
||||
text = String(cell.value);
|
||||
}
|
||||
}
|
||||
values.push(text.trim());
|
||||
});
|
||||
rawRows.push(values);
|
||||
});
|
||||
} else {
|
||||
const content = readFileSync(resolvedPath, "utf8");
|
||||
rawRows = parseCsvRows(content);
|
||||
}
|
||||
|
||||
if (rawRows.length < 2) {
|
||||
throw validationError(`台账文件中没有有效数据行: ${resolvedPath}`);
|
||||
}
|
||||
|
||||
const headerRow = rawRows[0]!;
|
||||
const colMap: Record<string, number> = {};
|
||||
headerRow.forEach((h, idx) => {
|
||||
const clean = String(h).trim().toLowerCase();
|
||||
if (clean.includes("审核id") || clean.includes("recordid")) colMap.recordId = idx;
|
||||
else if (clean.includes("单据编号") || clean.includes("sn")) colMap.sn = idx;
|
||||
else if (clean.includes("模板") || clean.includes("template")) colMap.template = idx;
|
||||
else if (clean.includes("事由") || clean.includes("标题") || clean.includes("title")) colMap.title = idx;
|
||||
else if (clean.includes("提交人") || clean.includes("submitter")) colMap.submitter = idx;
|
||||
else if (clean.includes("部门") || clean.includes("department")) colMap.department = idx;
|
||||
else if (clean.includes("时间") || clean.includes("createdat")) colMap.createdAt = idx;
|
||||
else if (clean.includes("ai审批决策") || clean.includes("aidecision") || clean.includes("ai决策")) colMap.aiDecision = idx;
|
||||
else if (clean.includes("ai审核") || clean.includes("ai意见") || clean.includes("aisummary") || clean.includes("违规详情")) colMap.aiSummary = idx;
|
||||
else if (clean.includes("人工审批结论") || clean.includes("人工结论") || clean.includes("humanresult")) colMap.humanResult = idx;
|
||||
else if (clean.includes("人工审批批注") || clean.includes("驳回说明") || clean.includes("驳回原因") || clean.includes("humancomment")) colMap.humanComment = idx;
|
||||
else if (clean.includes("人机一致性") || clean.includes("一致性") || clean.includes("agreement")) colMap.agreement = idx;
|
||||
else if (clean.includes("复核定性") || clean.includes("裁决") || clean.includes("verdict")) colMap.verdict = idx;
|
||||
else if (clean.includes("复核人") || clean.includes("reviewedby")) colMap.reviewedBy = idx;
|
||||
else if (clean.includes("复核批注") || clean.includes("批注说明") || clean.includes("reviewnote") || clean.includes("note")) colMap.reviewNote = idx;
|
||||
else if (clean.includes("耗时") || clean.includes("duration")) colMap.durationSeconds = idx;
|
||||
});
|
||||
|
||||
const blocks: ReportBlock[] = [];
|
||||
const reviews = new ReviewsMap();
|
||||
const createdDates: string[] = [];
|
||||
|
||||
for (let i = 1; i < rawRows.length; i++) {
|
||||
const row = rawRows[i]!;
|
||||
const sn = (colMap.sn !== undefined ? row[colMap.sn] : undefined) || `ROW-${i}`;
|
||||
const recordId = colMap.recordId !== undefined && row[colMap.recordId] !== "—" ? row[colMap.recordId] : undefined;
|
||||
const template = (colMap.template !== undefined ? row[colMap.template] : undefined) || "未标注模板";
|
||||
const title = colMap.title !== undefined ? row[colMap.title] : undefined;
|
||||
const submitter = colMap.submitter !== undefined ? row[colMap.submitter] : undefined;
|
||||
const department = colMap.department !== undefined ? row[colMap.department] : undefined;
|
||||
const createdAt = colMap.createdAt !== undefined ? row[colMap.createdAt] : undefined;
|
||||
if (createdAt && createdAt !== "—") createdDates.push(createdAt.slice(0, 10));
|
||||
|
||||
const aiDecision = colMap.aiDecision !== undefined ? row[colMap.aiDecision] : undefined;
|
||||
const aiSummary = colMap.aiSummary !== undefined ? row[colMap.aiSummary] : undefined;
|
||||
const humanResult = colMap.humanResult !== undefined ? row[colMap.humanResult] : undefined;
|
||||
const humanComment = colMap.humanComment !== undefined ? row[colMap.humanComment] : undefined;
|
||||
|
||||
let agreement: ReportBlock["agreement"] = "unknown";
|
||||
const agreementText = colMap.agreement !== undefined ? row[colMap.agreement] ?? "" : "";
|
||||
if (agreementText.includes("一致") || agreementText.toLowerCase() === "agreed") {
|
||||
agreement = "agreed";
|
||||
} else if (agreementText.includes("分歧") || agreementText.toLowerCase() === "diverged") {
|
||||
agreement = "diverged";
|
||||
} else if (agreementText.includes("未完结") || agreementText.includes("流转中")) {
|
||||
agreement = "unknown";
|
||||
} else {
|
||||
const aiPol = polarityOf(aiDecision);
|
||||
const humPol = polarityOf(humanResult);
|
||||
if (aiPol === "unknown" || humPol === "unknown") agreement = "unknown";
|
||||
else if (aiPol === humPol) agreement = "agreed";
|
||||
else agreement = "diverged";
|
||||
}
|
||||
|
||||
const rawVerdict = colMap.verdict !== undefined ? row[colMap.verdict] : undefined;
|
||||
const verdict = parseVerdictText(rawVerdict);
|
||||
const reviewedBy = colMap.reviewedBy !== undefined && row[colMap.reviewedBy] !== "—" ? row[colMap.reviewedBy] : undefined;
|
||||
const reviewNote = colMap.reviewNote !== undefined && row[colMap.reviewNote] !== "—" ? row[colMap.reviewNote] : undefined;
|
||||
|
||||
if (verdict || reviewedBy || reviewNote) {
|
||||
reviews.set({
|
||||
recordId,
|
||||
sn,
|
||||
verdict: verdict ?? (agreement === "agreed" ? "both_correct" : "undecided"),
|
||||
note: reviewNote,
|
||||
reviewedBy,
|
||||
recordedAt: new Date().toISOString()
|
||||
});
|
||||
}
|
||||
|
||||
const durVal = colMap.durationSeconds !== undefined ? Number(row[colMap.durationSeconds]) : undefined;
|
||||
|
||||
blocks.push({
|
||||
recordId,
|
||||
sn,
|
||||
template,
|
||||
title,
|
||||
submitter,
|
||||
department,
|
||||
createdAt,
|
||||
durationSeconds: Number.isFinite(durVal) ? durVal : undefined,
|
||||
aiDecision,
|
||||
humanResult,
|
||||
agreement,
|
||||
aiSummary,
|
||||
humanComment,
|
||||
verdict,
|
||||
reviewedBy,
|
||||
reviewNote
|
||||
});
|
||||
}
|
||||
|
||||
createdDates.sort();
|
||||
const startIso = createdDates[0] ?? new Date().toISOString().slice(0, 10);
|
||||
const endIso = createdDates[createdDates.length - 1] ?? startIso;
|
||||
const periodLabel = startIso === endIso ? startIso : `${startIso} ~ ${endIso}`;
|
||||
|
||||
const metrics = populateReviewsAndMetrics(blocks, reviews);
|
||||
|
||||
return {
|
||||
period: {
|
||||
start: startIso,
|
||||
end: endIso,
|
||||
label: periodLabel,
|
||||
month: startIso.slice(0, 7) === endIso.slice(0, 7) ? startIso.slice(0, 7) : undefined
|
||||
},
|
||||
corp: {
|
||||
id: options?.corp?.id ?? "local-ledger",
|
||||
name: options?.corp?.name ?? "本地台账企业"
|
||||
},
|
||||
fetched: {
|
||||
blocks: true,
|
||||
templateGroups: true,
|
||||
performance: metrics.performance !== undefined,
|
||||
riskStats: false,
|
||||
riskDetails: false
|
||||
},
|
||||
blocks,
|
||||
templateGroups: metrics.templateGroups,
|
||||
reviews,
|
||||
humanAccuracy: metrics.humanAccuracy,
|
||||
notes: metrics.notes,
|
||||
performance: metrics.performance
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 当针对独立 Markdown 文件直接执行 report export 且无预生成台账时,从 Markdown 表格提取构建台账
|
||||
*/
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import * as api from "../../api.js";
|
||||
import { formatBeijingIso } from "../../../../core/config/timestamps.js";
|
||||
import { validationError } from "../../../../core/errors.js";
|
||||
import type { ApprovalRun } from "../../types.js";
|
||||
import type { ReportDemand } from "./describe.js";
|
||||
import { loadReviews, type ReviewRecord } from "./review-store.js";
|
||||
import { loadReviews, ReviewsMap, type ReviewRecord } from "./review-store.js";
|
||||
|
||||
/** 单据在决策空间里的极性:同意为正向、驳回/终止为反向,用于比对 AI 与人工是否同向。 */
|
||||
type Polarity = "pass" | "reject" | "unknown";
|
||||
|
||||
function polarityOf(value: string | undefined): Polarity {
|
||||
export function polarityOf(value: string | undefined): Polarity {
|
||||
if (!value) return "unknown";
|
||||
const text = value.trim();
|
||||
if (/同意|通过|approve|pass|已支付|审批完成/i.test(text)) return "pass";
|
||||
@@ -31,7 +32,7 @@ export type ReportBlock = {
|
||||
aiSummary: string | undefined;
|
||||
humanComment: string | undefined;
|
||||
conditions?: string[];
|
||||
/** 本地人工裁决结论(若该 SN 已 review),来自 review-store */
|
||||
/** 本地人工裁决结论(来自 review-store,支持 recordId 与 sn 双键匹配) */
|
||||
verdict?: ReviewRecord["verdict"];
|
||||
reviewNote?: string;
|
||||
reviewedBy?: string;
|
||||
@@ -52,7 +53,7 @@ export type ReportTemplateGroup = {
|
||||
|
||||
export type ReportData = {
|
||||
/** 报告信息表要用的上下文 */
|
||||
period: { start: string; end: string; month: string };
|
||||
period: { start: string; end: string; label?: string; month?: string };
|
||||
corp: { id: string; name: string };
|
||||
/** 需求 → 是否已按需取数(渲染器据此判断该章节数据完备度) */
|
||||
fetched: Record<ReportDemand, boolean>;
|
||||
@@ -71,8 +72,8 @@ export type ReportData = {
|
||||
};
|
||||
blocks: ReportBlock[];
|
||||
templateGroups: ReportTemplateGroup[];
|
||||
/** 该租户该月的人工裁决(SN → 记录),由 review-store 载入,用于回填人工准确率 */
|
||||
reviews: Map<string, ReviewRecord>;
|
||||
/** 该租户的人工裁决集合,由 review-store 载入 */
|
||||
reviews: ReviewsMap | Map<string, ReviewRecord>;
|
||||
/** 人工审核准确率(%):仅当本地裁决覆盖样本时有值 */
|
||||
humanAccuracy?: number;
|
||||
/** 章节数据完备性标记,渲染时逐节如实写入 */
|
||||
@@ -88,34 +89,93 @@ export type ReportData = {
|
||||
};
|
||||
|
||||
export type CollectOptions = {
|
||||
month: string; // YYYY-MM
|
||||
startDate?: string;
|
||||
endDate?: string;
|
||||
month?: string; // 兼容旧单月参数
|
||||
corp: { id: string; name: string };
|
||||
/** 用于拉明细分块的上限,防御性封顶 */
|
||||
/** 单据模板白名单,未指定则拉取全量模板 */
|
||||
templates?: string[];
|
||||
/** 用于拉明细分块的上限(可选,未指定时默认拉取指定时间区间全量单据,最大安全上限 100000) */
|
||||
maxRuns?: number;
|
||||
/** 是否载入本地人工裁决(默认载入);关掉则 humanAccuracy 恒为不可得 */
|
||||
loadReviews?: boolean;
|
||||
};
|
||||
|
||||
function monthRange(month: string): { startDate: string; endDate: string; startIsoDate: string; endIsoDate: string } {
|
||||
const [y, m] = month.split("-").map(Number);
|
||||
if (!y || !m) throw new Error(`Invalid month "${month}", expected YYYY-MM`);
|
||||
const start = Date.UTC(y, m - 1, 1);
|
||||
const end = Date.UTC(y, m, 1) - 1;
|
||||
const lastDay = new Date(y, m, 0).getDate();
|
||||
const pad = (n: number) => String(n).padStart(2, "0");
|
||||
const startIsoDate = `${y}-${pad(m)}-01`;
|
||||
const endIsoDate = `${y}-${pad(m)}-${pad(lastDay)}`;
|
||||
return { startDate: String(start), endDate: String(end), startIsoDate, endIsoDate };
|
||||
export function resolveReportPeriod(options: {
|
||||
startDate?: string | number;
|
||||
endDate?: string | number;
|
||||
month?: string;
|
||||
}): {
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
startIsoDate: string;
|
||||
endIsoDate: string;
|
||||
startBeijingIso: string;
|
||||
endBeijingIso: string;
|
||||
periodLabel: string;
|
||||
month?: string;
|
||||
} {
|
||||
if (options.startDate && options.endDate) {
|
||||
const sStr = String(options.startDate).slice(0, 10);
|
||||
const eStr = String(options.endDate).slice(0, 10);
|
||||
const sTs = Date.parse(`${sStr}T00:00:00+08:00`);
|
||||
const eTs = Date.parse(`${eStr}T23:59:59.999+08:00`);
|
||||
if (Number.isNaN(sTs) || Number.isNaN(eTs)) {
|
||||
throw validationError(`Invalid date range: "${options.startDate}" to "${options.endDate}"`);
|
||||
}
|
||||
const startIsoDate = sStr;
|
||||
const endIsoDate = eStr;
|
||||
const startBeijingIso = formatBeijingIso(sTs);
|
||||
const endBeijingIso = formatBeijingIso(eTs);
|
||||
const periodLabel = `${startIsoDate} ~ ${endIsoDate}`;
|
||||
const month = startIsoDate.slice(0, 7) === endIsoDate.slice(0, 7) ? startIsoDate.slice(0, 7) : `${startIsoDate.slice(0, 7)}~${endIsoDate.slice(0, 7)}`;
|
||||
return {
|
||||
startDate: String(sTs),
|
||||
endDate: String(eTs),
|
||||
startIsoDate,
|
||||
endIsoDate,
|
||||
startBeijingIso,
|
||||
endBeijingIso,
|
||||
periodLabel,
|
||||
month
|
||||
};
|
||||
}
|
||||
|
||||
if (options.month) {
|
||||
const [y, m] = options.month.split("-").map(Number);
|
||||
if (!y || !m) throw validationError(`Invalid month "${options.month}", expected YYYY-MM`);
|
||||
const start = Date.UTC(y, m - 1, 1);
|
||||
const end = Date.UTC(y, m, 1) - 1;
|
||||
const lastDay = new Date(y, m, 0).getDate();
|
||||
const pad = (n: number) => String(n).padStart(2, "0");
|
||||
const startIsoDate = `${y}-${pad(m)}-01`;
|
||||
const endIsoDate = `${y}-${pad(m)}-${pad(lastDay)}`;
|
||||
return {
|
||||
startDate: String(start),
|
||||
endDate: String(end),
|
||||
startIsoDate,
|
||||
endIsoDate,
|
||||
startBeijingIso: formatBeijingIso(start),
|
||||
endBeijingIso: formatBeijingIso(end),
|
||||
periodLabel: `${startIsoDate} ~ ${endIsoDate}`,
|
||||
month: options.month
|
||||
};
|
||||
}
|
||||
|
||||
throw validationError("缺少统计起止时间:请指定 startDate 和 endDate(如 2026-08-12 至 2026-09-18)");
|
||||
}
|
||||
|
||||
/** 默认明细拉取安全兜底上限(100,000 笔),未指定限制时默认拉取全区间单据 */
|
||||
export const DEFAULT_MAX_REPORT_RUNS = 100_000;
|
||||
|
||||
/** 拉取报告所需数据。只取 demand 需要的部分,模板没提到的章节不发请求。 */
|
||||
export async function collectReportData(
|
||||
client: KyInstance,
|
||||
demands: Set<ReportDemand>,
|
||||
options: CollectOptions
|
||||
): Promise<ReportData> {
|
||||
const range = monthRange(options.month);
|
||||
const maxRuns = Math.min(options.maxRuns ?? 500, 500);
|
||||
const range = resolveReportPeriod(options);
|
||||
const maxRuns = options.maxRuns ?? DEFAULT_MAX_REPORT_RUNS;
|
||||
const fetched: Record<ReportDemand, boolean> = {
|
||||
performance: false,
|
||||
riskStats: false,
|
||||
@@ -126,17 +186,18 @@ export async function collectReportData(
|
||||
|
||||
const data: ReportData = {
|
||||
period: {
|
||||
start: formatBeijingIso(Number(range.startDate)),
|
||||
end: formatBeijingIso(Number(range.endDate)),
|
||||
month: options.month
|
||||
start: range.startBeijingIso,
|
||||
end: range.endBeijingIso,
|
||||
label: range.periodLabel,
|
||||
month: range.month
|
||||
},
|
||||
corp: options.corp,
|
||||
fetched,
|
||||
blocks: [],
|
||||
templateGroups: [],
|
||||
reviews: options.loadReviews === false
|
||||
? new Map()
|
||||
: loadReviews(options.corp.id, options.month),
|
||||
? new ReviewsMap()
|
||||
: loadReviews(options.corp.id),
|
||||
notes: {
|
||||
humanAccuracyAvailable: false,
|
||||
failureRateAvailable: false,
|
||||
@@ -196,20 +257,22 @@ export async function collectReportData(
|
||||
let offset = 0;
|
||||
try {
|
||||
while (runs.length < maxRuns) {
|
||||
const fetchLimit = Math.min(100, maxRuns - runs.length);
|
||||
const page = await api.listApprovalRuns(client, {
|
||||
offset,
|
||||
limit: 100,
|
||||
limit: fetchLimit,
|
||||
startDate: range.startDate,
|
||||
endDate: range.endDate
|
||||
});
|
||||
const records = page.records ?? [];
|
||||
if (!records.length) break;
|
||||
runs.push(...records);
|
||||
const toTake = records.slice(0, maxRuns - runs.length);
|
||||
runs.push(...toTake);
|
||||
offset += records.length;
|
||||
if (records.length < 100) break;
|
||||
if (records.length < fetchLimit || runs.length >= maxRuns) break;
|
||||
}
|
||||
|
||||
const blocks: ReportBlock[] = runs.map((record) => {
|
||||
let blocks: ReportBlock[] = runs.map((record) => {
|
||||
const summary = summarizeLocal(record);
|
||||
const aiPolarity = polarityOf(summary.aiDecision);
|
||||
const humanPolarity = polarityOf(summary.humanResult);
|
||||
@@ -236,6 +299,12 @@ export async function collectReportData(
|
||||
conditions: summary.conditions
|
||||
};
|
||||
});
|
||||
|
||||
if (options.templates && options.templates.length > 0) {
|
||||
const allowed = new Set(options.templates.map((t) => t.trim()));
|
||||
blocks = blocks.filter((b) => allowed.has(b.template));
|
||||
}
|
||||
|
||||
data.blocks = blocks;
|
||||
fetched.blocks = true;
|
||||
} catch {
|
||||
@@ -244,102 +313,151 @@ export async function collectReportData(
|
||||
}
|
||||
|
||||
data.notes.failureRateAvailable = data.performance !== undefined;
|
||||
data.notes.mismatchCategoriesAvailable = false; // 失准原因分类默认无上游字段,除非本地复核已全覆盖
|
||||
data.notes.mismatchCategoriesAvailable = false;
|
||||
|
||||
// 4. 人工裁决回填:把本地 review 挂到 blocks,并据此算人工准确率与复核后的 AI 准确率
|
||||
if (data.reviews.size > 0) {
|
||||
let reviewed = 0;
|
||||
let diverged = 0;
|
||||
let aiRight = 0;
|
||||
let humanRight = 0;
|
||||
let completedCount = 0;
|
||||
let completedReviewed = 0;
|
||||
let completedAiRight = 0;
|
||||
let completedHumanRight = 0;
|
||||
|
||||
for (const block of data.blocks) {
|
||||
if (block.agreement !== "unknown") completedCount += 1;
|
||||
const review = data.reviews.get(block.sn);
|
||||
if (review) {
|
||||
block.verdict = review.verdict;
|
||||
block.reviewNote = review.note;
|
||||
block.reviewedBy = review.reviewedBy;
|
||||
reviewed += 1;
|
||||
if (block.agreement === "diverged") diverged += 1;
|
||||
if (review.verdict === "human_correct" || review.verdict === "both_correct") humanRight += 1;
|
||||
if (review.verdict === "ai_correct" || review.verdict === "both_correct") aiRight += 1;
|
||||
if (block.agreement !== "unknown") {
|
||||
completedReviewed += 1;
|
||||
if (review.verdict === "human_correct" || review.verdict === "both_correct") completedHumanRight += 1;
|
||||
if (review.verdict === "ai_correct" || review.verdict === "both_correct") completedAiRight += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (reviewed > 0) {
|
||||
const useCompletedScope = completedCount > 0 && completedReviewed >= completedCount;
|
||||
const denom = useCompletedScope ? completedReviewed : reviewed;
|
||||
const hRight = useCompletedScope ? completedHumanRight : humanRight;
|
||||
const aRight = useCompletedScope ? completedAiRight : aiRight;
|
||||
|
||||
data.notes.reviewedCount = denom;
|
||||
data.notes.divergedCount = diverged;
|
||||
data.humanAccuracy = Number(((hRight / denom) * 100).toFixed(2));
|
||||
data.notes.humanAccuracyAvailable = true;
|
||||
|
||||
// 当本地复核已覆盖全量完结单据时,统一以完结复核口径(D1 + D2 + D4)更新 AI 准确率与有效样本量,消除“分歧单两头扣分”
|
||||
if (useCompletedScope && data.performance) {
|
||||
data.performance.approvalCount = denom;
|
||||
data.performance.accuracy = Number(((aRight / denom) * 100).toFixed(2));
|
||||
data.notes.mismatchCategoriesAvailable = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 5. 分模板统计(在 review 挂载后聚合,以便携带分模板的 AI/人工准确率与同意:驳回比例)
|
||||
if (demands.has("templateGroups") && data.blocks.length > 0) {
|
||||
const byTemplate = new Map<string, ReportTemplateGroup>();
|
||||
for (const block of data.blocks) {
|
||||
const key = block.template || "未标注模板";
|
||||
const group = byTemplate.get(key) ?? {
|
||||
template: key,
|
||||
total: 0,
|
||||
agreed: 0,
|
||||
diverged: 0,
|
||||
evaluated: 0,
|
||||
aiCorrect: 0,
|
||||
humanCorrect: 0,
|
||||
bothCorrect: 0,
|
||||
humanPass: 0,
|
||||
humanReject: 0
|
||||
};
|
||||
group.total += 1;
|
||||
if (block.agreement === "agreed") group.agreed += 1;
|
||||
if (block.agreement === "diverged") group.diverged += 1;
|
||||
if (block.agreement !== "unknown") {
|
||||
group.evaluated = (group.evaluated ?? 0) + 1;
|
||||
const hp = polarityOf(block.humanResult);
|
||||
if (hp === "pass") group.humanPass = (group.humanPass ?? 0) + 1;
|
||||
if (hp === "reject") group.humanReject = (group.humanReject ?? 0) + 1;
|
||||
const v = block.verdict;
|
||||
if (v === "both_correct" || (!v && block.agreement === "agreed")) {
|
||||
group.bothCorrect = (group.bothCorrect ?? 0) + 1;
|
||||
group.aiCorrect = (group.aiCorrect ?? 0) + 1;
|
||||
group.humanCorrect = (group.humanCorrect ?? 0) + 1;
|
||||
} else if (v === "ai_correct" || (!v && block.agreement === "diverged")) {
|
||||
group.aiCorrect = (group.aiCorrect ?? 0) + 1;
|
||||
} else if (v === "human_correct") {
|
||||
group.humanCorrect = (group.humanCorrect ?? 0) + 1;
|
||||
}
|
||||
}
|
||||
byTemplate.set(key, group);
|
||||
}
|
||||
data.templateGroups = [...byTemplate.values()].sort((a, b) => b.total - a.total);
|
||||
fetched.templateGroups = true;
|
||||
}
|
||||
// 4. 人工裁决回填与分模板指标聚合(支持 recordId 精确匹配与 sn 业务自然键匹配)
|
||||
const metrics = populateReviewsAndMetrics(data.blocks, data.reviews, data.performance, data.notes);
|
||||
data.templateGroups = metrics.templateGroups;
|
||||
data.humanAccuracy = metrics.humanAccuracy;
|
||||
data.notes = metrics.notes;
|
||||
data.performance = metrics.performance;
|
||||
fetched.templateGroups = demands.has("templateGroups") && data.templateGroups.length > 0;
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* 核心指标计算引擎:基于单据明细 blocks 与复核裁决集合 reviews,纯计算聚合各模板与全局指标。
|
||||
* 供 collectReportData(云端拉取)与 loadReportDataFromLedger(本地 Excel/CSV 驱动)共享 100% 一致口径。
|
||||
*/
|
||||
export function populateReviewsAndMetrics(
|
||||
blocks: ReportBlock[],
|
||||
reviews: ReviewsMap | Map<string, ReviewRecord>,
|
||||
initialPerformance?: ReportData["performance"],
|
||||
initialNotes?: Partial<ReportData["notes"]>
|
||||
): {
|
||||
templateGroups: ReportTemplateGroup[];
|
||||
humanAccuracy?: number;
|
||||
notes: ReportData["notes"];
|
||||
performance?: ReportData["performance"];
|
||||
} {
|
||||
const notes: ReportData["notes"] = {
|
||||
humanAccuracyAvailable: false,
|
||||
failureRateAvailable: initialPerformance !== undefined,
|
||||
mismatchCategoriesAvailable: false,
|
||||
...initialNotes
|
||||
};
|
||||
let performance = initialPerformance;
|
||||
|
||||
let reviewed = 0;
|
||||
let diverged = 0;
|
||||
let aiRight = 0;
|
||||
let humanRight = 0;
|
||||
let completedCount = 0;
|
||||
|
||||
for (const block of blocks) {
|
||||
if (block.agreement !== "unknown") completedCount += 1;
|
||||
const review = reviews instanceof ReviewsMap
|
||||
? reviews.get({ recordId: block.recordId, sn: block.sn })
|
||||
: reviews.get(block.sn);
|
||||
if (review) {
|
||||
block.verdict = review.verdict;
|
||||
block.reviewNote = review.note;
|
||||
block.reviewedBy = review.reviewedBy;
|
||||
reviewed += 1;
|
||||
if (block.agreement === "diverged") diverged += 1;
|
||||
} else if (block.verdict) {
|
||||
reviewed += 1;
|
||||
if (block.agreement === "diverged") diverged += 1;
|
||||
}
|
||||
|
||||
if (block.agreement !== "unknown") {
|
||||
const v = block.verdict;
|
||||
if (v === "both_correct" || (!v && block.agreement === "agreed")) {
|
||||
aiRight += 1;
|
||||
humanRight += 1;
|
||||
} else if (v === "ai_correct" || (!v && block.agreement === "diverged")) {
|
||||
aiRight += 1;
|
||||
} else if (v === "human_correct") {
|
||||
humanRight += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let humanAccuracy: number | undefined;
|
||||
if (reviewed > 0) {
|
||||
const divergedCount = blocks.filter((b) => b.agreement === "diverged").length;
|
||||
const unreviewedDiverged = blocks.filter((b) => b.agreement === "diverged" && !b.verdict).length;
|
||||
|
||||
notes.reviewedCount = completedCount > 0 ? completedCount : reviewed;
|
||||
notes.divergedCount = divergedCount;
|
||||
|
||||
if (completedCount > 0) {
|
||||
humanAccuracy = Number(((humanRight / completedCount) * 100).toFixed(2));
|
||||
notes.humanAccuracyAvailable = true;
|
||||
|
||||
if (!performance && unreviewedDiverged === 0) {
|
||||
performance = {
|
||||
approvalCount: completedCount,
|
||||
accuracy: Number(((aiRight / completedCount) * 100).toFixed(2)),
|
||||
sankey: { nodes: [], links: [] }
|
||||
};
|
||||
}
|
||||
|
||||
if (unreviewedDiverged === 0 && performance) {
|
||||
performance.approvalCount = completedCount;
|
||||
performance.accuracy = Number(((aiRight / completedCount) * 100).toFixed(2));
|
||||
notes.mismatchCategoriesAvailable = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const byTemplate = new Map<string, ReportTemplateGroup>();
|
||||
for (const block of blocks) {
|
||||
const key = block.template || "未标注模板";
|
||||
const group = byTemplate.get(key) ?? {
|
||||
template: key,
|
||||
total: 0,
|
||||
agreed: 0,
|
||||
diverged: 0,
|
||||
evaluated: 0,
|
||||
aiCorrect: 0,
|
||||
humanCorrect: 0,
|
||||
bothCorrect: 0,
|
||||
humanPass: 0,
|
||||
humanReject: 0
|
||||
};
|
||||
group.total += 1;
|
||||
if (block.agreement === "agreed") group.agreed += 1;
|
||||
if (block.agreement === "diverged") group.diverged += 1;
|
||||
if (block.agreement !== "unknown") {
|
||||
group.evaluated = (group.evaluated ?? 0) + 1;
|
||||
const hp = polarityOf(block.humanResult);
|
||||
if (hp === "pass") group.humanPass = (group.humanPass ?? 0) + 1;
|
||||
if (hp === "reject") group.humanReject = (group.humanReject ?? 0) + 1;
|
||||
const v = block.verdict;
|
||||
if (v === "both_correct" || (!v && block.agreement === "agreed")) {
|
||||
group.bothCorrect = (group.bothCorrect ?? 0) + 1;
|
||||
group.aiCorrect = (group.aiCorrect ?? 0) + 1;
|
||||
group.humanCorrect = (group.humanCorrect ?? 0) + 1;
|
||||
} else if (v === "ai_correct" || (!v && block.agreement === "diverged")) {
|
||||
group.aiCorrect = (group.aiCorrect ?? 0) + 1;
|
||||
} else if (v === "human_correct") {
|
||||
group.humanCorrect = (group.humanCorrect ?? 0) + 1;
|
||||
}
|
||||
}
|
||||
byTemplate.set(key, group);
|
||||
}
|
||||
const templateGroups = [...byTemplate.values()].sort((a, b) => b.total - a.total);
|
||||
|
||||
return {
|
||||
templateGroups,
|
||||
humanAccuracy,
|
||||
notes,
|
||||
performance
|
||||
};
|
||||
}
|
||||
|
||||
/** 局部摘要:避免依赖 capabilities/helpers 的深耦合,只取报告需要的字段。 */
|
||||
function summarizeLocal(record: ApprovalRun): {
|
||||
id: string;
|
||||
@@ -358,20 +476,25 @@ function summarizeLocal(record: ApprovalRun): {
|
||||
} {
|
||||
const result = (record.result ?? {}) as Record<string, unknown>;
|
||||
const document = (record.document ?? {}) as Record<string, unknown>;
|
||||
const manual = record.manualApprovalRecord as Record<string, unknown> | undefined;
|
||||
const manual =
|
||||
(record.manualApprovalRecord as Record<string, unknown> | undefined) ??
|
||||
(result.manualApprovalRecord as Record<string, unknown> | undefined) ??
|
||||
(document.manualApprovalRecord as Record<string, unknown> | undefined);
|
||||
const manualApproval = result.manualApproval as Record<string, unknown> | undefined;
|
||||
const pipelineData = record.pipelineData as Record<string, unknown> | undefined;
|
||||
|
||||
const aiDecision =
|
||||
firstString(result.decision) ??
|
||||
firstString((result.manualApproval as Record<string, unknown> | undefined)?.decision) ??
|
||||
firstString((result.manualApproval as Record<string, unknown> | undefined)?.result);
|
||||
firstString(manualApproval?.decision) ??
|
||||
firstString(manualApproval?.result);
|
||||
|
||||
const manualStatusObj = manual?.status as { label?: string; type?: string } | undefined;
|
||||
const humanResult =
|
||||
firstString(manualStatusObj?.label) ??
|
||||
firstString(manualStatusObj?.type) ??
|
||||
firstString(result.humanResult) ??
|
||||
firstString((result.manualApproval as Record<string, unknown> | undefined)?.humanResult) ??
|
||||
firstString(record.pipelineData && (record.pipelineData as Record<string, unknown>).humanResult);
|
||||
firstString(manualApproval?.humanResult) ??
|
||||
firstString(pipelineData?.humanResult);
|
||||
|
||||
const fields = (document.fields as Array<{ key?: string; label?: string; value?: unknown }> | undefined) ?? [];
|
||||
const tField = fields.find(
|
||||
@@ -396,6 +519,24 @@ function summarizeLocal(record: ApprovalRun): {
|
||||
const createdAt = record.createdAt ? formatBeijingIso(Number(record.createdAt) || Date.parse(String(record.createdAt))).slice(0, 19).replace("T", " ") : undefined;
|
||||
const durationSeconds = typeof record.durationMs === "number" ? Number((record.durationMs / 1000).toFixed(1)) : undefined;
|
||||
|
||||
const humanComment =
|
||||
firstString(manual?.rejectComment) ??
|
||||
firstString(manual?.comment) ??
|
||||
firstString(manual?.comments) ??
|
||||
firstString(manual?.opinion) ??
|
||||
firstString(manual?.approvalComment) ??
|
||||
firstString(manualApproval?.comment) ??
|
||||
firstString(manualApproval?.rejectComment) ??
|
||||
firstString(manualApproval?.opinion) ??
|
||||
firstString(result.humanComment) ??
|
||||
firstString(pipelineData?.rejectComment) ??
|
||||
firstString(pipelineData?.comment);
|
||||
|
||||
const aiSummary =
|
||||
firstString(result.summary) ??
|
||||
firstString(result.reason) ??
|
||||
firstString(result.explanation);
|
||||
|
||||
return {
|
||||
id: record.id,
|
||||
sn: record.sourceDocumentSN,
|
||||
@@ -407,11 +548,8 @@ function summarizeLocal(record: ApprovalRun): {
|
||||
durationSeconds,
|
||||
aiDecision,
|
||||
humanResult,
|
||||
aiSummary: firstString(result.summary),
|
||||
humanComment:
|
||||
firstString(manual?.rejectComment) ??
|
||||
firstString((result.manualApproval as Record<string, unknown> | undefined)?.comment) ??
|
||||
firstString(result.humanComment),
|
||||
aiSummary,
|
||||
humanComment,
|
||||
conditions: extractTriggeredConditions(result)
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,18 +1,26 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { collectReportData } from "./collect.js";
|
||||
import { collectReportData, polarityOf } from "./collect.js";
|
||||
import { loadReportDataFromLedger } from "../export/ledger.js";
|
||||
import { renderVennAccuracySvg } from "../charts/venn.js";
|
||||
|
||||
export type MonthlyReportDataOptions = {
|
||||
month: string; // YYYY-MM
|
||||
export type ReportDataOptions = {
|
||||
startDate?: string;
|
||||
endDate?: string;
|
||||
month?: string;
|
||||
corp: { id: string; name: string };
|
||||
templates?: string[];
|
||||
ledgerPath?: string;
|
||||
maxRuns?: number;
|
||||
};
|
||||
|
||||
export type MonthlyReportDataOptions = ReportDataOptions;
|
||||
|
||||
export type MonthlyReportDataResult = {
|
||||
period: {
|
||||
month: string;
|
||||
start: string;
|
||||
end: string;
|
||||
label?: string;
|
||||
month?: string;
|
||||
};
|
||||
corp: {
|
||||
id: string;
|
||||
@@ -100,12 +108,12 @@ export type MonthlyReportDataResult = {
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取月度报告的纯结构化数据包。
|
||||
* 获取审核报告的纯结构化数据包。
|
||||
* 不依赖 Markdown 模板,输出统一可直接消费的业务指标、分模板统计、待裁决分歧单据池与维恩图资产。
|
||||
*/
|
||||
export async function getMonthlyReportData(
|
||||
client: KyInstance,
|
||||
options: MonthlyReportDataOptions
|
||||
options: ReportDataOptions
|
||||
): Promise<MonthlyReportDataResult> {
|
||||
const demands = new Set<"performance" | "riskStats" | "riskDetails" | "blocks" | "templateGroups">([
|
||||
"performance",
|
||||
@@ -115,11 +123,16 @@ export async function getMonthlyReportData(
|
||||
"templateGroups"
|
||||
]);
|
||||
|
||||
const data = await collectReportData(client, demands, {
|
||||
month: options.month,
|
||||
corp: options.corp,
|
||||
maxRuns: options.maxRuns
|
||||
});
|
||||
const data = options.ledgerPath
|
||||
? await loadReportDataFromLedger(options.ledgerPath, { corp: options.corp })
|
||||
: await collectReportData(client, demands, {
|
||||
startDate: options.startDate,
|
||||
endDate: options.endDate,
|
||||
month: options.month,
|
||||
corp: options.corp,
|
||||
templates: options.templates,
|
||||
maxRuns: options.maxRuns
|
||||
});
|
||||
|
||||
const total = data.performance?.approvalCount || data.blocks.length || 0;
|
||||
const rawAiAcc = data.performance?.accuracy;
|
||||
@@ -192,7 +205,7 @@ export async function getMonthlyReportData(
|
||||
|
||||
const templateGroups = data.templateGroups.map((g) => {
|
||||
const evaluated = g.evaluated ?? g.total;
|
||||
const aiAccuracy = evaluated > 0 && g.aiCorrect !== undefined ? Number(((g.aiCorrect / evaluated) * 100).toFixed(2)) : undefined;
|
||||
const groupAiAccuracy = evaluated > 0 && g.aiCorrect !== undefined ? Number(((g.aiCorrect / evaluated) * 100).toFixed(2)) : undefined;
|
||||
const humanAccuracy = evaluated > 0 && g.humanCorrect !== undefined ? Number(((g.humanCorrect / evaluated) * 100).toFixed(2)) : undefined;
|
||||
const automationRate = g.total > 0 ? Number(((g.agreed / g.total) * 100).toFixed(2)) : undefined;
|
||||
const bothAccurateRate = evaluated > 0 && g.bothCorrect !== undefined ? Number(((g.bothCorrect / evaluated) * 100).toFixed(2)) : undefined;
|
||||
@@ -206,7 +219,7 @@ export async function getMonthlyReportData(
|
||||
evaluated,
|
||||
agreed: g.agreed,
|
||||
diverged: g.diverged,
|
||||
aiAccuracy,
|
||||
aiAccuracy: groupAiAccuracy,
|
||||
humanAccuracy,
|
||||
automationRate,
|
||||
humanPassRatio,
|
||||
@@ -262,7 +275,8 @@ export async function getMonthlyReportData(
|
||||
period: {
|
||||
month: data.period.month,
|
||||
start: data.period.start.slice(0, 10),
|
||||
end: data.period.end.slice(0, 10)
|
||||
end: data.period.end.slice(0, 10),
|
||||
label: data.period.label
|
||||
},
|
||||
corp: data.corp,
|
||||
metrics: {
|
||||
@@ -272,7 +286,15 @@ export async function getMonthlyReportData(
|
||||
accuracyFormula,
|
||||
automationRate: data.performance?.automationRate,
|
||||
avgDurationSeconds: data.performance?.avgDurationSeconds,
|
||||
riskInterceptCount: data.performance?.riskCount ?? data.blocks.filter((b) => b.agreement === "diverged" && b.verdict === "ai_correct").length
|
||||
riskInterceptCount:
|
||||
data.performance?.riskCount ??
|
||||
data.blocks.filter(
|
||||
(b) =>
|
||||
b.agreement === "diverged" &&
|
||||
b.verdict === "ai_correct" &&
|
||||
polarityOf(b.aiDecision) === "reject" &&
|
||||
polarityOf(b.humanResult) === "pass"
|
||||
).length
|
||||
},
|
||||
reviews: {
|
||||
available: data.notes.humanAccuracyAvailable,
|
||||
@@ -296,10 +318,12 @@ export async function getMonthlyReportData(
|
||||
vennSvg
|
||||
},
|
||||
nextActions: {
|
||||
reviewSet: `seal-use report review set --month ${data.period.month} --sn <SN> --verdict <ai_correct|human_correct|both_correct|both_wrong|undecided> --corp ${data.corp.id}`,
|
||||
reviewList: `seal-use report review list --month ${data.period.month} --corp ${data.corp.id}`,
|
||||
reviewSet: `seal-use report review set --sn <SN> --verdict <ai_correct|human_correct|both_correct|both_wrong|undecided> --corp ${data.corp.id}`,
|
||||
reviewList: `seal-use report review list --corp ${data.corp.id}`,
|
||||
validate: "seal-use report validate <报告文件.md>",
|
||||
render: "seal-use report render <报告文件.md> --out build/<报告文件>"
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export const getReportData = getMonthlyReportData;
|
||||
@@ -39,7 +39,7 @@ const TITLE_RULES: Array<{ pattern: RegExp; demand: ReportDemand; avoid?: RegExp
|
||||
{ pattern: /风险|潜在/, demand: "riskStats" },
|
||||
{ pattern: /TOP \d|构成总览|小节|明细/, demand: "riskDetails" },
|
||||
{ pattern: /准确率|时效|耗时|效能|稳定性|审核测试结果|样本/, demand: "performance", avoid: /一致性示例/ },
|
||||
{ pattern: /一致性|一致示例|通过 \/ 人工驳回|通过\/人工驳回|通过 \/ 人工驳回/, demand: "blocks" },
|
||||
{ pattern: /一致性|一致示例|通过 \/ 人工驳回|通过\/人工驳回|通过 \/ 人工驳回|分歧|复核归因/, demand: "blocks" },
|
||||
{ pattern: /分模板|单据模板.*率/, demand: "templateGroups" },
|
||||
{ pattern: /风险拦截/, demand: "riskStats" }
|
||||
];
|
||||
|
||||
@@ -2,26 +2,37 @@ import type { KyInstance } from "ky";
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { resolve } from "node:path";
|
||||
import { validationError } from "../../../../core/errors.js";
|
||||
import { CliError, validationError } from "../../../../core/errors.js";
|
||||
import { BUILTIN_MONTHLY_TEMPLATE, BUILTIN_TEMPLATE_PATH } from "../templates/resources.js";
|
||||
import { describeTemplate } from "./describe.js";
|
||||
import { collectReportData, type ReportData } from "./collect.js";
|
||||
import { renderMonthlyReport, type RenderOptions } from "./render.js";
|
||||
|
||||
import { renderVennAccuracySvg } from "../charts/venn.js";
|
||||
import { buildReportLedgerCsv, buildReportLedgerXlsx } from "../export/ledger.js";
|
||||
import { buildReportLedgerCsv, buildReportLedgerXlsx, loadReportDataFromLedger } from "../export/ledger.js";
|
||||
|
||||
export type MonthlyReportOptions = {
|
||||
month: string; // YYYY-MM
|
||||
export type ReportOptions = {
|
||||
startDate?: string;
|
||||
endDate?: string;
|
||||
month?: string; // 兼容旧单月参数
|
||||
corp: { id: string; name: string };
|
||||
/** 单据模板白名单列表(可选,未指定则拉取全量模板) */
|
||||
templates?: string[];
|
||||
/** 外部直接传入已编辑的台账文件路径 (.xlsx 或 .csv),传入时直接以该台账为唯一事实源,不再查询云端 */
|
||||
ledgerPath?: string;
|
||||
/** 模板路径;缺省用仓内内置 monthly.md,随二进制内嵌 */
|
||||
templatePath?: string;
|
||||
reportId?: string;
|
||||
maxRuns?: number;
|
||||
/** 是否跳过前置裁决门禁(当存在未裁决的分歧单时强行出具草稿,默认 false) */
|
||||
allowUnreviewed?: boolean;
|
||||
};
|
||||
|
||||
export type MonthlyReportOptions = ReportOptions;
|
||||
|
||||
export type MonthlyReportResult = {
|
||||
month: string;
|
||||
period: ReportData["period"];
|
||||
month?: string;
|
||||
corpId: string;
|
||||
reportId: string;
|
||||
templatePath: string;
|
||||
@@ -43,10 +54,10 @@ export type MonthlyReportResult = {
|
||||
};
|
||||
};
|
||||
|
||||
/** 一次调用产出填充好的月度报告 Markdown。模板皮与数据骨解耦:见 describe.ts。 */
|
||||
/** 一次调用产出填充好的审核报告 Markdown。模板皮与数据骨解耦:见 describe.ts。 */
|
||||
export async function buildMonthlyReport(
|
||||
client: KyInstance,
|
||||
options: MonthlyReportOptions
|
||||
options: ReportOptions
|
||||
): Promise<MonthlyReportResult> {
|
||||
const templatePath = options.templatePath
|
||||
? resolve(options.templatePath)
|
||||
@@ -60,14 +71,45 @@ export async function buildMonthlyReport(
|
||||
const template = options.templatePath ? readFileSync(templatePath, "utf8") : BUILTIN_MONTHLY_TEMPLATE;
|
||||
const plans = describeTemplate(template);
|
||||
|
||||
const demands = new Set(plans.flatMap((plan) => plan.demands));
|
||||
const data = await collectReportData(client, demands, {
|
||||
month: options.month,
|
||||
corp: options.corp,
|
||||
maxRuns: options.maxRuns
|
||||
});
|
||||
let data: ReportData;
|
||||
if (options.ledgerPath) {
|
||||
data = await loadReportDataFromLedger(options.ledgerPath, { corp: options.corp });
|
||||
} else {
|
||||
const demands = new Set(plans.flatMap((plan) => plan.demands));
|
||||
data = await collectReportData(client, demands, {
|
||||
startDate: options.startDate,
|
||||
endDate: options.endDate,
|
||||
month: options.month,
|
||||
corp: options.corp,
|
||||
templates: options.templates,
|
||||
maxRuns: options.maxRuns
|
||||
});
|
||||
}
|
||||
|
||||
const reportId = options.reportId ?? `RPT-${options.month.replace("-", "")}-${randomBytes(3).toString("hex").toUpperCase()}`;
|
||||
const unreviewedDiverged = data.blocks.filter(
|
||||
(b) => b.agreement === "diverged" && !b.verdict
|
||||
);
|
||||
if (unreviewedDiverged.length > 0 && !options.allowUnreviewed) {
|
||||
const snList = unreviewedDiverged.slice(0, 3).map((b) => b.sn).join(", ");
|
||||
const more = unreviewedDiverged.length > 3 ? ` 等共 ${unreviewedDiverged.length} 笔` : "";
|
||||
const periodArg = options.startDate && options.endDate
|
||||
? `--start-date ${options.startDate} --end-date ${options.endDate}`
|
||||
: options.month ? `--month ${options.month}` : "";
|
||||
const tip = options.ledgerPath
|
||||
? `请在台账文件(${options.ledgerPath})中为这些单据填写“复核定性裁决”列(如:AI判断正确 / 人工判断错误,或人工判断正确 / AI判定误判),或直接剔除不需要的单据/模板行。`
|
||||
: `请先执行 'seal-use report ledger ${periodArg} --corp ${options.corp.id}' 导出台账并在 Excel 中裁决,或通过 'seal-use report review set' 录入裁决结论。`;
|
||||
throw new CliError(
|
||||
`前置业务门禁拦截:检测到 ${unreviewedDiverged.length} 笔人机分歧单据尚未完成复核裁决(如 ${snList}${more})。\n` +
|
||||
`为保证报告结论的真实性与合规性,出具正式报告前必须完成人机分歧裁决。\n` +
|
||||
`${tip}\n` +
|
||||
`(若确需生成未定稿的内部预览草稿,请添加 --allow-unreviewed 参数继续)。`,
|
||||
1,
|
||||
options.ledgerPath ? undefined : `seal-use report data ${periodArg} --corp ${options.corp.id}`
|
||||
);
|
||||
}
|
||||
|
||||
const dateTag = (data.period.month || `${data.period.start.slice(0, 10)}_${data.period.end.slice(0, 10)}`).replace(/[-~]/g, "");
|
||||
const reportId = options.reportId ?? `RPT-${dateTag}-${randomBytes(3).toString("hex").toUpperCase()}`;
|
||||
const renderOptions: RenderOptions = {
|
||||
reportId,
|
||||
corpName: options.corp.name
|
||||
@@ -106,7 +148,8 @@ export async function buildMonthlyReport(
|
||||
}
|
||||
|
||||
return {
|
||||
month: options.month,
|
||||
period: data.period,
|
||||
month: data.period.month,
|
||||
corpId: options.corp.id,
|
||||
reportId,
|
||||
templatePath,
|
||||
@@ -125,3 +168,5 @@ export async function buildMonthlyReport(
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export const buildReport = buildMonthlyReport;
|
||||
@@ -1,6 +1,7 @@
|
||||
import { formatBeijingIso } from "../../../../core/config/timestamps.js";
|
||||
import type { ReportData, ReportBlock } from "./collect.js";
|
||||
import type { SectionPlan } from "./describe.js";
|
||||
import { ReviewsMap } from "./review-store.js";
|
||||
|
||||
export type RenderOptions = {
|
||||
/** 报告编号;未给则按 RPT-<YYYYMM>-<6位随机> 生成 */
|
||||
@@ -55,7 +56,8 @@ export function renderMonthlyReport(
|
||||
plans: SectionPlan[],
|
||||
options: RenderOptions = {}
|
||||
): string {
|
||||
const reportId = options.reportId ?? `RPT-${data.period.month.replace("-", "")}-${randomSuffix()}`;
|
||||
const dateTag = (data.period.month || `${data.period.start.slice(0, 10)}_${data.period.end.slice(0, 10)}`).replace(/[-~]/g, "");
|
||||
const reportId = options.reportId ?? `RPT-${dateTag}-${randomSuffix()}`;
|
||||
const corpName = options.corpName ?? data.corp.name;
|
||||
const generatedAt = options.generatedAt ?? beijingToday();
|
||||
const ctx: FillContext = { reportId, corpName, generatedAt, reportStatus: options.reportStatus };
|
||||
@@ -103,7 +105,7 @@ export function renderMonthlyReport(
|
||||
// 报告信息表:统计期间与生成日期按真实统计口径补齐
|
||||
result = result.replace(
|
||||
/(\| 统计期间 \| )[^\n|]+/,
|
||||
`$1${data.period.start.slice(0, 10)} ~ ${data.period.end.slice(0, 10)}`
|
||||
`$1${data.period.label || `${data.period.start.slice(0, 10)} ~ ${data.period.end.slice(0, 10)}`}`
|
||||
);
|
||||
result = result.replace(/(\| 生成日期 \| )[^\n|]+/, `$1${ctx.generatedAt}`);
|
||||
return result;
|
||||
@@ -111,11 +113,14 @@ export function renderMonthlyReport(
|
||||
|
||||
function fillInline(text: string, data: ReportData, ctx: FillContext): string {
|
||||
let result = text;
|
||||
const monthNum = parseInt(data.period.month.slice(5), 10);
|
||||
const monthNum = data.period.month ? parseInt(data.period.month.slice(5), 10) : NaN;
|
||||
const monthStr = Number.isFinite(monthNum) ? `${monthNum}月` : "";
|
||||
if (monthStr) {
|
||||
result = result.replace(/# 【[^】]+】\d+月AI审核准确率报告/, `# 【${ctx.corpName}】${monthStr}AI审核准确率报告`);
|
||||
result = result.replace(/《\d+月单据审批质量审计报告_全量看板\.xlsx》/g, `《${monthStr}单据审批质量审计报告_全量看板.xlsx》`);
|
||||
} else {
|
||||
result = result.replace(/# 【[^】]+】\d+月AI审核准确率报告/, `# 【${ctx.corpName}】AI审核准确率报告`);
|
||||
result = result.replace(/《\d+月单据审批质量审计报告_全量看板\.xlsx》/g, "《单据审批质量审计报告_全量看板.xlsx》");
|
||||
}
|
||||
result = result.replace(/【[^】]+】(?=\S*月)/, `【${ctx.corpName}】`);
|
||||
result = result.replaceAll("模板企业", ctx.corpName);
|
||||
@@ -177,8 +182,8 @@ function fillInline(text: string, data: ReportData, ctx: FillContext): string {
|
||||
/综合失准共 \d+ 单(\d+(?:\.\d+)?%)/g,
|
||||
`综合失准共 ${wrong} 单(${(100 - Number(formulaPct)).toFixed(2)}%)`
|
||||
);
|
||||
result = result.replace(/\*\*\d+ 单\*\*的深度稽核中/g, `**${total} 单**的深度稽核中`);
|
||||
result = result.replace(/\d+ 单的深度稽核中/g, `${total} 单的深度稽核中`);
|
||||
result = result.replace(/\*\*\d+ 单\*\*的深度(稽核|复核)中/g, `**${total} 单**的深度$1中`);
|
||||
result = result.replace(/\d+ 单的深度(稽核|复核)中/g, `${total} 单的深度$1中`);
|
||||
// 公式代入值:\frac{N}{M} = X% 结构化匹配
|
||||
result = result.replace(
|
||||
/= \\frac\{\d+\}\{\d+\} = \d+(?:\.\d+)?\\?%/g,
|
||||
@@ -190,7 +195,10 @@ function fillInline(text: string, data: ReportData, ctx: FillContext): string {
|
||||
);
|
||||
result = result.replace(/N = 240/g, `N = ${total}`);
|
||||
// 样本总量:真实单量 + 决策分布(无人工明细时只报总样本)
|
||||
const dist = distributionOf(data.blocks);
|
||||
const scopedBlocksForDist = data.notes.mismatchCategoriesAvailable
|
||||
? data.blocks.filter((b) => b.agreement !== "unknown")
|
||||
: data.blocks;
|
||||
const dist = distributionOf(scopedBlocksForDist);
|
||||
result = result.replace(
|
||||
/\*\*\d+ 张\*\*([^)]*)/,
|
||||
`**${total} 张**${dist ? `(${dist})` : ""}`
|
||||
@@ -207,28 +215,29 @@ function fillInline(text: string, data: ReportData, ctx: FillContext): string {
|
||||
const p1 = wrong > 0 ? Number((100 - p2 - p3).toFixed(1)) : 0;
|
||||
|
||||
result = result.replace(
|
||||
/###\s*2\.2\s*TOP\s*1[^(\n]*(\d+\s*张[^)\n]*)/,
|
||||
`### 2.2 TOP 1 · 规则执行与判定偏差(${c1} 张 / ${p1.toFixed(1)}%)`
|
||||
/###\s*(\d+\.\d+)\s*TOP\s*1[^(\n]*(\d+\s*张[^)\n]*)/,
|
||||
`### $1 TOP 1 · 规则执行与判定偏差(${c1} 张 / ${p1.toFixed(1)}%)`
|
||||
);
|
||||
result = result.replace(
|
||||
/###\s*2\.3\s*TOP\s*2[^(\n]*(\d+\s*张[^)\n]*)/,
|
||||
`### 2.3 TOP 2 · 数据与附件识别问题(${c2} 张 / ${p2.toFixed(1)}%)`
|
||||
/###\s*(\d+\.\d+)\s*TOP\s*2[^(\n]*(\d+\s*张[^)\n]*)/,
|
||||
`### $1 TOP 2 · 数据与附件识别问题(${c2} 张 / ${p2.toFixed(1)}%)`
|
||||
);
|
||||
result = result.replace(
|
||||
/###\s*2\.4\s*TOP\s*3[^(\n]*(\d+\s*张[^)\n]*)/,
|
||||
`### 2.4 TOP 3 · 费用明细查重冲突(${c3} 张 / ${p3.toFixed(1)}%)`
|
||||
/###\s*(\d+\.\d+)\s*TOP\s*3[^(\n]*(\d+\s*张[^)\n]*)/,
|
||||
`### $1 TOP 3 · 费用明细查重冲突(${c3} 张 / ${p3.toFixed(1)}%)`
|
||||
);
|
||||
|
||||
const sec3Idx = result.indexOf("## 3.");
|
||||
if (sec3Idx > 0) {
|
||||
let beforeSec3 = result.slice(0, sec3Idx);
|
||||
const riskSecMatch = result.match(/##\s*\d+\.\s*[^#\n]*风险/);
|
||||
const secRiskIdx = riskSecMatch ? result.indexOf(riskSecMatch[0]) : -1;
|
||||
if (secRiskIdx > 0) {
|
||||
let beforeSecRisk = result.slice(0, secRiskIdx);
|
||||
let fnIdx = 0;
|
||||
const fnCounts = [c1, c2, c3];
|
||||
beforeSec3 = beforeSec3.replace(/(节选 3 例,全量 \d+ 张)/g, (m) => {
|
||||
beforeSecRisk = beforeSecRisk.replace(/(节选 3 例,全量 \d+ 张)/g, (m) => {
|
||||
const val = fnCounts[fnIdx++];
|
||||
return val !== undefined ? `(节选 3 例,全量 ${val} 张)` : m;
|
||||
});
|
||||
result = beforeSec3 + result.slice(sec3Idx);
|
||||
result = beforeSecRisk + result.slice(secRiskIdx);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -237,7 +246,7 @@ function fillInline(text: string, data: ReportData, ctx: FillContext): string {
|
||||
result = result.replace(/\*\*83\.33%\*\*/g, `**${pct(data.humanAccuracy)}**`);
|
||||
}
|
||||
|
||||
// §3 小节标题与脚注单数同步:将总览表中的真实风险类型与张数同步至小节标题(解决 NM002 勾稽校验)
|
||||
// 小节标题与脚注单数同步:将总览表中的真实风险类型与张数同步至小节标题(解决 NM002 勾稽校验)
|
||||
if (data.fetched.riskStats && data.riskStats?.tags.length) {
|
||||
const tags = data.riskStats.tags.filter((t) => t.count !== undefined).slice(0, 3);
|
||||
const totalRisk = tags.reduce((sum, t) => sum + (t.count ?? 0), 0) || 1;
|
||||
@@ -246,36 +255,63 @@ function fillInline(text: string, data: ReportData, ctx: FillContext): string {
|
||||
const count = tag.count ?? 0;
|
||||
const share = ((count / totalRisk) * 100).toFixed(1);
|
||||
const name = tag.name ?? `TOP ${topNum} 风险`;
|
||||
const reg = new RegExp(`###\\s*3\\.${topNum + 1}\\s*TOP\\s*${topNum}[^(\n]*(\\d+\\s*张[^)\n]*)`, "g");
|
||||
result = result.replace(reg, `### 3.${topNum + 1} TOP ${topNum} · ${name}(${count} 张 / ${share}%)`);
|
||||
const reg = new RegExp(`###\\s*(\\d+\\.\\d+)\\s*TOP\\s*${topNum}[^(\n]*(\\d+\\s*张[^)\n]*)`, "g");
|
||||
result = result.replace(reg, `### $1 TOP ${topNum} · ${name}(${count} 张 / ${share}%)`);
|
||||
});
|
||||
const sec3Idx = result.indexOf("## 3.");
|
||||
if (sec3Idx >= 0) {
|
||||
let fromSec3 = result.slice(sec3Idx);
|
||||
if (tags[0]?.count) fromSec3 = fromSec3.replace(/(节选 3 例,全量 23 张)/, `(节选 3 例,全量 ${tags[0].count} 张)`);
|
||||
if (tags[1]?.count) fromSec3 = fromSec3.replace(/(节选 3 例,全量 9 张)/, `(节选 3 例,全量 ${tags[1].count} 张)`);
|
||||
if (tags[2]?.count) fromSec3 = fromSec3.replace(/(节选 3 条,全量 8 张)/, `(节选 3 例,全量 ${tags[2].count} 张)`);
|
||||
result = result.slice(0, sec3Idx) + fromSec3;
|
||||
const riskSecMatch = result.match(/##\s*\d+\.\s*[^#\n]*风险/);
|
||||
const secRiskIdx = riskSecMatch ? result.indexOf(riskSecMatch[0]) : -1;
|
||||
if (secRiskIdx >= 0) {
|
||||
let fromSecRisk = result.slice(secRiskIdx);
|
||||
if (tags[0]?.count) fromSecRisk = fromSecRisk.replace(/(节选 3 例,全量 23 张)/, `(节选 3 例,全量 ${tags[0].count} 张)`);
|
||||
if (tags[1]?.count) fromSecRisk = fromSecRisk.replace(/(节选 3 例,全量 9 张)/, `(节选 3 例,全量 ${tags[1].count} 张)`);
|
||||
if (tags[2]?.count) fromSecRisk = fromSecRisk.replace(/(节选 3 条,全量 8 张)/, `(节选 3 例,全量 ${tags[2].count} 张)`);
|
||||
result = result.slice(0, secRiskIdx) + fromSecRisk;
|
||||
}
|
||||
}
|
||||
|
||||
// §6 叙述统计同步:将明细表格真实行数与依规正确比例同步至正文(解决 NM004 勾稽校验)
|
||||
const divergedBlocks = data.blocks.filter((b) => b.agreement === "diverged").slice(0, 10);
|
||||
if (divergedBlocks.length > 0) {
|
||||
const totalSample = divergedBlocks.length;
|
||||
const correctSample = divergedBlocks.filter((b) => b.verdict === "ai_correct" || (!b.verdict && b.agreement === "diverged")).length;
|
||||
const missedSample = totalSample - correctSample;
|
||||
const correctShare = ((correctSample / totalSample) * 100).toFixed(1);
|
||||
// §5 / §6 分歧叙述统计同步:将真实分歧单数与非判定缺陷比例同步至正文(解决 NM004 勾稽校验)
|
||||
const allDiverged = data.blocks.filter((b) => b.agreement === "diverged");
|
||||
const divergedBlocks = allDiverged.slice(0, 10);
|
||||
if (allDiverged.length > 0) {
|
||||
const totalDiverged = allDiverged.length;
|
||||
const correctDiverged = allDiverged.filter((b) => b.verdict === "ai_correct" || b.verdict === "both_correct" || (!b.verdict && b.agreement === "diverged")).length;
|
||||
const missedDiverged = totalDiverged - correctDiverged;
|
||||
const correctShare = ((correctDiverged / totalDiverged) * 100).toFixed(1);
|
||||
|
||||
result = result.replace(/在上述 \*\*\d+ 笔\*\*单据中:/g, `在上述 **${totalSample} 笔**单据中:`);
|
||||
const divTotal = total ?? (data.blocks.length || 1);
|
||||
const divShare = ((totalDiverged / divTotal) * 100).toFixed(2);
|
||||
const missedShare = ((missedDiverged / divTotal) * 100).toFixed(2);
|
||||
|
||||
// 新模板模式(概览归因模式)
|
||||
result = result.replace(
|
||||
/\*\*\d+(?:\.\d+)?%(\d+ \/ \d+ 笔)属于依规正确(计入 D4)\*\*/g,
|
||||
`**${correctShare}%(${correctSample} / ${totalSample} 笔)属于依规正确(计入 D4)**`
|
||||
/存在分歧的单据共 \*\*\d+ 笔\*\*(占全量样本 \*\*\d+(?:\.\d+)?%\*\*)/g,
|
||||
`存在分歧的单据共 **${totalDiverged} 笔**(占全量样本 **${divShare}%**)`
|
||||
);
|
||||
result = result.replace(/仅有\s*\*{0,2}\d+\s*笔\*{0,2}\s*属于 AI 真实失准/g, `仅有 ${missedSample} 笔属于 AI 真实失准`);
|
||||
if (total) {
|
||||
const missedShare = ((missedSample / total) * 100).toFixed(2);
|
||||
result = result.replace(/(占全量样本 \d+(?:\.\d+)?%)/g, `(占全量样本 ${missedShare}%)`);
|
||||
result = result.replace(
|
||||
/绝大多数(\*\*\d+(?:\.\d+)?%\*\*,\d+ 笔)并非 AI 判定缺陷/g,
|
||||
`绝大多数(**${correctShare}%**,${correctDiverged} 笔)并非 AI 判定缺陷`
|
||||
);
|
||||
result = result.replace(
|
||||
/真实失准单据(仅 \*\*\d+ 笔\*\*,占全量 \*\*\d+(?:\.\d+)?%\*\*)/g,
|
||||
`真实失准单据(仅 **${missedDiverged} 笔**,占全量 **${missedShare}%**)`
|
||||
);
|
||||
|
||||
// 历史模板模式(逐单明细模式)
|
||||
if (divergedBlocks.length > 0) {
|
||||
const sampleCount = divergedBlocks.length;
|
||||
const sampleCorrect = divergedBlocks.filter((b) => b.verdict === "ai_correct" || b.verdict === "both_correct" || (!b.verdict && b.agreement === "diverged")).length;
|
||||
const sampleMissed = sampleCount - sampleCorrect;
|
||||
const sampleShare = ((sampleCorrect / sampleCount) * 100).toFixed(1);
|
||||
result = result.replace(/在上述 \*\*\d+ 笔\*\*单据中:/g, `在上述 **${sampleCount} 笔**单据中:`);
|
||||
result = result.replace(
|
||||
/\*\*\d+(?:\.\d+)?%(\d+ \/ \d+ 笔)属于依规正确(计入 D4)\*\*/g,
|
||||
`**${sampleShare}%(${sampleCorrect} / ${sampleCount} 笔)属于依规正确(计入 D4)**`
|
||||
);
|
||||
result = result.replace(/仅有\s*\*{0,2}\d+\s*笔\*{0,2}\s*属于 AI 真实失准/g, `仅有 ${sampleMissed} 笔属于 AI 真实失准`);
|
||||
if (total) {
|
||||
const sampleMissShare = ((sampleMissed / total) * 100).toFixed(2);
|
||||
result = result.replace(/(占全量样本 \d+(?:\.\d+)?%)/g, `(占全量样本 ${sampleMissShare}%)`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -334,7 +370,7 @@ function transformTable(
|
||||
if (!columns.length) return block;
|
||||
|
||||
const notes = noteAfter(columns, heading, lastH2, data);
|
||||
const rows = replacementRows(columns, sampleRows, data, heading);
|
||||
const rows = replacementRows(columns, sampleRows, data, heading, lastH2);
|
||||
// 无论是否替换数据行,缺口径说明都要追加(模板保留时同样需要知会)
|
||||
if (!rows) return [...block, ...notes];
|
||||
return [header, separator, ...rows.map((row) => `| ${row.map(escapeCell).join(" | ")} |`), ...notes];
|
||||
@@ -371,7 +407,8 @@ function replacementRows(
|
||||
columns: string[],
|
||||
sampleRows: string[],
|
||||
data: ReportData,
|
||||
heading: string
|
||||
heading: string,
|
||||
lastH2: string
|
||||
): Array<Array<string | number>> | null {
|
||||
const perf = data.performance;
|
||||
|
||||
@@ -399,13 +436,16 @@ function replacementRows(
|
||||
// §1.1 数据来源与范围
|
||||
if (columns.includes("项目") && columns.includes("内容") && heading.includes("数据来源")) {
|
||||
if (!perf) return null;
|
||||
const dist = distributionOf(data.blocks) ?? "";
|
||||
const scopedBlocksForDist = data.notes.mismatchCategoriesAvailable
|
||||
? data.blocks.filter((b) => b.agreement !== "unknown")
|
||||
: data.blocks;
|
||||
const dist = distributionOf(scopedBlocksForDist) ?? "";
|
||||
const scopeNote = data.notes.mismatchCategoriesAvailable && data.blocks.length > (perf.approvalCount ?? 0)
|
||||
? `(全月跑批 ${data.blocks.length} 张,其中已完成人工审批闭环 **${perf.approvalCount} 张**:${dist})`
|
||||
: (dist ? `(${dist})` : "");
|
||||
return [
|
||||
["数据来源", "客户授权的已完成历史审批单据"],
|
||||
["统计期间", `${data.period.start.slice(0, 10)} ~ ${data.period.end.slice(0, 10)} 期间单据`],
|
||||
["统计期间", `${data.period.label || `${data.period.start.slice(0, 10)} ~ ${data.period.end.slice(0, 10)}`} 期间单据`],
|
||||
["单据模板", data.templateGroups.length
|
||||
? `涵盖 ${data.templateGroups.map((g) => g.template).slice(0, 6).join("、")} 等 **${data.templateGroups.length} 类**业务单据模板`
|
||||
: "*(单据模板分布待取数)*"],
|
||||
@@ -483,18 +523,41 @@ function replacementRows(
|
||||
return null;
|
||||
}
|
||||
|
||||
// §5 审核分歧归因总览(4 列:原因分类 | 占比 | 单数 | 核心说明)
|
||||
if (columns.includes("原因分类") && columns.includes("占比") && columns.includes("单数")) {
|
||||
const diverged = data.blocks.filter((block) => block.agreement === "diverged");
|
||||
if (!diverged.length) {
|
||||
if (!data.fetched.blocks) return null;
|
||||
return [
|
||||
["线下口头要求/未在线配置规则", "0%", "0 张", "本期无分歧单据"],
|
||||
["AI 识别或规则理解偏差", "0%", "0 张", "本期无分歧单据"],
|
||||
["合计", "100%", "0 张", "—"]
|
||||
];
|
||||
}
|
||||
const totalSample = diverged.length;
|
||||
const correctSample = diverged.filter((b) => b.verdict === "ai_correct" || b.verdict === "both_correct" || (!b.verdict && b.agreement === "diverged")).length;
|
||||
const missedSample = totalSample - correctSample;
|
||||
const p1 = Number(((correctSample / totalSample) * 100).toFixed(1));
|
||||
const p2 = Number((100 - p1).toFixed(1));
|
||||
return [
|
||||
["线下口头要求/未在线配置规则", `${p1.toFixed(1)}%`, `${correctSample} 张`, "单据凭证齐全且符合现行线上规则,主要因经办人主动撤回、无理由终止或财务线下口头加码标准,AI 依既定规则放行"],
|
||||
["AI 识别或规则理解偏差", `${p2.toFixed(1)}%`, `${missedSample} 张`, "单据凭证或关键字段识别存在偏差,已纳入模型调优与规则优化样本"],
|
||||
["合计", "100%", `${totalSample} 张`, "—"]
|
||||
];
|
||||
}
|
||||
|
||||
// §6 AI 通过 / 人工驳回明细(7 列:单据编号|模板|AI|人工|原因分类|复核结论|截图)
|
||||
if (columns.includes("单据编号") && columns.some((col) => col.includes("原因分类"))) {
|
||||
if (!data.blocks.length) return null;
|
||||
const diverged = data.blocks.filter((block) => block.agreement === "diverged").slice(0, 10);
|
||||
if (!diverged.length) return null;
|
||||
return diverged.map((block) => {
|
||||
const isAiRight = block.verdict === "ai_correct" || (!block.verdict && block.agreement === "diverged");
|
||||
const category = isAiRight ? "**依规正确(计入 D4)**" : "**AI 失准(不计入分子)**";
|
||||
const reviewNote = data.reviews.get(block.sn)?.note;
|
||||
const isAiRight = block.verdict === "ai_correct" || block.verdict === "both_correct" || (!block.verdict && block.agreement === "diverged");
|
||||
const category = isAiRight ? "**依规正确(计入 D4)**" : "**AI 判定误判(不计入分子)**";
|
||||
const reviewNote = block.reviewNote ?? (data.reviews instanceof ReviewsMap ? data.reviews.get({ recordId: block.recordId, sn: block.sn }) : (data.reviews as Map<string, any>).get(block.sn))?.note;
|
||||
const conclusion = (!isAiRight && reviewNote)
|
||||
? `${reviewNote}(AI原判:${block.aiSummary || "—"})`
|
||||
: (block.aiSummary || reviewNote || (isAiRight ? "人工复核确认依规拦截风险" : "AI 误报"));
|
||||
: (block.aiSummary || reviewNote || (isAiRight ? "人工复核确认依规拦截风险" : "AI 误报/误判"));
|
||||
return [
|
||||
block.sn,
|
||||
block.template || "—",
|
||||
@@ -612,28 +675,39 @@ function replacementRows(
|
||||
});
|
||||
}
|
||||
|
||||
// §3 潜在风险明细表(2 列:单号 | 问题描述)
|
||||
if (columns.length === 2 && columns.includes("单号") && columns.includes("问题描述") && heading.includes("3.")) {
|
||||
// 潜在风险明细表(支持 2 列:单号 | 问题描述 或 3 列:单号 | 问题描述 | 审核详情)
|
||||
if (columns.includes("单号") && columns.includes("问题描述") && (heading.includes("风险") || lastH2.includes("风险"))) {
|
||||
if (!data.blocks.length) return null;
|
||||
if (heading.includes("3.2") || heading.includes("TOP 1")) {
|
||||
let picks: ReportBlock[] = [];
|
||||
if (heading.includes("TOP 1") || heading.includes("3.2")) {
|
||||
const matches = data.blocks.filter((b) => /招待|餐费|标准|超标|人均|酒水/i.test(b.aiSummary || ""));
|
||||
const picks = matches.length >= 3 ? matches.slice(0, 3) : data.blocks.filter((b) => b.agreement === "diverged").slice(0, 3);
|
||||
if (picks.length) return picks.map((b) => [b.sn, b.aiSummary || "业务招待人均消费超标或缺少事前申请"]);
|
||||
}
|
||||
if (heading.includes("3.3") || heading.includes("TOP 2")) {
|
||||
picks = matches.length >= 3 ? matches.slice(0, 3) : data.blocks.filter((b) => b.agreement === "diverged").slice(0, 3);
|
||||
} else if (heading.includes("TOP 2") || heading.includes("3.3")) {
|
||||
const matches = data.blocks.filter((b) => /比价|询价|合同|采购|订单|对账单|签章|未签署/i.test(b.aiSummary || ""));
|
||||
const picks = matches.length >= 3 ? matches.slice(0, 3) : data.blocks.filter((b) => b.agreement === "diverged").slice(3, 6);
|
||||
if (picks.length) return picks.map((b) => [b.sn, b.aiSummary || "大额采购未提供询价记录或合同未完成签署"]);
|
||||
}
|
||||
if (heading.includes("3.4") || heading.includes("TOP 3")) {
|
||||
picks = matches.length >= 3 ? matches.slice(0, 3) : data.blocks.filter((b) => b.agreement === "diverged").slice(3, 6);
|
||||
} else if (heading.includes("TOP 3") || heading.includes("3.4")) {
|
||||
const matches = data.blocks.filter((b) => /超期|跨季度|时效|发票日期|过期|出差申请/i.test(b.aiSummary || ""));
|
||||
const picks = matches.length >= 3 ? matches.slice(0, 3) : data.blocks.filter((b) => b.agreement === "diverged").slice(6, 9);
|
||||
if (picks.length) return picks.map((b) => [b.sn, b.aiSummary || "发票开票日期已跨季度超期,违反提交时效"]);
|
||||
picks = matches.length >= 3 ? matches.slice(0, 3) : data.blocks.filter((b) => b.agreement === "diverged").slice(6, 9);
|
||||
}
|
||||
if (!picks.length) return null;
|
||||
|
||||
const hasLinkCol = columns.length >= 3 && columns.some((c) => /链接|详情|直达|查看/i.test(c));
|
||||
const sealBaseUrl = `https://${data.corp.id.toLowerCase()}.sealai.cc`;
|
||||
|
||||
return picks.map((b) => {
|
||||
const desc = b.aiSummary || "业务招待人均消费超标或缺少事前申请";
|
||||
const recordId = b.recordId || (b as Record<string, unknown>).id;
|
||||
const sealUrl = recordId ? `${sealBaseUrl}/approval-result/${recordId}` : undefined;
|
||||
const linkText = sealUrl ? `[👉 查看详情](${sealUrl})` : "—";
|
||||
if (hasLinkCol) {
|
||||
return [b.sn, desc, linkText];
|
||||
}
|
||||
return [sealUrl ? `[${b.sn}](${sealUrl})` : b.sn, desc];
|
||||
});
|
||||
}
|
||||
|
||||
// §2 失准与复核分析明细表(2 列:单号 | 问题描述)
|
||||
if (columns.length === 2 && columns.includes("单号") && columns.includes("问题描述") && heading.includes("2.")) {
|
||||
// 失准与复核分析明细表(支持 2 列:单号 | 问题描述 或 3 列:单号 | 问题描述 | 审核详情)
|
||||
if (columns.includes("单号") && columns.includes("问题描述") && (heading.includes("失准") || lastH2.includes("失准"))) {
|
||||
if (!data.blocks.length) return null;
|
||||
const humanCorrectBlocks = data.blocks.filter((b) => b.verdict === "human_correct");
|
||||
const candidates = humanCorrectBlocks.length >= 3
|
||||
@@ -642,16 +716,25 @@ function replacementRows(
|
||||
if (!candidates.length) return null;
|
||||
|
||||
let sliceIndex = 0;
|
||||
if (heading.includes("2.3") || heading.includes("TOP 2")) sliceIndex = 1;
|
||||
else if (heading.includes("2.4") || heading.includes("TOP 3")) sliceIndex = 2;
|
||||
if (heading.includes("TOP 2") || heading.includes("2.3")) sliceIndex = 1;
|
||||
else if (heading.includes("TOP 3") || heading.includes("2.4")) sliceIndex = 2;
|
||||
|
||||
const start = sliceIndex * 3;
|
||||
const picks = candidates.slice(start, start + 3);
|
||||
if (!picks.length) return null;
|
||||
|
||||
const hasLinkCol = columns.length >= 3 && columns.some((c) => /链接|详情|直达|查看/i.test(c));
|
||||
const sealBaseUrl = `https://${data.corp.id.toLowerCase()}.sealai.cc`;
|
||||
|
||||
return picks.map((b) => {
|
||||
const issue = b.reviewNote || b.aiSummary || b.humanComment || b.conditions?.[0] || "规则执行与判定偏差";
|
||||
return [b.sn, issue];
|
||||
const recordId = b.recordId || (b as Record<string, unknown>).id;
|
||||
const sealUrl = recordId ? `${sealBaseUrl}/approval-result/${recordId}` : undefined;
|
||||
const linkText = sealUrl ? `[👉 查看详情](${sealUrl})` : "—";
|
||||
if (hasLinkCol) {
|
||||
return [b.sn, issue, linkText];
|
||||
}
|
||||
return [sealUrl ? `[${b.sn}](${sealUrl})` : b.sn, issue];
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -6,8 +6,16 @@ import { describeTemplate } from "./describe.js";
|
||||
import { collectReportData, type ReportData } from "./collect.js";
|
||||
import { renderMonthlyReport } from "./render.js";
|
||||
import { loadReviews, writeReview, reviewFilePath } from "./review-store.js";
|
||||
import { buildReportLedgerCsv, buildReportLedgerXlsx } from "../export/ledger.js";
|
||||
import {
|
||||
buildReportLedgerCsv,
|
||||
buildReportLedgerXlsx,
|
||||
loadReportDataFromLedger,
|
||||
parseVerdictText,
|
||||
formatVerdict,
|
||||
formatAiOpinion
|
||||
} from "../export/ledger.js";
|
||||
import { getMonthlyReportData } from "./data.js";
|
||||
import { buildMonthlyReport } from "./monthly.js";
|
||||
|
||||
const TEMPLATE = join(import.meta.dirname, "..", "templates", "monthly.md");
|
||||
|
||||
@@ -338,13 +346,72 @@ describe("review store + human accuracy join", () => {
|
||||
expect(data.humanAccuracy).toBe(50);
|
||||
|
||||
const csv = buildReportLedgerCsv(data);
|
||||
expect(csv.startsWith("\uFEFF单据编号(SN),单据模板")).toBe(true);
|
||||
expect(csv.startsWith("\uFEFF审核ID(recordId),单据编号(SN),单据模板")).toBe(true);
|
||||
expect(csv).toContain("对公付款");
|
||||
expect(csv).toContain("张山具体的报销单标题A");
|
||||
|
||||
const xlsx = await buildReportLedgerXlsx(data);
|
||||
expect(xlsx.byteLength).toBeGreaterThan(1000);
|
||||
});
|
||||
|
||||
test("fetches over 500 records across pages without being clamped when maxRuns is omitted", async () => {
|
||||
// 模拟服务端有 650 条记录(7 页:6 页 100 条 + 1 页 50 条)
|
||||
const totalRecords = 650;
|
||||
const fakeClient = {
|
||||
get: async (_url: string, opts?: { searchParams?: URLSearchParams }) => {
|
||||
const offset = Number(opts?.searchParams?.get("offset") ?? 0);
|
||||
const limit = Number(opts?.searchParams?.get("limit") ?? 100);
|
||||
const count = Math.max(0, Math.min(limit, totalRecords - offset));
|
||||
const records = Array.from({ length: count }, (_, i) => ({
|
||||
id: `run-${offset + i}`,
|
||||
sourceDocumentSN: `SN-${offset + i}`,
|
||||
result: { decision: "同意" },
|
||||
pipelineData: { humanResult: "同意" }
|
||||
}));
|
||||
return {
|
||||
json: async () => ({ data: { records, total: totalRecords } })
|
||||
};
|
||||
}
|
||||
} as never;
|
||||
|
||||
const data = await collectReportData(fakeClient, new Set(["blocks"]), {
|
||||
month: "2026-08",
|
||||
corp: { id: "corp-a", name: "A" }
|
||||
});
|
||||
|
||||
// 验证突破了原本的 500 条限制,全部 650 条完整拉出
|
||||
expect(data.blocks).toHaveLength(650);
|
||||
});
|
||||
|
||||
test("respects explicit maxRuns limit and slices precisely across pages", async () => {
|
||||
const totalRecords = 500;
|
||||
const fakeClient = {
|
||||
get: async (_url: string, opts?: { searchParams?: URLSearchParams }) => {
|
||||
const offset = Number(opts?.searchParams?.get("offset") ?? 0);
|
||||
const limit = Number(opts?.searchParams?.get("limit") ?? 100);
|
||||
const count = Math.max(0, Math.min(limit, totalRecords - offset));
|
||||
const records = Array.from({ length: count }, (_, i) => ({
|
||||
id: `run-${offset + i}`,
|
||||
sourceDocumentSN: `SN-${offset + i}`,
|
||||
result: { decision: "同意" },
|
||||
pipelineData: { humanResult: "同意" }
|
||||
}));
|
||||
return {
|
||||
json: async () => ({ data: { records, total: totalRecords } })
|
||||
};
|
||||
}
|
||||
} as never;
|
||||
|
||||
const data = await collectReportData(fakeClient, new Set(["blocks"]), {
|
||||
month: "2026-08",
|
||||
corp: { id: "corp-a", name: "A" },
|
||||
maxRuns: 150
|
||||
});
|
||||
|
||||
expect(data.blocks).toHaveLength(150);
|
||||
expect(data.blocks[0]?.sn).toBe("SN-0");
|
||||
expect(data.blocks[149]?.sn).toBe("SN-149");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getMonthlyReportData", () => {
|
||||
@@ -424,6 +491,381 @@ describe("getMonthlyReportData", () => {
|
||||
expect(data.nextActions.reviewSet).toContain("seal-use report review set");
|
||||
expect(data.nextActions.validate).toBe("seal-use report validate <报告文件.md>");
|
||||
});
|
||||
|
||||
test("riskInterceptCount fallback counts AI reject + human pass + ai_correct and excludes AI pass + human reject", async () => {
|
||||
// 模拟离线台账场景(无 cloud performance.riskCount)
|
||||
// DEMO-007: AI 驳回,人工同意,裁决 ai_correct → 真正的风险拦截!
|
||||
// DEMO-008: AI 同意,人工驳回,裁决 ai_correct → 依规放行正确,非风险拦截!
|
||||
writeReview("corp-test", { sn: "DEMO-007", month: "2026-08", verdict: "ai_correct" });
|
||||
writeReview("corp-test", { sn: "DEMO-008", month: "2026-08", verdict: "ai_correct" });
|
||||
|
||||
const runs = [
|
||||
{
|
||||
id: "r1",
|
||||
sourceDocumentSN: "DEMO-007",
|
||||
result: { decision: "驳回", summary: "发票违规超标" },
|
||||
pipelineData: { humanResult: "同意" },
|
||||
document: { fields: [{ key: "specificationId", value: "一般费用报销" }] }
|
||||
},
|
||||
{
|
||||
id: "r2",
|
||||
sourceDocumentSN: "DEMO-008",
|
||||
result: { decision: "同意", summary: "合规放行" },
|
||||
pipelineData: { humanResult: "驳回" },
|
||||
document: { fields: [{ key: "specificationId", value: "一般费用报销" }] }
|
||||
}
|
||||
];
|
||||
|
||||
const fakeClient = {
|
||||
get: async () => ({ json: async () => ({ data: { records: runs, total: 2 } }) })
|
||||
} as never;
|
||||
|
||||
const data = await getMonthlyReportData(fakeClient, {
|
||||
month: "2026-08",
|
||||
corp: { id: "corp-test", name: "测试企业" }
|
||||
});
|
||||
|
||||
// 只有 DEMO-007 算入风险拦截,DEMO-008 属于依规放行不虚增风险拦截
|
||||
expect(data.metrics.riskInterceptCount).toBe(1);
|
||||
});
|
||||
|
||||
test("blocks buildMonthlyReport when unreviewed diverged runs exist", async () => {
|
||||
const runs = [
|
||||
{ id: "r1", sourceDocumentSN: "DIVERGED-01", result: { decision: "同意" }, pipelineData: { humanResult: "驳回" } }
|
||||
];
|
||||
const fakeClient = {
|
||||
get: async () => ({ json: async () => ({ data: { records: runs, total: 1 } }) })
|
||||
} as never;
|
||||
|
||||
await expect(
|
||||
buildMonthlyReport(fakeClient, {
|
||||
month: "2026-08",
|
||||
corp: { id: "corp-gate-test", name: "门禁测试企业" }
|
||||
})
|
||||
).rejects.toThrow("前置业务门禁拦截:检测到 1 笔人机分歧单据尚未完成复核裁决");
|
||||
|
||||
// With allowUnreviewed: true, it should bypass the gate
|
||||
const draft = await buildMonthlyReport(fakeClient, {
|
||||
month: "2026-08",
|
||||
corp: { id: "corp-gate-test", name: "门禁测试企业" },
|
||||
allowUnreviewed: true
|
||||
});
|
||||
expect(draft.content).toBeDefined();
|
||||
});
|
||||
|
||||
test("supports custom chapters inserted in the middle and arbitrary section ordering", () => {
|
||||
const template = [
|
||||
"# 【测试企业】8月AI审核准确率报告",
|
||||
"## 1. 审核测试结果",
|
||||
"| 审核方式 | 准确率 |",
|
||||
"| --- | --- |",
|
||||
"| AI 审核 | 90% |",
|
||||
"| 人工审核 | 80% |",
|
||||
"",
|
||||
"## 2. 营销线专项业务洞察(新插入章节)",
|
||||
"本章节为针对营销业务线的专项分析。",
|
||||
"| 业务条线 | 抽检单数 | 合规率 |",
|
||||
"| --- | --- | --- |",
|
||||
"| 华东大区 | 50 | 98% |",
|
||||
"| 华南大区 | 45 | 96% |",
|
||||
"",
|
||||
"## 3. AI 发现的潜在风险",
|
||||
"### 3.1 风险构成总览",
|
||||
"| 维度 | 风险类型 | 占比 | 单数 |",
|
||||
"| --- | --- | --- | --- |",
|
||||
"| TOP 1 | 缺失要求凭证 | 100% | 23 张 |",
|
||||
"| 合计 | — | 100% | 23 张 |",
|
||||
"",
|
||||
"### 3.2 TOP 1 · 缺失要求凭证(23 张 / 100.0%)",
|
||||
"| 单号 | 问题描述 |",
|
||||
"| --- | --- |",
|
||||
"| FP260011 | 缺失附件 |"
|
||||
].join("\n");
|
||||
|
||||
const plans = describeTemplate(template);
|
||||
expect(plans).toHaveLength(3);
|
||||
expect(plans[1]!.demands).toEqual([]); // 纯叙述新章节无需数据依赖
|
||||
expect(plans[2]!.demands).toContain("riskStats");
|
||||
|
||||
const out = renderMonthlyReport(template, sampleData(), plans);
|
||||
expect(out).toContain("营销线专项业务洞察(新插入章节)");
|
||||
expect(out).toContain("华东大区");
|
||||
expect(out).toContain("华南大区");
|
||||
expect(out).toContain("缺失要求凭证");
|
||||
});
|
||||
|
||||
test("supports custom date range (e.g. 2026-08-12 to 2026-09-18) without month constraint", async () => {
|
||||
let calledStart = "";
|
||||
let calledEnd = "";
|
||||
const fakeClient = {
|
||||
get: async (_url: string, opts?: { searchParams?: URLSearchParams }) => {
|
||||
calledStart = opts?.searchParams?.get("startDate") ?? "";
|
||||
calledEnd = opts?.searchParams?.get("endDate") ?? "";
|
||||
return { json: async () => ({ data: { records: [], total: 0 } }) };
|
||||
},
|
||||
post: async () => ({ json: async () => ({ data: { approvalCount: 0 } }) })
|
||||
} as never;
|
||||
|
||||
const res = await getMonthlyReportData(fakeClient, {
|
||||
startDate: "2026-08-12",
|
||||
endDate: "2026-09-18",
|
||||
corp: { id: "corp-a", name: "A企业" }
|
||||
});
|
||||
|
||||
expect(res.period.start).toBe("2026-08-12");
|
||||
expect(res.period.end).toBe("2026-09-18");
|
||||
expect(res.period.label).toBe("2026-08-12 ~ 2026-09-18");
|
||||
expect(calledStart).toBe(String(Date.parse("2026-08-12T00:00:00+08:00")));
|
||||
expect(calledEnd).toBe(String(Date.parse("2026-09-18T23:59:59.999+08:00")));
|
||||
});
|
||||
|
||||
test("filters data.blocks and templateGroups by template whitelist at the source", async () => {
|
||||
const runs = [
|
||||
{ id: "r1", sourceDocumentSN: "SN1", result: { decision: "同意" }, pipelineData: { humanResult: "同意" }, document: { fields: [{ key: "specificationId", value: "差旅报销" }] } },
|
||||
{ id: "r2", sourceDocumentSN: "SN2", result: { decision: "同意" }, pipelineData: { humanResult: "同意" }, document: { fields: [{ key: "specificationId", value: "采购付款" }] } },
|
||||
{ id: "r3", sourceDocumentSN: "SN3", result: { decision: "同意" }, pipelineData: { humanResult: "同意" }, document: { fields: [{ key: "specificationId", value: "车辆津贴" }] } },
|
||||
{ id: "r4", sourceDocumentSN: "SN4", result: { decision: "同意" }, pipelineData: { humanResult: "同意" }, document: { fields: [{ key: "specificationId", value: "招待费报销" }] } }
|
||||
];
|
||||
const fakeClient = {
|
||||
get: async () => ({ json: async () => ({ data: { records: runs, total: 4 } }) }),
|
||||
post: async () => ({ json: async () => ({ data: { approvalCount: 4 } }) })
|
||||
} as never;
|
||||
|
||||
// 虽拉到 4 种模板,但指定只保留 2 种
|
||||
const res = await getMonthlyReportData(fakeClient, {
|
||||
startDate: "2026-08-12",
|
||||
endDate: "2026-09-18",
|
||||
corp: { id: "corp-a", name: "A企业" },
|
||||
templates: ["差旅报销", "采购付款"]
|
||||
});
|
||||
|
||||
expect(res.templateGroups).toHaveLength(2);
|
||||
expect(res.templateGroups.map((g) => g.template).sort()).toEqual(["差旅报销", "采购付款"]);
|
||||
expect(res.agreedRunsSample.every((b) => ["差旅报销", "采购付款"].includes(b.template))).toBe(true);
|
||||
});
|
||||
|
||||
test("reviews by recordId specifically overrides an agreed block to AI correct and decrements human accuracy", async () => {
|
||||
// 写入裁决:针对 r1 这条运行记录(AI 驳回,人工也驳回),指名道姓覆盖为 AI 正确、人工失准
|
||||
writeReview("corp-override", {
|
||||
recordId: "run-both-reject-1",
|
||||
sn: "SN-AGREED",
|
||||
verdict: "ai_correct",
|
||||
note: "人工随口驳回,AI 依据合规条款驳回正确"
|
||||
});
|
||||
|
||||
const runs = [
|
||||
{
|
||||
id: "run-both-reject-1",
|
||||
sourceDocumentSN: "SN-AGREED",
|
||||
result: { decision: "驳回", summary: "缺少合规凭证" },
|
||||
pipelineData: { humanResult: "驳回" },
|
||||
document: { fields: [{ key: "specificationId", value: "费用报销" }] }
|
||||
},
|
||||
{
|
||||
id: "run-both-approve-2",
|
||||
sourceDocumentSN: "SN-AGREED-2",
|
||||
result: { decision: "同意" },
|
||||
pipelineData: { humanResult: "同意" },
|
||||
document: { fields: [{ key: "specificationId", value: "费用报销" }] }
|
||||
}
|
||||
];
|
||||
|
||||
const fakeClient = {
|
||||
get: async () => ({ json: async () => ({ data: { records: runs, total: 2 } }) }),
|
||||
post: async () => ({ json: async () => ({ data: { approvalCount: 2 } }) })
|
||||
} as never;
|
||||
|
||||
const res = await getMonthlyReportData(fakeClient, {
|
||||
startDate: "2026-08-12",
|
||||
endDate: "2026-09-18",
|
||||
corp: { id: "corp-override", name: "覆写测试企业" }
|
||||
});
|
||||
|
||||
// run-both-reject-1 原本双方一致驳回,被覆盖为 ai_correct:
|
||||
// AI 准确率 = 2/2 = 100%
|
||||
// 人工准确率 = 1/2 = 50%
|
||||
expect(res.metrics.aiAccuracy).toBe(100);
|
||||
expect(res.metrics.humanAccuracy).toBe(50);
|
||||
|
||||
const group = res.templateGroups[0]!;
|
||||
expect(group.aiAccuracy).toBe(100);
|
||||
expect(group.humanAccuracy).toBe(50);
|
||||
});
|
||||
|
||||
test("wording distinction: formatVerdict and parseVerdictText clearly separate document validity from audit correctness", () => {
|
||||
expect(
|
||||
formatVerdict({
|
||||
sn: "1",
|
||||
template: "T",
|
||||
agreement: "diverged",
|
||||
aiDecision: "驳回",
|
||||
humanResult: "同意",
|
||||
aiSummary: "超标",
|
||||
humanComment: undefined,
|
||||
verdict: "ai_correct"
|
||||
})
|
||||
).toBe("AI 判断正确 / 人工判断错误");
|
||||
|
||||
expect(
|
||||
formatVerdict({
|
||||
sn: "2",
|
||||
template: "T",
|
||||
agreement: "diverged",
|
||||
aiDecision: "驳回",
|
||||
humanResult: "同意",
|
||||
aiSummary: "误报",
|
||||
humanComment: undefined,
|
||||
verdict: "human_correct"
|
||||
})
|
||||
).toBe("人工判断正确 / AI 判定误判");
|
||||
|
||||
expect(
|
||||
formatVerdict({
|
||||
sn: "3",
|
||||
template: "T",
|
||||
agreement: "agreed",
|
||||
aiDecision: "同意",
|
||||
humanResult: "同意",
|
||||
aiSummary: "合规",
|
||||
humanComment: undefined,
|
||||
verdict: "both_correct"
|
||||
})
|
||||
).toBe("双方判断均正确");
|
||||
|
||||
expect(
|
||||
formatVerdict({
|
||||
sn: "4",
|
||||
template: "T",
|
||||
agreement: "agreed",
|
||||
aiDecision: "同意",
|
||||
humanResult: "同意",
|
||||
aiSummary: "漏检",
|
||||
humanComment: undefined,
|
||||
verdict: "both_wrong"
|
||||
})
|
||||
).toBe("双方判定均误判");
|
||||
|
||||
expect(parseVerdictText("AI正确")).toBe("ai_correct");
|
||||
expect(parseVerdictText("AI判断正确 / 人工判断错误")).toBe("ai_correct");
|
||||
expect(parseVerdictText("人工错误")).toBe("ai_correct");
|
||||
expect(parseVerdictText("人工合理")).toBe("human_correct");
|
||||
expect(parseVerdictText("人工判断正确 / AI 判定误判")).toBe("human_correct");
|
||||
expect(parseVerdictText("AI误判")).toBe("human_correct");
|
||||
expect(parseVerdictText("双方判断均正确")).toBe("both_correct");
|
||||
expect(parseVerdictText("双方判定均误判")).toBe("both_wrong");
|
||||
expect(parseVerdictText("存疑待定")).toBe("undecided");
|
||||
});
|
||||
|
||||
test("formatAiOpinion combines summary and triggered conditions into full audit rationale", () => {
|
||||
const text = formatAiOpinion({
|
||||
aiSummary: "发票金额超标",
|
||||
conditions: ["发票金额超出城市报销标准(350元)", "缺少同行人名单"]
|
||||
});
|
||||
expect(text).toContain("发票金额超标");
|
||||
expect(text).toContain("【触发违规/风险项】1. 发票金额超出城市报销标准(350元); 2. 缺少同行人名单");
|
||||
});
|
||||
|
||||
test("ledger round-trip: buildReportLedgerXlsx exports full comments and loadReportDataFromLedger respects Agent edits", async () => {
|
||||
const tmp = mkdtempSync(join(tmpdir(), "seal-ledger-test-"));
|
||||
try {
|
||||
const data = sampleData({
|
||||
blocks: [
|
||||
{
|
||||
recordId: "rec-001",
|
||||
sn: "SN-001",
|
||||
template: "差旅报销",
|
||||
title: "北京出差差旅",
|
||||
submitter: "张三",
|
||||
department: "技术部",
|
||||
createdAt: "2026-08-15 10:00:00",
|
||||
aiDecision: "驳回",
|
||||
humanResult: "同意",
|
||||
agreement: "diverged",
|
||||
aiSummary: "住宿超标",
|
||||
conditions: ["超标50元"],
|
||||
humanComment: "领导特批放行",
|
||||
verdict: undefined
|
||||
},
|
||||
{
|
||||
recordId: "rec-002",
|
||||
sn: "SN-002",
|
||||
template: "采购付款",
|
||||
title: "办公用品采购",
|
||||
submitter: "李四",
|
||||
department: "行政部",
|
||||
createdAt: "2026-08-18 14:00:00",
|
||||
aiDecision: "同意",
|
||||
humanResult: "同意",
|
||||
agreement: "agreed",
|
||||
aiSummary: "凭证齐全",
|
||||
humanComment: "核验无误",
|
||||
verdict: undefined
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
// 1. 导出 Excel 台账
|
||||
const buffer = await buildReportLedgerXlsx(data);
|
||||
const xlsxFile = join(tmp, "台账.xlsx");
|
||||
await Bun.write(xlsxFile, buffer);
|
||||
|
||||
// 2. 逆向加载台账
|
||||
const loaded = await loadReportDataFromLedger(xlsxFile);
|
||||
expect(loaded.blocks).toHaveLength(2);
|
||||
expect(loaded.blocks[0]!.sn).toBe("SN-001");
|
||||
expect(loaded.blocks[0]!.humanComment).toBe("领导特批放行");
|
||||
expect(loaded.blocks[0]!.aiSummary).toContain("超标50元");
|
||||
|
||||
// 3. 模拟 Agent 自由编辑台账:直接在 CSV/Excel 中完成裁决,并剔除掉采购付款模板(仅留差旅报销)
|
||||
const editedCsv = [
|
||||
"审核ID(recordId),单据编号(SN),单据模板,单据标题/事由,提交人,费用承担部门,跑批时间,AI审批决策,AI审核完整意见与违规详情,人工审批结论,人工审批批注/驳回说明,人机一致性,复核定性裁决,复核人,复核批注说明,审批耗时(秒)",
|
||||
'rec-001,SN-001,差旅报销,北京出差,张三,技术部,2026-08-15 10:00:00,驳回,超标,同意,领导特批放行,分歧,AI判断正确 / 人工判断错误,王总监,特批应走线下签批流程不应线上直接放行,12'
|
||||
].join("\n");
|
||||
const csvFile = join(tmp, "台账-edited.csv");
|
||||
await Bun.write(csvFile, editedCsv);
|
||||
|
||||
const loadedEdited = await loadReportDataFromLedger(csvFile);
|
||||
// 严格尊重 Agent 裁剪:只剩下 1 笔差旅报销,完全没有采购付款
|
||||
expect(loadedEdited.blocks).toHaveLength(1);
|
||||
expect(loadedEdited.templateGroups).toHaveLength(1);
|
||||
expect(loadedEdited.templateGroups[0]!.template).toBe("差旅报销");
|
||||
// 权威识别已填写的裁决
|
||||
expect(loadedEdited.blocks[0]!.verdict).toBe("ai_correct");
|
||||
expect(loadedEdited.blocks[0]!.reviewedBy).toBe("王总监");
|
||||
expect(loadedEdited.humanAccuracy).toBe(0); // 人工判断错误
|
||||
expect(loadedEdited.performance?.accuracy).toBe(100); // AI判断正确
|
||||
} finally {
|
||||
rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("buildMonthlyReport driven directly by --ledger skips remote fetch and validates in-place", async () => {
|
||||
const tmp = mkdtempSync(join(tmpdir(), "seal-report-ledger-test-"));
|
||||
try {
|
||||
// 构造已由 Agent 完成复核的台账
|
||||
const csv = [
|
||||
"审核ID(recordId),单据编号(SN),单据模板,单据标题/事由,提交人,费用承担部门,跑批时间,AI审批决策,AI审核完整意见与违规详情,人工审批结论,人工审批批注/驳回说明,人机一致性,复核定性裁决,复核人,复核批注说明,审批耗时(秒)",
|
||||
'rec-001,SN-001,差旅报销,北京出差,张三,技术部,2026-08-15 10:00:00,驳回,超标,同意,无批注,分歧,AI判断正确 / 人工判断错误,评审专家,AI依据城市差旅标准拦截正确,12',
|
||||
'rec-002,SN-002,差旅报销,上海出差,李四,市场部,2026-08-16 11:00:00,同意,合规,同意,通过,一致,双方判断均正确,评审专家,无误,8'
|
||||
].join("\n");
|
||||
const csvFile = join(tmp, "台账.csv");
|
||||
await Bun.write(csvFile, csv);
|
||||
|
||||
const fakeClient = {} as never;
|
||||
|
||||
const report = await buildMonthlyReport(fakeClient, {
|
||||
ledgerPath: csvFile,
|
||||
corp: { id: "corp-ledger", name: "台账驱动测试企业" }
|
||||
});
|
||||
|
||||
expect(report.content).toBeTruthy();
|
||||
expect(report.notes.humanAccuracyAvailable).toBe(true);
|
||||
expect(report.dynamicAssets?.["assets/图1-准确率对比.svg"]).toBeTruthy();
|
||||
} finally {
|
||||
rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
|
||||
import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { validationError } from "../../../../core/errors.js";
|
||||
import { SEAL_STATE_DIR } from "../../../../core/paths.js";
|
||||
|
||||
/**
|
||||
* 人工裁决的本地持久化(JSONL,按 租户 × 月份 分片)。
|
||||
* 人工裁决的本地持久化(JSONL,按租户分片,支持 recordId 与 SN 双键检索)。
|
||||
*
|
||||
* 为什么是 JSONL:跨周 review 天然是**追加**场景——每审一批写一批,不整文件重写,
|
||||
* 为什么是 JSONL:跨周期 review 天然是追加写入场景——每审一批写一批,不整文件重写,
|
||||
* 避免并发覆盖;单行一条记录,可直接 tail/grep/手改,也可被 CLI 批量导入。
|
||||
* 为什么按租户+月份分片:租户隔离、月度报告天然对应一个文件、文件不会无限膨胀。
|
||||
*
|
||||
* 一条记录 = 一个 SN 在某个月被人工裁决一次的结果。同一 SN 重复裁决时,
|
||||
* 以**最后一条**为准(loadReviews 归并时后写覆盖先写)。
|
||||
* 为什么按租户分片:租户天然数据隔离。
|
||||
* 标识符规则:优先以具体审核运行 ID(recordId)精确定位单次审核;同时支持单据 SN 作为业务自然键。
|
||||
* 后写覆盖先写。
|
||||
*/
|
||||
|
||||
/** 人工裁决结论:谁对。both_* 覆盖"一致但仍复核"与"分歧后判定双方各有对错"的场景。 */
|
||||
@@ -22,10 +22,12 @@ export type ReviewVerdict =
|
||||
| "undecided"; // 已 review 但暂无法判定(保留占位,后续可改判)
|
||||
|
||||
export type ReviewRecord = {
|
||||
/** 合思/源单据 SN(裁决的自然键) */
|
||||
sn: string;
|
||||
/** 裁决所属统计月 YYYY-MM(与 report monthly 的 month 对齐) */
|
||||
month: string;
|
||||
/** 审核运行记录 ID(精确裁决键) */
|
||||
recordId?: string;
|
||||
/** 合思/源单据 SN(业务自然键) */
|
||||
sn?: string;
|
||||
/** 裁决所属统计周期或月份(可选留痕) */
|
||||
month?: string;
|
||||
verdict: ReviewVerdict;
|
||||
/** 裁决人(可选,留痕用) */
|
||||
reviewedBy?: string;
|
||||
@@ -43,33 +45,76 @@ const VERDICTS: ReadonlySet<string> = new Set([
|
||||
"undecided"
|
||||
]);
|
||||
|
||||
import { SEAL_STATE_DIR } from "../../../../core/paths.js";
|
||||
export class ReviewsMap {
|
||||
readonly byRecordId = new Map<string, ReviewRecord>();
|
||||
readonly bySn = new Map<string, ReviewRecord>();
|
||||
readonly records: ReviewRecord[] = [];
|
||||
|
||||
set(record: ReviewRecord): this;
|
||||
set(key: string, record: ReviewRecord): this;
|
||||
set(keyOrRecord: string | ReviewRecord, maybeRecord?: ReviewRecord): this {
|
||||
const record = typeof keyOrRecord === "string" ? maybeRecord! : keyOrRecord;
|
||||
const key = typeof keyOrRecord === "string" ? keyOrRecord : record.recordId ?? record.sn ?? "";
|
||||
this.records.push(record);
|
||||
if (record.recordId) this.byRecordId.set(record.recordId, record);
|
||||
if (record.sn) this.bySn.set(record.sn, record);
|
||||
if (!record.recordId && !record.sn && key) {
|
||||
this.bySn.set(key, record);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
get(key: { recordId?: string; sn?: string } | string | undefined): ReviewRecord | undefined {
|
||||
if (!key) return undefined;
|
||||
if (typeof key === "string") {
|
||||
return this.byRecordId.get(key) ?? this.bySn.get(key);
|
||||
}
|
||||
if (key.recordId && this.byRecordId.has(key.recordId)) {
|
||||
return this.byRecordId.get(key.recordId);
|
||||
}
|
||||
if (key.sn && this.bySn.has(key.sn)) {
|
||||
return this.bySn.get(key.sn);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
has(key: { recordId?: string; sn?: string } | string): boolean {
|
||||
return this.get(key) !== undefined;
|
||||
}
|
||||
|
||||
get size(): number {
|
||||
return new Set([...this.byRecordId.keys(), ...this.bySn.keys()]).size;
|
||||
}
|
||||
|
||||
values(): IterableIterator<ReviewRecord> {
|
||||
const unique = new Map<string, ReviewRecord>();
|
||||
for (const r of this.records) {
|
||||
const id = r.recordId ? `rec:${r.recordId}` : `sn:${r.sn}`;
|
||||
unique.set(id, r);
|
||||
}
|
||||
return unique.values();
|
||||
}
|
||||
}
|
||||
|
||||
const REVIEWS_DIR_ENV = "SEAL_USE_REVIEWS_DIR";
|
||||
|
||||
/** 裁决存储根目录:~/.config/seal-use/state/reviews/(租户 = 文件名前缀)。可用 SEAL_USE_REVIEWS_DIR 覆盖(测试/隔离)。 */
|
||||
/** 裁决存储根目录:~/.config/seal-use/state/reviews/。可用 SEAL_USE_REVIEWS_DIR 覆盖(测试/隔离)。 */
|
||||
export function reviewsDir(): string {
|
||||
const configured = process.env[REVIEWS_DIR_ENV]?.trim();
|
||||
if (configured) return configured;
|
||||
return join(SEAL_STATE_DIR, "reviews");
|
||||
}
|
||||
|
||||
/** 分片路径:<reviewsDir>/<corpId>-<YYYY-MM>.jsonl */
|
||||
export function reviewFilePath(corpId: string, month: string): string {
|
||||
return join(reviewsDir(), `${sanitizeCorpId(corpId)}-${month}.jsonl`);
|
||||
/** 分片路径:<reviewsDir>/<corpId>[-<scope>].jsonl */
|
||||
export function reviewFilePath(corpId: string, scope?: string): string {
|
||||
const cleanCorp = sanitizeCorpId(corpId);
|
||||
return scope ? join(reviewsDir(), `${cleanCorp}-${scope}.jsonl`) : join(reviewsDir(), `${cleanCorp}.jsonl`);
|
||||
}
|
||||
|
||||
function sanitizeCorpId(corpId: string): string {
|
||||
// corpId 可能含路径分隔符等非法字符,压成安全片段
|
||||
return corpId.replace(/[^a-zA-Z0-9._-]/g, "_");
|
||||
}
|
||||
|
||||
function assertMonth(month: string): void {
|
||||
if (!/^\d{4}-\d{2}$/.test(month)) {
|
||||
throw validationError(`Invalid month "${month}", expected YYYY-MM`);
|
||||
}
|
||||
}
|
||||
|
||||
function assertVerdict(verdict: string): asserts verdict is ReviewVerdict {
|
||||
if (!VERDICTS.has(verdict)) {
|
||||
throw validationError(
|
||||
@@ -79,59 +124,87 @@ function assertVerdict(verdict: string): asserts verdict is ReviewVerdict {
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取某租户某月的全部裁决,按 SN 归并(同一 SN 后写覆盖先写)。文件不存在返回空 Map。
|
||||
* 读取某租户的全部裁决。若指定 scope(如月份),则仅读取该分片;否则读取该租户的主文件与各分片文件。按后写覆盖先写。
|
||||
*/
|
||||
export function loadReviews(corpId: string, month: string): Map<string, ReviewRecord> {
|
||||
assertMonth(month);
|
||||
const filePath = reviewFilePath(corpId, month);
|
||||
const reviews = new Map<string, ReviewRecord>();
|
||||
if (!existsSync(filePath)) return reviews;
|
||||
export function loadReviews(corpId: string, scope?: string): ReviewsMap {
|
||||
const reviews = new ReviewsMap();
|
||||
const sanitized = sanitizeCorpId(corpId);
|
||||
const targetDir = reviewsDir();
|
||||
if (!existsSync(targetDir)) return reviews;
|
||||
|
||||
const lines = readFileSync(filePath, "utf8").split("\n");
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed) continue;
|
||||
const targetFile = reviewFilePath(corpId, scope);
|
||||
const filesToRead: string[] = [];
|
||||
if (scope) {
|
||||
if (existsSync(targetFile)) filesToRead.push(targetFile);
|
||||
} else {
|
||||
if (existsSync(targetFile)) filesToRead.push(targetFile);
|
||||
try {
|
||||
const parsed = JSON.parse(trimmed) as ReviewRecord;
|
||||
if (parsed && typeof parsed.sn === "string" && VERDICTS.has(parsed.verdict)) {
|
||||
reviews.set(parsed.sn, parsed); // 后写覆盖先写
|
||||
const allFiles = readdirSync(targetDir);
|
||||
for (const f of allFiles) {
|
||||
if (f.startsWith(`${sanitized}-`) && f.endsWith(".jsonl")) {
|
||||
filesToRead.push(join(targetDir, f));
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 跳过损坏行:单行坏数据不应让整个裁决集不可读
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
|
||||
for (const filePath of filesToRead) {
|
||||
try {
|
||||
const lines = readFileSync(filePath, "utf8").split("\n");
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed) continue;
|
||||
try {
|
||||
const parsed = JSON.parse(trimmed) as ReviewRecord;
|
||||
if (parsed && (parsed.recordId || parsed.sn) && VERDICTS.has(parsed.verdict)) {
|
||||
reviews.set(parsed.recordId ?? parsed.sn!, parsed);
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
|
||||
return reviews;
|
||||
}
|
||||
|
||||
/**
|
||||
* 追加写一条裁决到磁盘(真正的落盘入口)。corpId 由调用方显式传入(sn 与租户无关,文件按租户分片)。
|
||||
* 追加写一条裁决到磁盘(支持 recordId 与 sn)。
|
||||
*/
|
||||
export function writeReview(
|
||||
corpId: string,
|
||||
input: {
|
||||
sn: string;
|
||||
month: string;
|
||||
recordId?: string;
|
||||
sn?: string;
|
||||
month?: string;
|
||||
scope?: string;
|
||||
verdict: string;
|
||||
reviewedBy?: string;
|
||||
note?: string;
|
||||
recordedAt?: string;
|
||||
}
|
||||
): ReviewRecord {
|
||||
const recordId = input.recordId?.trim();
|
||||
const sn = input.sn?.trim();
|
||||
if (!sn) throw validationError("sn is required for a review record");
|
||||
assertMonth(input.month);
|
||||
if (!recordId && !sn) {
|
||||
throw validationError("At least one of recordId or sn is required for a review record");
|
||||
}
|
||||
if (input.month && !/^\d{4}-\d{2}$/.test(input.month)) {
|
||||
throw validationError(`Invalid month "${input.month}", expected YYYY-MM`);
|
||||
}
|
||||
assertVerdict(input.verdict);
|
||||
|
||||
const record: ReviewRecord = {
|
||||
sn,
|
||||
month: input.month,
|
||||
...(recordId ? { recordId } : {}),
|
||||
...(sn ? { sn } : {}),
|
||||
...(input.month ? { month: input.month } : {}),
|
||||
verdict: input.verdict,
|
||||
...(input.reviewedBy?.trim() ? { reviewedBy: input.reviewedBy.trim() } : {}),
|
||||
...(input.note?.trim() ? { note: input.note.trim() } : {}),
|
||||
recordedAt: input.recordedAt ?? new Date().toISOString().slice(0, 19).replace("T", " ")
|
||||
};
|
||||
|
||||
const filePath = reviewFilePath(corpId, input.month);
|
||||
const scope = input.scope ?? input.month;
|
||||
const filePath = reviewFilePath(corpId, scope);
|
||||
mkdirSync(dirname(filePath), { recursive: true, mode: 0o700 });
|
||||
appendFileSync(filePath, JSON.stringify(record) + "\n", { encoding: "utf-8", mode: 0o600 });
|
||||
return record;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Report templates
|
||||
|
||||
月度 AI 审核准确率报告的模板与配套资产(供 `seal-use report monthly` 消费)。
|
||||
企业 AI 审核报告(验收、上线、周期审计)的模板与配套资产(供 `seal-use report generate` / `report monthly` 消费)。
|
||||
|
||||
| 文件 | 用途 |
|
||||
| --- | --- |
|
||||
@@ -14,11 +14,19 @@
|
||||
默认模板和配图由本仓库 Git 管理(位于 `src/domains/seal/reports/templates/`),构建时直接内嵌进二进制;无需外置模板目录或已安装的 Skill。模板修改通过 PR 合入,再随构建/发版分发。`--template` 仅用于显式覆盖。
|
||||
|
||||
```bash
|
||||
seal-use report monthly --month 2026-08 --corp <corpId> --out 报告.md
|
||||
# 模式 A (首选·Excel 台账自由裁量驱动):
|
||||
seal-use report ledger --start-date 2026-08-12 --end-date 2026-09-18 --corp <corpId> --out 台账.xlsx
|
||||
seal-use report generate --ledger 台账.xlsx --corp <corpId> --out 报告.md
|
||||
|
||||
# 模式 B (直接时间周期/月度提数驱动):
|
||||
seal-use report generate --start-date 2026-08-12 --end-date 2026-09-18 --corp <corpId> --out 报告.md
|
||||
|
||||
# 校验与多端渲染:
|
||||
seal-use report validate 报告.md
|
||||
seal-use report render 报告.md --out build/报告
|
||||
```
|
||||
|
||||
|
||||
`monthly --out` 保存 Markdown 和同目录的 `<报告名>.assets/` 配图目录,返回文件路径、数据缺口与后续命令;不指定 `--out` 时继续返回 `content`。自定义模板的本地配图也一并复制。已有文件默认拒绝覆盖,显式 `--overwrite` 才允许替换。通用 `--output-file` 仍只保存 JSON,与 `--out` 不同。
|
||||
|
||||
校验、渲染仅操作本地文件,不需要 `--corp`、登录或网络取数。校验失败返回结构化问题、退出码 1,并阻止导出。渲染成功返回产物路径、格式和字节数;HTML 内嵌本地配图及公式资源,可随产物移动。默认产出 HTML、完整长图 PNG、A4 分页 PDF;`--format html|png|pdf` 可选格式,PNG/PDF 同时保留 HTML。
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
| 报告状态 | 草稿 |
|
||||
| 生成日期 | 2026-09-23 |
|
||||
|
||||
> **摘要**:以模板企业授权的 240 笔已完成历史审批单据为样本,对 AI 审核结论与人工审核结论进行全量复核。AI 审核准确率 **92.08%**,人工审核准确率 **83.33%**;系统全月成功审核率近 **90%**,自 8 月 8 日迭代后稳定在 **96.07%**。AI 还在人工已同意的单据中额外识别出 **40 笔**存在风险。
|
||||
> **摘要**:以模板企业授权的 240 笔已完成历史审批单据为样本,对 AI 审核结论与人工审核结论进行全量复核。AI 审核准确率 **92.08%**,人工审核准确率 **83.33%**。AI 还在人工已同意的单据中额外识别出 **40 笔**存在风险。
|
||||
|
||||
---
|
||||
|
||||
@@ -40,15 +40,6 @@ $$ \text{AI 审核准确率} = \frac{\text{依规判定正确单数}}{\text{样
|
||||
|
||||
*图 1 · AI 与人工审核准确率对比*
|
||||
|
||||
### 1.3 系统稳定性
|
||||
|
||||
| 项目 | 内容 |
|
||||
| --- | --- |
|
||||
| 全月成功审核率 | 近 **90%** |
|
||||
| 迭代影响 | 8 月第一周失败率较高;自 8 月 8 日迭代后,系统稳定性升至 **96.07%** 的稳定运行常态 |
|
||||
|
||||
> **注**:“审核失败”是产品侧的保护机制:当 AI 对单据内容无法形成可靠判断,系统会将该次审核标记为失败,以避免错误影响实际审批。
|
||||
|
||||
---
|
||||
|
||||
## 2. AI 失准分析(学习优化空间)
|
||||
@@ -156,45 +147,30 @@ $$ \text{AI 审核准确率} = \frac{\text{依规判定正确单数}}{\text{样
|
||||
| 风险拦截 | 在人工审核通过的单据中,AI 有效防堵无票支付、大额无合同预付、税票违规等税务与资金安全隐患 | 40 笔 |
|
||||
| 工作量 | 协助财务人员弥补遗漏、关注单据重点信息,大幅释放财务人员精力,专注于更有价值的工作 | — |
|
||||
|
||||

|
||||
---
|
||||
|
||||
*图 2 · 综合效益对比*
|
||||
## 5. 审核分歧与复核归因
|
||||
|
||||
在全量 **240 单**的深度复核中,AI 审核决策与人工实际审批结果存在分歧的单据共 **3 笔**(占全量样本 **1.25%**)。对分歧单据的复核定性与主要原因归类如下:
|
||||
|
||||
| 原因分类 | 占比 | 单数 | 核心说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| 线下口头要求/未在线配置规则 | 66.7% | 2 张 | 单据凭证齐全且符合现行线上规则,主要因经办人主动撤回、无理由终止或财务执行未上线的口头标准,AI 依既定规则放行 |
|
||||
| AI 识别或规则理解偏差 | 33.3% | 1 张 | 单据缺少必要发票凭据,AI 未能正确识别缺件卡口放行,已纳入模型调优与规则修复样本 |
|
||||
| 合计 | 100% | 3 张 | — |
|
||||
|
||||
**分歧分析与后续建议**:
|
||||
|
||||
1. **规则覆盖与口径统一**:存在分歧的单据中,绝大多数(**66.7%**,2 笔)并非 AI 判定缺陷,而是企业内部存在线下口头补充管控要求。建议根据实际管理需要,将此类管控标准沉淀并补充至线上规则库。
|
||||
2. **算法与识别调优**:对于真实失准单据(仅 **1 笔**,占全量 **0.42%**),已归入模型样本库进行针对性专项训练。
|
||||
|
||||
> 📌 **注**:分歧单据的逐单编号、审核比对意见与复核裁决记录,已完整收录于配套交付的《明细台账.xlsx》中,可供业务与审计部门按单查验核对。
|
||||
|
||||
---
|
||||
|
||||
## 5. AI 与人工审核一致性示例
|
||||
## 6. 支撑数据与交付材料
|
||||
|
||||
| 示例单号 | 单据模板 | AI 审核驳回意见 | 人工实际退回说明 | 双方一致性 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| FP260022 | 一般费用报销单【发票】- 个人报销 | 墨镜发票(776.15 元,税率 13%)仅开具普通发票,单笔超 500 元未按规定开具增值税专用发票且无免专票佐证,建议驳回换开专票。 | 发票不合规:普票替换成专票 | 专票合规要求 100% 对齐:均严格执行超 500 元 13% 高税率发票必须开具专票的硬性管控 |
|
||||
| FP260023 | 一般费用报销单【发票】- 个人报销 | 改衣明细表未上传,必备核心附件缺失,不符合改衣费报销要求,建议驳回。 | 附件不合规:未提供改衣费明细表 | 必备明细表缺失一致:AI 精准拦截缺件,人工直接依据未提供改衣费明细表退回 |
|
||||
| FP260024 | 差旅报销单-定额 | 定额补助消费日期与关联出差申请单行程不符,超出合理出差区间,建议驳回。 | 表单填写错误:结余补贴时间与出差时间不一致 | 行程时间勾稽一致:双方均识别出补贴申请时间与实际行程脱节 |
|
||||
|
||||

|
||||
|
||||
*图 3 · 上述示例单对应的单据截图(可多张)*
|
||||
|
||||
---
|
||||
|
||||
## 6. AI 通过 / 人工驳回单据明细
|
||||
|
||||
| 单据编号 | 单据模板 | AI 审批决策 | 人工审批参考结论 | 原因分类 | 复核结论 | 截图 |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| FP260031 | 发票-个人报销 | 同意 | 终止(改衣费超标) | **依规正确(计入 D4)** | 单据改衣费发票、支付凭证及改衣明细表齐全且金额一致,收款人合规,符合改衣费报销规则;人工以口头“改衣费超标”为由终止,规则库中无此标准,AI 依规放行正确。 | (截图) |
|
||||
| FP260032 | 预提类采购申请 | 同意 | 终止(请核对采购金额;请补充费用计划) | **依规正确(计入 D4)** | 现行规则库对该类申请单不含采购金额与费用计划的强制校验卡口,单据字段与基础凭证合规,AI 依既定规则放行正确。 | (截图) |
|
||||
| SJ260033 | 收据-个人报销 | 同意 | 终止(无理由) | **AI 失准(不计入分子)** | 单据费用依规则必须提供正规发票,本单仅附收据无发票,不符合科目票据规范,AI 误判放行,属于规则执行错误。 | (截图) |
|
||||
|
||||
在上述 **3 笔**单据中:
|
||||
|
||||
1. **66.7%(2 / 3 笔)属于依规正确(计入 D4)**:单据在线上规则库下完全合规,退单主要由于经办人撤回、无理由终止,或财务人员执行尚未纳入线上规则库的其他口径。**AI 线上放行依据规则库正确。**
|
||||
|
||||
2. **仅有 1 笔属于 AI 真实失准(占全量样本 0.42%)**,已如实扣除准确率,未计入分子。
|
||||
|
||||
---
|
||||
|
||||
## 7. 支撑数据与材料
|
||||
|
||||
### 7.1 分模板准确率与自动审批率
|
||||
### 6.1 分模板准确率与自动审批率
|
||||
|
||||
全量 N = 240:
|
||||
|
||||
@@ -209,19 +185,6 @@ $$ \text{AI 审核准确率} = \frac{\text{依规判定正确单数}}{\text{样
|
||||
|
||||
*(其余 10 类模板从略,实际报告列出全量 16 类)*
|
||||
|
||||
### 7.2 跑批原始数据
|
||||
### 6.2 跑批原始数据与交付台账
|
||||
|
||||
见附件《8月单据审批质量审计报告_全量看板.xlsx》。
|
||||
|
||||
### 7.3 抽样方法与可复现性
|
||||
|
||||
本次复核共抽取 240 笔样本,抽样规则如下:
|
||||
|
||||
| # | 抽样规则 |
|
||||
| --- | --- |
|
||||
| 1 | 时间全月均衡覆盖,上 / 中 / 下旬各 80 笔 |
|
||||
| 2 | 100 笔 AI 同意 + 100 笔 AI 驳回 + 40 笔建议复核 |
|
||||
| 3 | 保底 30 笔大额采购与预付款单据(上中下旬各 10 笔),其余按各报销模板实际发生比例加权分配 |
|
||||
| 4 | 固定随机种子(取账期截止日)自动执行,全流程清单支持第三方精准复现核验 |
|
||||
|
||||
抽样基于账期截止日的固定随机种子执行,全过程可由第三方复现,完整可执行代码随报告附件交付。
|
||||
见同目录配套交付的《明细台账.xlsx》及《明细台账.csv》(完整收录本月全量跑批单据、AI 审核意见、人工审批结论及逐笔复核定性台账)。
|
||||
@@ -63,4 +63,14 @@ describe("native report validator", () => {
|
||||
expect(check(valid + "\n1、2、70\n$$\\frac{1}{2} = 70\\%$$\n").issues).toContainEqual(expect.objectContaining({ code: "NM005" }))
|
||||
expect(check(valid + "\n$$123456$$\n").issues).toContainEqual(expect.objectContaining({ code: "NM005", message: "公式中的数值 123456 在正文别处找不到,可能与数据脱节" }))
|
||||
})
|
||||
test("checks companion ledger CSV and blocks when unreviewed records exist", () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "validate-ledger-"))
|
||||
dirs.push(dir)
|
||||
const md = join(dir, "报告.md")
|
||||
writeFileSync(md, valid)
|
||||
writeFileSync(join(dir, "报告-明细台账.csv"), "SN,单据模板,人机一致性,复核定性结论\nS1,对公,分歧,待复核\n")
|
||||
const res = validateReportDocument(md)
|
||||
expect(res.valid).toBe(false)
|
||||
expect(res.issues).toContainEqual(expect.objectContaining({ code: "LD001" }))
|
||||
})
|
||||
})
|
||||
@@ -5,7 +5,6 @@ export type ReportIssue = { level: "ERROR" | "WARN"; code: string; message: stri
|
||||
export type ReportValidation = { file: string; valid: boolean; tables: number; figures: number; issues: ReportIssue[] }
|
||||
type ReportTable = { line: number; header: string[]; rows: Array<{ line: number; cells: string[] }> }
|
||||
|
||||
const sectionNumbers = ["1", "2", "3", "4", "5", "6", "7"]
|
||||
const requiredInfoRows = ["报告编号", "客户名称", "统计期间", "报告状态", "生成日期"]
|
||||
const forbiddenMarks: Array<[RegExp, string]> = [
|
||||
[/<!--slot:/, "slot 标记"], [/<!--\/slot/, "slot 闭合"], [/<!--@/, "@table/@block 区域标记"],
|
||||
@@ -89,7 +88,8 @@ export function validateReportDocument(file: string): ReportValidation {
|
||||
const number = heading[2]!.match(/^(\d+)\./)
|
||||
if (level === 2 && number) seen.push(number[1]!)
|
||||
}
|
||||
if (seen.length && seen.join(",") !== sectionNumbers.join(",")) error("HD002", `## 章节编号应为 ${list(sectionNumbers)},实际 ${list(seen)}`)
|
||||
const expected = seen.map((_, i) => String(i + 1))
|
||||
if (seen.length && seen.join(",") !== expected.join(",")) error("HD002", `## 章节编号应自 1 开始连续递增,期望 ${list(expected)},实际 ${list(seen)}`)
|
||||
|
||||
const byHeader = (keyword: string) => parsedTables.find((table) => table.header.join("").replaceAll(" ", "").includes(keyword))
|
||||
|
||||
@@ -133,25 +133,67 @@ export function validateReportDocument(file: string): ReportValidation {
|
||||
error("NM003", `${keyword}「${row[1]}」占比 ${decimal(share)}% ≠ ${count.toFixed(0)}/${base.toFixed(0)} = ${(count / base * 100).toFixed(1)}%`)
|
||||
}
|
||||
}
|
||||
// 小节标题里的张数与总览表一致
|
||||
// 找到当前大章节的文本范围(从当前 ## 开始到下一个 ## 结束,只在本章节内核验小节)
|
||||
let chapterText = text
|
||||
for (let i = table.line - 1; i >= 0; i--) {
|
||||
if (lines[i]?.match(/^##\s+/)) {
|
||||
let nextH2Line = lines.length
|
||||
for (let j = i + 1; j < lines.length; j++) {
|
||||
if (lines[j]?.match(/^##\s+/)) {
|
||||
nextH2Line = j
|
||||
break
|
||||
}
|
||||
}
|
||||
chapterText = lines.slice(i, nextH2Line).join("\n")
|
||||
break
|
||||
}
|
||||
}
|
||||
// 小节标题里的张数与总览表一致(只在本核心章节范围内匹配,不受章节编号与位置影响)
|
||||
for (const top of tops) {
|
||||
const section = keyword === "失准类型" ? "2" : "3"
|
||||
const escaped = top.name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
|
||||
const match = text.match(new RegExp(`###\\s*${section}\\.\\d+\\s*${escaped}[^(]*((\\d+)\\s*张`))
|
||||
const match = chapterText.match(new RegExp(`###\\s*\\S*\\s*${escaped}[^(\\n]*((\\d+)\\s*张`))
|
||||
if (match && top.count !== null && Number(match[1]) !== top.count) error(tag, `${top.name} 小节标题写 ${match[1]} 张,总览表写 ${top.count.toFixed(0)} 张`)
|
||||
}
|
||||
}
|
||||
|
||||
// NM004:§6 明细表的结论分类计数 = 正文数字
|
||||
// NM004:分歧结论分类计数 = 正文数字
|
||||
const detail = byHeader("原因分类")
|
||||
if (detail) {
|
||||
const correct = detail.rows.filter((row) => row.cells.length > 4 && row.cells[4]!.includes("依规正确")).length
|
||||
const missed = detail.rows.filter((row) => row.cells.length > 4 && row.cells[4]!.includes("失准")).length
|
||||
const counts = text.match(/((\d+)\s*\/\s*(\d+)\s*笔)/)
|
||||
const miss = text.match(/仅有\s*\*{0,2}(\d+)\s*笔/)
|
||||
if (counts && Number(counts[1]) !== correct) error("NM004", `正文称依规正确 ${counts[1]} 笔,明细表实际 ${correct} 行`)
|
||||
if (counts && Number(counts[2]) !== detail.rows.length) error("NM004", `正文称合计 ${counts[2]} 笔,明细表实际 ${detail.rows.length} 行`)
|
||||
if (miss && Number(miss[1]) !== missed) error("NM004", `正文称 AI 失准 ${miss[1]} 笔,明细表实际 ${missed} 行`)
|
||||
if (detail.header.some((col) => col.includes("单号") || col.includes("单据编号"))) {
|
||||
const correct = detail.rows.filter((row) => row.cells.length > 4 && row.cells[4]!.includes("依规正确")).length
|
||||
const missed = detail.rows.filter((row) => row.cells.length > 4 && (row.cells[4]!.includes("失准") || row.cells[4]!.includes("误判"))).length
|
||||
const counts = text.match(/((\d+)\s*\/\s*(\d+)\s*笔)/)
|
||||
const miss = text.match(/仅有\s*\*{0,2}(\d+)\s*笔/)
|
||||
if (counts && Number(counts[1]) !== correct) error("NM004", `正文称依规正确 ${counts[1]} 笔,明细表实际 ${correct} 行`)
|
||||
if (counts && Number(counts[2]) !== detail.rows.length) error("NM004", `正文称合计 ${counts[2]} 笔,明细表实际 ${detail.rows.length} 行`)
|
||||
if (miss && Number(miss[1]) !== missed) error("NM004", `正文称 AI 失准 ${miss[1]} 笔,明细表实际 ${missed} 行`)
|
||||
} else if (detail.header.some((col) => col.includes("单数"))) {
|
||||
const countIdx = detail.header.findIndex((col) => col.includes("单数"))
|
||||
const rows = detail.rows.map((row) => row.cells)
|
||||
const nonTotals = rows.filter((row) => !["合计", "总计", "—"].includes(row[0]!))
|
||||
const totalRow = rows.find((row) => ["合计", "总计", "—"].includes(row[0]!))
|
||||
if (countIdx >= 0) {
|
||||
const sum = nonTotals.reduce((s, r) => s + (numeric(r[countIdx]!) ?? 0), 0)
|
||||
if (totalRow) {
|
||||
const totalVal = numeric(totalRow[countIdx]!)
|
||||
if (totalVal !== null && sum !== totalVal) error("NM004", `原因分类各维度单数之和 ${decimal(sum)} ≠ 合计 ${decimal(totalVal)}`)
|
||||
}
|
||||
const counts = text.match(/(\*{0,2}\d+(?:\.\d+)?%\*{0,2},\s*(\d+)\s*笔)/) ?? text.match(/((\d+)\s*\/\s*(\d+)\s*笔)/)
|
||||
if (counts && nonTotals[0]) {
|
||||
const c1 = numeric(nonTotals[0][countIdx]!)
|
||||
if (c1 !== null && Number(counts[1]) !== c1) {
|
||||
error("NM004", `正文称非判定缺陷 ${counts[1]} 笔,分类表实际 ${c1} 张`)
|
||||
}
|
||||
}
|
||||
const miss = text.match(/真实失准单据[^\d]*(\d+)\s*笔/) ?? text.match(/仅有\s*\*{0,2}(\d+)\s*笔/)
|
||||
if (miss && nonTotals[1]) {
|
||||
const c2 = numeric(nonTotals[1][countIdx]!)
|
||||
if (c2 !== null && Number(miss[1]) !== c2) {
|
||||
error("NM004", `正文称真实失准 ${miss[1]} 笔,分类表实际 ${c2} 张`)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// NM005:公式算术自洽,且代入值能在正文别处找到
|
||||
@@ -168,5 +210,25 @@ export function validateReportDocument(file: string): ReportValidation {
|
||||
if (!outside.includes(token)) error("NM005", `公式中的数值 ${token} 在正文别处找不到,可能与数据脱节`)
|
||||
}
|
||||
}
|
||||
|
||||
// 6. 配套台账勾稽门禁(若同目录下存在配套交付的明细台账 CSV)
|
||||
const baseStem = path.replace(/\.md$/, "")
|
||||
const ledgerCsvPath = existsSync(`${baseStem}-明细台账.csv`)
|
||||
? `${baseStem}-明细台账.csv`
|
||||
: existsSync(resolve(dirname(path), "明细台账.csv"))
|
||||
? resolve(dirname(path), "明细台账.csv")
|
||||
: null
|
||||
|
||||
if (ledgerCsvPath) {
|
||||
const csvContent = readFileSync(ledgerCsvPath, "utf8")
|
||||
const csvRows = csvContent.trim().split("\n").slice(1)
|
||||
const unreviewedRows = csvRows.filter((r) =>
|
||||
r.split(",").map((c) => c.replace(/^["'\s]+|["'\s]+$/g, "")).includes("待复核")
|
||||
)
|
||||
if (unreviewedRows.length > 0) {
|
||||
error("LD001", `配套台账(${ledgerCsvPath.split("/").pop()})中存在 ${unreviewedRows.length} 笔未裁决单据(标记为「待复核」),正式交付前必须完成全量裁决`)
|
||||
}
|
||||
}
|
||||
|
||||
return report
|
||||
}
|
||||
+1
-1
@@ -13,7 +13,7 @@ Release. On WSL, `seal-use-release-sync.timer` polls the latest release every
|
||||
|
||||
The first archive becomes available as soon as it is present in Gitea.
|
||||
The remaining assets retry idempotently on later timer runs if needed.
|
||||
Promotion only mirrors release assets; it does not update package-manager repositories.
|
||||
Promotion mirrors all published release assets as well as Git repository branches and tags to the local Gitea mirror. It does not update package-manager repositories.
|
||||
|
||||
The WSL worker uses its local mihomo listener at `http://127.0.0.1:7897` only
|
||||
for GitHub. It does not enable TUN or expose a LAN listener. Local Gitea
|
||||
|
||||
@@ -16,6 +16,7 @@ NO_PROXY_LIST="${NO_PROXY:-127.0.0.1,localhost,100.82.151.105,git.ying-qing.cn}"
|
||||
GITHUB_TOKEN_FILE="${SEAL_USE_GITHUB_TOKEN_FILE:-$HOME/.config/seal-use/github-token}"
|
||||
GITEA_TOKEN_FILE="${SEAL_USE_GITEA_TOKEN_FILE:-$HOME/.config/seal-use/gitea-token}"
|
||||
LOCK_FILE="${SEAL_USE_SYNC_LOCK_FILE:-$STATE_DIR/sync.lock}"
|
||||
GIT_MIRROR_DIR="${SEAL_USE_SYNC_GIT_MIRROR_DIR:-$STATE_DIR/repo.git}"
|
||||
|
||||
mkdir -p "$STATE_DIR" "$WORK_DIR"
|
||||
exec 9>"$LOCK_FILE"
|
||||
@@ -67,6 +68,39 @@ gitea_curl() {
|
||||
return "$rc"
|
||||
}
|
||||
|
||||
sync_git_repo() {
|
||||
log "synchronizing Git repository refs (branches and tags) to Gitea"
|
||||
if [ ! -d "$GIT_MIRROR_DIR" ]; then
|
||||
log "initializing bare mirror repository at $GIT_MIRROR_DIR"
|
||||
mkdir -p "$GIT_MIRROR_DIR"
|
||||
git init --bare "$GIT_MIRROR_DIR" >/dev/null
|
||||
fi
|
||||
|
||||
local gh_url="https://github.com/${GITHUB_REPO}.git"
|
||||
local gitea_url="${GITEA_BASE}/${GITEA_REPO}.git"
|
||||
|
||||
log "fetching latest refs from GitHub ($GITHUB_REPO)"
|
||||
if ! env HTTP_PROXY="$PROXY_URL" HTTPS_PROXY="$PROXY_URL" ALL_PROXY= NO_PROXY="$NO_PROXY_LIST" \
|
||||
git --git-dir="$GIT_MIRROR_DIR" \
|
||||
-c http.extraHeader="Authorization: Bearer ${GITHUB_TOKEN}" \
|
||||
fetch --prune --tags --force "$gh_url" '+refs/heads/*:refs/heads/*' '+refs/tags/*:refs/tags/*' >&2; then
|
||||
log "warning: failed to fetch Git refs from GitHub; skipping Git mirror push this run"
|
||||
return 0
|
||||
fi
|
||||
|
||||
log "mirroring refs to Gitea ($GITEA_REPO)"
|
||||
if ! env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY NO_PROXY="$NO_PROXY_LIST" \
|
||||
git --git-dir="$GIT_MIRROR_DIR" \
|
||||
-c http.extraHeader="Authorization: token ${GITEA_TOKEN}" \
|
||||
push --prune --tags --force "$gitea_url" '+refs/heads/*:refs/heads/*' '+refs/tags/*:refs/tags/*' >&2; then
|
||||
log "warning: failed to push Git refs to Gitea; will retry next timer"
|
||||
return 0
|
||||
fi
|
||||
log "Git repository refs successfully synchronized to Gitea"
|
||||
}
|
||||
|
||||
sync_git_repo
|
||||
|
||||
release_json=$(github_curl -H 'Accept: application/vnd.github+json' \
|
||||
"https://api.github.com/repos/$GITHUB_REPO/releases/latest") || die "cannot read latest GitHub release"
|
||||
tag=$(jq -r '.tag_name // empty' <<< "$release_json")
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
[Unit]
|
||||
Description=Promote GitHub releases to Gitea
|
||||
Description=Promote GitHub releases and mirror repository refs to Gitea
|
||||
After=network-online.target docker.service mihomo.service
|
||||
Wants=network-online.target
|
||||
Requires=mihomo.service
|
||||
|
||||
Reference in new issue
Block a user