Compare commits

..
29 Commits
Author SHA1 Message Date
yunyingk b72b5d7f71 Merge pull request #53 from yunyingk/feat/translator-full-fidelity-invoice-and-datalink
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
feat(bill): high-fidelity bill translation with invoice validation and datalink cards (v0.7.3)
2026-09-07 15:48:15 +08:00
gitea a8e32cff32 feat(bill): support full invoice validation details, datalink cards, and department paths (v0.7.3) 2026-09-07 15:47:44 +08:00
yunyingk 5e06429d6c Merge pull request #52 from yunyingk/feat/translator-modular-and-inline-attachments
feat(bill): refactor translator to modular functions and preserve inline positions
2026-09-07 15:20:54 +08:00
gitea 3777e81ee7 feat(bill): refactor translator to modular functions and preserve inline positions for attachments and invoices 2026-09-07 15:20:27 +08:00
yunyingk 0ee5031dc8 Merge pull request #51 from yunyingk/feat/corps-add-link-and-multi-cluster
feat: 支持协助链接秒级导入 (corps add-link) 与多集群 (wx2等) 动态换票
2026-09-07 14:45:03 +08:00
gitea 2bf8d22810 feat: 支持协助链接秒级导入 (corps add-link) 与多集群 (wx2等) 动态鉴权换票 2026-09-07 14:44:37 +08:00
yunyingk f2b0f15a6e Merge pull request #50 from yunyingk/chore/embed-approval-skill-reference
chore(skill): embed references/approval.md into embedded skill assets
2026-09-07 14:26:20 +08:00
gitea 065ba42bfe chore(skill): embed references/approval.md into embedded skill assets 2026-09-07 14:26:06 +08:00
yunyingk 6260b824a0 Merge pull request #49 from yunyingk/feat/context-introspection-and-aipro-status
feat: 全局运行上下文一键自省与 hose-aipro status 支持 (免读源码构建环境)
2026-09-07 14:17:59 +08:00
gitea 7efa83ff30 feat(cli): add context introspection command and hose-aipro status for zero-source-reading AX 2026-09-07 14:17:35 +08:00
yunyingk 1b5ae12254 Merge pull request #48 from yunyingk/feat/configurable-approval-gateway
feat(approval): introduce configurable gateway policy script and enforce strict reject/approve guardrails
2026-09-07 14:04:52 +08:00
gitea 27660bed92 feat(approval): introduce configurable gateway policy script and enforce strict reject/approve guardrails 2026-09-07 14:03:22 +08:00
yunyingk 01a3263423 Merge pull request #47 from yunyingk/fix/update-download-timeout
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
feat(aipro): approval lifecycle, gateway guardrails, update timeouts, and bump to v0.7.2
2026-09-07 00:02:06 +08:00
gitea 052fa77df6 chore(release): bump version to v0.7.2 2026-09-07 00:01:41 +08:00
gitea ca00e9a2cc feat(aipro): implement bind, review, decide with gateway guardrail and <150 chars opinion validation 2026-09-06 23:54:36 +08:00
gitea 7e39d95b36 feat(aipro): translate JSON output field names to Chinese in scopes and rules commands 2026-09-06 23:32:25 +08:00
gitea b0149ed32d feat(aipro): introduce init session with 6-char short runId and 6h TTL, support --run audit logging in scopes, translate, rules and logs 2026-09-06 23:23:57 +08:00
gitea a16d429d44 feat(aipro): add standalone document field translator and translate command 2026-09-06 22:58:34 +08:00
gitea 2afde446d2 feat(aipro): require wrapped array for rules input and flatten output by code 2026-09-06 22:46:37 +08:00
gitea 950dd6d8fa feat(aipro): add multi-index rules command outputting matched scopes and rules 2026-09-06 22:44:00 +08:00
gitea 8d203fc230 feat(aipro): format scopes command output as pure json with index and scope 2026-09-06 22:39:45 +08:00
gitea 62025cb6f1 feat(aipro): add scopes index command and decouple points from bills 2026-09-06 22:36:58 +08:00
gitea 2f8bcb90c9 refactor(cli): purge short hose alias and standardize on hose-use across docs, scripts, and prompts 2026-09-06 22:26:04 +08:00
gitea 304a8c0d98 fix(update): relax binary download timeout to 600s and pass auth token for github assets 2026-09-06 22:20:47 +08:00
yunyingk 86b88d8785 Merge pull request #46 from yunyingk/fix/approval-corp-isolation-and-release-packaging
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
fix(approval): isolate runs by corp, handle execution error, bundle hose-aipro alias, and bump to v0.7.1
2026-09-06 21:58:15 +08:00
gitea 9fa4cfe38f fix(approval): isolate runs by corp, handle execution error, bundle hose-aipro alias, and bump to v0.7.1 2026-09-06 21:57:53 +08:00
yunyingk 77bd125ef3 Merge pull request #45 from yunyingk/feat/approval-sqlite-engine
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
feat(approval): introduce sqlite rule engine, deterministic gateway, and hose-aipro cli (v0.7.0)
2026-09-06 19:07:40 +08:00
gitea 644c3d2005 fix(cli): unify hose-aipro as multicall symlink alias to hose-use binary 2026-09-06 19:05:07 +08:00
gitea 4e36a1d9a5 feat(approval): introduce sqlite rule engine, deterministic gateway, and hose-aipro cli (v0.7.0)
- Pure Rule Model & AST Parser:
  - Eliminate redundant title field; model rules purely via scope (scene index) and natural language body.
  - Implement AST parser for inline clauses: [action]{硬性|弹性|建议|特殊}.
  - Validate and enforce preference references with @{级别} syntax, strictly blocking invalid grammar.

- Embedded SQLite Database & Repository:
  - Native bun:sqlite integration with zero external dependencies, stored at ~/.config/hose-use/approval.db.
  - 5 core schemas: rules, preferences, approval_runs, approval_findings, and aipro_logs.
  - Support deduplicated scope indexing (listScopes with 1-based indices) and scope drill-down (getScopeDetail).

- Bill Requisition & Backlog Query Extension:
  - Add formatFlowAsBill adapter in domains/bill/tools.ts.
  - Fall back to flow and backlog inspection when bills are not found in invoice endpoints, unlocking full structured inspection for requisitions (such as S26000001) and loan requests.

- Deterministic Approval Gateway & Lifecycle:
  - Enforce mandatory approval lifecycle: points -> checklist -> review -> decide.
  - Physical gateway blocking: forbid decision if audit checklist is missing or empty, or if pending points remain unverified.
  - Hard tier severance: automatically sever and throw GatewayBlockError on approval attempts violating {硬性} clauses.

- Dedicated hose-aipro Global CLI & Immutable Audit Ledger:
  - Register secondary global binary hose-aipro alongside hose-use in package.json and build-binary.mjs.
  - Automatically record every AI Pro invocation, document context, args snapshot, operator, status, and verdict in aipro_logs.
  - Provide intuitive subcommands: points, checklist, review, decide, logs, rules.
  - Bump project version to v0.7.0 and regenerate OpenAPI bundles.
2026-09-06 19:03:06 +08:00
73 changed files with 7839 additions and 628 deletions

No files matched your search

+21 -6
View File
@@ -42,12 +42,27 @@ jobs:
- name: Package release archives
run: |
sudo apt-get update && sudo apt-get install -y zip
cd dist/bin
tar -czf hose-use-linux-x64.tar.gz hose-use-linux-x64
tar -czf hose-use-linux-arm64.tar.gz hose-use-linux-arm64
tar -czf hose-use-darwin-x64.tar.gz hose-use-darwin-x64
tar -czf hose-use-darwin-arm64.tar.gz hose-use-darwin-arm64
zip -q hose-use-windows-x64.zip hose-use-windows-x64.exe
package_unix() {
local binary="$1"
local archive="$2"
local stage
stage=$(mktemp -d)
cp "dist/bin/${binary}" "${stage}/${binary}"
ln -s "${binary}" "${stage}/hose-aipro"
tar -czf "dist/bin/${archive}" -C "${stage}" "${binary}" hose-aipro
rm -rf "${stage}"
}
package_unix hose-use-linux-x64 hose-use-linux-x64.tar.gz
package_unix hose-use-linux-arm64 hose-use-linux-arm64.tar.gz
package_unix hose-use-darwin-x64 hose-use-darwin-x64.tar.gz
package_unix hose-use-darwin-arm64 hose-use-darwin-arm64.tar.gz
stage=$(mktemp -d)
cp dist/bin/hose-use-windows-x64.exe "${stage}/hose-use-windows-x64.exe"
printf '@echo off\r\n"%%~dp0hose-use-windows-x64.exe" %%*\r\n' > "${stage}/hose-aipro.cmd"
(cd "${stage}" && zip -q "${GITHUB_WORKSPACE}/dist/bin/hose-use-windows-x64.zip" hose-use-windows-x64.exe hose-aipro.cmd)
rm -rf "${stage}"
- name: Publish GitHub Release
env:
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "hose-use",
"version": "0.6.2",
"version": "0.7.3",
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
"author": {
"name": "yingqing"
+1 -1
View File
@@ -6,7 +6,7 @@
合思/易快报(ekuaibao)企业费控与平台自建应用的高性能 CLI 命令行工具与底层 SDK(兼具轻量 MCP 适配能力):
- **CLI 工具 (`hose-use` / `hose`)**:面向运维/实施/开发者的高性能交互与自动化命令行
- **CLI 工具 (`hose-use` / `hose-aipro`)**:面向运维/实施/开发者的高性能交互与自动化命令行
- **底层 SDK (`src/domains/` & `src/core/`)**:纯函数式、零 UI 绑定的业务 API 与换票能力
- **MCP Server (`src/server.ts`)**:精简核心适配器(保留核心切换与扫描能力)
- **Agent Skill (`skills/hose-use`)**:内嵌 AI 智能体技能标准定义(支持 `hose-use skill install` 一键分发)
+2 -2
View File
@@ -1,4 +1,4 @@
# hose-use (v0.6.2)
# hose-use (v0.7.3)
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
@@ -92,7 +92,7 @@ hose-use mcp # 启动 MCP Server (默认暴露
```text
src/
├── cli.ts # CLI 入口 (bin: hose)
├── cli.ts # CLI 入口 (bin: hose-use, hose-aipro)
├── cli/ # CLI 核心引擎 (runner, parser, printer, commands)
├── core/ # 基础设施与底层 SDK
│ ├── auth/ # 认证与换票 (RSA 账密, TokenStore, AccountStore)
+748 -242
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -2,7 +2,7 @@
"openapi": "3.1.0",
"info": {
"title": "hose-use API & MCP Tools Specification",
"version": "0.6.2",
"version": "0.7.3",
"description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."
},
"servers": [
+1 -1
View File
@@ -1,7 +1,7 @@
openapi: 3.1.0
info:
title: hose-use API & MCP Tools Specification
version: 0.6.2
version: 0.7.3
description: >-
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
servers:
+4 -2
View File
@@ -1,13 +1,15 @@
{
"name": "hose-use",
"version": "0.6.2",
"version": "0.7.3",
"module": "src/server.ts",
"type": "module",
"bin": {
"hose-use": "src/cli.ts"
"hose-use": "src/cli.ts",
"hose-aipro": "src/cli.ts"
},
"scripts": {
"cli": "bun run src/cli.ts",
"aipro": "bun run src/aipro-cli.ts",
"probe": "bun run src/cli.ts probe",
"check": "tsc --noEmit",
"typecheck": "tsc --noEmit",
+15 -5
View File
@@ -1,4 +1,4 @@
import { mkdirSync } from "node:fs";
import { mkdirSync, existsSync, unlinkSync, symlinkSync } from "node:fs";
import { spawnSync } from "node:child_process";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
@@ -29,17 +29,27 @@ if (isAll) {
}
buildTarget(targetArg, config.bunTarget, resolve(root, config.outfile));
} else {
const output = resolve(root, "dist/bin/hose-use");
buildTarget("host", null, output);
const outputHose = resolve(root, "dist/bin/hose-use");
buildTarget("host", null, outputHose, "src/cli.ts");
// Unix Multicall Binary: 创建 hose-aipro -> hose-use 软链接别名
const outputAipro = resolve(root, "dist/bin/hose-aipro");
try {
if (existsSync(outputAipro)) unlinkSync(outputAipro);
symlinkSync("hose-use", outputAipro);
console.log(`[build:binary] created multicall symlink: ${outputAipro} -> hose-use`);
} catch {
// 忽略软链接异常
}
}
function buildTarget(name, bunTarget, output) {
function buildTarget(name, bunTarget, output, entry = "src/cli.ts") {
mkdirSync(dirname(output), { recursive: true });
const buildArgs = ["build", "--compile"];
if (bunTarget) {
buildArgs.push(`--target=${bunTarget}`);
}
buildArgs.push("--outfile", output, "src/cli.ts");
buildArgs.push("--outfile", output, entry);
console.log(`[build:binary] compiling target: ${name} -> ${output}`);
run(bun, buildArgs);
+3
View File
@@ -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");
+3 -2
View File
@@ -152,9 +152,9 @@ fi
chmod +x "$TMP_FILE"
mv "$TMP_FILE" "$TARGET_PATH"
# Also create 'hose' symlink if possible
# Create hose-aipro multicall alias pointing at the single binary.
if [ -w "$TARGET_DIR" ]; then
ln -sf "$TARGET_PATH" "${TARGET_DIR}/hose" 2>/dev/null || true
ln -sf "$TARGET_PATH" "${TARGET_DIR}/hose-aipro" 2>/dev/null || true
fi
# Ad-hoc sign on macOS
@@ -177,4 +177,5 @@ echo " 2. List corps: hose-use corps list"
echo " 3. List workflows: hose-use workflow list"
echo " 4. Switch mode: hose-use config mode stateless"
echo " 5. Self-update: hose-use update"
echo " AI PRO alias: hose-aipro"
echo ""
+94 -81
View File
@@ -1,12 +1,12 @@
---
name: hose-use
description: "v0.6.0: 合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号 API 登录、租户切换、单据检索与审批动作、工作流跨域扫描、内置 HTTP 交互文档与常驻守护进程。"
description: "v0.7.3: 合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号 API 登录、租户切换、单据检索与审批动作、工作流跨域扫描、内置 HTTP 交互文档与常驻守护进程。"
metadata:
version: 0.6.0
short-description: 合思/易快报企业级 CLI 工具与底层 SDK (v0.6.0)
version: 0.7.3
short-description: 合思/易快报企业级 CLI 工具与底层 SDK (v0.7.3)
---
# hose-use (v0.6.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 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,100 +30,112 @@ metadata:
| 用户意图 / 场景 | 推荐命令 | 深入参考文档 |
|---|---|---|
| 首次登录 / 账密认证 / Token过期 / 多账号 | `hose auth login`, `hose auth status`, `hose auth refresh` | [references/auth.md](references/auth.md) |
| 代客协助凭证导入 / 探针连通性诊断 | `hose auth import`, `hose probe` | [references/auth.md](references/auth.md) |
| 企业租户切换 / 查看当前企业 | `hose corps list`, `hose corps switch <id>` | [references/auth.md](references/auth.md) |
| 报销单据检索 / 费用明细下钻 / 中文字典 | `hose bill list`, `hose bill get <单号|ID> [--risk]` | [references/bill.md](references/bill.md) |
| 单据审批动作(同意/驳回/转交/加签/评论) | `hose bill approve|reject|transfer|add-node|comment <单号|ID> --yes` | [references/bill.md](references/bill.md) |
| 单据审批历史 / 当前节点 / 后续流程 | `hose bill flow <单号|ID>` | [references/bill.md](references/bill.md) |
| 单据风控预警 / 预算状态 / 发票风险 | `hose bill risk <单号|ID>` | [references/bill.md](references/bill.md) |
| 单据引用 ID 二级解析(人员/部门/费用类型) | `hose bill refs <单号|ID>` | [references/bill.md](references/bill.md) |
| 单据关联关系 / 冲借款与前置申请追溯 | `hose bill relations <单号|ID>` | [references/bill.md](references/bill.md) |
| 单据预算状态 / 超预算与占用信息 | `hose bill budget <单号|ID>` | [references/bill.md](references/bill.md) |
| 单据附件 / 发票原件标准列表 | `hose bill attachments <单号|ID>` | [references/bill.md](references/bill.md) |
| 单据附件下载 | `hose bill download <单号|ID> --output-dir <目录>` | [references/bill.md](references/bill.md) |
| 系统/自定义档案维度与档案项 | `hose dimension list`, `hose dimension items <维度>` | [references/dimension.md](references/dimension.md) |
| 企业角色、角色组与角色成员 | `hose role list`, `hose role groups`, `hose role members <角色>` | [references/role.md](references/role.md) |
| 角色权限只读快照 | `hose permission get` | [references/role.md](references/role.md) |
| 单据 Web 详情直达链接生成 | `hose bill link <单号|ID>` | [references/bill.md](references/bill.md) |
| 单据实体模型与字段元数据查询 | `hose bill schema` | [references/bill.md](references/bill.md) |
| 企业通讯录检索 / 员工档案 / 防爆保护 | `hose contact search`, `hose contact list`, `hose contact get` | [references/contact.md](references/contact.md) |
| 待办中心 / 已审批 / 我发起的 / 审批记录 / 抄送 | `hose task todo`, `hose task submitted`, `hose task records`, `hose task cc` | [references/task.md](references/task.md) |
| 消息中心 / 未读统计 / 标记已读 / 类型过滤 | `hose message list [--all]`, `hose message count`, `hose message read` | [references/message.md](references/message.md) |
| 跨自建应用工作流聚合检索 | `hose workflow list`, `hose platform list` | [references/workflow.md](references/workflow.md) |
| 特定任务节点扫描 (如脚本/Webhook) | `hose workflow find --task=code-js2` | [references/workflow.md](references/workflow.md) |
| 工作流详情与开通切换 | `hose workflow get`, `hose workflow toggle` | [references/workflow.md](references/workflow.md) |
| 工作流节点树、代码依赖与静态诊断 | `hose workflow analyze <pipelineId>` | [references/workflow.md](references/workflow.md) |
| 常驻守护进程管理 / 后台运行 | `hose service start`, `hose service status` | [references/service.md](references/service.md) |
| 待办/消息事件轮询与去重 | `hose service poll --corp=<id>` | [references/service.md](references/service.md) |
| 启动本地 HTTP 服务 / 打开可视化交互文档 | `hose http --port=8888` (访问 `/docs`) | [references/service.md](references/service.md) |
| 全局运行上下文 / 身份诊断 / 免读源码自省 | `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) |
| 单据审批动作(同意/驳回/转交/加签/评论) | `hose-use bill approve|reject|transfer|add-node|comment <单号|ID> --yes` | [references/bill.md](references/bill.md) |
| 单据审批历史 / 当前节点 / 后续流程 | `hose-use bill flow <单号|ID>` | [references/bill.md](references/bill.md) |
| 单据风控预警 / 预算状态 / 发票风险 | `hose-use bill risk <单号|ID>` | [references/bill.md](references/bill.md) |
| 单据引用 ID 二级解析(人员/部门/费用类型) | `hose-use bill refs <单号|ID>` | [references/bill.md](references/bill.md) |
| 单据关联关系 / 冲借款与前置申请追溯 | `hose-use bill relations <单号|ID>` | [references/bill.md](references/bill.md) |
| 单据预算状态 / 超预算与占用信息 | `hose-use bill budget <单号|ID>` | [references/bill.md](references/bill.md) |
| 单据附件 / 发票原件标准列表 | `hose-use bill attachments <单号|ID>` | [references/bill.md](references/bill.md) |
| 单据附件下载 | `hose-use bill download <单号|ID> --output-dir <目录>` | [references/bill.md](references/bill.md) |
| 系统/自定义档案维度与档案项 | `hose-use dimension list`, `hose-use dimension items <维度>` | [references/dimension.md](references/dimension.md) |
| 企业角色、角色组与角色成员 | `hose-use role list`, `hose-use role groups`, `hose-use role members <角色>` | [references/role.md](references/role.md) |
| 角色权限只读快照 | `hose-use permission get` | [references/role.md](references/role.md) |
| 单据 Web 详情直达链接生成 | `hose-use bill link <单号|ID>` | [references/bill.md](references/bill.md) |
| 单据实体模型与字段元数据查询 | `hose-use bill schema` | [references/bill.md](references/bill.md) |
| 企业通讯录检索 / 员工档案 / 防爆保护 | `hose-use contact search`, `hose-use contact list`, `hose-use contact get` | [references/contact.md](references/contact.md) |
| 待办中心 / 已审批 / 我发起的 / 审批记录 / 抄送 | `hose-use task todo`, `hose-use task submitted`, `hose-use task records`, `hose-use task cc` | [references/task.md](references/task.md) |
| 消息中心 / 未读统计 / 标记已读 / 类型过滤 | `hose-use message list [--all]`, `hose-use message count`, `hose-use message read` | [references/message.md](references/message.md) |
| 跨自建应用工作流聚合检索 | `hose-use workflow list`, `hose-use platform list` | [references/workflow.md](references/workflow.md) |
| 特定任务节点扫描 (如脚本/Webhook) | `hose-use workflow find --task=code-js2` | [references/workflow.md](references/workflow.md) |
| 工作流详情与开通切换 | `hose-use workflow get`, `hose-use workflow toggle` | [references/workflow.md](references/workflow.md) |
| 工作流节点树、代码依赖与静态诊断 | `hose-use workflow analyze <pipelineId>` | [references/workflow.md](references/workflow.md) |
| 常驻守护进程管理 / 后台运行 | `hose-use service start`, `hose-use service status` | [references/service.md](references/service.md) |
| 待办/消息事件轮询与去重 | `hose-use service poll --corp=<id>` | [references/service.md](references/service.md) |
| 启动本地 HTTP 服务 / 打开可视化交互文档 | `hose-use http --port=8888` (访问 `/docs`) | [references/service.md](references/service.md) |
| CLI 同进程执行网关 / REST 接口调用 | `POST /api/cli`, `GET /v1/corps` | [references/service.md](references/service.md) |
| 导出标准 OpenAPI 3.1.0 JSON 规范 | `hose openapi`, `hose openapi --raw` | [references/service.md](references/service.md) |
| 一键自动自更新 / 查看版本发布日志 | `hose update`, `hose update --changelog` | `hose update --help` |
| 导出标准 OpenAPI 3.1.0 JSON 规范 | `hose-use openapi`, `hose-use openapi --raw` | [references/service.md](references/service.md) |
| 一键自动自更新 / 查看版本发布日志 | `hose-use update`, `hose-use update --changelog` | `hose-use update --help` |
---
## 常用命令速查
```bash
# 0. 全局上下文一键自省 (免读源码构建环境)
hose-use context # 文本格式仪表盘 (当前账号/企业/工号/Token/AI PRO/路径)
hose-use context --json # 结构化 JSON (供 Agent 零解析直接构建完整上下文)
hose-aipro status # 查看 AI PRO 审批网关状态、当前连接企业与规则场景库
hose-aipro # 首页直接展示动态企业页眉与快速工作流
# 1. 认证与企业
hose auth login --phone=17718556446 --password=... # 纯 API 账密自动登录
hose auth status # 查看 Token 剩余有效期与登录账号
hose corps list # 查看企业租户列表
hose corps switch ID01MCcOgJl1td # 切换工作企业
hose probe # 诊断当前企业接口连通性
hose-use auth login --phone=17718556446 --password=... # 纯 API 账密自动登录
hose-use auth status # 查看 Token 剩余有效期与登录账号
hose-use corps list # 查看企业租户列表 (标注 * 为统一默认企业)
hose-use corps switch ID01MCcOgJl1td # 切换工作企业
hose-use probe # 诊断当前企业接口连通性
# 2. 企业通讯录与人员 (默认严格防爆限流,优先 search)
hose contact search 王硕 # 模糊搜索员工工号、邮箱与电话
hose contact list --limit=20 # 采样查看企业通讯录(带防爆截断保护)
hose contact list --json -o /tmp/staffs.json # 导出全量通讯录至本地磁盘并防爆
hose contact get ID01MCcOgJl1td:3LsanKdS7Uo000 # 精准获取指定员工档案
hose-use contact search 王硕 # 模糊搜索员工工号、邮箱与电话
hose-use contact list --limit=20 # 采样查看企业通讯录(带防爆截断保护)
hose-use contact list --json -o /tmp/staffs.json # 导出全量通讯录至本地磁盘并防爆
hose-use contact get ID01MCcOgJl1td:3LsanKdS7Uo000 # 精准获取指定员工档案
# 3. 单据与费用
hose bill list # 查看最新单据与报销记录
hose bill link CL20260901001 # 生成官方 Web 详情直达免密跳转链接
hose bill list --json -o /tmp/bills.json # 导出全量单据报文至本地磁盘
hose bill get n0GMIM0dkQmKbS # 精准查询单据详情 (中文字段映射)
hose bill get S26000001 --risk # 在详情中附加费控风控与发票风险快照
hose bill approve S26000001 --yes # 同意当前待办
hose bill reject S26000001 --comment "金额不符" --yes # 驳回并写明原因
hose bill transfer S26000001 --approver-id 111 --yes # 转交给工号/员工 ID/唯一姓名
hose bill add-node S26000001 --approver-id 111 --mode pre --yes # 前加签;--mode post 为后加签
hose bill comment S26000001 --comment "请补充发票" --yes # 追加单据评论
hose bill refs S26000001 # 解析提交人、归属人、部门、法人实体与费用类型
hose bill relations S26000001 # 追溯冲借款、事前申请和合同关联
hose bill budget S26000001 # 查看单据预算超限和预算接口状态
hose bill attachments S26000001 # 查看附件和发票原件列表
hose bill download S26000001 --output-dir ./downloads # 下载附件到本地目录
hose dimension list # 查看系统与自定义档案维度
hose dimension items 项目 # 查看项目、成本中心等档案项
hose role list # 查看企业角色定义
hose role groups # 查看角色组及其角色
hose role members 财务主管 # 查看指定角色成员
hose permission get # 查看角色权限开关(只读)
hose bill schema # 查询单据实体元数据字典
hose-use bill list # 查看最新单据与报销记录
hose-use bill link CL20260901001 # 生成官方 Web 详情直达免密跳转链接
hose-use bill list --json -o /tmp/bills.json # 导出全量单据报文至本地磁盘
hose-use bill get n0GMIM0dkQmKbS # 精准查询单据详情 (中文字段映射)
hose-use bill get S26000001 --risk # 在详情中附加费控风控与发票风险快照
hose-use bill approve S26000001 --yes # 同意当前待办
hose-use bill reject S26000001 --comment "金额不符" --yes # 驳回并写明原因
hose-use bill transfer S26000001 --approver-id 111 --yes # 转交给工号/员工 ID/唯一姓名
hose-use bill add-node S26000001 --approver-id 111 --mode pre --yes # 前加签;--mode post 为后加签
hose-use bill comment S26000001 --comment "请补充发票" --yes # 追加单据评论
hose-use bill refs S26000001 # 解析提交人、归属人、部门、法人实体与费用类型
hose-use bill relations S26000001 # 追溯冲借款、事前申请和合同关联
hose-use bill budget S26000001 # 查看单据预算超限和预算接口状态
hose-use bill attachments S26000001 # 查看附件和发票原件列表
hose-use bill download S26000001 --output-dir ./downloads # 下载附件到本地目录
hose-use dimension list # 查看系统与自定义档案维度
hose-use dimension items 项目 # 查看项目、成本中心等档案项
hose-use role list # 查看企业角色定义
hose-use role groups # 查看角色组及其角色
hose-use role members 财务主管 # 查看指定角色成员
hose-use permission get # 查看角色权限开关(只读)
hose-use bill schema # 查询单据实体元数据字典
# 4. 待办与消息
hose task submitted # 查看我发起的单据
hose message list --unread # 查看未读消息
hose message list --all # 合并查看已读和未读消息
hose message count # 查看未读数量
hose message read <messageId> # 标记单条消息已读
hose-use task submitted # 查看我发起的单据
hose-use message list --unread # 查看未读消息
hose-use message list --all # 合并查看已读和未读消息
hose-use message count # 查看未读数量
hose-use message read <messageId> # 标记单条消息已读
# 5. 自建应用与工作流
hose platform list # 查看自建应用列表
hose workflow list # 聚合扫描全部应用下的工作流
hose workflow find --task=code-js2 # 查找部署了代码节点的工作流
hose workflow get wf_01k83y... # 查看指定工作流节点拓扑
hose workflow analyze wf_01k83y... --json # 输出节点树、引用依赖与静态诊断
hose-use platform list # 查看自建应用列表
hose-use workflow list # 聚合扫描全部应用下的工作流
hose-use workflow find --task=code-js2 # 查找部署了代码节点的工作流
hose-use workflow get wf_01k83y... # 查看指定工作流节点拓扑
hose-use workflow analyze wf_01k83y... --json # 输出节点树、引用依赖与静态诊断
# 6. 服务与守护进程
hose http --port=8888 # 启动前台 HTTP 服务与交互式文档
hose service start # 后台启动常驻守护进程服务
hose service status # 查看常驻守护进程运行状态与端点
hose service poll --corp=ID01ofWoOC1wiX --json # 轮询待办/消息并去重落盘
hose service logs # 查看常驻守护进程日志
hose service stop # 停止后台常驻守护进程
hose-use http --port=8888 # 启动前台 HTTP 服务与交互式文档
hose-use service start # 后台启动常驻守护进程服务
hose-use service status # 查看常驻守护进程运行状态与端点
hose-use service poll --corp=ID01ofWoOC1wiX --json # 轮询待办/消息并去重落盘
hose-use service logs # 查看常驻守护进程日志
hose-use service stop # 停止后台常驻守护进程
```
---
+85
View File
@@ -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万需特殊说明]{特殊}`:直接触发人工会签或复核分支。
+29 -1
View File
@@ -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
+17 -17
View File
@@ -41,8 +41,8 @@ hose-use bill flow CL20260903001
在详情中附加风控与合规快照时加 `--risk`。该选项会沿用审批详情页的风控、预算和发票风险接口,并在 JSON 的每个单据项中增加 `risk` 字段:
```bash
hose bill get S26000001 --risk
hose bill get S26000001 --risk --json
hose-use bill get S26000001 --risk
hose-use bill get S26000001 --risk --json
```
### 中文字段智能映射字典
@@ -74,19 +74,19 @@ hose-use bill risk CL20260903001
```bash
# 同意:可附带纯文本审批意见
hose bill approve S26000001 --comment "同意" --yes
hose-use bill approve S26000001 --comment "同意" --yes
# 驳回:原因是必填项;默认退回提交人,可用 --reject-to 指定目标
hose bill reject S26000001 --comment "请补充发票" --yes
hose-use bill reject S26000001 --comment "请补充发票" --yes
# 转交:--approver-id 支持完整员工 ID、工号或唯一姓名
hose bill transfer S26000001 --approver-id 111 --yes
hose-use bill transfer S26000001 --approver-id 111 --yes
# 加签:默认前加签,--mode post 表示后加签
hose bill add-node S26000001 --approver-id 111 --mode pre --comment "请协助复核" --yes
hose-use bill add-node S26000001 --approver-id 111 --mode pre --comment "请协助复核" --yes
# 评论:支持 --participants 传入逗号分隔的人员 ID
hose bill comment S26000001 --comment "补充说明" --participants <staffId> --yes
hose-use bill comment S26000001 --comment "补充说明" --participants <staffId> --yes
```
动作解析流程会先通过审批 backlog 详情定位 `backlogId`、`flowId` 和当前节点 ID;当响应包含 `flow.actions` 时,会校验当前登录员工是否拥有对应的 `freeflow.*` 动作。底层请求对应:`freeflow.agree`、`freeflow.reject`、`freeflow.addnode` 和 `freeflow.comment`。
@@ -96,8 +96,8 @@ hose bill comment S26000001 --comment "补充说明" --participants <staffId> --
读取审批详情并联动组织架构、部门树和费用类型目录,将底层 ID 转为姓名、工号、部门全路径或费用类型名称,同时保留原始 ID:
```bash
hose bill refs S26000001
hose bill refs S26000001 --json
hose-use bill refs S26000001
hose-use bill refs S26000001 --json
```
JSON 输出包含 `submitter`、`owner`、`department`、`legalEntity`、`feeTypes`、`dimensions` 和 `unresolved`。单据里出现法人实体、项目或成本中心 ID 时,会联动 `dimension` 目录补充名称与编码;目录在当前进程内按企业缓存 10 分钟。
@@ -107,8 +107,8 @@ JSON 输出包含 `submitter`、`owner`、`department`、`legalEntity`、`feeTyp
从审批详情中的冲借款、前置申请、合同和费用关联字段抽取关系树:
```bash
hose bill relations S26000001
hose bill relations S26000001 --json
hose-use bill relations S26000001
hose-use bill relations S26000001 --json
```
表格模式按树形缩进显示关联 ID、单号、标题和金额;JSON 模式保留每个节点的原始字段,便于继续下钻。
@@ -118,8 +118,8 @@ hose bill relations S26000001 --json
读取审批页使用的预算状态接口,查看单据是否超预算及接口返回的可用/占用金额字段:
```bash
hose bill budget S26000001
hose bill budget S26000001 --json
hose-use bill budget S26000001
hose-use bill budget S26000001 --json
```
### 单据附件列表 (`bill attachments`)
@@ -127,15 +127,15 @@ hose bill budget S26000001 --json
从审批详情中递归提取普通附件与发票原件的文件名、`fileId`、`key`、URL 和来源字段,并通过附件文件服务补齐可下载地址:
```bash
hose bill attachments S26000001
hose bill attachments S26000001 --json
hose-use bill attachments S26000001
hose-use bill attachments S26000001 --json
```
需要落盘时使用 `bill download`。命令会创建目标目录、清理文件名中的路径字符,并返回本地路径和字节数;指定 `--file-id` 可只下载一个附件:
```bash
hose bill download S26000001 --output-dir ./downloads
hose bill download S26000001 --file-id ID01THIU98FNyT --output-dir ./downloads --json
hose-use bill download S26000001 --output-dir ./downloads
hose-use bill download S26000001 --file-id ID01THIU98FNyT --output-dir ./downloads --json
```
## 5. 单据实体元数据字典 (`bill schema`)
+13 -13
View File
@@ -9,8 +9,8 @@
企业通讯录往往包含上千乃至上万名员工。**无节制全量拉取会瞬间冲垮 Agent 上下文,导致会话熔断或崩溃。**
因此,`hose-use` 遵循以下防爆安全原则:
1. **搜索优先 (Search First)**:优先使用 `hose contact search <关键词>` 进行局部模糊匹配(仅返回 1~5 条命中结果);
2. **列表默认限流截断 (Default Limit 20)**:`hose contact list` 默认截断只输出前 20 条,并打印总人数统计和精准检索指引;
1. **搜索优先 (Search First)**:优先使用 `hose-use contact search <关键词>` 进行局部模糊匹配(仅返回 1~5 条命中结果);
2. **列表默认限流截断 (Default Limit 20)**:`hose-use contact list` 默认截断只输出前 20 条,并打印总人数统计和精准检索指引;
3. **大报文转储落地 (`-o / --output-file`)**:若需全量导出通讯录供复杂分析,使用 `-o` 将全量人员安全落盘到磁盘,仅向 Agent 回传精简的文件路径元数据;
4. **全量放行保护 (`--full`)**:仅在确定企业体量较小或明确需要全量时方可显式加上 `--full`。
@@ -20,22 +20,22 @@
```bash
# 1. 模糊搜索人员 (支持姓名、邮箱、手机号、staffId)
hose contact search 王硕
hose contact search xiezihao@hosecloud.com
hose contact search 18600612659
hose-use contact search 王硕
hose-use contact search xiezihao@hosecloud.com
hose-use contact search 18600612659
# 2. 采样查看企业通讯录 (默认截断前 20 条,防上下文溢出)
hose contact list
hose contact list --limit=50
hose-use contact list
hose-use contact list --limit=50
# 3. 大报文安全落地到磁盘 (返回精简文件元数据,保护 LLM 终端)
hose contact list --json -o /tmp/all_staffs.json
hose-use contact list --json -o /tmp/all_staffs.json
# 4. 精确下钻查看指定人员详细档案
hose contact get ID01MCcOgJl1td:3LsanKdS7Uo000
hose-use contact get ID01MCcOgJl1td:3LsanKdS7Uo000
# 5. 指定特定企业租户检索
hose contact search 李 --corp=ID01MCcOgJl1td
hose-use contact search 李 --corp=ID01MCcOgJl1td
```
---
@@ -60,6 +60,6 @@ hose contact search 李 --corp=ID01MCcOgJl1td
### 1. 查找某人发起的单据
当用户要求“帮我查一下王硕提交的报销单”时:
1. 先通过 `hose contact search 王硕` 获取其 `staffId`(如 `ID01MCcOgJl1td:3LsanKdS7Uo000`);
2. 再通过 `hose bill list --keyword=王硕` 或根据 `staffId` 过滤单据明细;
3. 获得单据后,通过 `hose bill link <单号>` 生成官方 Web 直达链接反馈给用户。
1. 先通过 `hose-use contact search 王硕` 获取其 `staffId`(如 `ID01MCcOgJl1td:3LsanKdS7Uo000`);
2. 再通过 `hose-use bill list --keyword=王硕` 或根据 `staffId` 过滤单据明细;
3. 获得单据后,通过 `hose-use bill link <单号>` 生成官方 Web 直达链接反馈给用户。
+4 -4
View File
@@ -4,12 +4,12 @@
```bash
# 查看系统/自定义档案维度目录
hose dimension list
hose dimension list --keyword=项目
hose-use dimension list
hose-use dimension list --keyword=项目
# 查看某个维度的档案项(支持维度 ID、编码或名称)
hose dimension items 项目
hose dimension items DA001 --json
hose-use dimension items 项目
hose-use dimension items DA001 --json
```
目录来源于 `/api/v1/basedata/dimensions/active`,档案项来源于 `/api/v1/basedata/dimensionItems/$<dimensionId>`。结果在同一进程内按企业缓存 10 分钟,JSON 会保留底层 ID、编码、父项 ID 和表单字段。
+7 -7
View File
@@ -3,13 +3,13 @@
消息中心是 CLI-only 能力,不新增 MCP tool。命令默认查询未读消息。
```bash
hose message list --unread
hose message list --read
hose message list --all
hose message list --type=Approve
hose message count
hose message read <messageId>
hose message read-all
hose-use message list --unread
hose-use message list --read
hose-use message list --all
hose-use message list --type=Approve
hose-use message count
hose-use message read <messageId>
hose-use message read-all
```
`message list --json` 返回消息 ID、标题、内容、消息类型、已读状态和原始字段;`--all` 会并行拉取已读与未读页面并去重后按时间排序;`--type` 在 CLI 层按 `messageType`、`msgType`、`msgTypeName` 或 `msgName` 做兼容过滤。`message read-all` 会分页读取全部未读消息再逐条标记,避免只处理首 100 条。
+7 -7
View File
@@ -3,11 +3,11 @@
角色页对应的只读 CLI:
```bash
hose role list
hose role list --keyword=财务
hose role groups
hose role members 财务主管
hose role members CODE15 --json
hose-use role list
hose-use role list --keyword=财务
hose-use role groups
hose-use role members 财务主管
hose-use role members CODE15 --json
```
接口来自系统配置 → 角色页面:角色定义列表、角色组及指定角色成员。成员查询支持角色 ID、编码或名称。
@@ -15,6 +15,6 @@ hose role members CODE15 --json
权限页的角色权限快照:
```bash
hose permission get
hose permission get --json
hose-use permission get
hose-use permission get --json
```
+9 -9
View File
@@ -3,15 +3,15 @@
## CLI
```bash
hose task todo # 待我审批
hose task approved # 我已审批
hose task records # 审批记录
hose task submitted # 我发起的单据
hose task cc --unread # 未读抄送
hose task cc --read # 已读抄送
hose task todo --staff <员工工号或ID> # 在当前页结果中按人员过滤
hose task todo --json --count 50
hose task records --from 2026-01-01 --to 2026-09-05
hose-use task todo # 待我审批
hose-use task approved # 我已审批
hose-use task records # 审批记录
hose-use task submitted # 我发起的单据
hose-use task cc --unread # 未读抄送
hose-use task cc --read # 已读抄送
hose-use task todo --staff <员工工号或ID> # 在当前页结果中按人员过滤
hose-use task todo --json --count 50
hose-use task records --from 2026-01-01 --to 2026-09-05
```
任务结果包含任务 ID、流程 ID、单号、标题、单据模板、提交人、金额、状态、当前节点和可用动作。分页使用 `--start` 与 `--count`。
+151
View File
@@ -0,0 +1,151 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { runAiProCli } from "./aipro-cli.js";
import { closeApprovalDatabase, getApprovalDatabase } from "./domains/approval/db.js";
import { ApprovalRepository } from "./domains/approval/repository.js";
describe("CLI - hose-aipro 审批流与网关阻拦全链路测试", () => {
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("完整闭环:bind 挂载 ➔ review 证据核验 ➔ decide 网关阻拦与裁决 ➔ logs 审计追溯", async () => {
const db = getApprovalDatabase(":memory:");
const repo = new ApprovalRepository(db);
// 1. 创建审批会话
const run = repo.createApprovalRun({
documentSn: "TEST-SN-999",
corpId: "test-corp",
documentSnapshot: "# 单据测试快照",
});
const runId = run.shortId!;
expect(runId).toHaveLength(6);
// 2. bind 挂载规则并拆解为要点清单
const bindRes = await runAiProCli(["bind", "--run", runId, "--rules", "[1, 2]"]);
expect(bindRes.exitCode).toBe(0);
const bindData = JSON.parse(bindRes.stdout);
expect(bindData.length).toBe(3);
expect(bindData[0]["要点编号"]).toBe(1);
expect(bindData[0]["严格程度"]).toBe("硬性");
expect(bindData[0]["归属规则"]).toBe(1);
expect(bindData[0]["审核要点"]).toBe("必须上传真实发票");
expect(bindData[0]["核验状态"]).toBe("待核验");
expect(bindData[1]["要点编号"]).toBe(2);
expect(bindData[1]["严格程度"]).toBe("建议");
expect(bindData[1]["归属规则"]).toBe(1);
expect(bindData[2]["要点编号"]).toBe(3);
expect(bindData[2]["严格程度"]).toBe("硬性");
expect(bindData[2]["归属规则"]).toBe(2);
// 3. 门禁测试:要点处于 PENDING 时,尝试执行 approve 必须被网关阻拦
const block1 = await runAiProCli(["decide", "approve", "--run", runId, "--opinion", "尝试盲目放行"]);
expect(block1.exitCode).toBe(1);
expect(block1.stderr).toContain("待核验");
// 4. review 事实打标录入(要点 3 硬性违规,缺少特批邮件)
const reviewRes = await runAiProCli([
"review",
"--run",
runId,
"--eval",
"1=PASS:已上传增值税普通发票; 2=PASS:已注明详细出差事由; 3=FAIL:住宿费超标500元且无特批邮件",
]);
expect(reviewRes.exitCode).toBe(0);
const reviewData = JSON.parse(reviewRes.stdout);
expect(reviewData["要点总数"]).toBe(3);
expect(reviewData["已通过"]).toBe(2);
expect(reviewData["未通过"]).toBe(1);
expect(reviewData["待核验"]).toBe(0);
// 5. 门禁测试:硬性违规未通过时,尝试执行 approve 必须被物理一票否决
const block2 = await runAiProCli(["decide", "approve", "--run", runId, "--opinion", "强行同意放水"]);
expect(block2.exitCode).toBe(1);
expect(block2.stderr).toContain("硬性违规条款未通过");
// 6. 门禁测试:审批意见超过 150 字符时,必须被参数校验阻断
const over150Text = "测试超长文字。".repeat(30);
const block3 = await runAiProCli(["decide", "reject", "--run", runId, "--opinion", over150Text]);
expect(block3.exitCode).toBe(1);
expect(block3.stderr).toContain("不可超过 150 字符");
// 7. 正确决策:执行 reject 驳回,提供小于 150 字的专业意见(Dry-run)
const rejectRes = await runAiProCli([
"decide",
"reject",
"--run",
runId,
"--opinion",
"住宿费超标500元且未见前置特批邮件,不符合差旅规约第2条,予以驳回,请补充特批后重提。",
]);
expect(rejectRes.exitCode).toBe(0);
const rejectData = JSON.parse(rejectRes.stdout);
expect(rejectData["会话ID"]).toBe(runId);
expect(rejectData["执行动作"]).toBe("驳回");
expect(rejectData["网关状态"]).toBe("放行");
// 8. 审计监控流水验证:会话账本包含全链路记录
const logsRes = await runAiProCli(["logs", "--run", runId, "--json"]);
expect(logsRes.exitCode).toBe(0);
const logsData = JSON.parse(logsRes.stdout);
const actions = logsData.logs.map((l: any) => l.action);
expect(actions).toContain("bind");
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("严禁无故或恶意驳回");
});
});
+1184
View File
File diff suppressed because it is too large. Load diff
+12 -3
View File
@@ -14,11 +14,20 @@ process.stderr.on("error", (err: any) => {
const entryFile = fileURLToPath(import.meta.url);
const appRoot = dirname(dirname(entryFile));
const result = await runCli(process.argv.slice(2), {
appRoot,
entryFile,
// Unix Multicall Binary Pattern: 检测是否通过 hose-aipro 符号链接/别名唤起
const candidates = [process.argv0, process.argv[1], process.argv[0]].filter(Boolean) as string[];
const isAiPro = candidates.some((c) => {
const base = c.split("/").pop() || "";
return base.includes("hose-aipro") || base === "aipro" || base.includes("aipro-cli");
});
const result = isAiPro
? await (await import("./aipro-cli.js")).runAiProCli(process.argv.slice(2))
: await runCli(process.argv.slice(2), {
appRoot,
entryFile,
});
try {
if (result.stdout) process.stdout.write(result.stdout);
} catch (err: any) {
+330
View File
@@ -0,0 +1,330 @@
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
import { printJson, printTable } from "../printer.js";
import { stringOption, booleanOption, numberOption } from "../parser.js";
import { createEkbClient } from "../../core/auth/ekb.js";
import {
ApprovalService,
ApprovalGatewayBlockedError,
FindingCheckStatus,
} from "../../domains/approval/index.js";
export async function handleApprovalCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const corp = runtime.selectedCorp;
if (!corp) {
throw new Error(
"未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose-use auth login 登录。"
);
}
const client = await createEkbClient(corp);
const corpId = corp.corpId || corp.id;
const service = new ApprovalService();
// 解析命令层级:
// 形式 A: hose-use approval audit points S26000001
// 形式 B: hose-use approval points S26000001
// 形式 C: hose-use approval audit S26000001
let subAction = parsed.action?.toLowerCase();
let args = [...parsed.args];
if (subAction === "audit" && args.length > 0) {
const candidateSub = args[0]?.toLowerCase();
if (["points", "inject", "checklist", "list", "review", "eval", "evaluate", "decide", "approve", "reject"].includes(candidateSub)) {
subAction = candidateSub;
args.shift();
}
}
const targetSn = args[0] || stringOption(parsed.options, ["code", "sn", "target", "id"]);
switch (subAction) {
// ── 1. 规则注入与出明细级审核要点清单 ─────────────────────────────────────
case "points":
case "inject": {
if (!targetSn) {
throw new Error("请提供单号或单据 ID: hose-use approval audit points <单号>");
}
const scopeOption = stringOption(parsed.options, ["scope", "s"]);
const result = await service.injectAuditPoints(client, corpId, targetSn, {
scope: scopeOption ? (isNaN(Number(scopeOption)) ? scopeOption : Number(scopeOption)) : undefined,
});
if (runtime.jsonMode) {
return {
stdout: printJson(
{
sn: result.bill.billCode,
scope: result.scope,
runId: result.run.id,
count: result.findings.length,
findings: result.findings,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
const headers = ["#", "严格程度", "归属规则", "审核要点内容", "核验状态"];
const rows = result.findings.map((f, i) => [
i + 1,
`[${f.strictness}]`,
f.ruleCode ? `#${f.ruleCode}` : "-",
f.clauseText,
f.checkStatus,
]);
const table = printTable(headers, rows);
const title = `====== 单据 ${result.bill.billCode} 明细级审核要点清单 (场景: ${result.scope} | 共 ${result.findings.length} 条要点) ======\n`;
const tip =
`\n[要点注入完成] 审核要点已固化至审批实例,审批链路已激活!\n` +
`下一步: 请对要点进行事实核验判定: hose-use approval audit review ${result.bill.billCode} --eval "1=PASS; 2=FAIL:证据说明; ..."\n` +
`完成核验后,由确定性网关仲裁审批: hose-use approval audit decide ${result.bill.billCode} --apply --yes\n`;
return {
stdout: title + table + tip,
stderr: "",
exitCode: 0,
};
}
// ── 2. 查看当前审核要点清单与核验状态 ─────────────────────────────────────
case "checklist":
case "list":
case "status": {
if (!targetSn) {
throw new Error("请提供单号或单据 ID: hose-use approval audit checklist <单号>");
}
const { run, findings } = service.getAuditChecklist(targetSn, corpId);
if (!run || findings.length === 0) {
const errorMsg =
`[审批链路阻断] 单据 [${targetSn}] 尚未注入任何明细级审核要点(要点列表为空)!\n` +
`审批链路当前物理不通!请先执行: hose-use approval audit points ${targetSn} 注入审核要点清单。\n`;
return { stdout: "", stderr: errorMsg, exitCode: 1 };
}
if (runtime.jsonMode) {
return {
stdout: printJson({ run, findings }, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
const headers = ["#", "严格程度", "规则", "审核要点内容", "核验状态", "事实证据 / 推理说明"];
const rows = findings.map((f, i) => [
i + 1,
`[${f.strictness}]`,
f.ruleCode ? `#${f.ruleCode}` : "-",
f.clauseText,
f.checkStatus === "PASS" ? "✅ PASS" : f.checkStatus === "FAIL" ? "❌ FAIL" : f.checkStatus === "SKIP" ? "➖ SKIP" : "⏳ PENDING",
[f.evidence, f.reasoning].filter(Boolean).join(" | ") || "-",
]);
const table = printTable(headers, rows);
const pendingCount = findings.filter((f) => f.checkStatus === "PENDING").length;
const title = `====== 单据 ${targetSn} 审核要点核验进度 (总计: ${findings.length} | 待核验: ${pendingCount} | 运行决策: ${run.decision}) ======\n`;
return {
stdout: title + table,
stderr: "",
exitCode: 0,
};
}
// ── 3. 逐项核验事实打标 ──────────────────────────────────────────────────
case "review":
case "eval":
case "evaluate": {
if (!targetSn) {
throw new Error("请提供单号: hose-use approval audit review <单号> --eval '...'");
}
const evalStr = stringOption(parsed.options, ["eval", "findings", "data", "e"]);
const pointIndex = numberOption(parsed.options, ["point", "p", "index", "i"], 0);
const statusInput = stringOption(parsed.options, ["status", "state"])?.toUpperCase() as FindingCheckStatus | undefined;
const evidence = stringOption(parsed.options, ["evidence", "proof"]);
const reasoning = stringOption(parsed.options, ["reasoning", "reason", "r"]);
const updates: Array<{
index?: number;
id?: string;
status: FindingCheckStatus;
evidence?: string;
reasoning?: string;
}> = [];
if (typeof pointIndex === "number" && pointIndex > 0 && statusInput) {
updates.push({
index: pointIndex,
status: statusInput,
evidence,
reasoning,
});
} else if (evalStr) {
// 解析便捷语法: "1=FAIL:未上传发票; 2=PASS; 3=SKIP; 4=FAIL:大连住宿超标且无特批"
const segments = evalStr.split(";").map((s) => s.trim()).filter(Boolean);
for (const seg of segments) {
const match = seg.match(/^(\d+)\s*=\s*(PASS|FAIL|SKIP)(?::(.*))?$/i);
if (match) {
const idx = parseInt(match[1], 10);
const status = match[2].toUpperCase() as FindingCheckStatus;
const desc = match[3]?.trim();
updates.push({
index: idx,
status,
evidence: desc,
reasoning: desc,
});
}
}
}
if (updates.length === 0) {
throw new Error(
`请提供核验判定参数,例如:\n` +
` hose-use approval audit review ${targetSn} --eval "1=PASS; 2=FAIL:未上传特批邮件; 3=SKIP"\n` +
` 或: hose-use approval audit review ${targetSn} --point 2 --status FAIL --reason "缺少特批邮件"`
);
}
try {
const updatedFindings = service.evaluateAuditPoints(targetSn, updates, corpId);
const headers = ["#", "严格程度", "审核要点内容", "核验状态", "事实证据与说明"];
const rows = updatedFindings.map((f, i) => [
i + 1,
`[${f.strictness}]`,
f.clauseText,
f.checkStatus === "PASS" ? "✅ PASS" : f.checkStatus === "FAIL" ? "❌ FAIL" : f.checkStatus === "SKIP" ? "➖ SKIP" : "⏳ PENDING",
[f.evidence, f.reasoning].filter(Boolean).join(" | ") || "-",
]);
const table = printTable(headers, rows);
const pendingCount = updatedFindings.filter((f) => f.checkStatus === "PENDING").length;
const msg =
`====== 单据 ${targetSn} 核验判定已更新 (待核验剩余: ${pendingCount} 项) ======\n` +
table +
(pendingCount === 0
? `\n[核验全部闭环] 所有要点已完成事实核验!可运行确定性网关仲裁: hose-use approval audit decide ${targetSn} --apply --yes\n`
: `\n[待续] 尚有 ${pendingCount} 项处于 PENDING,请继续核验。\n`);
return { stdout: msg, stderr: "", exitCode: 0 };
} catch (err: any) {
if (err instanceof ApprovalGatewayBlockedError) {
return { stdout: "", stderr: `${err.message}\n`, exitCode: 1 };
}
throw err;
}
}
// ── 4. 确定性网关仲裁与审批决断 ──────────────────────────────────────────
case "decide":
case "approve":
case "reject": {
if (!targetSn) {
throw new Error("请提供单号: hose-use approval audit decide <单号> [--apply] [--yes]");
}
const apply = booleanOption(parsed.options, ["apply", "execute", "run", "do"]);
if (apply) {
const confirmed = booleanOption(parsed.options, ["yes", "y", "confirm"]);
if (!confirmed) {
if (!process.stdin.isTTY || !process.stdout.isTTY) {
throw new Error("开启 --apply 会真实改变单据流转状态,请显式添加 --yes 确认。");
}
const { prompt } = await import("../helpers.js");
const ans = await prompt("网关将向合思系统真实执行审批/驳回/留痕,确认继续?输入 yes: ");
if (!/^(y|yes|是)$/i.test(ans.trim())) throw new Error("已取消审批操作");
}
}
const requestedAction = subAction === "approve" ? "approve" : subAction === "reject" ? "reject" : (stringOption(parsed.options, ["action"]) as any);
const userComment = stringOption(parsed.options, ["comment", "message", "m"]);
try {
const decisionResult = await service.decideAudit(client, corpId, targetSn, {
requestedAction,
apply,
comment: userComment,
});
if (runtime.jsonMode) {
return {
stdout: printJson(decisionResult, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
const outLines: string[] = [];
outLines.push(`\n====== 合思 AI 确定性网关仲裁裁决书 (单号: ${targetSn}) ======`);
outLines.push(`网关决策 : ${decisionResult.decision}`);
outLines.push(`违规统计 : 硬性 ${decisionResult.hardFailedCount} 项 | 弹性 ${decisionResult.elasticFailedCount} 项 | 建议 ${decisionResult.suggestFailedCount} 项 | 特殊 ${decisionResult.specialFailedCount} 项`);
if (apply) {
outLines.push(`下游动作 : 已安全执行 [${decisionResult.appliedAction}] 动作`);
} else {
outLines.push(`执行模式 : 预审仿真 (Dry Run)。若需执行下游审批流转,请追加 --apply --yes`);
}
outLines.push(`\n--- 审计意见文本快照 ---\n${decisionResult.decisionSummary}\n`);
return {
stdout: outLines.join("\n"),
stderr: "",
exitCode: 0,
};
} catch (err: any) {
if (err instanceof ApprovalGatewayBlockedError) {
return {
stdout: "",
stderr: `\n${err.message}\n`,
exitCode: 1,
};
}
throw err;
}
}
// ── 5. 缺省:智能引导 (未注入则出要点,已注入则显示清单) ─────────────────────
case "audit":
case undefined: {
if (!targetSn) {
return {
stdout:
`====== 合思 AI 确定性审批网关 (hose-use approval) ======\n` +
`用法:\n` +
` 1. 出明细级审核要点 (规则注入) : hose-use approval audit points <单号> [--scope <场景>]\n` +
` 2. 查看当前审核要点清单 : hose-use approval audit checklist <单号>\n` +
` 3. 逐项录入事实核验判定 : hose-use approval audit review <单号> --eval "1=PASS; 2=FAIL:说明"\n` +
` 4. 网关确定性仲裁与执行审批 : hose-use approval audit decide <单号> [--apply] [--yes]\n`,
stderr: "",
exitCode: 0,
};
}
// 检查当前是否已注入要点
const { run } = service.getAuditChecklist(targetSn, corpId);
if (!run) {
// 自动触发第一步:注入并出审核要点
return await handleApprovalCommand(
{ ...parsed, action: "points", args: [targetSn] },
runtime
);
} else {
// 已有要点,展示清单与进度
return await handleApprovalCommand(
{ ...parsed, action: "checklist", args: [targetSn] },
runtime
);
}
}
default:
throw new Error(`未知的审批网关动作: ${subAction}。请运行 hose-use approval audit 查看帮助。`);
}
}
+70 -44
View File
@@ -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> {
@@ -309,7 +335,7 @@ async function handleAccounts(parsed: CliParsedArgs, runtime: CliRuntime): Promi
}
if (accounts.length === 0) {
return { stdout: "暂无保存的账号,请使用 hose auth login 登录\n", stderr: "", exitCode: 0 };
return { stdout: "暂无保存的账号,请使用 hose-use auth login 登录\n", stderr: "", exitCode: 0 };
}
const rows = accounts.map((acc, i) => [
@@ -327,7 +353,7 @@ async function handleAccounts(parsed: CliParsedArgs, runtime: CliRuntime): Promi
async function handleSwitchAccount(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const target = parsed.args[0] || stringOption(parsed.options, ["account", "a"]);
if (!target) {
return { stdout: "", stderr: "用法: hose auth switch-account <accountId>\n", exitCode: 1 };
return { stdout: "", stderr: "用法: hose-use auth switch-account <accountId>\n", exitCode: 1 };
}
const success = setActiveAccount(target);
+14 -14
View File
@@ -27,7 +27,7 @@ export async function handleBillCommand(
const corp = runtime.selectedCorp;
if (!corp) {
throw new Error(
"未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose auth login 登录。"
"未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose-use auth login 登录。"
);
}
@@ -75,7 +75,7 @@ export async function handleBillCommand(
case "agree": {
await requireWriteConfirmation();
const target = actionTarget();
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose bill approve <单号|ID> --yes");
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill approve <单号|ID> --yes");
const result = await approveBill(client, corpId, target, actionOptions());
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
return { stdout: `审批同意成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 };
@@ -85,7 +85,7 @@ export async function handleBillCommand(
case "deny": {
await requireWriteConfirmation();
const target = actionTarget();
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose bill reject <单号|ID> --comment <原因> --yes");
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill reject <单号|ID> --comment <原因> --yes");
const options = actionOptions();
if (!options.comment?.trim()) throw new Error("驳回原因不能为空,请通过 --comment 提供原因");
const result = await rejectBill(client, corpId, target, options);
@@ -97,7 +97,7 @@ export async function handleBillCommand(
case "shift": {
await requireWriteConfirmation();
const target = actionTarget();
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose bill transfer <单号|ID> --approver-id <员工ID> --yes");
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill transfer <单号|ID> --approver-id <员工ID> --yes");
const options = { ...actionOptions(), approverIds: await resolveApproverIds(actionOptions().approverIds) };
const result = await transferBill(client, corpId, target, options);
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
@@ -110,7 +110,7 @@ export async function handleBillCommand(
case "counter-sign": {
await requireWriteConfirmation();
const target = actionTarget();
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose bill add-node <单号|ID> --approver-id <员工ID> --yes");
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill add-node <单号|ID> --approver-id <员工ID> --yes");
const options = { ...actionOptions(), approverIds: await resolveApproverIds(actionOptions().approverIds) };
const result = await addNodeBill(client, corpId, target, options);
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
@@ -121,7 +121,7 @@ export async function handleBillCommand(
case "remark": {
await requireWriteConfirmation();
const target = actionTarget();
if (!target) throw new Error("请提供单号或单据 ID: hose bill comment <单号|ID> --comment <内容> --yes");
if (!target) throw new Error("请提供单号或单据 ID: hose-use bill comment <单号|ID> --comment <内容> --yes");
const result = await commentBill(client, corpId, target, actionOptions());
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
return { stdout: `单据评论成功\n单号: ${result.billCode || target}\n流程 ID: ${result.flowId}\n`, stderr: "", exitCode: 0 };
@@ -326,7 +326,7 @@ export async function handleBillCommand(
case "records":
case "timeline": {
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) throw new Error("请提供要查询流程的单号或单据 ID: hose bill flow <单号|ID>");
if (!target) throw new Error("请提供要查询流程的单号或单据 ID: hose-use bill flow <单号|ID>");
const flow = await getBillFlow(client, corpId, target);
if (!flow) {
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
@@ -368,7 +368,7 @@ export async function handleBillCommand(
case "review":
case "warnings": {
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) throw new Error("请提供要查询风控结果的单号或单据 ID: hose bill risk <单号|ID>");
if (!target) throw new Error("请提供要查询风控结果的单号或单据 ID: hose-use bill risk <单号|ID>");
const report = await getBillRisk(client, corpId, target);
if (!report) {
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
@@ -398,7 +398,7 @@ export async function handleBillCommand(
case "budget":
case "budgets": {
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) throw new Error("请提供要查询预算状态的单号或单据 ID: hose bill budget <单号|ID>");
if (!target) throw new Error("请提供要查询预算状态的单号或单据 ID: hose-use bill budget <单号|ID>");
const report = await getBillRisk(client, corpId, target);
if (!report) {
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
@@ -424,7 +424,7 @@ export async function handleBillCommand(
case "references":
case "resolve": {
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) throw new Error("请提供要解析引用的单号或单据 ID: hose bill refs <单号|ID>");
if (!target) throw new Error("请提供要解析引用的单号或单据 ID: hose-use bill refs <单号|ID>");
const report = await getBillReferences(client, corpId, target);
if (!report) {
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
@@ -453,7 +453,7 @@ export async function handleBillCommand(
case "relation":
case "links": {
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) throw new Error("请提供要查询关联关系的单号或单据 ID: hose bill relations <单号|ID>");
if (!target) throw new Error("请提供要查询关联关系的单号或单据 ID: hose-use bill relations <单号|ID>");
const report = await getBillRelations(client, corpId, target);
if (!report) {
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
@@ -486,7 +486,7 @@ export async function handleBillCommand(
case "attachment":
case "files": {
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) throw new Error("请提供要查询附件的单号或单据 ID: hose bill attachments <单号|ID>");
if (!target) throw new Error("请提供要查询附件的单号或单据 ID: hose-use bill attachments <单号|ID>");
const report = await getBillAttachments(client, corpId, target);
if (!report) {
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
@@ -507,7 +507,7 @@ export async function handleBillCommand(
case "download":
case "file-download": {
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) throw new Error("请提供要下载附件的单号或单据 ID: hose bill download <单号|ID>");
if (!target) throw new Error("请提供要下载附件的单号或单据 ID: hose-use bill download <单号|ID>");
const outputDir = stringOption(parsed.options, ["output-dir", "dir"]) || `${process.cwd()}/downloads`;
const fileId = stringOption(parsed.options, ["file-id", "file"]);
const result = await downloadBillAttachments(client, corpId, target, outputDir, fileId);
@@ -540,7 +540,7 @@ export async function handleBillCommand(
if (!target) {
return {
stdout: "",
stderr: "用法: hose bill link <单号或ID>",
stderr: "用法: hose-use bill link <单号或ID>",
exitCode: 1,
};
}
+3 -3
View File
@@ -67,7 +67,7 @@ async function handleShow(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
});
return {
stdout: `====== 全局运行配置 ======\n${output}\n\n提示:\n 切换模式: hose config mode <stateful|stateless>\n 指定企业: hose corps switch <corpId>\n 更新源设置: hose config set updateSource <auto|github|gitea>\n`,
stdout: `====== 全局运行配置 ======\n${output}\n\n提示:\n 切换模式: hose-use config mode <stateful|stateless>\n 指定企业: hose-use corps switch <corpId>\n 更新源设置: hose-use config set updateSource <auto|github|gitea>\n`,
stderr: "",
exitCode: 0,
};
@@ -79,7 +79,7 @@ async function handleMode(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
if (!targetMode || (targetMode !== "stateful" && targetMode !== "stateless")) {
return {
stdout: "",
stderr: "用法: hose config mode <stateful|stateless>\n",
stderr: "用法: hose-use config mode <stateful|stateless>\n",
exitCode: 1,
};
}
@@ -105,7 +105,7 @@ async function handleSet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<Cl
if (!rawKey || val === undefined) {
return {
stdout: "",
stderr: "用法: hose config set <key> <val> (如 hose config set defaultCorpId uzU7pcWfScck00)\n",
stderr: "用法: hose-use config set <key> <val> (如 hose-use config set defaultCorpId uzU7pcWfScck00)\n",
exitCode: 1,
};
}
+6 -6
View File
@@ -16,7 +16,7 @@ export async function handleContactCommand(
if (!corp) {
return {
stdout: "",
stderr: "未指定或未找到有效企业配置。请运行 'hose corps list' 或指定 '--corp=<id>'",
stderr: "未指定或未找到有效企业配置。请运行 'hose-use corps list' 或指定 '--corp=<id>'",
exitCode: 1,
};
}
@@ -24,13 +24,13 @@ export async function handleContactCommand(
const action = parsed.action || parsed.args[0] || "list";
const limit = numberOption(parsed.options, ["limit", "l"]);
// 1. 搜索: hose contact search <keyword> 或 hose contact find <keyword>
// 1. 搜索: hose-use contact search <keyword> 或 hose-use contact find <keyword>
if (action === "search" || action === "find") {
const keyword = parsed.args[0] || stringOption(parsed.options, ["keyword", "query", "k"]) || "";
if (!keyword.trim()) {
return {
stdout: "",
stderr: "用法: hose contact search <关键词 (姓名/邮箱/工号)>",
stderr: "用法: hose-use contact search <关键词 (姓名/邮箱/工号)>",
exitCode: 1,
};
}
@@ -67,13 +67,13 @@ export async function handleContactCommand(
};
}
// 2. 详情: hose contact get <staffId>
// 2. 详情: hose-use contact get <staffId>
if (action === "get") {
const staffId = parsed.args[0] || stringOption(parsed.options, ["id", "staff-id"]);
if (!staffId) {
return {
stdout: "",
stderr: "用法: hose contact get <staffId>",
stderr: "用法: hose-use contact get <staffId>",
exitCode: 1,
};
}
@@ -110,7 +110,7 @@ export async function handleContactCommand(
};
}
// 3. 列表采样: hose contact list (默认限流截断防爆)
// 3. 列表采样: hose-use contact list (默认限流截断防爆)
if (action === "list") {
const isFull = runtime.outputOptions?.allowFull === true;
const result = await listStaffsProtected(corp, {
+97
View File
@@ -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");
});
});
+152
View File
@@ -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 };
}
+81
View File
@@ -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");
});
});
+78 -5
View File
@@ -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,
};
}
@@ -42,7 +47,7 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
}
if (corps.length === 0) {
return { stdout: "未找到任何企业配置,请先运行 hose auth login\n", stderr: "", exitCode: 0 };
return { stdout: "未找到任何企业配置,请先运行 hose-use auth login\n", stderr: "", exitCode: 0 };
}
const rows = corps.map((c, i) => [
@@ -61,7 +66,7 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
);
return {
stdout: `====== 已配置企业列表 (${corps.length} 家) ======\n${table}\n\n提示: 使用 hose 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,
};
@@ -70,14 +75,14 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
async function handleSwitch(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const corpId = parsed.args[0];
if (!corpId) {
return { stdout: "", stderr: "用法: hose corps switch <企业ID>\n", exitCode: 1 };
return { stdout: "", stderr: "用法: hose-use corps switch <企业ID>\n", exitCode: 1 };
}
const success = runtime.corpContext.switchCorp(corpId);
if (!success) {
return {
stdout: "",
stderr: `企业 ${corpId} 不存在或未配置。可运行 hose corps list 查看可用列表。\n`,
stderr: `企业 ${corpId} 不存在或未配置。可运行 hose-use corps list 查看可用列表。\n`,
exitCode: 1,
};
}
@@ -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,
};
}
}
+2 -2
View File
@@ -6,7 +6,7 @@ import { searchDimensions, resolveDimension } from "../../domains/dimension/tool
export async function handleDimensionCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const corp = runtime.selectedCorp;
if (!corp) throw new Error("未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose auth login 登录。");
if (!corp) throw new Error("未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose-use auth login 登录。");
const client = await createEkbClient(corp);
const corpId = corp.corpId || corp.id;
const action = parsed.action?.toLowerCase() || "list";
@@ -19,7 +19,7 @@ export async function handleDimensionCommand(parsed: CliParsedArgs, runtime: Cli
}
if (["items", "get", "show"].includes(action)) {
const target = parsed.args[0] || stringOption(parsed.options, ["dimension", "id", "code", "name"]);
if (!target) throw new Error("请提供档案维度 ID、编码或名称: hose dimension items <维度>");
if (!target) throw new Error("请提供档案维度 ID、编码或名称: hose-use dimension items <维度>");
const result = await resolveDimension(client, corpId, target);
if (!result) {
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
+2 -2
View File
@@ -24,7 +24,7 @@ function renderItems(items: MessageItem[]): string {
export async function handleMessageCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const corp = runtime.selectedCorp;
if (!corp) throw new Error("未指定或未找到有效企业。请运行 hose corps list 或指定 --corp=<id>");
if (!corp) throw new Error("未指定或未找到有效企业。请运行 hose-use corps list 或指定 --corp=<id>");
const action = parsed.action || parsed.args[0] || "list";
const client = await createEkbClient(corp);
const corpId = corp.corpId || corp.id;
@@ -37,7 +37,7 @@ export async function handleMessageCommand(parsed: CliParsedArgs, runtime: CliRu
if (action === "read" || action === "mark-read") {
const messageId = parsed.args[0] || stringOption(parsed.options, ["id", "message-id"]);
if (!messageId) return { stdout: "", stderr: "用法: hose message read <messageId>\n", exitCode: 1 };
if (!messageId) return { stdout: "", stderr: "用法: hose-use message read <messageId>\n", exitCode: 1 };
await readMessage(client, corpId, messageId);
if (runtime.jsonMode) return { stdout: printJson({ corpId, id: messageId, read: true }, runtime.outputOptions), stderr: "", exitCode: 0 };
return { stdout: `已标记消息为已读: ${messageId}\n`, stderr: "", exitCode: 0 };
+1 -1
View File
@@ -5,7 +5,7 @@ import { getPermissions } from "../../domains/permission/tools.js";
export async function handlePermissionCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const corp = runtime.selectedCorp;
if (!corp) throw new Error("未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose auth login 登录。");
if (!corp) throw new Error("未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose-use auth login 登录。");
const action = parsed.action?.toLowerCase() || "get";
if (!["get", "list", "show"].includes(action)) throw new Error(`未知 permission 子命令: ${action}。支持: get`);
const client = await createEkbClient(corp);
+1 -1
View File
@@ -11,7 +11,7 @@ export async function handlePlatformCommand(
if (!currentCorp) {
return {
stdout: "",
stderr: "未选中企业,请先通过 hose corps switch 或 --corp 指定企业\n",
stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n",
exitCode: 1,
};
}
+48 -33
View File
@@ -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";
@@ -11,7 +12,7 @@ export async function handleProbeCommand(
if (!currentCorp) {
return {
stdout: "",
stderr: "未配置任何企业,请先运行 hose auth login 或使用 --corp 指定\n",
stderr: "未配置任何企业,请先运行 hose-use auth login 或使用 --corp 指定\n",
exitCode: 1,
};
}
@@ -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) {
+2 -2
View File
@@ -6,7 +6,7 @@ import { getRoleGroups, getRoleMembers, searchRoles } from "../../domains/role/t
export async function handleRoleCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const corp = runtime.selectedCorp;
if (!corp) throw new Error("未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose auth login 登录。");
if (!corp) throw new Error("未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose-use auth login 登录。");
const client = await createEkbClient(corp), corpId = corp.corpId || corp.id;
const action = parsed.action?.toLowerCase() || "list";
if (["list", "search"].includes(action)) {
@@ -26,7 +26,7 @@ export async function handleRoleCommand(parsed: CliParsedArgs, runtime: CliRunti
}
if (["members", "member", "staffs", "staff"].includes(action)) {
const target = parsed.args[0] || stringOption(parsed.options, ["role", "id", "code", "name"]);
if (!target) throw new Error("请提供角色 ID、编码或名称: hose role members <角色>");
if (!target) throw new Error("请提供角色 ID、编码或名称: hose-use role members <角色>");
const report = await getRoleMembers(client, corpId, target);
if (!report) {
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
+115
View File
@@ -0,0 +1,115 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { runCli } from "../runner.js";
import { closeApprovalDatabase, getApprovalDatabase } from "../../domains/approval/db.js";
import { ApprovalRepository } from "../../domains/approval/repository.js";
describe("CLI - hose-use rule 规则与场景索引命令", () => {
beforeEach(() => {
process.env.HOSE_APPROVAL_DB = ":memory:";
const db = getApprovalDatabase(":memory:");
const repo = new ApprovalRepository(db);
// 预置几条测试规则 (仅需 适用场景 + 规约正文 两个要素)
repo.createRule({
scope: "差旅报销",
body: "差旅报销时,[必须上传发票]{硬性}。"
});
repo.createRule({
scope: "差旅报销",
body: "差旅报销时,[尽量上传支付凭证]{弹性}。"
});
repo.createRule({
scope: "业务招待",
body: "招待报销时,[必须提供餐饮点餐水单]{硬性}。"
});
});
afterEach(() => {
closeApprovalDatabase();
delete process.env.HOSE_APPROVAL_DB;
});
test("hose-use rule scopes 一键获取去重场景索引列表", async () => {
const res = await runCli(["rule", "scopes", "--json"]);
expect(res.exitCode).toBe(0);
const data = JSON.parse(res.stdout);
expect(data.count).toBe(2);
expect(data.scopes[0].index).toBe(1);
expect(data.scopes[0].scope).toBe("差旅报销");
expect(data.scopes[0].ruleCount).toBe(2);
expect(data.scopes[0].ruleCodes).toEqual([1, 2]);
expect(data.scopes[1].index).toBe(2);
expect(data.scopes[1].scope).toBe("业务招待");
expect(data.scopes[1].ruleCount).toBe(1);
expect(data.scopes[1].ruleCodes).toEqual([3]);
});
test("hose-use rule scope <1> 输入索引号获取该场景下的全部规则明细", async () => {
const res = await runCli(["rule", "scope", "1", "--json"]);
expect(res.exitCode).toBe(0);
const data = JSON.parse(res.stdout);
expect(data.index).toBe(1);
expect(data.scope).toBe("差旅报销");
expect(data.ruleCount).toBe(2);
expect(data.rules.length).toBe(2);
expect(data.rules[0].code).toBe(1);
expect(data.rules[0].parsed.clauses[0].strictness).toBe("硬性");
expect(data.rules[1].code).toBe(2);
expect(data.rules[1].parsed.clauses[0].strictness).toBe("弹性");
});
test("hose-use rule scope <场景名称> 输入名称同样可以获取明细", async () => {
const res = await runCli(["rule", "scope", "业务招待", "--json"]);
expect(res.exitCode).toBe(0);
const data = JSON.parse(res.stdout);
expect(data.index).toBe(2);
expect(data.scope).toBe("业务招待");
expect(data.ruleCount).toBe(1);
expect(data.rules[0].code).toBe(3);
expect(data.rules[0].parsed.clauses[0].action).toBe("必须提供餐饮点餐水单");
});
test("hose-use rule scope <不存在> 返回 1 并提示未找到", async () => {
const res = await runCli(["rule", "scope", "999", "--json"]);
expect(res.exitCode).toBe(1);
const data = JSON.parse(res.stdout);
expect(data.found).toBe(false);
});
test("hose-use rule add 纯双参数 (索引 + 正文) 快速新增并强校验", async () => {
// 成功添加:支持直接传 [适用场景] [正文] 两个参数
const addRes = await runCli([
"rule",
"add",
"办公采购",
"单笔采购大于1万,[必须附采购合同]{硬性};[建议由采购员集中办理]{建议}。",
"--json"
]);
expect(addRes.exitCode).toBe(0);
const addData = JSON.parse(addRes.stdout);
expect(addData.success).toBe(true);
expect(addData.rule.code).toBe(4);
expect(addData.rule.scope).toBe("办公采购");
// 再次调用 scopes 应该出现第 3 个索引
const scopesRes = await runCli(["rule", "scopes", "--json"]);
const scopesData = JSON.parse(scopesRes.stdout);
expect(scopesData.count).toBe(3);
expect(scopesData.scopes[2].scope).toBe("办公采购");
});
test("hose-use rule add 语法错误拦截并阻止入库", async () => {
const failRes = await runCli([
"rule",
"add",
"差旅报销",
"差旅报销时,[必须附发票]{严重}。" // 非法严格程度
]);
expect(failRes.exitCode).not.toBe(0);
expect(failRes.stderr).toContain("非法严格程度");
});
});
+268
View File
@@ -0,0 +1,268 @@
import { ApprovalRepository, parseRuleBody } from "../../domains/approval/index.js";
import { booleanOption, stringOption } from "../parser.js";
import { printJson, printTable } from "../printer.js";
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
export async function handleRuleCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const repo = new ApprovalRepository();
const action = (parsed.action || "scopes").toLowerCase();
// 1. 获取所有去重索引(适用场景)列表及对应索引号
// 用法: hose-use rule scopes [--all]
if (["scopes", "scope-list", "indexes", "index"].includes(action)) {
const showAll = booleanOption(parsed.options, ["all"]);
const status = showAll ? undefined : "active";
const scopes = repo.listScopes(status);
if (runtime.jsonMode) {
return {
stdout: printJson({ count: scopes.length, scopes }, runtime.outputOptions),
stderr: "",
exitCode: 0
};
}
const rows = scopes.map((s) => [
s.index,
s.scope,
s.ruleCount,
s.ruleCodes.map((c) => `#${c}`).join(", ") || "-"
]);
const header = `====== 审批规约索引列表 (共 ${scopes.length} 个适用场景) ======\n`;
const table = rows.length
? printTable(["索引号", "适用场景 (Scope)", "规则数", "包含规则编号"], rows)
: "暂无有效规则索引。可使用 hose-use rule add 添加规则。\n";
return {
stdout: `${header}${table}\n提示:输入 "hose-use rule scope <索引号>" 查看该场景下的全部规约明细。\n`,
stderr: "",
exitCode: 0
};
}
// 2. 根据索引号或场景名称,获取该场景下的所有规约明细
// 用法: hose-use rule scope <1|"差旅报销">
if (action === "scope") {
const target = parsed.args[0] || stringOption(parsed.options, ["target", "name", "id", "index"]);
if (!target) {
throw new Error("请提供索引号或适用场景名称: hose-use rule scope <索引号|场景名称>");
}
const detail = repo.getScopeDetail(target);
if (!detail) {
if (runtime.jsonMode) {
return {
stdout: printJson({ found: false, target }, runtime.outputOptions),
stderr: "",
exitCode: 1
};
}
return {
stdout: "",
stderr: `[NOT FOUND] 未找到索引号或场景为 "${target}" 的有效规则。\n提示:可先运行 "hose-use rule scopes" 查看所有可用索引号。\n`,
exitCode: 1
};
}
if (runtime.jsonMode) {
return {
stdout: printJson(detail, runtime.outputOptions),
stderr: "",
exitCode: 0
};
}
const lines: string[] = [
`====== 适用场景 [${detail.index}] ${detail.scope} (共 ${detail.ruleCount} 条规则) ======\n`
];
detail.rules.forEach((r, idx) => {
lines.push(`${idx + 1}. [规则 #${r.code}] (v${r.version})`);
lines.push(` 正文: ${r.body}`);
lines.push(" 审查要点:");
r.parsed.clauses.forEach((c) => {
lines.push(` - [${c.strictness}] ${c.action}`);
});
lines.push("");
});
return {
stdout: lines.join("\n"),
stderr: "",
exitCode: 0
};
}
// 3. 规则列表查询
// 用法: hose-use rule list [--scope <name>] [--status active]
if (action === "list") {
const scope = stringOption(parsed.options, ["scope", "s"]);
const statusOption = stringOption(parsed.options, ["status"]);
const status = (statusOption as any) || "active";
const rules = repo.listRules({ scope, status });
if (runtime.jsonMode) {
return {
stdout: printJson({ count: rules.length, rules }, runtime.outputOptions),
stderr: "",
exitCode: 0
};
}
const rows = rules.map((r) => [
`#${r.code}`,
r.scope,
`v${r.version}`,
r.status,
r.body.length > 35 ? r.body.slice(0, 35) + "..." : r.body,
r.id
]);
const header = `====== 审批规约清单 (共 ${rules.length} 条) ======\n`;
const table = rows.length
? printTable(["编号", "适用场景 (索引)", "版本", "状态", "规约正文预览", "ID"], rows)
: "暂无规则记录。\n";
return { stdout: `${header}${table}\n`, stderr: "", exitCode: 0 };
}
// 4. 查看单条规则详情
// 用法: hose-use rule get <code|id>
if (action === "get" || action === "show") {
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) {
throw new Error("请提供规则编号或 ID: hose-use rule get <编号|ID>");
}
let rule = /^\d+$/.test(target) ? repo.getRuleByCode(Number(target)) : null;
if (!rule) {
rule = repo.getRuleById(target);
}
if (!rule) {
if (runtime.jsonMode) {
return {
stdout: printJson({ found: false, target }, runtime.outputOptions),
stderr: "",
exitCode: 1
};
}
return {
stdout: "",
stderr: `[NOT FOUND] 未找到编号或 ID 为 "${target}" 的规则。\n`,
exitCode: 1
};
}
const parsedRule = parseRuleBody(rule.body);
const result = {
...rule,
parsed: parsedRule
};
if (runtime.jsonMode) {
return {
stdout: printJson(result, runtime.outputOptions),
stderr: "",
exitCode: 0
};
}
const lines: string[] = [
`====== 规则 #${rule.code} 详情 ======\n`,
`规则 ID: ${rule.id}`,
`适用场景: ${rule.scope}`,
`规则版本: v${rule.version}`,
`当前状态: ${rule.status}`,
`规约正文:\n${rule.body}\n`,
`审查要点拆解 (${parsedRule.clauses.length} 项):`
];
parsedRule.clauses.forEach((c) => {
lines.push(` - [${c.strictness}] ${c.action}`);
});
return { stdout: lines.join("\n") + "\n", stderr: "", exitCode: 0 };
}
// 5. 新增规则 (内置语法分析强校验)
// 用法: hose-use rule add <适用场景/索引> <规约正文>
// 或: hose-use rule add --scope <scope> --body <body>
if (action === "add" || action === "create") {
let scope = stringOption(parsed.options, ["scope", "s"]);
let body = stringOption(parsed.options, ["body", "b"]);
if (!scope && parsed.args.length >= 1) {
scope = parsed.args[0];
if (!body && parsed.args.length >= 2) {
body = parsed.args.slice(1).join(" ");
}
}
if (!scope) throw new Error("缺少适用场景/索引参数:请输入索引名称或使用 --scope 指定");
if (!body) throw new Error("缺少规约正文参数:请输入正文或使用 --body 指定,须包含 [动作句式]{硬性|弹性|建议|特殊}");
const rule = repo.createRule({
scope,
body,
status: "active"
});
if (runtime.jsonMode) {
return {
stdout: printJson({ success: true, rule }, runtime.outputOptions),
stderr: "",
exitCode: 0
};
}
return {
stdout: `✓ 成功创建规则 #${rule.code} (ID: ${rule.id})!\n适用场景 (索引): ${rule.scope}\n规约正文: ${rule.body}\n`,
stderr: "",
exitCode: 0
};
}
// 6. 删除规则
// 用法: hose-use rule delete <id>
if (action === "delete" || action === "remove" || action === "rm") {
const target = parsed.args[0] || stringOption(parsed.options, ["id", "code"]);
if (!target) throw new Error("请提供要删除的规则 ID 或编号: hose-use rule delete <ID|编号>");
let ruleId = target;
if (/^\d+$/.test(target)) {
const found = repo.getRuleByCode(Number(target));
if (!found) throw new Error(`未找到编号为 #${target} 的规则`);
ruleId = found.id;
}
const deleted = repo.deleteRule(ruleId);
if (runtime.jsonMode) {
return {
stdout: printJson({ success: deleted, id: ruleId }, runtime.outputOptions),
stderr: "",
exitCode: deleted ? 0 : 1
};
}
return {
stdout: deleted ? `✓ 成功删除规则 (ID: ${ruleId})\n` : `未找到规则 (ID: ${ruleId})\n`,
stderr: "",
exitCode: deleted ? 0 : 1
};
}
throw new Error(
`未知 rule 子命令: "${action}"。\n支持命令:\n` +
` hose-use rule scopes 获取去重场景索引列表与索引号\n` +
` hose-use rule scope <索引号|场景> 获取指定场景下的全部规则明细\n` +
` hose-use rule list 列出全部规则\n` +
` hose-use rule get <编号|ID> 查看规则详情与要点拆解\n` +
` hose-use rule add 添加新规则 (带语法强校验)\n` +
` hose-use rule delete <编号|ID> 删除规则\n`
);
}
+1 -1
View File
@@ -15,7 +15,7 @@ function dateOption(value: string | undefined): number | undefined {
export async function handleTaskCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const corp = runtime.selectedCorp;
if (!corp) throw new Error("未指定或未找到有效企业。请运行 hose corps list 或指定 --corp=<id>");
if (!corp) throw new Error("未指定或未找到有效企业。请运行 hose-use corps list 或指定 --corp=<id>");
const action = parsed.action || parsed.args[0] || "todo";
const view: TaskView | undefined = action === "todo" || action === "pending"
? "todo"
+11 -1
View File
@@ -796,7 +796,17 @@ export async function downloadFile(
const candidate = uniqueCandidates[i]!;
try {
logProgress(`==> [${i + 1}/${uniqueCandidates.length}] 正在下载更新: ${candidate}`);
const res = await fetch(candidate, { signal: AbortSignal.timeout(6000) });
const reqHeaders: Record<string, string> = {
"User-Agent": `hose-use/${VERSION}`,
};
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
if (token && candidate.includes("github.com")) {
reqHeaders["Authorization"] = `Bearer ${token}`;
}
const res = await fetch(candidate, {
headers: reqHeaders,
signal: AbortSignal.timeout(600_000), // 放宽至 600 秒(10 分钟),保障大体积二进制完整下载
});
if (!res.ok) {
throw new Error(`HTTP ${res.status} ${res.statusText}`);
}
+5 -5
View File
@@ -17,7 +17,7 @@ export async function handleWorkflowCommand(
if (!currentCorp) {
return {
stdout: "",
stderr: "未选中企业,请先通过 hose corps switch 或 --corp 指定企业\n",
stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n",
exitCode: 1,
};
}
@@ -52,7 +52,7 @@ export async function handleWorkflowCommand(
async function handleAnalyze(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
if (!pipelineId) return { stdout: "", stderr: "用法: hose workflow analyze <pipelineId>\n", exitCode: 1 };
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow analyze <pipelineId>\n", exitCode: 1 };
const clients = await createClientsForCorp(runtime.selectedCorp!);
const detail = await api.getWorkflowDetail(clients.easoClient, pipelineId);
const result = analyzeWorkflow(detail);
@@ -110,7 +110,7 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
async function handleGet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
if (!pipelineId) {
return { stdout: "", stderr: "用法: hose workflow get <pipelineId>\n", exitCode: 1 };
return { stdout: "", stderr: "用法: hose-use workflow get <pipelineId>\n", exitCode: 1 };
}
const clients = await createClientsForCorp(runtime.selectedCorp!);
@@ -152,7 +152,7 @@ async function handleFind(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
if (!taskType) {
return {
stdout: "",
stderr: "用法: hose workflow find --task=<节点类型> (如 code-js2, http, condition)\n",
stderr: "用法: hose-use workflow find --task=<节点类型> (如 code-js2, http, condition)\n",
exitCode: 1,
};
}
@@ -207,7 +207,7 @@ async function handleToggle(parsed: CliParsedArgs, runtime: CliRuntime): Promise
if (!pipelineId || stateArg === undefined) {
return {
stdout: "",
stderr: "用法: hose workflow toggle <pipelineId> --state=<1|0> (1启用, 0停用)\n",
stderr: "用法: hose-use workflow toggle <pipelineId> --state=<1|0> (1启用, 0停用)\n",
exitCode: 1,
};
}
+9 -1
View File
@@ -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)
@@ -127,6 +131,8 @@ export function printHelp(): string {
dimension 系统/自定义档案维度 (list, items <维度>)
role 角色定义与成员 (list, groups, members <角色>)
permission 权限模型快照 (get)
rule 本地 AI 审批规约管理 (scopes, scope <索引号|场景>, list, get, add, delete)
approval 确定性审批网关与要点仲裁 (audit points <单号>, checklist <单号>, review <单号>, decide <单号>)
skill Agent Skill 管理 (install, status, dump)
probe 连通性诊断 (probe [corpId])
update 版本自更新与发布记录 (update, update check, update --changelog, --github, --gitea, --repo=<owner/repo>)
@@ -147,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 # 查看多级企业配置目录链
+22 -1
View File
@@ -21,6 +21,9 @@ import { handleMessageCommand } from "./commands/message.js";
import { handleDimensionCommand } from "./commands/dimension.js";
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"]);
@@ -141,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);
@@ -181,6 +195,13 @@ async function dispatchCli(
case "permission":
case "permissions":
return await handlePermissionCommand(parsed, runtime);
case "rule":
case "rules":
return await handleRuleCommand(parsed, runtime);
case "approval":
case "approvals":
case "audit":
return await handleApprovalCommand(parsed, runtime);
case "message":
case "messages":
case "notify":
@@ -220,7 +241,7 @@ async function dispatchCli(
default:
return {
stdout: "",
stderr: `未知命令域: ${parsed.area}。运行 hose --help 查看帮助\n`,
stderr: `未知命令域: ${parsed.area}。运行 hose-use --help 查看帮助\n`,
exitCode: 1,
};
}
+1 -1
View File
@@ -39,7 +39,7 @@ export async function runServiceCommand(
case undefined:
return serviceStatus(config);
default:
throw new Error("用法: hose service <start|stop|restart|status|logs|poll>");
throw new Error("用法: hose-use service <start|stop|restart|status|logs|poll>");
}
}
+28 -6
View File
@@ -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
View File
@@ -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
View File
@@ -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 = {
+1 -1
View File
@@ -47,7 +47,7 @@ export const authTools = [
if (!current) {
return {
authenticated: false,
message: "未配置任何企业,请先运行 hose auth login",
message: "未配置任何企业,请先运行 hose-use auth login",
};
}
+3 -3
View File
@@ -45,7 +45,7 @@ export function resolveCorpConfig(
if (!options.stateful) {
throw new Error(
"当前处于无状态模式 (Stateless Mode)。执行企业级操作必须显式指定 --corp <corpId>。\n" +
"如需设置默认企业,可执行 `hose config mode stateful` 切换为有状态模式。"
"如需设置默认企业,可执行 `hose-use config mode stateful` 切换为有状态模式。"
);
}
@@ -53,7 +53,7 @@ export function resolveCorpConfig(
if (firstCorp) return firstCorp;
const hintDirs = candidateDirs?.length ? ` (已检索路径: ${candidateDirs.join(", ")})` : "";
throw new Error(`未找到任何企业配置。请先运行 'hose auth login' 登录或添加企业配置${hintDirs}。`);
throw new Error(`未找到任何企业配置。请先运行 'hose-use auth login' 登录或添加企业配置${hintDirs}。`);
}
export class CorpContext {
@@ -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
View File
@@ -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(),
+5 -1
View File
@@ -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);
+2
View File
@@ -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,
+359
View File
@@ -0,0 +1,359 @@
import { Database } from "bun:sqlite";
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { closeApprovalDatabase, getApprovalDatabase } from "./db.js";
import { ApprovalRepository } from "./repository.js";
import { ApprovalService } from "./service.js";
import { ApprovalRuleValidationError } from "./types.js";
describe("Approval Domain - SQLite 持久化与规约仓储", () => {
let db: Database;
let repo: ApprovalRepository;
beforeEach(() => {
// 每次测试使用独立的内存数据库,隔离状态
db = getApprovalDatabase(":memory:");
repo = new ApprovalRepository(db);
});
afterEach(() => {
closeApprovalDatabase();
});
test("数据库初始化时自动种子化默认偏好配置", () => {
const defaultPref = repo.getDefaultPreference();
expect(defaultPref).toBeDefined();
expect(defaultPref.id).toBe("default");
expect(defaultPref.name).toBe("标准财务审批偏好");
expect(defaultPref.rulesReject).toContain("@{硬性}");
expect(defaultPref.rulesReview).toContain("@{特殊}");
});
test("成功创建合规规则并自动递增编号", () => {
const rule1 = repo.createRule({
scope: "差旅报销",
body: "差旅报销时,[一定需要上传发票]{硬性},[尽量上传支付凭证]{弹性}。"
});
expect(rule1.id).toBeDefined();
expect(rule1.code).toBe(1);
expect(rule1.scope).toBe("差旅报销");
expect(rule1.version).toBe(1);
expect(rule1.status).toBe("active");
const rule2 = repo.createRule({
scope: "业务招待",
body: "招待报销时,[必须提供菜单水单]{硬性};[建议注明客户姓名与职务]{建议}。"
});
expect(rule2.code).toBe(2);
expect(rule2.scope).toBe("业务招待");
expect(repo.countRules()).toBe(2);
});
test("强校验拦截:不合规的规则正文物理禁止入库", () => {
const initialCount = repo.countRules();
expect(() => {
repo.createRule({
scope: "差旅报销",
body: "差旅报销时,[必须上传发票]{严重}。" // 非法严格程度
});
}).toThrow(ApprovalRuleValidationError);
// 验证数据库没有任何脏数据写入
expect(repo.countRules()).toBe(initialCount);
expect(() => {
repo.createRule({
scope: "差旅报销",
body: "差旅报销时,[必须上传发票],大家遵守。" // 悬空中括号
});
}).toThrow(ApprovalRuleValidationError);
expect(repo.countRules()).toBe(initialCount);
});
test("更新规则正文时自动增加版本号并再次校验", () => {
const created = repo.createRule({
scope: "差旅报销",
body: "差旅报销时,[必须上传发票]{硬性}。"
});
expect(created.version).toBe(1);
// 正常更新
const updated = repo.updateRule(created.id, {
body: "差旅报销时,[必须上传发票]{硬性};[尽量上传水单]{弹性}。"
});
expect(updated.version).toBe(2);
expect(updated.body).toContain("[尽量上传水单]{弹性}");
// 非法更新被拦截,原数据不变
expect(() => {
repo.updateRule(created.id, {
body: "差旅报销时,[必须上传发票]{未知名词}。"
});
}).toThrow(ApprovalRuleValidationError);
const check = repo.getRuleById(created.id);
expect(check?.version).toBe(2); // 版本未递增,未被篡改
});
test("按 Scope 与 Status 进行条件过滤检索", () => {
repo.createRule({
scope: "差旅报销",
body: "[必须提供发票]{硬性}。"
});
repo.createRule({
scope: "差旅报销",
body: "[尽量提供水单]{弹性}。",
status: "draft"
});
repo.createRule({
scope: "业务招待",
body: "[必须提供人均名单]{硬性}。"
});
const travelRules = repo.listRules({ scope: "差旅报销" });
expect(travelRules.length).toBe(2);
const activeTravelRules = repo.listRules({ scope: "差旅报销", status: "active" });
expect(activeTravelRules.length).toBe(1);
const entertainRules = repo.listRules({ scope: "业务招待" });
expect(entertainRules.length).toBe(1);
});
test("一键获取去重索引列表 listScopes 及对应的索引编号", () => {
// 插入多条规则,部分共享相同索引
repo.createRule({ scope: "差旅报销", body: "[必须上传发票]{硬性}。" });
repo.createRule({ scope: "差旅报销", body: "[尽量上传水单]{弹性}。" });
repo.createRule({ scope: "业务招待", body: "[必须提供人均名单]{硬性}。" });
repo.createRule({ scope: "差旅报销", body: "[建议注明事由]{建议}。" });
repo.createRule({ scope: "办公采购", body: "[发票抬头须一致]{硬性}。" });
const scopes = repo.listScopes("active");
expect(scopes.length).toBe(3); // 差旅报销、业务招待、办公采购
// 验证索引 1:差旅报销
expect(scopes[0]!.index).toBe(1);
expect(scopes[0]!.scope).toBe("差旅报销");
expect(scopes[0]!.ruleCount).toBe(3);
expect(scopes[0]!.ruleCodes).toEqual([1, 2, 4]);
// 验证索引 2:业务招待
expect(scopes[1]!.index).toBe(2);
expect(scopes[1]!.scope).toBe("业务招待");
expect(scopes[1]!.ruleCount).toBe(1);
expect(scopes[1]!.ruleCodes).toEqual([3]);
// 验证索引 3:办公采购
expect(scopes[2]!.index).toBe(3);
expect(scopes[2]!.scope).toBe("办公采购");
expect(scopes[2]!.ruleCount).toBe(1);
expect(scopes[2]!.ruleCodes).toEqual([5]);
});
test("通过索引编号或索引名称获取该索引对应的所有规则明细 getScopeDetail", () => {
repo.createRule({ scope: "差旅报销", body: "[必须上传发票]{硬性}。" });
repo.createRule({ scope: "差旅报销", body: "[尽量上传支付凭证]{弹性}。" });
repo.createRule({ scope: "业务招待", body: "[必须提供人均名单]{硬性}。" });
// 1. 通过数字索引号 1 检索
const detailByIndex = repo.getScopeDetail(1);
expect(detailByIndex).not.toBeNull();
expect(detailByIndex!.scope).toBe("差旅报销");
expect(detailByIndex!.rules.length).toBe(2);
expect(detailByIndex!.rules[0]!.parsed.clauses[0]!.strictness).toBe("硬性");
expect(detailByIndex!.rules[1]!.parsed.clauses[0]!.strictness).toBe("弹性");
// 2. 通过索引名称 "业务招待" 检索
const detailByName = repo.getScopeDetail("业务招待");
expect(detailByName).not.toBeNull();
expect(detailByName!.index).toBe(2);
expect(detailByName!.rules.length).toBe(1);
// 3. 不存在的索引号返回 null
expect(repo.getScopeDetail(999)).toBeNull();
expect(repo.getScopeDetail("不存在的场景")).toBeNull();
});
test("风格偏好的更新与非法引用拦截", () => {
const pref = repo.getDefaultPreference();
const updated = repo.updatePreference(pref.id, {
name: "宽松型偏好",
rulesReview: "触发 @{特殊} 条款;未满足 @{弹性} 且金额 > 2000 元"
});
expect(updated.name).toBe("宽松型偏好");
expect(updated.rulesReview).toContain("金额 > 2000 元");
// 非法偏好引用被拦截
expect(() => {
repo.updatePreference(pref.id, {
rulesReview: "触犯 @{严重} 条款则复核"
});
}).toThrow(ApprovalRuleValidationError);
});
test("审批运行、要点清单注入与全流程审计流水登记", () => {
// 1. 创建审批运行记录并注入要点清单
const run = repo.createOrResetApprovalRun({
documentSn: "TEST260001",
flowId: "FLOW_001",
decision: "PENDING",
});
expect(run.id).toBeDefined();
expect(run.documentSn).toBe("TEST260001");
expect(run.decision).toBe("PENDING");
const findings = repo.injectFindings(run.id, [
{ clauseText: "必须上传发票", strictness: "硬性", checkStatus: "PENDING" },
{ clauseText: "建议说明事由", strictness: "建议", checkStatus: "PENDING" },
]);
expect(findings.length).toBe(2);
expect(findings[0]!.strictness).toBe("硬性");
expect(findings[0]!.checkStatus).toBe("PENDING");
// 2. 更新核验状态
const updated = repo.updateFinding(findings[0]!.id, {
checkStatus: "FAIL",
evidence: "未提供发票附件",
});
expect(updated.checkStatus).toBe("FAIL");
expect(updated.evidence).toBe("未提供发票附件");
// 3. 登记 AI PRO 审计监控日志
const log = repo.logAiProAction({
action: "decide",
documentSn: "TEST260001",
operator: "AI-Agent-01",
status: "BLOCKED",
decision: "REJECT",
summary: "硬性违规条款未通过,网关阻断放行",
});
expect(log.id).toBeDefined();
expect(log.status).toBe("BLOCKED");
const logs = repo.listAiProLogs("TEST260001");
expect(logs.length).toBe(1);
expect(logs[0]!.action).toBe("decide");
expect(logs[0]!.status).toBe("BLOCKED");
});
test("审批运行按当前企业隔离相同单号", () => {
const corpARun = repo.createOrResetApprovalRun({
documentSn: "SAME-SN",
corpId: "corp-a",
decision: "PENDING",
});
repo.injectFindings(corpARun.id, [
{ clauseText: "企业 A 要点", strictness: "硬性", checkStatus: "PENDING" },
]);
const corpBRun = repo.createOrResetApprovalRun({
documentSn: "SAME-SN",
corpId: "corp-b",
decision: "PENDING",
});
expect(corpBRun.id).not.toBe(corpARun.id);
expect(repo.getAuditChecklist("SAME-SN", "corp-a").findings[0]?.clauseText).toBe("企业 A 要点");
expect(repo.getAuditChecklist("SAME-SN", "corp-b").findings).toEqual([]);
});
test("下游审批执行失败时将运行标记为 ERROR", async () => {
const run = repo.createOrResetApprovalRun({
documentSn: "EXEC-FAIL",
corpId: "corp-a",
decision: "PENDING",
});
repo.injectFindings(run.id, [
{ clauseText: "已核验", strictness: "硬性", checkStatus: "PASS" },
]);
const service = new ApprovalService(repo);
const client = {
post: async () => {
throw new Error("downstream unavailable");
},
} as any;
await expect(
service.decideAudit(client, "corp-a", "EXEC-FAIL", {
apply: true,
requestedAction: "approve",
}),
).rejects.toThrow("downstream unavailable");
expect(repo.getAuditChecklist("EXEC-FAIL", "corp-a").run?.decision).toBe("ERROR");
});
test("审批会话 6 位 shortId 生成、6 小时 TTL 与会话级日志挂载", () => {
// 1. 同一单号多次审批,生成完全独立的运行实例
const run1 = repo.createApprovalRun({
documentSn: "MULTI-RUN-001",
corpId: "corp-test",
documentSnapshot: "# 单据初审快照",
});
const run2 = repo.createApprovalRun({
documentSn: "MULTI-RUN-001",
corpId: "corp-test",
documentSnapshot: "# 单据复审快照",
});
expect(run1.id).not.toBe(run2.id);
expect(run1.shortId).toHaveLength(6);
expect(run2.shortId).toHaveLength(6);
expect(run1.shortId).not.toBe(run2.shortId);
expect(run1.expiresAt).toBeGreaterThan(Date.now());
// 2. 通过 6 位短 ID 检索会话
const found1 = repo.getRunByHandle(run1.shortId!);
expect(found1?.id).toBe(run1.id);
expect(found1?.documentSnapshot).toBe("# 单据初审快照");
// 3. 过期检测拦截
const expiredRun = repo.createApprovalRun({
documentSn: "EXPIRED-001",
expiresAt: Date.now() - 1000, // 过去的时间
});
expect(() => repo.getRunByHandle(expiredRun.shortId!)).toThrow("已过期");
// 4. 会话级日志挂载与检索
repo.logAiProAction({
action: "init",
runId: run1.shortId,
documentSn: "MULTI-RUN-001",
summary: "初始化审批会话",
});
repo.logAiProAction({
action: "translate",
runId: run1.shortId,
documentSn: "MULTI-RUN-001",
summary: "读取快照",
});
repo.logAiProAction({
action: "init",
runId: run2.shortId,
documentSn: "MULTI-RUN-001",
summary: "第二次初始化审批会话",
});
const run1Logs = repo.listAiProLogs({ runId: run1.shortId! });
expect(run1Logs.length).toBe(2);
expect(run1Logs.map((l) => l.action).sort()).toEqual(["init", "translate"].sort());
const run2Logs = repo.listAiProLogs({ runId: run2.shortId! });
expect(run2Logs.length).toBe(1);
expect(run2Logs[0]!.summary).toBe("第二次初始化审批会话");
});
});
+200
View File
@@ -0,0 +1,200 @@
import { Database } from "bun:sqlite";
import { chmodSync, existsSync, mkdirSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
export const DEFAULT_APPROVAL_DB_PATH = join(
homedir(),
".config",
"hose-use",
"approval.db"
);
export function resolveApprovalDbPath(): string {
const envPath = process.env.HOSE_APPROVAL_DB?.trim();
if (envPath) {
return envPath;
}
return DEFAULT_APPROVAL_DB_PATH;
}
let activeDb: Database | null = null;
let currentDbPath: string | null = null;
/**
* 获取或创建 SQLite 数据库连接单例
*/
export function getApprovalDatabase(customPath?: string): Database {
const targetPath = customPath ?? resolveApprovalDbPath();
if (activeDb && currentDbPath === targetPath) {
return activeDb;
}
// 内存数据库无需创建目录
if (targetPath !== ":memory:") {
const dir = dirname(targetPath);
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true, mode: 0o700 });
}
}
const db = new Database(targetPath);
if (targetPath !== ":memory:") {
// 规则、单据快照、审核证据和审计日志都可能包含敏感信息。
// SQLite 默认文件权限受 umask 影响,不能依赖默认值保护凭证与业务数据。
chmodSync(targetPath, 0o600);
}
currentDbPath = targetPath;
activeDb = db;
initDatabaseSchema(db);
return db;
}
/**
* 关闭并清理当前数据库连接(用于测试重置或进程退出)
*/
export function closeApprovalDatabase(): void {
if (activeDb) {
activeDb.close();
activeDb = null;
currentDbPath = null;
}
}
/**
* 初始化表结构与默认数据
*/
export function initDatabaseSchema(db: Database): void {
// 启用 WAL 模式提高并发性能与数据安全性
db.run("PRAGMA journal_mode = WAL;");
db.run("PRAGMA foreign_keys = ON;");
// 1. 规约主表
db.run(`
CREATE TABLE IF NOT EXISTS rules (
id TEXT PRIMARY KEY,
code INTEGER NOT NULL UNIQUE,
scope TEXT NOT NULL,
body TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'active',
version INTEGER NOT NULL DEFAULT 1,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
`);
db.run("CREATE INDEX IF NOT EXISTS idx_rules_scope ON rules(scope);");
db.run("CREATE INDEX IF NOT EXISTS idx_rules_status ON rules(status);");
// 2. 风格偏好表
db.run(`
CREATE TABLE IF NOT EXISTS preferences (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
is_default INTEGER NOT NULL DEFAULT 0,
rules_reject TEXT NOT NULL,
rules_review TEXT NOT NULL,
rules_pass_note TEXT NOT NULL,
rules_approve TEXT NOT NULL,
updated_at INTEGER NOT NULL
);
`);
// 3. 审批运行执行记录表
db.run(`
CREATE TABLE IF NOT EXISTS approval_runs (
id TEXT PRIMARY KEY,
short_id TEXT,
expires_at INTEGER,
flow_id TEXT,
document_sn TEXT NOT NULL,
corp_id TEXT,
scope TEXT,
decision TEXT NOT NULL,
decision_summary TEXT,
matched_rules_count INTEGER NOT NULL DEFAULT 0,
failed_rules_count INTEGER NOT NULL DEFAULT 0,
document_snapshot TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
`);
try {
db.run("ALTER TABLE approval_runs ADD COLUMN scope TEXT;");
} catch {}
try {
db.run("ALTER TABLE approval_runs ADD COLUMN short_id TEXT;");
} catch {}
try {
db.run("ALTER TABLE approval_runs ADD COLUMN expires_at INTEGER;");
} catch {}
db.run("CREATE INDEX IF NOT EXISTS idx_runs_document_sn ON approval_runs(document_sn);");
db.run("CREATE INDEX IF NOT EXISTS idx_runs_short_id ON approval_runs(short_id);");
db.run("CREATE INDEX IF NOT EXISTS idx_runs_created_at ON approval_runs(created_at);");
// 4. 审批要点事实记录表
db.run(`
CREATE TABLE IF NOT EXISTS approval_findings (
id TEXT PRIMARY KEY,
run_id TEXT NOT NULL REFERENCES approval_runs(id) ON DELETE CASCADE,
rule_id TEXT REFERENCES rules(id) ON DELETE SET NULL,
clause_text TEXT NOT NULL,
strictness TEXT NOT NULL,
check_status TEXT NOT NULL,
evidence TEXT,
reasoning TEXT,
created_at INTEGER NOT NULL
);
`);
db.run("CREATE INDEX IF NOT EXISTS idx_findings_run_id ON approval_findings(run_id);");
// 5. AI PRO 全流程操作与审计监控流水表
db.run(`
CREATE TABLE IF NOT EXISTS aipro_logs (
id TEXT PRIMARY KEY,
run_id TEXT,
action TEXT NOT NULL,
document_sn TEXT,
operator TEXT,
args TEXT,
status TEXT NOT NULL,
decision TEXT,
summary TEXT,
created_at INTEGER NOT NULL
);
`);
try {
db.run("ALTER TABLE aipro_logs ADD COLUMN run_id TEXT;");
} catch {}
db.run("CREATE INDEX IF NOT EXISTS idx_aipro_logs_document_sn ON aipro_logs(document_sn);");
db.run("CREATE INDEX IF NOT EXISTS idx_aipro_logs_run_id ON aipro_logs(run_id);");
db.run("CREATE INDEX IF NOT EXISTS idx_aipro_logs_created_at ON aipro_logs(created_at);");
// 种子数据:初始化默认偏好
seedDefaultPreference(db);
}
function seedDefaultPreference(db: Database): void {
const existing = db.query("SELECT id FROM preferences WHERE id = 'default'").get();
if (!existing) {
const now = Date.now();
db.run(
`
INSERT INTO preferences (
id, name, is_default, rules_reject, rules_review, rules_pass_note, rules_approve, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
`,
[
"default",
"标准财务审批偏好",
1,
"确认触犯任何 @{硬性} 条款(刚性底线,直接阻断)",
"触发任何 @{特殊} 条款;未满足 @{弹性} 条款且单据金额 > 500 元;未满足 @{弹性} 累计达 3 处以上;单据未命中任何已有规则",
"未满足 @{弹性} 条款但单据金额 <= 500 元(企业尺度豁免放行);未满足 @{建议} 条款(倡导性要求,附温馨提示)",
"所有条款全部满足,秒级免审全自动通过",
now
]
);
}
}
+285
View File
@@ -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 单据走免审专属绿色通道");
});
});
+334
View File
@@ -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();
+6
View File
@@ -0,0 +1,6 @@
export * from "./types.js";
export * from "./parser.js";
export * from "./db.js";
export * from "./repository.js";
export * from "./service.js";
export * from "./gateway.js";
+84
View File
@@ -0,0 +1,84 @@
import { describe, expect, test } from "bun:test";
import { parseRuleBody, validatePreferenceText } from "./parser.js";
import { ApprovalRuleValidationError } from "./types.js";
describe("Approval Rule Parser - 规则语法解析与校验", () => {
test("正常解析包含单一硬性条款的规则", () => {
const text = "差旅报销时,[必须上传真实有效的发票]{硬性}。";
const result = parseRuleBody(text);
expect(result.clauses.length).toBe(1);
expect(result.clauses[0]!.action).toBe("必须上传真实有效的发票");
expect(result.clauses[0]!.strictness).toBe("硬性");
expect(result.cleanText).toBe("差旅报销时,必须上传真实有效的发票。");
});
test("正常解析包含复合梯度(硬性、弹性、建议、特殊)的整段自然语言规约", () => {
const text =
"员工进行差旅报销时,[一定需要上传发票]{硬性}。[尽量上传支付凭证]{弹性}以佐证真实性;" +
"如涉及大额费用或合规争议,[须提交法务专项审核]{特殊};针对市内同城交通,[建议补充说明消费事由]{建议}。";
const result = parseRuleBody(text);
expect(result.clauses.length).toBe(4);
expect(result.clauses[0]!.action).toBe("一定需要上传发票");
expect(result.clauses[0]!.strictness).toBe("硬性");
expect(result.clauses[1]!.action).toBe("尽量上传支付凭证");
expect(result.clauses[1]!.strictness).toBe("弹性");
expect(result.clauses[2]!.action).toBe("须提交法务专项审核");
expect(result.clauses[2]!.strictness).toBe("特殊");
expect(result.clauses[3]!.action).toBe("建议补充说明消费事由");
expect(result.clauses[3]!.strictness).toBe("建议");
expect(result.cleanText).toBe(
"员工进行差旅报销时,一定需要上传发票。尽量上传支付凭证以佐证真实性;" +
"如涉及大额费用或合规争议,须提交法务专项审核;针对市内同城交通,建议补充说明消费事由。"
);
});
test("拦截非法的严格程度标签", () => {
const text = "差旅报销时,[必须上传发票]{必须遵守}。";
expect(() => parseRuleBody(text)).toThrow(ApprovalRuleValidationError);
expect(() => parseRuleBody(text)).toThrow('非法严格程度 "必须遵守"');
});
test("拦截悬空的中括号(未指定严格程度)", () => {
const text = "差旅报销时,[必须上传发票],请大家注意。";
expect(() => parseRuleBody(text)).toThrow(ApprovalRuleValidationError);
expect(() => parseRuleBody(text)).toThrow('检测到未指定严格程度的标记 "[必须上传发票]"');
});
test("拦截括号未闭合的语法错误", () => {
expect(() => parseRuleBody("差旅报销时,[必须上传发票{硬性}。")).toThrow("未闭合的左中括号");
expect(() => parseRuleBody("差旅报销时,[必须上传发票]{硬性。")).toThrow("未闭合的左花括号");
expect(() => parseRuleBody("差旅报销时,必须上传发票]{硬性}。")).toThrow("未匹配的多余右中括号");
});
test("拦截空的动作句式", () => {
const text = "差旅报销时,[ ]{硬性}。";
expect(() => parseRuleBody(text)).toThrow(ApprovalRuleValidationError);
expect(() => parseRuleBody(text)).toThrow("动作句式不能为空");
});
test("拦截未包含任何判定标记的纯文字", () => {
const text = "这是一段关于差旅报销的日常说明,没有任何裁判条款。";
expect(() => parseRuleBody(text)).toThrow(ApprovalRuleValidationError);
expect(() => parseRuleBody(text)).toThrow("未包含任何有效的规则标记");
});
});
describe("Approval Preference Parser - 偏好引用语法校验", () => {
test("校验通过合法的 @{级别} 引用", () => {
const text = "满足以下条件:触犯任何 @{硬性} 条款,或触发 @{特殊} 条款,或未满足 @{弹性} 且金额 > 500";
expect(validatePreferenceText(text)).toBe(true);
});
test("拦截非法的 @{级别} 引用", () => {
const text = "若违反 @{严重} 条款则驳回";
expect(() => validatePreferenceText(text)).toThrow(ApprovalRuleValidationError);
expect(() => validatePreferenceText(text)).toThrow('非法的偏好引用 "@{严重}"');
});
});
+149
View File
@@ -0,0 +1,149 @@
import {
ApprovalRuleValidationError,
isValidStrictnessTier,
ParsedRule,
RuleClause,
StrictnessTier,
VALID_STRICTNESS_TIERS
} from "./types.js";
const CLAUSE_REGEX = /\[([^\[\]]+)\]\{([^{}]+)\}/g;
const ORPHAN_BRACKET_REGEX = /\[([^\[\]]+)\](?!\s*\{)/g;
const PREFERENCE_REF_REGEX = /@\{([^{}]+)\}/g;
/**
* 解析并严格校验规则正文
*
* 规则正文格式:
* 采用自然语言,在需要约束的判定点使用 [动作句式]{严格程度} 包裹。
* 允许的严格程度:硬性 | 弹性 | 建议 | 特殊
*
* @throws {ApprovalRuleValidationError} 当语法不合规或严格程度非法时抛出
*/
export function parseRuleBody(body: string): ParsedRule {
if (!body || typeof body !== "string" || body.trim().length === 0) {
throw new ApprovalRuleValidationError("规则正文不能为空");
}
// 1. 括号闭合完整性检查
checkBracketBalance(body);
// 2. 检测悬空的中括号(即写了 [动作] 但漏掉了 {级别})
const orphanMatches = Array.from(body.matchAll(ORPHAN_BRACKET_REGEX));
if (orphanMatches.length > 0) {
const firstOrphan = orphanMatches[0]![0];
throw new ApprovalRuleValidationError(
`检测到未指定严格程度的标记 "${firstOrphan}",请紧跟花括号指定级别,如 "${firstOrphan}{硬性}"`
);
}
// 3. 提取所有 [动作句式]{级别}
const clauses: RuleClause[] = [];
const matches = Array.from(body.matchAll(CLAUSE_REGEX));
for (const match of matches) {
const raw = match[0];
const rawAction = match[1];
const rawTier = match[2];
const startIndex = match.index ?? 0;
const endIndex = startIndex + raw.length;
const action = rawAction ? rawAction.trim() : "";
const tier = rawTier ? rawTier.trim() : "";
if (action.length === 0) {
throw new ApprovalRuleValidationError(`动作句式不能为空: "${raw}"`);
}
if (!isValidStrictnessTier(tier)) {
throw new ApprovalRuleValidationError(
`非法严格程度 "${tier}",仅支持:${VALID_STRICTNESS_TIERS.join("、")}`
);
}
clauses.push({
action,
strictness: tier as StrictnessTier,
raw,
startIndex,
endIndex
});
}
// 4. 一条合法的业务规约必须至少包含一个裁决要点
if (clauses.length === 0) {
throw new ApprovalRuleValidationError(
`规则正文未包含任何有效的规则标记,格式须为 [动作句式]{${VALID_STRICTNESS_TIERS.join("|")}}`
);
}
// 5. 生成剥离语法标记后的纯净自然语言
const cleanText = body.replace(CLAUSE_REGEX, (_match, action) => action.trim());
return {
rawBody: body,
clauses,
cleanText
};
}
/**
* 校验规则正文,合规返回 true,不合规抛出 ApprovalRuleValidationError
*/
export function validateRuleBody(body: string): boolean {
parseRuleBody(body);
return true;
}
/**
* 解析并校验偏好配置文本中的 @{级别} 引用
*/
export function validatePreferenceText(text: string): boolean {
if (!text || typeof text !== "string") return true;
const matches = Array.from(text.matchAll(PREFERENCE_REF_REGEX));
for (const match of matches) {
const tier = match[1]?.trim() ?? "";
if (!isValidStrictnessTier(tier)) {
throw new ApprovalRuleValidationError(
`非法的偏好引用 "@{${tier}}",仅支持:${VALID_STRICTNESS_TIERS.map((t) => `@{${t}}`).join("、")}`
);
}
}
return true;
}
/**
* 括号成对匹配与平衡检查
*/
function checkBracketBalance(text: string): void {
let openSquare = 0;
let openCurly = 0;
for (let i = 0; i < text.length; i++) {
const char = text[i];
if (char === "[") {
openSquare++;
} else if (char === "]") {
openSquare--;
if (openSquare < 0) {
throw new ApprovalRuleValidationError("检测到未匹配的多余右中括号 ']'");
}
} else if (char === "{") {
openCurly++;
} else if (char === "}") {
openCurly--;
if (openCurly < 0) {
throw new ApprovalRuleValidationError("检测到未匹配的多余右花括号 '}'");
}
}
}
if (openSquare > 0) {
throw new ApprovalRuleValidationError("检测到未闭合的左中括号 '['");
}
if (openCurly > 0) {
throw new ApprovalRuleValidationError("检测到未闭合的左花括号 '{'");
}
}
+734
View File
@@ -0,0 +1,734 @@
import { Database } from "bun:sqlite";
import { getApprovalDatabase } from "./db.js";
import { parseRuleBody, validatePreferenceText } from "./parser.js";
import {
AiProLogRecord,
ApprovalDecision,
ApprovalFindingRecord,
ApprovalRunRecord,
FindingCheckStatus,
PreferenceRecord,
RuleRecord,
ScopeDetail,
ScopeSummary,
StrictnessTier
} from "./types.js";
export function generateShortRunId(): string {
const chars = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
let result = "";
for (let i = 0; i < 6; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
return result;
}
export interface CreateRuleInput {
scope: string;
body: string;
status?: "active" | "draft" | "archived";
}
export interface UpdateRuleInput {
scope?: string;
body?: string;
status?: "active" | "draft" | "archived";
}
export interface ListRulesFilter {
scope?: string;
status?: "active" | "draft" | "archived";
}
export class ApprovalRepository {
private db: Database;
constructor(db?: Database) {
this.db = db ?? getApprovalDatabase();
}
// ===================== 规约管理 (Rules) =====================
/**
* 创建规则:必须先通过语法校验器,校验通过方可入库
*/
public createRule(input: CreateRuleInput): RuleRecord {
// 语法强校验拦截:不合规直接抛错,物理阻止入库
parseRuleBody(input.body);
const now = Date.now();
const id = crypto.randomUUID();
// 自动分配自增可读编号 code
const maxCodeRow = this.db
.query("SELECT COALESCE(MAX(code), 0) AS maxCode FROM rules")
.get() as { maxCode: number } | null;
const nextCode = (maxCodeRow?.maxCode ?? 0) + 1;
const status = input.status ?? "active";
this.db.run(
`
INSERT INTO rules (id, code, scope, body, status, version, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, 1, ?, ?)
`,
[id, nextCode, input.scope.trim(), input.body.trim(), status, now, now]
);
return this.getRuleById(id)!;
}
public getRuleById(id: string): RuleRecord | null {
const row = this.db.query("SELECT * FROM rules WHERE id = ?").get(id) as any;
return row ? this.mapRuleRow(row) : null;
}
public getRuleByCode(code: number): RuleRecord | null {
const row = this.db.query("SELECT * FROM rules WHERE code = ?").get(code) as any;
return row ? this.mapRuleRow(row) : null;
}
public listRules(filter?: ListRulesFilter): RuleRecord[] {
const conditions: string[] = [];
const params: any[] = [];
if (filter?.scope) {
conditions.push("scope = ?");
params.push(filter.scope.trim());
}
if (filter?.status) {
conditions.push("status = ?");
params.push(filter.status);
}
let sql = "SELECT * FROM rules";
if (conditions.length > 0) {
sql += " WHERE " + conditions.join(" AND ");
}
sql += " ORDER BY code ASC";
const rows = this.db.query(sql).all(...params) as any[];
return rows.map((r) => this.mapRuleRow(r));
}
public countRules(filter?: ListRulesFilter): number {
const conditions: string[] = [];
const params: any[] = [];
if (filter?.scope) {
conditions.push("scope = ?");
params.push(filter.scope.trim());
}
if (filter?.status) {
conditions.push("status = ?");
params.push(filter.status);
}
let sql = "SELECT COUNT(*) as cnt FROM rules";
if (conditions.length > 0) {
sql += " WHERE " + conditions.join(" AND ");
}
const row = this.db.query(sql).get(...params) as { cnt: number } | null;
return row?.cnt ?? 0;
}
/**
* 获取去重后的所有索引(适用场景)列表及统计信息
* 每个索引按出现次序/最小编号分配 1-based 索引编号 (1, 2, 3...)
*/
public listScopes(status: "active" | "draft" | "archived" = "active"): ScopeSummary[] {
const rows = this.db
.query(`
SELECT scope, COUNT(*) as ruleCount, GROUP_CONCAT(code) as codeList
FROM rules
WHERE status = ?
GROUP BY scope
ORDER BY MIN(code) ASC
`)
.all(status) as any[];
return rows.map((row, idx) => {
const ruleCodes = String(row.codeList || "")
.split(",")
.map((c) => Number(c.trim()))
.filter((c) => !isNaN(c))
.sort((a, b) => a - b);
return {
index: idx + 1,
scope: row.scope,
ruleCount: Number(row.ruleCount),
ruleCodes
};
});
}
/**
* 根据 1-based 索引号或索引全名,获取该索引下的所有有效规约明细
*/
public getScopeDetail(indexOrName: number | string): ScopeDetail | null {
const scopes = this.listScopes("active");
let targetScope: ScopeSummary | undefined;
const trimmed = String(indexOrName).trim();
if (/^\d+$/.test(trimmed)) {
const idx = Number(trimmed);
targetScope = scopes.find((s) => s.index === idx);
} else {
targetScope = scopes.find(
(s) => s.scope.toLowerCase() === trimmed.toLowerCase()
);
}
if (!targetScope) {
return null;
}
const rules = this.listRules({ scope: targetScope.scope, status: "active" });
const detailedRules = rules.map((r) => {
const parsed = parseRuleBody(r.body);
return {
...r,
parsed
};
});
return {
index: targetScope.index,
scope: targetScope.scope,
ruleCount: targetScope.ruleCount,
rules: detailedRules
};
}
public updateRule(id: string, updates: UpdateRuleInput): RuleRecord {
const existing = this.getRuleById(id);
if (!existing) {
throw new Error(`未找到 ID 为 "${id}" 的规则`);
}
if (updates.body !== undefined) {
parseRuleBody(updates.body);
}
const now = Date.now();
const newScope = updates.scope !== undefined ? updates.scope.trim() : existing.scope;
const newBody = updates.body !== undefined ? updates.body.trim() : existing.body;
const newStatus = updates.status !== undefined ? updates.status : existing.status;
const newVersion = existing.version + 1;
this.db.run(
`
UPDATE rules
SET scope = ?, body = ?, status = ?, version = ?, updated_at = ?
WHERE id = ?
`,
[newScope, newBody, newStatus, newVersion, now, id]
);
return this.getRuleById(id)!;
}
public deleteRule(id: string): boolean {
const result = this.db.run("DELETE FROM rules WHERE id = ?", [id]);
return result.changes > 0;
}
// ===================== 风格偏好管理 (Preferences) =====================
public getDefaultPreference(): PreferenceRecord {
const row = this.db
.query("SELECT * FROM preferences WHERE is_default = 1 LIMIT 1")
.get() as any;
if (!row) {
const fallback = this.db
.query("SELECT * FROM preferences ORDER BY updated_at DESC LIMIT 1")
.get() as any;
if (!fallback) {
throw new Error("数据库未初始化默认偏好配置");
}
return this.mapPreferenceRow(fallback);
}
return this.mapPreferenceRow(row);
}
public getPreferenceById(id: string): PreferenceRecord | null {
const row = this.db.query("SELECT * FROM preferences WHERE id = ?").get(id) as any;
return row ? this.mapPreferenceRow(row) : null;
}
public updatePreference(
id: string,
updates: Partial<Omit<PreferenceRecord, "id" | "updatedAt">>
): PreferenceRecord {
const existing = this.getPreferenceById(id);
if (!existing) {
throw new Error(`未找到 ID 为 "${id}" 的偏好配置`);
}
if (updates.rulesReject !== undefined) validatePreferenceText(updates.rulesReject);
if (updates.rulesReview !== undefined) validatePreferenceText(updates.rulesReview);
if (updates.rulesPassNote !== undefined) validatePreferenceText(updates.rulesPassNote);
if (updates.rulesApprove !== undefined) validatePreferenceText(updates.rulesApprove);
const now = Date.now();
const name = updates.name ?? existing.name;
const isDefault = updates.isDefault !== undefined ? (updates.isDefault ? 1 : 0) : existing.isDefault ? 1 : 0;
const rulesReject = updates.rulesReject ?? existing.rulesReject;
const rulesReview = updates.rulesReview ?? existing.rulesReview;
const rulesPassNote = updates.rulesPassNote ?? existing.rulesPassNote;
const rulesApprove = updates.rulesApprove ?? existing.rulesApprove;
this.db.run(
`
UPDATE preferences
SET name = ?, is_default = ?, rules_reject = ?, rules_review = ?, rules_pass_note = ?, rules_approve = ?, updated_at = ?
WHERE id = ?
`,
[name, isDefault, rulesReject, rulesReview, rulesPassNote, rulesApprove, now, id]
);
return this.getPreferenceById(id)!;
}
// ===================== 审批运行与要点清单 (Runs & Findings) =====================
public createApprovalRun(input: CreateApprovalRunInput): ApprovalRunRecord {
const id = crypto.randomUUID();
const shortId = input.shortId ?? generateShortRunId();
const now = Date.now();
const expiresAt = input.expiresAt ?? (now + 6 * 3600 * 1000); // 6 小时有效期
this.db.run(
`
INSERT INTO approval_runs (
id, short_id, expires_at, flow_id, document_sn, corp_id, scope, decision, decision_summary, matched_rules_count, failed_rules_count, document_snapshot, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`,
[
id,
shortId,
expiresAt,
input.flowId ?? null,
input.documentSn.trim(),
input.corpId ?? null,
input.scope ?? null,
input.decision ?? "PENDING",
input.decisionSummary ?? null,
input.matchedRulesCount ?? 0,
input.failedRulesCount ?? 0,
input.documentSnapshot ?? null,
now,
now,
]
);
return this.getRunById(id)!;
}
public createOrResetApprovalRun(input: CreateApprovalRunInput): ApprovalRunRecord {
const existing = this.getLatestRunBySn(input.documentSn, input.corpId ?? undefined);
const now = Date.now();
if (existing) {
// 清理旧要点,重置运行记录
this.db.run("DELETE FROM approval_findings WHERE run_id = ?", [existing.id]);
this.db.run(
`
UPDATE approval_runs
SET flow_id = ?, corp_id = ?, scope = ?, decision = ?, decision_summary = ?, matched_rules_count = ?, failed_rules_count = ?, document_snapshot = ?, updated_at = ?
WHERE id = ?
`,
[
(input.flowId !== undefined ? input.flowId : existing.flowId) ?? null,
(input.corpId !== undefined ? input.corpId : existing.corpId) ?? null,
(input.scope !== undefined ? input.scope : existing.scope) ?? null,
input.decision ?? "PENDING",
(input.decisionSummary !== undefined ? input.decisionSummary : null) ?? null,
input.matchedRulesCount ?? 0,
input.failedRulesCount ?? 0,
(input.documentSnapshot !== undefined ? input.documentSnapshot : existing.documentSnapshot) ?? null,
now,
existing.id,
]
);
return this.getRunById(existing.id)!;
}
return this.createApprovalRun(input);
}
public getRunByHandle(handle: string, corpId?: string): ApprovalRunRecord | null {
const trimmed = handle.trim();
const now = Date.now();
// 1. 如果符合 6 位大写短 ID 特征
if (/^[A-Za-z0-9]{6}$/.test(trimmed)) {
const row = this.db
.query("SELECT * FROM approval_runs WHERE UPPER(short_id) = UPPER(?) AND (expires_at IS NULL OR expires_at > ?)")
.get(trimmed, now) as any;
if (row) return this.mapRunRow(row);
const expiredRow = this.db.query("SELECT * FROM approval_runs WHERE UPPER(short_id) = UPPER(?)").get(trimmed) as any;
if (expiredRow) {
throw new Error(`审批会话 [${trimmed}] 已过期(有效时长 6 小时),请运行 hose-aipro init 重新发起审批会话`);
}
}
// 2. 尝试按长 UUID 查找
const byId = this.getRunById(trimmed);
if (byId) return byId;
// 3. 尝试按单号查找最新未过期的运行记录
return this.getLatestRunBySn(trimmed, corpId);
}
public getLatestRunBySn(documentSn: string, corpId?: string): ApprovalRunRecord | null {
const params: string[] = [documentSn.trim()];
let sql = "SELECT * FROM approval_runs WHERE document_sn = ?";
if (corpId !== undefined) {
sql += " AND corp_id = ?";
params.push(corpId);
}
sql += " ORDER BY created_at DESC LIMIT 1";
const row = this.db.query(sql).get(...params) as any;
return row ? this.mapRunRow(row) : null;
}
public getRunById(id: string): ApprovalRunRecord | null {
const row = this.db.query("SELECT * FROM approval_runs WHERE id = ?").get(id) as any;
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">>
): ApprovalRunRecord {
const existing = this.getRunById(id);
if (!existing) {
throw new Error(`未找到 ID 为 "${id}" 的审批运行记录`);
}
const now = Date.now();
const flowId = updates.flowId !== undefined ? updates.flowId : existing.flowId;
const corpId = updates.corpId !== undefined ? updates.corpId : existing.corpId;
const decision = updates.decision !== undefined ? updates.decision : existing.decision;
const decisionSummary = updates.decisionSummary !== undefined ? updates.decisionSummary : existing.decisionSummary;
const matchedRulesCount = updates.matchedRulesCount !== undefined ? updates.matchedRulesCount : existing.matchedRulesCount;
const failedRulesCount = updates.failedRulesCount !== undefined ? updates.failedRulesCount : existing.failedRulesCount;
const documentSnapshot = updates.documentSnapshot !== undefined ? updates.documentSnapshot : existing.documentSnapshot;
this.db.run(
`
UPDATE approval_runs
SET flow_id = ?, corp_id = ?, decision = ?, decision_summary = ?, matched_rules_count = ?, failed_rules_count = ?, document_snapshot = ?, updated_at = ?
WHERE id = ?
`,
[
flowId ?? null,
corpId ?? null,
decision ?? "PENDING",
decisionSummary ?? null,
matchedRulesCount,
failedRulesCount,
documentSnapshot ?? null,
now,
id,
]
);
return this.getRunById(id)!;
}
public injectFindings(runId: string, findings: CreateFindingInput[]): ApprovalFindingRecord[] {
const run = this.getRunById(runId);
if (!run) {
throw new Error(`审批运行记录不存在: ${runId}`);
}
// 重新挂载时清空旧要点
this.db.run("DELETE FROM approval_findings WHERE run_id = ?", [runId]);
const now = Date.now();
const insertStmt = this.db.prepare(`
INSERT INTO approval_findings (
id, run_id, rule_id, clause_text, strictness, check_status, evidence, reasoning, created_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
`);
for (const f of findings) {
const id = crypto.randomUUID();
insertStmt.run(
id,
runId,
f.ruleId ?? null,
f.clauseText.trim(),
f.strictness,
f.checkStatus ?? "PENDING",
f.evidence ?? null,
f.reasoning ?? null,
now
);
}
this.db.run(
"UPDATE approval_runs SET matched_rules_count = ?, updated_at = ? WHERE id = ?",
[findings.length, now, runId]
);
return this.getFindingsByRunId(runId);
}
public getFindingsByRunId(runId: string): ApprovalFindingRecord[] {
const rows = this.db
.query("SELECT * FROM approval_findings WHERE run_id = ? ORDER BY rowid ASC")
.all(runId) as any[];
return rows.map((r) => this.mapFindingRow(r));
}
public updateFinding(
findingId: string,
updates: {
checkStatus?: FindingCheckStatus;
evidence?: string | null;
reasoning?: string | null;
}
): ApprovalFindingRecord {
const row = this.db.query("SELECT * FROM approval_findings WHERE id = ?").get(findingId) as any;
if (!row) {
throw new Error(`未找到审核要点记录: ${findingId}`);
}
const checkStatus = updates.checkStatus ?? row.check_status;
const evidence = updates.evidence !== undefined ? updates.evidence : row.evidence;
const reasoning = updates.reasoning !== undefined ? updates.reasoning : row.reasoning;
this.db.run(
`
UPDATE approval_findings
SET check_status = ?, evidence = ?, reasoning = ?
WHERE id = ?
`,
[checkStatus, evidence, reasoning, findingId]
);
const updated = this.db.query("SELECT * FROM approval_findings WHERE id = ?").get(findingId) as any;
return this.mapFindingRow(updated);
}
public getAuditChecklist(documentSn: string, corpId?: string): {
run: ApprovalRunRecord | null;
findings: ApprovalFindingRecord[];
} {
const run = this.getLatestRunBySn(documentSn, corpId);
if (!run) {
return { run: null, findings: [] };
}
const findings = this.getFindingsByRunId(run.id);
return { run, findings };
}
// ===================== 内部字段映射 =====================
private mapRuleRow(row: any): RuleRecord {
return {
id: row.id,
code: Number(row.code),
scope: row.scope,
body: row.body,
status: row.status,
version: Number(row.version),
createdAt: Number(row.created_at),
updatedAt: Number(row.updated_at)
};
}
private mapPreferenceRow(row: any): PreferenceRecord {
return {
id: row.id,
name: row.name,
isDefault: Boolean(row.is_default),
rulesReject: row.rules_reject,
rulesReview: row.rules_review,
rulesPassNote: row.rules_pass_note,
rulesApprove: row.rules_approve,
updatedAt: Number(row.updated_at)
};
}
private mapRunRow(row: any): ApprovalRunRecord {
return {
id: row.id,
shortId: row.short_id ?? null,
expiresAt: row.expires_at ? Number(row.expires_at) : null,
flowId: row.flow_id,
documentSn: row.document_sn,
corpId: row.corp_id,
scope: row.scope ?? null,
decision: row.decision as ApprovalDecision,
decisionSummary: row.decision_summary,
matchedRulesCount: Number(row.matched_rules_count || 0),
failedRulesCount: Number(row.failed_rules_count || 0),
documentSnapshot: row.document_snapshot,
createdAt: Number(row.created_at),
updatedAt: Number(row.updated_at),
};
}
private mapFindingRow(row: any): ApprovalFindingRecord {
let ruleCode: number | undefined;
if (row.rule_id) {
const rule = this.db.query("SELECT code FROM rules WHERE id = ?").get(row.rule_id) as any;
if (rule) ruleCode = Number(rule.code);
}
return {
id: row.id,
runId: row.run_id,
ruleId: row.rule_id,
ruleCode,
clauseText: row.clause_text,
strictness: row.strictness as StrictnessTier,
checkStatus: row.check_status as FindingCheckStatus,
evidence: row.evidence,
reasoning: row.reasoning,
createdAt: Number(row.created_at),
};
}
// ===================== AI PRO 审计监控日志 (Audit Logs) =====================
public logAiProAction(input: CreateAiProLogInput): AiProLogRecord {
const id = crypto.randomUUID();
const now = Date.now();
const status = input.status ?? "SUCCESS";
this.db.run(
`
INSERT INTO aipro_logs (id, run_id, action, document_sn, operator, args, status, decision, summary, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`,
[
id,
input.runId ?? null,
input.action,
input.documentSn ?? null,
input.operator ?? null,
input.args ?? null,
status,
input.decision ?? null,
input.summary ?? null,
now,
]
);
return {
id,
runId: input.runId,
action: input.action,
documentSn: input.documentSn,
operator: input.operator,
args: input.args,
status,
decision: input.decision,
summary: input.summary,
createdAt: now,
};
}
public listAiProLogs(filter?: string | { documentSn?: string; runId?: string }, limit = 50): AiProLogRecord[] {
let sql = "SELECT * FROM aipro_logs";
const conditions: string[] = [];
const params: any[] = [];
const f = typeof filter === "string" ? { documentSn: filter } : filter;
if (f?.runId) {
conditions.push("run_id = ?");
params.push(f.runId.trim());
}
if (f?.documentSn) {
conditions.push("document_sn = ?");
params.push(f.documentSn.trim());
}
if (conditions.length > 0) {
sql += " WHERE " + conditions.join(" AND ");
}
sql += " ORDER BY created_at DESC LIMIT ?";
params.push(limit);
const rows = this.db.query(sql).all(...params) as any[];
return rows.map((r) => ({
id: r.id,
runId: r.run_id ?? null,
action: r.action,
documentSn: r.document_sn,
operator: r.operator,
args: r.args,
status: r.status as "SUCCESS" | "BLOCKED" | "ERROR",
decision: r.decision as ApprovalDecision | null,
summary: r.summary,
createdAt: Number(r.created_at),
}));
}
}
export interface CreateApprovalRunInput {
documentSn: string;
shortId?: string | null;
expiresAt?: number | null;
flowId?: string | null;
corpId?: string | null;
scope?: string | null;
decision?: ApprovalDecision;
decisionSummary?: string | null;
matchedRulesCount?: number;
failedRulesCount?: number;
documentSnapshot?: string | null;
}
export interface CreateFindingInput {
ruleId?: string | null;
clauseText: string;
strictness: StrictnessTier;
checkStatus?: FindingCheckStatus;
evidence?: string | null;
reasoning?: string | null;
}
export interface CreateAiProLogInput {
action: string;
runId?: string | null;
documentSn?: string | null;
operator?: string | null;
args?: string | null;
status?: "SUCCESS" | "BLOCKED" | "ERROR";
decision?: ApprovalDecision | null;
summary?: string | null;
}
+302
View File
@@ -0,0 +1,302 @@
import { KyInstance } from "ky";
import { ApprovalRepository } from "./repository.js";
import { parseRuleBody } from "./parser.js";
import {
ApprovalDecision,
ApprovalFindingRecord,
ApprovalGatewayBlockedError,
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";
export interface InjectPointsResult {
run: ApprovalRunRecord;
findings: ApprovalFindingRecord[];
bill: FormattedBill;
scope: string;
}
export interface DecideAuditOptions {
requestedAction?: "approve" | "reject" | "comment";
apply?: boolean;
comment?: string;
gatewayConfig?: Partial<GatewayPolicyConfig>;
}
export interface DecideAuditResult {
run: ApprovalRunRecord;
decision: ApprovalDecision;
decisionSummary: string;
hardFailedCount: number;
elasticFailedCount: number;
suggestFailedCount: number;
specialFailedCount: number;
appliedAction?: "approve" | "reject" | "comment";
actionResult?: unknown;
}
export class ApprovalService {
private repo: ApprovalRepository;
private gatewayPolicy: ApprovalGatewayPolicy;
constructor(repo?: ApprovalRepository, gatewayPolicy?: ApprovalGatewayPolicy) {
this.repo = repo ?? new ApprovalRepository();
this.gatewayPolicy = gatewayPolicy ?? defaultGatewayPolicy;
}
/**
* 第一步:规则注入,提取单据明细级审核要点清单
*/
public async injectAuditPoints(
client: KyInstance,
corpId: string,
documentSn: string,
options: { scope?: string | number } = {}
): Promise<InjectPointsResult> {
// 1. 获取单据详情
const bills = await getBillByCodeOrId(client, corpId, documentSn);
if (bills.length === 0) {
throw new Error(`在当前企业下未找到单号或 ID 为 [${documentSn}] 的单据`);
}
const bill = bills[0];
const actualSn = bill.billCode || documentSn;
// 2. 匹配适用场景 (Scope)
let scopeDetail = options.scope !== undefined ? this.repo.getScopeDetail(options.scope) : null;
if (!scopeDetail) {
const allScopes = this.repo.listScopes();
if (allScopes.length === 0) {
throw new Error("规约库中暂无任何生效规则,请先使用 hose-use rule add <场景> <正文> 新增规则");
}
// 自动启发式场景匹配
const candidates = [bill.title, bill.stage, bill.billName].filter(Boolean) as string[];
let matchedSummary = allScopes.find((s) =>
candidates.some((c) => c.includes(s.scope) || s.scope.includes(c))
);
// 差旅特化匹配
if (!matchedSummary && candidates.some((c) => /差旅|出差|trip|hotel|住宿/i.test(c))) {
matchedSummary = allScopes.find((s) => /差旅|出差/i.test(s.scope));
}
// 默认回退至第一个场景
matchedSummary = matchedSummary ?? allScopes[0];
scopeDetail = this.repo.getScopeDetail(matchedSummary.index);
}
if (!scopeDetail || scopeDetail.rules.length === 0) {
throw new Error(`适用场景 [${options.scope ?? "自动匹配"}] 下暂无任何生效规则`);
}
// 3. 提取所有规则的 AST 条款要点
const clauseInputs: Array<{
ruleId: string;
ruleCode: number;
clauseText: string;
strictness: any;
}> = [];
for (const rule of scopeDetail.rules) {
const parsed = parseRuleBody(rule.body);
for (const clause of parsed.clauses) {
clauseInputs.push({
ruleId: rule.id,
ruleCode: rule.code,
clauseText: clause.action,
strictness: clause.strictness,
});
}
}
if (clauseInputs.length === 0) {
throw new Error(`场景 [${scopeDetail.scope}] 下的规则正文中未解析出任何合法判定要点 ([动作]{级别})`);
}
// 4. 为单据创建/重置审批运行记录
const run = this.repo.createOrResetApprovalRun({
documentSn: actualSn,
flowId: bill.billId,
corpId,
scope: scopeDetail.scope,
decision: "PENDING",
matchedRulesCount: clauseInputs.length,
failedRulesCount: 0,
documentSnapshot: JSON.stringify(bill),
});
// 5. 注入待核验要点清单 (Checklist)
const findings = this.repo.injectFindings(
run.id,
clauseInputs.map((c) => ({
ruleId: c.ruleId,
clauseText: c.clauseText,
strictness: c.strictness,
checkStatus: "PENDING",
}))
);
return {
run,
findings,
bill,
scope: scopeDetail.scope,
};
}
/**
* 查看单据当前审核清单状态
*/
public getAuditChecklist(documentSn: string, corpId?: string) {
return this.repo.getAuditChecklist(documentSn, corpId);
}
/**
* 第二步:对注入的要点逐项进行事实核验判定
*/
public evaluateAuditPoints(
documentSn: string,
evaluations: Array<{
index?: number;
id?: string;
status: FindingCheckStatus;
evidence?: string;
reasoning?: string;
}>,
corpId?: string,
): ApprovalFindingRecord[] {
const { run, findings } = this.repo.getAuditChecklist(documentSn, corpId);
if (!run || findings.length === 0) {
throw new ApprovalGatewayBlockedError(
`[审批链路阻断] 单据 [${documentSn}] 尚未注入任何审核要点清单(要点列表为空)。\n` +
`在没有注入审核要点的情况下,无法进行事实核验!\n` +
`请先执行: hose-use approval audit points ${documentSn} 注入审核要点清单。`
);
}
for (const item of evaluations) {
let target: ApprovalFindingRecord | undefined;
if (item.id) {
target = findings.find((f) => f.id === item.id);
} else if (item.index !== undefined) {
target = findings[item.index - 1];
}
if (!target) {
throw new Error(`未找到要点: ${item.id ?? `#${item.index}`}`);
}
this.repo.updateFinding(target.id, {
checkStatus: item.status,
evidence: item.evidence,
reasoning: item.reasoning,
});
}
return this.repo.getFindingsByRunId(run.id);
}
/**
* 第三步:确定性网关裁决与下游流转
*/
public async decideAudit(
client: KyInstance,
corpId: string,
documentSn: string,
options: DecideAuditOptions = {}
): Promise<DecideAuditResult> {
const { run, findings } = this.repo.getAuditChecklist(documentSn, corpId);
if (!run) {
throw new ApprovalGatewayBlockedError(
`[审批链路阻断] 单据 [${documentSn}] 尚未注入任何明细级审核要点(要点列表为空)!\n` +
`网关卡点生效:审核要点未注入前,审批链路物理切断,绝对禁止进入审批决策!\n` +
`请先执行: hose-use approval audit points ${documentSn} 注入审核要点。`
);
}
// 确定性网关仲裁:由独立的可配置网关策略脚本执行(执行核心门禁与裁决计算)
const gatewayResult = evaluateGatewayPolicy(
{
documentSn,
findings,
requestedAction: options.requestedAction,
opinion: options.comment,
},
options.gatewayConfig ?? this.gatewayPolicy.getConfig()
);
const {
decision,
decisionSummary,
hardFailedCount,
elasticFailedCount,
suggestFailedCount,
specialFailedCount,
} = gatewayResult;
// 4. 更新数据库中的运行记录状态
this.repo.updateApprovalRun(run.id, {
decision,
decisionSummary,
failedRulesCount: gatewayResult.analysis.failedFindings.length,
});
let appliedAction = options.requestedAction;
let actionResult: unknown = undefined;
// 5. 如果开启了 --apply,由网关在内部安全受控地调用下游接口。
// 远端失败时把本地运行标记为 ERROR,避免数据库显示“已决策”但实际未执行。
if (options.apply) {
if (!appliedAction) {
appliedAction = decision === "REJECT" ? "reject" : decision === "APPROVE" || decision === "PASS_WITH_NOTE" ? "approve" : "comment";
}
try {
if (appliedAction === "reject") {
actionResult = await rejectBill(client, corpId, documentSn, {
comment: decisionSummary,
});
} else if (appliedAction === "approve") {
actionResult = await approveBill(client, corpId, documentSn, {
comment: decisionSummary,
});
} else {
actionResult = await commentBill(client, corpId, documentSn, {
comment: decisionSummary,
});
}
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
this.repo.updateApprovalRun(run.id, {
decision: "ERROR",
decisionSummary: `${decisionSummary}\n[下游执行失败] ${message}`,
});
throw error;
}
}
const updatedRun = this.repo.getRunById(run.id)!;
return {
run: updatedRun,
decision,
decisionSummary,
hardFailedCount,
elasticFailedCount,
suggestFailedCount,
specialFailedCount,
appliedAction,
actionResult,
};
}
}
+139
View File
@@ -0,0 +1,139 @@
export type StrictnessTier = "硬性" | "弹性" | "建议" | "特殊";
export const VALID_STRICTNESS_TIERS: readonly StrictnessTier[] = [
"硬性",
"弹性",
"建议",
"特殊"
] as const;
export function isValidStrictnessTier(value: string): value is StrictnessTier {
return (VALID_STRICTNESS_TIERS as readonly string[]).includes(value);
}
export interface RuleClause {
/** 抽取的动作句式文本,如 "一定需要上传发票" */
action: string;
/** 严格程度级别 */
strictness: StrictnessTier;
/** 原始标记子串,如 "[一定需要上传发票]{硬性}" */
raw: string;
/** 在正文中的起始字符索引 */
startIndex: number;
/** 在正文中的结束字符索引 */
endIndex: number;
}
export interface ParsedRule {
/** 原始正文 */
rawBody: string;
/** 解析出的所有判定要点 */
clauses: RuleClause[];
/** 剥离语法包裹后的纯文本,用于全文检索与语境理解 */
cleanText: string;
}
export interface ScopeSummary {
/** 1-based 索引编号 (1, 2, 3...),供 AI 和 CLI 快捷定位 */
index: number;
/** 适用场景名称/索引全名 */
scope: string;
/** 该索引下包含的有效规则总数 */
ruleCount: number;
/** 归属该索引的所有规则编号数组 (如 [1, 2, 4]) */
ruleCodes: number[];
}
export interface ScopeDetail {
index: number;
scope: string;
ruleCount: number;
rules: Array<RuleRecord & { parsed: ParsedRule }>;
}
export interface RuleRecord {
id: string;
code: number;
scope: string;
body: string;
status: "active" | "draft" | "archived";
version: number;
createdAt: number;
updatedAt: number;
}
export interface PreferenceRecord {
id: string;
name: string;
isDefault: boolean;
rulesReject: string;
rulesReview: string;
rulesPassNote: string;
rulesApprove: string;
updatedAt: number;
}
export type ApprovalDecision = "PENDING" | "APPROVE" | "REJECT" | "PASS_WITH_NOTE" | "REVIEW" | "ERROR";
export interface ApprovalRunRecord {
id: string;
shortId?: string | null;
expiresAt?: number | null;
flowId?: string | null;
documentSn: string;
corpId?: string | null;
scope?: string | null;
decision: ApprovalDecision;
decisionSummary?: string | null;
matchedRulesCount: number;
failedRulesCount: number;
documentSnapshot?: string | null;
createdAt: number;
updatedAt: number;
}
export type FindingCheckStatus = "PENDING" | "PASS" | "FAIL" | "SKIP";
export interface ApprovalFindingRecord {
id: string;
runId: string;
ruleId?: string | null;
ruleCode?: number | null;
clauseText: string;
strictness: StrictnessTier;
checkStatus: FindingCheckStatus;
evidence?: string | null;
reasoning?: string | null;
createdAt: number;
}
export class ApprovalRuleValidationError extends Error {
public readonly code = "RULE_VALIDATION_ERROR";
constructor(message: string) {
super(message);
this.name = "ApprovalRuleValidationError";
}
}
export class ApprovalGatewayBlockedError extends Error {
public readonly code = "APPROVAL_GATEWAY_BLOCKED";
constructor(message: string) {
super(message);
this.name = "ApprovalGatewayBlockedError";
}
}
export interface AiProLogRecord {
id: string;
runId?: string | null;
action: string;
documentSn?: string | null;
operator?: string | null;
args?: string | null;
status: "SUCCESS" | "BLOCKED" | "ERROR";
decision?: ApprovalDecision | null;
summary?: string | null;
createdAt: number;
}
+1 -1
View File
@@ -36,4 +36,4 @@ src/domains/bill/
- `commentBill` 调用 `POST /api/flow/v1/flows/comment/$<flowId>`,使用 `freeflow.comment`,保留参与人和私密评论参数;
- 动作执行前从审批详情解析 backlog ID、流程 ID、当前节点 ID,并可依据 `flow.actions` 校验当前身份是否具备该动作权限。
CLI 入口为 `hose bill approve|reject|transfer|add-node|comment <单号|ID>`。所有会改变状态的动作都要求 `--yes`(交互终端未提供时会拒绝执行);转交和加签的 `--approver-id` 支持完整员工 ID、工号或唯一姓名匹配,驳回强制要求 `--comment`。
CLI 入口为 `hose-use bill approve|reject|transfer|add-node|comment <单号|ID>`。所有会改变状态的动作都要求 `--yes`(交互终端未提供时会拒绝执行);转交和加签的 `--approver-id` 支持完整员工 ID、工号或唯一姓名匹配,驳回强制要求 `--comment`。
+42 -1
View File
@@ -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;
}
}
+225
View File
@@ -281,4 +281,229 @@ describe("Bill Domain", () => {
} as any;
await expect(resolveBillStaffIds(client, "corp-action", ["111", "谢子豪"])).resolves.toEqual(["corp:staff-2", "corp:staff-1"]);
});
it("translates raw bill flow into standard markdown representation", () => {
const { translateBillFlowToMarkdown } = require("./translator.js");
const rawFlow = {
flowId: {
state: "APPROVING",
form: {
code: "S26000001",
title: "我🩷吃醋",
specificationId: "ID01MCcOgJl1td:PRESET_REQUISITION_TRIP",
submitterId: { name: "谢子豪" },
requisitionDate: 1769961600000,
submitDate: 1770284988706,
requisitionMoney: { standard: "1000.00", standardStrCode: "CNY" },
details: [
{
feeTypeId: "ID01MCcOgJl1td:hotel",
feeTypeForm: {
amount: { standard: "1000", standardStrCode: "CNY" },
feeDate: 1770220800000,
city: '[{"key":"513","label":"辽宁省/大连市/大连市区"}]',
consumptionReasons: "今日在大连见客户",
detailId: "ID01QkCjK2m47Z",
detailNo: 1,
},
},
],
},
},
};
const markdown = translateBillFlowToMarkdown(rawFlow);
expect(markdown).toContain("# 单据:S26000001");
expect(markdown).toContain("- **状态**: 审批中 (approving)");
expect(markdown).toContain("- **单据模板**: `差旅申请单`");
expect(markdown).toContain("- **标题**: `我🩷吃醋`");
expect(markdown).toContain("- **提交人**: 谢子豪");
expect(markdown).toContain("- **申请金额**: CNY 1000.00");
expect(markdown).toContain("### 费用明细(共 1 条)");
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\")");
});
});
+313 -1
View File
@@ -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,
@@ -646,6 +649,138 @@ export function formatSingleBill(
};
}
export function formatFlowAsBill(
raw: Record<string, unknown>,
dictionary: Map<string, { label: string; type: string }>
): FormattedBill {
const flow = (raw.flowId && typeof raw.flowId === "object" ? raw.flowId : {}) as Record<string, unknown>;
const form = (flow.form && typeof flow.form === "object" ? flow.form : {}) as Record<string, unknown>;
const billCode = (typeof form.code === "string" && form.code.trim()) || (typeof flow.id === "string" ? flow.id : String(raw.id || ""));
const title = (typeof form.title === "string" && form.title.trim()) || (typeof flow.title === "string" ? flow.title : undefined);
const billName = title || (flow.formType === "requisition" ? "差旅申请单" : "审批单据");
const stage = typeof flow.formType === "string" ? flow.formType : "flow";
const state = raw.nodeName
? `${raw.state || flow.state || "APPROVING"} (${raw.nodeName})`
: (typeof raw.state === "string" ? raw.state : typeof flow.state === "string" ? flow.state : "APPROVING");
let amountStr: string | undefined;
for (const key of ["requisitionMoney", "amount", "expenseMoney", "payMoney"]) {
const val = form[key];
if (val && typeof val === "object" && (val as any).standard !== undefined) {
const money = val as any;
amountStr = `${money.standardSymbol || "¥"}${money.standard} ${money.standardStrCode || "CNY"}`.trim();
break;
}
}
let submitterId: string | undefined;
const submitter = form.submitterId as Record<string, unknown> | undefined;
if (submitter && typeof submitter === "object") {
const name = submitter.name || "";
const code = submitter.code ? ` (${submitter.code})` : "";
const dept = (submitter.defaultDepartment as Record<string, unknown>)?.name;
submitterId = `${name}${code}${dept ? ` - ${dept}` : ""}`.trim();
} else if (typeof form.submitterId === "string") {
submitterId = form.submitterId;
}
let submitDateStr: string | undefined;
if (typeof form.submitDate === "number" && form.submitDate > 1000000000000) {
submitDateStr = new Date(form.submitDate).toLocaleString("zh-CN");
}
const createTimeNum = typeof flow.createTime === "number" ? flow.createTime : typeof raw.createTime === "number" ? raw.createTime : 0;
const updateTimeNum = typeof flow.updateTime === "number" ? flow.updateTime : typeof raw.updateTime === "number" ? raw.updateTime : 0;
const createTimeStr = createTimeNum > 0 ? new Date(createTimeNum).toLocaleString("zh-CN") : "";
const updateTimeStr = updateTimeNum > 0 ? new Date(updateTimeNum).toLocaleString("zh-CN") : "";
const readableDetails: Record<string, any> = {};
if (raw.nodeName) readableDetails["当前节点"] = raw.nodeName;
if (raw.id) readableDetails["任务 ID"] = raw.id;
if (flow.id) readableDetails["流程 ID"] = flow.id;
if (flow.formType) readableDetails["表单类型"] = flow.formType;
const detailsArray = Array.isArray(form.details) ? form.details : [];
if (detailsArray.length > 0) {
readableDetails["费用明细条数"] = `${detailsArray.length} 笔`;
detailsArray.forEach((item, idx) => {
const feeForm = (item.feeTypeForm && typeof item.feeTypeForm === "object" ? item.feeTypeForm : {}) as Record<string, unknown>;
const feeTypeId = typeof item.feeTypeId === "string" ? item.feeTypeId.split(":").at(-1) || item.feeTypeId : "费用";
let rowMoney = "";
if (feeForm.amount && typeof feeForm.amount === "object") {
const m = feeForm.amount as any;
rowMoney = `${m.standardSymbol || "¥"}${m.standard} ${m.standardStrCode || "CNY"}`.trim();
}
let cityStr = "";
if (typeof feeForm.city === "string") {
try {
const parsedCity = JSON.parse(feeForm.city);
if (Array.isArray(parsedCity) && parsedCity[0]?.label) {
cityStr = parsedCity[0].label;
} else {
cityStr = feeForm.city;
}
} catch {
cityStr = feeForm.city;
}
}
let dateStr = "";
if (typeof feeForm.feeDate === "number" && feeForm.feeDate > 1000000000000) {
dateStr = new Date(feeForm.feeDate).toLocaleDateString("zh-CN");
}
const reason = feeForm.consumptionReasons || feeForm.reason || "";
const attachments = Array.isArray(feeForm.attachments) ? feeForm.attachments.length : 0;
const summaryParts = [
`[${feeTypeId}]`,
cityStr,
rowMoney,
dateStr,
reason ? `事由: ${reason}` : "",
`附件: ${attachments} 个`,
].filter(Boolean);
readableDetails[`明细 #${idx + 1}`] = summaryParts.join(" | ");
if (reason) readableDetails[`明细 #${idx + 1} 事由`] = reason;
if (cityStr) readableDetails[`明细 #${idx + 1} 城市`] = cityStr;
});
}
for (const [k, v] of Object.entries(form)) {
if (["code", "title", "details", "submitterId", "submitDate", "requisitionMoney", "amount", "expenseMoney", "logs", "flowPlanId"].includes(k)) continue;
if (v === null || v === undefined || v === "") continue;
const meta = dictionary.get(k);
const bareKey = k.replace(/^E_[^_]+_/, "").replace(/^E_/, "");
const label = meta ? meta.label : (COMMON_FIELD_LABELS[k] || COMMON_FIELD_LABELS[bareKey] || k);
if (typeof v === "object") {
readableDetails[label] = JSON.stringify(v);
} else {
readableDetails[label] = v;
}
}
return {
billId: String(flow.id || raw.id || ""),
billCode,
billName,
title,
stage,
state,
amount: amountStr,
submitterId,
submitDate: submitDateStr,
corporationId: String(flow.corporationId || raw.corporationId || ""),
ownerId: typeof flow.ownerId === "object" ? (flow.ownerId as any)?.name : typeof flow.ownerId === "string" ? flow.ownerId : undefined,
createTime: createTimeStr,
updateTime: updateTimeStr,
details: readableDetails,
};
}
// ── 业务操作:按单号或 ID 精确查询单据 ─────────────────────────────────────────
export async function getBillByCodeOrId(
@@ -685,7 +820,21 @@ export async function getBillByCodeOrId(
return false;
});
return matched.map((it) => formatSingleBill(it, dictionary));
if (matched.length > 0) {
return matched.map((it) => formatSingleBill(it, dictionary));
}
// 3. 回退到审批流程/待办接口检索(支持申请单 Requisition、借款单、自由流待办)
try {
const rawFlow = await getRawBillFlow(client, corpId, cleanQuery);
if (rawFlow) {
return [formatFlowAsBill(rawFlow, dictionary)];
}
} catch {
// 忽略流程回退错误
}
return [];
}
function flowPerson(value: unknown): { id?: string; name?: string; code?: string } | undefined {
@@ -1124,3 +1273,166 @@ export const billTools = [
},
},
];
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";
+688
View File
@@ -0,0 +1,688 @@
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;
}
// ── 1. 金额格式化 ─────────────────────────────────────────────────────────────
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 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 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);
}
// ── 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 "对公付款";
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>,
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>;
const code = form.code || flowIdObj.code || "未知单号";
const title = form.title || flowIdObj.title || "<无标题>";
const rawState = flowIdObj.state || "approving";
const stateLabel = String(rawState).toUpperCase() === "APPROVING" ? "审批中" : rawState;
const submitTime = formatDateValue(form.submitDate || flowIdObj.createTime);
const templateName = resolveSpecificationName(form.specificationId);
const submitterName = formatPersonValue(form.submitterId, options?.staffMap);
const requisitionDate = formatDateValue(form.requisitionDate || form.expenseDate);
const lines: string[] = [];
lines.push(`# 单据:${code}`);
lines.push("");
lines.push("## 基本信息");
lines.push("");
lines.push(`- **状态**: ${stateLabel} (${String(rawState).toLowerCase()})`);
lines.push(`- **提交时间**: ${submitTime}`);
lines.push("");
lines.push(`### 单据信息(${code})`);
lines.push("");
lines.push(`- **单据模板**: \`${templateName}\``);
lines.push(`- **补充申请**: <无>`);
lines.push(`- **标题**: \`${title}\``);
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}`);
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 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} 条)`);
lines.push("");
details.forEach((item: any, idx: number) => {
const num = idx + 1;
lines.push(`#### 明细 ${num}`);
lines.push("");
const feeForm = item.feeTypeForm || item;
const feeTypeId = item.feeTypeId || feeForm.feeTypeId || "";
let feeTypeName = "住宿费";
let feeTypePath = "差旅报销/住宿费";
if (options?.feeTypeMap?.has(feeTypeId)) {
const match = options.feeTypeMap.get(feeTypeId)!;
feeTypeName = match.name || feeTypeName;
feeTypePath = match.path || feeTypeName;
} else if (typeof feeTypeId === "string") {
if (feeTypeId.includes("hotel") || feeTypeId.includes("住宿")) {
feeTypeName = "住宿费";
feeTypePath = "差旅报销/住宿费";
} else if (feeTypeId.includes("meal") || feeTypeId.includes("餐")) {
feeTypeName = "餐饮费";
feeTypePath = "业务招待/餐饮费";
} else if (feeTypeId.includes("traffic") || feeTypeId.includes("交通")) {
feeTypeName = "市内交通费";
feeTypePath = "差旅报销/市内交通费";
} else if (feeTypeId.includes("3iPhCno9HdI") || feeTypeId.includes("办公")) {
feeTypeName = "办公用品";
feeTypePath = "办公费/办公用品";
}
}
lines.push(`- **费用类型**: ${feeTypePath}(name=${feeTypeName})`);
if (feeForm.feeDate) {
lines.push(`- **日期**: ${formatDateValue(feeForm.feeDate, true)}`);
}
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("");
});
return lines.join("\n");
}
+1 -1
View File
@@ -24,7 +24,7 @@ export async function listStaffsProtected(
limit,
hasMore,
hint: hasMore
? `企业员工共 ${total} 人,当前仅展示前 ${staffs.length} 条以防止上下文溢出。可使用 'hose contact search <姓名|工号>' 精准检索,或附加 '--limit <数量>' / '-o <文件路径>' / '--full'`
? `企业员工共 ${total} 人,当前仅展示前 ${staffs.length} 条以防止上下文溢出。可使用 'hose-use contact search <姓名|工号>' 精准检索,或附加 '--limit <数量>' / '-o <文件路径>' / '--full'`
: undefined,
staffs,
};
+1 -1
View File
@@ -4,4 +4,4 @@
- `GET /api/glue/v1/organization/permissions/query?model=ROLE&corpId=...`
CLI 入口为 `hose permission get`(也支持 `hose permissions get`)。写入权限仍需通过 Web 端明确操作,CLI 不提供写操作。
CLI 入口为 `hose-use permission get`(也支持 `hose-use permissions get`)。写入权限仍需通过 Web 端明确操作,CLI 不提供写操作。
+1 -1
View File
@@ -6,4 +6,4 @@
- `GET /api/v1/organization/roleGroups?corpId=...`:角色组及其角色定义
- `GET /api/v1/organization/staffs/byRole?roleDefId=...&corpId=...`:指定角色的员工成员
CLI 入口为 `hose role list`、`hose role groups` 和 `hose role members <角色 ID|编码|名称>`。
CLI 入口为 `hose-use role list`、`hose-use role groups` 和 `hose-use role members <角色 ID|编码|名称>`。
+1 -1
View File
@@ -1 +1 @@
export const VERSION = "0.6.2";
export const VERSION = "0.7.3";