Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b72b5d7f71 | ||
|
|
a8e32cff32 | ||
|
|
5e06429d6c | ||
|
|
3777e81ee7 | ||
|
|
0ee5031dc8 | ||
|
|
2bf8d22810 | ||
|
|
f2b0f15a6e | ||
|
|
065ba42bfe | ||
|
|
6260b824a0 | ||
|
|
7efa83ff30 | ||
|
|
1b5ae12254 | ||
|
|
27660bed92 |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.7.2",
|
||||
"version": "0.7.3",
|
||||
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
|
||||
"author": {
|
||||
"name": "yingqing"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# hose-use (v0.7.2)
|
||||
# hose-use (v0.7.3)
|
||||
|
||||
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
|
||||
|
||||
|
||||
Vendored
+748
-242
File diff suppressed because it is too large.
Load diff
Vendored
+1
-1
@@ -2,7 +2,7 @@
|
||||
"openapi": "3.1.0",
|
||||
"info": {
|
||||
"title": "hose-use API & MCP Tools Specification",
|
||||
"version": "0.7.2",
|
||||
"version": "0.7.3",
|
||||
"description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."
|
||||
},
|
||||
"servers": [
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
openapi: 3.1.0
|
||||
info:
|
||||
title: hose-use API & MCP Tools Specification
|
||||
version: 0.7.2
|
||||
version: 0.7.3
|
||||
description: >-
|
||||
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
|
||||
servers:
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.7.2",
|
||||
"version": "0.7.3",
|
||||
"module": "src/server.ts",
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -51,6 +51,9 @@ console.log("✓ Updated README.md");
|
||||
const skillPath = join(ROOT, "skills", "hose-use", "SKILL.md");
|
||||
let skillContent = readFileSync(skillPath, "utf-8");
|
||||
skillContent = skillContent.replace(/# hose-use \(v[\d.]+\)/g, `# hose-use (v${nextVersion})`);
|
||||
skillContent = skillContent.replace(/v[\d.]+: 合思/g, `v${nextVersion}: 合思`);
|
||||
skillContent = skillContent.replace(/version: [\d.]+/g, `version: ${nextVersion}`);
|
||||
skillContent = skillContent.replace(/\(v[\d.]+\)/g, `(v${nextVersion})`);
|
||||
writeFileSync(skillPath, skillContent);
|
||||
console.log("✓ Updated skills/hose-use/SKILL.md");
|
||||
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
---
|
||||
name: hose-use
|
||||
description: "v0.7.2: 合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号 API 登录、租户切换、单据检索与审批动作、工作流跨域扫描、内置 HTTP 交互文档与常驻守护进程。"
|
||||
description: "v0.7.3: 合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号 API 登录、租户切换、单据检索与审批动作、工作流跨域扫描、内置 HTTP 交互文档与常驻守护进程。"
|
||||
metadata:
|
||||
version: 0.7.2
|
||||
short-description: 合思/易快报企业级 CLI 工具与底层 SDK (v0.7.2)
|
||||
version: 0.7.3
|
||||
short-description: 合思/易快报企业级 CLI 工具与底层 SDK (v0.7.3)
|
||||
---
|
||||
|
||||
# hose-use (v0.7.2)
|
||||
# hose-use (v0.7.3)
|
||||
|
||||
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
|
||||
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
|
||||
@@ -15,8 +15,9 @@ metadata:
|
||||
|
||||
## Agent 执行原则 (First Rules)
|
||||
|
||||
0. **一键构建上下文(Zero Source-Reading)**:在开始执行任务前,优先执行 `hose-use context --json` 或 `hose-aipro status --json` 一键获取当前账号、企业租户、登录凭证、运行模式与 AI PRO 网关状态。**严禁翻阅源码目录探查配置与企业列表**。
|
||||
1. **通道自适应**:将 CLI/MCP 视为 Agent 的执行通道,而不是要求用户学习命令行。Agent 应主动将用户的自然语言诉求转换为具体的 CLI 命令;严禁要求用户手动拼装命令行参数。
|
||||
2. **多租户优先探查**:在需要企业参数前,优先执行 `hose-use corps list`。如果目标企业已配置,通过企业名称映射出对应的 `id` 并作为 `--corp=<id>` 传入;不要向普通用户询问底层 `corpId`。
|
||||
2. **多租户优先探查**:在需要企业参数前,优先执行 `hose-use corps list` 或 `hose-use context`。如果目标企业已配置,通过企业名称映射出对应的 `id` 并作为 `--corp=<id>` 传入;不要向普通用户询问底层 `corpId`。
|
||||
3. **输出防护与大报文处理**:
|
||||
- 面对单据明细、实体字典、工作流等大数据量查询,优先使用 `--json -o <path>` 本地转储或使用 `--limit` 限制分页;
|
||||
- 严禁盲目使用 `--full` 将上万行原始报文一次性塞入上下文;
|
||||
@@ -29,7 +30,13 @@ metadata:
|
||||
|
||||
| 用户意图 / 场景 | 推荐命令 | 深入参考文档 |
|
||||
|---|---|---|
|
||||
| 全局运行上下文 / 身份诊断 / 免读源码自省 | `hose-use context [--json]`, `hose-use status` | [references/auth.md](references/auth.md) |
|
||||
| AI PRO 审批仲裁网关状态与当前连接企业 | `hose-aipro status [--json]`, `hose-use aipro status` | [references/approval.md](references/approval.md) |
|
||||
| AI PRO 规则场景库与审核要点清单 | `hose-aipro scopes`, `hose-aipro points <索引>` | [references/approval.md](references/approval.md) |
|
||||
| AI PRO 确定性审批仲裁全流程 (核验/仲裁) | `hose-aipro bind`, `hose-aipro review`, `hose-aipro decide` | [references/approval.md](references/approval.md) |
|
||||
| 本地 AI 审批规约与规则增删改查 | `hose-use rule scopes`, `hose-use rule add`, `hose-use rule list` | [references/approval.md](references/approval.md) |
|
||||
| 首次登录 / 账密认证 / Token过期 / 多账号 | `hose-use auth login`, `hose-use auth status`, `hose-use auth refresh` | [references/auth.md](references/auth.md) |
|
||||
| 第三方免密/协助链接一键秒级导入 | `hose-use corps add-link <url>`, `hose-use auth add-link <url>` | [references/auth.md](references/auth.md) |
|
||||
| 代客协助凭证导入 / 探针连通性诊断 | `hose-use auth import`, `hose-use probe` | [references/auth.md](references/auth.md) |
|
||||
| 企业租户切换 / 查看当前企业 | `hose-use corps list`, `hose-use corps switch <id>` | [references/auth.md](references/auth.md) |
|
||||
| 报销单据检索 / 费用明细下钻 / 中文字典 | `hose-use bill list`, `hose-use bill get <单号|ID> [--risk]` | [references/bill.md](references/bill.md) |
|
||||
@@ -65,10 +72,16 @@ metadata:
|
||||
## 常用命令速查
|
||||
|
||||
```bash
|
||||
# 0. 全局上下文一键自省 (免读源码构建环境)
|
||||
hose-use context # 文本格式仪表盘 (当前账号/企业/工号/Token/AI PRO/路径)
|
||||
hose-use context --json # 结构化 JSON (供 Agent 零解析直接构建完整上下文)
|
||||
hose-aipro status # 查看 AI PRO 审批网关状态、当前连接企业与规则场景库
|
||||
hose-aipro # 首页直接展示动态企业页眉与快速工作流
|
||||
|
||||
# 1. 认证与企业
|
||||
hose-use auth login --phone=17718556446 --password=... # 纯 API 账密自动登录
|
||||
hose-use auth status # 查看 Token 剩余有效期与登录账号
|
||||
hose-use corps list # 查看企业租户列表
|
||||
hose-use corps list # 查看企业租户列表 (标注 * 为统一默认企业)
|
||||
hose-use corps switch ID01MCcOgJl1td # 切换工作企业
|
||||
hose-use probe # 诊断当前企业接口连通性
|
||||
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
# 合思 AI PRO 确定性审批仲裁网关 (Approval Gateway & AI PRO Guide)
|
||||
|
||||
本参考专卷面向开发者与 AI 智能体,系统说明 `hose-aipro` 命令行、确定性网关仲裁机制与本地规约管理。
|
||||
|
||||
---
|
||||
|
||||
## 1. 架构与定位
|
||||
|
||||
- **双向命令入口**:可通过独立二进制 `hose-aipro <子命令>` 或统一入口 `hose-use aipro <子命令>` 唤起。
|
||||
- **共享统一上下文**:`hose-aipro` 与 `hose-use` 共享相同的企业租户配置(`~/.config/hose-use/config.json` 与 `enterprises` 凭证目录)。
|
||||
- **零源码阅读自省**:运行 `hose-aipro status` 或 `hose-use context` 即可直接构建完整的运行时上下文,无需翻阅代码。
|
||||
- **强确定性硬条款阻断**:AI 仅负责事实核验打标(PASS / FAIL / SKIP);下游流转动作(同意 / 驳回 / 转人工)由本地网关根据【硬性 / 弹性 / 建议 / 特殊】分级硬编码规则仲裁,物理切断幻觉可能导致的违规放行。
|
||||
|
||||
---
|
||||
|
||||
## 2. 核心工作流与命令
|
||||
|
||||
### 步骤 0:查看运行上下文与当前绑定企业
|
||||
```bash
|
||||
hose-aipro status
|
||||
hose-aipro status --json
|
||||
```
|
||||
- 输出当前连接的企业 ID/名称、操作员工号、Token 有效期、已加载场景库统计与待决断会话数。
|
||||
|
||||
### 步骤 1:查看规约场景索引库
|
||||
```bash
|
||||
hose-aipro scopes
|
||||
# 或使用 hose-use:
|
||||
hose-use rule scopes
|
||||
```
|
||||
- 输出本地 SQLite 数据库中所有生效场景(如 `#1 差旅报销`、`#2 业务招待`)及规则条数。
|
||||
|
||||
### 步骤 2:查看场景审核要点清单
|
||||
```bash
|
||||
hose-aipro points 1
|
||||
# 或通过场景名称:
|
||||
hose-aipro points 差旅报销
|
||||
```
|
||||
- 查看场景下的所有审核要点、判定依据与严格级别(`硬性` / `弹性` / `建议` / `特殊`)。
|
||||
|
||||
### 步骤 3:为单据挂载审核要点清单
|
||||
```bash
|
||||
hose-aipro bind S26000001 1
|
||||
```
|
||||
- 将场景 #1 的要点清单初始化并绑定至单号 `S26000001`。
|
||||
|
||||
### 步骤 4:查看单据审核清单与核验进度
|
||||
```bash
|
||||
hose-aipro checklist S26000001
|
||||
```
|
||||
- 检查当前单据下各要点的打标状态(`PENDING` / `PASS` / `FAIL` / `SKIP`)。
|
||||
|
||||
### 步骤 5:逐项录入事实核验打标
|
||||
```bash
|
||||
# 批量快速打标:
|
||||
hose-aipro review S26000001 --eval "1=PASS:发票合规; 2=FAIL:住宿超标; 3=SKIP"
|
||||
|
||||
# 单项精准打标:
|
||||
hose-aipro review S26000001 --point 2 --status FAIL --reason "住宿费超过差旅标准 200 元"
|
||||
```
|
||||
|
||||
### 步骤 6:确定性网关仲裁与审批执行
|
||||
```bash
|
||||
# 预审仿真 (Dry Run - 仅仲裁不改变下游单据状态):
|
||||
hose-aipro decide S26000001
|
||||
|
||||
# 真实驱动下游执行 (需加 --apply --yes 确认):
|
||||
hose-aipro decide S26000001 --apply --yes
|
||||
```
|
||||
|
||||
### 步骤 7:审计流水全流程追溯
|
||||
```bash
|
||||
hose-aipro logs [单号]
|
||||
```
|
||||
- 追溯单据从初始化、打标到决断的每一步本地不可篡改审计记录。
|
||||
|
||||
---
|
||||
|
||||
## 3. 规约语法与严格程度等级
|
||||
|
||||
规则正文中必须包含合法的条款判定标记:
|
||||
- `[必须上传真实发票]{硬性}`:硬性条款违规时,网关物理阻断同意操作,必须驳回。
|
||||
- `[尽量提供行程水单]{弹性}`:弹性条款允许按策略放行或转人工复核。
|
||||
- `[建议补充备注说明]{建议}`:仅作提醒,不构成驳回条件。
|
||||
- `[金额大于10万需特殊说明]{特殊}`:直接触发人工会签或复核分支。
|
||||
@@ -2,6 +2,21 @@
|
||||
|
||||
本参考专卷详细说明 `hose-use` 的登录鉴权、会话维护、代客凭证、企业租户切换以及全局运行模式。
|
||||
|
||||
## 0. 全局运行上下文与环境自省 (`context`)
|
||||
|
||||
面向开发者与 AI 智能体的一键自省命令。**无需翻阅任何源码**即可直接获知当前登录主账号、当前激活企业、操作工号、Token 状态、多企业列表统计、AI PRO 规约库及配置文件路径。
|
||||
|
||||
```bash
|
||||
# 文本格式仪表盘
|
||||
hose-use context
|
||||
|
||||
# 结构化 JSON 输出 (推荐 Agent 首选使用)
|
||||
hose-use context --json
|
||||
```
|
||||
|
||||
- **别名**:`hose-use status`, `hose-use whoami`, `hose-use env`
|
||||
- **两端互通**:`hose-use` 与 `hose-aipro` 共享同一套企业与身份凭证上下文。
|
||||
|
||||
---
|
||||
|
||||
## 1. 账号认证与登录 (`auth`)
|
||||
@@ -27,6 +42,19 @@ hose-use auth refresh
|
||||
```
|
||||
- 主动调用主站会话刷新接口,续期当前企业凭据的 AccessToken。
|
||||
|
||||
### 第三方免密/协助链接一键导入 (`corps add-link` / `auth add-link`)
|
||||
```bash
|
||||
# 直接粘贴企业微信免密、合思代客或协助 thirdparty.html 链接
|
||||
hose-use corps add-link "https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=...&ekbCorpId=..."
|
||||
|
||||
# 可选附加别名与覆盖参数
|
||||
hose-use corps add-link "<url>" --name="客户企业别名" --overwrite
|
||||
```
|
||||
- **全自动识别与身份探测**:
|
||||
- 自动从 URL 提取服务节点 `baseUrl`、集群环境 `cluster`(如 `wx2`、`app`)、`accessToken` 与 `corpId`;
|
||||
- 自动向 `$UNITY` JWT 与主站 Session 反查员工工号 (`staffId`)、员工姓名、绑定手机、企业全称与是否企业管理员,无需手动寻找工号;
|
||||
- 动态自适应多集群环境换票,确保主站单据审批与 EASO 低代码工作流平台权限全绿连通。
|
||||
|
||||
### 代客协助凭证导入
|
||||
```bash
|
||||
hose-use auth import \
|
||||
@@ -35,7 +63,7 @@ hose-use auth import \
|
||||
--staff-id="Cxa3oOtQi2eS$g:2HQbkGx2DgnM00" \
|
||||
--token="1361c470-3d7c-4a3a-a1fb-e946aee5723b"
|
||||
```
|
||||
- **智能探测机制**:若 `corp-id` 包含 `$UNITY` 或特殊字符,系统会自动探测代客服务会话接口,解析 13 位过期毫秒时间戳并正确建立凭证映射。
|
||||
- **智能探测机制**:若 `corp-id` 包含 `$UNITY` 或特殊字符,系统会自动探测代客服务会话接口,解析 13 位过期毫秒时间戳并正确建立凭证映射。也可直接传入抓包 cURL 或包含 URL 的文本。
|
||||
|
||||
### 多账号清单
|
||||
```bash
|
||||
|
||||
@@ -112,4 +112,40 @@ describe("CLI - hose-aipro 审批流与网关阻拦全链路测试", () => {
|
||||
expect(actions).toContain("review");
|
||||
expect(actions).toContain("decide");
|
||||
});
|
||||
|
||||
test("门禁防御:单据无硬性或弹性违规时,尝试执行 reject 必须被网关阻断(禁止无因驳回)", async () => {
|
||||
const db = getApprovalDatabase(":memory:");
|
||||
const repo = new ApprovalRepository(db);
|
||||
|
||||
const run = repo.createApprovalRun({
|
||||
documentSn: "CLEAN-BILL-001",
|
||||
corpId: "test-corp",
|
||||
documentSnapshot: "# 正常单据快照",
|
||||
});
|
||||
const runId = run.shortId!;
|
||||
|
||||
// 挂载规则 1 并打标为全部 PASS
|
||||
await runAiProCli(["bind", "--run", runId, "--rules", "[1]"]);
|
||||
await runAiProCli([
|
||||
"review",
|
||||
"--run",
|
||||
runId,
|
||||
"--eval",
|
||||
"1=PASS:发票已上传; 2=PASS:事由已补充",
|
||||
]);
|
||||
|
||||
// 尝试在无违规情况下驳回,必须被网关拦截
|
||||
const blockReject = await runAiProCli([
|
||||
"decide",
|
||||
"reject",
|
||||
"--run",
|
||||
runId,
|
||||
"--opinion",
|
||||
"单据完全合规但尝试无故驳回",
|
||||
]);
|
||||
|
||||
expect(blockReject.exitCode).toBe(1);
|
||||
expect(blockReject.stderr).toContain("不存在任何【硬性】或【弹性】违规条款");
|
||||
expect(blockReject.stderr).toContain("严禁无故或恶意驳回");
|
||||
});
|
||||
});
|
||||
+100
-28
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env bun
|
||||
import { parseArgs, stringOption, booleanOption, numberOption } from "./cli/parser.js";
|
||||
import { printJson, printTable, redactSensitiveText } from "./cli/printer.js";
|
||||
import { printJson, printTable, redactSensitiveText, formatExpiresAt } from "./cli/printer.js";
|
||||
import { initCorpRuntime } from "./cli/helpers.js";
|
||||
import { createEkbClient } from "./core/auth/ekb.js";
|
||||
import {
|
||||
@@ -12,9 +12,10 @@ import {
|
||||
CreateFindingInput,
|
||||
RuleRecord,
|
||||
parseRuleBody,
|
||||
validateGatewayAction,
|
||||
} from "./domains/approval/index.js";
|
||||
import { getRawBillFlow } from "./domains/bill/api.js";
|
||||
import { approveBill, rejectBill } from "./domains/bill/tools.js";
|
||||
import { approveBill, rejectBill, getTranslatorContext } from "./domains/bill/tools.js";
|
||||
import { translateBillFlowToMarkdown } from "./domains/bill/translator.js";
|
||||
import { VERSION } from "./version.js";
|
||||
|
||||
@@ -55,7 +56,7 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string;
|
||||
const targetSn = positional[1] || stringOption(parsed.options, ["code", "sn", "id", "target"]);
|
||||
const args = positional.slice(1);
|
||||
const corpId = corp?.corpId || corp?.id;
|
||||
const operator = corp?.staffId || corp?.name || "AI-Agent";
|
||||
const operator = corp?.credentials?.staffId || corp?.staffId || corp?.name || "AI-Agent";
|
||||
|
||||
const requireCorpId = () => {
|
||||
if (!corpId) {
|
||||
@@ -73,6 +74,81 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string;
|
||||
|
||||
try {
|
||||
switch (command) {
|
||||
// ── 0. 运行时上下文与身份诊断 (status / whoami / context / info) ────────
|
||||
case "status":
|
||||
case "whoami":
|
||||
case "context":
|
||||
case "info": {
|
||||
const scopes = repo.listScopes("active");
|
||||
const rules = repo.listRules();
|
||||
const runs = corpId ? repo.listRuns({ corpId }) : repo.listRuns();
|
||||
const pendingRuns = runs.filter((r) => r.decision === "PENDING");
|
||||
const recentLogs = repo.listAiProLogs(undefined, 5);
|
||||
const isJson = runtime.jsonMode || booleanOption(parsed.options, ["json", "j"]);
|
||||
|
||||
const corpStaffId = corp?.credentials?.staffId || corp?.staffId || "-";
|
||||
const corpStaffName = corp?.staffName || corp?.session?.staffName || null;
|
||||
const corpExpiresAt = corp?.auth?.expiresAt || corp?.session?.expTime;
|
||||
|
||||
if (isJson) {
|
||||
return {
|
||||
stdout: JSON.stringify(
|
||||
{
|
||||
tool: "hose-aipro",
|
||||
version: VERSION,
|
||||
corp: corp
|
||||
? {
|
||||
id: corp.id,
|
||||
name: corp.name,
|
||||
staffId: corpStaffId,
|
||||
userName: corpStaffName,
|
||||
source: corp.source,
|
||||
expiresAt: corpExpiresAt,
|
||||
expired: corpExpiresAt ? corpExpiresAt <= Date.now() : false,
|
||||
baseUrl: corp.baseUrl,
|
||||
}
|
||||
: null,
|
||||
operator,
|
||||
ruleEngine: {
|
||||
scopesCount: scopes.length,
|
||||
rulesCount: rules.length,
|
||||
scopes: scopes.map((s) => ({ index: s.index, scope: s.scope, ruleCount: s.ruleCount })),
|
||||
},
|
||||
sessions: {
|
||||
total: runs.length,
|
||||
pending: pendingRuns.length,
|
||||
},
|
||||
recentLogsCount: recentLogs.length,
|
||||
},
|
||||
null,
|
||||
2
|
||||
) + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const lines = [
|
||||
`====== 合思 AI PRO 确定性审批网关运行上下文 (v${VERSION}) ======`,
|
||||
` 当前连接企业 : ${corp ? `${corp.name} (${corp.id})` : "⚠️ 未指定企业"}`,
|
||||
` 当前操作工号 : ${corpStaffId}`,
|
||||
` 操作员标识 : ${operator}`,
|
||||
` 凭证有效状态 : ${corp ? formatExpiresAt(corpExpiresAt) : "-"}`,
|
||||
` 主站 BaseURL : ${corp?.baseUrl || "-"}`,
|
||||
` 规约场景库 : 已加载 ${scopes.length} 个场景 (${scopes.map((s) => `#${s.index} ${s.scope}`).join(", ") || "无"}),共 ${rules.length} 条仲裁规则`,
|
||||
` 未结审批会话 : ${pendingRuns.length} 个待决断会话 (当前企业历史总会话: ${runs.length} 个)`,
|
||||
"",
|
||||
"提示:",
|
||||
" - 查看规约场景列表: hose-aipro scopes",
|
||||
" - 切换全局工作企业: hose-use corps switch <企业ID>",
|
||||
" - 临时指定执行企业: hose-aipro --corp=<企业ID> <子命令>",
|
||||
" - 单据审批全流程 : hose-aipro bind <单号> <索引号> -> hose-aipro review -> hose-aipro decide",
|
||||
"",
|
||||
];
|
||||
|
||||
return { stdout: lines.join("\n"), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
// ── 1. 初始化审批实例会话(签发 6 位短 ID,有效期 6 小时)──────────────
|
||||
case "init":
|
||||
case "start": {
|
||||
@@ -88,7 +164,8 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string;
|
||||
const flowIdObj = (raw.flowId && typeof raw.flowId === "object" ? raw.flowId : raw) as Record<string, any>;
|
||||
const form = (flowIdObj.form && typeof flowIdObj.form === "object" ? flowIdObj.form : {}) as Record<string, any>;
|
||||
const title = form.title || flowIdObj.title || "<无标题>";
|
||||
const snapshot = translateBillFlowToMarkdown(raw);
|
||||
const translatorContext = await getTranslatorContext(context.client, context.corpId, raw).catch(() => undefined);
|
||||
const snapshot = translateBillFlowToMarkdown(raw, translatorContext);
|
||||
|
||||
// 创建全新独立运行实例 (永久长 ID + 6 位短 ID, 6 小时有效期)
|
||||
const run = repo.createApprovalRun({
|
||||
@@ -222,7 +299,8 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string;
|
||||
if (!raw) {
|
||||
throw new Error(`在当前企业下未找到单号或 ID 为 [${targetSn}] 的单据`);
|
||||
}
|
||||
const markdown = translateBillFlowToMarkdown(raw);
|
||||
const translatorContext = await getTranslatorContext(context.client, context.corpId, raw).catch(() => undefined);
|
||||
const markdown = translateBillFlowToMarkdown(raw, translatorContext);
|
||||
|
||||
repo.logAiProAction({
|
||||
action: "translate",
|
||||
@@ -878,31 +956,15 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string;
|
||||
throw new Error("必须提供小于 150 字的审批意见: --opinion '<审批意见>'");
|
||||
}
|
||||
|
||||
if (opinion.length > 150) {
|
||||
throw new Error(`[参数校验阻断] 审批意见不可超过 150 字符,当前长度为 ${opinion.length} 字符,请精简。`);
|
||||
}
|
||||
|
||||
const findings = repo.getFindingsByRunId(runRecord.id);
|
||||
if (findings.length === 0) {
|
||||
throw new Error(`[网关安全阻断] 会话 [${runRecord.shortId || runRecord.id}] 尚未挂载任何规约审核要点,审批链路物理不通!请先执行 bind 挂载。`);
|
||||
}
|
||||
|
||||
// 网关刚性阻拦检查(它只阻拦,不决断)
|
||||
if (action === "APPROVE") {
|
||||
// 门禁 1: 漏检拦截
|
||||
const pendingFindings = findings.filter((f) => f.checkStatus === "PENDING");
|
||||
if (pendingFindings.length > 0) {
|
||||
const pendingIndices = pendingFindings.map((f) => `#${findings.indexOf(f) + 1}`).join(", ");
|
||||
throw new Error(`[网关安全阻断] 尚有 ${pendingFindings.length} 处审核要点处于“待核验”状态(要点 ${pendingIndices}),禁止盲目放行同意!`);
|
||||
}
|
||||
|
||||
// 门禁 2: 硬性一票否决
|
||||
const hardFailed = findings.filter((f) => f.checkStatus === "FAIL" && f.strictness === "硬性");
|
||||
if (hardFailed.length > 0) {
|
||||
const failedNames = hardFailed.map((f) => `【#${findings.indexOf(f) + 1} ${f.clauseText}】`).join("、");
|
||||
throw new Error(`[网关安全阻断] 单据存在硬性违规条款未通过(${failedNames}),物理切断“同意”流转,绝对禁止放行!`);
|
||||
}
|
||||
}
|
||||
// 网关刚性安全门禁检查(统一由可配置网关 TS 策略执行:意见长度、待核验漏检、硬性违规禁止同意、无硬性/弹性违规禁止驳回)
|
||||
validateGatewayAction({
|
||||
documentSn: runRecord.documentSn,
|
||||
findings,
|
||||
requestedAction: action === "APPROVE" ? "approve" : "reject",
|
||||
opinion,
|
||||
});
|
||||
|
||||
// Apply execution
|
||||
const apply = booleanOption(parsed.options, ["apply", "execute", "run", "do"]);
|
||||
@@ -1036,11 +1098,21 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string;
|
||||
// ── 7. 帮助 ───────────────────────────────────────────────────────────
|
||||
case "help":
|
||||
default: {
|
||||
const corpExpiresAt = corp?.auth?.expiresAt || corp?.session?.expTime;
|
||||
const corpBanner = corp
|
||||
? `[当前连接企业: ${corp.name} (${corp.id}) | 操作人: ${operator} | 凭证状态: ${formatExpiresAt(corpExpiresAt)}]\n[全局切换: hose-use corps switch <企业ID> | 临时指定: hose-aipro --corp=<企业ID>]`
|
||||
: `[当前企业: 未指定 | 请先运行 hose-use auth login 或带上 --corp=<企业ID>]`;
|
||||
|
||||
const helpText = `
|
||||
合思 AI PRO 确定性审批仲裁网关 CLI (hose-aipro) v${VERSION}
|
||||
一切操作在本地 SQLite 强受控、全流程监控、不可篡改审计留痕。
|
||||
|
||||
${corpBanner}
|
||||
|
||||
核心工作流:
|
||||
0. 查看 AI PRO 运行上下文与当前绑定企业:
|
||||
hose-aipro status # 查看当前企业、操作人、规则库统计与待办会话
|
||||
|
||||
1. 查看规约场景索引库 (获取规则索引号):
|
||||
hose-aipro scopes # 列出所有场景索引 (Index / Scope / 规则数)
|
||||
|
||||
|
||||
+68
-42
@@ -5,6 +5,7 @@ import {
|
||||
sendSmsVerificationCode,
|
||||
importCredentials,
|
||||
importF12Credentials,
|
||||
importFromLink,
|
||||
parseHeadersOrCurl,
|
||||
refreshAccountCorporations,
|
||||
} from "../../core/auth/login.js";
|
||||
@@ -35,6 +36,8 @@ export async function handleAuthCommand(
|
||||
return handleRefresh(parsed, runtime);
|
||||
case "import":
|
||||
return handleImport(parsed, runtime);
|
||||
case "add-link":
|
||||
return handleAddLink(parsed, runtime);
|
||||
case "accounts":
|
||||
return handleAccounts(parsed, runtime);
|
||||
case "switch-account":
|
||||
@@ -42,7 +45,7 @@ export async function handleAuthCommand(
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 auth 子命令: ${action}。支持: login, status, refresh, import, accounts, switch-account\n`,
|
||||
stderr: `未知 auth 子命令: ${action}。支持: login, status, refresh, import, add-link, accounts, switch-account\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
@@ -231,69 +234,92 @@ async function handleRefresh(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
||||
}
|
||||
|
||||
async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
let raw = stringOption(parsed.options, ["raw", "headers", "curl"]);
|
||||
let raw = parsed.args[0] || stringOption(parsed.options, ["raw", "headers", "curl", "url", "link"]);
|
||||
let accessToken = stringOption(parsed.options, ["token", "accessToken"]);
|
||||
let corpId = stringOption(parsed.options, ["corp", "corpId"]);
|
||||
let staffId = stringOption(parsed.options, ["staff", "staffId"]);
|
||||
let name = stringOption(parsed.options, ["name"]);
|
||||
const overwrite = booleanOption(parsed.options, ["overwrite", "force", "f"], false);
|
||||
|
||||
if (!raw && !accessToken) {
|
||||
raw = await prompt("请粘贴抓包文本 / cURL 命令行 (直接回车则手动逐项输入): ");
|
||||
if (!raw && !accessToken && process.stdin.isTTY) {
|
||||
raw = await prompt("请粘贴抓包文本 / cURL 命令行 / 协助免密 URL (直接回车则手动逐项输入): ");
|
||||
}
|
||||
|
||||
let baseUrl: string | undefined;
|
||||
|
||||
if (raw) {
|
||||
const parsedObj = parseHeadersOrCurl(raw);
|
||||
if (parsedObj.accessToken) accessToken = parsedObj.accessToken;
|
||||
if (parsedObj.corpId) corpId = parsedObj.corpId;
|
||||
if (parsedObj.staffId) staffId = parsedObj.staffId;
|
||||
if (parsedObj.baseUrl) baseUrl = parsedObj.baseUrl;
|
||||
}
|
||||
|
||||
if (!accessToken) accessToken = await prompt("请输入 accessToken: ");
|
||||
if (!corpId) corpId = await prompt("请输入 corpId: ");
|
||||
if (!staffId) staffId = await prompt("请输入 staffId: ");
|
||||
if (!accessToken && process.stdin.isTTY) accessToken = await prompt("请输入 accessToken: ");
|
||||
if (!corpId && process.stdin.isTTY) corpId = await prompt("请输入 corpId: ");
|
||||
|
||||
if (!accessToken || !corpId || !staffId) {
|
||||
return { stdout: "", stderr: "accessToken, corpId, staffId 均为必填!\n", exitCode: 1 };
|
||||
if (!accessToken || !corpId) {
|
||||
return { stdout: "", stderr: "accessToken 与 corpId 均为必填!\n", exitCode: 1 };
|
||||
}
|
||||
|
||||
const imported = await importCredentials({
|
||||
accessToken,
|
||||
corpId,
|
||||
staffId,
|
||||
name,
|
||||
});
|
||||
try {
|
||||
const imported = await importCredentials({
|
||||
accessToken,
|
||||
corpId,
|
||||
staffId,
|
||||
name,
|
||||
baseUrl,
|
||||
overwrite,
|
||||
source: raw && (raw.startsWith("http://") || raw.startsWith("https://")) ? "link" : undefined,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(imported), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const summaryPairs: Record<string, unknown> = {
|
||||
"企业名称": imported.name,
|
||||
"企业 ID": imported.id,
|
||||
"员工工号": imported.credentials.staffId,
|
||||
"员工姓名": imported.staffName || imported.session?.staffName || "-",
|
||||
"凭证来源": formatSourceLabel(imported.source),
|
||||
"过期时间": formatExpiresAt(imported.auth?.expiresAt || imported.session?.expTime),
|
||||
"保存路径": `enterprises/${imported.id}.json`,
|
||||
};
|
||||
|
||||
if (imported.session?.isAssistPlatform) {
|
||||
summaryPairs["协助平台"] = "是 (Assist Platform 调试授权)";
|
||||
if (imported.session.operationUserName || imported.session.operationUserId) {
|
||||
summaryPairs["协助操作人"] = `${imported.session.operationUserName || ""} (${imported.session.operationUserId || ""})`.trim();
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(imported, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
if (imported.session.assistId) {
|
||||
summaryPairs["协助会话 ID"] = imported.session.assistId;
|
||||
|
||||
const summaryPairs: Record<string, unknown> = {
|
||||
"企业名称": imported.name,
|
||||
"企业 ID": imported.id,
|
||||
"集群环境": imported.cluster || "app",
|
||||
"员工工号": imported.credentials.staffId,
|
||||
"员工姓名": imported.staffName || imported.session?.staffName || "-",
|
||||
"手机号码": imported.session?.cellphone || "-",
|
||||
"是否管理": imported.session?.isAdmin ? "是" : "否",
|
||||
"凭证来源": formatSourceLabel(imported.source),
|
||||
"服务节点": imported.baseUrl,
|
||||
"过期时间": formatExpiresAt(imported.auth?.expiresAt || imported.session?.expTime),
|
||||
"保存路径": `enterprises/${imported.id}.json`,
|
||||
};
|
||||
|
||||
if (imported.session?.isAssistPlatform) {
|
||||
summaryPairs["协助平台"] = "是 (Assist Platform 调试授权)";
|
||||
if (imported.session.operationUserName || imported.session.operationUserId) {
|
||||
summaryPairs["协助操作人"] = `${imported.session.operationUserName || ""} (${imported.session.operationUserId || ""})`.trim();
|
||||
}
|
||||
if (imported.session.assistId) {
|
||||
summaryPairs["协助会话 ID"] = imported.session.assistId;
|
||||
}
|
||||
}
|
||||
|
||||
const summaryText = printKeyValue(summaryPairs);
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] 成功导入并保存企业凭证!\n${summaryText}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[ERROR] 导入凭证失败: ${error instanceof Error ? error.message : String(error)}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const summaryText = printKeyValue(summaryPairs);
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] 成功导入并保存企业凭证!\n${summaryText}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const linkUrl = parsed.args[0] || stringOption(parsed.options, ["url", "link"]);
|
||||
return handleImport({ ...parsed, args: linkUrl ? [linkUrl] : [] }, runtime);
|
||||
}
|
||||
|
||||
async function handleAccounts(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { runCli } from "../runner.js";
|
||||
import { runAiProCli } from "../../aipro-cli.js";
|
||||
import { closeApprovalDatabase, getApprovalDatabase } from "../../domains/approval/db.js";
|
||||
import { ApprovalRepository } from "../../domains/approval/repository.js";
|
||||
|
||||
describe("CLI - 上下文自省与 AI PRO 状态命令 (Zero-Source-Reading Context)", () => {
|
||||
beforeEach(() => {
|
||||
process.env.HOSE_APPROVAL_DB = ":memory:";
|
||||
const db = getApprovalDatabase(":memory:");
|
||||
const repo = new ApprovalRepository(db);
|
||||
|
||||
repo.createRule({
|
||||
scope: "差旅报销",
|
||||
body: "差旅报销时,[必须上传发票]{硬性}。",
|
||||
});
|
||||
repo.createRule({
|
||||
scope: "业务招待",
|
||||
body: "招待报销时,[必须提供餐饮点餐水单]{硬性}。",
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
closeApprovalDatabase();
|
||||
delete process.env.HOSE_APPROVAL_DB;
|
||||
});
|
||||
|
||||
test("hose-use context 打印文本格式仪表盘", async () => {
|
||||
const res = await runCli(["context"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("全局运行上下文与身份诊断");
|
||||
expect(res.stdout).toContain("AI PRO 规约库");
|
||||
expect(res.stdout).toContain("差旅报销");
|
||||
expect(res.stdout).toContain("业务招待");
|
||||
});
|
||||
|
||||
test("hose-use context --json 输出完备的结构化数据", async () => {
|
||||
const res = await runCli(["context", "--json"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
|
||||
const data = JSON.parse(res.stdout);
|
||||
expect(data.tool).toBe("hose-use");
|
||||
expect(data.corporationsSummary).toBeDefined();
|
||||
expect(data.aiProGateway).toBeDefined();
|
||||
expect(data.aiProGateway.scopesCount).toBe(2);
|
||||
expect(data.aiProGateway.rulesCount).toBe(2);
|
||||
expect(data.runtime.mode).toBeDefined();
|
||||
expect(data.runtime.configFile).toBeDefined();
|
||||
});
|
||||
|
||||
test("hose-use status 与 whoami 别名成功解析至 context", async () => {
|
||||
const resStatus = await runCli(["status", "--json"]);
|
||||
expect(resStatus.exitCode).toBe(0);
|
||||
const dataStatus = JSON.parse(resStatus.stdout);
|
||||
expect(dataStatus.tool).toBe("hose-use");
|
||||
|
||||
const resWhoami = await runCli(["whoami", "--json"]);
|
||||
expect(resWhoami.exitCode).toBe(0);
|
||||
const dataWhoami = JSON.parse(resWhoami.stdout);
|
||||
expect(dataWhoami.tool).toBe("hose-use");
|
||||
});
|
||||
|
||||
test("hose-aipro status 输出 AI PRO 专属上下文", async () => {
|
||||
const res = await runAiProCli(["status"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("合思 AI PRO 确定性审批网关运行上下文");
|
||||
expect(res.stdout).toContain("规约场景库");
|
||||
expect(res.stdout).toContain("差旅报销");
|
||||
});
|
||||
|
||||
test("hose-aipro status --json 输出结构化数据", async () => {
|
||||
const res = await runAiProCli(["status", "--json"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
|
||||
const data = JSON.parse(res.stdout);
|
||||
expect(data.tool).toBe("hose-aipro");
|
||||
expect(data.ruleEngine.scopesCount).toBe(2);
|
||||
expect(data.ruleEngine.rulesCount).toBe(2);
|
||||
expect(data.sessions).toBeDefined();
|
||||
});
|
||||
|
||||
test("hose-use aipro status 双向桥接成功转发", async () => {
|
||||
const res = await runCli(["aipro", "status", "--json"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
|
||||
const data = JSON.parse(res.stdout);
|
||||
expect(data.tool).toBe("hose-aipro");
|
||||
expect(data.ruleEngine.scopesCount).toBe(2);
|
||||
});
|
||||
|
||||
test("hose-aipro 帮助页在顶部动态展示当前企业页眉", async () => {
|
||||
const res = await runAiProCli(["help"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("[当前");
|
||||
expect(res.stdout).toContain("hose-aipro status");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,152 @@
|
||||
import { getActiveAccount } from "../../core/auth/account-store.js";
|
||||
import {
|
||||
resolveGlobalConfigFile,
|
||||
resolvePrimaryEnterprisesDir,
|
||||
resolveWritableEnterprisesDir,
|
||||
getEnterprisesDirCandidates,
|
||||
} from "../../core/config/loader.js";
|
||||
import { ApprovalRepository } from "../../domains/approval/index.js";
|
||||
import { VERSION } from "../../version.js";
|
||||
import { formatExpiresAt, formatSourceLabel, printJson } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
|
||||
export async function handleContextCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const currentCorp = runtime.selectedCorp;
|
||||
const allCorps = runtime.corpContext.listCorps();
|
||||
const activeAccount = getActiveAccount();
|
||||
const isStateful = runtime.corpContext.isStateful();
|
||||
const configFile = resolveGlobalConfigFile();
|
||||
const enterprisesDir = resolvePrimaryEnterprisesDir() || resolveWritableEnterprisesDir();
|
||||
|
||||
let scopesCount = 0;
|
||||
let rulesCount = 0;
|
||||
let scopes: Array<{ index: number; scope: string; ruleCount: number }> = [];
|
||||
let totalRunsCount = 0;
|
||||
let pendingRunsCount = 0;
|
||||
|
||||
try {
|
||||
const repo = new ApprovalRepository();
|
||||
const loadedScopes = repo.listScopes("active");
|
||||
scopesCount = loadedScopes.length;
|
||||
scopes = loadedScopes.map((s) => ({
|
||||
index: s.index,
|
||||
scope: s.scope,
|
||||
ruleCount: s.ruleCount,
|
||||
}));
|
||||
const loadedRules = repo.listRules();
|
||||
rulesCount = loadedRules.length;
|
||||
|
||||
const runs = currentCorp?.id ? repo.listRuns({ corpId: currentCorp.id }) : repo.listRuns();
|
||||
totalRunsCount = runs.length;
|
||||
pendingRunsCount = runs.filter((r) => r.decision === "PENDING").length;
|
||||
} catch {
|
||||
// 容错处理(如 SQLite 尚未初始化等场景)
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const validCorps = allCorps.filter((c) => !c.expiresAt || c.expiresAt > now);
|
||||
const expiredCorps = allCorps.filter((c) => c.expiresAt && c.expiresAt <= now);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
tool: "hose-use",
|
||||
version: VERSION,
|
||||
account: activeAccount
|
||||
? {
|
||||
accountId: activeAccount.accountId,
|
||||
userId: activeAccount.userId || null,
|
||||
corporationCount: activeAccount.corporations.length,
|
||||
}
|
||||
: currentCorp?.accountId
|
||||
? {
|
||||
accountId: currentCorp.accountId,
|
||||
userId: null,
|
||||
corporationCount: allCorps.filter((c) => c.accountId === currentCorp.accountId).length,
|
||||
}
|
||||
: null,
|
||||
activeCorporation: currentCorp
|
||||
? {
|
||||
id: currentCorp.id,
|
||||
name: currentCorp.name,
|
||||
staffId: currentCorp.credentials?.staffId || currentCorp.staffId,
|
||||
userName: currentCorp.staffName || currentCorp.session?.staffName || null,
|
||||
source: currentCorp.source,
|
||||
expiresAt: currentCorp.auth?.expiresAt || currentCorp.session?.expTime,
|
||||
expired:
|
||||
(currentCorp.auth?.expiresAt || currentCorp.session?.expTime)
|
||||
? (currentCorp.auth?.expiresAt || currentCorp.session?.expTime)! <= now
|
||||
: false,
|
||||
baseUrl: currentCorp.baseUrl,
|
||||
accountId: currentCorp.accountId || null,
|
||||
}
|
||||
: null,
|
||||
corporationsSummary: {
|
||||
total: allCorps.length,
|
||||
validCount: validCorps.length,
|
||||
expiredCount: expiredCorps.length,
|
||||
activeCorpId: currentCorp?.id || null,
|
||||
},
|
||||
aiProGateway: {
|
||||
connectedCorpId: currentCorp?.id || null,
|
||||
scopesCount,
|
||||
rulesCount,
|
||||
scopes,
|
||||
pendingRunsCount,
|
||||
totalRunsCount,
|
||||
},
|
||||
runtime: {
|
||||
mode: isStateful ? "stateful" : "stateless",
|
||||
configFile,
|
||||
enterprisesDir,
|
||||
candidates: getEnterprisesDirCandidates(),
|
||||
},
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const accountStr = activeAccount?.accountId || currentCorp?.accountId || "-";
|
||||
const userIdStr = activeAccount?.userId ? ` (用户 ID: ${activeAccount.userId})` : "";
|
||||
const corpStaffId = currentCorp?.credentials?.staffId || currentCorp?.staffId || "-";
|
||||
const corpStaffName = currentCorp?.staffName || currentCorp?.session?.staffName || "-";
|
||||
const corpExpiresAt = currentCorp?.auth?.expiresAt || currentCorp?.session?.expTime;
|
||||
|
||||
const scopesStr =
|
||||
scopes.length > 0
|
||||
? `已加载 ${scopesCount} 个场景 (${scopes.map((s) => `#${s.index} ${s.scope}`).join(", ")}),共 ${rulesCount} 条仲裁规则`
|
||||
: "暂未配置场景规则 (可使用 hose-use rule add 添加)";
|
||||
|
||||
const lines = [
|
||||
`====== 全局运行上下文与身份诊断 (hose-use v${VERSION}) ======`,
|
||||
` 当前活跃账号 : ${accountStr}${userIdStr}`,
|
||||
` 当前激活企业 : ${currentCorp ? `${currentCorp.name} (${currentCorp.id})` : "⚠️ 未激活任何企业"}`,
|
||||
` 当前操作员工 : ${corpStaffId}`,
|
||||
` 员工真实姓名 : ${corpStaffName}`,
|
||||
` 凭证来源类型 : ${currentCorp ? formatSourceLabel(currentCorp.source) : "-"}`,
|
||||
` 凭证有效状态 : ${currentCorp ? formatExpiresAt(corpExpiresAt) : "-"}`,
|
||||
` 主站 BaseURL : ${currentCorp?.baseUrl || "-"}`,
|
||||
` 已配置企业总数: ${allCorps.length} 家 (有效: ${validCorps.length} 家, 已过期: ${expiredCorps.length} 家)`,
|
||||
` AI PRO 规约库 : ${scopesStr}`,
|
||||
` AI PRO 待决断 : ${pendingRunsCount} 个待决断会话 (当前企业历史总会话: ${totalRunsCount} 个)`,
|
||||
` 运行模式设置 : ${isStateful ? "有状态模式 (Stateful - 自动记忆当前企业)" : "无状态模式 (Stateless)"}`,
|
||||
` 全局配置文件 : ${configFile}`,
|
||||
` 企业凭证目录 : ${enterprisesDir}`,
|
||||
"",
|
||||
"提示:",
|
||||
" - hose-use 与 hose-aipro 默认共享同一套企业与身份凭证上下文,无须重复配置。",
|
||||
" - 切换全局默认企业: hose-use corps switch <企业ID>",
|
||||
" - 单次临时指定企业: hose-use --corp=<企业ID> <命令> 或 hose-aipro --corp=<企业ID> <子命令>",
|
||||
" - AI PRO 专属上下文: hose-aipro status",
|
||||
"",
|
||||
];
|
||||
|
||||
return { stdout: lines.join("\n"), stderr: "", exitCode: 0 };
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { describe, it, expect } from "bun:test";
|
||||
import { parseHeadersOrCurl } from "../../core/auth/login.js";
|
||||
import { resolveCorpCluster } from "../../core/auth/easo.js";
|
||||
import { handleCorpsCommand } from "./corps.js";
|
||||
import type { CliRuntime } from "../types.js";
|
||||
|
||||
describe("core/auth/login > parseHeadersOrCurl & URL link parsing", () => {
|
||||
it("successfully parses standard thirdparty.html assistance links", () => {
|
||||
const url = "https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=token123&ekbCorpId=corpABC&pageType=home";
|
||||
const parsed = parseHeadersOrCurl(url);
|
||||
|
||||
expect(parsed.baseUrl).toBe("https://wx2.ekuaibao.com");
|
||||
expect(parsed.accessToken).toBe("token123");
|
||||
expect(parsed.corpId).toBe("corpABC");
|
||||
});
|
||||
|
||||
it("extracts custom staffId and standard corpId query params", () => {
|
||||
const url = "https://app.ekuaibao.com/thirdparty.html?token=secret999&corpId=corpXYZ&staffId=corpXYZ:user1";
|
||||
const parsed = parseHeadersOrCurl(url);
|
||||
|
||||
expect(parsed.baseUrl).toBe("https://app.ekuaibao.com");
|
||||
expect(parsed.accessToken).toBe("secret999");
|
||||
expect(parsed.corpId).toBe("corpXYZ");
|
||||
expect(parsed.staffId).toBe("corpXYZ:user1");
|
||||
});
|
||||
|
||||
it("handles curl command lines with assistance URL", () => {
|
||||
const curl = `curl "https://wx.ekuaibao.com/web/thirdparty.html?accessToken=testToken&ekbCorpId=testCorp" -H "User-Agent: Mozilla"`;
|
||||
const parsed = parseHeadersOrCurl(curl);
|
||||
|
||||
expect(parsed.baseUrl).toBe("https://wx.ekuaibao.com");
|
||||
expect(parsed.accessToken).toBe("testToken");
|
||||
expect(parsed.corpId).toBe("testCorp");
|
||||
});
|
||||
});
|
||||
|
||||
describe("core/auth/easo > resolveCorpCluster", () => {
|
||||
it("prioritizes explicit cluster config", () => {
|
||||
expect(resolveCorpCluster({ cluster: "wx2", baseUrl: "https://app.ekuaibao.com" })).toBe("wx2");
|
||||
});
|
||||
|
||||
it("extracts cluster from hostname subdomain", () => {
|
||||
expect(resolveCorpCluster({ baseUrl: "https://wx2.ekuaibao.com" })).toBe("wx2");
|
||||
expect(resolveCorpCluster({ baseUrl: "https://wx.ekuaibao.com" })).toBe("wx");
|
||||
expect(resolveCorpCluster({ baseUrl: "https://app.ekuaibao.com" })).toBe("app");
|
||||
});
|
||||
|
||||
it("falls back to app when unknown", () => {
|
||||
expect(resolveCorpCluster({})).toBe("app");
|
||||
expect(resolveCorpCluster({ baseUrl: "https://custom-domain.com" })).toBe("app");
|
||||
});
|
||||
});
|
||||
|
||||
describe("cli/commands/corps > handleCorpsCommand add-link", () => {
|
||||
const dummyRuntime: CliRuntime = {
|
||||
corpContext: {
|
||||
listCorps: () => [],
|
||||
getCurrent: () => null,
|
||||
switchCorp: () => false,
|
||||
resolve: () => null,
|
||||
} as any,
|
||||
selectedCorp: null,
|
||||
jsonMode: false,
|
||||
};
|
||||
|
||||
it("returns error exit code when no link URL is provided", async () => {
|
||||
const res = await handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
action: "add-link",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["corps", "add-link"],
|
||||
},
|
||||
dummyRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(1);
|
||||
expect(res.stderr).toContain("必须提供协助/免密链接 URL");
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,6 @@
|
||||
import { importFromLink } from "../../core/auth/login.js";
|
||||
import { stringOption, booleanOption } from "../parser.js";
|
||||
import { prompt } from "../helpers.js";
|
||||
import { printJson, printKeyValue, printTable, formatSourceLabel, formatExpiresAt } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
|
||||
@@ -15,10 +18,12 @@ export async function handleCorpsCommand(
|
||||
return handleSwitch(parsed, runtime);
|
||||
case "current":
|
||||
return handleCurrent(parsed, runtime);
|
||||
case "add-link":
|
||||
return handleAddLink(parsed, runtime);
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 corps 子命令: ${action}。支持: list, switch, current\n`,
|
||||
stderr: `未知 corps 子命令: ${action}。支持: list, switch, current, add-link\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
@@ -61,7 +66,7 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
|
||||
);
|
||||
|
||||
return {
|
||||
stdout: `====== 已配置企业列表 (${corps.length} 家) ======\n${table}\n\n提示: 使用 hose-use corps switch <企业ID> 切换工作企业\n`,
|
||||
stdout: `====== 已配置企业列表 (${corps.length} 家) ======\n${table}\n\n提示:\n - 标记 * 为当前激活企业(同时作为 hose-use 与 hose-aipro 的统一默认执行上下文)\n - 使用 hose-use corps switch <企业ID> 切换工作企业\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
@@ -113,6 +118,7 @@ async function handleCurrent(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
||||
"Token 过期时间": formatExpiresAt(current.auth?.expiresAt || current.session?.expTime),
|
||||
"所属账号": current.accountId || "-",
|
||||
"主站地址": current.baseUrl || "https://app.ekuaibao.com",
|
||||
"适用上下文": "同时作为 hose-use 与 hose-aipro 的统一执行环境",
|
||||
};
|
||||
|
||||
if (current.session) {
|
||||
@@ -147,3 +153,70 @@ async function handleCurrent(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
let linkUrl = parsed.args[0] || stringOption(parsed.options, ["url", "link"]);
|
||||
const name = stringOption(parsed.options, ["name"]);
|
||||
const overwrite = booleanOption(parsed.options, ["overwrite", "force", "f"], false);
|
||||
|
||||
if (!linkUrl && process.stdin.isTTY) {
|
||||
linkUrl = await prompt("请输入第三方协助/免密登录链接 URL: ");
|
||||
}
|
||||
|
||||
if (!linkUrl) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "错误:必须提供协助/免密链接 URL!用法: hose-use corps add-link <url> [--name <企业别名>] [--overwrite]\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const corp = await importFromLink(linkUrl, {
|
||||
name,
|
||||
overwrite,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(corp, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const summaryPairs: Record<string, unknown> = {
|
||||
"企业名称": corp.name,
|
||||
"企业 ID": corp.id,
|
||||
"集群环境": corp.cluster || "app",
|
||||
"员工工号": corp.credentials.staffId,
|
||||
"员工姓名": corp.staffName || corp.session?.staffName || "-",
|
||||
"手机号码": corp.session?.cellphone || "-",
|
||||
"是否管理": corp.session?.isAdmin ? "是" : "否",
|
||||
"凭证来源": formatSourceLabel(corp.source),
|
||||
"服务节点": corp.baseUrl,
|
||||
"过期时间": formatExpiresAt(corp.auth?.expiresAt || corp.session?.expTime),
|
||||
"保存路径": `enterprises/${corp.id}.json`,
|
||||
};
|
||||
|
||||
if (corp.session?.isAssistPlatform) {
|
||||
summaryPairs["协助平台"] = "是 (Assist Platform 调试授权)";
|
||||
if (corp.session.operationUserName || corp.session.operationUserId) {
|
||||
summaryPairs["协助操作人"] = `${corp.session.operationUserName || ""} (${corp.session.operationUserId || ""})`.trim();
|
||||
}
|
||||
if (corp.session.assistId) {
|
||||
summaryPairs["协助会话 ID"] = corp.session.assistId;
|
||||
}
|
||||
}
|
||||
|
||||
const summaryText = printKeyValue(summaryPairs);
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] 成功导入并保存企业凭证!\n${summaryText}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[ERROR] 导入协助链接失败: ${error instanceof Error ? error.message : String(error)}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
+47
-32
@@ -1,4 +1,5 @@
|
||||
import { createClientsForCorp } from "../helpers.js";
|
||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||
import { getEasoClient } from "../../core/auth/easo.js";
|
||||
import * as api from "../../domains/platform/api.js";
|
||||
import { printJson, printKeyValue, formatSourceLabel, formatExpiresAt } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
@@ -30,49 +31,63 @@ export async function handleProbeCommand(
|
||||
platformAccess: { status: "pending" },
|
||||
};
|
||||
|
||||
// 1. 独立测试 EKB 主站 Session
|
||||
let ekbClient: Awaited<ReturnType<typeof createEkbClient>> | null = null;
|
||||
try {
|
||||
const clients = await createClientsForCorp(currentCorp);
|
||||
ekbClient = await createEkbClient(currentCorp);
|
||||
const sessionRes = await ekbClient
|
||||
.get("api/account/v2/session")
|
||||
.json<{ value?: { userId?: string; loginStaffId?: string; expTime?: number } }>();
|
||||
|
||||
// 1. 测试 EKB 主站 Session
|
||||
results.ekbSession = {
|
||||
status: "ok",
|
||||
userId: sessionRes.value?.userId,
|
||||
loginStaffId: sessionRes.value?.loginStaffId,
|
||||
expTime: sessionRes.value?.expTime ? new Date(sessionRes.value.expTime).toLocaleString() : undefined,
|
||||
};
|
||||
} catch (e) {
|
||||
results.ekbSession = {
|
||||
status: "error",
|
||||
error: e instanceof Error ? e.message : String(e),
|
||||
};
|
||||
}
|
||||
|
||||
// 2. 独立测试自建应用列表访问
|
||||
let platforms: any[] = [];
|
||||
if (ekbClient) {
|
||||
try {
|
||||
const sessionRes = await clients.ekbClient
|
||||
.get("api/account/v2/session")
|
||||
.json<{ value?: { userId?: string; loginStaffId?: string; expTime?: number } }>();
|
||||
|
||||
results.ekbSession = {
|
||||
status: "ok",
|
||||
userId: sessionRes.value?.userId,
|
||||
loginStaffId: sessionRes.value?.loginStaffId,
|
||||
expTime: sessionRes.value?.expTime ? new Date(sessionRes.value.expTime).toLocaleString() : undefined,
|
||||
};
|
||||
} catch (e) {
|
||||
results.ekbSession = {
|
||||
status: "error",
|
||||
error: e instanceof Error ? e.message : String(e),
|
||||
};
|
||||
}
|
||||
|
||||
// 2. 测试 EASO Token 换取
|
||||
try {
|
||||
const platforms = await api.listPlatforms(clients.ekbClient, currentCorp.credentials.corpId);
|
||||
platforms = await api.listPlatforms(ekbClient, currentCorp.credentials.corpId);
|
||||
results.platformAccess = {
|
||||
status: "ok",
|
||||
totalPlatforms: platforms.length,
|
||||
};
|
||||
|
||||
const stats = await api.getWorkflowStats(clients.easoClient, platforms[0]?.id || "platform");
|
||||
results.easoToken = {
|
||||
status: "ok",
|
||||
message: "EASO 四步换票握手成功",
|
||||
};
|
||||
} catch (e) {
|
||||
results.easoToken = {
|
||||
results.platformAccess = {
|
||||
status: "error",
|
||||
error: e instanceof Error ? e.message : String(e),
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
results.error = error instanceof Error ? error.message : String(error);
|
||||
} else {
|
||||
results.platformAccess = {
|
||||
status: "error",
|
||||
error: "主站客户端未能初始化",
|
||||
};
|
||||
}
|
||||
|
||||
// 3. 独立测试 EASO Token 换取
|
||||
try {
|
||||
const { client: easoClient } = await getEasoClient(currentCorp);
|
||||
const targetPlatformId = platforms[0]?.id || currentCorp.credentials.corpId;
|
||||
await api.getWorkflowStats(easoClient, targetPlatformId);
|
||||
results.easoToken = {
|
||||
status: "ok",
|
||||
message: "EASO 四步换票握手成功",
|
||||
};
|
||||
} catch (e) {
|
||||
results.easoToken = {
|
||||
status: "error",
|
||||
error: e instanceof Error ? e.message : String(e),
|
||||
};
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
|
||||
+7
-1
@@ -46,6 +46,8 @@ export function formatSourceLabel(source?: string): string {
|
||||
return "统一认证中心 (IDP 账密/短信)";
|
||||
case "browser":
|
||||
return "浏览器会话同步 (WebBridge)";
|
||||
case "link":
|
||||
return "协助/免密链接导入 (Assistance Link)";
|
||||
case "curl":
|
||||
case "f12":
|
||||
return "cURL 抓包导入 (cURL/F12)";
|
||||
@@ -56,7 +58,7 @@ export function formatSourceLabel(source?: string): string {
|
||||
}
|
||||
}
|
||||
|
||||
export function formatExpiresAt(expiresAt?: number): string {
|
||||
export function formatExpiresAt(expiresAt?: number | null): string {
|
||||
if (!expiresAt || expiresAt <= 0) return "长期有效 / 服务端未显式限制";
|
||||
const diffMs = expiresAt - Date.now();
|
||||
const dateStr = new Date(expiresAt).toLocaleString("zh-CN", { hour12: false });
|
||||
@@ -115,8 +117,10 @@ export function printHelp(): string {
|
||||
hose-use <命令域> <子命令> [参数] [选项]
|
||||
|
||||
核心命令域:
|
||||
context 查看全局运行上下文与身份诊断 (context, status, whoami, env)
|
||||
auth 认证与凭证管理 (login, status, refresh, import, accounts)
|
||||
corps 多企业租户管理 (list, switch, current)
|
||||
aipro 合思 AI PRO 确定性审批仲裁网关入口 (status, scopes, bind, checklist, review, decide, logs)
|
||||
config 全局运行模式与路径诊断 (show, paths, mode <stateful|stateless>, set)
|
||||
workflow 工作流管理 (list, get, find, analyze, toggle)
|
||||
bill 单据检索与审批动作 (list, get <单号|ID> [--risk], approve|reject|transfer|add-node|comment <单号|ID> [选项], refs, relations, attachments, download, flow, risk, budget, schema, link)
|
||||
@@ -149,6 +153,8 @@ export function printHelp(): string {
|
||||
--help, -h 查看帮助信息
|
||||
|
||||
常用示例:
|
||||
hose-use context # 一键查看全局运行上下文与身份诊断 (免读源码)
|
||||
hose-use aipro status # 查看 AI PRO 审批网关状态与当前连接企业
|
||||
hose-use auth login --phone=177... --password=... # 纯 API 账密自动登录
|
||||
hose-use auth status # 查看当前登录状态与活跃企业
|
||||
hose-use config paths # 查看多级企业配置目录链
|
||||
|
||||
@@ -23,6 +23,7 @@ import { handleRoleCommand } from "./commands/role.js";
|
||||
import { handlePermissionCommand } from "./commands/permission.js";
|
||||
import { handleRuleCommand } from "./commands/rule.js";
|
||||
import { handleApprovalCommand } from "./commands/approval.js";
|
||||
import { handleContextCommand } from "./commands/context.js";
|
||||
import type { CliParsedArgs, CliResult, CliRunOptions } from "./types.js";
|
||||
|
||||
const STANDING_COMMANDS = new Set(["http", "server", "web", "mcp"]);
|
||||
@@ -143,6 +144,17 @@ async function dispatchCli(
|
||||
|
||||
try {
|
||||
switch (parsed.area) {
|
||||
case "context":
|
||||
case "status":
|
||||
case "whoami":
|
||||
case "env":
|
||||
return await handleContextCommand(parsed, runtime);
|
||||
case "aipro": {
|
||||
const { runAiProCli } = await import("../aipro-cli.js");
|
||||
const aiproIdx = parsed.raw.findIndex((a) => a.toLowerCase() === "aipro");
|
||||
const subArgs = aiproIdx !== -1 ? parsed.raw.slice(aiproIdx + 1) : parsed.raw.slice(1);
|
||||
return await runAiProCli(subArgs);
|
||||
}
|
||||
case "auth":
|
||||
case "login":
|
||||
return await handleAuthCommand(parsed, runtime);
|
||||
|
||||
+28
-6
@@ -7,6 +7,22 @@ const EASO_BASE_URL = "https://unity.ekuaibao.com";
|
||||
const BUSINESS_CENTER_URL = "https://business-center.ekuaibao.com";
|
||||
const EKB_BASE_URL = "https://app.ekuaibao.com";
|
||||
|
||||
export function resolveCorpCluster(corp: { cluster?: string; baseUrl?: string }): string {
|
||||
if (corp.cluster && corp.cluster.trim()) {
|
||||
return corp.cluster.trim();
|
||||
}
|
||||
if (corp.baseUrl) {
|
||||
try {
|
||||
const url = new URL(corp.baseUrl);
|
||||
const match = /^([a-z0-9-]+)\.ekuaibao\.com$/i.exec(url.hostname);
|
||||
if (match && match[1]) {
|
||||
return match[1].toLowerCase();
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
return "app";
|
||||
}
|
||||
|
||||
// 内存缓存
|
||||
const easoMemoryCache = new Map<
|
||||
string,
|
||||
@@ -19,14 +35,15 @@ function isExpired(entry: { expiresAt: number }, refreshTtl: number): boolean {
|
||||
|
||||
async function fetchHoseToken(
|
||||
accessToken: string,
|
||||
corpId: string
|
||||
corpId: string,
|
||||
environment: string = "app"
|
||||
): Promise<string> {
|
||||
const response = await ky
|
||||
.get(`${BUSINESS_CENTER_URL}/auth/oauth2/grant/ekb/accessToken`, {
|
||||
searchParams: {
|
||||
corpId,
|
||||
ekbAccessToken: accessToken,
|
||||
environment: "app",
|
||||
environment,
|
||||
},
|
||||
})
|
||||
.json<{ data: string }>();
|
||||
@@ -39,10 +56,11 @@ async function fetchHoseToken(
|
||||
async function fetchUnityJwt(
|
||||
accessToken: string,
|
||||
corpId: string,
|
||||
staffId: string
|
||||
staffId: string,
|
||||
baseUrl: string = EKB_BASE_URL
|
||||
): Promise<string> {
|
||||
const response = await ky
|
||||
.get(`${EKB_BASE_URL}/api/engine/realm/$UNITY/actions/jwt`, {
|
||||
.get(`${baseUrl}/api/engine/realm/$UNITY/actions/jwt`, {
|
||||
searchParams: { corpId },
|
||||
headers: {
|
||||
accesstoken: accessToken,
|
||||
@@ -106,16 +124,20 @@ export async function getEasoClient(corp: CorpConfig): Promise<{
|
||||
|
||||
const corpId = corp.corpId || corp.credentials.corpId;
|
||||
const staffId = corp.staffId || corp.credentials.staffId;
|
||||
const environment = resolveCorpCluster(corp);
|
||||
const baseUrl = corp.baseUrl || EKB_BASE_URL;
|
||||
|
||||
// 重新换取
|
||||
const hoseToken = await fetchHoseToken(
|
||||
corp.credentials.accessToken,
|
||||
corpId
|
||||
corpId,
|
||||
environment
|
||||
);
|
||||
const unityJwt = await fetchUnityJwt(
|
||||
corp.credentials.accessToken,
|
||||
corpId,
|
||||
staffId
|
||||
staffId,
|
||||
baseUrl
|
||||
);
|
||||
const easoToken = await fetchEasoRealmToken(
|
||||
corpId,
|
||||
|
||||
+174
-61
@@ -1,8 +1,11 @@
|
||||
import crypto from "crypto";
|
||||
import ky from "ky";
|
||||
import { existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { AuthenticationError } from "../errors.js";
|
||||
import { CorpConfig } from "../config/types.js";
|
||||
import { saveCorpConfig, saveMultipleCorpConfigs } from "../config/loader.js";
|
||||
import { saveCorpConfig, saveMultipleCorpConfigs, resolveWritableEnterprisesDir } from "../config/loader.js";
|
||||
import { resolveCorpCluster } from "./easo.js";
|
||||
import {
|
||||
saveAccount,
|
||||
getAccount,
|
||||
@@ -221,10 +224,20 @@ export async function syncFromBrowserSession(
|
||||
export interface F12ImportParams {
|
||||
accessToken: string;
|
||||
corpId: string;
|
||||
staffId: string;
|
||||
staffId?: string;
|
||||
name?: string;
|
||||
baseUrl?: string;
|
||||
cluster?: string;
|
||||
source?: import("../config/types.js").CredentialSource;
|
||||
enterprisesDir?: string;
|
||||
overwrite?: boolean;
|
||||
}
|
||||
|
||||
export interface ImportFromLinkOptions {
|
||||
name?: string;
|
||||
baseUrl?: string;
|
||||
enterprisesDir?: string;
|
||||
overwrite?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -234,6 +247,26 @@ export function parseHeadersOrCurl(rawInput: string): Partial<F12ImportParams> {
|
||||
const result: Partial<F12ImportParams> = {};
|
||||
if (!rawInput) return result;
|
||||
|
||||
// 0. 尝试匹配完整 URL(包含 http:// 或 https://)
|
||||
const urlMatch = /(https?:\/\/[^\s"'<>]+)/i.exec(rawInput);
|
||||
if (urlMatch) {
|
||||
try {
|
||||
const parsedUrl = new URL(urlMatch[1]);
|
||||
result.baseUrl = `${parsedUrl.protocol}//${parsedUrl.host}`;
|
||||
const tokenParam =
|
||||
parsedUrl.searchParams.get("accessToken") ||
|
||||
parsedUrl.searchParams.get("token");
|
||||
if (tokenParam) result.accessToken = tokenParam;
|
||||
const corpParam =
|
||||
parsedUrl.searchParams.get("ekbCorpId") ||
|
||||
parsedUrl.searchParams.get("corpId") ||
|
||||
parsedUrl.searchParams.get("corporationId");
|
||||
if (corpParam) result.corpId = corpParam;
|
||||
const staffParam = parsedUrl.searchParams.get("staffId");
|
||||
if (staffParam) result.staffId = staffParam;
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// 1. 尝试匹配各种 -H / --header 参数:-H 'header: value' 或 -H "header: value"
|
||||
const headerRegex = /(?:-H|--header)\s+['"]([^'"]+)['"]/gi;
|
||||
let match: RegExpExecArray | null;
|
||||
@@ -263,13 +296,25 @@ export function parseHeadersOrCurl(rawInput: string): Partial<F12ImportParams> {
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 从 URL 中提取 query 参数(例如 ?corpId=xxx 或 &corpId=xxx)
|
||||
// 3. 从 URL/Query 中提取 query 参数(例如 ?corpId=xxx 或 &corpId=xxx 或 ekbCorpId=xxx)
|
||||
if (!result.corpId) {
|
||||
const urlCorpMatch = /(?:[?&]corpId=)([^&'"\s]+)/i.exec(rawInput);
|
||||
const urlCorpMatch = /(?:[?&](?:ekbCorpId|corpId|corporationId)=)([^&'"\s]+)/i.exec(rawInput);
|
||||
if (urlCorpMatch) {
|
||||
result.corpId = decodeURIComponent(urlCorpMatch[1]);
|
||||
}
|
||||
}
|
||||
if (!result.accessToken) {
|
||||
const urlTokenMatch = /(?:[?&](?:accessToken|token)=)([^&'"\s]+)/i.exec(rawInput);
|
||||
if (urlTokenMatch) {
|
||||
result.accessToken = decodeURIComponent(urlTokenMatch[1]);
|
||||
}
|
||||
}
|
||||
if (!result.staffId) {
|
||||
const urlStaffMatch = /(?:[?&]staffId=)([^&'"\s]+)/i.exec(rawInput);
|
||||
if (urlStaffMatch) {
|
||||
result.staffId = decodeURIComponent(urlStaffMatch[1]);
|
||||
}
|
||||
}
|
||||
|
||||
// 4. 从 Cookie (-b / Cookie header) 中提取 ekb-access-token 或 corpId
|
||||
if (!result.accessToken) {
|
||||
@@ -294,14 +339,76 @@ export function parseHeadersOrCurl(rawInput: string): Partial<F12ImportParams> {
|
||||
export async function importCredentials(
|
||||
params: F12ImportParams
|
||||
): Promise<CorpConfig> {
|
||||
const { accessToken, corpId, staffId } = params;
|
||||
const { accessToken, corpId } = params;
|
||||
let staffId = params.staffId;
|
||||
const baseUrl = params.baseUrl || DEFAULT_EKB_BASE_URL;
|
||||
|
||||
if (!accessToken || !corpId || !staffId) {
|
||||
throw new AuthenticationError("导入凭证失败:accessToken、corpId、staffId 均为必填项");
|
||||
if (!accessToken || !corpId) {
|
||||
throw new AuthenticationError("导入凭证失败:accessToken 与 corpId 均为必填项");
|
||||
}
|
||||
|
||||
// 1. 验证凭证有效性并提取官方服务端 Session 元数据
|
||||
// 检查已存在保护:当明确要求不覆盖 (overwrite === false) 且文件已存在时拦截
|
||||
const targetDir = params.enterprisesDir || resolveWritableEnterprisesDir();
|
||||
const targetFile = join(targetDir, `${corpId}.json`);
|
||||
if (params.overwrite === false && existsSync(targetFile)) {
|
||||
throw new AuthenticationError(`企业 [${corpId}] 配置文件已存在。若要更新覆盖,请附加 --overwrite 参数。`);
|
||||
}
|
||||
|
||||
// 1. 若 staffId 缺失,优先通过 $UNITY JWT 自动探测 staffId、企业名与身份
|
||||
let corpName = params.name;
|
||||
let staffName: string | undefined;
|
||||
let cellphone: string | undefined;
|
||||
let isAdmin: boolean | undefined;
|
||||
let sourceChannel: string | undefined;
|
||||
let jwtExpMs: number | undefined;
|
||||
|
||||
try {
|
||||
const jwtHeaders: Record<string, string> = {
|
||||
accesstoken: accessToken,
|
||||
corpid: corpId,
|
||||
};
|
||||
if (staffId) {
|
||||
jwtHeaders.staffid = staffId;
|
||||
}
|
||||
const jwtRes = await ky
|
||||
.get(`${baseUrl}/api/engine/realm/$UNITY/actions/jwt`, {
|
||||
searchParams: { corpId },
|
||||
headers: jwtHeaders,
|
||||
})
|
||||
.json<{ id?: string; value?: string }>();
|
||||
const token = jwtRes.id || jwtRes.value;
|
||||
if (token) {
|
||||
const parts = token.split(".");
|
||||
if (parts.length >= 2) {
|
||||
const payload = JSON.parse(Buffer.from(parts[1], "base64").toString("utf-8"));
|
||||
if (!staffId && payload.staffId) {
|
||||
staffId = payload.staffId;
|
||||
}
|
||||
if (!corpName && payload.corporationName) {
|
||||
corpName = payload.corporationName;
|
||||
}
|
||||
if (payload.staffName) {
|
||||
staffName = payload.staffName;
|
||||
}
|
||||
if (payload.cellphone) {
|
||||
cellphone = payload.cellphone;
|
||||
}
|
||||
if (payload.isAdmin !== undefined) {
|
||||
isAdmin = payload.isAdmin === "true" || payload.isAdmin === true;
|
||||
}
|
||||
if (payload.sourceChannel) {
|
||||
sourceChannel = payload.sourceChannel;
|
||||
}
|
||||
if (payload.exp) {
|
||||
jwtExpMs = Number(payload.exp) * 1000;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 探测失败则继续后续降级流程
|
||||
}
|
||||
|
||||
// 2. 验证凭证有效性并提取官方服务端 Session 元数据
|
||||
let sessionData: {
|
||||
id?: string;
|
||||
userId?: string;
|
||||
@@ -321,13 +428,16 @@ export async function importCredentials(
|
||||
} | undefined;
|
||||
|
||||
try {
|
||||
const sessionHeaders: Record<string, string> = {
|
||||
accesstoken: accessToken,
|
||||
corpid: corpId,
|
||||
};
|
||||
if (staffId) {
|
||||
sessionHeaders.staffid = staffId;
|
||||
}
|
||||
const res = await ky
|
||||
.get(`${baseUrl}/api/account/v2/session`, {
|
||||
headers: {
|
||||
accesstoken: accessToken,
|
||||
corpid: corpId,
|
||||
staffid: staffId,
|
||||
},
|
||||
headers: sessionHeaders,
|
||||
})
|
||||
.json<{
|
||||
value?: {
|
||||
@@ -353,60 +463,31 @@ export async function importCredentials(
|
||||
if (!sessionData || (!sessionData.corporationId && !sessionData.id && !sessionData.userId)) {
|
||||
throw new Error("服务端未返回有效 Session");
|
||||
}
|
||||
|
||||
if (!staffId && sessionData.loginStaffId) {
|
||||
staffId = sessionData.loginStaffId;
|
||||
}
|
||||
if (!staffName && sessionData.privilege) {
|
||||
staffName = sessionData.privilege;
|
||||
}
|
||||
} catch (err) {
|
||||
throw new AuthenticationError(`凭证校验失败,请检查 token 是否已过期: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
|
||||
// 2. 尝试通过 $UNITY JWT 获取真实企业名称与员工详细信息 (如果未手动指定)
|
||||
let corpName = params.name;
|
||||
let staffName = sessionData?.privilege;
|
||||
let cellphone: string | undefined;
|
||||
let isAdmin: boolean | undefined;
|
||||
let sourceChannel: string | undefined;
|
||||
let jwtExpMs: number | undefined;
|
||||
// 兜底 staffId:若依然为空,退化为 corpId:admin
|
||||
if (!staffId) {
|
||||
staffId = `${corpId}:admin`;
|
||||
}
|
||||
|
||||
try {
|
||||
const jwtRes = await ky
|
||||
.get(`${baseUrl}/api/engine/realm/$UNITY/actions/jwt`, {
|
||||
searchParams: { corpId },
|
||||
headers: {
|
||||
accesstoken: accessToken,
|
||||
corpid: corpId,
|
||||
staffid: staffId,
|
||||
},
|
||||
})
|
||||
.json<{ id?: string; value?: string }>();
|
||||
const token = jwtRes.id || jwtRes.value;
|
||||
if (token) {
|
||||
const parts = token.split(".");
|
||||
if (parts.length >= 2) {
|
||||
const payload = JSON.parse(Buffer.from(parts[1], "base64").toString("utf-8"));
|
||||
if (!corpName && payload.corporationName) {
|
||||
corpName = payload.corporationName;
|
||||
}
|
||||
if (payload.staffName) {
|
||||
staffName = payload.staffName;
|
||||
}
|
||||
if (payload.cellphone) {
|
||||
cellphone = payload.cellphone;
|
||||
}
|
||||
if (payload.isAdmin !== undefined) {
|
||||
isAdmin = payload.isAdmin === "true" || payload.isAdmin === true;
|
||||
}
|
||||
if (payload.exp) {
|
||||
jwtExpMs = Number(payload.exp) * 1000;
|
||||
}
|
||||
}
|
||||
// 3. 智能判断语义化凭证来源与集群环境
|
||||
let source: import("../config/types.js").CredentialSource = params.source || "curl";
|
||||
if (!params.source) {
|
||||
if (sessionData?.isAssistPlatform || sessionData?.platform === "ASSIST") {
|
||||
source = "assist";
|
||||
}
|
||||
} catch {
|
||||
// 忽略尝试获取企业名失败
|
||||
}
|
||||
|
||||
// 3. 智能判断语义化凭证来源
|
||||
let source: import("../config/types.js").CredentialSource = "curl";
|
||||
if (sessionData?.isAssistPlatform || sessionData?.platform === "ASSIST") {
|
||||
source = "assist";
|
||||
}
|
||||
const cluster = params.cluster || resolveCorpCluster({ cluster: params.cluster, baseUrl });
|
||||
|
||||
// 4. 计算 Token 过期时间戳 (ms)
|
||||
let expiresAt: number | undefined;
|
||||
@@ -414,8 +495,8 @@ export async function importCredentials(
|
||||
expiresAt = sessionData.expTime;
|
||||
} else if (jwtExpMs && jwtExpMs > 0) {
|
||||
expiresAt = jwtExpMs;
|
||||
} else if (sessionData?.isAssistPlatform && sessionData?.loginTime) {
|
||||
// 协助平台短期调试 Token 通常 2 小时有效
|
||||
} else if ((sessionData?.isAssistPlatform || source === "link") && sessionData?.loginTime) {
|
||||
// 协助/免密平台短期调试 Token 通常 2 小时有效
|
||||
expiresAt = sessionData.loginTime + 2 * 3600 * 1000;
|
||||
}
|
||||
|
||||
@@ -423,6 +504,7 @@ export async function importCredentials(
|
||||
id: corpId,
|
||||
name: corpName || `企业-${corpId}`,
|
||||
baseUrl,
|
||||
cluster,
|
||||
source,
|
||||
staffName,
|
||||
credentials: {
|
||||
@@ -456,6 +538,37 @@ export async function importCredentials(
|
||||
return corpConfig;
|
||||
}
|
||||
|
||||
/**
|
||||
* 直接通过第三方协助/免密链接 (thirdparty.html / assistance link) 一键导入企业
|
||||
*/
|
||||
export async function importFromLink(
|
||||
linkUrl: string,
|
||||
options: ImportFromLinkOptions = {}
|
||||
): Promise<CorpConfig> {
|
||||
const parsed = parseHeadersOrCurl(linkUrl);
|
||||
const accessToken = parsed.accessToken;
|
||||
const corpId = parsed.corpId;
|
||||
const baseUrl = options.baseUrl || parsed.baseUrl || DEFAULT_EKB_BASE_URL;
|
||||
|
||||
if (!accessToken) {
|
||||
throw new AuthenticationError("未能从提供的链接中提取到 accessToken 参数");
|
||||
}
|
||||
if (!corpId) {
|
||||
throw new AuthenticationError("未能从提供的链接中提取到 ekbCorpId 或 corpId 参数");
|
||||
}
|
||||
|
||||
return await importCredentials({
|
||||
accessToken,
|
||||
corpId,
|
||||
staffId: parsed.staffId,
|
||||
name: options.name,
|
||||
baseUrl,
|
||||
enterprisesDir: options.enterprisesDir,
|
||||
overwrite: options.overwrite,
|
||||
source: "link",
|
||||
});
|
||||
}
|
||||
|
||||
// 保持历史命名兼容
|
||||
export const importF12Credentials = importCredentials;
|
||||
|
||||
|
||||
+13
-6
@@ -2,6 +2,7 @@ import ky from "ky";
|
||||
import { CorpConfig } from "../../core/config/types.js";
|
||||
import { createAuthClient } from "../../core/http/factory.js";
|
||||
import { AuthenticationError } from "../../core/errors.js";
|
||||
import { resolveCorpCluster } from "./easo.js";
|
||||
|
||||
const PIPER_BASE_URL = "https://piper.ekuaibao.com";
|
||||
const BUSINESS_CENTER_URL = "https://business-center.ekuaibao.com";
|
||||
@@ -19,14 +20,15 @@ function isExpired(entry: { expiresAt: number }, refreshTtl: number): boolean {
|
||||
|
||||
async function fetchHoseToken(
|
||||
accessToken: string,
|
||||
corpId: string
|
||||
corpId: string,
|
||||
environment: string = "app"
|
||||
): Promise<string> {
|
||||
const response = await ky
|
||||
.get(`${BUSINESS_CENTER_URL}/auth/oauth2/grant/ekb/accessToken`, {
|
||||
searchParams: {
|
||||
corpId,
|
||||
ekbAccessToken: accessToken,
|
||||
environment: "app",
|
||||
environment,
|
||||
},
|
||||
})
|
||||
.json<{ data: string }>();
|
||||
@@ -39,10 +41,11 @@ async function fetchHoseToken(
|
||||
async function fetchEasoJwt(
|
||||
accessToken: string,
|
||||
corpId: string,
|
||||
staffId: string
|
||||
staffId: string,
|
||||
baseUrl: string = EKB_BASE_URL
|
||||
): Promise<string> {
|
||||
const response = await ky
|
||||
.get(`${EKB_BASE_URL}/api/engine/realm/$EASO/actions/jwt`, {
|
||||
.get(`${baseUrl}/api/engine/realm/$EASO/actions/jwt`, {
|
||||
searchParams: { corpId },
|
||||
headers: {
|
||||
accesstoken: accessToken,
|
||||
@@ -82,16 +85,20 @@ export async function getPiperClient(
|
||||
|
||||
const corpId = corp.corpId || corp.credentials.corpId;
|
||||
const staffId = corp.staffId || corp.credentials.staffId;
|
||||
const environment = resolveCorpCluster(corp);
|
||||
const baseUrl = corp.baseUrl || EKB_BASE_URL;
|
||||
|
||||
// 重新换取
|
||||
const hoseToken = await fetchHoseToken(
|
||||
corp.credentials.accessToken,
|
||||
corpId
|
||||
corpId,
|
||||
environment
|
||||
);
|
||||
const easoJwt = await fetchEasoJwt(
|
||||
corp.credentials.accessToken,
|
||||
corpId,
|
||||
staffId
|
||||
staffId,
|
||||
baseUrl
|
||||
);
|
||||
|
||||
const entry = {
|
||||
|
||||
@@ -152,7 +152,7 @@ export class CorpContext {
|
||||
staffId: corp.credentials.staffId,
|
||||
baseUrl: corp.baseUrl,
|
||||
current: corp.id === this.current?.id,
|
||||
expiresAt: corp.auth?.expiresAt || corp.session?.expTime,
|
||||
expiresAt: corp.auth?.expiresAt || (corp.session?.expTime ?? undefined),
|
||||
}));
|
||||
}
|
||||
}
|
||||
+17
-15
@@ -4,6 +4,7 @@ export const CredentialSourceSchema = z.enum([
|
||||
"account", // 官方统一认证中心 (IDP) 账密/短信登录
|
||||
"assist", // 官方协助/代客平台 (Assist Platform) 调试授权会话
|
||||
"browser", // 浏览器会话 / Cookie 同步
|
||||
"link", // 协助/免密链接导入 (thirdparty.html / assistance link)
|
||||
"manual", // 手动配置
|
||||
"curl", // cURL 抓包 / HTTP Headers 导入
|
||||
"f12", // 兼容旧版抓包标识
|
||||
@@ -23,20 +24,20 @@ export const CorpAuthConfigSchema = z.object({
|
||||
});
|
||||
|
||||
export const CorpSessionInfoSchema = z.object({
|
||||
platform: z.string().optional().describe("官方会话平台类型 (如 ASSIST, WEB, MOBILE, OPENAPI)"),
|
||||
isAssistPlatform: z.boolean().optional().describe("是否为官方协助/代客平台登录"),
|
||||
isShortTermToken: z.boolean().optional().describe("是否为短期临时 Token"),
|
||||
assistId: z.string().optional().describe("协助会话/工单 ID"),
|
||||
operationUserId: z.string().optional().describe("协助操作人 ID (如内部运维/实施账号)"),
|
||||
operationUserName: z.string().optional().describe("协助操作人姓名"),
|
||||
staffName: z.string().optional().describe("当前员工真实姓名"),
|
||||
cellphone: z.string().optional().describe("绑定手机号"),
|
||||
isAdmin: z.boolean().optional().describe("是否管理员"),
|
||||
deviceType: z.string().optional().describe("设备类型"),
|
||||
loginAccountType: z.string().optional().describe("登录账号类型"),
|
||||
loginTime: z.number().optional().describe("登录时间戳 (ms)"),
|
||||
expTime: z.number().optional().describe("过期时间戳 (ms)"),
|
||||
sourceChannel: z.string().optional().describe("来源渠道 (如 APP, WEB)"),
|
||||
platform: z.string().nullable().optional().describe("官方会话平台类型 (如 ASSIST, WEB, MOBILE, OPENAPI)"),
|
||||
isAssistPlatform: z.boolean().nullable().optional().describe("是否为官方协助/代客平台登录"),
|
||||
isShortTermToken: z.boolean().nullable().optional().describe("是否为短期临时 Token"),
|
||||
assistId: z.string().nullable().optional().describe("协助会话/工单 ID"),
|
||||
operationUserId: z.string().nullable().optional().describe("协助操作人 ID (如内部运维/实施账号)"),
|
||||
operationUserName: z.string().nullable().optional().describe("协助操作人姓名"),
|
||||
staffName: z.string().nullable().optional().describe("当前员工真实姓名"),
|
||||
cellphone: z.string().nullable().optional().describe("绑定手机号"),
|
||||
isAdmin: z.boolean().nullable().optional().describe("是否管理员"),
|
||||
deviceType: z.string().nullable().optional().describe("设备类型"),
|
||||
loginAccountType: z.string().nullable().optional().describe("登录账号类型"),
|
||||
loginTime: z.number().nullable().optional().describe("登录时间戳 (ms)"),
|
||||
expTime: z.number().nullable().optional().describe("过期时间戳 (ms)"),
|
||||
sourceChannel: z.string().nullable().optional().describe("来源渠道 (如 APP, WEB)"),
|
||||
});
|
||||
export type CorpSessionInfo = z.infer<typeof CorpSessionInfoSchema>;
|
||||
|
||||
@@ -48,7 +49,8 @@ export const CorpConfigSchema = z.object({
|
||||
staffId: z.string().optional().describe("员工工号 (默认取 credentials.staffId)"),
|
||||
staffName: z.string().optional().describe("员工真实姓名"),
|
||||
baseUrl: z.string().url().optional().default("https://app.ekuaibao.com"),
|
||||
source: CredentialSourceSchema.optional().default("manual").describe("凭证来源: account/assist/browser/manual/curl/f12"),
|
||||
cluster: z.string().optional().describe("企业部署集群 (如 app, wx2, wx)"),
|
||||
source: CredentialSourceSchema.optional().default("manual").describe("凭证来源: account/assist/browser/link/manual/curl/f12"),
|
||||
accountId: z.string().optional().describe("所属主账号标识(如手机号)"),
|
||||
credentials: CorpCredentialsSchema,
|
||||
auth: CorpAuthConfigSchema.optional(),
|
||||
|
||||
@@ -27,6 +27,9 @@ describe("embedded-skill - 多文件内嵌 Skill 体系", () => {
|
||||
|
||||
expect(EMBEDDED_SKILL_FILES["references/contact.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/contact.md"]).toContain("contact search");
|
||||
|
||||
expect(EMBEDDED_SKILL_FILES["references/approval.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/approval.md"]).toContain("hose-aipro");
|
||||
});
|
||||
|
||||
test("installSkillFiles 递归保留层级结构并落盘到目标目录", () => {
|
||||
@@ -34,10 +37,11 @@ describe("embedded-skill - 多文件内嵌 Skill 体系", () => {
|
||||
try {
|
||||
const res = installSkillFiles(tmp);
|
||||
expect(res.targetDir).toBe(tmp);
|
||||
expect(res.files.length).toBe(11);
|
||||
expect(res.files.length).toBe(12);
|
||||
expect(existsSync(join(tmp, "SKILL.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "agents", "openai.yaml"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "auth.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "approval.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "bill.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "contact.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "role.md"))).toBe(true);
|
||||
|
||||
@@ -13,11 +13,13 @@ import refTask from "../../skills/hose-use/references/task.md" with { type: "tex
|
||||
import refMessage from "../../skills/hose-use/references/message.md" with { type: "text" };
|
||||
import refDimension from "../../skills/hose-use/references/dimension.md" with { type: "text" };
|
||||
import refRole from "../../skills/hose-use/references/role.md" with { type: "text" };
|
||||
import refApproval from "../../skills/hose-use/references/approval.md" with { type: "text" };
|
||||
|
||||
export const EMBEDDED_SKILL_FILES: Record<string, string> = {
|
||||
"SKILL.md": skillMain,
|
||||
"agents/openai.yaml": agentOpenAi,
|
||||
"references/auth.md": refAuth,
|
||||
"references/approval.md": refApproval,
|
||||
"references/bill.md": refBill,
|
||||
"references/contact.md": refContact,
|
||||
"references/task.md": refTask,
|
||||
|
||||
@@ -0,0 +1,285 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import {
|
||||
analyzeFindings,
|
||||
validateGatewayAction,
|
||||
evaluateGatewayPolicy,
|
||||
ApprovalGatewayPolicy,
|
||||
GatewayPolicyConfig,
|
||||
} from "./gateway.js";
|
||||
import { ApprovalFindingRecord, ApprovalGatewayBlockedError } from "./types.js";
|
||||
|
||||
function makeFinding(partial: Partial<ApprovalFindingRecord>): ApprovalFindingRecord {
|
||||
return {
|
||||
id: crypto.randomUUID(),
|
||||
runId: "test-run",
|
||||
clauseText: partial.clauseText ?? "测试条款",
|
||||
strictness: partial.strictness ?? "硬性",
|
||||
checkStatus: partial.checkStatus ?? "PASS",
|
||||
evidence: partial.evidence ?? null,
|
||||
reasoning: partial.reasoning ?? null,
|
||||
createdAt: Date.now(),
|
||||
};
|
||||
}
|
||||
|
||||
describe("Approval Gateway Policy - 可配置审批网关规则测试", () => {
|
||||
// ── 1. 硬性违规场景 ────────────────────────────────────────────────────────
|
||||
test("硬性违规:必须驳回,绝对禁止同意放行", () => {
|
||||
const findings: ApprovalFindingRecord[] = [
|
||||
makeFinding({ clauseText: "必须上传真实发票", strictness: "硬性", checkStatus: "FAIL", evidence: "无发票" }),
|
||||
makeFinding({ clauseText: "建议填写出差事由", strictness: "建议", checkStatus: "PASS" }),
|
||||
];
|
||||
|
||||
// 1.1 尝试 approve 必须被网关强力阻断
|
||||
expect(() => {
|
||||
validateGatewayAction({
|
||||
documentSn: "DOC-001",
|
||||
findings,
|
||||
requestedAction: "approve",
|
||||
opinion: "尝试放行",
|
||||
});
|
||||
}).toThrow(ApprovalGatewayBlockedError);
|
||||
|
||||
// 1.2 尝试 reject 可以正常放行
|
||||
expect(() => {
|
||||
validateGatewayAction({
|
||||
documentSn: "DOC-001",
|
||||
findings,
|
||||
requestedAction: "reject",
|
||||
opinion: "缺少发票予以驳回",
|
||||
});
|
||||
}).not.toThrow();
|
||||
|
||||
// 1.3 默认仲裁决断结果必须为 REJECT
|
||||
const result = evaluateGatewayPolicy({
|
||||
documentSn: "DOC-001",
|
||||
findings,
|
||||
});
|
||||
expect(result.decision).toBe("REJECT");
|
||||
expect(result.hardFailedCount).toBe(1);
|
||||
expect(result.decisionSummary).toContain("触犯硬性刚性条款,决策锁定为【驳回】");
|
||||
});
|
||||
|
||||
// ── 2. 零违规(全通过)场景 ────────────────────────────────────────────────
|
||||
test("零违规:没有硬性或弹性违规不能驳回,必须同意放行", () => {
|
||||
const findings: ApprovalFindingRecord[] = [
|
||||
makeFinding({ clauseText: "必须上传真实发票", strictness: "硬性", checkStatus: "PASS" }),
|
||||
makeFinding({ clauseText: "尽量上传付款水单", strictness: "弹性", checkStatus: "PASS" }),
|
||||
makeFinding({ clauseText: "建议补充事由", strictness: "建议", checkStatus: "SKIP" }),
|
||||
];
|
||||
|
||||
// 2.1 尝试 reject 必须被网关阻断(禁止无因驳回)
|
||||
expect(() => {
|
||||
validateGatewayAction({
|
||||
documentSn: "DOC-002",
|
||||
findings,
|
||||
requestedAction: "reject",
|
||||
opinion: "恶意驳回",
|
||||
});
|
||||
}).toThrow(ApprovalGatewayBlockedError);
|
||||
|
||||
try {
|
||||
validateGatewayAction({
|
||||
documentSn: "DOC-002",
|
||||
findings,
|
||||
requestedAction: "reject",
|
||||
opinion: "恶意驳回",
|
||||
});
|
||||
} catch (err: any) {
|
||||
expect(err.message).toContain("不存在任何【硬性】或【弹性】违规条款");
|
||||
}
|
||||
|
||||
// 2.2 尝试 approve 正常放行
|
||||
expect(() => {
|
||||
validateGatewayAction({
|
||||
documentSn: "DOC-002",
|
||||
findings,
|
||||
requestedAction: "approve",
|
||||
opinion: "合规通过",
|
||||
});
|
||||
}).not.toThrow();
|
||||
|
||||
// 2.3 决策结果为 APPROVE
|
||||
const result = evaluateGatewayPolicy({
|
||||
documentSn: "DOC-002",
|
||||
findings,
|
||||
});
|
||||
expect(result.decision).toBe("APPROVE");
|
||||
expect(result.decisionSummary).toContain("决策锁定为【同意通过】");
|
||||
});
|
||||
|
||||
// ── 3. 仅建议项违规场景 ────────────────────────────────────────────────────
|
||||
test("仅建议项违规:不构成驳回理由,禁止驳回,决断为备注通过", () => {
|
||||
const findings: ApprovalFindingRecord[] = [
|
||||
makeFinding({ clauseText: "必须上传真实发票", strictness: "硬性", checkStatus: "PASS" }),
|
||||
makeFinding({ clauseText: "建议补充说明消费事由", strictness: "建议", checkStatus: "FAIL", evidence: "事由偏简略" }),
|
||||
];
|
||||
|
||||
// 3.1 尝试驳回:建议项不能作为驳回理由,必须阻断
|
||||
expect(() => {
|
||||
validateGatewayAction({
|
||||
documentSn: "DOC-003",
|
||||
findings,
|
||||
requestedAction: "reject",
|
||||
opinion: "因事由简略驳回",
|
||||
});
|
||||
}).toThrow("建议项不构成驳回理由");
|
||||
|
||||
// 3.2 尝试同意:放行
|
||||
expect(() => {
|
||||
validateGatewayAction({
|
||||
documentSn: "DOC-003",
|
||||
findings,
|
||||
requestedAction: "approve",
|
||||
opinion: "备注事由后放行",
|
||||
});
|
||||
}).not.toThrow();
|
||||
|
||||
// 3.3 决断结果为 PASS_WITH_NOTE
|
||||
const result = evaluateGatewayPolicy({
|
||||
documentSn: "DOC-003",
|
||||
findings,
|
||||
});
|
||||
expect(result.decision).toBe("PASS_WITH_NOTE");
|
||||
expect(result.decisionSummary).toContain("决策锁定为【备注通过】");
|
||||
});
|
||||
|
||||
// ── 4. 弹性违规场景 ────────────────────────────────────────────────────────
|
||||
test("弹性违规:允许驳回;数量 <= 2 时为备注通过,>= 3 时建议人工复核", () => {
|
||||
// 4.1 存在 1 项弹性违规
|
||||
const findings1: ApprovalFindingRecord[] = [
|
||||
makeFinding({ clauseText: "必须上传发票", strictness: "硬性", checkStatus: "PASS" }),
|
||||
makeFinding({ clauseText: "尽量上传水单", strictness: "弹性", checkStatus: "FAIL", evidence: "未提供水单" }),
|
||||
];
|
||||
|
||||
// 因为有弹性违规,允许驳回
|
||||
expect(() => {
|
||||
validateGatewayAction({
|
||||
documentSn: "DOC-004-1",
|
||||
findings: findings1,
|
||||
requestedAction: "reject",
|
||||
opinion: "未提供水单予以驳回",
|
||||
});
|
||||
}).not.toThrow();
|
||||
|
||||
// 自动决断为 PASS_WITH_NOTE(弹性超标未达阈值)
|
||||
const result1 = evaluateGatewayPolicy({
|
||||
documentSn: "DOC-004-1",
|
||||
findings: findings1,
|
||||
});
|
||||
expect(result1.decision).toBe("PASS_WITH_NOTE");
|
||||
|
||||
// 4.2 存在 3 项弹性违规(达到阈值)
|
||||
const findings3: ApprovalFindingRecord[] = [
|
||||
makeFinding({ clauseText: "必须上传发票", strictness: "硬性", checkStatus: "PASS" }),
|
||||
makeFinding({ clauseText: "尽量上传水单1", strictness: "弹性", checkStatus: "FAIL" }),
|
||||
makeFinding({ clauseText: "尽量上传水单2", strictness: "弹性", checkStatus: "FAIL" }),
|
||||
makeFinding({ clauseText: "尽量上传水单3", strictness: "弹性", checkStatus: "FAIL" }),
|
||||
];
|
||||
|
||||
const result3 = evaluateGatewayPolicy({
|
||||
documentSn: "DOC-004-3",
|
||||
findings: findings3,
|
||||
});
|
||||
expect(result3.decision).toBe("REVIEW");
|
||||
expect(result3.decisionSummary).toContain("建议人工复核");
|
||||
});
|
||||
|
||||
// ── 5. 特殊项违规场景 ──────────────────────────────────────────────────────
|
||||
test("特殊项命中:转人工复核,禁止直接驳回", () => {
|
||||
const findings: ApprovalFindingRecord[] = [
|
||||
makeFinding({ clauseText: "必须上传发票", strictness: "硬性", checkStatus: "PASS" }),
|
||||
makeFinding({ clauseText: "大额争议须法务审核", strictness: "特殊", checkStatus: "FAIL", evidence: "单据超10万" }),
|
||||
];
|
||||
|
||||
expect(() => {
|
||||
validateGatewayAction({
|
||||
documentSn: "DOC-005",
|
||||
findings,
|
||||
requestedAction: "reject",
|
||||
opinion: "法务未审直接驳回",
|
||||
});
|
||||
}).toThrow("特殊");
|
||||
|
||||
const result = evaluateGatewayPolicy({
|
||||
documentSn: "DOC-005",
|
||||
findings,
|
||||
});
|
||||
expect(result.decision).toBe("REVIEW");
|
||||
});
|
||||
|
||||
// ── 6. 待核验(PENDING)漏检拦截 ───────────────────────────────────────────
|
||||
test("待核验漏检保护:存在 PENDING 要点时,同意和驳回均被阻断", () => {
|
||||
const findings: ApprovalFindingRecord[] = [
|
||||
makeFinding({ clauseText: "发票检查", strictness: "硬性", checkStatus: "PASS" }),
|
||||
makeFinding({ clauseText: "住宿限额检查", strictness: "硬性", checkStatus: "PENDING" }),
|
||||
];
|
||||
|
||||
// 同意被阻断
|
||||
expect(() => {
|
||||
validateGatewayAction({
|
||||
documentSn: "DOC-006",
|
||||
findings,
|
||||
requestedAction: "approve",
|
||||
opinion: "盲目同意",
|
||||
});
|
||||
}).toThrow("PENDING 待核验状态");
|
||||
|
||||
// 驳回也被阻断(必须先完成核验)
|
||||
expect(() => {
|
||||
validateGatewayAction({
|
||||
documentSn: "DOC-006",
|
||||
findings,
|
||||
requestedAction: "reject",
|
||||
opinion: "盲目驳回",
|
||||
});
|
||||
}).toThrow("PENDING 待核验状态");
|
||||
});
|
||||
|
||||
// ── 7. 审批意见长度边角限制 ───────────────────────────────────────────────
|
||||
test("审批意见长度控制:超过 150 字符时抛错阻断", () => {
|
||||
const findings: ApprovalFindingRecord[] = [
|
||||
makeFinding({ clauseText: "发票检查", strictness: "硬性", checkStatus: "FAIL" }),
|
||||
];
|
||||
|
||||
const overLength = "超长意见内容".repeat(35); // > 150 字
|
||||
expect(() => {
|
||||
validateGatewayAction({
|
||||
documentSn: "DOC-007",
|
||||
findings,
|
||||
requestedAction: "reject",
|
||||
opinion: overLength,
|
||||
});
|
||||
}).toThrow("不可超过 150 字符");
|
||||
});
|
||||
|
||||
// ── 8. 自定义逻辑扩展钩子 (customHook) ────────────────────────────────────
|
||||
test("支持配置自定义网关钩子覆盖或扩展逻辑", () => {
|
||||
const findings: ApprovalFindingRecord[] = [
|
||||
makeFinding({ clauseText: "普通合规检查", strictness: "建议", checkStatus: "PASS" }),
|
||||
];
|
||||
|
||||
const policy = new ApprovalGatewayPolicy({
|
||||
customHook: (context, analysis, config) => {
|
||||
if (context.documentSn.startsWith("VIP-")) {
|
||||
return {
|
||||
decision: "APPROVE",
|
||||
decisionSummary: "VIP 单据走免审专属绿色通道",
|
||||
analysis,
|
||||
hardFailedCount: 0,
|
||||
elasticFailedCount: 0,
|
||||
suggestFailedCount: 0,
|
||||
specialFailedCount: 0,
|
||||
};
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const result = policy.evaluate({
|
||||
documentSn: "VIP-88888",
|
||||
findings,
|
||||
});
|
||||
|
||||
expect(result.decision).toBe("APPROVE");
|
||||
expect(result.decisionSummary).toBe("VIP 单据走免审专属绿色通道");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,334 @@
|
||||
import {
|
||||
ApprovalDecision,
|
||||
ApprovalFindingRecord,
|
||||
ApprovalGatewayBlockedError,
|
||||
StrictnessTier,
|
||||
} from "./types.js";
|
||||
|
||||
/**
|
||||
* 审批仲裁网关策略配置接口
|
||||
*/
|
||||
export interface GatewayPolicyConfig {
|
||||
/**
|
||||
* 弹性违规项允许的最大数量。超过此数量自动转为建议人工复核 (默认: 2)
|
||||
*/
|
||||
maxElasticViolationsForPassWithNote: number;
|
||||
|
||||
/**
|
||||
* 是否严格禁止在无硬性违规且无弹性违规时执行驳回 (默认: true)
|
||||
* 业务铁律:没有硬性违反或弹性违反不能驳回,物理切断恶意/无故驳回分支
|
||||
*/
|
||||
blockRejectWithoutHardOrElasticFailure: boolean;
|
||||
|
||||
/**
|
||||
* 是否在存在硬性违规时一票否决,物理切断同意分支 (默认: true)
|
||||
* 业务铁律:有硬性违反必须驳回(或复核),绝对禁止放行同意
|
||||
*/
|
||||
blockApproveWithHardFailure: boolean;
|
||||
|
||||
/**
|
||||
* 审批意见的最大字符数限制 (默认: 150)
|
||||
*/
|
||||
maxOpinionLength: number;
|
||||
|
||||
/**
|
||||
* 可配置的自定义逻辑扩展钩子。
|
||||
* 返回具体结果时直接作为最终裁决;返回 void 或 undefined 时继续执行标准裁决矩阵。
|
||||
*/
|
||||
customHook?: (
|
||||
context: GatewayContext,
|
||||
analysis: FindingsAnalysis,
|
||||
config: GatewayPolicyConfig
|
||||
) => GatewayDecisionResult | void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 网关默认策略配置
|
||||
*/
|
||||
export const DEFAULT_GATEWAY_CONFIG: GatewayPolicyConfig = {
|
||||
maxElasticViolationsForPassWithNote: 2,
|
||||
blockRejectWithoutHardOrElasticFailure: true,
|
||||
blockApproveWithHardFailure: true,
|
||||
maxOpinionLength: 150,
|
||||
};
|
||||
|
||||
/**
|
||||
* 网关裁决输入上下文
|
||||
*/
|
||||
export interface GatewayContext {
|
||||
documentSn: string;
|
||||
findings: ApprovalFindingRecord[];
|
||||
requestedAction?: "approve" | "reject" | "comment";
|
||||
opinion?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 要点事实核验分析结果
|
||||
*/
|
||||
export interface FindingsAnalysis {
|
||||
allFindings: ApprovalFindingRecord[];
|
||||
pendingFindings: ApprovalFindingRecord[];
|
||||
passedFindings: ApprovalFindingRecord[];
|
||||
failedFindings: ApprovalFindingRecord[];
|
||||
skippedFindings: ApprovalFindingRecord[];
|
||||
hardFailed: ApprovalFindingRecord[];
|
||||
elasticFailed: ApprovalFindingRecord[];
|
||||
suggestFailed: ApprovalFindingRecord[];
|
||||
specialFailed: ApprovalFindingRecord[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 网关综合判定结果
|
||||
*/
|
||||
export interface GatewayDecisionResult {
|
||||
decision: ApprovalDecision;
|
||||
decisionSummary: string;
|
||||
analysis: FindingsAnalysis;
|
||||
hardFailedCount: number;
|
||||
elasticFailedCount: number;
|
||||
suggestFailedCount: number;
|
||||
specialFailedCount: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 分析审核要点状态与严格度分布
|
||||
*/
|
||||
export function analyzeFindings(findings: ApprovalFindingRecord[]): FindingsAnalysis {
|
||||
const pendingFindings: ApprovalFindingRecord[] = [];
|
||||
const passedFindings: ApprovalFindingRecord[] = [];
|
||||
const failedFindings: ApprovalFindingRecord[] = [];
|
||||
const skippedFindings: ApprovalFindingRecord[] = [];
|
||||
const hardFailed: ApprovalFindingRecord[] = [];
|
||||
const elasticFailed: ApprovalFindingRecord[] = [];
|
||||
const suggestFailed: ApprovalFindingRecord[] = [];
|
||||
const specialFailed: ApprovalFindingRecord[] = [];
|
||||
|
||||
for (const f of findings) {
|
||||
if (f.checkStatus === "PENDING") {
|
||||
pendingFindings.push(f);
|
||||
} else if (f.checkStatus === "PASS") {
|
||||
passedFindings.push(f);
|
||||
} else if (f.checkStatus === "SKIP") {
|
||||
skippedFindings.push(f);
|
||||
} else if (f.checkStatus === "FAIL") {
|
||||
failedFindings.push(f);
|
||||
if (f.strictness === "硬性") {
|
||||
hardFailed.push(f);
|
||||
} else if (f.strictness === "弹性") {
|
||||
elasticFailed.push(f);
|
||||
} else if (f.strictness === "建议") {
|
||||
suggestFailed.push(f);
|
||||
} else if (f.strictness === "特殊") {
|
||||
specialFailed.push(f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
allFindings: findings,
|
||||
pendingFindings,
|
||||
passedFindings,
|
||||
failedFindings,
|
||||
skippedFindings,
|
||||
hardFailed,
|
||||
elasticFailed,
|
||||
suggestFailed,
|
||||
specialFailed,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验网关拟执行的动作是否合法(前置门禁防御)
|
||||
*
|
||||
* 包含核心卡点:
|
||||
* 1. 空要点清单拦截:未注入要点前物理切断审批链路
|
||||
* 2. 审批意见长度校验:超长直接拦截
|
||||
* 3. 待核验拦截:存在 PENDING 要点时禁止提前决断
|
||||
* 4. 硬性一票否决:有硬性违规绝对禁止同意放行
|
||||
* 5. 无因驳回拦截:无硬性违规且无弹性违规时绝对禁止驳回
|
||||
*
|
||||
* @throws {ApprovalGatewayBlockedError} 当任一门禁被触发时抛出
|
||||
*/
|
||||
export function validateGatewayAction(
|
||||
context: GatewayContext,
|
||||
userConfig?: Partial<GatewayPolicyConfig>
|
||||
): FindingsAnalysis {
|
||||
const config = { ...DEFAULT_GATEWAY_CONFIG, ...userConfig };
|
||||
|
||||
// ── 门禁 1: 空要点清单拦截 ────────────────────────────────────────────────
|
||||
if (!context.findings || context.findings.length === 0) {
|
||||
throw new ApprovalGatewayBlockedError(
|
||||
`[审批链路阻断] 单据 [${context.documentSn}] 尚未注入任何明细级审核要点(要点列表为空)!\n` +
|
||||
`网关卡点生效:审核要点未注入前,审批链路物理切断,绝对禁止进入审批决策!\n` +
|
||||
`请先执行: hose-aipro bind 挂载审核要点清单。`
|
||||
);
|
||||
}
|
||||
|
||||
// ── 门禁 2: 审批意见长度边角检查 ──────────────────────────────────────────
|
||||
if (context.opinion && context.opinion.length > config.maxOpinionLength) {
|
||||
throw new ApprovalGatewayBlockedError(
|
||||
`[参数校验阻断] 审批意见不可超过 ${config.maxOpinionLength} 字符,当前长度为 ${context.opinion.length} 字符,请精简。`
|
||||
);
|
||||
}
|
||||
|
||||
// ── 门禁 3: 漏检拦截(存在待核验项)───────────────────────────────────────
|
||||
const analysis = analyzeFindings(context.findings);
|
||||
if (analysis.pendingFindings.length > 0) {
|
||||
const pendingIndices = analysis.pendingFindings
|
||||
.map((f) => `#${context.findings.indexOf(f) + 1} [${f.strictness}] ${f.clauseText}`)
|
||||
.join(";");
|
||||
throw new ApprovalGatewayBlockedError(
|
||||
`[审批链路阻断] 单据 [${context.documentSn}] 尚有 ${analysis.pendingFindings.length} 处审核要点处于 PENDING 待核验状态!\n` +
|
||||
`网关卡点生效:禁止在核验未全部闭环前提前决断。\n` +
|
||||
`待核验项: ${pendingIndices}`
|
||||
);
|
||||
}
|
||||
|
||||
// ── 门禁 4: 硬性条款刚性底线(有硬性违规时绝对禁止同意)─────────────────
|
||||
if (context.requestedAction === "approve" && config.blockApproveWithHardFailure && analysis.hardFailed.length > 0) {
|
||||
const violatedNames = analysis.hardFailed
|
||||
.map((f) => `【#${context.findings.indexOf(f) + 1} ${f.clauseText}】`)
|
||||
.join("、");
|
||||
throw new ApprovalGatewayBlockedError(
|
||||
`[网关强力阻断] 单据 [${context.documentSn}] 存在硬性违规条款未通过(${violatedNames})!\n` +
|
||||
`网关物理切断“同意”流转,绝对禁止放行通过!当前只允许执行驳回 (reject) 或建议复核。`
|
||||
);
|
||||
}
|
||||
|
||||
// ── 门禁 5: 无因驳回拦截(没有硬性或弹性违规不能驳回)────────────────────
|
||||
if (
|
||||
context.requestedAction === "reject" &&
|
||||
config.blockRejectWithoutHardOrElasticFailure &&
|
||||
analysis.hardFailed.length === 0 &&
|
||||
analysis.elasticFailed.length === 0
|
||||
) {
|
||||
let detail = "单据所有核验要点均已通过";
|
||||
if (analysis.suggestFailed.length > 0) {
|
||||
const suggestNames = analysis.suggestFailed
|
||||
.map((f) => `【#${context.findings.indexOf(f) + 1} ${f.clauseText}】`)
|
||||
.join("、");
|
||||
detail = `单据仅存在倡导性的【建议】项未满足(${suggestNames}),建议项不构成驳回理由`;
|
||||
} else if (analysis.specialFailed.length > 0) {
|
||||
const specialNames = analysis.specialFailed
|
||||
.map((f) => `【#${context.findings.indexOf(f) + 1} ${f.clauseText}】`)
|
||||
.join("、");
|
||||
detail = `单据命中【特殊】条款(${specialNames}),按规则须提交人工复核,不能直接驳回`;
|
||||
}
|
||||
|
||||
throw new ApprovalGatewayBlockedError(
|
||||
`[网关安全阻断] 单据 [${context.documentSn}] 不存在任何【硬性】或【弹性】违规条款(${detail})!\n` +
|
||||
`网关物理切断驳回分支,严禁无故或恶意驳回!当前只允许执行同意 (approve) 或转人工复核。`
|
||||
);
|
||||
}
|
||||
|
||||
return analysis;
|
||||
}
|
||||
|
||||
/**
|
||||
* 确定性网关仲裁:执行所有校验并计算最终决策结果与审查报告
|
||||
*/
|
||||
export function evaluateGatewayPolicy(
|
||||
context: GatewayContext,
|
||||
userConfig?: Partial<GatewayPolicyConfig>
|
||||
): GatewayDecisionResult {
|
||||
const config = { ...DEFAULT_GATEWAY_CONFIG, ...userConfig };
|
||||
|
||||
// 1. 前置动作合法性校验(拦截非法同意、非法驳回、未闭环核验等)
|
||||
const analysis = validateGatewayAction(context, config);
|
||||
|
||||
// 2. 优先执行用户自定义逻辑钩子
|
||||
if (config.customHook) {
|
||||
const customResult = config.customHook(context, analysis, config);
|
||||
if (customResult) {
|
||||
return customResult;
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 执行标准确定性裁决矩阵
|
||||
let decision: ApprovalDecision;
|
||||
if (analysis.hardFailed.length > 0) {
|
||||
decision = "REJECT";
|
||||
} else if (analysis.specialFailed.length > 0) {
|
||||
decision = "REVIEW";
|
||||
} else if (analysis.elasticFailed.length > 0) {
|
||||
decision =
|
||||
analysis.elasticFailed.length > config.maxElasticViolationsForPassWithNote
|
||||
? "REVIEW"
|
||||
: "PASS_WITH_NOTE";
|
||||
} else if (analysis.suggestFailed.length > 0) {
|
||||
decision = "PASS_WITH_NOTE";
|
||||
} else {
|
||||
decision = "APPROVE";
|
||||
}
|
||||
|
||||
// 4. 组装格式化合规审查报告
|
||||
const summaryLines: string[] = [];
|
||||
summaryLines.push(`【合思 AI 确定性网关审查报告】`);
|
||||
summaryLines.push(`单号: ${context.documentSn} | 审核要点总数: ${context.findings.length} 项`);
|
||||
summaryLines.push(``);
|
||||
summaryLines.push(`[逐项核验事实]`);
|
||||
context.findings.forEach((f, idx) => {
|
||||
const icon = f.checkStatus === "PASS" ? "✅" : f.checkStatus === "FAIL" ? "❌" : "➖";
|
||||
const reason = f.evidence || f.reasoning ? ` (${[f.evidence, f.reasoning].filter(Boolean).join(" - ")})` : "";
|
||||
summaryLines.push(` ${icon} #${idx + 1} [${f.strictness}] ${f.clauseText}${reason}`);
|
||||
});
|
||||
summaryLines.push(``);
|
||||
|
||||
if (decision === "REJECT") {
|
||||
summaryLines.push(`[网关结论] ❌ 触犯硬性刚性条款,决策锁定为【驳回】`);
|
||||
} else if (decision === "REVIEW") {
|
||||
summaryLines.push(`[网关结论] ⚠️ 触发特殊或弹性超标条款,决策锁定为【建议人工复核】`);
|
||||
} else if (decision === "PASS_WITH_NOTE") {
|
||||
summaryLines.push(`[网关结论] 💡 满足核心要求,包含弹性/建议提示,决策锁定为【备注通过】`);
|
||||
} else {
|
||||
summaryLines.push(`[网关结论] ✅ 所有规则判定全部通过,决策锁定为【同意通过】`);
|
||||
}
|
||||
|
||||
if (context.opinion) {
|
||||
summaryLines.push(`[审批附加说明] ${context.opinion}`);
|
||||
}
|
||||
|
||||
const decisionSummary = summaryLines.join("\n");
|
||||
|
||||
return {
|
||||
decision,
|
||||
decisionSummary,
|
||||
analysis,
|
||||
hardFailedCount: analysis.hardFailed.length,
|
||||
elasticFailedCount: analysis.elasticFailed.length,
|
||||
suggestFailedCount: analysis.suggestFailed.length,
|
||||
specialFailedCount: analysis.specialFailed.length,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 可配置的审批仲裁网关策略类
|
||||
*/
|
||||
export class ApprovalGatewayPolicy {
|
||||
private config: GatewayPolicyConfig;
|
||||
|
||||
constructor(config?: Partial<GatewayPolicyConfig>) {
|
||||
this.config = { ...DEFAULT_GATEWAY_CONFIG, ...config };
|
||||
}
|
||||
|
||||
public getConfig(): GatewayPolicyConfig {
|
||||
return { ...this.config };
|
||||
}
|
||||
|
||||
public updateConfig(updates: Partial<GatewayPolicyConfig>): void {
|
||||
this.config = { ...this.config, ...updates };
|
||||
}
|
||||
|
||||
public validate(context: GatewayContext): FindingsAnalysis {
|
||||
return validateGatewayAction(context, this.config);
|
||||
}
|
||||
|
||||
public evaluate(context: GatewayContext): GatewayDecisionResult {
|
||||
return evaluateGatewayPolicy(context, this.config);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 全局默认网关单例
|
||||
*/
|
||||
export const defaultGatewayPolicy = new ApprovalGatewayPolicy();
|
||||
@@ -3,3 +3,4 @@ export * from "./parser.js";
|
||||
export * from "./db.js";
|
||||
export * from "./repository.js";
|
||||
export * from "./service.js";
|
||||
export * from "./gateway.js";
|
||||
@@ -398,6 +398,33 @@ export class ApprovalRepository {
|
||||
return row ? this.mapRunRow(row) : null;
|
||||
}
|
||||
|
||||
public listRuns(filter?: { corpId?: string; decision?: ApprovalDecision; limit?: number }): ApprovalRunRecord[] {
|
||||
const conditions: string[] = [];
|
||||
const params: (string | number)[] = [];
|
||||
|
||||
if (filter?.corpId !== undefined) {
|
||||
conditions.push("corp_id = ?");
|
||||
params.push(filter.corpId);
|
||||
}
|
||||
if (filter?.decision !== undefined) {
|
||||
conditions.push("decision = ?");
|
||||
params.push(filter.decision);
|
||||
}
|
||||
|
||||
let sql = "SELECT * FROM approval_runs";
|
||||
if (conditions.length > 0) {
|
||||
sql += " WHERE " + conditions.join(" AND ");
|
||||
}
|
||||
sql += " ORDER BY created_at DESC";
|
||||
if (filter?.limit) {
|
||||
sql += " LIMIT ?";
|
||||
params.push(filter.limit);
|
||||
}
|
||||
|
||||
const rows = this.db.query(sql).all(...params) as any[];
|
||||
return rows.map((r) => this.mapRunRow(r));
|
||||
}
|
||||
|
||||
public updateApprovalRun(
|
||||
id: string,
|
||||
updates: Partial<Omit<ApprovalRunRecord, "id" | "documentSn" | "createdAt">>
|
||||
|
||||
@@ -8,6 +8,12 @@ import {
|
||||
ApprovalRunRecord,
|
||||
FindingCheckStatus,
|
||||
} from "./types.js";
|
||||
import {
|
||||
ApprovalGatewayPolicy,
|
||||
defaultGatewayPolicy,
|
||||
evaluateGatewayPolicy,
|
||||
GatewayPolicyConfig,
|
||||
} from "./gateway.js";
|
||||
import { getBillByCodeOrId, approveBill, rejectBill, commentBill } from "../bill/tools.js";
|
||||
import type { FormattedBill } from "../bill/types.js";
|
||||
|
||||
@@ -22,6 +28,7 @@ export interface DecideAuditOptions {
|
||||
requestedAction?: "approve" | "reject" | "comment";
|
||||
apply?: boolean;
|
||||
comment?: string;
|
||||
gatewayConfig?: Partial<GatewayPolicyConfig>;
|
||||
}
|
||||
|
||||
export interface DecideAuditResult {
|
||||
@@ -38,9 +45,11 @@ export interface DecideAuditResult {
|
||||
|
||||
export class ApprovalService {
|
||||
private repo: ApprovalRepository;
|
||||
private gatewayPolicy: ApprovalGatewayPolicy;
|
||||
|
||||
constructor(repo?: ApprovalRepository) {
|
||||
constructor(repo?: ApprovalRepository, gatewayPolicy?: ApprovalGatewayPolicy) {
|
||||
this.repo = repo ?? new ApprovalRepository();
|
||||
this.gatewayPolicy = gatewayPolicy ?? defaultGatewayPolicy;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -207,8 +216,7 @@ export class ApprovalService {
|
||||
): Promise<DecideAuditResult> {
|
||||
const { run, findings } = this.repo.getAuditChecklist(documentSn, corpId);
|
||||
|
||||
// ── 核心门禁 1:如果审核要点列表为空,审批链路物理不通! ────────────────────
|
||||
if (!run || findings.length === 0) {
|
||||
if (!run) {
|
||||
throw new ApprovalGatewayBlockedError(
|
||||
`[审批链路阻断] 单据 [${documentSn}] 尚未注入任何明细级审核要点(要点列表为空)!\n` +
|
||||
`网关卡点生效:审核要点未注入前,审批链路物理切断,绝对禁止进入审批决策!\n` +
|
||||
@@ -216,80 +224,31 @@ export class ApprovalService {
|
||||
);
|
||||
}
|
||||
|
||||
// ── 核心门禁 2:检查是否有未完成事实核验的 PENDING 要点 ──────────────────────
|
||||
const pendingFindings = findings.filter((f) => f.checkStatus === "PENDING");
|
||||
if (pendingFindings.length > 0) {
|
||||
throw new ApprovalGatewayBlockedError(
|
||||
`[审批链路阻断] 单据 [${documentSn}] 尚有 ${pendingFindings.length} 处审核要点处于 PENDING 待核验状态!\n` +
|
||||
`网关卡点生效:禁止在核验未全部闭环前提前决断。\n` +
|
||||
`待核验项: ${pendingFindings.map((f, i) => `#${i + 1} [${f.strictness}] ${f.clauseText}`).join(";")}`
|
||||
);
|
||||
}
|
||||
// 确定性网关仲裁:由独立的可配置网关策略脚本执行(执行核心门禁与裁决计算)
|
||||
const gatewayResult = evaluateGatewayPolicy(
|
||||
{
|
||||
documentSn,
|
||||
findings,
|
||||
requestedAction: options.requestedAction,
|
||||
opinion: options.comment,
|
||||
},
|
||||
options.gatewayConfig ?? this.gatewayPolicy.getConfig()
|
||||
);
|
||||
|
||||
// ── 核心门禁 3:梯度级别与硬性刚性防线 ───────────────────────────────────────
|
||||
const failedFindings = findings.filter((f) => f.checkStatus === "FAIL");
|
||||
const hardFailed = failedFindings.filter((f) => f.strictness === "硬性");
|
||||
const specialFailed = failedFindings.filter((f) => f.strictness === "特殊");
|
||||
const elasticFailed = failedFindings.filter((f) => f.strictness === "弹性");
|
||||
const suggestFailed = failedFindings.filter((f) => f.strictness === "建议");
|
||||
|
||||
// 硬性条款违规拦截:物理切断 approve 通道
|
||||
if (hardFailed.length > 0 && options.requestedAction === "approve") {
|
||||
const violatedNames = hardFailed.map((f) => `【${f.clauseText}】`).join("、");
|
||||
throw new ApprovalGatewayBlockedError(
|
||||
`[网关强力阻断] 单据 [${documentSn}] 触犯刚性底线【硬性】违规条款: ${violatedNames}!\n` +
|
||||
`网关物理切断同意分支,绝对禁止放行通过!当前只允许执行驳回 (reject) 或建议复核。`
|
||||
);
|
||||
}
|
||||
|
||||
// 计算网关裁决决策
|
||||
let decision: ApprovalDecision;
|
||||
if (hardFailed.length > 0) {
|
||||
decision = "REJECT";
|
||||
} else if (specialFailed.length > 0) {
|
||||
decision = "REVIEW";
|
||||
} else if (elasticFailed.length > 0) {
|
||||
decision = elasticFailed.length >= 3 ? "REVIEW" : "PASS_WITH_NOTE";
|
||||
} else if (suggestFailed.length > 0) {
|
||||
decision = "PASS_WITH_NOTE";
|
||||
} else {
|
||||
decision = "APPROVE";
|
||||
}
|
||||
|
||||
// 组装格式化合规意见报告
|
||||
const summaryLines: string[] = [];
|
||||
summaryLines.push(`【合思 AI 确定性网关审查报告】`);
|
||||
summaryLines.push(`单号: ${documentSn} | 审核要点总数: ${findings.length} 项`);
|
||||
summaryLines.push(``);
|
||||
summaryLines.push(`[逐项核验事实]`);
|
||||
findings.forEach((f, idx) => {
|
||||
const icon = f.checkStatus === "PASS" ? "✅" : f.checkStatus === "FAIL" ? "❌" : "➖";
|
||||
const reason = f.evidence || f.reasoning ? ` (${[f.evidence, f.reasoning].filter(Boolean).join(" - ")})` : "";
|
||||
summaryLines.push(` ${icon} #${idx + 1} [${f.strictness}] ${f.clauseText}${reason}`);
|
||||
});
|
||||
summaryLines.push(``);
|
||||
|
||||
if (decision === "REJECT") {
|
||||
summaryLines.push(`[网关结论] ❌ 触犯硬性刚性条款,决策锁定为【驳回】`);
|
||||
} else if (decision === "REVIEW") {
|
||||
summaryLines.push(`[网关结论] ⚠️ 触发特殊或弹性超标条款,决策锁定为【建议人工复核】`);
|
||||
} else if (decision === "PASS_WITH_NOTE") {
|
||||
summaryLines.push(`[网关结论] 💡 满足核心要求,包含弹性/建议提示,决策锁定为【备注通过】`);
|
||||
} else {
|
||||
summaryLines.push(`[网关结论] ✅ 所有规则判定全部通过,决策锁定为【同意通过】`);
|
||||
}
|
||||
|
||||
if (options.comment) {
|
||||
summaryLines.push(`[审批附加说明] ${options.comment}`);
|
||||
}
|
||||
|
||||
const decisionSummary = summaryLines.join("\n");
|
||||
const {
|
||||
decision,
|
||||
decisionSummary,
|
||||
hardFailedCount,
|
||||
elasticFailedCount,
|
||||
suggestFailedCount,
|
||||
specialFailedCount,
|
||||
} = gatewayResult;
|
||||
|
||||
// 4. 更新数据库中的运行记录状态
|
||||
this.repo.updateApprovalRun(run.id, {
|
||||
decision,
|
||||
decisionSummary,
|
||||
failedRulesCount: failedFindings.length,
|
||||
failedRulesCount: gatewayResult.analysis.failedFindings.length,
|
||||
});
|
||||
|
||||
let appliedAction = options.requestedAction;
|
||||
@@ -332,10 +291,10 @@ export class ApprovalService {
|
||||
run: updatedRun,
|
||||
decision,
|
||||
decisionSummary,
|
||||
hardFailedCount: hardFailed.length,
|
||||
elasticFailedCount: elasticFailed.length,
|
||||
suggestFailedCount: suggestFailed.length,
|
||||
specialFailedCount: specialFailed.length,
|
||||
hardFailedCount,
|
||||
elasticFailedCount,
|
||||
suggestFailedCount,
|
||||
specialFailedCount,
|
||||
appliedAction,
|
||||
actionResult,
|
||||
};
|
||||
|
||||
+42
-1
@@ -18,7 +18,7 @@ function flowLookupSelect(): string {
|
||||
}
|
||||
|
||||
function flowDetailSelect(): string {
|
||||
return "flowId(form(`...`),logs(operatorId,nextOperatorId,`...`),plan(`...`),`...`),`...`";
|
||||
return "flowId(form(specificationId(id,name,code),`...`),logs(operatorId,nextOperatorId,`...`),plan(`...`),`...`),`...`";
|
||||
}
|
||||
|
||||
export async function listActiveStaffCatalog(
|
||||
@@ -396,3 +396,44 @@ export async function listEntitySchemas(
|
||||
const parsed = EntityListResponseSchema.parse(json);
|
||||
return parsed.items;
|
||||
}
|
||||
|
||||
// ── 发票票面查验详情与商品明细 API ──────────────────────────────────────────────
|
||||
|
||||
export async function getInvoiceValidationDetail(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
invoiceId: string
|
||||
): Promise<Record<string, unknown> | undefined> {
|
||||
try {
|
||||
const response = await client.get(`api/v2/invoice/validation/$${encodeURIComponent(invoiceId)}`, {
|
||||
searchParams: { masterId: invoiceId, corpId }
|
||||
});
|
||||
return (await response.json()) as Record<string, unknown>;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// ── 数据连接业务对象与卡片详情 API ──────────────────────────────────────────────
|
||||
|
||||
export async function getDatalinkCard(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
entityId: string,
|
||||
type = "CARD"
|
||||
): Promise<Record<string, unknown> | undefined> {
|
||||
try {
|
||||
const response = await client.get(`api/v2/datalink/detail/$${encodeURIComponent(entityId)}/$${encodeURIComponent(type)}`, {
|
||||
searchParams: {
|
||||
entityId,
|
||||
type,
|
||||
join: "data.dataLink.entityId,entity,/v2/datalink/entity",
|
||||
corpId,
|
||||
}
|
||||
});
|
||||
const json = (await response.json()) as { value?: Record<string, unknown> };
|
||||
return json?.value ?? undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -323,4 +323,187 @@ describe("Bill Domain", () => {
|
||||
expect(markdown).toContain("- **城市**: 辽宁省/大连市/大连市区");
|
||||
expect(markdown).toContain("- **消费事由**: `今日在大连见客户`");
|
||||
});
|
||||
|
||||
it("modular translator formatting functions format scalar and complex types properly", () => {
|
||||
const {
|
||||
formatAmountValue,
|
||||
formatDateValue,
|
||||
formatPersonValue,
|
||||
formatDepartmentValue,
|
||||
formatReferenceOrObject,
|
||||
formatApportionSplits,
|
||||
formatInlineAttachments,
|
||||
formatInlineInvoices,
|
||||
} = require("./translator.js");
|
||||
|
||||
// Amount
|
||||
expect(formatAmountValue({ standard: "350", standardStrCode: "CNY" })).toBe("CNY 350.00");
|
||||
expect(formatAmountValue(12.5)).toBe("CNY 12.50");
|
||||
expect(formatAmountValue("¥100")).toBe("CNY 100.00");
|
||||
|
||||
// Date
|
||||
expect(formatDateValue(1788364800000)).toMatch(/2026-09-03/);
|
||||
expect(formatDateValue(1788364800000, true)).toMatch(/2026-09-03 \d{2}:\d{2}/);
|
||||
|
||||
// Person
|
||||
const staffMap = new Map([["staff-1", { name: "张三", code: "ZS01" }]]);
|
||||
expect(formatPersonValue("staff-1", staffMap)).toBe("张三(ZS01)");
|
||||
expect(formatPersonValue({ name: "李四", code: "LS02" })).toBe("李四(LS02)");
|
||||
|
||||
// Department
|
||||
const deptMap = new Map([["dept-1", { path: "总公司/财务部" }]]);
|
||||
expect(formatDepartmentValue("dept-1", deptMap)).toBe("总公司/财务部");
|
||||
expect(formatDepartmentValue({ fullPath: "总公司/研发部" })).toBe("总公司/研发部");
|
||||
|
||||
// Reference & Objects (Supplier, Bank, Dimension)
|
||||
const dimMap = new Map([
|
||||
["ID_dim_1", { name: "钰泰半导体股份有限公司", code: "ETA" }],
|
||||
["ID_biz_1", { name: "费用", code: "CODE2" }],
|
||||
]);
|
||||
expect(formatReferenceOrObject("ID_dim_1", dimMap)).toBe("钰泰半导体股份有限公司(code=ETA)");
|
||||
expect(formatReferenceOrObject("ID_biz_1", dimMap)).toBe("费用(code=CODE2)");
|
||||
expect(formatReferenceOrObject({
|
||||
supplierName: "上海戴维迪",
|
||||
account: "03365200040008552",
|
||||
bank: "农业银行",
|
||||
})).toBe("供应商名称=上海戴维迪;账号=03365200040008552;银行=农业银行");
|
||||
|
||||
// Apportion splits
|
||||
const apportions = [
|
||||
{
|
||||
apportionForm: {
|
||||
apportionPercent: "100.00",
|
||||
apportionMoney: { standard: "350", standardStrCode: "CNY" },
|
||||
expenseDepartment: "dept-1",
|
||||
},
|
||||
},
|
||||
];
|
||||
expect(formatApportionSplits(apportions, deptMap)).toBe("分摊比例=100.00%;分摊金额=CNY 350.00;报销部门=总公司/财务部");
|
||||
|
||||
// Inline attachments
|
||||
const attachments = [
|
||||
{ fileName: "协议书.pdf", fileId: "file-01" },
|
||||
{ fileName: "账单.pdf", fileId: "file-02" },
|
||||
];
|
||||
const attLines = formatInlineAttachments(attachments);
|
||||
expect(attLines[0]).toBe("- **附件Attachment**:");
|
||||
expect(attLines[1]).toBe(" 1. `协议书.pdf` (fileId=\"file-01\")");
|
||||
expect(attLines[2]).toBe(" 2. `账单.pdf` (fileId=\"file-02\")");
|
||||
|
||||
// Inline invoices
|
||||
const invoices = [
|
||||
{
|
||||
invoiceCode: "26312000005586052981",
|
||||
fileInfo: { fileName: "发票原件.pdf", fileId: "inv-01" },
|
||||
buyer: "钰泰半导体",
|
||||
seller: "上海戴维迪",
|
||||
approveAmount: { standard: "350.00" },
|
||||
taxAmount: { standard: "19.81" },
|
||||
},
|
||||
];
|
||||
const invLines = formatInlineInvoices(invoices);
|
||||
expect(invLines[0]).toBe("- **发票列表**(1):");
|
||||
expect(invLines.join("\n")).toContain("发票号码: 26312000005586052981");
|
||||
expect(invLines.join("\n")).toContain("原始文件名: 发票原件.pdf");
|
||||
expect(invLines.join("\n")).toContain("购方: 钰泰半导体");
|
||||
expect(invLines.join("\n")).toContain("销方: 上海戴维迪");
|
||||
expect(invLines.join("\n")).toContain("价税合计: CNY 350.00");
|
||||
});
|
||||
|
||||
it("translates full bill preserving relative attachment and invoice positions", () => {
|
||||
const { translateBillFlowToMarkdown } = require("./translator.js");
|
||||
const complexFlow = {
|
||||
flowId: {
|
||||
state: "APPROVING",
|
||||
form: {
|
||||
code: "B26002288",
|
||||
title: "方镕霖的8月图文快印的对公付款",
|
||||
specificationId: "ID_PAYMENT",
|
||||
submitDate: 1788415807829,
|
||||
description: "戴维迪图文快印8月月结费用,¥350.00",
|
||||
法人实体: "dim_eta",
|
||||
expenseDepartment: "dept_admin",
|
||||
u_提交人部门: "dept_admin",
|
||||
u_经常交易供应商: "上海戴维迪图文制作有限公司",
|
||||
payMoney: { standard: "350.00", standardStrCode: "CNY" },
|
||||
expenseMoney: { standard: "350.00", standardStrCode: "CNY" },
|
||||
u_本单税额: { standard: "19.81", standardStrCode: "CNY" },
|
||||
details: [
|
||||
{
|
||||
feeTypeId: "fee_print",
|
||||
feeTypeForm: {
|
||||
amount: { standard: "350.00", standardStrCode: "CNY" },
|
||||
feeDate: 1788364800000,
|
||||
consumptionReasons: "8月图文快印",
|
||||
detailId: "DETAIL_01",
|
||||
detailNo: 1,
|
||||
u_业务类型: "dim_biz_fee",
|
||||
attachments: [
|
||||
{ fileName: "18-1-服务框架协议书.pdf", fileId: "ID01TvInwhsEwf" },
|
||||
{ fileName: "钰泰账单.pdf", fileId: "ID01VWUmNcRryf" },
|
||||
],
|
||||
invoiceForm: {
|
||||
invoices: [
|
||||
{
|
||||
invoiceCode: "26312000005586052981",
|
||||
buyer: "钰泰半导体股份有限公司",
|
||||
seller: "上海戴维迪图文制作有限公司",
|
||||
approveAmount: { standard: "350.00", standardStrCode: "CNY" },
|
||||
taxAmount: { standard: "19.81", standardStrCode: "CNY" },
|
||||
},
|
||||
],
|
||||
},
|
||||
apportions: [
|
||||
{
|
||||
apportionForm: {
|
||||
apportionPercent: "100.00",
|
||||
apportionMoney: { standard: "350.00", standardStrCode: "CNY" },
|
||||
expenseDepartment: "dept_admin",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const options = {
|
||||
dimensionItemMap: new Map([
|
||||
["dim_eta", { name: "钰泰半导体股份有限公司", code: "ETA" }],
|
||||
["dim_biz_fee", { name: "费用", code: "CODE2" }],
|
||||
]),
|
||||
departmentMap: new Map([
|
||||
["dept_admin", { path: "钰泰半导体/行政中心/人事行政部" }],
|
||||
]),
|
||||
feeTypeMap: new Map([
|
||||
["fee_print", { name: "图文快印费", path: "办公费/图文快印费" }],
|
||||
]),
|
||||
};
|
||||
|
||||
const md = translateBillFlowToMarkdown(complexFlow, options);
|
||||
// 验证顶层关键字段不再丢失
|
||||
expect(md).toContain("- **单号**: `B26002288`");
|
||||
expect(md).toContain("- **法人实体**: 钰泰半导体股份有限公司(code=ETA)");
|
||||
expect(md).toContain("- **费用承担部门**: 钰泰半导体/行政中心/人事行政部");
|
||||
expect(md).toContain("- **提交人部门**: 钰泰半导体/行政中心/人事行政部");
|
||||
expect(md).toContain("- **事由**: `戴维迪图文快印8月月结费用,¥350.00`");
|
||||
expect(md).toContain("- **经常交易供应商**: 上海戴维迪图文制作有限公司");
|
||||
expect(md).toContain("- **本单税额**: CNY 19.81");
|
||||
expect(md).toContain("- **支付金额**: CNY 350.00");
|
||||
|
||||
// 验证明细 1 内部原位挂载发票列表与附件列表
|
||||
expect(md).toContain("#### 明细 1");
|
||||
expect(md).toContain("- **费用类型**: 办公费/图文快印费(name=图文快印费)");
|
||||
expect(md).toContain("- **发票列表**(1):");
|
||||
expect(md).toContain("发票号码: 26312000005586052981");
|
||||
expect(md).toContain("购方: 钰泰半导体股份有限公司");
|
||||
expect(md).toContain("销方: 上海戴维迪图文制作有限公司");
|
||||
expect(md).toContain("- **业务类型**: 费用(code=CODE2)");
|
||||
expect(md).toContain("- **费用归属分摊**: 分摊比例=100.00%;分摊金额=CNY 350.00;报销部门=钰泰半导体/行政中心/人事行政部");
|
||||
expect(md).toContain("- **附件Attachment**:");
|
||||
expect(md).toContain("1. `18-1-服务框架协议书.pdf` (fileId=\"ID01TvInwhsEwf\")");
|
||||
expect(md).toContain("2. `钰泰账单.pdf` (fileId=\"ID01VWUmNcRryf\")");
|
||||
});
|
||||
});
|
||||
+165
-1
@@ -18,9 +18,12 @@ import {
|
||||
transferBillAction,
|
||||
addNodeBillAction,
|
||||
commentBillAction,
|
||||
getInvoiceValidationDetail,
|
||||
getDatalinkCard,
|
||||
type BillActionOptions,
|
||||
type BillActionTarget,
|
||||
} from "./api.js";
|
||||
import type { TranslatorOptions } from "./translator.js";
|
||||
import {
|
||||
type RawBillItem,
|
||||
type FormattedBill,
|
||||
@@ -1271,4 +1274,165 @@ export const billTools = [
|
||||
},
|
||||
];
|
||||
|
||||
export { translateBillFlowToMarkdown } from "./translator.js";
|
||||
export async function getTranslatorContext(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
rawFlow?: Record<string, unknown>
|
||||
): Promise<TranslatorOptions> {
|
||||
const [feeTypeTree, catalog, dimEntity, dimBiz, dimBool] = await Promise.allSettled([
|
||||
getFeeTypeTree(client, corpId),
|
||||
getReferenceCatalog(client, corpId),
|
||||
resolveDimension(client, corpId, "法人实体"),
|
||||
resolveDimension(client, corpId, "业务类型"),
|
||||
resolveDimension(client, corpId, "是否"),
|
||||
]);
|
||||
|
||||
const feeTypeMap = new Map<string, { name?: string; path?: string }>();
|
||||
if (feeTypeTree.status === "fulfilled") {
|
||||
const flat = flattenFeeTypes(feeTypeTree.value);
|
||||
for (const [id, val] of flat.entries()) {
|
||||
feeTypeMap.set(id, { name: val.name as string, path: val.path as string });
|
||||
}
|
||||
}
|
||||
|
||||
const staffMap = catalog.status === "fulfilled" ? catalog.value.staff : undefined;
|
||||
const departmentMap = catalog.status === "fulfilled" ? catalog.value.departments : undefined;
|
||||
|
||||
const dimensionItemMap = new Map<string, { name?: string; code?: string; label?: string }>();
|
||||
for (const dimRes of [dimEntity, dimBiz, dimBool]) {
|
||||
if (dimRes.status === "fulfilled" && dimRes.value?.items) {
|
||||
for (const item of dimRes.value.items) {
|
||||
dimensionItemMap.set(item.id, { name: item.name, code: item.code });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const invoiceDetailMap = new Map<string, Record<string, unknown>>();
|
||||
const datalinkCardMap = new Map<string, string>();
|
||||
|
||||
if (rawFlow) {
|
||||
const flowIdObj = (rawFlow.flowId && typeof rawFlow.flowId === "object" ? rawFlow.flowId : rawFlow) as Record<string, any>;
|
||||
const form = (flowIdObj.form && typeof flowIdObj.form === "object" ? flowIdObj.form : {}) as Record<string, any>;
|
||||
|
||||
// 1. 扫描所有发票 invoiceId
|
||||
const invoiceIds = new Set<string>();
|
||||
const details = Array.isArray(form.details) ? form.details : [];
|
||||
for (const d of details) {
|
||||
const ftf = d?.feeTypeForm || d || {};
|
||||
const invs = ftf.invoiceForm?.invoices || ftf.invoices || [];
|
||||
if (Array.isArray(invs)) {
|
||||
for (const inv of invs) {
|
||||
const id = inv.invoiceId || inv.id;
|
||||
if (typeof id === "string" && id) invoiceIds.add(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const invoiceFetches = Array.from(invoiceIds).map(async (id) => {
|
||||
const detail = await getInvoiceValidationDetail(client, corpId, id);
|
||||
if (detail) invoiceDetailMap.set(id, detail);
|
||||
});
|
||||
|
||||
// 2. 扫描数据连接/卡片 ID (例如供应商 ID01...,payeeId 等)
|
||||
const cardCandidateIds = new Set<string>();
|
||||
for (const [_, v] of Object.entries(form)) {
|
||||
if (typeof v === "string" && v.startsWith("ID01")) {
|
||||
if (!dimensionItemMap.has(v)) {
|
||||
cardCandidateIds.add(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const cardFetches = Array.from(cardCandidateIds).map(async (cardId) => {
|
||||
const cardVal = await getDatalinkCard(client, corpId, cardId);
|
||||
const cardObj = (cardVal?.data as any)?.dataLink || (cardVal?.data as any)?.form || cardVal?.data;
|
||||
if (cardObj && typeof cardObj === "object") {
|
||||
const parts: string[] = [];
|
||||
let suppName = "";
|
||||
let suppCode = "";
|
||||
let bankCard = "";
|
||||
let payeeInfoStr = "";
|
||||
let payeeInfoDirect = "";
|
||||
|
||||
for (const [fieldKey, fieldVal] of Object.entries(cardObj)) {
|
||||
if (fieldKey.endsWith("_name") || fieldKey.includes("供应商名称")) {
|
||||
suppName = String(fieldVal);
|
||||
} else if (fieldKey.endsWith("_code") || fieldKey.includes("供应商编码")) {
|
||||
suppCode = String(fieldVal);
|
||||
} else if (fieldKey.includes("银行卡号") || fieldKey.includes("卡号")) {
|
||||
bankCard = String(fieldVal);
|
||||
} else if (fieldKey.includes("收款信息") && typeof fieldVal === "object" && fieldVal !== null) {
|
||||
const pi = fieldVal as Record<string, any>;
|
||||
const piParts: string[] = [];
|
||||
const directParts: string[] = [];
|
||||
const accountName = pi.name || pi.accountName || pi.accountOwner;
|
||||
const accountNo = pi.cardNo || pi.account;
|
||||
const accountType = (pi.type || pi.accountType) === "PUBLIC" ? "对公账户" : (pi.type || pi.accountType);
|
||||
const accountSort = pi.sort || pi.accountCategory || pi.accountClass;
|
||||
const bankName = pi.bank || pi.bankName;
|
||||
const branchName = pi.branch || pi.openBankName;
|
||||
|
||||
if (accountName) piParts.push(`开户名=${accountName}`);
|
||||
if (accountNo) piParts.push(`账号=${accountNo}`);
|
||||
if (accountType) piParts.push(`账户类型=${accountType}`);
|
||||
if (accountSort) piParts.push(`账户类别=${accountSort}`);
|
||||
if (bankName) piParts.push(`银行=${bankName}`);
|
||||
if (branchName) piParts.push(`开户网点=${branchName}`);
|
||||
if (piParts.length > 0) {
|
||||
payeeInfoStr = piParts.join(";");
|
||||
}
|
||||
|
||||
if (accountNo) directParts.push(`账号=${accountNo}`);
|
||||
if (bankName) directParts.push(`银行=${bankName}`);
|
||||
if (accountName) directParts.push(`开户名=${accountName}`);
|
||||
if (branchName) directParts.push(`开户网点=${branchName}`);
|
||||
if (accountType) directParts.push(`账户类型=${accountType}`);
|
||||
if (accountSort) directParts.push(`账户类别=${accountSort}`);
|
||||
if (directParts.length > 0) {
|
||||
payeeInfoDirect = directParts.join(";");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (suppName) parts.push(`供应商名称=${suppName}`);
|
||||
if (suppCode) parts.push(`供应商编码=${suppCode}`);
|
||||
if (bankCard) parts.push(`银行卡号=${bankCard}`);
|
||||
if (payeeInfoStr) parts.push(`收款信息=${payeeInfoStr}`);
|
||||
|
||||
if (parts.length > 0) {
|
||||
datalinkCardMap.set(cardId, parts.join(";"));
|
||||
}
|
||||
if (payeeInfoDirect || payeeInfoStr) {
|
||||
const valToSet = payeeInfoDirect || payeeInfoStr;
|
||||
datalinkCardMap.set(`payeeInfo:${cardId}`, valToSet);
|
||||
if (suppCode) datalinkCardMap.set(suppCode, valToSet);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
await Promise.allSettled([...invoiceFetches, ...cardFetches]);
|
||||
}
|
||||
|
||||
return {
|
||||
feeTypeMap,
|
||||
staffMap,
|
||||
departmentMap,
|
||||
dimensionItemMap,
|
||||
invoiceDetailMap,
|
||||
datalinkCardMap,
|
||||
};
|
||||
}
|
||||
|
||||
export {
|
||||
translateBillFlowToMarkdown,
|
||||
formatAmountValue,
|
||||
formatDateValue,
|
||||
formatPersonValue,
|
||||
formatDepartmentValue,
|
||||
formatReferenceOrObject,
|
||||
formatApportionSplits,
|
||||
formatInlineInvoices,
|
||||
formatInlineAttachments,
|
||||
formatDynamicField,
|
||||
type TranslatorOptions,
|
||||
} from "./translator.js";
|
||||
+586
-80
@@ -1,91 +1,472 @@
|
||||
import { KyInstance } from "ky";
|
||||
import { getRawBillFlow } from "./api.js";
|
||||
import { getFeeTypeTree } from "./api.js";
|
||||
|
||||
function formatDate(val: unknown): string {
|
||||
if (!val) return "";
|
||||
if (typeof val === "number" || (typeof val === "string" && /^\d+$/.test(val))) {
|
||||
const d = new Date(Number(val));
|
||||
if (!isNaN(d.getTime())) {
|
||||
const year = d.getFullYear();
|
||||
const month = String(d.getMonth() + 1).padStart(2, "0");
|
||||
const day = String(d.getDate()).padStart(2, "0");
|
||||
return `${year}-${month}-${day}`;
|
||||
}
|
||||
}
|
||||
if (typeof val === "string") {
|
||||
const match = val.match(/^(\d{4})[-/](\d{1,2})[-/](\d{1,2})/);
|
||||
if (match) {
|
||||
return `${match[1]}-${match[2].padStart(2, "0")}-${match[3].padStart(2, "0")}`;
|
||||
}
|
||||
return val;
|
||||
}
|
||||
return String(val);
|
||||
export interface TranslatorOptions {
|
||||
feeTypeMap?: Map<string, { name?: string; path?: string }>;
|
||||
staffMap?: Map<string, Record<string, unknown>>;
|
||||
departmentMap?: Map<string, { path?: string; item?: Record<string, unknown> }>;
|
||||
dimensionItemMap?: Map<string, { name?: string; code?: string; label?: string; path?: string }>;
|
||||
dictionary?: Map<string, { label: string; type?: string }>;
|
||||
corpName?: string;
|
||||
}
|
||||
|
||||
function formatDateTime(val: unknown): string {
|
||||
if (!val) return "";
|
||||
if (typeof val === "number" || (typeof val === "string" && /^\d+$/.test(val))) {
|
||||
const d = new Date(Number(val));
|
||||
if (!isNaN(d.getTime())) {
|
||||
const year = d.getFullYear();
|
||||
const month = String(d.getMonth() + 1).padStart(2, "0");
|
||||
const day = String(d.getDate()).padStart(2, "0");
|
||||
const hours = String(d.getHours()).padStart(2, "0");
|
||||
const minutes = String(d.getMinutes()).padStart(2, "0");
|
||||
return `${year}-${month}-${day} ${hours}:${minutes}`;
|
||||
}
|
||||
}
|
||||
return String(val);
|
||||
}
|
||||
// ── 1. 金额格式化 ─────────────────────────────────────────────────────────────
|
||||
|
||||
function parseCity(cityVal: unknown): string {
|
||||
if (!cityVal) return "";
|
||||
if (typeof cityVal === "string") {
|
||||
try {
|
||||
const parsed = JSON.parse(cityVal);
|
||||
if (Array.isArray(parsed) && parsed[0]?.label) {
|
||||
return parsed[0].label;
|
||||
}
|
||||
} catch {}
|
||||
return cityVal;
|
||||
}
|
||||
if (Array.isArray(cityVal) && cityVal[0]?.label) {
|
||||
return cityVal[0].label;
|
||||
}
|
||||
return String(cityVal);
|
||||
}
|
||||
|
||||
function formatAmount(money: any): string {
|
||||
if (!money) return "CNY 0.00";
|
||||
export function formatAmountValue(money: unknown): string {
|
||||
if (money === null || money === undefined || money === "") return "CNY 0.00";
|
||||
if (typeof money === "number") return `CNY ${money.toFixed(2)}`;
|
||||
if (typeof money === "string") {
|
||||
const n = parseFloat(money.replace(/[^0-9.-]/g, ""));
|
||||
return isNaN(n) ? money : `CNY ${n.toFixed(2)}`;
|
||||
const trimmed = money.trim();
|
||||
if (!trimmed) return "CNY 0.00";
|
||||
const n = parseFloat(trimmed.replace(/[^0-9.-]/g, ""));
|
||||
if (isNaN(n)) return trimmed;
|
||||
const currencyMatch = trimmed.match(/^([A-Za-z]{3}|¥|\$)/);
|
||||
const curr = currencyMatch ? (currencyMatch[1] === "¥" ? "CNY" : currencyMatch[1]) : "CNY";
|
||||
return `${curr} ${n.toFixed(2)}`;
|
||||
}
|
||||
if (typeof money === "object") {
|
||||
const currency = money.standardStrCode || money.currency || "CNY";
|
||||
const amountNum = parseFloat(money.standard || money.amount || 0);
|
||||
return `${currency} ${isNaN(amountNum) ? "0.00" : amountNum.toFixed(2)}`;
|
||||
const obj = money as Record<string, unknown>;
|
||||
const curr = (obj.standardStrCode || obj.currency || (obj.standardSymbol === "¥" ? "CNY" : obj.standardSymbol) || "CNY") as string;
|
||||
const val = obj.standard ?? obj.amount ?? obj.value ?? 0;
|
||||
const n = typeof val === "number" ? val : parseFloat(String(val).replace(/[^0-9.-]/g, ""));
|
||||
return `${curr} ${isNaN(n) ? "0.00" : n.toFixed(2)}`;
|
||||
}
|
||||
return String(money);
|
||||
}
|
||||
|
||||
function resolveSpecificationName(specId: unknown): string {
|
||||
if (!specId || typeof specId !== "string") return "未知模板";
|
||||
// ── 2. 日期时间格式化 ─────────────────────────────────────────────────────────
|
||||
|
||||
export function formatDateValue(val: unknown, withTime = false): string {
|
||||
if (!val) return "";
|
||||
let d: Date | undefined;
|
||||
if (typeof val === "number" || (typeof val === "string" && /^\d+$/.test(val.trim()))) {
|
||||
const num = Number(val);
|
||||
if (!isNaN(num) && num > 0) d = new Date(num);
|
||||
} else if (typeof val === "string") {
|
||||
const match = val.match(/^(\d{4})[-/](\d{1,2})[-/](\d{1,2})(?:[ T](\d{1,2}):(\d{1,2}))?/);
|
||||
if (match) {
|
||||
const year = match[1];
|
||||
const month = match[2].padStart(2, "0");
|
||||
const day = match[3].padStart(2, "0");
|
||||
if (withTime && match[4] !== undefined && match[5] !== undefined) {
|
||||
return `${year}-${month}-${day} ${match[4].padStart(2, "0")}:${match[5].padStart(2, "0")}`;
|
||||
}
|
||||
return `${year}-${month}-${day}`;
|
||||
}
|
||||
const parsed = Date.parse(val);
|
||||
if (!isNaN(parsed)) d = new Date(parsed);
|
||||
}
|
||||
|
||||
if (d && !isNaN(d.getTime())) {
|
||||
const formatter = new Intl.DateTimeFormat("zh-CN", {
|
||||
timeZone: "Asia/Shanghai",
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
...(withTime ? { hour: "2-digit", minute: "2-digit", hour12: false } : {}),
|
||||
});
|
||||
const parts = formatter.formatToParts(d);
|
||||
const partMap: Record<string, string> = {};
|
||||
for (const p of parts) partMap[p.type] = p.value;
|
||||
const dateStr = `${partMap.year}-${partMap.month}-${partMap.day}`;
|
||||
if (withTime && partMap.hour !== undefined && partMap.minute !== undefined) {
|
||||
return `${dateStr} ${partMap.hour}:${partMap.minute}`;
|
||||
}
|
||||
return dateStr;
|
||||
}
|
||||
return String(val);
|
||||
}
|
||||
|
||||
// ── 3. 城市解析 ───────────────────────────────────────────────────────────────
|
||||
|
||||
export function parseCityValue(cityVal: unknown): string {
|
||||
if (!cityVal) return "";
|
||||
if (typeof cityVal === "string") {
|
||||
try {
|
||||
const parsed = JSON.parse(cityVal);
|
||||
if (Array.isArray(parsed) && parsed[0]?.label) return parsed[0].label;
|
||||
} catch {}
|
||||
return cityVal;
|
||||
}
|
||||
if (Array.isArray(cityVal) && cityVal[0]?.label) {
|
||||
return String(cityVal[0].label);
|
||||
}
|
||||
return String(cityVal);
|
||||
}
|
||||
|
||||
// ── 4. 员工/人员格式化 ─────────────────────────────────────────────────────────
|
||||
|
||||
export function formatPersonValue(
|
||||
val: unknown,
|
||||
staffMap?: Map<string, Record<string, unknown>>
|
||||
): string {
|
||||
if (!val) return "未知";
|
||||
if (Array.isArray(val)) {
|
||||
return val.map((v) => formatPersonValue(v, staffMap)).join("、");
|
||||
}
|
||||
if (typeof val === "string") {
|
||||
const trimmed = val.trim();
|
||||
if (staffMap?.has(trimmed)) {
|
||||
const match = staffMap.get(trimmed)!;
|
||||
const name = (match.name || match.nickName || trimmed) as string;
|
||||
const code = match.code ? `(${match.code})` : "";
|
||||
return `${name}${code}`;
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
if (typeof val === "object") {
|
||||
const obj = val as Record<string, unknown>;
|
||||
const name = (obj.name || obj.nickName || obj.staffName || "") as string;
|
||||
const code = obj.code ? `(${obj.code})` : "";
|
||||
if (name) return `${name}${code}`;
|
||||
}
|
||||
return String(val);
|
||||
}
|
||||
|
||||
export interface TranslatorOptions {
|
||||
corpName?: string;
|
||||
feeTypeMap?: Map<string, { name?: string; path?: string }>;
|
||||
staffMap?: Map<string, Record<string, unknown>>;
|
||||
departmentMap?: Map<string, { path?: string; item?: Record<string, unknown> }>;
|
||||
dimensionItemMap?: Map<string, { name?: string; code?: string; label?: string; path?: string }>;
|
||||
invoiceDetailMap?: Map<string, Record<string, unknown>>;
|
||||
datalinkCardMap?: Map<string, string>;
|
||||
}
|
||||
|
||||
// ── 5. 部门全路径格式化 ───────────────────────────────────────────────────────
|
||||
|
||||
export function formatDepartmentValue(
|
||||
val: unknown,
|
||||
departmentMap?: Map<string, { path?: string; item?: Record<string, unknown> }>
|
||||
): string {
|
||||
if (!val) return "";
|
||||
if (Array.isArray(val)) {
|
||||
return val.map((v) => formatDepartmentValue(v, departmentMap)).join("、");
|
||||
}
|
||||
if (typeof val === "string") {
|
||||
const trimmed = val.trim();
|
||||
if (departmentMap?.has(trimmed)) {
|
||||
const match = departmentMap.get(trimmed)!;
|
||||
return match.path || (match.item?.name as string) || trimmed;
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
if (typeof val === "object") {
|
||||
const obj = val as Record<string, unknown>;
|
||||
const id = (obj.id || obj.deptId || obj.departmentId || "") as string;
|
||||
if (id) {
|
||||
const match = departmentMap?.get(id) ?? departmentMap?.get(id.split(":").at(-1) ?? id);
|
||||
if (match?.path) return match.path;
|
||||
if (match?.item?.name) return match.item.name as string;
|
||||
}
|
||||
return (obj.fullPath || obj.path || obj.name || "") as string;
|
||||
}
|
||||
return String(val);
|
||||
}
|
||||
|
||||
// ── 6. 复杂对象与引用字典格式化 (供应商/银行卡号/枚举/档案项) ──────────────────
|
||||
|
||||
export function formatReferenceOrObject(
|
||||
val: unknown,
|
||||
dimensionMap?: Map<string, { name?: string; code?: string; label?: string; path?: string }>,
|
||||
datalinkCardMap?: Map<string, string>
|
||||
): string {
|
||||
if (val === null || val === undefined) return "";
|
||||
if (typeof val === "boolean") return val ? "是" : "否";
|
||||
if (typeof val === "number") return String(val);
|
||||
|
||||
if (typeof val === "string") {
|
||||
const trimmed = val.trim();
|
||||
if (datalinkCardMap?.has(trimmed)) {
|
||||
return datalinkCardMap.get(trimmed)!;
|
||||
}
|
||||
if (dimensionMap?.has(trimmed)) {
|
||||
const match = dimensionMap.get(trimmed)!;
|
||||
const title = match.name || match.label || match.path || trimmed;
|
||||
return match.code ? `${title}(code=${match.code})` : title;
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
if (Array.isArray(val)) {
|
||||
const city = parseCityValue(val);
|
||||
if (city && city !== String(val)) return city;
|
||||
return val.map((item) => formatReferenceOrObject(item, dimensionMap, datalinkCardMap)).join(";");
|
||||
}
|
||||
|
||||
if (typeof val === "object") {
|
||||
const obj = val as Record<string, unknown>;
|
||||
// 金额对象判断
|
||||
if ("standard" in obj || "standardStrCode" in obj) {
|
||||
return formatAmountValue(obj);
|
||||
}
|
||||
// 标准枚举/档案节点判断
|
||||
if (obj.name || obj.label) {
|
||||
const title = (obj.name || obj.label || "") as string;
|
||||
const code = obj.code ? `(code=${obj.code})` : "";
|
||||
return `${title}${code}`;
|
||||
}
|
||||
// 供应商/银行账户解构
|
||||
const parts: string[] = [];
|
||||
if (obj.supplierName) parts.push(`供应商名称=${obj.supplierName}`);
|
||||
if (obj.supplierCode) parts.push(`供应商编码=${obj.supplierCode}`);
|
||||
if (obj.accountName || obj.accountOwner) parts.push(`开户名=${obj.accountName || obj.accountOwner}`);
|
||||
if (obj.account || obj.cardNo || obj.bankCardNo) parts.push(`账号=${obj.account || obj.cardNo || obj.bankCardNo}`);
|
||||
if (obj.bankCardNumber) parts.push(`银行卡号=${obj.bankCardNumber}`);
|
||||
if (obj.accountType) parts.push(`账户类型=${obj.accountType}`);
|
||||
if (obj.accountCategory) parts.push(`账户类别=${obj.accountCategory}`);
|
||||
if (obj.bank || obj.bankName) parts.push(`银行=${obj.bank || obj.bankName}`);
|
||||
if (obj.openBankName || obj.branchBank) parts.push(`开户网点=${obj.openBankName || obj.branchBank}`);
|
||||
if (parts.length > 0) return parts.join(";");
|
||||
|
||||
// 默认键值对铺平
|
||||
const entries = Object.entries(obj).filter(([k, v]) => v !== null && v !== undefined && v !== "");
|
||||
if (entries.length === 0) return "";
|
||||
return entries.map(([k, v]) => `${k}=${typeof v === "object" ? formatReferenceOrObject(v, dimensionMap) : v}`).join(";");
|
||||
}
|
||||
|
||||
return String(val);
|
||||
}
|
||||
|
||||
// ── 7. 费用归属分摊格式化 ─────────────────────────────────────────────────────
|
||||
|
||||
export function formatApportionSplits(
|
||||
apportions: unknown[],
|
||||
departmentMap?: Map<string, { path?: string; item?: Record<string, unknown> }>
|
||||
): string {
|
||||
if (!Array.isArray(apportions) || apportions.length === 0) return "";
|
||||
const parts: string[] = [];
|
||||
for (const item of apportions) {
|
||||
if (!item || typeof item !== "object") continue;
|
||||
const form = (item as Record<string, unknown>).apportionForm && typeof (item as Record<string, unknown>).apportionForm === "object"
|
||||
? (item as Record<string, unknown>).apportionForm as Record<string, unknown>
|
||||
: (item as Record<string, unknown>);
|
||||
|
||||
const subParts: string[] = [];
|
||||
let percent = form.apportionPercent || form.percent;
|
||||
if (percent !== undefined && percent !== null && percent !== "") {
|
||||
const pStr = String(percent);
|
||||
subParts.push(`分摊比例=${pStr.endsWith("%") ? pStr : `${pStr}%`}`);
|
||||
}
|
||||
const money = form.apportionMoney || form.money || form.amount;
|
||||
if (money !== undefined && money !== null) {
|
||||
subParts.push(`分摊金额=${formatAmountValue(money)}`);
|
||||
}
|
||||
const dept = form.expenseDepartment || form.department;
|
||||
if (dept) {
|
||||
subParts.push(`报销部门=${formatDepartmentValue(dept, departmentMap)}`);
|
||||
}
|
||||
if (subParts.length > 0) {
|
||||
parts.push(subParts.join(";"));
|
||||
}
|
||||
}
|
||||
return parts.join(" | ");
|
||||
}
|
||||
|
||||
// ── 8. 明细发票列表行内格式化 ─────────────────────────────────────────────────
|
||||
|
||||
export function formatInlineInvoices(
|
||||
invoices: unknown[],
|
||||
invoiceDetailMap?: Map<string, Record<string, unknown>>
|
||||
): string[] {
|
||||
if (!Array.isArray(invoices) || invoices.length === 0) return [];
|
||||
const lines: string[] = [];
|
||||
lines.push(`- **发票列表**(${invoices.length}):`);
|
||||
|
||||
invoices.forEach((invItem: any, idx: number) => {
|
||||
const num = idx + 1;
|
||||
const inv = invItem.invoice || invItem;
|
||||
const rawInvoiceId = String(inv.invoiceId || inv.id || "");
|
||||
const detailFromMap = (rawInvoiceId && invoiceDetailMap?.get(rawInvoiceId)) || undefined;
|
||||
const master = detailFromMap?.master as Record<string, unknown> | undefined;
|
||||
const masterForm = (master?.form as Record<string, unknown>) || {};
|
||||
const goodsDetails = Array.isArray(detailFromMap?.details) ? detailFromMap.details : [];
|
||||
|
||||
const verify = inv.verifyResult || inv;
|
||||
const fileInfo = inv.fileInfo || {};
|
||||
let code = inv.invoiceCode || inv.invoiceNo || inv.invoiceNumber || verify.invoiceNo || (masterForm["E_system_发票主体_发票号码"] as string) || inv.invoiceId || `发票-${num}`;
|
||||
if (typeof code === "string" && code.includes("::")) {
|
||||
code = code.split("::").at(-1) || code;
|
||||
}
|
||||
|
||||
const fileId = fileInfo.fileId || inv.fileId || inv.invoiceId || "";
|
||||
let fileName = fileInfo.fileName || inv.fileName || "";
|
||||
if (!fileName && masterForm["E_system_发票主体_图片"]) {
|
||||
try {
|
||||
fileName = decodeURIComponent(String(masterForm["E_system_发票主体_图片"]));
|
||||
} catch {
|
||||
fileName = String(masterForm["E_system_发票主体_图片"]);
|
||||
}
|
||||
}
|
||||
const fileType = fileInfo.fileType || inv.fileType || "invoice";
|
||||
const rawDate = inv.invoiceDate || verify.invoiceDate || masterForm["E_system_发票主体_发票日期"];
|
||||
const invoiceDate = formatDateValue(rawDate);
|
||||
const verifyStatus = inv.verifyState || verify.verifyStatus || (masterForm["E_system_发票主体_验真"] ? "verified" : undefined) || "verified";
|
||||
const buyer = verify.buyer || inv.buyer || masterForm["E_system_发票主体_购买方名称"] || "";
|
||||
const buyerTax = verify.buyerTaxNo || inv.buyerTaxNo || masterForm["E_system_发票主体_购买方纳税人识别号"] || "";
|
||||
const seller = verify.seller || inv.seller || masterForm["E_system_发票主体_销售方名称"] || "";
|
||||
const sellerTax = verify.sellerTaxNo || inv.sellerTaxNo || masterForm["E_system_发票主体_销售方纳税人识别号"] || "";
|
||||
|
||||
let invoiceType = inv.invoiceType || verify.invoiceType;
|
||||
if (!invoiceType && masterForm["E_system_发票主体_发票类别"]) {
|
||||
const cat = String(masterForm["E_system_发票主体_发票类别"]);
|
||||
if (cat.includes("SPECIAL") || cat.includes("专票")) {
|
||||
invoiceType = "电子发票(增值税专用发票)";
|
||||
} else {
|
||||
invoiceType = "电子发票";
|
||||
}
|
||||
}
|
||||
invoiceType = invoiceType || "电子发票";
|
||||
|
||||
const remark = (masterForm["E_system_发票主体_备注"] as string) || inv.remark || "";
|
||||
const totalAmount = formatAmountValue(inv.approveAmount || inv.totalAmount || verify.amount || inv.amount || masterForm["E_system_发票主体_价税合计"]);
|
||||
const taxAmount = formatAmountValue(inv.taxAmount || verify.taxAmount || masterForm["E_system_发票主体_税额"]);
|
||||
|
||||
lines.push(` ${num}. **发票号码: ${code}**`);
|
||||
if (fileId) lines.push(` 原始文件fileId: ${fileId}`);
|
||||
if (fileName) lines.push(` 原始文件名: ${fileName}`);
|
||||
if (fileType) lines.push(` 原始文件类型: ${fileType}`);
|
||||
if (invoiceDate) lines.push(` 发票日期: ${invoiceDate}`);
|
||||
if (verifyStatus) lines.push(` 验真状态: ${verifyStatus}`);
|
||||
if (buyer) lines.push(` 购方: ${buyer}${buyerTax ? `,税号: ${buyerTax}` : ""}`);
|
||||
if (seller) lines.push(` 销方: ${seller}${sellerTax ? `,税号: ${sellerTax}` : ""}`);
|
||||
if (invoiceType) lines.push(` 发票类型: ${invoiceType}`);
|
||||
if (remark) lines.push(` 备注: ${remark}`);
|
||||
lines.push(` 价税合计: ${totalAmount}`);
|
||||
if (taxAmount && taxAmount !== "CNY 0.00") lines.push(` 税额: ${taxAmount}`);
|
||||
|
||||
const items = verify.items || inv.items || (goodsDetails.length > 0 ? goodsDetails.map((gd: any) => {
|
||||
const f = gd.form || {};
|
||||
return {
|
||||
名称: gd.name || f["E_system_发票明细_name"] || "",
|
||||
单位: f["E_system_发票明细_单位"] || "",
|
||||
数量: String(f["E_system_发票明细_数量"] || ""),
|
||||
单价: formatAmountValue(f["E_system_发票明细_单价"]),
|
||||
金额: formatAmountValue(f["E_system_发票明细_金额"]),
|
||||
税率: f["E_system_发票明细_税率"] || "",
|
||||
税额: formatAmountValue(f["E_system_发票明细_税额"]),
|
||||
};
|
||||
}) : undefined);
|
||||
|
||||
if (Array.isArray(items) && items.length > 0) {
|
||||
lines.push(` 发票明细(${items.length}):`);
|
||||
for (const it of items) {
|
||||
lines.push(` - ${JSON.stringify(it)}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (master && Object.keys(masterForm).length > 0) {
|
||||
const invInfoObj = {
|
||||
销售方地址电话: masterForm["E_system_发票主体_销售方地址电话"] || "",
|
||||
是否有发票原件: masterForm["E_system_发票主体_是否有发票原件"] ? "是" : "否",
|
||||
收票状态: masterForm["E_system_收票状态"] || "NORECEIVE",
|
||||
可抵扣税额: formatAmountValue(masterForm["E_税额"] || masterForm["E_system_发票主体_税额"]),
|
||||
名称: masterForm["E_system_发票主体_name"] || code,
|
||||
发票号码: code,
|
||||
发票日期: invoiceDate,
|
||||
购买方名称: buyer,
|
||||
购买方纳税人识别号: buyerTax,
|
||||
发票金额: formatAmountValue(masterForm["E_不计税金额"] || masterForm["E_system_发票主体_发票金额"]),
|
||||
税额: taxAmount,
|
||||
价税合计: totalAmount,
|
||||
销售方名称: seller,
|
||||
销售方纳税人识别号: sellerTax,
|
||||
销售方开户行及账号: masterForm["E_system_发票主体_销售方开户行及账号"] || "",
|
||||
备注: remark,
|
||||
发票类别: invoiceType,
|
||||
不计税金额: formatAmountValue(masterForm["E_不计税金额"] || masterForm["E_system_发票主体_发票金额"]),
|
||||
发票状态: masterForm["E_system_发票主体_发票状态"] || "NORMAL_BLUE",
|
||||
是否电子票: masterForm["E_system_发票主体_是否电子票"] ? "是" : "否",
|
||||
};
|
||||
lines.push(` 发票信息: ${JSON.stringify(invInfoObj)}`);
|
||||
}
|
||||
});
|
||||
|
||||
return lines;
|
||||
}
|
||||
|
||||
// ── 9. 明细附件列表行内格式化 ─────────────────────────────────────────────────
|
||||
|
||||
export function formatInlineAttachments(attachments: unknown[]): string[] {
|
||||
if (!Array.isArray(attachments) || attachments.length === 0) return [];
|
||||
const valid = attachments.filter((item): item is Record<string, unknown> => Boolean(item && typeof item === "object"));
|
||||
if (valid.length === 0) return [];
|
||||
|
||||
const lines: string[] = [];
|
||||
lines.push(`- **附件Attachment**:`);
|
||||
valid.forEach((att: any, idx: number) => {
|
||||
const num = idx + 1;
|
||||
const name = att.fileName || att.name || "未命名附件";
|
||||
const fileId = att.fileId ? ` (fileId="${att.fileId}")` : "";
|
||||
lines.push(` ${num}. \`${name}\`${fileId}`);
|
||||
});
|
||||
return lines;
|
||||
}
|
||||
|
||||
// ── 10. 模板名称标准化 ────────────────────────────────────────────────────────
|
||||
|
||||
export function resolveSpecificationName(specId: unknown): string {
|
||||
if (!specId) return "未知模板";
|
||||
if (typeof specId === "object") {
|
||||
const obj = specId as Record<string, unknown>;
|
||||
if (typeof obj.name === "string" && obj.name) return obj.name;
|
||||
if (typeof obj.id === "string") return resolveSpecificationName(obj.id);
|
||||
}
|
||||
if (typeof specId !== "string") return "未知模板";
|
||||
if (specId.includes("REQUISITION_TRIP") || specId.includes("trip")) return "差旅申请单";
|
||||
if (specId.includes("REIMBURSEMENT") || specId.includes("expense")) return "报销单";
|
||||
if (specId.includes("LOAN") || specId.includes("loan")) return "借款单";
|
||||
if (specId.includes("PAYMENT") || specId.includes("payment")) return "对公付款单";
|
||||
if (specId.includes("PAYMENT") || specId.includes("payment")) return "对公付款";
|
||||
return specId;
|
||||
}
|
||||
|
||||
// ── 11. 动态表单字段过滤与格式化 ──────────────────────────────────────────────
|
||||
|
||||
const BUILTIN_SYSTEM_KEYS = new Set([
|
||||
"code", "title", "specificationId", "details", "itineraries", "logs", "flowPlanId",
|
||||
"actions", "threadId", "pipeline", "grayver", "dbVersion", "active", "version",
|
||||
"sourceSign", "createTime", "updateTime", "printState", "printCount", "onlyOwnerPrint",
|
||||
"ownerAndApproverPrintNodeFlag", "rejectionNum", "reviewStatus", "voucherStatus",
|
||||
"voucherCreateTime", "preApprovedNodeName", "preNodeApprovedTime", "submitterId",
|
||||
"expenseDate", "requisitionDate", "submitDate", "description", "expenseMoney",
|
||||
"payMoney", "amount", "requisitionMoney", "companyRealPay", "writtenOffMoney",
|
||||
"法人实体", "expenseDepartment", "u_提交人部门", "voucherNo", "payeeId",
|
||||
"u_发票金额", "u_本单税额", "u_本单不含税", "u_是否有纸质票据", "u_经常交易供应商"
|
||||
]);
|
||||
|
||||
export function formatDynamicField(
|
||||
key: string,
|
||||
val: unknown,
|
||||
options?: TranslatorOptions
|
||||
): { label: string; text: string } | undefined {
|
||||
if (BUILTIN_SYSTEM_KEYS.has(key)) return undefined;
|
||||
if (val === null || val === undefined || val === "") return undefined;
|
||||
|
||||
let label = (options as any)?.dictionary?.get(key)?.label || key.replace(/^u_/, "");
|
||||
const lowerKey = key.toLowerCase();
|
||||
|
||||
let text: string;
|
||||
if (lowerKey.includes("money") || lowerKey.includes("amount") || lowerKey.includes("金额") || lowerKey.includes("税额")) {
|
||||
text = formatAmountValue(val);
|
||||
} else if (lowerKey.includes("date") || lowerKey.includes("time") || lowerKey.includes("日期") || lowerKey.includes("时间")) {
|
||||
text = formatDateValue(val);
|
||||
} else if (lowerKey.includes("department") || lowerKey.includes("部门")) {
|
||||
text = formatDepartmentValue(val, options?.departmentMap);
|
||||
} else if (lowerKey.includes("person") || lowerKey.includes("staff") || lowerKey.includes("submitter")) {
|
||||
text = formatPersonValue(val, options?.staffMap);
|
||||
} else {
|
||||
text = formatReferenceOrObject(val, options?.dimensionItemMap, options?.datalinkCardMap);
|
||||
}
|
||||
|
||||
if (!text) return undefined;
|
||||
return { label, text };
|
||||
}
|
||||
|
||||
// ── 12. 主入口:全量单据流转译 Markdown ───────────────────────────────────────
|
||||
|
||||
/**
|
||||
* 将合思原始单据流对象转译为标准 LLM / 审核视图 Markdown (单据字段转译器)
|
||||
*/
|
||||
export function translateBillFlowToMarkdown(
|
||||
rawFlow: Record<string, unknown>,
|
||||
feeTypeMap?: Map<string, { name?: string; path?: string }>
|
||||
options?: TranslatorOptions
|
||||
): string {
|
||||
const flowIdObj = (rawFlow.flowId && typeof rawFlow.flowId === "object" ? rawFlow.flowId : rawFlow) as Record<string, any>;
|
||||
const form = (flowIdObj.form && typeof flowIdObj.form === "object" ? flowIdObj.form : {}) as Record<string, any>;
|
||||
@@ -94,11 +475,10 @@ export function translateBillFlowToMarkdown(
|
||||
const title = form.title || flowIdObj.title || "<无标题>";
|
||||
const rawState = flowIdObj.state || "approving";
|
||||
const stateLabel = String(rawState).toUpperCase() === "APPROVING" ? "审批中" : rawState;
|
||||
const submitTime = formatDate(form.submitDate || flowIdObj.createTime);
|
||||
const submitTime = formatDateValue(form.submitDate || flowIdObj.createTime);
|
||||
const templateName = resolveSpecificationName(form.specificationId);
|
||||
const submitterName = form.submitterId?.name || (typeof form.submitterId === "string" ? form.submitterId : "未知");
|
||||
const requisitionDate = formatDate(form.requisitionDate);
|
||||
const totalMoney = formatAmount(form.requisitionMoney || form.amount);
|
||||
const submitterName = formatPersonValue(form.submitterId, options?.staffMap);
|
||||
const requisitionDate = formatDateValue(form.requisitionDate || form.expenseDate);
|
||||
|
||||
const lines: string[] = [];
|
||||
lines.push(`# 单据:${code}`);
|
||||
@@ -113,20 +493,110 @@ export function translateBillFlowToMarkdown(
|
||||
lines.push(`- **单据模板**: \`${templateName}\``);
|
||||
lines.push(`- **补充申请**: <无>`);
|
||||
lines.push(`- **标题**: \`${title}\``);
|
||||
lines.push(`- **提交人**: ${submitterName}`);
|
||||
if (requisitionDate) {
|
||||
lines.push(`- **申请日期**: ${requisitionDate}`);
|
||||
}
|
||||
lines.push(`- **提交人**: ${submitterName}`);
|
||||
|
||||
// 法人实体
|
||||
const legalEntityVal = form.法人实体 ?? form.legalEntity;
|
||||
if (legalEntityVal) {
|
||||
const formattedEntity = formatReferenceOrObject(legalEntityVal, options?.dimensionItemMap, options?.datalinkCardMap);
|
||||
lines.push(`- **法人实体**: ${formattedEntity}`);
|
||||
} else if (options?.corpName) {
|
||||
lines.push(`- **法人实体**: ${options.corpName}`);
|
||||
}
|
||||
|
||||
// 部门
|
||||
const expenseDept = form.expenseDepartment;
|
||||
if (expenseDept) {
|
||||
lines.push(`- **费用承担部门**: ${formatDepartmentValue(expenseDept, options?.departmentMap)}`);
|
||||
}
|
||||
const submitterDept = form.u_提交人部门 ?? form.submitterDepartment;
|
||||
if (submitterDept) {
|
||||
lines.push(`- **提交人部门**: ${formatDepartmentValue(submitterDept, options?.departmentMap)}`);
|
||||
}
|
||||
|
||||
// 事由说明
|
||||
const desc = form.description || form.reason;
|
||||
if (desc) {
|
||||
lines.push(`- **事由**: \`${desc}\``);
|
||||
}
|
||||
|
||||
// 是否有纸质票据
|
||||
const paperInvoice = form.u_是否有纸质票据;
|
||||
if (paperInvoice !== undefined && paperInvoice !== null && paperInvoice !== "") {
|
||||
lines.push(`- **是否有纸质票据**: ${formatReferenceOrObject(paperInvoice, options?.dimensionItemMap, options?.datalinkCardMap)}`);
|
||||
}
|
||||
|
||||
// 经常交易供应商
|
||||
const vendor = form.u_经常交易供应商 ?? form.payeeId;
|
||||
if (vendor) {
|
||||
lines.push(`- **经常交易供应商**: ${formatReferenceOrObject(vendor, options?.dimensionItemMap, options?.datalinkCardMap)}`);
|
||||
}
|
||||
|
||||
// 收款信息
|
||||
const payeeAccount = form.payeeAccountId ?? form.payeeInfo;
|
||||
if (payeeAccount) {
|
||||
lines.push(`- **收款信息**: ${formatReferenceOrObject(payeeAccount, options?.dimensionItemMap, options?.datalinkCardMap)}`);
|
||||
} else if (vendor && typeof vendor === "string" && options?.datalinkCardMap?.has(`payeeInfo:${vendor}`)) {
|
||||
lines.push(`- **收款信息**: ${options.datalinkCardMap.get(`payeeInfo:${vendor}`)}`);
|
||||
}
|
||||
|
||||
// 发票金额-总、税额、不含税
|
||||
if (form.u_发票金额) {
|
||||
lines.push(`- **发票金额-总**: ${formatAmountValue(form.u_发票金额)}`);
|
||||
}
|
||||
if (form.u_本单税额) {
|
||||
lines.push(`- **本单税额**: ${formatAmountValue(form.u_本单税额)}`);
|
||||
}
|
||||
if (form.u_本单不含税) {
|
||||
lines.push(`- **本单不含税**: ${formatAmountValue(form.u_本单不含税)}`);
|
||||
}
|
||||
|
||||
// 动态扩展字段追加
|
||||
for (const [k, v] of Object.entries(form)) {
|
||||
const formatted = formatDynamicField(k, v, options);
|
||||
if (formatted) {
|
||||
lines.push(`- **${formatted.label}**: ${formatted.text}`);
|
||||
}
|
||||
}
|
||||
|
||||
lines.push(`- **单号**: \`${code}\``);
|
||||
if (form.payMoney) {
|
||||
lines.push(`- **支付金额**: ${formatAmountValue(form.payMoney)}`);
|
||||
}
|
||||
lines.push(`- **提交日期**: ${submitTime}`);
|
||||
lines.push(`- **申请金额**: ${totalMoney}`);
|
||||
|
||||
if (form.requisitionMoney) {
|
||||
lines.push(`- **申请金额**: ${formatAmountValue(form.requisitionMoney)}`);
|
||||
}
|
||||
if (form.expenseMoney) {
|
||||
lines.push(`- **报销金额**: ${formatAmountValue(form.expenseMoney)}`);
|
||||
} else if (!form.requisitionMoney && (form.amount || form.payMoney)) {
|
||||
lines.push(`- **申请金额**: ${formatAmountValue(form.amount || form.payMoney)}`);
|
||||
}
|
||||
|
||||
if (form.companyRealPay !== undefined) {
|
||||
lines.push(`- **公司实付金额**: ${formatAmountValue(form.companyRealPay)}`);
|
||||
}
|
||||
if (form.writtenOffMoney !== undefined) {
|
||||
lines.push(`- **核销金额**: ${formatAmountValue(form.writtenOffMoney)}`);
|
||||
}
|
||||
lines.push("");
|
||||
|
||||
// 行程规划
|
||||
const itineraries = Array.isArray(form.itineraries) ? form.itineraries : [];
|
||||
lines.push(`### 行程规划(共 ${itineraries.length} 条)`);
|
||||
// 关联申请
|
||||
const requisitions = Array.isArray(form.requisitionIds) ? form.requisitionIds : [];
|
||||
lines.push(`### 关联申请(共 ${requisitions.length} 条)`);
|
||||
lines.push("");
|
||||
|
||||
// 行程规划 (仅在有行程时输出)
|
||||
const itineraries = Array.isArray(form.itineraries) ? form.itineraries : [];
|
||||
if (itineraries.length > 0) {
|
||||
lines.push(`### 行程规划(共 ${itineraries.length} 条)`);
|
||||
lines.push("");
|
||||
}
|
||||
|
||||
// 费用明细
|
||||
const details = Array.isArray(form.details) ? form.details : [];
|
||||
lines.push(`### 费用明细(共 ${details.length} 条)`);
|
||||
@@ -142,8 +612,8 @@ export function translateBillFlowToMarkdown(
|
||||
let feeTypeName = "住宿费";
|
||||
let feeTypePath = "差旅报销/住宿费";
|
||||
|
||||
if (feeTypeMap?.has(feeTypeId)) {
|
||||
const match = feeTypeMap.get(feeTypeId)!;
|
||||
if (options?.feeTypeMap?.has(feeTypeId)) {
|
||||
const match = options.feeTypeMap.get(feeTypeId)!;
|
||||
feeTypeName = match.name || feeTypeName;
|
||||
feeTypePath = match.path || feeTypeName;
|
||||
} else if (typeof feeTypeId === "string") {
|
||||
@@ -156,25 +626,61 @@ export function translateBillFlowToMarkdown(
|
||||
} else if (feeTypeId.includes("traffic") || feeTypeId.includes("交通")) {
|
||||
feeTypeName = "市内交通费";
|
||||
feeTypePath = "差旅报销/市内交通费";
|
||||
} else if (feeTypeId.includes("3iPhCno9HdI") || feeTypeId.includes("办公")) {
|
||||
feeTypeName = "办公用品";
|
||||
feeTypePath = "办公费/办公用品";
|
||||
}
|
||||
}
|
||||
|
||||
lines.push(`- **费用类型**: ${feeTypePath}(name=${feeTypeName})`);
|
||||
lines.push(`- **金额**: ${formatAmount(feeForm.amount)}`);
|
||||
if (feeForm.feeDate) {
|
||||
lines.push(`- **日期**: ${formatDateTime(feeForm.feeDate)}`);
|
||||
lines.push(`- **日期**: ${formatDateValue(feeForm.feeDate, true)}`);
|
||||
}
|
||||
const city = parseCity(feeForm.city);
|
||||
lines.push(`- **金额**: ${formatAmountValue(feeForm.amount)}`);
|
||||
|
||||
// 明细发票列表(内嵌相对位置)
|
||||
const invoiceList = feeForm.invoiceForm?.invoices || feeForm.invoices;
|
||||
if (Array.isArray(invoiceList) && invoiceList.length > 0) {
|
||||
lines.push(...formatInlineInvoices(invoiceList, options?.invoiceDetailMap));
|
||||
}
|
||||
|
||||
const city = parseCityValue(feeForm.city);
|
||||
if (city) {
|
||||
lines.push(`- **城市**: ${city}`);
|
||||
}
|
||||
if (feeForm.consumptionReasons) {
|
||||
lines.push(`- **消费事由**: \`${feeForm.consumptionReasons}\``);
|
||||
}
|
||||
if (feeForm.invoice) {
|
||||
lines.push(`- **发票张数**: ${feeForm.invoice}`);
|
||||
}
|
||||
if (feeForm.u_发票金额) {
|
||||
lines.push(`- **发票金额**: ${formatAmountValue(feeForm.u_发票金额)}`);
|
||||
}
|
||||
if (feeForm.taxAmount) {
|
||||
lines.push(`- **税额**: ${formatAmountValue(feeForm.taxAmount)}`);
|
||||
}
|
||||
|
||||
// 明细费用归属分摊
|
||||
if (Array.isArray(feeForm.apportions) && feeForm.apportions.length > 0) {
|
||||
lines.push(`- **费用归属分摊**: ${formatApportionSplits(feeForm.apportions, options?.departmentMap)}`);
|
||||
}
|
||||
|
||||
// 明细自定义业务字段
|
||||
if (feeForm.u_业务类型) {
|
||||
lines.push(`- **业务类型**: ${formatReferenceOrObject(feeForm.u_业务类型, options?.dimensionItemMap)}`);
|
||||
}
|
||||
|
||||
if (feeForm.detailId) {
|
||||
lines.push(`- **费用ID**: \`${feeForm.detailId}\``);
|
||||
}
|
||||
lines.push(`- **明细序号**: ${feeForm.detailNo || num}`);
|
||||
|
||||
// 明细附件列表(内嵌相对位置)
|
||||
if (Array.isArray(feeForm.attachments) && feeForm.attachments.length > 0) {
|
||||
lines.push(...formatInlineAttachments(feeForm.attachments));
|
||||
}
|
||||
|
||||
lines.push("");
|
||||
});
|
||||
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
export const VERSION = "0.7.2";
|
||||
export const VERSION = "0.7.3";
|
||||
Reference in new issue
Block a user