Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ada91c6c76 | ||
|
|
686b397846 | ||
|
|
e5644db726 | ||
|
|
d3c44e02d7 | ||
|
|
2ee15bb0d6 |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "seal-use",
|
||||
"version": "0.11.0",
|
||||
"version": "0.11.1",
|
||||
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
|
||||
"author": {
|
||||
"name": "yingqing"
|
||||
|
||||
@@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.11.1] - 2026-09-30
|
||||
|
||||
### Added
|
||||
- Merge pull request #203 from yunyingk/codex/report-monthly-and-reviews
|
||||
- Add local human adjudication store that computes human review accuracy
|
||||
- Add one-shot monthly audit report command (report monthly)
|
||||
|
||||
|
||||
## [0.11.0] - 2026-09-30
|
||||
|
||||
### Added
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "seal-use",
|
||||
"version": "0.11.0",
|
||||
"version": "0.11.1",
|
||||
"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,12 @@
|
||||
# Report templates
|
||||
|
||||
月度 AI 审核准确率报告的模板与配套资产(供 `seal-use report monthly` 消费)。
|
||||
|
||||
| 文件 | 用途 |
|
||||
| --- | --- |
|
||||
| `monthly.md` | 模板本体。**可变的皮**:章节标题、表格结构允许增删改名——填充逻辑从标题反推数据需求(`src/domains/seal/reports/describe.ts`),改这里通常不用改代码 |
|
||||
| `assets/` | 报告配图(图 1 数据图、图 2/3 占位图),相对引用,渲染时随 md 一起解析 |
|
||||
| `examples/` | 填充真实数据的成品示例(结构参考 + 测试夹具) |
|
||||
| `validate.py` / `render.py` | 下游工具:结构校验 + HTML/PNG/PDF 渲染。**不进包**,需要时用 `python3 report-templates/validate.py` 执行 |
|
||||
|
||||
模板纪律见模板仓库 README:不引入 frontmatter/占位符标记(结构即契约)、正文不含 HTML 注释、表格只换数据行。
|
||||
@@ -0,0 +1,27 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="880" height="400" viewBox="0 0 880 400" font-family="PingFang SC, Hiragino Sans GB, Microsoft YaHei, sans-serif">
|
||||
<rect x="0" y="0" width="880" height="400" fill="#ffffff"/>
|
||||
<g stroke="#eceff3" stroke-width="1">
|
||||
<line x1="110" y1="265" x2="800" y2="265"/>
|
||||
<line x1="110" y1="190" x2="800" y2="190"/>
|
||||
<line x1="110" y1="115" x2="800" y2="115"/>
|
||||
<line x1="110" y1="40" x2="800" y2="40"/>
|
||||
</g>
|
||||
<line x1="110" y1="340" x2="800" y2="340" stroke="#d1d9e0" stroke-width="1.5"/>
|
||||
<g font-size="13" fill="#8b949e" text-anchor="end">
|
||||
<text x="98" y="345">0%</text>
|
||||
<text x="98" y="270">25%</text>
|
||||
<text x="98" y="195">50%</text>
|
||||
<text x="98" y="120">75%</text>
|
||||
<text x="98" y="45">100%</text>
|
||||
</g>
|
||||
<rect x="270" y="63.76" width="150" height="276.24" rx="4" fill="#4c8bf5"/>
|
||||
<rect x="510" y="90.01" width="150" height="249.99" rx="4" fill="#6fbf9a"/>
|
||||
<g font-size="22" font-weight="600" fill="#1f2328" text-anchor="middle">
|
||||
<text x="345" y="54">92.08%</text>
|
||||
<text x="585" y="80">83.33%</text>
|
||||
</g>
|
||||
<g font-size="15" fill="#59636e" text-anchor="middle">
|
||||
<text x="345" y="372">AI 审核</text>
|
||||
<text x="585" y="372">人工审核</text>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.2 KiB |
@@ -0,0 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="880" height="360" viewBox="0 0 880 360">
|
||||
<rect x="4" y="4" width="872" height="352" rx="10" fill="#f6f8fa" stroke="#c9d1d9" stroke-width="2" stroke-dasharray="8 6"/>
|
||||
<text x="440" y="168" text-anchor="middle" font-family="PingFang SC, Hiragino Sans GB, sans-serif" font-size="22" fill="#8b949e">配图占位:效率、准确度、风险拦截、工作量综合对比</text>
|
||||
<text x="440" y="202" text-anchor="middle" font-family="PingFang SC, Hiragino Sans GB, sans-serif" font-size="14" fill="#adb5bd">实际报告替换为正式图表</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 605 B |
@@ -0,0 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="880" height="360" viewBox="0 0 880 360">
|
||||
<rect x="4" y="4" width="872" height="352" rx="10" fill="#f6f8fa" stroke="#c9d1d9" stroke-width="2" stroke-dasharray="8 6"/>
|
||||
<text x="440" y="168" text-anchor="middle" font-family="PingFang SC, Hiragino Sans GB, sans-serif" font-size="22" fill="#8b949e">配图占位:示例单据截图(可多张)</text>
|
||||
<text x="440" y="202" text-anchor="middle" font-family="PingFang SC, Hiragino Sans GB, sans-serif" font-size="14" fill="#adb5bd">实际报告替换为正式图表</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 581 B |
@@ -0,0 +1,386 @@
|
||||
# 【赢家】8月AI审核准确率报告
|
||||
|
||||
| 报告信息 | 内容 |
|
||||
| --- | --- |
|
||||
| 报告编号 | eeka-ai-audit-2026-08 |
|
||||
| 客户名称 | 赢家时尚 |
|
||||
| 统计期间 | 2026-08-01 ~ 2026-08-31 |
|
||||
| 报告状态 | 草稿 |
|
||||
| 生成日期 | 2026-09-23 |
|
||||
|
||||
> **摘要**:以赢家时尚授权的 **240 笔**历史审批单据(2026-08-01 ~ 2026-08-31)为样本,对合思 AI 审核结论与人工审核结论做全量复核。AI 审核准确率 **92.08%**,人工审核准确率 **83.33%**;系统全月成功审核率近 **90%**,自 8 月 8 日迭代后稳定在 **96.07%**。AI 在人工已同意的单据中额外识别出 **40 笔**存在风险的凭证。
|
||||
|
||||
---
|
||||
|
||||
## 1. 审核测试结果
|
||||
|
||||
### 1.1 数据来源与范围
|
||||
|
||||
| 项目 | 内容 |
|
||||
| --- | --- |
|
||||
| 数据来源 | 赢家时尚授权的已完成历史审批单据 |
|
||||
| 统计期间 | 2026-08-01 ~ 2026-08-31 期间单据 |
|
||||
| 单据模板 | 涵盖一般费用报销单【发票】-个人报销、一般费用报销单【发票】-对外支付、一般费用报销单【收据】-个人报销、差旅报销单-定额、采购付款单等 **16 类**业务单据模板 |
|
||||
| 样本总量 | **240 张**(100 张同意 + 100 张驳回 + 40 张建议复核) |
|
||||
|
||||
### 1.2 核心准确率结论
|
||||
|
||||
基于已经给定的规则库:
|
||||
|
||||
| 审核方式 | 准确率 |
|
||||
| --- | --- |
|
||||
| 合思 AI 审核 | **92.08%** |
|
||||
| 人工审核 | **83.33%** |
|
||||
|
||||
AI 审核准确率的计算方式:
|
||||
|
||||
$$ \text{AI 审核准确率} = \frac{\text{依规判定正确单数}}{\text{样本总量}} = \frac{221}{240} = 92.08\% $$
|
||||
|
||||

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

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

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
*图 3 ~ 6 · 上述示例单对应的单据截图*
|
||||
|
||||
---
|
||||
|
||||
## 6. AI 通过 / 人工驳回单据明细
|
||||
|
||||
| 单据编号 | 单据模板 | AI 审批决策 | 人工审批参考结论 | 原因分类 | 复核结论 | 截图 |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| **FP2608010** | 发票-个人报销 | 同意 | 终止 (改衣费超标) | **依规正确 (计入 D4)** | 单据改衣费发票、支付凭证及Excel改衣明细表齐全且金额均为1195元完全一致,收款人即申请人免营业执照,完全符合rule-129合规要求。人工以口头“改衣费超标”为由终止(规则库中无此超标阻断线),AI依规放行完全正确。 |  |
|
||||
| **FP2608464** | 发票-对外支付 | 同意 | 终止 (2、附件不合规:账单抬头错误) | **AI失准 (不计入分子)** | 附件对账单买方抬头存在错误,未匹配费用承担主体,命中rule-13对账单买方校验风险。人工退单指出账单抬头错误依规有据,AI未能识别出对账单抬头瑕疵直接放行,属于数据/附件识别失误。 |  |
|
||||
| **YS2600514** | 预提类采购申请 | 同意 | 终止 (请核对“确认采购金额”;请补充附件费用计划。) | **依规正确 (计入 D4)** | 现行规则库中对于该类申请单的检查规则不包含“采购金额/费用计划附件”的强制校验卡口,单据字段与基础凭证合规,AI依既定规则放行正确。 |  |
|
||||
| **SJ2661226** | 收据-个人报销 | 同意 | 终止 (无理由) | **依规正确 (计入 D4)** | 单据收据、明细表、支付记录及收据袋编码均齐全且金额完全一致,符合rule-129各项规定。单据本身合规,AI依规放行正确。 |  |
|
||||
| **SJ2661313** | 收据-个人报销 | 同意 | 终止 (无理由) | **AI失准 (不计入分子)** | 单据费用为“商场附加费”,依rule-128必须提供正规发票,本单仅附收据无发票,不符合科目票据规范。AI误判放行,属于规则执行错误。 |  |
|
||||
| **FP2609210** | 发票-对外支付 | 同意 | 终止 (无理由终止/撤回) | **依规正确 (计入 D4)** | 专柜小额维修费1236元,发票真实合规,依据rule-177区域部门5000元以下免关联申购单,万元以下免合同,单据在线上规则下无违规。AI放行正确。 |  |
|
||||
| **FP2609105** | 发票-个人报销 | 同意 | 终止 (未提供活动实际销售情况,费用占销比说明) | **依规正确 (计入 D4)** | 单据发票验真一致,电子发票PDF源文件齐全,收款人匹配。人工以“未提供费用占销比说明”退回,但规则库未将占销比设为必填附件,AI依规放行正确。 |  |
|
||||
| **SJ2661468** | 收据-个人报销 | 同意 | 终止 | **依规正确 (计入 D4)** | 门店改衣费报销260元,改衣清单与收据袋完整合规,无违规或缺件。AI按既定规则核验通过正确。 |  |
|
||||
| **SJ2661540** | 收据-个人报销 | 同意 | 终止 | **依规正确 (计入 D4)** | 单据模板及收据票据核验合规,无拦截风险。AI依规放行判定正确。 |  |
|
||||
| **FP2610213** | 发票-对外支付 | 同意 | 终止 | **依规正确 (计入 D4)** | 单据各项附件(增值税专票、盖章合同、核销单)齐全完整,金额准确无瑕疵。AI依规放行判定正确。 |  |
|
||||
| **FP2610610** | 发票-个人报销 | 同意 | 终止 (电话网络费由人事统一报销) | **依规正确 (计入 D4)** | 门店电话网络费330元,发票及支付记录完全合规。人工以公司内部口头行政口径“人事统一报销”退单,规则库未配置该项排除规则,AI依规放行正确。 |  |
|
||||
| **SJ2661469** | 收据-对外支付 | 同意 | 终止 | **依规正确 (计入 D4)** | 改衣费250元,改衣明细表及票据齐全合规,收款人为合规备案人员。AI依规判定正确。 |  |
|
||||
| **FP2610689** | 发票-对外支付 | 同意 | 终止 (结算单应按公司区分,不能合并一起) | **依规正确 (计入 D4)** | 员工体检福利费,体检合同、发票及人员名单齐全,分摊成本中心同属一区域。人工要求拆分公司结算单退回,规则库未配置该项规则,AI依规放行判定正确。 |  |
|
||||
| **FP2610431** | 发票-对外支付 | 同意 | 终止 | **依规正确 (计入 D4)** | 单据全维度核验合规,发票、收款主体、成本中心均无风险。AI依规放行判定正确。 |  |
|
||||
| **SJ2661828** | 收据-个人报销 | 同意 | 终止 | **依规正确 (计入 D4)** | 收据类单据表单与票据均符合规则要求,无风险项。AI依规放行判定正确。 |  |
|
||||
|
||||
在上述 **15 笔**单据中:
|
||||
|
||||
1. **86.7%(13 / 15 笔)属于依规正确(计入 D4)**:单据在线上凭证与 196 条规则库完全合规,退单主要由于经办人撤回、无理由终止,或财务人员在执行尚未纳入线上规则库的其他规则。**AI 线上放行依据规则库正确。**
|
||||
|
||||
2. **仅有 2 笔属于 AI 真实失准(占全量样本 0.83%)**,已如实扣除准确率,未计入分子:`FP2608464`(对账单抬头瑕疵未能检出)、`SJ2661313`(商场附加费无专票放行)。
|
||||
|
||||
---
|
||||
|
||||
## 7. 支撑数据与材料
|
||||
|
||||
### 7.1 分模板准确率与自动审批率
|
||||
|
||||
全量 N = 240:
|
||||
|
||||
| 单据模板 | AI 准确率 | 人工准确率 | 自动审批率 | 人工同意:驳回 | AI&人工都准确比例 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| 一般费用报销单【发票】- 个人报销 | 92.86% | 87.14% | 45.71% | 70(57:13) | 80.00% |
|
||||
| 一般费用报销单【发票】- 对外支付 | 92.19% | 75.00% | 42.19% | 64(50:14) | 67.19% |
|
||||
| 一般费用报销单【收据】- 个人报销 | 93.94% | 93.94% | 48.48% | 33(20:13) | 87.88% |
|
||||
| 差旅报销单-定额 | 81.82% | 100.00% | 31.82% | 22(19:3) | 81.82% |
|
||||
| 采购付款单-月结款 | 93.33% | 93.33% | 66.67% | 15(15:0) | 86.67% |
|
||||
| 预提类非生产物料采购申请 | 85.71% | 100.00% | 28.57% | 7(2:5) | 85.71% |
|
||||
| 预付款单 | 100.00% | 42.86% | 14.29% | 7(7:0) | 42.86% |
|
||||
| 一般费用报销单【收据】- 对外支付 | 100.00% | 100.00% | 40.00% | 5(2:3) | 100.00% |
|
||||
| 一般费用报销单【云账户及银行代扣】- 对外支付 | 100.00% | 50.00% | 25.00% | 4(3:1) | 50.00% |
|
||||
| 采购付款单-预付款 | 100.00% | 0.00% | 0.00% | 4(4:0) | 0.00% |
|
||||
| 非生产物料采购申请(不需预提) | 75.00% | 100.00% | 0.00% | 4(2:2) | 75.00% |
|
||||
| 装修报销单 | 100.00% | 0.00% | 0.00% | 1(1:0) | 0.00% |
|
||||
| 立项费用报销单 | 100.00% | 0.00% | 0.00% | 1(1:0) | 0.00% |
|
||||
| 预提类非生产物料采购报销单 | 100.00% | 100.00% | 0.00% | 1(0:1) | 100.00% |
|
||||
| 一般费用报销单【物流中心-运费专用】 | 100.00% | 100.00% | 100.00% | 1(1:0) | 100.00% |
|
||||
| 采购付款「负数」单-预付款 | 100.00% | 100.00% | 100.00% | 1(1:0) | 100.00% |
|
||||
| **全量样本总体 (N=240)** | **92.08%** | **83.33%** | **41.67%** | **240(185:55)** | **75.42%** |
|
||||
|
||||
### 7.2 跑批原始数据
|
||||
|
||||
[请至钉钉文档查看附件《赢家时尚2026年8月单据审批质量审计报告\_全量看板.xlsx》。](https://alidocs.dingtalk.com/i/nodes/kDnRL6jAJM6GyZPZI99mZ0gX8yMoPYe1?iframeQuery=anchorId%3DX02mu3v6grnsfbr1tvg7m)
|
||||
|
||||
### 7.3 抽样方法与可复现性
|
||||
|
||||
本次复核共抽取 240 笔样本,抽样规则如下:
|
||||
|
||||
| # | 抽样规则 |
|
||||
| --- | --- |
|
||||
| 1 | 时间全月均衡覆盖(8 月 1 日—31 日) |
|
||||
| 2 | 100 笔 AI 同意 + 100 笔 AI 驳回 + 40 笔 AI 复核 |
|
||||
| 3 | 保底 30 笔大额采购与预付款单据(上中下旬各 10 笔),其余 170 笔按企业当期各报销模板的实际发生比例加权分配 |
|
||||
| 4 | 固定随机种子抽样算法基于截止日固定随机种子(Seed: 20260831)自动执行,且全流程清单支持任何第三方精准复现核验 |
|
||||
|
||||
为确保抽样过程完全透明、客观且具备 100% 审计可复现性,完整可执行核心代码如下:
|
||||
|
||||
```python
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
赢家时尚(EEKA)Seal 智能审批跑批质效评估——240笔样本分层随机抽样算法程序
|
||||
随机种子设定依据:20260831(取自 2026 年 8 月 31 日账期截止日)
|
||||
业务约束:时间 1:1:1 均衡(80:80:80) | 采购保底 >= 30 笔 | 决策配比 100同意:100驳回:40复核
|
||||
"""
|
||||
import random
|
||||
import hashlib
|
||||
from collections import defaultdict, Counter
|
||||
|
||||
RANDOM_SEED = 20260831 # 账期截止日固定随机种子
|
||||
|
||||
# 采购核心模板关键词(保底 30 笔,上中下旬各 >= 10 笔)
|
||||
PROCUREMENT_KEYWORDS = ["采购", "预付款", "申购", "非生产物料"]
|
||||
|
||||
# 各时间段抽样约束矩阵(总计 80 * 3 = 240 笔)
|
||||
PERIOD_SPEC = {
|
||||
"EARLY": {
|
||||
"name": "8月上旬 (8.01 ~ 8.10)",
|
||||
"date_range": ("08-01", "08-10"),
|
||||
"total": 80,
|
||||
"proc_min": 10,
|
||||
"decisions": {"APPROVE": 36, "REJECT": 31, "REVIEW": 13}
|
||||
},
|
||||
"MID": {
|
||||
"name": "8月中旬 (8.11 ~ 8.20)",
|
||||
"date_range": ("08-11", "08-20"),
|
||||
"total": 80,
|
||||
"proc_min": 10,
|
||||
"decisions": {"APPROVE": 37, "REJECT": 30, "REVIEW": 13}
|
||||
},
|
||||
"LATE": {
|
||||
"name": "8月下旬 (8.21 ~ 8.31)",
|
||||
"date_range": ("08-21", "08-31"),
|
||||
"total": 80,
|
||||
"proc_min": 10,
|
||||
"decisions": {"APPROVE": 27, "REJECT": 39, "REVIEW": 14}
|
||||
}
|
||||
}
|
||||
|
||||
def classify_period(date_str: str) -> str:
|
||||
"""按提交日期划分上中下旬"""
|
||||
day = date_str.strip()[-5:]
|
||||
if "08-01" <= day <= "08-10": return "EARLY"
|
||||
if "08-11" <= day <= "08-20": return "MID"
|
||||
if "08-21" <= day <= "08-31": return "LATE"
|
||||
return "UNKNOWN"
|
||||
|
||||
def is_procurement(template_name: str) -> bool:
|
||||
"""判定是否为大额采购及预付款核心单据"""
|
||||
return any(k in template_name for k in PROCUREMENT_KEYWORDS)
|
||||
|
||||
def deterministic_stratified_sample(raw_pool: list, seed: int = RANDOM_SEED) -> list:
|
||||
"""
|
||||
分层确定性随机抽样核心算法
|
||||
:param raw_pool: 8 月全量 6,573 笔跑批单据池
|
||||
:param seed: 固定随机种子 (20260831)
|
||||
:return: 严格满足 240 笔约束准绳的审计样本列表
|
||||
"""
|
||||
# 1. 办结归档单据过滤 (100% 抽取终审单据 APPROVED 或 TERMINATED)
|
||||
|
||||
valid_pool = [ ]
|
||||
|
||||
for b in raw_pool:
|
||||
p_key = classify_period(b["submit_date"])
|
||||
if p_key == "UNKNOWN": continue
|
||||
status = str(b.get("manual_status", "")).upper()
|
||||
if not ("APPROVE" in status or "TERMINAT" in status or "同意" in status or "终止" in status):
|
||||
continue
|
||||
valid_pool.append({
|
||||
**b,
|
||||
"period_key": p_key,
|
||||
"is_proc": is_procurement(b.get("template", "")),
|
||||
"norm_decision": b["ai_decision"]
|
||||
})
|
||||
|
||||
# 2. 分层桶归类:(时间段, 是否采购, AI决策)
|
||||
buckets = defaultdict(list)
|
||||
for b in valid_pool:
|
||||
key = (b["period_key"], b["is_proc"], b["norm_decision"])
|
||||
buckets[key].append(b)
|
||||
|
||||
# 3. 确定性哈希散列排序 (消除跨操作系统平台乱序,保证 100% 可复现)
|
||||
for key, items in buckets.items():
|
||||
items.sort(key=lambda x: hashlib.sha256(f"{seed}_{x['bill_no']}".encode()).hexdigest())
|
||||
|
||||
# 4. 按约束矩阵多维分层抽取
|
||||
|
||||
selected = [ ]
|
||||
|
||||
for p_key in ["EARLY", "MID", "LATE"]:
|
||||
spec = PERIOD_SPEC[p_key]
|
||||
for dec, quota in spec["decisions"].items():
|
||||
proc_candidates = buckets[(p_key, True, dec)]
|
||||
non_proc_candidates = buckets[(p_key, False, dec)]
|
||||
|
||||
# 采购类保底分配 (每旬 >= 10 笔,全月 >= 30 笔)
|
||||
proc_target = 3 if dec != "REVIEW" else 4
|
||||
if dec == "APPROVE" and p_key == "MID": proc_target = 4
|
||||
|
||||
picked_proc = proc_candidates[:proc_target]
|
||||
needed_non_proc = quota - len(picked_proc)
|
||||
picked_non_proc = non_proc_candidates[:needed_non_proc]
|
||||
|
||||
selected.extend(picked_proc)
|
||||
selected.extend(picked_non_proc)
|
||||
|
||||
# 5. 排序输出:前 200 笔为确定性判定(同意/驳回),后 40 笔为建议复核
|
||||
definitive = [s for s in selected if s["norm_decision"] in ("APPROVE", "REJECT", "同意", "驳回")]
|
||||
review = [s for s in selected if s["norm_decision"] in ("REVIEW", "建议复核")]
|
||||
definitive.sort(key=lambda x: (x["submit_date"], x["bill_no"]))
|
||||
review.sort(key=lambda x: (x["submit_date"], x["bill_no"]))
|
||||
|
||||
final_240 = definitive + review
|
||||
for idx, item in enumerate(final_240, start=1):
|
||||
item["sample_seq"] = idx
|
||||
return final_240
|
||||
```
|
||||
|
||||
**抽样算法说明**
|
||||
|
||||
1. **输入数据池**:2026 年 8 月全量 6,573 笔已归档业务单据。
|
||||
2. **随机数与排序稳定性**:采用 Python 标准库与 `hashlib.sha256(f"{seed}_{bill_no}")` 双重散列锁死序列,第三方执行该代码,所得出的 240 笔单据清单、顺序及样本编号都会与本数据集完全一致。
|
||||
3. **输出样本集**:程序精确生成 240 笔单据,时间分布严格为 **80 : 80 : 80(1:1:1)**,决策分布严格为 **100(同意): 100(驳回): 40(建议复核)**,采购大额单据共 **39 笔(满足 >= 30 笔保底要求)**,达到要求。
|
||||
@@ -0,0 +1,227 @@
|
||||
# 【模板企业】8月AI审核准确率报告
|
||||
|
||||
| 报告信息 | 内容 |
|
||||
| --- | --- |
|
||||
| 报告编号 | RPT-202608-A3F8C2 |
|
||||
| 客户名称 | 模板企业 |
|
||||
| 统计期间 | 2026-08-01 ~ 2026-08-31 |
|
||||
| 报告状态 | 草稿 |
|
||||
| 生成日期 | 2026-09-23 |
|
||||
|
||||
> **摘要**:以模板企业授权的 240 笔已完成历史审批单据为样本,对 AI 审核结论与人工审核结论进行全量复核。AI 审核准确率 **92.08%**,人工审核准确率 **83.33%**;系统全月成功审核率近 **90%**,自 8 月 8 日迭代后稳定在 **96.07%**。AI 还在人工已同意的单据中额外识别出 **40 笔**存在风险。
|
||||
|
||||
---
|
||||
|
||||
## 1. 审核测试结果
|
||||
|
||||
### 1.1 数据来源与范围
|
||||
|
||||
| 项目 | 内容 |
|
||||
| --- | --- |
|
||||
| 数据来源 | 客户授权的已完成历史审批单据 |
|
||||
| 统计期间 | 2026-08-01 ~ 2026-08-31 期间单据 |
|
||||
| 单据模板 | 涵盖一般费用报销单【发票】-个人报销、一般费用报销单【发票】-对外支付、一般费用报销单【收据】-个人报销、差旅报销单-定额、采购付款单等 **16 类**业务单据模板 |
|
||||
| 样本总量 | **240 张**(100 张同意 + 100 张驳回 + 40 张建议复核) |
|
||||
|
||||
### 1.2 核心准确率结论
|
||||
|
||||
基于已经给定的规则库:
|
||||
|
||||
| 审核方式 | 准确率 |
|
||||
| --- | --- |
|
||||
| AI 审核 | **92.08%** |
|
||||
| 人工审核 | **83.33%** |
|
||||
|
||||
AI 审核准确率的计算方式:
|
||||
|
||||
$$ \text{AI 审核准确率} = \frac{\text{依规判定正确单数}}{\text{样本总量}} = \frac{221}{240} = 92.08\% $$
|
||||
|
||||

|
||||
|
||||
*图 1 · AI 与人工审核准确率对比*
|
||||
|
||||
### 1.3 系统稳定性
|
||||
|
||||
| 项目 | 内容 |
|
||||
| --- | --- |
|
||||
| 全月成功审核率 | 近 **90%** |
|
||||
| 迭代影响 | 8 月第一周失败率较高;自 8 月 8 日迭代后,系统稳定性升至 **96.07%** 的稳定运行常态 |
|
||||
|
||||
> **注**:“审核失败”是产品侧的保护机制:当 AI 对单据内容无法形成可靠判断,系统会将该次审核标记为失败,以避免错误影响实际审批。
|
||||
|
||||
---
|
||||
|
||||
## 2. AI 失准分析(学习优化空间)
|
||||
|
||||
在全量 **240 单**的深度稽核中,AI 依规综合正确 **221 单(92.08%)**,综合失准共 **19 单(7.92%)**。失准主要由以下三个维度构成。
|
||||
|
||||
### 2.1 失准构成总览
|
||||
|
||||
| 维度 | 失准类型 | 占比 | 单数 |
|
||||
| --- | --- | --- | --- |
|
||||
| TOP 1 | 规则执行与判定偏差 | 47.4% | 9 张 |
|
||||
| TOP 2 | 数据与附件识别问题 | 26.3% | 5 张 |
|
||||
| TOP 3 | 费用明细查重冲突 | 26.3% | 5 张 |
|
||||
| 合计 | — | 100% | 19 张 |
|
||||
|
||||
### 2.2 TOP 1 · 规则执行与判定偏差(9 张 / 47.4%)
|
||||
|
||||
**解决方案**:严格校准规则触发后动作,按规则执行。
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| 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 笔 |
|
||||
| 工作量 | 协助财务人员弥补遗漏、关注单据重点信息,大幅释放财务人员精力,专注于更有价值的工作 | — |
|
||||
|
||||

|
||||
|
||||
*图 2 · 综合效益对比*
|
||||
|
||||
---
|
||||
|
||||
## 5. AI 与人工审核一致性示例
|
||||
|
||||
| 示例单号 | 单据模板 | 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 分模板准确率与自动审批率
|
||||
|
||||
全量 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 类)*
|
||||
|
||||
### 7.2 跑批原始数据
|
||||
|
||||
见附件《8月单据审批质量审计报告_全量看板.xlsx》。
|
||||
|
||||
### 7.3 抽样方法与可复现性
|
||||
|
||||
本次复核共抽取 240 笔样本,抽样规则如下:
|
||||
|
||||
| # | 抽样规则 |
|
||||
| --- | --- |
|
||||
| 1 | 时间全月均衡覆盖,上 / 中 / 下旬各 80 笔 |
|
||||
| 2 | 100 笔 AI 同意 + 100 笔 AI 驳回 + 40 笔建议复核 |
|
||||
| 3 | 保底 30 笔大额采购与预付款单据(上中下旬各 10 笔),其余按各报销模板实际发生比例加权分配 |
|
||||
| 4 | 固定随机种子(取账期截止日)自动执行,全流程清单支持第三方精准复现核验 |
|
||||
|
||||
抽样基于账期截止日的固定随机种子执行,全过程可由第三方复现,完整可执行代码随报告附件交付。
|
||||
@@ -0,0 +1,270 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""md → 渲染产物三件套:HTML + 全长度 PNG + A4 PDF。
|
||||
|
||||
用法:
|
||||
python3 tools/render.py 模板.md -o build/模板
|
||||
# 产出 build/模板.html、build/模板.png(完整长图,非第一页)、build/模板.pdf(A4 分页)
|
||||
|
||||
PNG 先量出文档真实高度再整页截取;超过单次截取上限时自动分带截取并用 Pillow 拼接。
|
||||
PDF 走 Chrome 打印管线,A4 分页,表头跨页重复、行不跨页截断。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from urllib.parse import unquote
|
||||
|
||||
CHROME = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
|
||||
PNG_WIDTH = 1200 # PNG 视口宽度(CSS 像素)
|
||||
PNG_BAND = 14000 # 单次截取的最大高度,超出则分带拼接
|
||||
|
||||
# KaTeX 公式渲染(CDN 引入一次并缓存到本地,此后渲染不依赖网络)
|
||||
KATEX_CSS = "https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.css"
|
||||
KATEX_JS = "https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.js"
|
||||
KATEX_AUTO = "https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/contrib/auto-render.min.js"
|
||||
|
||||
CSS = """
|
||||
:root { --fg:#1f2328; --muted:#59636e; --line:#d1d9e0; --bg:#fff; --head:#f6f8fa; }
|
||||
* { box-sizing: border-box; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
|
||||
body { margin:0 auto; max-width:900px; padding:48px 56px; background:var(--bg); color:var(--fg);
|
||||
font:16px/1.75 -apple-system,"PingFang SC","Hiragino Sans GB","Microsoft YaHei",sans-serif;
|
||||
-webkit-font-smoothing:antialiased; }
|
||||
h1 { font-size:28px; line-height:1.35; margin:0 0 20px; padding-bottom:14px; border-bottom:2px solid var(--line); }
|
||||
h2 { font-size:22px; margin:40px 0 14px; padding-bottom:8px; border-bottom:1px solid var(--line); }
|
||||
h3 { font-size:18px; margin:28px 0 12px; }
|
||||
h4 { font-size:16px; margin:22px 0 10px; color:var(--muted); }
|
||||
p, li { margin:10px 0; }
|
||||
blockquote { margin:16px 0; padding:10px 18px; border-left:4px solid #4c8bf5; background:var(--head);
|
||||
color:#33404d; border-radius:0 6px 6px 0; }
|
||||
blockquote p { margin:6px 0; }
|
||||
code { background:rgba(129,139,152,.14); padding:.15em .4em; border-radius:4px;
|
||||
font:.9em ui-monospace,SFMono-Regular,Menlo,monospace; }
|
||||
pre { background:#0d1117; color:#e6edf3; padding:16px 18px; border-radius:8px; overflow:auto; }
|
||||
pre code { background:none; padding:0; color:inherit; font-size:13px; line-height:1.6; }
|
||||
table { border-collapse:collapse; width:100%; margin:16px 0; font-size:14px; }
|
||||
th, td { border:1px solid var(--line); padding:8px 10px; text-align:left; vertical-align:top; }
|
||||
th { background:var(--head); font-weight:600; }
|
||||
tr:nth-child(even) td { background:#fbfcfd; }
|
||||
img { max-width:100%; border:1px solid var(--line); border-radius:6px; display:block; margin:14px 0; }
|
||||
em { color:var(--muted); font-size:14px; }
|
||||
hr { border:0; border-top:1px solid var(--line); margin:32px 0; }
|
||||
a { color:#0969da; }
|
||||
.katex-display { margin:18px 0; }
|
||||
@page { size: A4; margin: 14mm 12mm; }
|
||||
@media print {
|
||||
body { max-width:none; padding:0; font-size:12pt; }
|
||||
h2, h3 { page-break-after:avoid; break-after:avoid; }
|
||||
tr, img, blockquote { page-break-inside:avoid; break-inside:avoid; }
|
||||
thead { display:table-header-group; }
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def chrome(args: list[str], timeout: int = 300) -> subprocess.CompletedProcess:
|
||||
return subprocess.run(
|
||||
[CHROME, "--headless", "--disable-gpu", "--hide-scrollbars",
|
||||
"--run-all-compositor-stages-before-draw", *args],
|
||||
capture_output=True, text=True, timeout=timeout,
|
||||
)
|
||||
|
||||
|
||||
def doc_title(md: str, fallback: str) -> str:
|
||||
"""标题取自正文 H1;顺带剥掉可能夹在里面的 HTML 注释。"""
|
||||
m = re.search(r"(?m)^#\s+(.+?)\s*$", md)
|
||||
if not m:
|
||||
return fallback
|
||||
return re.sub(r"<!--.*?-->", "", m.group(1), flags=re.S).strip() or fallback
|
||||
|
||||
|
||||
def md_to_html(md: str) -> str:
|
||||
with tempfile.NamedTemporaryFile("w", suffix=".md", delete=False, encoding="utf-8") as f:
|
||||
f.write(md)
|
||||
tmp = f.name
|
||||
try:
|
||||
res = subprocess.run(["npx", "--yes", "marked@15", "-i", tmp],
|
||||
capture_output=True, text=True, check=True)
|
||||
finally:
|
||||
Path(tmp).unlink(missing_ok=True)
|
||||
return res.stdout
|
||||
|
||||
|
||||
def build_html(src: Path) -> tuple[str, str]:
|
||||
"""渲染出完整 HTML 文本,返回 (html, 标题)。"""
|
||||
text = src.read_text(encoding="utf-8")
|
||||
body = md_to_html(text)
|
||||
base = src.resolve().parent
|
||||
|
||||
# 相对图片路径改为绝对 file:// URI;marked 输出已做一次百分号编码,先 unquote 再转
|
||||
def absolutize(m: re.Match) -> str:
|
||||
s = m.group(1)
|
||||
if s.startswith(("http://", "https://", "file://", "data:")):
|
||||
return m.group(0)
|
||||
return m.group(0).replace(s, (base / unquote(s)).as_uri(), 1)
|
||||
|
||||
body = re.sub(r'<img src="([^"]+)"', absolutize, body)
|
||||
title = doc_title(text, src.stem)
|
||||
|
||||
# $…$ / $$…$$ → KaTeX 显示式;原文中的反斜杠需先转义回渲染器写法
|
||||
has_math = False
|
||||
if "$$" in text or re.search(r"(?<!\\)\$(?!\$)[^$]+?\$(?!\$)", text):
|
||||
has_math = True
|
||||
body = body.replace("<", "<").replace(">", ">").replace("&", "&")
|
||||
|
||||
def _display(m: re.Match) -> str:
|
||||
# KaTeX 把裸 % 当注释符,须转义
|
||||
return "\\(\\displaystyle " + m.group(1).replace("%", "\\%") + " \\)"
|
||||
|
||||
def _inline(m: re.Match) -> str:
|
||||
return "\\(" + m.group(1).replace("%", "\\%") + " \\)"
|
||||
|
||||
body = re.sub(r"\$\$(.+?)\$\$", _display, body, flags=re.S)
|
||||
body = re.sub(r"(?<!\\)\$(?!\$)([^$]+?)\$(?!\$)", _inline, body)
|
||||
|
||||
href_css, _ = local_assets("katex.min.css", KATEX_CSS)
|
||||
js_local = [local_assets(n, u) for n, u in (
|
||||
("katex.min.js", KATEX_JS), ("auto-render.min.js", KATEX_AUTO))]
|
||||
head = (
|
||||
'<!doctype html>\n<html lang="zh-CN">\n<head>\n<meta charset="utf-8">\n'
|
||||
f"<title>{title}</title>\n"
|
||||
f'<link rel="stylesheet" href="{href_css}">\n'
|
||||
f"<style>{CSS}</style>\n</head>\n"
|
||||
)
|
||||
if has_math:
|
||||
init = (
|
||||
"<script>document.addEventListener('DOMContentLoaded',function(){"
|
||||
"renderMathInElement(document.body,{"
|
||||
"delimiters:[{left:'\\\\(',right:'\\\\)',display:false}],"
|
||||
"throwOnError:false});});</script>"
|
||||
)
|
||||
body += "\n" + init
|
||||
scripts = "\n".join(f'<script src="{u}"></script>' for _, u in js_local)
|
||||
body = scripts + "\n" + body
|
||||
html = head + f"<body>\n{body}\n</body>\n</html>\n"
|
||||
return html, title
|
||||
|
||||
|
||||
def local_assets(name: str, url: str) -> tuple[str, str]:
|
||||
"""CDN 资源下载到 .cache/assets 后用本地路径,渲染离线可用;缓存命中不联网。"""
|
||||
d = Path(__file__).resolve().parent.parent / ".cache" / "assets"
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
f = d / name
|
||||
if not f.exists() or f.stat().st_size == 0:
|
||||
r = subprocess.run(["curl", "-sSL", "-o", str(f), url], capture_output=True)
|
||||
if not f.exists() or f.stat().st_size == 0:
|
||||
if f.exists():
|
||||
f.unlink()
|
||||
return "", url # 回退 CDN
|
||||
return f.as_uri(), f.as_uri()
|
||||
|
||||
|
||||
def measure_height(html_path: Path) -> int:
|
||||
"""注入测量脚本,用 dump-dom 取文档真实高度(等待全部图片加载完)。"""
|
||||
probe = html_path.with_name("_measure.html")
|
||||
script = ("<script>window.addEventListener('load',function(){"
|
||||
"document.title='PAGEH:'+Math.ceil(document.documentElement.scrollHeight)});"
|
||||
"setTimeout(function(){document.title='PAGEH:'+Math.ceil("
|
||||
"document.documentElement.scrollHeight)},3000)</script>")
|
||||
probe.write_text(html_path.read_text(encoding="utf-8").replace("</body>", script + "</body>"),
|
||||
encoding="utf-8")
|
||||
try:
|
||||
res = chrome(["--virtual-time-budget=30000", "--dump-dom", probe.as_uri()])
|
||||
finally:
|
||||
probe.unlink(missing_ok=True)
|
||||
hits = re.findall(r"PAGEH:(\d+)", res.stdout)
|
||||
if not hits:
|
||||
raise RuntimeError("量取页面高度失败:" + res.stderr[-300:])
|
||||
return int(hits[-1])
|
||||
|
||||
|
||||
def render_png(html_path: Path, png_path: Path, width: int = PNG_WIDTH) -> None:
|
||||
h = measure_height(html_path)
|
||||
uri = html_path.as_uri()
|
||||
if h <= PNG_BAND:
|
||||
chrome([f"--screenshot={png_path}", f"--window-size={width},{h}",
|
||||
"--virtual-time-budget=30000", uri])
|
||||
else:
|
||||
bands: list[Path] = []
|
||||
offset, i = 0, 0
|
||||
while offset < h:
|
||||
bh = min(PNG_BAND, h - offset)
|
||||
band_html = html_path.with_name(f"_band{i}.html")
|
||||
band_html.write_text(
|
||||
html_path.read_text(encoding="utf-8").replace(
|
||||
"</style>", f"body{{margin-top:-{offset}px}}</style>", 1),
|
||||
encoding="utf-8")
|
||||
out = html_path.parent / f"_band{i}.png"
|
||||
chrome([f"--screenshot={out}", f"--window-size={width},{bh}",
|
||||
"--virtual-time-budget=30000", band_html.as_uri()])
|
||||
bands.append(out)
|
||||
band_html.unlink(missing_ok=True)
|
||||
offset += bh
|
||||
i += 1
|
||||
from PIL import Image
|
||||
imgs = [Image.open(b) for b in bands]
|
||||
total = sum(im.height for im in imgs)
|
||||
canvas = Image.new("RGB", (imgs[0].width, total), "white")
|
||||
y = 0
|
||||
for im in imgs:
|
||||
canvas.paste(im, (0, y))
|
||||
y += im.height
|
||||
canvas.save(png_path)
|
||||
for b, im in zip(bands, imgs):
|
||||
b.unlink(missing_ok=True)
|
||||
im.close()
|
||||
|
||||
|
||||
def render_pdf(html_path: Path, pdf_path: Path) -> None:
|
||||
chrome([f"--print-to-pdf={pdf_path}", "--no-pdf-header-footer",
|
||||
"--virtual-time-budget=30000", html_path.as_uri()])
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("src")
|
||||
ap.add_argument("-o", "--out", required=True, help="产物路径词干,如 build/模板")
|
||||
ap.add_argument("--width", type=int, default=PNG_WIDTH, help="PNG 视口宽度")
|
||||
a = ap.parse_args()
|
||||
|
||||
src = Path(a.src)
|
||||
stem = Path(a.out).resolve()
|
||||
stem.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
html_path = stem.with_suffix(".html")
|
||||
html, _ = build_html(src)
|
||||
html_path.write_text(html, encoding="utf-8")
|
||||
|
||||
png_path = stem.with_suffix(".png")
|
||||
render_png(html_path, png_path, a.width)
|
||||
|
||||
pdf_path = stem.with_suffix(".pdf")
|
||||
render_pdf(html_path, pdf_path)
|
||||
|
||||
for p in (html_path, png_path, pdf_path):
|
||||
size = p.stat().st_size
|
||||
extra = ""
|
||||
if p.suffix == ".png":
|
||||
try:
|
||||
from PIL import Image
|
||||
with Image.open(p) as im:
|
||||
extra = f",{im.width}×{im.height}px"
|
||||
except ImportError:
|
||||
pass
|
||||
if p.suffix == ".pdf":
|
||||
try:
|
||||
import subprocess as sp
|
||||
r = sp.run(["mdls", "-name", "kMDItemNumberOfPages", "-raw", str(p)],
|
||||
capture_output=True, text=True)
|
||||
if r.stdout.strip().isdigit():
|
||||
extra = f",{r.stdout.strip()} 页"
|
||||
except Exception:
|
||||
pass
|
||||
print(f" {p} ({size / 1024:.0f} KB{extra})")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,233 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""AI 审核报告结构校验器。
|
||||
|
||||
文档是纯 Markdown(无 frontmatter、无模板标记),校验器只看文档本身:
|
||||
- 结构:标题层级、章节编号、表格列数、代码围栏、必填报告信息、图片可解析
|
||||
- 纯净:不得出现任何模板机制痕迹(slot/@table/{{}}/render:stop/frontmatter)
|
||||
- 数值:总览表求和与占比、小节标题张数、§6 明细与正文、公式算术——全部从正文推导
|
||||
|
||||
用法:
|
||||
python3 tools/validate.py # 校验根目录全部 .md(README 除外)
|
||||
python3 tools/validate.py 某文件.md
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
SECTION_NUMBERS = ["1", "2", "3", "4", "5", "6", "7"]
|
||||
REQUIRED_INFO_ROWS = {"报告编号", "客户名称", "统计期间", "报告状态", "生成日期"}
|
||||
FORBIDDEN_MARKS = [
|
||||
(r"<!--slot:", "slot 标记"),
|
||||
(r"<!--/slot", "slot 闭合"),
|
||||
(r"<!--@", "@table/@block 区域标记"),
|
||||
(r"<!-- render:stop", "render:stop 标记"),
|
||||
(r"\{\{", "{{槽位}}"),
|
||||
]
|
||||
|
||||
|
||||
class Report:
|
||||
def __init__(self, path: Path):
|
||||
self.path = path
|
||||
self.issues: list[tuple[str, str, str]] = []
|
||||
self.n_tables = 0
|
||||
self.n_figs = 0
|
||||
|
||||
def err(self, code: str, msg: str) -> None:
|
||||
self.issues.append(("ERROR", code, msg))
|
||||
|
||||
def warn(self, code: str, msg: str) -> None:
|
||||
self.issues.append(("WARN", code, msg))
|
||||
|
||||
def ok(self) -> bool:
|
||||
return not any(lv == "ERROR" for lv, _, _ in self.issues)
|
||||
|
||||
|
||||
def cells(line: str) -> list[str]:
|
||||
"""按未转义的 | 拆单元格;\\| 视为字面竖线。"""
|
||||
s = line.strip()
|
||||
if s.startswith("|"):
|
||||
s = s[1:]
|
||||
if s.endswith("|") and not s.endswith("\\|"):
|
||||
s = s[:-1]
|
||||
return [p.replace("\\|", "|").strip() for p in re.split(r"(?<!\\)\|", s)]
|
||||
|
||||
|
||||
def is_sep(line: str) -> bool:
|
||||
return line.strip() != "" and "-" in line and set(line.strip()) <= set("|-: ")
|
||||
|
||||
|
||||
def iter_tables(lines: list[str]):
|
||||
i = 0
|
||||
while i < len(lines):
|
||||
if lines[i].startswith("|") and i + 1 < len(lines) and is_sep(lines[i + 1]):
|
||||
header = cells(lines[i])
|
||||
body, j = [], i + 2
|
||||
while j < len(lines) and lines[j].startswith("|"):
|
||||
body.append((j + 1, cells(lines[j])))
|
||||
j += 1
|
||||
yield i + 1, header, body
|
||||
i = j
|
||||
else:
|
||||
i += 1
|
||||
|
||||
|
||||
def table_by_header(lines: list[str], keyword: str) -> dict | None:
|
||||
"""按表头关键词找表,返回 {rows, start, end}(行号 1-based,含表头与分隔行)。"""
|
||||
for lineno, header, rows in iter_tables(lines):
|
||||
if keyword in "".join(header).replace(" ", ""):
|
||||
end = rows[-1][0] if rows else lineno + 1
|
||||
return {"rows": [r for _, r in rows], "start": lineno, "end": end}
|
||||
return None
|
||||
|
||||
|
||||
def pct(x: str) -> float | None:
|
||||
m = re.search(r"(\d+(?:\.\d+)?)\s*%", x)
|
||||
return float(m.group(1)) if m else None
|
||||
|
||||
|
||||
def count(x: str) -> float | None:
|
||||
m = re.search(r"(\d+(?:\.\d+)?)", x)
|
||||
return float(m.group(1)) if m else None
|
||||
|
||||
|
||||
def check(path: Path) -> Report:
|
||||
r = Report(path)
|
||||
text = path.read_text(encoding="utf-8")
|
||||
lines = text.split("\n")
|
||||
|
||||
# 1. 纯净性:单层纯 Markdown
|
||||
if text.startswith("---\n"):
|
||||
r.err("FM001", "文件以 YAML frontmatter 开头;元数据请放正文「报告信息」表")
|
||||
for pat, name in FORBIDDEN_MARKS:
|
||||
if re.search(pat, text):
|
||||
r.err("MK001", f"出现模板机制痕迹({name}),模板应是纯 Markdown 文档")
|
||||
|
||||
# 2. 代码围栏
|
||||
fences = [i for i, ln in enumerate(lines, 1) if ln.startswith("```")]
|
||||
if len(fences) % 2:
|
||||
r.err("MD001", f"代码围栏为奇数({len(fences)}),存在未闭合代码块")
|
||||
|
||||
# 3. 表格列数与表头
|
||||
for lineno, header, rows in iter_tables(lines):
|
||||
r.n_tables += 1
|
||||
n = len(header)
|
||||
for rl, row in rows:
|
||||
if len(row) != n:
|
||||
r.err("TB001", f"第 {rl} 行表格列数 {len(row)} ≠ 表头 {n} 列")
|
||||
if any("**" in c for c in header):
|
||||
r.err("TB002", f"第 {lineno} 行表头含加粗标记 **")
|
||||
|
||||
# 4. 标题层级与章节编号
|
||||
prev, seen = 0, []
|
||||
for ln in lines:
|
||||
m = re.match(r"^(#{1,6})\s+(.*)$", ln)
|
||||
if not m:
|
||||
continue
|
||||
lvl = len(m.group(1))
|
||||
if prev and lvl > prev + 1:
|
||||
r.err("HD001", f"标题层级跳级({prev} → {lvl}):{m.group(2)[:40]}")
|
||||
prev = lvl
|
||||
m2 = re.match(r"^(\d+)\.", m.group(2))
|
||||
if lvl == 2 and m2:
|
||||
seen.append(m2.group(1))
|
||||
if seen and seen != SECTION_NUMBERS:
|
||||
r.err("HD002", f"## 章节编号应为 {SECTION_NUMBERS},实际 {seen}")
|
||||
|
||||
# 5. 报告信息表
|
||||
info = table_by_header(lines, "报告信息")
|
||||
if not info:
|
||||
r.err("INFO001", "缺少「报告信息」表")
|
||||
else:
|
||||
keys = {row[0] for row in info["rows"] if row}
|
||||
missing = REQUIRED_INFO_ROWS - keys
|
||||
if missing:
|
||||
r.err("INFO001", f"报告信息表缺少:{', '.join(sorted(missing))}")
|
||||
empty = [row[0] for row in info["rows"] if row and len(row) > 1 and not row[1].strip()]
|
||||
if empty:
|
||||
r.err("INFO002", f"报告信息表以下项为空:{', '.join(empty)}")
|
||||
|
||||
# 6. 图片可解析:http(s) 或存在的本地文件
|
||||
for m in re.finditer(r"!\[[^\]]*\]\(([^)]+)\)", text):
|
||||
src = m.group(1).strip()
|
||||
r.n_figs += 1
|
||||
if src.startswith(("http://", "https://")):
|
||||
continue
|
||||
if not (path.parent / src).exists():
|
||||
r.err("IMG001", f"图片不存在:{src}")
|
||||
|
||||
# 7. 数值自洽(全部从正文推导)
|
||||
for tag, kw in (("NM001", "失准类型"), ("NM002", "风险类型")):
|
||||
tb = table_by_header(lines, kw)
|
||||
if not tb:
|
||||
continue
|
||||
rows = tb["rows"]
|
||||
tops = [(c[0], count(c[3])) for c in rows if len(c) > 3 and c[0].startswith("TOP")]
|
||||
totals = [count(c[3]) for c in rows if len(c) > 3 and c[0] in ("合计", "总计", "—")]
|
||||
if tops and totals and all(c is not None for _, c in tops):
|
||||
if sum(c for _, c in tops) != totals[0]:
|
||||
r.err(tag, f"{kw}各维度之和 {sum(c for _, c in tops)} ≠ 合计 {totals[0]}")
|
||||
base = totals[0] if totals else None
|
||||
for c in rows:
|
||||
if len(c) < 4:
|
||||
continue
|
||||
share, cnt = pct(c[2]), count(c[3])
|
||||
if share and cnt and base and c[0].startswith("TOP") and abs(cnt / base * 100 - share) > 0.15:
|
||||
r.err("NM003", f"{kw}「{c[1]}」占比 {share}% ≠ {cnt:.0f}/{base:.0f} = {cnt / base * 100:.1f}%")
|
||||
# 小节标题里的张数与总览表一致
|
||||
for no, cnt in tops:
|
||||
sec = "2" if kw == "失准类型" else "3"
|
||||
m = re.search(r"###\s*%s\.\d+\s*%s[^(]*((\d+)\s*张" % (sec, re.escape(no)), text)
|
||||
if m and cnt is not None and int(m.group(1)) != cnt:
|
||||
r.err(tag, f"{no} 小节标题写 {m.group(1)} 张,总览表写 {cnt:.0f} 张")
|
||||
|
||||
# NM004:§6 明细表的结论分类计数 = 正文数字
|
||||
pr = table_by_header(lines, "原因分类")
|
||||
if pr:
|
||||
d4 = sum(1 for c in pr["rows"] if len(c) > 4 and "依规正确" in c[4])
|
||||
miss = sum(1 for c in pr["rows"] if len(c) > 4 and "失准" in c[4])
|
||||
m = re.search(r"((\d+)\s*/\s*(\d+)\s*笔)", text)
|
||||
m2 = re.search(r"仅有\s*\*{0,2}(\d+)\s*笔", text)
|
||||
if m and int(m.group(1)) != d4:
|
||||
r.err("NM004", f"正文称依规正确 {m.group(1)} 笔,明细表实际 {d4} 行")
|
||||
if m and int(m.group(2)) != len(pr["rows"]):
|
||||
r.err("NM004", f"正文称合计 {m.group(2)} 笔,明细表实际 {len(pr['rows'])} 行")
|
||||
if m2 and int(m2.group(1)) != miss:
|
||||
r.err("NM004", f"正文称 AI 失准 {m2.group(1)} 笔,明细表实际 {miss} 行")
|
||||
|
||||
# NM005:公式算术自洽,且代入值能在正文别处找到
|
||||
formula_lines = [l for l in lines if l.strip().startswith("$$")]
|
||||
outside = "\n".join(l for l in lines if not l.strip().startswith("$$"))
|
||||
for ln in formula_lines:
|
||||
for frac in re.finditer(r"\\frac\{(\d+)\}\{(\d+)\}\s*=\s*([\d.]+)\\%", ln):
|
||||
a, b, p = int(frac.group(1)), int(frac.group(2)), float(frac.group(3))
|
||||
if b and abs(a / b * 100 - p) > 0.05:
|
||||
r.err("NM005", f"公式 {a}/{b} = {p}% 算术不成立(实为 {a / b * 100:.2f}%)")
|
||||
for tok in re.findall(r"\d+(?:\.\d+)?", ln):
|
||||
if tok not in outside:
|
||||
r.err("NM005", f"公式中的数值 {tok} 在正文别处找不到,可能与数据脱节")
|
||||
|
||||
return r
|
||||
|
||||
|
||||
def default_paths() -> list[Path]:
|
||||
"""默认校验根目录全部 .md(README.md 除外)。"""
|
||||
return sorted(p for p in Path(".").glob("*.md") if p.name != "README.md")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
paths = [Path(a) for a in sys.argv[1:]] or default_paths()
|
||||
failed = False
|
||||
for p in paths:
|
||||
rep = check(p)
|
||||
print(f"[{'PASS' if rep.ok() else 'FAIL'}] {p} (表格 {rep.n_tables} 个, 图片 {rep.n_figs} 张)")
|
||||
for lv, code, msg in rep.issues:
|
||||
print(f" {lv} {code}: {msg}")
|
||||
failed |= not rep.ok()
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,9 +1,9 @@
|
||||
---
|
||||
name: seal-use
|
||||
description: "v0.11.0: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
|
||||
description: "v0.11.1: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
|
||||
metadata:
|
||||
version: 0.11.0
|
||||
short-description: Seal tenant and Hose approval automation (v0.11.0)
|
||||
version: 0.11.1
|
||||
short-description: Seal tenant and Hose approval automation (v0.11.1)
|
||||
---
|
||||
|
||||
# Seal Use
|
||||
@@ -98,6 +98,7 @@ Hose 专属命令应从命令名或选项中明确可见:`auth hose-*`、`appr
|
||||
| 客诉、截图/通知、预期业务行为,并要求诊断或修改规则 | `references/customer-feedback-rule-remediation.md` | 只有该流程明确要求附件追踪或测试发布时,才追加对应 reference |
|
||||
| 附件、发票、收据、OCR 或界面高亮结论争议 | `references/approval-attachment-trace.md` | 先完成追踪和归因后,才读 `approval-bad-cases.md` 做案例对照 |
|
||||
| 已完成当前追踪后的相似坏案例对照 | `references/approval-bad-cases.md` | 不能作为首次诊断入口 |
|
||||
| 月度审核准确率报告、月报生成、accuracy report | 本文「月度审核准确率报告」一节 | 需要结构校验或 PDF 渲染时,再读 `report-templates/README.md` |
|
||||
|
||||
冲突时遵循三条优先级:材料获取先于来源判断;来源判断先于 Hose 具体探测;审批事实追踪先于坏案例类比。跨阶段请求也要按阶段顺序读取,不能用后置 reference 替代前置 reference。
|
||||
|
||||
@@ -110,3 +111,35 @@ seal-use approval-runs diagnose --sn <单号> --corp <corpId>
|
||||
```
|
||||
|
||||
一次返回单据摘要、AI 判定结果、引用规则、判定当时的规则版本快照(含被引规则的快照内容)与 Langfuse trace 指针;需要完整 result 原文加 `--full`,需要按 recordId 定位则直接传 `<recordId>`。只有诊断结果不够、需要更细颗粒时,再拆用 `pick` / `get --summary` / `cited-rules` / `rules version`。
|
||||
|
||||
## 月度审核准确率报告
|
||||
|
||||
月度报告一次调用生成,不要手搓 Markdown 表格或串行取数:
|
||||
|
||||
```bash
|
||||
seal-use report monthly --month <YYYY-MM> --corp <corpId>
|
||||
```
|
||||
|
||||
按模板结构(`report-templates/monthly.md`)自动从效能/风险/审批运行接口取数填充,返回填充后的 Markdown、各章节数据完备度(`sections`)与数据缺口标注(`notes`)。要点:
|
||||
|
||||
- **模板是可变的皮**:章节增删改名只要关键词仍命中,取数需求自动跟着走(`src/domains/seal/reports/describe.ts`)。改模板通常不用改代码。
|
||||
- **无上游口径不编造**:人工审核准确率、失准原因分类等取不到的指标,保留模板示例值并在表后追加 `> ⚠️ 数据说明` 标注来源缺口——如实告知而非填假数字。
|
||||
- 结果里的 `next` 给出下游 `validate` / `render` 指引(校验与 HTML/PNG/PDF 渲染用 `report-templates/validate.py`、`render.py`,不进包)。
|
||||
- 只读能力 `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/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 注册表与读写白名单。
|
||||
@@ -0,0 +1,78 @@
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import type { createSealClient } from "../../core/http/factory.js";
|
||||
import { runCapability } from "../helpers.js";
|
||||
import { numberOption, stringOption } from "../parser.js";
|
||||
import { outputOptions, printJson } from "../printer.js";
|
||||
import { loadReviews, reviewFilePath, writeReview } from "../../domains/seal/reports/review-store.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
|
||||
/** `seal-use report monthly` — 月度 AI 审核准确率报告(Markdown 填充)。 */
|
||||
export async function handleReportCommand(
|
||||
action: string | undefined,
|
||||
client: Awaited<ReturnType<typeof createSealClient>>,
|
||||
corp: CorpConfig,
|
||||
args: ParsedArgs
|
||||
) {
|
||||
if (action === "monthly" || action === "month") {
|
||||
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>]");
|
||||
}
|
||||
await runCapability(
|
||||
"sealReportMonthlyGet",
|
||||
client,
|
||||
corp,
|
||||
{
|
||||
month,
|
||||
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)
|
||||
},
|
||||
outputOptions(args.options)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
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>]");
|
||||
}
|
||||
|
||||
if (sub === "list") {
|
||||
const reviews = loadReviews(corp.id, month);
|
||||
printJson({
|
||||
corpId: corp.id,
|
||||
month,
|
||||
file: reviewFilePath(corp.id, month),
|
||||
count: reviews.size,
|
||||
reviews: [...reviews.values()]
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (sub === "set") {
|
||||
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 record = writeReview(corp.id, {
|
||||
sn,
|
||||
month,
|
||||
verdict,
|
||||
note: stringOption(args.options.note),
|
||||
reviewedBy: stringOption(args.options["reviewed-by"]) ?? stringOption(args.options.reviewedBy)
|
||||
});
|
||||
printJson({ corpId: corp.id, file: reviewFilePath(corp.id, month), record });
|
||||
return;
|
||||
}
|
||||
|
||||
throw new Error(`Unknown report review subcommand: ${sub ?? ""}. Use 'set' or 'list'.`);
|
||||
}
|
||||
|
||||
throw new Error(`Unknown report command: ${action ?? ""}. Run 'seal-use report --help' for available commands.`);
|
||||
}
|
||||
@@ -600,6 +600,48 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
area: "report",
|
||||
title: "Monthly audit accuracy reports",
|
||||
description: "Generate the monthly AI audit accuracy report (Markdown) from a mutable template plus live tenant data.",
|
||||
commands: [
|
||||
{
|
||||
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> [--template <file>] [--report-id <RPT-...>] [--max-runs <n>] [--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 report-templates/monthly.md" },
|
||||
{ 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)" }
|
||||
],
|
||||
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."
|
||||
},
|
||||
{
|
||||
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>]"],
|
||||
options: [
|
||||
{ flag: "--month <YYYY-MM>", description: "Statistics month, YYYY-MM (required)" },
|
||||
{ flag: "--sn <SN>", description: "Document SN to adjudicate (required)" },
|
||||
{ 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/reviews/). Typically adjudicate diverged blocks (AI != human); report monthly joins these to compute human accuracy. No network: writes only the local store."
|
||||
},
|
||||
{
|
||||
name: "review list",
|
||||
summary: "List human adjudications recorded for a tenant+month",
|
||||
usage: ["seal-use report review list --month <YYYY-MM> [--corp <corpId>]"],
|
||||
options: [
|
||||
{ flag: "--month <YYYY-MM>", description: "Statistics month, YYYY-MM (required)" }
|
||||
],
|
||||
description: "Reads the local JSONL store and returns all adjudications keyed by SN."
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
area: "simulation",
|
||||
title: "Simulation testing engine",
|
||||
@@ -1276,6 +1318,12 @@ export function renderHelp(target: string[] = []): string {
|
||||
const matchedCommand = findCommandInArea(areaEntry, actionPath, rest);
|
||||
|
||||
if (!matchedCommand) {
|
||||
// 前缀命令(如 `report review` 覆盖 `review set`/`review list`):列出该组子命令而非报错
|
||||
const groupPrefix = `${actionPath} `;
|
||||
const subcommands = areaEntry.commands.filter((cmd) => cmd.name?.startsWith(groupPrefix));
|
||||
if (subcommands.length > 0) {
|
||||
return renderAreaHelp({ ...areaEntry, commands: subcommands });
|
||||
}
|
||||
throw usageError(`Unknown ${areaEntry.area} command: ${rest.join(" ")}. Run 'seal-use ${areaEntry.area} --help' for available commands.`);
|
||||
}
|
||||
|
||||
|
||||
@@ -54,12 +54,16 @@ export const VALUE_FLAGS = new Set([
|
||||
"json", "key-id", "keyId", "keyword", "level", "limit",
|
||||
"lines", "link", "linter", "manual-status", "manualApprovalStatus", "manualStatus",
|
||||
"max-chars", "maxChars", "maxResults", "min-score", "minScore", "mode",
|
||||
"max-runs",
|
||||
"month",
|
||||
"n", "name", "note", "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",
|
||||
"prod", "prod-corp", "prodCorp", "purpose", "q", "query",
|
||||
"record-id", "record-ids", "recordId", "recordIds", "reject-node", "rejectNode",
|
||||
"reviewed-by", "reviewedBy",
|
||||
"report-id",
|
||||
"repo", "request-ids", "requestIds", "result-url", "resultUrl", "reuse-window",
|
||||
"reuseWindow", "rule", "rule-id", "ruleId", "ruleVersion", "runtime-id",
|
||||
"runtimeId", "samples", "scenarios", "schema-config", "schemaConfig", "scope",
|
||||
@@ -70,9 +74,12 @@ export const VALUE_FLAGS = new Set([
|
||||
"staffName", "staffPhone", "start", "start-date", "start-time", "startDate",
|
||||
"startTime", "state", "status", "strictness", "tag", "tag-id",
|
||||
"tagId", "tags", "target", "target-corp", "targetCorp", "task-mode",
|
||||
"template",
|
||||
"taskMode", "template-id", "templateId", "test-corp", "thinking-depth", "thinkingDepth",
|
||||
"timeout", "timezone", "title", "to", "token", "tokenId",
|
||||
"template",
|
||||
"type", "until", "url", "userId", "version-name", "versionName",
|
||||
"verdict",
|
||||
"webhook", "workflow-type-id", "workflowTypeId"
|
||||
]);
|
||||
|
||||
@@ -100,6 +107,8 @@ export const KNOWN_FLAGS = new Set([
|
||||
"key-id", "keyId", "keyword", "level", "limit", "lines",
|
||||
"link", "linter", "local", "manual-status", "manualApprovalStatus", "manualStatus",
|
||||
"max-chars", "maxChars", "maxResults", "min-score", "minScore", "mode",
|
||||
"max-runs",
|
||||
"month",
|
||||
"n", "name", "no-attachments", "no-flow", "no-wait", "noWait",
|
||||
"note", "o", "offset", "out", "out-dir", "outDir",
|
||||
"outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file", "outputFile", "overwrite",
|
||||
@@ -108,7 +117,9 @@ export const KNOWN_FLAGS = new Set([
|
||||
"prod", "prod-corp", "prodCorp", "publish", "purpose", "q",
|
||||
"query", "quiet", "r", "recode", "record-id", "record-ids",
|
||||
"recordId", "recordIds", "refresh", "reject-node", "rejectNode", "repo",
|
||||
"report-id",
|
||||
"request-ids", "requestIds", "result-url", "resultUrl", "reuse-window", "reuseWindow",
|
||||
"reviewed-by", "reviewedBy",
|
||||
"reveal", "rotate-secret", "rotateSecret", "rule", "rule-id", "ruleId",
|
||||
"ruleVersion", "runtime-id", "runtimeId", "samples", "save", "scenarios",
|
||||
"schema-config", "schemaConfig", "scope", "sealUrl", "search", "secret",
|
||||
@@ -120,10 +131,12 @@ export const KNOWN_FLAGS = new Set([
|
||||
"staffId", "staffName", "staffPhone", "start", "start-date", "start-time",
|
||||
"startDate", "startTime", "state", "status", "strict", "strictness",
|
||||
"summary", "tag", "tag-id", "tagId", "tags", "target",
|
||||
"template",
|
||||
"target-corp", "targetCorp", "task-mode", "taskMode", "template-id", "templateId",
|
||||
"test-corp", "thinking-depth", "thinkingDepth", "timeout", "timezone", "title",
|
||||
"to", "to-downloads", "toDownloads", "token", "tokenId", "type",
|
||||
"until", "url", "userId", "v", "version", "version-name",
|
||||
"verdict",
|
||||
"versionName", "wait", "webhook", "with-flow", "workflow-type-id", "workflowTypeId",
|
||||
"workspace", "yes"
|
||||
]);
|
||||
|
||||
@@ -78,6 +78,7 @@ const READ_ONLY_COMMANDS: Record<string, string[]> = {
|
||||
// `analyze` is deliberately absent: it POSTs and starts an analysis server-side, so it is a
|
||||
// mutation despite reading like a query. See SEAL_MUTATING_CAPABILITIES.
|
||||
analytics: ["insight", "risks", "performance", "export"],
|
||||
report: ["monthly", "review list"],
|
||||
source: ["config"],
|
||||
skill: ["dump", "status"],
|
||||
doctor: ["", "guide", "paths", "tenant", "auth"],
|
||||
|
||||
@@ -53,6 +53,7 @@ export const KNOWN_AREAS = new Set([
|
||||
"rules",
|
||||
"approval-runs",
|
||||
"analytics",
|
||||
"report",
|
||||
"simulation",
|
||||
"deploy",
|
||||
"preference",
|
||||
@@ -386,6 +387,11 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (area === "report") {
|
||||
await (await import("./commands/report.js")).handleReportCommand(action, client, corp, args);
|
||||
return;
|
||||
}
|
||||
|
||||
if (area === "simulation") {
|
||||
await (await import("./commands/simulation.js")).handleSimulationCommand(action, maybeName, client, corp, args);
|
||||
return;
|
||||
|
||||
@@ -8,6 +8,7 @@ import { approvalRunsCapabilities } from "./approval-runs.js";
|
||||
import { simulationCapabilities } from "./simulation.js";
|
||||
import { deployCapabilities } from "./deploy.js";
|
||||
import { preferenceCapabilities } from "./preference.js";
|
||||
import { reportCapabilities } from "./reports.js";
|
||||
|
||||
export * from "./helpers.js";
|
||||
export * from "./validate.js";
|
||||
@@ -22,7 +23,8 @@ export const sealCapabilities = [
|
||||
...approvalRunsCapabilities,
|
||||
...simulationCapabilities,
|
||||
...deployCapabilities,
|
||||
...preferenceCapabilities
|
||||
...preferenceCapabilities,
|
||||
...reportCapabilities
|
||||
];
|
||||
|
||||
export type SealCapability = (typeof sealCapabilities)[number];
|
||||
@@ -99,6 +101,7 @@ export const SEAL_READ_ONLY_CAPABILITIES: ReadonlySet<string> = new Set([
|
||||
"sealPermissionsConfigsList",
|
||||
"sealPreferenceGet",
|
||||
"sealPreferenceThinkingDepthPoliciesList",
|
||||
"sealReportMonthlyGet",
|
||||
"sealSessionGet",
|
||||
"sealSimulationBatchGet",
|
||||
"sealSimulationBatchRecordsGet",
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import { buildMonthlyReport } from "../reports/monthly.js";
|
||||
import type { CapabilityContext } from "./helpers.js";
|
||||
|
||||
export const reportCapabilities = [
|
||||
{
|
||||
name: "sealReportMonthlyGet",
|
||||
description:
|
||||
"生成月度 AI 审核准确率报告(Markdown)。按模板结构从效能/风险/审批运行接口取数填充,返回填充后的内容与各章节数据完备度;无法从上游取得的口径(人工准确率、失准原因分类)如实标注而非编造",
|
||||
parameters: z.object({
|
||||
month: z
|
||||
.string()
|
||||
.regex(/^\d{4}-\d{2}$/)
|
||||
.describe("统计月份,YYYY-MM"),
|
||||
templatePath: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("自定义模板 Markdown 路径;缺省用 report-templates/monthly.md"),
|
||||
reportId: z.string().optional().describe("自定义报告编号(RPT-YYYYMM-XXXXXX)"),
|
||||
maxRuns: z
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.max(500)
|
||||
.optional()
|
||||
.describe("拉取审批运行明细分块的上限,默认 500")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: { month: string; templatePath?: string; reportId?: string; maxRuns?: number },
|
||||
context: CapabilityContext
|
||||
) =>
|
||||
buildMonthlyReport(client, {
|
||||
month: params.month,
|
||||
corp: { id: context.corp.id, name: context.corp.name },
|
||||
templatePath: params.templatePath,
|
||||
reportId: params.reportId,
|
||||
maxRuns: params.maxRuns
|
||||
})
|
||||
}
|
||||
];
|
||||
@@ -0,0 +1,311 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import * as api from "../api.js";
|
||||
import { formatBeijingIso } from "../../../core/config/timestamps.js";
|
||||
import type { ApprovalRun } from "../types.js";
|
||||
import type { ReportDemand } from "./describe.js";
|
||||
import { loadReviews, type ReviewRecord } from "./review-store.js";
|
||||
|
||||
/** 单据在决策空间里的极性:同意为正向、驳回/终止为反向,用于比对 AI 与人工是否同向。 */
|
||||
type Polarity = "pass" | "reject" | "unknown";
|
||||
|
||||
function polarityOf(value: string | undefined): Polarity {
|
||||
if (!value) return "unknown";
|
||||
const text = value.trim();
|
||||
if (/同意|通过|approve|pass/i.test(text)) return "pass";
|
||||
if (/驳回|拒绝|终止|退回|reject|deny/i.test(text)) return "reject";
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
export type ReportBlock = {
|
||||
sn: string;
|
||||
template: string;
|
||||
aiDecision: string | undefined;
|
||||
humanResult: string | undefined;
|
||||
agreement: "agreed" | "diverged" | "unknown";
|
||||
aiSummary: string | undefined;
|
||||
humanComment: string | undefined;
|
||||
/** 本地人工裁决结论(若该 SN 已 review),来自 review-store */
|
||||
verdict?: ReviewRecord["verdict"];
|
||||
};
|
||||
|
||||
export type ReportTemplateGroup = {
|
||||
template: string;
|
||||
total: number;
|
||||
agreed: number;
|
||||
diverged: number;
|
||||
};
|
||||
|
||||
export type ReportData = {
|
||||
/** 报告信息表要用的上下文 */
|
||||
period: { start: string; end: string; month: string };
|
||||
corp: { id: string; name: string };
|
||||
/** 需求 → 是否已按需取数(渲染器据此判断该章节数据完备度) */
|
||||
fetched: Record<ReportDemand, boolean>;
|
||||
performance?: {
|
||||
approvalCount?: number;
|
||||
accuracy?: number;
|
||||
accuracyTrend?: number;
|
||||
automationRate?: number;
|
||||
riskCount?: number;
|
||||
/** 平均耗时(秒);上游给秒就传秒 */
|
||||
avgDurationSeconds?: number;
|
||||
sankey: { nodes: Array<{ id: string }>; links: Array<{ source: string; target: string; value: number }> };
|
||||
};
|
||||
riskStats?: {
|
||||
tags: Array<{ id?: string; name?: string; count?: number }>;
|
||||
};
|
||||
blocks: ReportBlock[];
|
||||
templateGroups: ReportTemplateGroup[];
|
||||
/** 该租户该月的人工裁决(SN → 记录),由 review-store 载入,用于回填人工准确率 */
|
||||
reviews: Map<string, ReviewRecord>;
|
||||
/** 人工审核准确率(%):仅当本地裁决覆盖样本时有值 */
|
||||
humanAccuracy?: number;
|
||||
/** 章节数据完备性标记,渲染时逐节如实写入 */
|
||||
notes: {
|
||||
/** 人工准确率是否可得(有本地裁决) */
|
||||
humanAccuracyAvailable: boolean;
|
||||
failureRateAvailable: boolean;
|
||||
mismatchCategoriesAvailable: boolean;
|
||||
/** 裁决样本数 / 分歧样本数,供报告如实说明覆盖度 */
|
||||
reviewedCount?: number;
|
||||
divergedCount?: number;
|
||||
};
|
||||
};
|
||||
|
||||
export type CollectOptions = {
|
||||
month: string; // YYYY-MM
|
||||
corp: { id: string; name: string };
|
||||
/** 用于拉明细分块的上限,防御性封顶 */
|
||||
maxRuns?: number;
|
||||
/** 是否载入本地人工裁决(默认载入);关掉则 humanAccuracy 恒为不可得 */
|
||||
loadReviews?: boolean;
|
||||
};
|
||||
|
||||
function monthRange(month: string): { startDate: string; endDate: 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;
|
||||
return { startDate: String(start), endDate: String(end) };
|
||||
}
|
||||
|
||||
/** 拉取报告所需数据。只取 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 fetched: Record<ReportDemand, boolean> = {
|
||||
performance: false,
|
||||
riskStats: false,
|
||||
riskDetails: false,
|
||||
blocks: false,
|
||||
templateGroups: false
|
||||
};
|
||||
|
||||
const data: ReportData = {
|
||||
period: {
|
||||
start: formatBeijingIso(Number(range.startDate)),
|
||||
end: formatBeijingIso(Number(range.endDate)),
|
||||
month: options.month
|
||||
},
|
||||
corp: options.corp,
|
||||
fetched,
|
||||
blocks: [],
|
||||
templateGroups: [],
|
||||
reviews: options.loadReviews === false
|
||||
? new Map()
|
||||
: loadReviews(options.corp.id, options.month),
|
||||
notes: {
|
||||
humanAccuracyAvailable: false,
|
||||
failureRateAvailable: false,
|
||||
mismatchCategoriesAvailable: false
|
||||
}
|
||||
};
|
||||
|
||||
// 1. 效能指标(§1 / §4)
|
||||
if (demands.has("performance")) {
|
||||
try {
|
||||
const perf = await api.getInsightPerformance(client, {
|
||||
startDate: range.startDate,
|
||||
endDate: range.endDate
|
||||
});
|
||||
const metrics = (perf.metrics ?? {}) as Record<string, { value?: number; trend?: number } | undefined>;
|
||||
data.performance = {
|
||||
approvalCount: metrics.approvalCount?.value,
|
||||
accuracy: metrics.accuracy?.value,
|
||||
accuracyTrend: metrics.accuracy?.trend,
|
||||
automationRate: metrics.automationRate?.value,
|
||||
riskCount: metrics.riskCount?.value,
|
||||
avgDurationSeconds: metrics.avgDuration?.value,
|
||||
sankey: perf.sankeyData ?? { nodes: [], links: [] }
|
||||
};
|
||||
fetched.performance = true;
|
||||
} catch {
|
||||
// 指标接口不可达:章节保持模板原文并在填充时标注数据未取到
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 风险标签统计(§3 / §4 风险拦截)
|
||||
if (demands.has("riskStats") || demands.has("riskDetails")) {
|
||||
try {
|
||||
const stats = await api.getInsightStats(client, {
|
||||
startDate: range.startDate,
|
||||
endDate: range.endDate,
|
||||
limit: 50
|
||||
});
|
||||
const rawList = ((stats as { tags?: unknown }).tags ?? (stats as { list?: unknown }).list ?? []) as Array<Record<string, unknown>>;
|
||||
data.riskStats = {
|
||||
tags: rawList.slice(0, 20).map((tag) => ({
|
||||
id: typeof tag.id === "string" ? tag.id : undefined,
|
||||
name: typeof tag.name === "string" ? tag.name : typeof tag.title === "string" ? tag.title : undefined,
|
||||
count: typeof tag.count === "number" ? tag.count : typeof tag.value === "number" ? tag.value : undefined
|
||||
}))
|
||||
};
|
||||
fetched.riskStats = true;
|
||||
fetched.riskDetails = data.riskStats.tags.length > 0;
|
||||
} catch {
|
||||
// 风险统计不可达
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 决策分块(§2 / §5 / §6)与分模板统计(§7.1)
|
||||
if (demands.has("blocks") || demands.has("templateGroups")) {
|
||||
const runs: ApprovalRun[] = [];
|
||||
let offset = 0;
|
||||
try {
|
||||
while (runs.length < maxRuns) {
|
||||
const page = await api.listApprovalRuns(client, {
|
||||
offset,
|
||||
limit: 100,
|
||||
startDate: range.startDate,
|
||||
endDate: range.endDate
|
||||
});
|
||||
const records = page.records ?? [];
|
||||
if (!records.length) break;
|
||||
runs.push(...records);
|
||||
offset += records.length;
|
||||
if (records.length < 100) break;
|
||||
}
|
||||
|
||||
const blocks: ReportBlock[] = runs.map((record) => {
|
||||
const summary = summarizeLocal(record);
|
||||
const aiPolarity = polarityOf(summary.aiDecision);
|
||||
const humanPolarity = polarityOf(summary.humanResult);
|
||||
const agreement =
|
||||
aiPolarity === "unknown" || humanPolarity === "unknown"
|
||||
? "unknown"
|
||||
: aiPolarity === humanPolarity
|
||||
? "agreed"
|
||||
: "diverged";
|
||||
return {
|
||||
sn: summary.sn ?? summary.id,
|
||||
template: summary.template,
|
||||
aiDecision: summary.aiDecision,
|
||||
humanResult: summary.humanResult,
|
||||
agreement,
|
||||
aiSummary: summary.aiSummary,
|
||||
humanComment: summary.humanComment
|
||||
};
|
||||
});
|
||||
data.blocks = blocks;
|
||||
fetched.blocks = true;
|
||||
|
||||
if (demands.has("templateGroups")) {
|
||||
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 };
|
||||
group.total += 1;
|
||||
if (block.agreement === "agreed") group.agreed += 1;
|
||||
if (block.agreement === "diverged") group.diverged += 1;
|
||||
byTemplate.set(key, group);
|
||||
}
|
||||
data.templateGroups = [...byTemplate.values()].sort((a, b) => b.total - a.total);
|
||||
fetched.templateGroups = true;
|
||||
}
|
||||
} catch {
|
||||
// 分块拉取失败:章节保持模板原文
|
||||
}
|
||||
}
|
||||
|
||||
data.notes.failureRateAvailable = data.performance !== undefined;
|
||||
data.notes.mismatchCategoriesAvailable = false; // 失准原因分类无上游字段,需人工归类
|
||||
|
||||
// 3. 人工裁决回填:把本地 review 挂到 blocks,并据此算人工准确率
|
||||
if (data.reviews.size > 0) {
|
||||
let reviewed = 0;
|
||||
let diverged = 0;
|
||||
let aiRight = 0;
|
||||
let humanRight = 0;
|
||||
for (const block of data.blocks) {
|
||||
const review = data.reviews.get(block.sn);
|
||||
if (review) {
|
||||
block.verdict = review.verdict;
|
||||
reviewed += 1;
|
||||
if (block.agreement === "diverged") diverged += 1;
|
||||
// 人工正确:human_correct 或 both_correct;AI 正确:ai_correct 或 both_correct
|
||||
if (review.verdict === "human_correct" || review.verdict === "both_correct") humanRight += 1;
|
||||
if (review.verdict === "ai_correct" || review.verdict === "both_correct") aiRight += 1;
|
||||
}
|
||||
}
|
||||
if (reviewed > 0) {
|
||||
data.notes.reviewedCount = reviewed;
|
||||
data.notes.divergedCount = diverged;
|
||||
// 人工准确率 = 被裁决为"人工对"的单数 / 被裁决总单数
|
||||
data.humanAccuracy = Number(((humanRight / reviewed) * 100).toFixed(2));
|
||||
data.notes.humanAccuracyAvailable = true;
|
||||
// AI 准确率同样可从裁决侧复核(供对照),但 §1.2 主准确率仍用上游 performance
|
||||
void aiRight;
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
/** 局部摘要:避免依赖 capabilities/helpers 的深耦合,只取报告需要的字段。 */
|
||||
function summarizeLocal(record: ApprovalRun): {
|
||||
id: string;
|
||||
sn?: string;
|
||||
template: string;
|
||||
aiDecision?: string;
|
||||
humanResult?: string;
|
||||
aiSummary?: string;
|
||||
humanComment?: string;
|
||||
} {
|
||||
const result = (record.result ?? {}) as Record<string, unknown>;
|
||||
const document = (record.document ?? {}) as Record<string, unknown>;
|
||||
|
||||
const aiDecision =
|
||||
firstString(result.decision) ??
|
||||
firstString((result.manualApproval as Record<string, unknown> | undefined)?.decision) ??
|
||||
firstString((result.manualApproval as Record<string, unknown> | undefined)?.result);
|
||||
|
||||
const humanResult =
|
||||
firstString(result.humanResult) ??
|
||||
firstString((result.manualApproval as Record<string, unknown> | undefined)?.humanResult) ??
|
||||
firstString(record.pipelineData && (record.pipelineData as Record<string, unknown>).humanResult);
|
||||
|
||||
const template =
|
||||
firstString(document.templateName) ??
|
||||
firstString(document.title) ??
|
||||
firstString(document.name) ??
|
||||
"";
|
||||
|
||||
return {
|
||||
id: record.id,
|
||||
sn: record.sourceDocumentSN,
|
||||
template,
|
||||
aiDecision,
|
||||
humanResult,
|
||||
aiSummary: firstString(result.summary),
|
||||
humanComment: firstString((result.manualApproval as Record<string, unknown> | undefined)?.comment) ??
|
||||
firstString(result.humanComment)
|
||||
};
|
||||
}
|
||||
|
||||
function firstString(value: unknown): string | undefined {
|
||||
return typeof value === "string" && value.trim() ? value.trim() : undefined;
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
/**
|
||||
* 模板 → 数据需求 分析器。
|
||||
*
|
||||
* 报告模板是可变的皮:章节标题允许增删、改名、重排。
|
||||
* 这里不硬编码任何章节,而是扫描模板的 `##`/`###` 标题,用关键词规则反推每个章节
|
||||
* 需要哪些数据(demand)。渲染器逐节按 demand 取数——模板改了,只需调整或新增规则,
|
||||
* 编排器(collect/render)不用动。
|
||||
*/
|
||||
|
||||
export type ReportDemand =
|
||||
/** 审核效能指标(准确率、自动化率、平均耗时、审批量) */
|
||||
| "performance"
|
||||
/** 风险标签统计(§3 风险构成) */
|
||||
| "riskStats"
|
||||
/** 风险标签下的单据明细(§3 TOP 小节) */
|
||||
| "riskDetails"
|
||||
/** AI 与人工的决策分块(§2 失准、§5 一致性、§6 通过/驳回明细) */
|
||||
| "blocks"
|
||||
/** 分模板(单据模板)维度的分组统计(§7.1) */
|
||||
| "templateGroups";
|
||||
|
||||
export type SectionPlan = {
|
||||
/** 章节的 ## 标题原文 */
|
||||
heading: string;
|
||||
/** 是否为二级章节(## 为 true,### 为 false) */
|
||||
level: 2 | 3;
|
||||
/** 该章节声明的需求;为空表示保持模板原文(纯叙述章节) */
|
||||
demands: ReportDemand[];
|
||||
/** 章节序号(## 级别从 1 递增;### 归属最近的 ##) */
|
||||
chapter: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* 标题关键词 → 数据需求。规则即契约:命中一个关键词就声明一个需求,多命中取并集。
|
||||
* 顺序无关;`avoid` 关键词优先(防止"人工审核准确率"这类词把一致性章节误判成效能章节)。
|
||||
*/
|
||||
const TITLE_RULES: Array<{ pattern: RegExp; demand: ReportDemand; avoid?: RegExp }> = [
|
||||
{ pattern: /AI 失准|失准分析|误判|失准构成/, demand: "blocks" },
|
||||
{ pattern: /风险|潜在/, demand: "riskStats" },
|
||||
{ pattern: /TOP \d|构成总览|小节|明细/, demand: "riskDetails" },
|
||||
{ pattern: /准确率|时效|耗时|效能|稳定性|审核测试结果|样本/, demand: "performance", avoid: /一致性示例/ },
|
||||
{ pattern: /一致性|一致示例|通过 \/ 人工驳回|通过\/人工驳回|通过 \/ 人工驳回/, demand: "blocks" },
|
||||
{ pattern: /分模板|单据模板.*率/, demand: "templateGroups" },
|
||||
{ pattern: /风险拦截/, demand: "riskStats" }
|
||||
];
|
||||
|
||||
/** 汇总一个 `##` 章节内所有标题(含自身)命中的需求。 */
|
||||
function demandsFor(titles: string[]): ReportDemand[] {
|
||||
const demands = new Set<ReportDemand>();
|
||||
for (const title of titles) {
|
||||
for (const rule of TITLE_RULES) {
|
||||
if (rule.avoid && rule.avoid.test(title)) continue;
|
||||
if (rule.pattern.test(title)) demands.add(rule.demand);
|
||||
}
|
||||
}
|
||||
return [...demands];
|
||||
}
|
||||
|
||||
/**
|
||||
* 扫描模板文本,产出逐节执行计划。
|
||||
* 同时返回模板正文里出现过的 `data:` 元数据行(如 `数据来源`、`统计期间` 行)供填充使用。
|
||||
*/
|
||||
export function describeTemplate(template: string): SectionPlan[] {
|
||||
const lines = template.split("\n");
|
||||
const plans: SectionPlan[] = [];
|
||||
let chapter = 0;
|
||||
/** 当前 ## 章节内累积的标题(## 标题 + 其下 ### 标题),到下一个 ## 时结算 */
|
||||
let pendingTitles: string[] = [];
|
||||
let pendingHeading = "";
|
||||
let pendingLevel: 2 | 3 = 2;
|
||||
let pendingChapter = 0;
|
||||
|
||||
const flush = () => {
|
||||
if (!pendingHeading) return;
|
||||
plans.push({
|
||||
heading: pendingHeading,
|
||||
level: pendingLevel,
|
||||
demands: demandsFor(pendingTitles),
|
||||
chapter: pendingChapter
|
||||
});
|
||||
};
|
||||
|
||||
for (const line of lines) {
|
||||
const h2 = line.match(/^## (.+)$/);
|
||||
const h3 = line.match(/^### (.+)$/);
|
||||
if (h2) {
|
||||
flush();
|
||||
chapter += 1;
|
||||
pendingHeading = h2[1]!.trim();
|
||||
pendingLevel = 2;
|
||||
pendingChapter = chapter;
|
||||
pendingTitles = [pendingHeading];
|
||||
} else if (h3) {
|
||||
if (pendingHeading) pendingTitles.push(h3[1]!.trim());
|
||||
else {
|
||||
// `###` 出现在任何 `##` 之前:作为独立段落登记,序号并入后续章节
|
||||
pendingHeading = h3[1]!.trim();
|
||||
pendingLevel = 3;
|
||||
pendingChapter = chapter;
|
||||
pendingTitles = [pendingHeading];
|
||||
}
|
||||
}
|
||||
}
|
||||
flush();
|
||||
|
||||
return plans;
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { join, resolve } from "node:path";
|
||||
import { isCompiledBinary } from "../../../core/runtime.js";
|
||||
import { describeTemplate } from "./describe.js";
|
||||
import { collectReportData, type ReportData } from "./collect.js";
|
||||
import { renderMonthlyReport, type RenderOptions } from "./render.js";
|
||||
|
||||
export type MonthlyReportOptions = {
|
||||
month: string; // YYYY-MM
|
||||
corp: { id: string; name: string };
|
||||
/** 模板路径;缺省用仓内 report-templates/monthly.md */
|
||||
templatePath?: string;
|
||||
reportId?: string;
|
||||
maxRuns?: number;
|
||||
};
|
||||
|
||||
export type MonthlyReportResult = {
|
||||
month: string;
|
||||
corpId: string;
|
||||
reportId: string;
|
||||
templatePath: string;
|
||||
/** 模板各章节声明的数据需求与取数结果,供 agent 判断哪些章节可直接用、哪些需人工补 */
|
||||
sections: Array<{ heading: string; demands: string[]; fetched: string[] }>;
|
||||
notes: ReportData["notes"];
|
||||
/** 报告 Markdown 本体 */
|
||||
content: string;
|
||||
next: {
|
||||
validate: string;
|
||||
render: string;
|
||||
};
|
||||
};
|
||||
|
||||
function defaultTemplatePath(): string {
|
||||
if (isCompiledBinary()) {
|
||||
// 模板不进包;编译产物用 cwd(与 rules lint --file 的相对路径解析一致)
|
||||
return join(process.cwd(), "report-templates", "monthly.md");
|
||||
}
|
||||
// dev: src/domains/seal/reports → 仓库根
|
||||
return join(import.meta.dirname, "..", "..", "..", "..", "report-templates", "monthly.md");
|
||||
}
|
||||
|
||||
/** 一次调用产出填充好的月度报告 Markdown。模板皮与数据骨解耦:见 describe.ts。 */
|
||||
export async function buildMonthlyReport(
|
||||
client: KyInstance,
|
||||
options: MonthlyReportOptions
|
||||
): Promise<MonthlyReportResult> {
|
||||
const templatePath = options.templatePath
|
||||
? resolve(options.templatePath)
|
||||
: defaultTemplatePath();
|
||||
if (!existsSync(templatePath)) {
|
||||
throw new Error(
|
||||
`未找到报告模板: ${templatePath}\n` +
|
||||
`可用 --template <file> 指定路径,或在 report-templates/ 目录下运行。`
|
||||
);
|
||||
}
|
||||
const template = readFileSync(templatePath, "utf8");
|
||||
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
|
||||
});
|
||||
|
||||
const renderOptions: RenderOptions = {
|
||||
reportId: options.reportId,
|
||||
corpName: options.corp.name
|
||||
};
|
||||
const content = renderMonthlyReport(template, data, plans, renderOptions);
|
||||
|
||||
const reportId = options.reportId ?? `RPT-${options.month.replace("-", "")}-XXXXXX`;
|
||||
return {
|
||||
month: options.month,
|
||||
corpId: options.corp.id,
|
||||
reportId,
|
||||
templatePath,
|
||||
sections: plans.map((plan) => ({
|
||||
heading: plan.heading,
|
||||
demands: plan.demands,
|
||||
fetched: plan.demands.filter((demand) => data.fetched[demand])
|
||||
})),
|
||||
notes: data.notes,
|
||||
content,
|
||||
next: {
|
||||
validate: `python3 tools/validate.py <报告文件.md>(校验器与渲染器见 ai-audit-report-template 仓库)`,
|
||||
render: `python3 tools/render.py <报告文件.md> -o build/<报告文件>(产出 HTML / PNG / A4 PDF 三件套)`
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
import { formatBeijingIso } from "../../../core/config/timestamps.js";
|
||||
import type { ReportData, ReportBlock } from "./collect.js";
|
||||
import type { SectionPlan } from "./describe.js";
|
||||
|
||||
export type RenderOptions = {
|
||||
/** 报告编号;未给则按 RPT-<YYYYMM>-<6位随机> 生成 */
|
||||
reportId?: string;
|
||||
corpName?: string;
|
||||
/** 生成日期(YYYY-MM-DD),默认北京时间今天 */
|
||||
generatedAt?: string;
|
||||
reportStatus?: string;
|
||||
};
|
||||
|
||||
function pct(value: number | undefined, digits = 2): string {
|
||||
if (value === undefined || Number.isNaN(value)) return "—";
|
||||
return `${value.toFixed(digits)}%`;
|
||||
}
|
||||
|
||||
function escapeCell(value: string | number | undefined): string {
|
||||
if (value === undefined || value === null) return "—";
|
||||
return String(value).replace(/\|/g, "\\|").replace(/\n/g, " ");
|
||||
}
|
||||
|
||||
function parseRow(line: string): string[] {
|
||||
return line
|
||||
.trim()
|
||||
.replace(/^\|/, "")
|
||||
.replace(/\|$/, "")
|
||||
.split("|")
|
||||
.map((cell) => cell.trim());
|
||||
}
|
||||
|
||||
/** 当前统计口径不可得时,模板示例数据一律不冒充真实值;空串表示"保持模板原文并知会"。 */
|
||||
const HUMAN_ACCURACY_NOTE =
|
||||
"> ⚠️ **数据说明**:上游暂无人工审核准确率口径,本表人工一行为模板示例值,请业务侧核算后替换。";
|
||||
|
||||
type FillContext = {
|
||||
reportId: string;
|
||||
corpName: string;
|
||||
generatedAt: string;
|
||||
reportStatus?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* 用数据填充模板,产出报告 Markdown。
|
||||
*
|
||||
* 约定(模板是可变的皮):
|
||||
* - 表格:表头两行保留,数据行整体替换;识别不了的表原样保留。
|
||||
* - 叙述行:按句子改写占位数字,不按行号——模板重排段落不受影响。
|
||||
* - 上游没有的口径(人工准确率、失准原因分类)不编造:表格留模板示例并追加 ⚠️ 数据说明。
|
||||
*/
|
||||
export function renderMonthlyReport(
|
||||
template: string,
|
||||
data: ReportData,
|
||||
plans: SectionPlan[],
|
||||
options: RenderOptions = {}
|
||||
): string {
|
||||
const reportId = options.reportId ?? `RPT-${data.period.month.replace("-", "")}-${randomSuffix()}`;
|
||||
const corpName = options.corpName ?? data.corp.name;
|
||||
const generatedAt = options.generatedAt ?? beijingToday();
|
||||
const ctx: FillContext = { reportId, corpName, generatedAt, reportStatus: options.reportStatus };
|
||||
|
||||
const lines = template.split("\n");
|
||||
const out: string[] = [];
|
||||
let planIndex = 0;
|
||||
let tableBuffer: string[] = [];
|
||||
let lastH2 = "";
|
||||
let lastHeading = "";
|
||||
|
||||
const flushTable = () => {
|
||||
if (tableBuffer.length) {
|
||||
out.push(...transformTable(tableBuffer, data, lastHeading, lastH2));
|
||||
tableBuffer = [];
|
||||
}
|
||||
};
|
||||
|
||||
for (const raw of lines) {
|
||||
const h2 = raw.match(/^## (.+)$/);
|
||||
const h3 = raw.match(/^### (.+)$/);
|
||||
if (h2 || h3) {
|
||||
flushTable();
|
||||
const heading = (h2?.[1] ?? h3?.[1] ?? "").trim();
|
||||
const plan = plans.find((item, idx) => idx >= planIndex && item.heading === heading);
|
||||
if (plan) planIndex = plans.indexOf(plan) + 1;
|
||||
if (h2) lastH2 = heading;
|
||||
lastHeading = heading;
|
||||
out.push(raw);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (raw.trim().startsWith("|")) {
|
||||
tableBuffer.push(raw);
|
||||
continue;
|
||||
}
|
||||
|
||||
flushTable();
|
||||
out.push(fillInline(raw, data, ctx));
|
||||
}
|
||||
flushTable();
|
||||
|
||||
let result = out.join("\n");
|
||||
result = fillInline(result, data, ctx);
|
||||
// 报告信息表:统计期间与生成日期按真实统计口径补齐
|
||||
result = result.replace(
|
||||
/(\| 统计期间 \| )[^\n|]+/,
|
||||
`$1${data.period.start.slice(0, 10)} ~ ${data.period.end.slice(0, 10)}`
|
||||
);
|
||||
result = result.replace(/(\| 生成日期 \| )[^\n|]+/, `$1${ctx.generatedAt}`);
|
||||
return result;
|
||||
}
|
||||
|
||||
function fillInline(text: string, data: ReportData, ctx: FillContext): string {
|
||||
let result = text;
|
||||
result = result.replace(/【[^】]+】(?=\S*月)/, `【${ctx.corpName}】`);
|
||||
result = result.replace(/RPT-\d{6}-[A-Z0-9]+/, ctx.reportId);
|
||||
if (ctx.reportStatus) result = result.replace(/(报告状态\s*\|\s*)[^\n|]+/, `$1${ctx.reportStatus}`);
|
||||
|
||||
const perf = data.performance;
|
||||
if (!data.fetched.performance || !perf) return result;
|
||||
|
||||
const total = perf.approvalCount;
|
||||
const acc = perf.accuracy;
|
||||
const correct = total !== undefined && acc !== undefined ? Math.round((total * acc) / 100) : undefined;
|
||||
const wrong = total !== undefined && correct !== undefined ? total - correct : undefined;
|
||||
|
||||
// §1 摘要与叙述行:把模板里的占位样本量/准确率换成真实值
|
||||
if (total !== undefined && acc !== undefined && correct !== undefined && wrong !== undefined) {
|
||||
result = result.replace(/\*\*\d+ 笔\*\*/, `**${total} 笔**`);
|
||||
result = result.replace(/\*\*\d{3} 笔\*\*/, `**${total} 笔**`);
|
||||
result = result.replace(/\*\*9\d\.\d\d%\*\*/g, `**${pct(acc)}**`);
|
||||
result = result.replace(/92\.08%/g, pct(acc));
|
||||
result = result.replace(/240 笔/g, `${total} 笔`);
|
||||
// §2 叙述:模板里"依规综合正确 N 单(X%)"与"失准共 M 单(Y%)"是硬编码占位,
|
||||
// 用结构化模式匹配(不依赖具体数字),换成真实 correct/wrong。
|
||||
result = result.replace(
|
||||
/依规综合正确 \*\*\d+ 单(\d+(?:\.\d+)?%)\*\*/g,
|
||||
`依规综合正确 **${correct} 单(${pct(acc)})**`
|
||||
);
|
||||
result = result.replace(
|
||||
/综合失准共 \*\*\d+ 单(\d+(?:\.\d+)?%)\*\*/g,
|
||||
`综合失准共 **${wrong} 单(${pct(100 - acc)})**`
|
||||
);
|
||||
// 无加粗的裸形式
|
||||
result = result.replace(
|
||||
/依规综合正确 \d+ 单(\d+(?:\.\d+)?%)/g,
|
||||
`依规综合正确 ${correct} 单(${pct(acc)})`
|
||||
);
|
||||
result = result.replace(
|
||||
/综合失准共 \d+ 单(\d+(?:\.\d+)?%)/g,
|
||||
`综合失准共 ${wrong} 单(${pct(100 - acc)})`
|
||||
);
|
||||
result = result.replace(/\*\*\d+ 单\*\*的深度稽核中/g, `**${total} 单**的深度稽核中`);
|
||||
result = result.replace(/\d+ 单的深度稽核中/g, `${total} 单的深度稽核中`);
|
||||
// 公式代入值:\frac{N}{M} = X% 结构化匹配
|
||||
result = result.replace(
|
||||
/= \\frac\{\d+\}\{\d+\} = \d+(?:\.\d+)?\\?%/g,
|
||||
`= \\frac{${correct}}{${total}} = ${acc.toFixed(2)}\\%`
|
||||
);
|
||||
result = result.replace(
|
||||
/\d+\/\d+ = \d+(?:\.\d+)?%/g,
|
||||
`${correct}/${total} = ${pct(acc)}`
|
||||
);
|
||||
result = result.replace(/N = 240/g, `N = ${total}`);
|
||||
// 样本总量:真实单量 + 决策分布(无人工明细时只报总样本)
|
||||
const dist = distributionOf(data.blocks);
|
||||
result = result.replace(
|
||||
/\*\*\d+ 张\*\*([^)]*)/,
|
||||
`**${total} 张**${dist ? `(${dist})` : ""}`
|
||||
);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function distributionOf(blocks: ReportBlock[]): string | undefined {
|
||||
if (!blocks.length) return undefined;
|
||||
const counts = { pass: 0, reject: 0, unknown: 0 };
|
||||
for (const block of blocks) {
|
||||
const ai = (block.aiDecision ?? "").trim();
|
||||
if (/同意|通过|approve/i.test(ai)) counts.pass += 1;
|
||||
else if (/驳回|拒绝|终止|退回|reject/i.test(ai)) counts.reject += 1;
|
||||
else counts.unknown += 1;
|
||||
}
|
||||
const parts = [`${counts.pass} 张同意`, `${counts.reject} 张驳回`];
|
||||
if (counts.unknown) parts.push(`${counts.unknown} 张未定`);
|
||||
return parts.join(" + ");
|
||||
}
|
||||
|
||||
/** 表格块变换:保留表头两行,按所在章节 + 表头识别语义后重写数据行。 */
|
||||
function transformTable(
|
||||
block: string[],
|
||||
data: ReportData,
|
||||
heading: string,
|
||||
lastH2: string
|
||||
): string[] {
|
||||
if (block.length < 2) return block;
|
||||
const header = block[0]!;
|
||||
const separator = block[1]!;
|
||||
const sampleRows = block.slice(2);
|
||||
const columns = parseRow(header);
|
||||
if (!columns.length) return block;
|
||||
|
||||
const notes = noteAfter(columns, heading, lastH2, data);
|
||||
const rows = replacementRows(columns, sampleRows, data, heading);
|
||||
// 无论是否替换数据行,缺口径说明都要追加(模板保留时同样需要知会)
|
||||
if (!rows) return [...block, ...notes];
|
||||
return [header, separator, ...rows.map((row) => `| ${row.map(escapeCell).join(" | ")} |`), ...notes];
|
||||
}
|
||||
|
||||
/** 表后追加的数据说明(人工准确率缺口径时)。 */
|
||||
function noteAfter(columns: string[], heading: string, lastH2: string, data: ReportData): string[] {
|
||||
if (columns.includes("审核方式") && columns.includes("准确率")) {
|
||||
if (data.notes.humanAccuracyAvailable && data.humanAccuracy !== undefined) {
|
||||
const reviewed = data.notes.reviewedCount ?? 0;
|
||||
const diverged = data.notes.divergedCount ?? 0;
|
||||
return ["", `> ℹ️ **数据说明**:人工审核准确率由本地人工裁决回填(已裁决 ${reviewed} 笔,其中分歧 ${diverged} 笔);AI 准确率为上游效能口径。`, ""];
|
||||
}
|
||||
return ["", HUMAN_ACCURACY_NOTE, ""];
|
||||
}
|
||||
if (heading.includes("失准构成总览") && lastH2.includes("失准") && data.fetched.performance) {
|
||||
return ["", "> ⚠️ **数据说明**:失准原因分类(规则执行/识别/查重等维度)无上游字段,上表为模板示例分类,需人工归类后替换。", ""];
|
||||
}
|
||||
// §6:明细表保留模板示例行时(无分歧单据可填),必须标注是示例而非真实数据
|
||||
if (columns.includes("单据编号") && columns.some((col) => col.includes("原因分类"))) {
|
||||
return ["", "> ⚠️ **数据说明**:本期无 AI 与人工分歧的单据可填,或「原因分类/复核结论」需人工归类;上表为模板示例行,请以真实明细替换。", ""];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function replacementRows(
|
||||
columns: string[],
|
||||
sampleRows: string[],
|
||||
data: ReportData,
|
||||
heading: string
|
||||
): Array<Array<string | number>> | null {
|
||||
const perf = data.performance;
|
||||
|
||||
// 报告信息表:fillInline 已处理,行保留
|
||||
if (columns.includes("报告编号")) return null;
|
||||
|
||||
// §1.2 准确率结论表(表头 2 列:审核方式|准确率;示例行 AI/人工 两行)
|
||||
if (columns.includes("审核方式") && columns.includes("准确率") && columns.length === 2) {
|
||||
if (!data.fetched.performance || !perf) return null;
|
||||
const humanCell = data.notes.humanAccuracyAvailable && data.humanAccuracy !== undefined
|
||||
? `**${pct(data.humanAccuracy)}**`
|
||||
: sampleRows.length > 1
|
||||
? (parseRow(sampleRows[1]!)[1] ?? "*(口径待业务提供)*")
|
||||
: "*(口径待业务提供)*";
|
||||
return [
|
||||
["AI 审核", `**${pct(perf.accuracy)}**`],
|
||||
["人工审核", humanCell]
|
||||
];
|
||||
}
|
||||
|
||||
// §1.1 数据来源与范围
|
||||
if (columns.includes("项目") && columns.includes("内容") && heading.includes("数据来源")) {
|
||||
if (!perf) return null;
|
||||
const dist = distributionOf(data.blocks) ?? "";
|
||||
return [
|
||||
["数据来源", "客户授权的已完成历史审批单据"],
|
||||
["统计期间", `${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} 类**业务单据模板`
|
||||
: "*(单据模板分布待取数)*"],
|
||||
["样本总量", `**${perf.approvalCount ?? "—"} 张**${dist ? `(${dist})` : ""}`]
|
||||
];
|
||||
}
|
||||
|
||||
// §1.3 系统稳定性
|
||||
if (columns.includes("项目") && columns.includes("内容") && heading.includes("系统稳定性")) {
|
||||
if (!perf) return null;
|
||||
return [
|
||||
["全月成功审核率", `近 **${pct(perf.automationRate, 0)}**(自动化审核采纳率口径)`],
|
||||
["迭代影响", `*(迭代影响需业务口径补充;本月自动化采纳率 ${pct(perf.automationRate)})*`]
|
||||
];
|
||||
}
|
||||
|
||||
// §4 综合效益
|
||||
if (columns.includes("维度") && columns.includes("结论") && columns.includes("关键数据") && perf) {
|
||||
return [
|
||||
["准确度", "除去 AI 无法形成可靠判断而转失败的单据,AI 在既定规则范围内的准确率", `**${pct(perf.accuracy)}**`],
|
||||
["时效", "AI 审核单张单据平均耗时", perf.avgDurationSeconds !== undefined ? `平均 **${perf.avgDurationSeconds.toFixed(1)} 秒**` : "—"],
|
||||
["风险拦截", "在人工审核通过的单据中,AI 有效防堵的凭证与资金隐患", perf.riskCount !== undefined ? `${perf.riskCount} 笔` : "—"],
|
||||
["工作量", "协助财务人员弥补遗漏、聚焦高价值工作", "—"]
|
||||
];
|
||||
}
|
||||
|
||||
// §2.1 / §3.x 构成总览(维度 | …类型 | 占比 | 单数)
|
||||
if (columns.includes("维度") && columns.includes("单数") && columns.includes("占比")) {
|
||||
const isRisk = columns.some((col) => col.includes("风险"));
|
||||
if (isRisk) {
|
||||
if (!data.fetched.riskStats || !data.riskStats?.tags.length) return null;
|
||||
const tags = data.riskStats.tags.filter((tag) => tag.count !== undefined).slice(0, 3);
|
||||
const total = tags.reduce((sum, tag) => sum + (tag.count ?? 0), 0) || 1;
|
||||
const typeIdx = Math.max(1, columns.findIndex((col) => col.includes("风险")));
|
||||
const pctIdx = columns.indexOf("占比");
|
||||
const countIdx = columns.indexOf("单数");
|
||||
const rows: Array<Array<string | number>> = tags.map((tag, idx) => {
|
||||
const row: Array<string | number> = Array.from({ length: columns.length }, () => "—");
|
||||
row[0] = `TOP ${idx + 1}`;
|
||||
row[typeIdx] = tag.name ?? tag.id ?? "未命名风险";
|
||||
row[pctIdx] = pct(((tag.count ?? 0) / total) * 100, 1);
|
||||
row[countIdx] = `${tag.count} 张`;
|
||||
return row;
|
||||
});
|
||||
const totalRow: Array<string | number> = Array.from({ length: columns.length }, () => "—");
|
||||
totalRow[0] = "合计";
|
||||
totalRow[pctIdx] = "100%";
|
||||
totalRow[countIdx] = `${total} 张`;
|
||||
rows.push(totalRow);
|
||||
return rows;
|
||||
}
|
||||
// 失准构成:无上游分类 → 留模板原文
|
||||
return null;
|
||||
}
|
||||
|
||||
// §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) => [
|
||||
block.sn,
|
||||
block.template || "—",
|
||||
block.aiDecision ?? "—",
|
||||
block.humanResult ?? "—",
|
||||
"*(原因分类待人工归类)*",
|
||||
block.aiSummary ?? "—",
|
||||
"(截图)"
|
||||
]);
|
||||
}
|
||||
|
||||
// §7.1 分模板统计(只认明确带"模板"或 6 列且有"AI 准确率"的表头;不吃掉一致性示例的 5 列表)
|
||||
if (
|
||||
(columns.includes("单据模板") || columns[0] === "模板") &&
|
||||
(columns.includes("AI 准确率") || columns.includes("自动审批率") || columns.includes("单量"))
|
||||
) {
|
||||
if (!data.fetched.templateGroups) return null;
|
||||
if (!data.templateGroups.length) return null;
|
||||
return data.templateGroups.slice(0, 20).map((group) => {
|
||||
const agreement = group.total ? (group.agreed / group.total) * 100 : 0;
|
||||
if (columns.includes("AI 准确率")) {
|
||||
// 分模板的"准确率"应为逐单判定正确率,无判定字段时以 AI/人工一致率占位并说明
|
||||
const row: Array<string | number> = Array.from({ length: columns.length }, () => "—");
|
||||
row[0] = group.template;
|
||||
row[columns.indexOf("AI 准确率")] = pct(agreement);
|
||||
const manualIdx = columns.findIndex((col) => col.includes("人工"));
|
||||
if (manualIdx >= 0 && columns[manualIdx] === "人工同意:驳回") {
|
||||
row[manualIdx] = `${group.total} 笔`;
|
||||
}
|
||||
return row;
|
||||
}
|
||||
if (columns.length >= 2) return [group.template, group.total];
|
||||
return [group.template];
|
||||
});
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function beijingToday(): string {
|
||||
return formatBeijingIso().slice(0, 10);
|
||||
}
|
||||
|
||||
function randomSuffix(): string {
|
||||
const alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
|
||||
let out = "";
|
||||
for (let i = 0; i < 6; i++) out += alphabet[Math.floor(Math.random() * alphabet.length)]!;
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
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";
|
||||
|
||||
const TEMPLATE = join(import.meta.dirname, "..", "..", "..", "..", "report-templates", "monthly.md");
|
||||
|
||||
function sampleData(overrides: Partial<ReportData> = {}): ReportData {
|
||||
return {
|
||||
period: { start: "2026-08-01T00:00:00+08:00", end: "2026-08-31T23:59:59+08:00", month: "2026-08" },
|
||||
corp: { id: "corp-a", name: "赢家时尚" },
|
||||
fetched: { performance: true, riskStats: true, riskDetails: true, blocks: true, templateGroups: true },
|
||||
performance: {
|
||||
approvalCount: 240,
|
||||
accuracy: 92.08,
|
||||
automationRate: 41.67,
|
||||
riskCount: 40,
|
||||
avgDurationSeconds: 445.4,
|
||||
sankey: { nodes: [], links: [] }
|
||||
},
|
||||
riskStats: {
|
||||
tags: [
|
||||
{ id: "B.1.1", name: "缺失要求凭证", count: 23 },
|
||||
{ id: "B.2.3", name: "大额预付与采购口径偏差", count: 9 },
|
||||
{ id: "B.3.1", name: "票据合规与专票强制违规", count: 8 },
|
||||
{ id: "B.4.1", name: "长尾风险", count: 30 }
|
||||
]
|
||||
},
|
||||
blocks: [
|
||||
{ sn: "FP260001", template: "费用报销", aiDecision: "同意", humanResult: "驳回", agreement: "diverged", aiSummary: "合规放行", humanComment: "超标" },
|
||||
{ sn: "FP260002", template: "费用报销", aiDecision: "同意", humanResult: "同意", agreement: "agreed", aiSummary: "合规放行", humanComment: undefined }
|
||||
],
|
||||
templateGroups: [
|
||||
{ template: "费用报销", total: 100, agreed: 92, diverged: 8 },
|
||||
{ template: "差旅报销", total: 140, agreed: 130, diverged: 10 }
|
||||
],
|
||||
reviews: new Map(),
|
||||
notes: { humanAccuracyAvailable: false, failureRateAvailable: true, mismatchCategoriesAvailable: false },
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
|
||||
describe("describeTemplate", () => {
|
||||
test("infers data demands from section headings without hard-coding chapters", () => {
|
||||
const template = [
|
||||
"# x",
|
||||
"## 1. 审核测试结果",
|
||||
"### 1.2 核心准确率结论",
|
||||
"## 2. AI 失准分析",
|
||||
"## 3. AI 发现的潜在风险",
|
||||
"### 3.1 风险构成总览",
|
||||
"## 4. 综合效益",
|
||||
"## 5. AI 与人工审核一致性示例",
|
||||
"## 6. AI 通过 / 人工驳回单据明细",
|
||||
"### 7.1 分模板准确率与自动审批率"
|
||||
].join("\n");
|
||||
|
||||
const plans = describeTemplate(template);
|
||||
const byHeading = new Map(plans.map((plan) => [plan.heading, plan.demands]));
|
||||
|
||||
// 每个 ## 章节一条 plan;### 子标题的需求并入所属章节
|
||||
expect(byHeading.get("1. 审核测试结果")).toContain("performance");
|
||||
expect(byHeading.get("2. AI 失准分析")).toContain("blocks");
|
||||
expect(byHeading.get("3. AI 发现的潜在风险")).toContain("riskStats");
|
||||
expect(byHeading.get("3. AI 发现的潜在风险")).toContain("riskDetails"); // 由 ### 3.1 并入
|
||||
expect(byHeading.get("5. AI 与人工审核一致性示例")).toContain("blocks");
|
||||
expect(byHeading.get("6. AI 通过 / 人工驳回单据明细")).toContain("blocks");
|
||||
// "人工审核准确率" 不应把一致性章节误判为效能章节
|
||||
expect(byHeading.get("5. AI 与人工审核一致性示例")).not.toContain("performance");
|
||||
// 子标题不单独成 plan
|
||||
expect(byHeading.has("3.1 风险构成总览")).toBe(false);
|
||||
});
|
||||
|
||||
test("renaming a chapter keeps working when keywords still match", () => {
|
||||
// 模板可变:章节改名后只要关键词仍命中就能取到需求
|
||||
const template = "## 1. 月度测试结果\n## 2. 误判分析\n## 3. 风险扫描";
|
||||
const plans = describeTemplate(template);
|
||||
expect(plans).toHaveLength(3);
|
||||
expect(plans[0]!.demands).toEqual([]); // "月度测试结果" 不含既有规则关键词
|
||||
expect(plans[1]!.demands).toContain("blocks"); // "误判" 命中规则
|
||||
expect(plans[2]!.demands).toContain("riskStats");
|
||||
});
|
||||
});
|
||||
|
||||
describe("renderMonthlyReport", () => {
|
||||
test("fills identity, period, and performance facts from real data", () => {
|
||||
const template = readFileSync(TEMPLATE, "utf8");
|
||||
const plans = describeTemplate(template);
|
||||
const out = renderMonthlyReport(template, sampleData(), plans, { reportId: "RPT-202608-TEST01" });
|
||||
|
||||
expect(out).toContain("【赢家时尚】8月AI审核准确率报告");
|
||||
expect(out).toContain("RPT-202608-TEST01");
|
||||
expect(out).toContain("2026-08-01 ~ 2026-08-31");
|
||||
// §1.2 AI 准确率用真实值
|
||||
expect(out).toContain("**92.08%**");
|
||||
// §1.1 样本总量 = 真实审批量 + blocks 的决策分布(fixture: 2 同意 0 驳回)
|
||||
expect(out).toContain("**240 张**(2 张同意 + 0 张驳回)");
|
||||
// §4 关键数据
|
||||
expect(out).toContain("平均 **445.4 秒**");
|
||||
expect(out).toContain("40 笔");
|
||||
// §7.1 分模板:模板名 + 一致率占位
|
||||
expect(out).toContain("差旅报销");
|
||||
expect(out).toContain("92.86%"); // 130/140 一致率
|
||||
expect(out).toContain("费用报销");
|
||||
});
|
||||
|
||||
test("keeps template sample values and adds a warning note when a metric has no upstream source", () => {
|
||||
const template = readFileSync(TEMPLATE, "utf8");
|
||||
const plans = describeTemplate(template);
|
||||
const out = renderMonthlyReport(template, sampleData(), plans);
|
||||
|
||||
// 人工审核准确率:无上游口径 → 模板示例值保留 + ⚠️ 数据说明
|
||||
expect(out).toContain("人工审核准确率");
|
||||
expect(out).toContain("数据说明");
|
||||
expect(out).toContain("人工准确率");
|
||||
// 失准原因分类:无上游字段 → 不编造
|
||||
expect(out).toContain("失准原因分类");
|
||||
// 不应把示例值(83.33%)冒充为真实抓取结果的同时又丢失说明
|
||||
expect(out).toContain("**83.33%**");
|
||||
});
|
||||
|
||||
test("replaces the sample mismatch narrative with real counts", () => {
|
||||
const template = readFileSync(TEMPLATE, "utf8");
|
||||
const plans = describeTemplate(template);
|
||||
const out = renderMonthlyReport(template, sampleData(), plans);
|
||||
// 221/240 与 19 单 是模板示例;真实数据 240 * 92.08% = 221, 失准 19 → 数字仍成立,
|
||||
// 关键是失准构成总览不冒充分类(已由 noteAfter 标注),且叙述句不残留 92.08% 之外的错误样本量
|
||||
expect(out).toContain("221 单(92.08%)");
|
||||
expect(out).toContain("19 单(7.92%)");
|
||||
});
|
||||
|
||||
test("custom template path drives the same pipeline (skin is swappable)", () => {
|
||||
const template = [
|
||||
"# 【X】月报",
|
||||
"",
|
||||
"| 报告信息 | 内容 |",
|
||||
"| --- | --- |",
|
||||
"| 报告编号 | RPT-202608-PLACE |",
|
||||
"| 客户名称 | 占位 |",
|
||||
"| 统计期间 | 占位 |",
|
||||
"| 生成日期 | 占位 |",
|
||||
"",
|
||||
"## 1. 审核测试结果",
|
||||
"",
|
||||
"本月样本 **0 笔**。",
|
||||
"",
|
||||
"| 审核方式 | 准确率 |",
|
||||
"| --- | --- |",
|
||||
"| AI 审核 | **0%** |",
|
||||
"| 人工审核 | **0%** |"
|
||||
].join("\n");
|
||||
|
||||
const plans = describeTemplate(template);
|
||||
const out = renderMonthlyReport(template, sampleData(), plans, { reportId: "RPT-202608-CUSTOM" });
|
||||
|
||||
expect(out).toContain("RPT-202608-CUSTOM");
|
||||
expect(out).toContain("**92.08%**");
|
||||
expect(out).toContain("**240 笔**");
|
||||
// 表头保留
|
||||
expect(out).toContain("| 审核方式 | 准确率 |");
|
||||
// ⚠️ 说明在表后追加
|
||||
expect(out).toContain("⚠️ **数据说明**");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe("review store + human accuracy join", () => {
|
||||
const originalEnv = process.env.SEAL_USE_REVIEWS_DIR;
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = mkdtempSync(join(tmpdir(), "seal-reviews-test-"));
|
||||
process.env.SEAL_USE_REVIEWS_DIR = testDir;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (originalEnv === undefined) delete process.env.SEAL_USE_REVIEWS_DIR;
|
||||
else process.env.SEAL_USE_REVIEWS_DIR = originalEnv;
|
||||
rmSync(testDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test("writeReview appends and loadReviews merges by SN (last write wins)", () => {
|
||||
writeReview("corp-a", { sn: "FP1", month: "2026-08", verdict: "human_correct" });
|
||||
writeReview("corp-a", { sn: "FP2", month: "2026-08", verdict: "ai_correct" });
|
||||
// 同一 SN 改判:后写覆盖先写
|
||||
writeReview("corp-a", { sn: "FP1", month: "2026-08", verdict: "both_correct" });
|
||||
|
||||
const reviews = loadReviews("corp-a", "2026-08");
|
||||
expect(reviews.size).toBe(2);
|
||||
expect(reviews.get("FP1")?.verdict).toBe("both_correct");
|
||||
expect(reviews.get("FP2")?.verdict).toBe("ai_correct");
|
||||
|
||||
// 文件按租户+月份分片,追加式 JSONL
|
||||
expect(reviewFilePath("corp-a", "2026-08")).toContain("corp-a-2026-08.jsonl");
|
||||
const content = readFileSync(reviewFilePath("corp-a", "2026-08"), "utf8").trim().split("\n");
|
||||
expect(content).toHaveLength(3); // 3 次写入(含改判)
|
||||
});
|
||||
|
||||
test("loadReviews isolates tenants and months, skips corrupt lines", () => {
|
||||
writeReview("corp-a", { sn: "A1", month: "2026-08", verdict: "ai_correct" });
|
||||
writeReview("corp-b", { sn: "B1", month: "2026-08", verdict: "human_correct" });
|
||||
writeReview("corp-a", { sn: "A2", month: "2026-09", verdict: "ai_correct" });
|
||||
// 写入一行损坏数据
|
||||
const fs = require("node:fs") as typeof import("node:fs");
|
||||
fs.appendFileSync(reviewFilePath("corp-a", "2026-08"), "{corrupt json}\n", "utf8");
|
||||
|
||||
expect(loadReviews("corp-a", "2026-08").size).toBe(1);
|
||||
expect(loadReviews("corp-b", "2026-08").size).toBe(1);
|
||||
expect(loadReviews("corp-a", "2026-09").size).toBe(1);
|
||||
expect(loadReviews("corp-a", "2026-07").size).toBe(0);
|
||||
});
|
||||
|
||||
test("rejects invalid month and verdict with exit 13 validation error", () => {
|
||||
expect(() => writeReview("corp-a", { sn: "X", month: "bad", verdict: "ai_correct" })).toThrow();
|
||||
expect(() => writeReview("corp-a", { sn: "X", month: "2026-08", verdict: "wrong" })).toThrow();
|
||||
expect(() => writeReview("corp-a", { sn: " ", month: "2026-08", verdict: "ai_correct" })).toThrow();
|
||||
});
|
||||
|
||||
test("collectReportData joins reviews onto fetched blocks and computes human accuracy", async () => {
|
||||
// 写入裁决:3 个 SN,其中 1 个分歧单被判人工对
|
||||
writeReview("corp-a", { sn: "D1", month: "2026-08", verdict: "human_correct" }); // 分歧,人工对
|
||||
writeReview("corp-a", { sn: "A1", month: "2026-08", verdict: "ai_correct" }); // 一致,AI 对
|
||||
writeReview("corp-a", { sn: "A2", month: "2026-08", verdict: "both_correct" }); // 一致,双方对
|
||||
|
||||
// 伪客户端:只返回 3 条审批运行(SN 对应裁决),不发真网络
|
||||
const runs = [
|
||||
{ id: "r1", sourceDocumentSN: "D1", result: { decision: "同意" }, pipelineData: { humanResult: "驳回" } },
|
||||
{ id: "r2", sourceDocumentSN: "A1", result: { decision: "驳回" }, pipelineData: { humanResult: "驳回" } },
|
||||
{ id: "r3", sourceDocumentSN: "A2", result: { decision: "同意" }, pipelineData: { humanResult: "同意" } }
|
||||
];
|
||||
const fakeClient = {
|
||||
get: async () => ({ json: async () => ({ data: { records: runs, total: 3 } }) })
|
||||
} as never;
|
||||
|
||||
const data = await collectReportData(fakeClient, new Set(["blocks"]), {
|
||||
month: "2026-08",
|
||||
corp: { id: "corp-a", name: "A" }
|
||||
});
|
||||
|
||||
expect(data.reviews.size).toBe(3);
|
||||
expect(data.blocks).toHaveLength(3);
|
||||
// 每个 block 挂上裁决
|
||||
expect(data.blocks.map((b) => b.verdict)).toEqual(["human_correct", "ai_correct", "both_correct"]);
|
||||
// 裁决数 = 3,人工对 = human_correct(D1) + both_correct(A2) = 2 → 2/3 = 66.67%
|
||||
expect(data.notes.reviewedCount).toBe(3);
|
||||
expect(data.notes.humanAccuracyAvailable).toBe(true);
|
||||
expect(data.humanAccuracy).toBeCloseTo(66.67, 1);
|
||||
// D1 是分歧单(AI 同意 / 人工驳回)
|
||||
expect(data.notes.divergedCount).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
test("no reviews → human accuracy unavailable (honest gap, not fabricated)", async () => {
|
||||
const fakeClient = {
|
||||
get: async () => ({ json: async () => ({ data: { records: [{ id: "r1", sourceDocumentSN: "X1" }], total: 1 } }) })
|
||||
} as never;
|
||||
const data = await collectReportData(fakeClient, new Set(["blocks"]), {
|
||||
month: "2026-08",
|
||||
corp: { id: "corp-no-reviews", name: "B" }
|
||||
});
|
||||
expect(data.reviews.size).toBe(0);
|
||||
expect(data.notes.humanAccuracyAvailable).toBe(false);
|
||||
expect(data.humanAccuracy).toBeUndefined();
|
||||
});
|
||||
|
||||
test("render uses human accuracy when available and shows review coverage note", () => {
|
||||
const template = readFileSync(TEMPLATE, "utf8");
|
||||
const plans = describeTemplate(template);
|
||||
const reviews = new Map();
|
||||
reviews.set("FP260001", { sn: "FP260001", month: "2026-08", verdict: "human_correct", recordedAt: "" });
|
||||
const data = sampleData({
|
||||
reviews,
|
||||
humanAccuracy: 75,
|
||||
notes: { humanAccuracyAvailable: true, failureRateAvailable: true, mismatchCategoriesAvailable: false, reviewedCount: 4, divergedCount: 2 }
|
||||
});
|
||||
const out = renderMonthlyReport(template, data, plans);
|
||||
|
||||
// §1.2 人工审核行用真实 75%,且不再弹"口径待业务提供"
|
||||
expect(out).toContain("**75.00%**");
|
||||
expect(out).toContain("已裁决 4 笔");
|
||||
expect(out).not.toContain("口径待业务提供");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,137 @@
|
||||
import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { validationError } from "../../../core/errors.js";
|
||||
|
||||
/**
|
||||
* 人工裁决的本地持久化(JSONL,按 租户 × 月份 分片)。
|
||||
*
|
||||
* 为什么是 JSONL:跨周 review 天然是**追加**场景——每审一批写一批,不整文件重写,
|
||||
* 避免并发覆盖;单行一条记录,可直接 tail/grep/手改,也可被 CLI 批量导入。
|
||||
* 为什么按租户+月份分片:租户隔离、月度报告天然对应一个文件、文件不会无限膨胀。
|
||||
*
|
||||
* 一条记录 = 一个 SN 在某个月被人工裁决一次的结果。同一 SN 重复裁决时,
|
||||
* 以**最后一条**为准(loadReviews 归并时后写覆盖先写)。
|
||||
*/
|
||||
|
||||
/** 人工裁决结论:谁对。both_* 覆盖"一致但仍复核"与"分歧后判定双方各有对错"的场景。 */
|
||||
export type ReviewVerdict =
|
||||
| "ai_correct" // AI 对,人工错
|
||||
| "human_correct" // 人工对,AI 错
|
||||
| "both_correct" // 双方都对(意见不同但结论都成立,或一致且复核通过)
|
||||
| "both_wrong" // 双方都错
|
||||
| "undecided"; // 已 review 但暂无法判定(保留占位,后续可改判)
|
||||
|
||||
export type ReviewRecord = {
|
||||
/** 合思/源单据 SN(裁决的自然键) */
|
||||
sn: string;
|
||||
/** 裁决所属统计月 YYYY-MM(与 report monthly 的 month 对齐) */
|
||||
month: string;
|
||||
verdict: ReviewVerdict;
|
||||
/** 裁决人(可选,留痕用) */
|
||||
reviewedBy?: string;
|
||||
/** 裁决备注(可选):为什么这么判 */
|
||||
note?: string;
|
||||
/** 写入时间(北京时间 ISO 秒) */
|
||||
recordedAt: string;
|
||||
};
|
||||
|
||||
const VERDICTS: ReadonlySet<string> = new Set([
|
||||
"ai_correct",
|
||||
"human_correct",
|
||||
"both_correct",
|
||||
"both_wrong",
|
||||
"undecided"
|
||||
]);
|
||||
|
||||
const REVIEWS_DIR_ENV = "SEAL_USE_REVIEWS_DIR";
|
||||
|
||||
/** 裁决存储根目录:~/.config/seal-use/reviews/(租户 = 文件名前缀)。可用 SEAL_USE_REVIEWS_DIR 覆盖(测试/隔离)。 */
|
||||
export function reviewsDir(): string {
|
||||
const configured = process.env[REVIEWS_DIR_ENV]?.trim();
|
||||
if (configured) return configured;
|
||||
return join(homedir(), ".config", "seal-use", "reviews");
|
||||
}
|
||||
|
||||
/** 分片路径:<reviewsDir>/<corpId>-<YYYY-MM>.jsonl */
|
||||
export function reviewFilePath(corpId: string, month: string): string {
|
||||
return join(reviewsDir(), `${sanitizeCorpId(corpId)}-${month}.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(
|
||||
`Invalid verdict "${verdict}". Expected one of: ${[...VERDICTS].join(", ")}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取某租户某月的全部裁决,按 SN 归并(同一 SN 后写覆盖先写)。文件不存在返回空 Map。
|
||||
*/
|
||||
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;
|
||||
|
||||
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 && typeof parsed.sn === "string" && VERDICTS.has(parsed.verdict)) {
|
||||
reviews.set(parsed.sn, parsed); // 后写覆盖先写
|
||||
}
|
||||
} catch {
|
||||
// 跳过损坏行:单行坏数据不应让整个裁决集不可读
|
||||
}
|
||||
}
|
||||
return reviews;
|
||||
}
|
||||
|
||||
/**
|
||||
* 追加写一条裁决到磁盘(真正的落盘入口)。corpId 由调用方显式传入(sn 与租户无关,文件按租户分片)。
|
||||
*/
|
||||
export function writeReview(
|
||||
corpId: string,
|
||||
input: {
|
||||
sn: string;
|
||||
month: string;
|
||||
verdict: string;
|
||||
reviewedBy?: string;
|
||||
note?: string;
|
||||
recordedAt?: string;
|
||||
}
|
||||
): ReviewRecord {
|
||||
const sn = input.sn?.trim();
|
||||
if (!sn) throw validationError("sn is required for a review record");
|
||||
assertMonth(input.month);
|
||||
assertVerdict(input.verdict);
|
||||
|
||||
const record: ReviewRecord = {
|
||||
sn,
|
||||
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);
|
||||
mkdirSync(dirname(filePath), { recursive: true, mode: 0o700 });
|
||||
appendFileSync(filePath, JSON.stringify(record) + "\n", { encoding: "utf-8", mode: 0o600 });
|
||||
return record;
|
||||
}
|
||||
Reference in new issue
Block a user