Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cd7bb44f04 | ||
|
|
0cdd62161f | ||
|
|
9f9f3abe22 | ||
|
|
fb700a4c86 | ||
|
|
0be629778f | ||
|
|
a415bf38c3 | ||
|
|
d447426d48 | ||
|
|
03d2337e13 | ||
|
|
6f49bfc8a4 | ||
|
|
97b67c71da | ||
|
|
09c4e7df4a | ||
|
|
69c6396d38 | ||
|
|
3c680d0ed3 | ||
|
|
215bc5e2a1 | ||
|
|
3d0bc2ebff | ||
|
|
1cd8901f7a | ||
|
|
8efce4342a | ||
|
|
893fc47ac6 | ||
|
|
2502a49fb9 | ||
|
|
212371eb03 | ||
|
|
e852dbfd47 | ||
|
|
0c953df30e | ||
|
|
9a2d4529f5 | ||
|
|
3937d3799b | ||
|
|
bcf8ac0de6 | ||
|
|
3a15b064fe | ||
|
|
00cbf039eb | ||
|
|
a2eb04c4c1 | ||
|
|
3f015d8e22 | ||
|
|
2b467dc076 | ||
|
|
a5b5f1918e | ||
|
|
b72b5d7f71 | ||
|
|
a8e32cff32 | ||
|
|
5e06429d6c | ||
|
|
3777e81ee7 | ||
|
|
0ee5031dc8 | ||
|
|
2bf8d22810 | ||
|
|
f2b0f15a6e | ||
|
|
065ba42bfe | ||
|
|
6260b824a0 | ||
|
|
7efa83ff30 | ||
|
|
1b5ae12254 | ||
|
|
27660bed92 |
No files matched your search
@@ -46,3 +46,5 @@ data/
|
||||
|
||||
# Local roadmaps & scratch notes
|
||||
*.local.md
|
||||
.agents/
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.7.2",
|
||||
"version": "0.8.4",
|
||||
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
|
||||
"author": {
|
||||
"name": "yingqing"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# hose-use (v0.7.2)
|
||||
# hose-use (v0.8.5)
|
||||
|
||||
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
|
||||
|
||||
@@ -29,6 +29,7 @@ hose-use auth refresh # 批量刷新账号名下全部
|
||||
|
||||
# 2. 多企业租户管理
|
||||
hose-use corps list # 列出名下所有已配置企业
|
||||
hose-use corps search <关键词> # 模糊搜索已保存的企业与员工 (别名: corps find)
|
||||
hose-use corps switch <corpId> # 切换工作企业
|
||||
hose-use corps current # 查看当前激活企业
|
||||
|
||||
@@ -38,11 +39,20 @@ hose-use config paths # 查看多级企业目录发现
|
||||
hose-use config mode stateless # 切换为无状态模式 (防止 Agent 误操作)
|
||||
hose-use config mode stateful # 切换为有状态模式 (记忆默认企业)
|
||||
|
||||
# 4. 平台与工作流管理 (跨自建应用聚合)
|
||||
# 4. 工作台应用、菜单与工作流管理 (跨自建应用聚合)
|
||||
hose-use app list # 查看工作台应用管理列表 (含套件/制度/模板/自建)
|
||||
hose-use app get <应用ID|名称> # 查看具体应用详情与 Web 直达路由
|
||||
hose-use menu list # 查看桌面端全站一级主导航与模块列表
|
||||
hose-use workflow list # 汇总查看全部工作流列表
|
||||
hose-use workflow get <pipelineId> # 获取工作流详情与节点结构
|
||||
hose-use workflow find --task=code-js2 # 搜索包含特定节点类型的工作流
|
||||
hose-use workflow toggle <pipelineId> --state=1 # 启用/停用工作流
|
||||
hose-use workflow save <pipelineId> --file=workflow.json # 按完整快照保存草稿
|
||||
hose-use workflow patch <pipelineId> --file=workflow.json --path=tasks.0.code --value='return 2;' --output=patched.json
|
||||
hose-use workflow history <pipelineId> # 查看服务端版本快照历史
|
||||
hose-use workflow logs <pipelineId> --state=FAILED # 查看工作流运行错误日志
|
||||
hose-use workflow check --json --fail-on-alert # 检查错误管道并按错误计数去重提醒
|
||||
hose-use workflow publish <pipelineId> # 保存后的发布/启用
|
||||
hose-use platform list # 查看企业下所有启用的自建应用
|
||||
|
||||
# 5. 单据与费用明细管理 (DataLink 字典自动还原 & 200KB 防爆拦截)
|
||||
|
||||
Vendored
+748
-242
File diff suppressed because it is too large.
Load diff
Vendored
+1
-1
@@ -2,7 +2,7 @@
|
||||
"openapi": "3.1.0",
|
||||
"info": {
|
||||
"title": "hose-use API & MCP Tools Specification",
|
||||
"version": "0.7.2",
|
||||
"version": "0.8.4",
|
||||
"description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."
|
||||
},
|
||||
"servers": [
|
||||
|
||||
@@ -10,6 +10,12 @@ src/domains/platform/
|
||||
├── api.ts # HTTP 传输层(EKB / EASO / Piper 接口封装)
|
||||
└── tools.ts # MCP tool 注册 + 服务层聚合函数
|
||||
|
||||
src/domains/datalink/
|
||||
├── types.ts # 应用、业务对象、字段、记录与权限模型
|
||||
├── api.ts # DataLink HTTP 接口封装
|
||||
├── services.ts # 应用/对象解析与过滤辅助
|
||||
└── tools.ts # DataLink MCP tools
|
||||
|
||||
src/server.ts # MCP Server 入口,负责 tool 注册与客户端派发
|
||||
```
|
||||
|
||||
@@ -40,6 +46,18 @@ src/server.ts # MCP Server 入口,负责 tool 注册与客户端派发
|
||||
|
||||
## MCP Tools
|
||||
|
||||
### DataLink 应用与业务对象
|
||||
|
||||
| Tool | 说明 | 后端 |
|
||||
|---|---|---|
|
||||
| `datalink_platform_list` | 列出当前企业账号可见的启用自建应用 | EKB |
|
||||
| `datalink_platform_get` | 获取应用详情及管理员、人员、角色、部门权限 | EKB |
|
||||
| `datalink_entity_list` | 获取应用下业务对象、字段、操作和可见性配置 | EKB |
|
||||
| `datalink_record_search` | 分页检索业务对象记录,支持 `filterBy` | EKB |
|
||||
| `datalink_import_jobs` | 查看对象导入任务及最近导入结果 | EKB |
|
||||
|
||||
CLI 入口保持在 `platform` 命令域,支持 `list`、`get`、`entities`、`schema`、`records`、`permissions` 和 `imports`。
|
||||
|
||||
| Tool | 说明 | 后端 |
|
||||
|---|---|---|
|
||||
| `platform_list` | 列出企业下所有启用的自建应用 | EKB |
|
||||
@@ -48,6 +66,12 @@ src/server.ts # MCP Server 入口,负责 tool 注册与客户端派发
|
||||
| `platform_workflow_charge` | 查询企业工作流用量配额 | EASO |
|
||||
| `platform_workflow_detail` | 获取工作流详情(含节点配置) | EASO / Piper |
|
||||
| `platform_workflow_toggle` | 启用/停用工作流 | EASO / Piper |
|
||||
| `workflow save` (CLI) | 按完整快照保存工作流草稿并校验版本 | Piper |
|
||||
| `workflow history` (CLI) | 读取工作流服务端版本快照历史 | Piper |
|
||||
| `workflow patch` (CLI) | 在本地完整快照上修改节点路径,生成新草稿文件 | 本地 |
|
||||
| `workflow logs` (CLI) | 查询指定工作流运行日志 | Piper |
|
||||
| `workflow check` (CLI) | 扫描错误管道并持久化去重提醒 | 本地 + EASO |
|
||||
| `workflow publish` (CLI) | 将已保存的工作流状态切换为启用 | Piper |
|
||||
| `platform_workflow_jobs` | 查询工作流运行中的任务 | EASO / Piper |
|
||||
| `platform_workflow_dsl` | 获取工作流 DSL 配置列表 | EASO / Piper |
|
||||
| `platform_workflow_staffs` | 获取企业员工列表 | EASO / Piper |
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
openapi: 3.1.0
|
||||
info:
|
||||
title: hose-use API & MCP Tools Specification
|
||||
version: 0.7.2
|
||||
version: 0.8.4
|
||||
description: >-
|
||||
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
|
||||
servers:
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.7.2",
|
||||
"version": "0.8.5",
|
||||
"module": "src/server.ts",
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env bun
|
||||
import { readFileSync, writeFileSync, existsSync, cpSync } from "node:fs";
|
||||
import { readFileSync, writeFileSync, existsSync, cpSync, readdirSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { execSync } from "node:child_process";
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -75,7 +78,10 @@ if (existsSync(pluginJsonPath)) {
|
||||
// 6. Sync to global ~/.agents/skills/hose-use/ if present
|
||||
const globalSkillDir = join(process.env.HOME || "", ".agents", "skills", "hose-use");
|
||||
if (existsSync(globalSkillDir)) {
|
||||
cpSync(join(ROOT, "skills", "hose-use"), globalSkillDir, { recursive: true });
|
||||
const srcDir = join(ROOT, "skills", "hose-use");
|
||||
for (const item of readdirSync(srcDir)) {
|
||||
cpSync(join(srcDir, item), join(globalSkillDir, item), { recursive: true, force: true });
|
||||
}
|
||||
console.log("✓ Synchronized ~/.agents/skills/hose-use/");
|
||||
}
|
||||
|
||||
|
||||
+53
-12
@@ -1,12 +1,12 @@
|
||||
---
|
||||
name: hose-use
|
||||
description: "v0.7.2: 合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号 API 登录、租户切换、单据检索与审批动作、工作流跨域扫描、内置 HTTP 交互文档与常驻守护进程。"
|
||||
description: "v0.8.5: 合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号 API 登录、租户切换、单据检索与审批动作、工作流跨域扫描、内置 HTTP 交互文档与常驻守护进程。"
|
||||
metadata:
|
||||
version: 0.7.2
|
||||
short-description: 合思/易快报企业级 CLI 工具与底层 SDK (v0.7.2)
|
||||
version: 0.8.5
|
||||
short-description: 合思/易快报企业级 CLI 工具与底层 SDK (v0.8.5)
|
||||
---
|
||||
|
||||
# hose-use (v0.7.2)
|
||||
# hose-use (v0.8.5)
|
||||
|
||||
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
|
||||
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
|
||||
@@ -15,8 +15,9 @@ metadata:
|
||||
|
||||
## Agent 执行原则 (First Rules)
|
||||
|
||||
0. **一键构建上下文(Zero Source-Reading)**:在开始执行任务前,优先执行 `hose-use context --json` 或 `hose-aipro status --json` 一键获取当前账号、企业租户、登录凭证、运行模式与 AI PRO 网关状态。**严禁翻阅源码目录探查配置与企业列表**。
|
||||
1. **通道自适应**:将 CLI/MCP 视为 Agent 的执行通道,而不是要求用户学习命令行。Agent 应主动将用户的自然语言诉求转换为具体的 CLI 命令;严禁要求用户手动拼装命令行参数。
|
||||
2. **多租户优先探查**:在需要企业参数前,优先执行 `hose-use corps list`。如果目标企业已配置,通过企业名称映射出对应的 `id` 并作为 `--corp=<id>` 传入;不要向普通用户询问底层 `corpId`。
|
||||
2. **多租户优先探查**:在需要企业参数前,优先执行 `hose-use corps list` 或 `hose-use context`。如果目标企业已配置,通过企业名称映射出对应的 `id` 并作为 `--corp=<id>` 传入;不要向普通用户询问底层 `corpId`。
|
||||
3. **输出防护与大报文处理**:
|
||||
- 面对单据明细、实体字典、工作流等大数据量查询,优先使用 `--json -o <path>` 本地转储或使用 `--limit` 限制分页;
|
||||
- 严禁盲目使用 `--full` 将上万行原始报文一次性塞入上下文;
|
||||
@@ -29,7 +30,13 @@ metadata:
|
||||
|
||||
| 用户意图 / 场景 | 推荐命令 | 深入参考文档 |
|
||||
|---|---|---|
|
||||
| 全局运行上下文 / 身份诊断 / 免读源码自省 | `hose-use context [--json]`, `hose-use status` | [references/auth.md](references/auth.md) |
|
||||
| AI PRO 审批仲裁网关状态与当前连接企业 | `hose-aipro status [--json]`, `hose-use aipro status` | [references/approval.md](references/approval.md) |
|
||||
| AI PRO 规则场景库与审核要点清单 | `hose-aipro scopes`, `hose-aipro points <索引>` | [references/approval.md](references/approval.md) |
|
||||
| AI PRO 确定性审批仲裁全流程 (核验/仲裁) | `hose-aipro bind`, `hose-aipro review`, `hose-aipro decide` | [references/approval.md](references/approval.md) |
|
||||
| 本地 AI 审批规约与规则增删改查 | `hose-use rule scopes`, `hose-use rule add`, `hose-use rule list` | [references/approval.md](references/approval.md) |
|
||||
| 首次登录 / 账密认证 / Token过期 / 多账号 | `hose-use auth login`, `hose-use auth status`, `hose-use auth refresh` | [references/auth.md](references/auth.md) |
|
||||
| 第三方免密/协助链接一键秒级导入 | `hose-use corps add-link <url>`, `hose-use auth add-link <url>` | [references/auth.md](references/auth.md) |
|
||||
| 代客协助凭证导入 / 探针连通性诊断 | `hose-use auth import`, `hose-use probe` | [references/auth.md](references/auth.md) |
|
||||
| 企业租户切换 / 查看当前企业 | `hose-use corps list`, `hose-use corps switch <id>` | [references/auth.md](references/auth.md) |
|
||||
| 报销单据检索 / 费用明细下钻 / 中文字典 | `hose-use bill list`, `hose-use bill get <单号|ID> [--risk]` | [references/bill.md](references/bill.md) |
|
||||
@@ -42,17 +49,23 @@ metadata:
|
||||
| 单据附件 / 发票原件标准列表 | `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 feetype list`, `hose-use feetype create`, `hose-use feetype get <ID>` | [references/feetype.md](references/feetype.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) |
|
||||
| 应用管理 (桌面端工作台开通的用车/套件/制度/自建前台应用) | `hose-use app list [--keyword]`, `hose-use app get <应用>` | [references/workflow.md](references/workflow.md) |
|
||||
| 自建应用与数据模型 (开放平台业务对象/字段定义/底层记录) | `hose-use platform list`, `hose-use platform entities <应用>` | [references/workflow.md](references/workflow.md) |
|
||||
| 自建应用单条记录操作 (详情/停启用/字段编辑/台账重算) | `hose-use platform record <get|toggle|edit|recompute>` | [references/workflow.md](references/workflow.md) |
|
||||
| 跨自建应用工作流聚合检索与节点扫描 | `hose-use workflow list`, `hose-use workflow find --task=code-js2` | [references/workflow.md](references/workflow.md) |
|
||||
| 桌面端全站主导航与一级模块树 | `hose-use menu list`, `hose-use menu tree` | [references/workflow.md](references/workflow.md) |
|
||||
| 模糊搜索已保存的企业与员工信息 | `hose-use corps search <关键词>` | [references/auth.md](references/auth.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 get`, `hose-use workflow patch`, `hose-use workflow save`, `hose-use workflow publish`, `hose-use workflow history`, `hose-use workflow logs`, `hose-use workflow toggle` | [references/workflow.md](references/workflow.md) |
|
||||
| 工作流节点树、代码依赖与静态诊断 | `hose-use workflow analyze <pipelineId>` | [references/workflow.md](references/workflow.md) |
|
||||
| 工作流错误管道扫描与本地去重提醒 | `hose-use workflow check [--fail-on-alert]` | [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) |
|
||||
@@ -65,10 +78,16 @@ metadata:
|
||||
## 常用命令速查
|
||||
|
||||
```bash
|
||||
# 0. 全局上下文一键自省 (免读源码构建环境)
|
||||
hose-use context # 文本格式仪表盘 (当前账号/企业/工号/Token/AI PRO/路径)
|
||||
hose-use context --json # 结构化 JSON (供 Agent 零解析直接构建完整上下文)
|
||||
hose-aipro status # 查看 AI PRO 审批网关状态、当前连接企业与规则场景库
|
||||
hose-aipro # 首页直接展示动态企业页眉与快速工作流
|
||||
|
||||
# 1. 认证与企业
|
||||
hose-use auth login --phone=17718556446 --password=... # 纯 API 账密自动登录
|
||||
hose-use auth status # 查看 Token 剩余有效期与登录账号
|
||||
hose-use corps list # 查看企业租户列表
|
||||
hose-use corps list # 查看企业租户列表 (标注 * 为统一默认企业)
|
||||
hose-use corps switch ID01MCcOgJl1td # 切换工作企业
|
||||
hose-use probe # 诊断当前企业接口连通性
|
||||
|
||||
@@ -96,6 +115,13 @@ hose-use bill attachments S26000001 # 查看附件和发票
|
||||
hose-use bill download S26000001 --output-dir ./downloads # 下载附件到本地目录
|
||||
hose-use dimension list # 查看系统与自定义档案维度
|
||||
hose-use dimension items 项目 # 查看项目、成本中心等档案项
|
||||
hose-use feetype list # 树形层级查看企业费用类型
|
||||
hose-use feetype get 交通费 --specs # 查看费用类型详情与报账/申请字段
|
||||
hose-use feetype create --name="市内打车" --parent="交通费" # 在指定父级下新建费用类型
|
||||
hose-use feetype update 市内打车 --desc="滴滴企业版" # 修改费用类型属性
|
||||
hose-use feetype disable 市内打车 # 停用费用类型 (软删除)
|
||||
hose-use feetype enable 市内打车 # 重新启用费用类型
|
||||
hose-use feetype move 市内打车 --parent="差旅费用" # 移动费用类型到新父级
|
||||
hose-use role list # 查看企业角色定义
|
||||
hose-use role groups # 查看角色组及其角色
|
||||
hose-use role members 财务主管 # 查看指定角色成员
|
||||
@@ -109,12 +135,27 @@ hose-use message list --all # 合并查看已读和
|
||||
hose-use message count # 查看未读数量
|
||||
hose-use message read <messageId> # 标记单条消息已读
|
||||
|
||||
# 5. 自建应用与工作流
|
||||
hose-use platform list # 查看自建应用列表
|
||||
hose-use workflow list # 聚合扫描全部应用下的工作流
|
||||
# 5. 应用管理、自建应用与工作流
|
||||
hose-use app list # 查看应用管理列表(桌面端工作台业务应用集成)
|
||||
hose-use app get 用车补贴 # 查看指定应用管理的配置与 Web 路由
|
||||
hose-use platform list # 列出企业可见的自建应用平台
|
||||
hose-use platform entities 新转转集团 # 查看自建应用下的业务对象与字段
|
||||
hose-use platform records 新转转集团 合同 # 查看业务对象的底层数据记录
|
||||
hose-use platform record get 新转转集团 合同 <记录ID> # 获取单条记录完整字段与属性详情
|
||||
hose-use platform record toggle 新转转集团 合同 <记录ID> # 切换单条记录停启用状态
|
||||
hose-use platform record edit 新转转集团 合同 <记录ID> --data='{"name":"新名称"}' # 编辑记录字段
|
||||
hose-use platform record recompute 新转转集团 合同 <记录ID> # 重新计算记录关联的全部台账
|
||||
hose-use menu 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 # 输出节点树、引用依赖与静态诊断
|
||||
hose-use workflow save wf_01k83y... --file=workflow.json # 按完整快照保存草稿并做版本保护
|
||||
hose-use workflow patch wf_01k83y... --file=workflow.json --path=tasks.0.code --value='return 2;' --output=patched.json
|
||||
hose-use workflow history wf_01k83y... --json # 查看服务端版本快照历史
|
||||
hose-use workflow logs wf_01k83y... --state=FAILED # 查看运行错误日志
|
||||
hose-use workflow check --json --fail-on-alert # 扫描错误管道并只提醒新增错误计数
|
||||
hose-use workflow publish wf_01k83y... # 将保存后的工作流发布/启用
|
||||
|
||||
# 6. 服务与守护进程
|
||||
hose-use http --port=8888 # 启动前台 HTTP 服务与交互式文档
|
||||
|
||||
@@ -11,6 +11,6 @@ tools:
|
||||
properties:
|
||||
command:
|
||||
type: "string"
|
||||
description: "完整的 hose-use 命令字符串,例如 'bill list --json', 'workflow find --task=code-js2', 'service status'"
|
||||
description: "完整的 hose-use 命令字符串,例如 'bill list --json', 'workflow check --json', 'workflow get <pipelineId> --json -o workflow.json', 'workflow save <pipelineId> --file=workflow.json', 'service status'"
|
||||
required:
|
||||
- "command"
|
||||
@@ -0,0 +1,85 @@
|
||||
# 合思 AI PRO 确定性审批仲裁网关 (Approval Gateway & AI PRO Guide)
|
||||
|
||||
本参考专卷面向开发者与 AI 智能体,系统说明 `hose-aipro` 命令行、确定性网关仲裁机制与本地规约管理。
|
||||
|
||||
---
|
||||
|
||||
## 1. 架构与定位
|
||||
|
||||
- **双向命令入口**:可通过独立二进制 `hose-aipro <子命令>` 或统一入口 `hose-use aipro <子命令>` 唤起。
|
||||
- **共享统一上下文**:`hose-aipro` 与 `hose-use` 共享相同的企业租户配置(`~/.config/hose-use/config.json` 与 `enterprises` 凭证目录)。
|
||||
- **零源码阅读自省**:运行 `hose-aipro status` 或 `hose-use context` 即可直接构建完整的运行时上下文,无需翻阅代码。
|
||||
- **强确定性硬条款阻断**:AI 仅负责事实核验打标(PASS / FAIL / SKIP);下游流转动作(同意 / 驳回 / 转人工)由本地网关根据【硬性 / 弹性 / 建议 / 特殊】分级硬编码规则仲裁,物理切断幻觉可能导致的违规放行。
|
||||
|
||||
---
|
||||
|
||||
## 2. 核心工作流与命令
|
||||
|
||||
### 步骤 0:查看运行上下文与当前绑定企业
|
||||
```bash
|
||||
hose-aipro status
|
||||
hose-aipro status --json
|
||||
```
|
||||
- 输出当前连接的企业 ID/名称、操作员工号、Token 有效期、已加载场景库统计与待决断会话数。
|
||||
|
||||
### 步骤 1:查看规约场景索引库
|
||||
```bash
|
||||
hose-aipro scopes
|
||||
# 或使用 hose-use:
|
||||
hose-use rule scopes
|
||||
```
|
||||
- 输出本地 SQLite 数据库中所有生效场景(如 `#1 差旅报销`、`#2 业务招待`)及规则条数。
|
||||
|
||||
### 步骤 2:查看场景审核要点清单
|
||||
```bash
|
||||
hose-aipro points 1
|
||||
# 或通过场景名称:
|
||||
hose-aipro points 差旅报销
|
||||
```
|
||||
- 查看场景下的所有审核要点、判定依据与严格级别(`硬性` / `弹性` / `建议` / `特殊`)。
|
||||
|
||||
### 步骤 3:为单据挂载审核要点清单
|
||||
```bash
|
||||
hose-aipro bind S26000001 1
|
||||
```
|
||||
- 将场景 #1 的要点清单初始化并绑定至单号 `S26000001`。
|
||||
|
||||
### 步骤 4:查看单据审核清单与核验进度
|
||||
```bash
|
||||
hose-aipro checklist S26000001
|
||||
```
|
||||
- 检查当前单据下各要点的打标状态(`PENDING` / `PASS` / `FAIL` / `SKIP`)。
|
||||
|
||||
### 步骤 5:逐项录入事实核验打标
|
||||
```bash
|
||||
# 批量快速打标:
|
||||
hose-aipro review S26000001 --eval "1=PASS:发票合规; 2=FAIL:住宿超标; 3=SKIP"
|
||||
|
||||
# 单项精准打标:
|
||||
hose-aipro review S26000001 --point 2 --status FAIL --reason "住宿费超过差旅标准 200 元"
|
||||
```
|
||||
|
||||
### 步骤 6:确定性网关仲裁与审批执行
|
||||
```bash
|
||||
# 预审仿真 (Dry Run - 仅仲裁不改变下游单据状态):
|
||||
hose-aipro decide S26000001
|
||||
|
||||
# 真实驱动下游执行 (需加 --apply --yes 确认):
|
||||
hose-aipro decide S26000001 --apply --yes
|
||||
```
|
||||
|
||||
### 步骤 7:审计流水全流程追溯
|
||||
```bash
|
||||
hose-aipro logs [单号]
|
||||
```
|
||||
- 追溯单据从初始化、打标到决断的每一步本地不可篡改审计记录。
|
||||
|
||||
---
|
||||
|
||||
## 3. 规约语法与严格程度等级
|
||||
|
||||
规则正文中必须包含合法的条款判定标记:
|
||||
- `[必须上传真实发票]{硬性}`:硬性条款违规时,网关物理阻断同意操作,必须驳回。
|
||||
- `[尽量提供行程水单]{弹性}`:弹性条款允许按策略放行或转人工复核。
|
||||
- `[建议补充备注说明]{建议}`:仅作提醒,不构成驳回条件。
|
||||
- `[金额大于10万需特殊说明]{特殊}`:直接触发人工会签或复核分支。
|
||||
@@ -2,6 +2,21 @@
|
||||
|
||||
本参考专卷详细说明 `hose-use` 的登录鉴权、会话维护、代客凭证、企业租户切换以及全局运行模式。
|
||||
|
||||
## 0. 全局运行上下文与环境自省 (`context`)
|
||||
|
||||
面向开发者与 AI 智能体的一键自省命令。**无需翻阅任何源码**即可直接获知当前登录主账号、当前激活企业、操作工号、Token 状态、多企业列表统计、AI PRO 规约库及配置文件路径。
|
||||
|
||||
```bash
|
||||
# 文本格式仪表盘
|
||||
hose-use context
|
||||
|
||||
# 结构化 JSON 输出 (推荐 Agent 首选使用)
|
||||
hose-use context --json
|
||||
```
|
||||
|
||||
- **别名**:`hose-use status`, `hose-use whoami`, `hose-use env`
|
||||
- **两端互通**:`hose-use` 与 `hose-aipro` 共享同一套企业与身份凭证上下文。
|
||||
|
||||
---
|
||||
|
||||
## 1. 账号认证与登录 (`auth`)
|
||||
@@ -27,6 +42,25 @@ 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
|
||||
|
||||
# 未提供服务端 expTime 时,可显式指定本地有效期
|
||||
hose-use corps add-link "<url>" --ttl 3d
|
||||
hose-use corps add-link "<url>" --expires 3 # 等价于 3 天;--days 3 也可以
|
||||
```
|
||||
- **全自动识别与身份探测**:
|
||||
- 自动从 URL 提取服务节点 `baseUrl`、集群环境 `cluster`(如 `wx2`、`app`)、`accessToken` 与 `corpId`;
|
||||
- 自动向 `$UNITY` JWT 与主站 Session 反查员工工号 (`staffId`)、员工姓名、绑定手机、企业全称与是否企业管理员,无需手动寻找工号;
|
||||
- 动态自适应多集群环境换票,确保主站单据审批与 EASO 低代码工作流平台权限全绿连通。
|
||||
- 非账号来源(link/browser/assist/curl/manual)不会触发账号换票;Token 失效时提示重新导入链接。
|
||||
- 服务端返回的 expTime 优先;未返回时不再强制套用 2 小时,可使用 `--ttl` / `--expires` 指定有效期。
|
||||
|
||||
### 代客协助凭证导入
|
||||
```bash
|
||||
hose-use auth import \
|
||||
@@ -35,7 +69,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
|
||||
@@ -53,6 +87,14 @@ hose-use corps list
|
||||
hose-use corps list --json
|
||||
```
|
||||
|
||||
### 模糊搜索企业 (`corps search` / `corps find`)
|
||||
```bash
|
||||
# 支持根据企业名称、企业 ID、员工工号、员工姓名或所属账号模糊搜索
|
||||
hose-use corps search 某企业
|
||||
hose-use corps search 17718556446
|
||||
hose-use corps search 周某某 --json
|
||||
```
|
||||
|
||||
### 切换当前活跃企业
|
||||
```bash
|
||||
hose-use corps switch uzU7pcWfScck00
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
# 费用类型与表单字段规格管理 (feetype)
|
||||
|
||||
费用类型 (FeeType) 是合思/易快报费控系统的底层核心业务实体,涵盖企业报销科目树、单据表单字段规则规格以及申请/报账控件配置。
|
||||
|
||||
## 常用命令
|
||||
|
||||
```bash
|
||||
# 1. 列表与树形层级
|
||||
hose-use feetype list # 树形层级展示当前企业所有活跃费用类型
|
||||
hose-use feetype list --all # 包含已停用的全量费用类型
|
||||
hose-use feetype list --keyword="差旅" # 模糊搜索名称、编码或路径
|
||||
hose-use feetype list --flat # 以平铺表格格式展示
|
||||
hose-use feetype list --json # JSON 结构化输出 (Agent 推荐)
|
||||
|
||||
# 2. 单项详情与字段规格
|
||||
hose-use feetype get 交通费 # 查看费用类型基本配置、层级与父子节点
|
||||
hose-use feetype get 交通费 --specs # 同时输出报账字段与申请字段配置摘要
|
||||
hose-use feetype fields 交通费 # 查看完整的报账与申请字段表格 (字段名、类型、必填、可编辑)
|
||||
|
||||
# 3. 创建与修改 (增改)
|
||||
hose-use feetype create --name="市内打车费" --parent="交通费" # 在指定父级下创建,自动继承父级字段规则
|
||||
hose-use feetype create --name="公杂费" --code="COST88" # 自定义编码并建在顶级
|
||||
hose-use feetype update 市内打车费 --desc="包含出租车与网约车" # 修改描述或属性
|
||||
hose-use feetype update 市内打车费 --color="#4caf50" # 修改标识颜色
|
||||
|
||||
# 4. 停用与启用 (删查)
|
||||
hose-use feetype disable 市内打车费 # 停用费用类型 (软删除,用户端隐藏)
|
||||
hose-use feetype enable 市内打车费 # 重新启用费用类型 (支持 --recursive 级联启用)
|
||||
|
||||
# 5. 调整层级结构
|
||||
hose-use feetype move 市内打车费 --parent="差旅费用" # 移动至差旅费用之下
|
||||
hose-use feetype move 市内打车费 --parent=root # 移至企业顶级根节点
|
||||
```
|
||||
@@ -1,28 +1,78 @@
|
||||
# 工作流与自建应用指南 (Workflow & Platform Guide)
|
||||
# 应用管理、自建应用与工作流指南 (App, Platform & Workflow Guide)
|
||||
|
||||
本参考专卷详细说明合思自建应用(EASO 开放平台)的工作流跨域扫描、任务节点聚合检索与自动化开通。
|
||||
本参考专卷详细说明合思桌面端【应用管理】、企业后台【自建应用】(DataLink 数据建模与底层记录)以及任务节点工作流(Workflow)的查询与使用。
|
||||
|
||||
> **核心概念辨析(严禁混淆)**:
|
||||
> - **【应用管理】(唯一命令:`hose-use app`)**:对应合思桌面端顶层一级导航【应用管理】。聚合了企业为员工开通的**全部前台业务落地应用**,既包括用车补贴、用车制度、E商卡等官方套件与制度,也包括新转转集团、差旅申请等挂载了视图的自建应用前台入口。
|
||||
> - **【自建应用】(唯一命令:`hose-use platform` / `datalink`)**:对应企业后台【应用中心 -> 自建应用】(开放平台/PaaS)。负责业务对象建模(entities)、字段定义(schema)、权限快照与底层业务记录(records)。**切勿将自建应用称为“应用管理”**。
|
||||
> - **【工作流】(唯一命令:`hose-use workflow`)**:自建应用下的任务流水线、拓扑节点(如自定义 JS 脚本 `code-js2`、Webhook 通知等)。
|
||||
|
||||
---
|
||||
|
||||
## 1. 自建应用管理 (`platform`)
|
||||
## 1. 应用管理 (`app`)
|
||||
|
||||
合思企业支持创建多个自建应用,每个应用承载独立的业务流程与工作流。
|
||||
查看员工工作台开通的业务应用列表与详情:
|
||||
|
||||
```bash
|
||||
# 列出当前企业下全部已开通的自建应用
|
||||
hose-use platform list
|
||||
hose-use platform list --json
|
||||
```
|
||||
# 列出工作台开通的全部业务应用(用车、制度、模板、自建前台等)
|
||||
hose-use app list
|
||||
hose-use app list --keyword="差旅"
|
||||
hose-use app list --json
|
||||
|
||||
**输出关键字段**:
|
||||
- `appId`:应用全局唯一标识
|
||||
- `appName`:应用中文名称
|
||||
- `status`:应用运行状态(ENABLE / DISABLE)
|
||||
- `createdAt` / `updatedAt`:创建与最后更新时间
|
||||
# 查看某个应用的详情与配置
|
||||
hose-use app get 用车补贴
|
||||
hose-use app get ID01RKbEvQsWbd
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. 跨应用工作流聚合检索 (`workflow list`)
|
||||
## 2. 自建应用与数据模型 (`platform` / `datalink`)
|
||||
|
||||
合思企业支持创建多个自建应用,每个自建应用可承载多个业务对象、字段模型与业务数据记录:
|
||||
|
||||
```bash
|
||||
# 列出当前企业下全部已开通的自建应用平台
|
||||
hose-use platform list
|
||||
hose-use platform list --json
|
||||
|
||||
# 查看指定自建应用包含的业务对象清单
|
||||
hose-use platform entities 新转转集团
|
||||
|
||||
# 查看业务对象的完整字段定义(schema)
|
||||
hose-use platform schema 新转转集团 合同
|
||||
hose-use platform schema 新转转集团 合同 --keyword="金额"
|
||||
|
||||
# 检索业务对象的底层真实数据记录
|
||||
hose-use platform records 新转转集团 合同 --limit=5
|
||||
hose-use platform records 新转转集团 合同 --keyword="技术服务" --fields "合同编号,金额,经办人" --json
|
||||
```
|
||||
|
||||
### 2.1 业务对象记录操作 (`platform record`)
|
||||
|
||||
支持对业务对象单条记录进行精准详情查看、停用/启用状态翻转、表单字段更新以及台账重新计算:
|
||||
|
||||
```bash
|
||||
# 1. 查看单条记录详情 (包含基本信息、实体字段、关联台账与可见范围)
|
||||
hose-use platform record get 新转转集团 合同 ID01TqE4yUG6hF
|
||||
hose-use platform record get 新转转集团 合同 ID01TqE4yUG6hF --json
|
||||
|
||||
# 2. 切换记录停用/启用状态 (默认自动翻转,支持 --state 显式指定)
|
||||
hose-use platform record toggle 新转转集团 合同 ID01TqE4yUG6hF
|
||||
hose-use platform record toggle 新转转集团 合同 ID01TqE4yUG6hF --state=false # 停用
|
||||
hose-use platform record toggle 新转转集团 合同 ID01TqE4yUG6hF --state=true # 启用
|
||||
|
||||
# 3. 编辑更新记录字段 (传入 JSON 字典或 --data)
|
||||
hose-use platform record edit 新转转集团 合同 ID01TqE4yUG6hF --data='{"name":"新名称","项目内容":"技术支持"}'
|
||||
hose-use platform record edit 新转转集团 合同 ID01TqE4yUG6hF '{"name":"新名称"}'
|
||||
|
||||
# 4. 重新计算记录关联的全部台账
|
||||
hose-use platform record recompute 新转转集团 合同 ID01TqE4yUG6hF
|
||||
```
|
||||
|
||||
|
||||
---
|
||||
|
||||
## 3. 跨应用工作流聚合检索 (`workflow list`)
|
||||
|
||||
合思官方后台一次只能查看单个自建应用的工作流。`hose-use` 实现了跨应用并发聚合扫描:
|
||||
|
||||
@@ -36,7 +86,7 @@ hose-use workflow list --app-id=app_01j72x...
|
||||
|
||||
---
|
||||
|
||||
## 3. 工作流任务节点精准扫描 (`workflow find`)
|
||||
## 4. 工作流任务节点精准扫描 (`workflow find`)
|
||||
|
||||
用于快速定位企业中部署了特定逻辑节点(如自定义 JS 脚本、飞书推送、钉钉同步等)的工作流:
|
||||
|
||||
@@ -53,7 +103,7 @@ hose-use workflow find --keyword="自动审批"
|
||||
|
||||
---
|
||||
|
||||
## 4. 工作流详情查询 (`workflow get`)
|
||||
## 5. 工作流详情查询 (`workflow get`)
|
||||
|
||||
获取工作流的完整节点拓扑、参数配置与表达式定义:
|
||||
|
||||
@@ -64,7 +114,7 @@ hose-use workflow get wf_01k83y... --json -o /tmp/workflow_detail.json
|
||||
|
||||
---
|
||||
|
||||
## 5. 工作流启用与关闭 (`workflow toggle`)
|
||||
## 6. 工作流启用与关闭 (`workflow toggle`)
|
||||
|
||||
```bash
|
||||
# 激活/启用指定工作流
|
||||
@@ -74,10 +124,71 @@ hose-use workflow toggle wf_01k83y... --enable
|
||||
hose-use workflow toggle wf_01k83y... --disable
|
||||
```
|
||||
|
||||
## 6. 工作流静态分析 (`workflow analyze`)
|
||||
## 7. 工作流静态分析 (`workflow analyze`)
|
||||
|
||||
从应用中心的具体自建应用进入工作流详情后,CLI 可以读取同一份详情并生成递归节点树、代码表达式引用依赖和明显配置诊断;该命令只读,不执行工作流:
|
||||
|
||||
```bash
|
||||
hose-use workflow analyze wf_01k83y... --json
|
||||
```
|
||||
|
||||
## 8. 工作流草稿保存 (`workflow save`)
|
||||
|
||||
Web 端“保存更新”是对完整 pipeline 的 PUT,而不是单节点 PATCH。推荐先导出详情,再修改 JSON,最后按版本保护保存:
|
||||
|
||||
```bash
|
||||
hose-use workflow get <pipelineId> --json -o workflow.json
|
||||
# 修改 workflow.json 中的 tasks / inputs / $snapshot 等字段
|
||||
hose-use workflow save <pipelineId> --file=workflow.json
|
||||
```
|
||||
|
||||
命令会先重新读取远端版本;若 `version` 或 `tasksVersion` 已变化会拒绝覆盖。确认需要强制覆盖时显式使用 `--force-write`。
|
||||
|
||||
## 9. 本地节点草稿修改 (`workflow patch`)
|
||||
|
||||
网页编辑器最终提交的是完整 pipeline,因此节点修改先在完整 JSON 草稿上完成,再交给 `workflow save` 做版本保护和服务端持久化:
|
||||
|
||||
```bash
|
||||
hose-use workflow patch <pipelineId> \\
|
||||
--file=workflow.json \\
|
||||
--path=tasks.1.form.title \\
|
||||
--value="新的标题" \\
|
||||
--output=workflow.patched.json
|
||||
```
|
||||
|
||||
数组也可以使用 `tasks[1].form.title`。需要写入数字、布尔值或对象时加 `--value-json`;使用 `--in-place` 才会覆盖输入文件。该命令只修改本地草稿,不直接触发远端写入。
|
||||
|
||||
## 10. 工作流版本历史 (`workflow history`)
|
||||
|
||||
服务端每次完整保存都会生成一个版本快照,可用以下命令读取审计历史:
|
||||
|
||||
```bash
|
||||
hose-use workflow history <pipelineId> --json
|
||||
```
|
||||
|
||||
## 11. 运行日志与错误管道提醒
|
||||
|
||||
查询单个工作流的运行日志:
|
||||
|
||||
```bash
|
||||
hose-use workflow logs <pipelineId> --state=FAILED --json
|
||||
```
|
||||
|
||||
扫描企业内工作流列表中的 `errorCount`,并把已提醒的错误计数保存在本地状态文件;同一错误计数不会重复提醒,错误计数增加时才产生新提醒:
|
||||
|
||||
```bash
|
||||
hose-use workflow check --json
|
||||
hose-use workflow check --json --fail-on-alert
|
||||
```
|
||||
|
||||
默认状态文件为 `~/.config/hose-use/workflow-alerts-<corp>.json`,可用 `--state-file` 指定。`--fail-on-alert` 适合被常驻服务或外部调度器检测;它只改变退出码,不自动向外部人员发送消息。
|
||||
|
||||
## 12. 发布工作流 (`workflow publish`)
|
||||
|
||||
网页端发布动作对应 Piper 的状态接口:`PUT /api/easo/pipelines/state/{pipelineId}?state=1`。CLI 提供同等入口:
|
||||
|
||||
```bash
|
||||
hose-use workflow publish <pipelineId>
|
||||
```
|
||||
|
||||
建议先执行 `workflow save`,确认保存成功后再执行 `workflow publish`;发布只切换启用状态,不替代完整配置保存。
|
||||
@@ -112,4 +112,40 @@ describe("CLI - hose-aipro 审批流与网关阻拦全链路测试", () => {
|
||||
expect(actions).toContain("review");
|
||||
expect(actions).toContain("decide");
|
||||
});
|
||||
|
||||
test("门禁防御:单据无硬性或弹性违规时,尝试执行 reject 必须被网关阻断(禁止无因驳回)", async () => {
|
||||
const db = getApprovalDatabase(":memory:");
|
||||
const repo = new ApprovalRepository(db);
|
||||
|
||||
const run = repo.createApprovalRun({
|
||||
documentSn: "CLEAN-BILL-001",
|
||||
corpId: "test-corp",
|
||||
documentSnapshot: "# 正常单据快照",
|
||||
});
|
||||
const runId = run.shortId!;
|
||||
|
||||
// 挂载规则 1 并打标为全部 PASS
|
||||
await runAiProCli(["bind", "--run", runId, "--rules", "[1]"]);
|
||||
await runAiProCli([
|
||||
"review",
|
||||
"--run",
|
||||
runId,
|
||||
"--eval",
|
||||
"1=PASS:发票已上传; 2=PASS:事由已补充",
|
||||
]);
|
||||
|
||||
// 尝试在无违规情况下驳回,必须被网关拦截
|
||||
const blockReject = await runAiProCli([
|
||||
"decide",
|
||||
"reject",
|
||||
"--run",
|
||||
runId,
|
||||
"--opinion",
|
||||
"单据完全合规但尝试无故驳回",
|
||||
]);
|
||||
|
||||
expect(blockReject.exitCode).toBe(1);
|
||||
expect(blockReject.stderr).toContain("不存在任何【硬性】或【弹性】违规条款");
|
||||
expect(blockReject.stderr).toContain("严禁无故或恶意驳回");
|
||||
});
|
||||
});
|
||||
+100
-28
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env bun
|
||||
import { parseArgs, stringOption, booleanOption, numberOption } from "./cli/parser.js";
|
||||
import { printJson, printTable, redactSensitiveText } from "./cli/printer.js";
|
||||
import { printJson, printTable, redactSensitiveText, formatExpiresAt } from "./cli/printer.js";
|
||||
import { initCorpRuntime } from "./cli/helpers.js";
|
||||
import { createEkbClient } from "./core/auth/ekb.js";
|
||||
import {
|
||||
@@ -12,9 +12,10 @@ import {
|
||||
CreateFindingInput,
|
||||
RuleRecord,
|
||||
parseRuleBody,
|
||||
validateGatewayAction,
|
||||
} from "./domains/approval/index.js";
|
||||
import { getRawBillFlow } from "./domains/bill/api.js";
|
||||
import { approveBill, rejectBill } from "./domains/bill/tools.js";
|
||||
import { approveBill, rejectBill, getTranslatorContext } from "./domains/bill/tools.js";
|
||||
import { translateBillFlowToMarkdown } from "./domains/bill/translator.js";
|
||||
import { VERSION } from "./version.js";
|
||||
|
||||
@@ -55,7 +56,7 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string;
|
||||
const targetSn = positional[1] || stringOption(parsed.options, ["code", "sn", "id", "target"]);
|
||||
const args = positional.slice(1);
|
||||
const corpId = corp?.corpId || corp?.id;
|
||||
const operator = corp?.staffId || corp?.name || "AI-Agent";
|
||||
const operator = corp?.credentials?.staffId || corp?.staffId || corp?.name || "AI-Agent";
|
||||
|
||||
const requireCorpId = () => {
|
||||
if (!corpId) {
|
||||
@@ -73,6 +74,81 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string;
|
||||
|
||||
try {
|
||||
switch (command) {
|
||||
// ── 0. 运行时上下文与身份诊断 (status / whoami / context / info) ────────
|
||||
case "status":
|
||||
case "whoami":
|
||||
case "context":
|
||||
case "info": {
|
||||
const scopes = repo.listScopes("active");
|
||||
const rules = repo.listRules();
|
||||
const runs = corpId ? repo.listRuns({ corpId }) : repo.listRuns();
|
||||
const pendingRuns = runs.filter((r) => r.decision === "PENDING");
|
||||
const recentLogs = repo.listAiProLogs(undefined, 5);
|
||||
const isJson = runtime.jsonMode || booleanOption(parsed.options, ["json", "j"]);
|
||||
|
||||
const corpStaffId = corp?.credentials?.staffId || corp?.staffId || "-";
|
||||
const corpStaffName = corp?.staffName || corp?.session?.staffName || null;
|
||||
const corpExpiresAt = corp?.auth?.expiresAt || corp?.session?.expTime;
|
||||
|
||||
if (isJson) {
|
||||
return {
|
||||
stdout: JSON.stringify(
|
||||
{
|
||||
tool: "hose-aipro",
|
||||
version: VERSION,
|
||||
corp: corp
|
||||
? {
|
||||
id: corp.id,
|
||||
name: corp.name,
|
||||
staffId: corpStaffId,
|
||||
userName: corpStaffName,
|
||||
source: corp.source,
|
||||
expiresAt: corpExpiresAt,
|
||||
expired: corpExpiresAt ? corpExpiresAt <= Date.now() : false,
|
||||
baseUrl: corp.baseUrl,
|
||||
}
|
||||
: null,
|
||||
operator,
|
||||
ruleEngine: {
|
||||
scopesCount: scopes.length,
|
||||
rulesCount: rules.length,
|
||||
scopes: scopes.map((s) => ({ index: s.index, scope: s.scope, ruleCount: s.ruleCount })),
|
||||
},
|
||||
sessions: {
|
||||
total: runs.length,
|
||||
pending: pendingRuns.length,
|
||||
},
|
||||
recentLogsCount: recentLogs.length,
|
||||
},
|
||||
null,
|
||||
2
|
||||
) + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const lines = [
|
||||
`====== 合思 AI PRO 确定性审批网关运行上下文 (v${VERSION}) ======`,
|
||||
` 当前连接企业 : ${corp ? `${corp.name} (${corp.id})` : "⚠️ 未指定企业"}`,
|
||||
` 当前操作工号 : ${corpStaffId}`,
|
||||
` 操作员标识 : ${operator}`,
|
||||
` 凭证有效状态 : ${corp ? formatExpiresAt(corpExpiresAt) : "-"}`,
|
||||
` 主站 BaseURL : ${corp?.baseUrl || "-"}`,
|
||||
` 规约场景库 : 已加载 ${scopes.length} 个场景 (${scopes.map((s) => `#${s.index} ${s.scope}`).join(", ") || "无"}),共 ${rules.length} 条仲裁规则`,
|
||||
` 未结审批会话 : ${pendingRuns.length} 个待决断会话 (当前企业历史总会话: ${runs.length} 个)`,
|
||||
"",
|
||||
"提示:",
|
||||
" - 查看规约场景列表: hose-aipro scopes",
|
||||
" - 切换全局工作企业: hose-use corps switch <企业ID>",
|
||||
" - 临时指定执行企业: hose-aipro --corp=<企业ID> <子命令>",
|
||||
" - 单据审批全流程 : hose-aipro bind <单号> <索引号> -> hose-aipro review -> hose-aipro decide",
|
||||
"",
|
||||
];
|
||||
|
||||
return { stdout: lines.join("\n"), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
// ── 1. 初始化审批实例会话(签发 6 位短 ID,有效期 6 小时)──────────────
|
||||
case "init":
|
||||
case "start": {
|
||||
@@ -88,7 +164,8 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string;
|
||||
const flowIdObj = (raw.flowId && typeof raw.flowId === "object" ? raw.flowId : raw) as Record<string, any>;
|
||||
const form = (flowIdObj.form && typeof flowIdObj.form === "object" ? flowIdObj.form : {}) as Record<string, any>;
|
||||
const title = form.title || flowIdObj.title || "<无标题>";
|
||||
const snapshot = translateBillFlowToMarkdown(raw);
|
||||
const translatorContext = await getTranslatorContext(context.client, context.corpId, raw).catch(() => undefined);
|
||||
const snapshot = translateBillFlowToMarkdown(raw, translatorContext);
|
||||
|
||||
// 创建全新独立运行实例 (永久长 ID + 6 位短 ID, 6 小时有效期)
|
||||
const run = repo.createApprovalRun({
|
||||
@@ -222,7 +299,8 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string;
|
||||
if (!raw) {
|
||||
throw new Error(`在当前企业下未找到单号或 ID 为 [${targetSn}] 的单据`);
|
||||
}
|
||||
const markdown = translateBillFlowToMarkdown(raw);
|
||||
const translatorContext = await getTranslatorContext(context.client, context.corpId, raw).catch(() => undefined);
|
||||
const markdown = translateBillFlowToMarkdown(raw, translatorContext);
|
||||
|
||||
repo.logAiProAction({
|
||||
action: "translate",
|
||||
@@ -878,31 +956,15 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string;
|
||||
throw new Error("必须提供小于 150 字的审批意见: --opinion '<审批意见>'");
|
||||
}
|
||||
|
||||
if (opinion.length > 150) {
|
||||
throw new Error(`[参数校验阻断] 审批意见不可超过 150 字符,当前长度为 ${opinion.length} 字符,请精简。`);
|
||||
}
|
||||
|
||||
const findings = repo.getFindingsByRunId(runRecord.id);
|
||||
if (findings.length === 0) {
|
||||
throw new Error(`[网关安全阻断] 会话 [${runRecord.shortId || runRecord.id}] 尚未挂载任何规约审核要点,审批链路物理不通!请先执行 bind 挂载。`);
|
||||
}
|
||||
|
||||
// 网关刚性阻拦检查(它只阻拦,不决断)
|
||||
if (action === "APPROVE") {
|
||||
// 门禁 1: 漏检拦截
|
||||
const pendingFindings = findings.filter((f) => f.checkStatus === "PENDING");
|
||||
if (pendingFindings.length > 0) {
|
||||
const pendingIndices = pendingFindings.map((f) => `#${findings.indexOf(f) + 1}`).join(", ");
|
||||
throw new Error(`[网关安全阻断] 尚有 ${pendingFindings.length} 处审核要点处于“待核验”状态(要点 ${pendingIndices}),禁止盲目放行同意!`);
|
||||
}
|
||||
|
||||
// 门禁 2: 硬性一票否决
|
||||
const hardFailed = findings.filter((f) => f.checkStatus === "FAIL" && f.strictness === "硬性");
|
||||
if (hardFailed.length > 0) {
|
||||
const failedNames = hardFailed.map((f) => `【#${findings.indexOf(f) + 1} ${f.clauseText}】`).join("、");
|
||||
throw new Error(`[网关安全阻断] 单据存在硬性违规条款未通过(${failedNames}),物理切断“同意”流转,绝对禁止放行!`);
|
||||
}
|
||||
}
|
||||
// 网关刚性安全门禁检查(统一由可配置网关 TS 策略执行:意见长度、待核验漏检、硬性违规禁止同意、无硬性/弹性违规禁止驳回)
|
||||
validateGatewayAction({
|
||||
documentSn: runRecord.documentSn,
|
||||
findings,
|
||||
requestedAction: action === "APPROVE" ? "approve" : "reject",
|
||||
opinion,
|
||||
});
|
||||
|
||||
// Apply execution
|
||||
const apply = booleanOption(parsed.options, ["apply", "execute", "run", "do"]);
|
||||
@@ -1036,11 +1098,21 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string;
|
||||
// ── 7. 帮助 ───────────────────────────────────────────────────────────
|
||||
case "help":
|
||||
default: {
|
||||
const corpExpiresAt = corp?.auth?.expiresAt || corp?.session?.expTime;
|
||||
const corpBanner = corp
|
||||
? `[当前连接企业: ${corp.name} (${corp.id}) | 操作人: ${operator} | 凭证状态: ${formatExpiresAt(corpExpiresAt)}]\n[全局切换: hose-use corps switch <企业ID> | 临时指定: hose-aipro --corp=<企业ID>]`
|
||||
: `[当前企业: 未指定 | 请先运行 hose-use auth login 或带上 --corp=<企业ID>]`;
|
||||
|
||||
const helpText = `
|
||||
合思 AI PRO 确定性审批仲裁网关 CLI (hose-aipro) v${VERSION}
|
||||
一切操作在本地 SQLite 强受控、全流程监控、不可篡改审计留痕。
|
||||
|
||||
${corpBanner}
|
||||
|
||||
核心工作流:
|
||||
0. 查看 AI PRO 运行上下文与当前绑定企业:
|
||||
hose-aipro status # 查看当前企业、操作人、规则库统计与待办会话
|
||||
|
||||
1. 查看规约场景索引库 (获取规则索引号):
|
||||
hose-aipro scopes # 列出所有场景索引 (Index / Scope / 规则数)
|
||||
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
import { describe, it, expect, spyOn } from "bun:test";
|
||||
import { handleAppCommand } from "./app.js";
|
||||
import * as menuTools from "../../domains/menu/tools.js";
|
||||
import type { CliRuntime } from "../types.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
|
||||
describe("cli/commands/app > handleAppCommand", () => {
|
||||
const dummyRuntimeNoCorp: CliRuntime = {
|
||||
corpContext: {
|
||||
listCorps: () => [],
|
||||
getCurrent: () => null,
|
||||
switchCorp: () => false,
|
||||
resolve: () => null,
|
||||
} as any,
|
||||
selectedCorp: null,
|
||||
jsonMode: false,
|
||||
};
|
||||
|
||||
const mockCorp: CorpConfig = {
|
||||
id: "corp123",
|
||||
name: "转转二手交易网",
|
||||
source: "account",
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
credentials: {
|
||||
accessToken: "mock-token",
|
||||
corpId: "corp123",
|
||||
staffId: "mock-staff",
|
||||
},
|
||||
};
|
||||
|
||||
const dummyRuntimeWithCorp: CliRuntime = {
|
||||
corpContext: {
|
||||
listCorps: () => [mockCorp],
|
||||
getCurrent: () => mockCorp,
|
||||
switchCorp: () => true,
|
||||
resolve: () => mockCorp,
|
||||
} as any,
|
||||
selectedCorp: mockCorp,
|
||||
jsonMode: false,
|
||||
};
|
||||
|
||||
it("fails with exitCode 1 when no corp is selected", async () => {
|
||||
const res = await handleAppCommand(
|
||||
{
|
||||
area: "app",
|
||||
action: "list",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["app", "list"],
|
||||
},
|
||||
dummyRuntimeNoCorp
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(1);
|
||||
expect(res.stderr).toContain("未选中企业");
|
||||
});
|
||||
|
||||
it("lists workbench apps in table format", async () => {
|
||||
const mockApps = [
|
||||
{
|
||||
id: "SCGY:corp123",
|
||||
name: "用车补贴",
|
||||
code: "dataLinkItem",
|
||||
href: "/third-party-item/SCGY:corp123",
|
||||
type: "MENU",
|
||||
},
|
||||
{
|
||||
id: "ID01PIqCA1Di0v",
|
||||
name: "用车制度",
|
||||
code: "dataLinkItem",
|
||||
href: "/third-party-item/ID01PIqCA1Di0v",
|
||||
type: "REGULATION",
|
||||
},
|
||||
];
|
||||
|
||||
const spy = spyOn(menuTools, "fetchWorkbenchAppsList").mockResolvedValue(mockApps as any);
|
||||
|
||||
const res = await handleAppCommand(
|
||||
{
|
||||
area: "app",
|
||||
action: "list",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["app", "list"],
|
||||
},
|
||||
dummyRuntimeWithCorp
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("工作台应用管理列表");
|
||||
expect(res.stdout).toContain("用车补贴");
|
||||
expect(res.stdout).toContain("用车制度");
|
||||
expect(res.stdout).toContain("用车/商旅套件");
|
||||
expect(res.stdout).toContain("制度与规约");
|
||||
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it("filters workbench apps with --keyword", async () => {
|
||||
const mockApps = [
|
||||
{
|
||||
id: "SCGY:corp123",
|
||||
name: "用车补贴",
|
||||
code: "dataLinkItem",
|
||||
href: "/third-party-item/SCGY:corp123",
|
||||
},
|
||||
{
|
||||
id: "ID01PIqCA1Di0v",
|
||||
name: "差旅申请",
|
||||
code: "dataLinkItem",
|
||||
href: "/third-party-item/ID01PIqCA1Di0v",
|
||||
},
|
||||
];
|
||||
|
||||
const spy = spyOn(menuTools, "fetchWorkbenchAppsList").mockResolvedValue(mockApps as any);
|
||||
|
||||
const res = await handleAppCommand(
|
||||
{
|
||||
area: "app",
|
||||
action: "list",
|
||||
args: [],
|
||||
options: { keyword: "补贴" },
|
||||
raw: ["app", "list", "--keyword", "补贴"],
|
||||
},
|
||||
dummyRuntimeWithCorp
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("用车补贴");
|
||||
expect(res.stdout).not.toContain("差旅申请");
|
||||
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it("supports --json output for app list", async () => {
|
||||
const mockApps = [
|
||||
{
|
||||
id: "SCGY:corp123",
|
||||
name: "用车补贴",
|
||||
code: "dataLinkItem",
|
||||
href: "/third-party-item/SCGY:corp123",
|
||||
},
|
||||
];
|
||||
|
||||
const spy = spyOn(menuTools, "fetchWorkbenchAppsList").mockResolvedValue(mockApps as any);
|
||||
|
||||
const jsonRuntime = { ...dummyRuntimeWithCorp, jsonMode: true };
|
||||
const res = await handleAppCommand(
|
||||
{
|
||||
area: "app",
|
||||
action: "list",
|
||||
args: [],
|
||||
options: { json: true },
|
||||
raw: ["app", "list", "--json"],
|
||||
},
|
||||
jsonRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
const parsed = JSON.parse(res.stdout);
|
||||
expect(parsed.total).toBe(1);
|
||||
expect(parsed.apps[0].id).toBe("SCGY:corp123");
|
||||
expect(parsed.apps[0].name).toBe("用车补贴");
|
||||
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it("returns error for unknown subcommand", async () => {
|
||||
const res = await handleAppCommand(
|
||||
{
|
||||
area: "app",
|
||||
action: "unknownAction",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["app", "unknownAction"],
|
||||
},
|
||||
dummyRuntimeWithCorp
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(1);
|
||||
expect(res.stderr).toContain("未知 app 子命令");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,149 @@
|
||||
import { fetchWorkbenchAppsList } from "../../domains/menu/tools.js";
|
||||
import { getPlatform } from "../../domains/datalink/api.js";
|
||||
import { createClientsForCorp } from "../helpers.js";
|
||||
import { stringOption, booleanOption } from "../parser.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
|
||||
function inferCategory(app: { id: string; name: string; type?: string | null }): string {
|
||||
if (app.id.startsWith("SCGY:") || app.type === "PRIVATE_CAR") return "用车/商旅套件";
|
||||
if (app.type === "REGULATION") return "制度与规约";
|
||||
if (app.type === "VCM") return "商旅卡与金融";
|
||||
if (app.name.includes("[模板]") || app.name.includes("模板")) return "预置模板";
|
||||
return "自建业务应用";
|
||||
}
|
||||
|
||||
export async function handleAppCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
if (!runtime.selectedCorp) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const action = parsed.action || "list";
|
||||
|
||||
switch (action) {
|
||||
case "list":
|
||||
case "ls":
|
||||
case "apps":
|
||||
case "workbench": {
|
||||
const keyword = stringOption(parsed.options, ["keyword", "k", "q", "query"])?.toLowerCase();
|
||||
const apps = await fetchWorkbenchAppsList(runtime.selectedCorp);
|
||||
|
||||
const filtered = keyword
|
||||
? apps.filter((app) =>
|
||||
[app.id, app.name, app.code, app.href]
|
||||
.filter((val): val is string => Boolean(val))
|
||||
.some((val) => val.toLowerCase().includes(keyword))
|
||||
)
|
||||
: apps;
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId: runtime.selectedCorp.credentials.corpId,
|
||||
corpName: runtime.selectedCorp.name,
|
||||
total: apps.length,
|
||||
count: filtered.length,
|
||||
keyword: keyword ?? null,
|
||||
apps: filtered,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (filtered.length === 0) {
|
||||
const msg = keyword
|
||||
? `企业 [${runtime.selectedCorp.name}] 下未找到匹配 "${keyword}" 的工作台应用\n`
|
||||
: `企业 [${runtime.selectedCorp.name}] 下暂无工作台应用配置\n`;
|
||||
return { stdout: msg, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const headers = ["#", "应用 ID", "应用名称", "应用分类", "功能代码", "Web 直达路由"];
|
||||
const rows = filtered.map((app, i) => [
|
||||
i + 1,
|
||||
app.id,
|
||||
app.name,
|
||||
inferCategory(app),
|
||||
app.code || "dataLinkItem",
|
||||
app.href,
|
||||
]);
|
||||
|
||||
const title = `====== [${runtime.selectedCorp.name}] 工作台应用管理列表 (${filtered.length} 个应用) ======\n`;
|
||||
return {
|
||||
stdout: title + printTable(headers, rows) + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
case "get":
|
||||
case "show": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["id", "name", "app"]);
|
||||
if (!target) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "请提供应用 ID 或名称: hose-use app get <应用 ID|名称>\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const apps = await fetchWorkbenchAppsList(runtime.selectedCorp);
|
||||
const matched = apps.find(
|
||||
(a) =>
|
||||
a.id.toLowerCase() === target.toLowerCase() ||
|
||||
a.name.toLowerCase().includes(target.toLowerCase())
|
||||
);
|
||||
|
||||
const appId = matched ? matched.id : target;
|
||||
const appName = matched ? matched.name : target;
|
||||
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp);
|
||||
const corpId = runtime.selectedCorp.credentials.corpId;
|
||||
|
||||
try {
|
||||
const detail = await getPlatform(clients.ekbClient, corpId, appId);
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(detail, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const infoRows = [
|
||||
["应用 ID", detail.id],
|
||||
["应用名称", detail.name],
|
||||
["应用分类", inferCategory(detail)],
|
||||
["启用状态", detail.active ? "🟢 已启用" : "⚪ 未启用"],
|
||||
["Web 路由", matched?.href || `/third-party-item/${detail.id}`],
|
||||
["管理员数", detail.adminIds.length],
|
||||
["可见人员数", detail.staffIds.length],
|
||||
["可见角色数", detail.roleIds.length],
|
||||
["可见部门数", detail.departmentIds.length],
|
||||
];
|
||||
|
||||
const text = `====== 工作台应用详情: ${appName} ======\n${printTable(["属性", "信息"], infoRows)}\n`;
|
||||
return { stdout: text, stderr: "", exitCode: 0 };
|
||||
} catch (err) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `获取应用详情失败: ${err instanceof Error ? err.message : String(err)}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 app 子命令: ${action}。支持: list, get\n用法: hose-use app list [--keyword <关键词>]\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { describe, it, expect } from "bun:test";
|
||||
import { handleAuthCommand } from "./auth.js";
|
||||
import type { CliRuntime } from "../types.js";
|
||||
|
||||
describe("cli/commands/auth > aliases and subcommands", () => {
|
||||
const dummyRuntime: CliRuntime = {
|
||||
corpContext: {
|
||||
listCorps: () => [],
|
||||
getCurrent: () => null,
|
||||
switchCorp: () => false,
|
||||
resolve: () => null,
|
||||
} as any,
|
||||
selectedCorp: null,
|
||||
jsonMode: false,
|
||||
};
|
||||
|
||||
it("maps auth list to handleAccounts smoothly", async () => {
|
||||
const res = await handleAuthCommand(
|
||||
{
|
||||
area: "auth",
|
||||
action: "list",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["auth", "list"],
|
||||
},
|
||||
dummyRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
// 应该输出已保存账号表格或无账号提示
|
||||
expect(res.stdout).toMatch(/(已保存账号列表|暂无保存的账号)/);
|
||||
});
|
||||
|
||||
it("supports auth accounts with --json mode", async () => {
|
||||
const jsonRuntime = { ...dummyRuntime, jsonMode: true };
|
||||
const res = await handleAuthCommand(
|
||||
{
|
||||
area: "auth",
|
||||
action: "list",
|
||||
args: [],
|
||||
options: { json: true },
|
||||
raw: ["auth", "list", "--json"],
|
||||
},
|
||||
jsonRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
const data = JSON.parse(res.stdout);
|
||||
expect(data).toHaveProperty("accounts");
|
||||
});
|
||||
|
||||
it("handles auth status / current aliases without crash", async () => {
|
||||
const res = await handleAuthCommand(
|
||||
{
|
||||
area: "auth",
|
||||
action: "current",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["auth", "current"],
|
||||
},
|
||||
dummyRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("当前登录与企业状态");
|
||||
});
|
||||
});
|
||||
+82
-42
@@ -5,6 +5,7 @@ import {
|
||||
sendSmsVerificationCode,
|
||||
importCredentials,
|
||||
importF12Credentials,
|
||||
importFromLink,
|
||||
parseHeadersOrCurl,
|
||||
refreshAccountCorporations,
|
||||
} from "../../core/auth/login.js";
|
||||
@@ -30,19 +31,31 @@ export async function handleAuthCommand(
|
||||
return handleLogin(parsed, runtime);
|
||||
case "status":
|
||||
case "whoami":
|
||||
case "current":
|
||||
return handleStatus(parsed, runtime);
|
||||
case "refresh":
|
||||
case "renew":
|
||||
return handleRefresh(parsed, runtime);
|
||||
case "import":
|
||||
case "add":
|
||||
return handleImport(parsed, runtime);
|
||||
case "add-link":
|
||||
case "link":
|
||||
case "import-link":
|
||||
return handleAddLink(parsed, runtime);
|
||||
case "accounts":
|
||||
case "list":
|
||||
case "account":
|
||||
case "accs":
|
||||
return handleAccounts(parsed, runtime);
|
||||
case "switch-account":
|
||||
case "switch":
|
||||
case "use-account":
|
||||
return handleSwitchAccount(parsed, runtime);
|
||||
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 +244,96 @@ 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);
|
||||
const ttl = stringOption(parsed.options, ["ttl"]);
|
||||
const expires = stringOption(parsed.options, ["expires", "days"]);
|
||||
|
||||
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,
|
||||
ttl,
|
||||
expires,
|
||||
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> {
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
searchAndFormatBills,
|
||||
getBillByCodeOrId,
|
||||
getBillFlow,
|
||||
formatBillFlowOperator,
|
||||
getBillRisk,
|
||||
getBillReferences,
|
||||
getBillRelations,
|
||||
@@ -339,7 +340,7 @@ export async function handleBillCommand(
|
||||
entry.time ? new Date(entry.time).toLocaleString("zh-CN") : "-",
|
||||
entry.nodeName || "-",
|
||||
entry.action || "-",
|
||||
entry.operator?.name || (entry.automatic ? "系统" : "-"),
|
||||
formatBillFlowOperator(entry.operator, entry.automatic, entry.operator?.id?.toLowerCase().includes("ebot")),
|
||||
entry.durationMs !== undefined ? `${Math.round(entry.durationMs / 1000)} 秒` : "-",
|
||||
entry.skipped ? "自动跳过" : entry.automatic ? "自动" : "",
|
||||
entry.comment || "-",
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import { describe, it, expect } from "bun:test";
|
||||
import { handleConfigCommand } from "./config.js";
|
||||
import type { CliRuntime } from "../types.js";
|
||||
|
||||
describe("cli/commands/config > aliases and path mapping", () => {
|
||||
const dummyRuntime: CliRuntime = {
|
||||
corpContext: {
|
||||
listCorps: () => [],
|
||||
getCurrent: () => null,
|
||||
switchCorp: () => false,
|
||||
resolve: () => null,
|
||||
} as any,
|
||||
selectedCorp: null,
|
||||
jsonMode: false,
|
||||
};
|
||||
|
||||
it("maps config show to config paths diagnosis", async () => {
|
||||
const res = await handleConfigCommand(
|
||||
{
|
||||
area: "config",
|
||||
action: "show",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["config", "show"],
|
||||
},
|
||||
dummyRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("配置路径诊断 (Config Paths)");
|
||||
expect(res.stdout).toContain("当前生效配置文件");
|
||||
expect(res.stdout).toContain("运行模式 (Mode)");
|
||||
});
|
||||
|
||||
it("supports config paths directly", async () => {
|
||||
const res = await handleConfigCommand(
|
||||
{
|
||||
area: "config",
|
||||
action: "paths",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["config", "paths"],
|
||||
},
|
||||
dummyRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("配置路径诊断 (Config Paths)");
|
||||
});
|
||||
|
||||
it("supports config show --json structured output", async () => {
|
||||
const jsonRuntime = { ...dummyRuntime, jsonMode: true };
|
||||
const res = await handleConfigCommand(
|
||||
{
|
||||
area: "config",
|
||||
action: "show",
|
||||
args: [],
|
||||
options: { json: true },
|
||||
raw: ["config", "show", "--json"],
|
||||
},
|
||||
jsonRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
const data = JSON.parse(res.stdout);
|
||||
expect(data).toHaveProperty("configFile");
|
||||
expect(data).toHaveProperty("writableDir");
|
||||
expect(data).toHaveProperty("mode");
|
||||
});
|
||||
|
||||
it("supports config get for inspecting global stateful configuration", async () => {
|
||||
const res = await handleConfigCommand(
|
||||
{
|
||||
area: "config",
|
||||
action: "get",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["config", "get"],
|
||||
},
|
||||
dummyRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("全局运行配置");
|
||||
expect(res.stdout).toContain("运行模式 (Mode)");
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
import { resolve } from "node:path";
|
||||
import {
|
||||
loadGlobalConfig,
|
||||
saveGlobalConfig,
|
||||
@@ -6,6 +7,7 @@ import {
|
||||
resolveWritableEnterprisesDir,
|
||||
getEnterprisesDirCandidates,
|
||||
} from "../../core/config/loader.js";
|
||||
import { booleanOption } from "../parser.js";
|
||||
import { printJson, printKeyValue } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
|
||||
@@ -13,25 +15,30 @@ export async function handleConfigCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const action = parsed.action || "show";
|
||||
const action = parsed.action || "paths";
|
||||
|
||||
switch (action) {
|
||||
case "show":
|
||||
case "get":
|
||||
case "list":
|
||||
return handleShow(parsed, runtime);
|
||||
case "paths":
|
||||
case "path":
|
||||
case "dirs":
|
||||
case "show":
|
||||
case "list":
|
||||
return handlePaths(parsed, runtime);
|
||||
case "get":
|
||||
case "status":
|
||||
case "info":
|
||||
return handleShow(parsed, runtime);
|
||||
case "mode":
|
||||
return handleMode(parsed, runtime);
|
||||
case "test-dir":
|
||||
case "test-enterprises-dir":
|
||||
return handleTestDir(parsed, runtime);
|
||||
case "set":
|
||||
return handleSet(parsed, runtime);
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 config 子命令: ${action}。支持: show, paths, mode <stateful|stateless>, set <key> <val>\n`,
|
||||
stderr: `未知 config 子命令: ${action}。支持: paths, show, get, mode <stateful|stateless>, test-dir <path|--clear>, set <key> <val>\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
@@ -47,6 +54,7 @@ async function handleShow(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
|
||||
stateful: globalConfig.stateful,
|
||||
defaultCorpId: globalConfig.defaultCorpId || null,
|
||||
defaultAccountId: globalConfig.defaultAccountId || null,
|
||||
testEnterprisesDir: globalConfig.testEnterprisesDir || null,
|
||||
activeCorp: currentCorp ? { id: currentCorp.id, name: currentCorp.name } : null,
|
||||
updateRepo: globalConfig.updateRepo || null,
|
||||
updateSource: globalConfig.updateSource || "auto",
|
||||
@@ -61,13 +69,14 @@ async function handleShow(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
|
||||
"运行模式 (Mode)": globalConfig.stateful ? "有状态模式 (Stateful - 自动记忆默认企业)" : "无状态模式 (Stateless - 每次需显式传 --corp)",
|
||||
"默认工作企业": globalConfig.defaultCorpId || "未设置 (使用首个可用企业)",
|
||||
"当前解析企业": currentCorp ? `${currentCorp.name} (${currentCorp.id})` : "无",
|
||||
"测试企业目录": globalConfig.testEnterprisesDir || "未配置 (仅读全局用户企业)",
|
||||
"默认自更新仓库": globalConfig.updateRepo || "官方默认 (yunyingk/hose-use)",
|
||||
"自更新源偏好": globalConfig.updateSource || "auto (自动择优)",
|
||||
"配置文件路径": configPath,
|
||||
});
|
||||
|
||||
return {
|
||||
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`,
|
||||
stdout: `====== 全局运行配置 ======\n${output}\n\n提示:\n 切换模式: hose-use config mode <stateful|stateless>\n 指定企业: hose-use corps switch <corpId>\n 配置测试目录: hose-use config test-dir <dir> (或 --clear)\n 更新源设置: hose-use config set updateSource <auto|github|gitea>\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
@@ -98,6 +107,54 @@ async function handleMode(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
|
||||
};
|
||||
}
|
||||
|
||||
async function handleTestDir(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const isClear = booleanOption(parsed.options, ["clear"]) || parsed.args[0] === "--clear" || parsed.args[0] === "clear";
|
||||
const globalConfig = loadGlobalConfig();
|
||||
|
||||
if (isClear) {
|
||||
const updated = saveGlobalConfig({ testEnterprisesDir: undefined });
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(updated), stderr: "", exitCode: 0 };
|
||||
}
|
||||
return {
|
||||
stdout: "[SUCCESS] 已清除测试企业目录配置,恢复默认全局目录。\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const dirArg = parsed.args[0];
|
||||
if (!dirArg) {
|
||||
const info = {
|
||||
testEnterprisesDir: globalConfig.testEnterprisesDir || null,
|
||||
configFile: resolveGlobalConfigFile(),
|
||||
};
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(info), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const output = printKeyValue({
|
||||
"当前测试企业目录": globalConfig.testEnterprisesDir || "未配置 (当前只读全局企业目录)",
|
||||
"全局配置文件路径": resolveGlobalConfigFile(),
|
||||
});
|
||||
return {
|
||||
stdout: `====== 测试企业目录配置 ======\n${output}\n\n提示:\n 设置测试目录: hose-use config test-dir <path>\n 清除测试目录: hose-use config test-dir --clear\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const resolved = resolve(dirArg);
|
||||
const updated = saveGlobalConfig({ testEnterprisesDir: resolved });
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(updated), stderr: "", exitCode: 0 };
|
||||
}
|
||||
return {
|
||||
stdout: `[SUCCESS] 测试企业目录已设置为: ${resolved}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleSet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const rawKey = parsed.args[0];
|
||||
const val = parsed.args[1];
|
||||
@@ -123,6 +180,13 @@ async function handleSet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<Cl
|
||||
} else if (keyLower === "defaultaccountid") {
|
||||
resolvedKey = "defaultAccountId";
|
||||
partial.defaultAccountId = val;
|
||||
} else if (keyLower === "testenterprisesdir" || keyLower === "testdir") {
|
||||
resolvedKey = "testEnterprisesDir";
|
||||
if (val === "clear" || val === "none" || val === "" || val === "null") {
|
||||
partial.testEnterprisesDir = undefined;
|
||||
} else {
|
||||
partial.testEnterprisesDir = resolve(val);
|
||||
}
|
||||
} else if (keyLower === "updaterepo") {
|
||||
resolvedKey = "updateRepo";
|
||||
partial.updateRepo = val;
|
||||
@@ -140,7 +204,7 @@ async function handleSet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<Cl
|
||||
} else {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `不支持配置键: ${rawKey}。支持: stateful, defaultCorpId, defaultAccountId, updateRepo, updateSource\n`,
|
||||
stderr: `不支持配置键: ${rawKey}。支持: stateful, defaultCorpId, defaultAccountId, testEnterprisesDir, updateRepo, updateSource\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
@@ -165,11 +229,17 @@ async function handlePaths(parsed: CliParsedArgs, runtime: CliRuntime): Promise<
|
||||
const writableDir = resolveWritableEnterprisesDir();
|
||||
const configFile = resolveGlobalConfigFile();
|
||||
const candidates = getEnterprisesDirCandidates();
|
||||
const globalConfig = loadGlobalConfig();
|
||||
const currentCorp = runtime.selectedCorp;
|
||||
|
||||
const data = {
|
||||
configFile,
|
||||
writableDir,
|
||||
existingDirs,
|
||||
mode: globalConfig.stateful ? "stateful" : "stateless",
|
||||
stateful: globalConfig.stateful,
|
||||
defaultCorpId: globalConfig.defaultCorpId || null,
|
||||
activeCorp: currentCorp ? { id: currentCorp.id, name: currentCorp.name } : null,
|
||||
env: {
|
||||
HOSE_ENTERPRISES_DIR: envDir || null,
|
||||
HOSE_USER_ENTERPRISES_DIR: envUserDir || null,
|
||||
@@ -179,13 +249,16 @@ async function handlePaths(parsed: CliParsedArgs, runtime: CliRuntime): Promise<
|
||||
};
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(data), stderr: "", exitCode: 0 };
|
||||
return { stdout: printJson(data, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const output = printKeyValue({
|
||||
"当前生效配置文件": configFile,
|
||||
"凭证保存写入目录": writableDir,
|
||||
"已发现企业目录": existingDirs.length ? existingDirs.join("\n ") : "无 (未发现任何有效企业目录)",
|
||||
"运行模式 (Mode)": globalConfig.stateful ? "有状态模式 (Stateful - 自动记忆默认企业)" : "无状态模式 (Stateless - 每次需显式传 --corp)",
|
||||
"默认工作企业": globalConfig.defaultCorpId || "未设置 (使用首个可用企业)",
|
||||
"当前解析企业": currentCorp ? `${currentCorp.name} (${currentCorp.id})` : "无",
|
||||
"环境变量指定目录": envDir || "未设置 (HOSE_ENTERPRISES_DIR)",
|
||||
"全部目录候选链": candidates.join("\n "),
|
||||
});
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { runCli } from "../runner.js";
|
||||
import { runAiProCli } from "../../aipro-cli.js";
|
||||
import { closeApprovalDatabase, getApprovalDatabase } from "../../domains/approval/db.js";
|
||||
import { ApprovalRepository } from "../../domains/approval/repository.js";
|
||||
|
||||
describe("CLI - 上下文自省与 AI PRO 状态命令 (Zero-Source-Reading Context)", () => {
|
||||
beforeEach(() => {
|
||||
process.env.HOSE_APPROVAL_DB = ":memory:";
|
||||
const db = getApprovalDatabase(":memory:");
|
||||
const repo = new ApprovalRepository(db);
|
||||
|
||||
repo.createRule({
|
||||
scope: "差旅报销",
|
||||
body: "差旅报销时,[必须上传发票]{硬性}。",
|
||||
});
|
||||
repo.createRule({
|
||||
scope: "业务招待",
|
||||
body: "招待报销时,[必须提供餐饮点餐水单]{硬性}。",
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
closeApprovalDatabase();
|
||||
delete process.env.HOSE_APPROVAL_DB;
|
||||
});
|
||||
|
||||
test("hose-use context 打印文本格式仪表盘", async () => {
|
||||
const res = await runCli(["context"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("全局运行上下文与身份诊断");
|
||||
expect(res.stdout).toContain("AI PRO 规约库");
|
||||
expect(res.stdout).toContain("差旅报销");
|
||||
expect(res.stdout).toContain("业务招待");
|
||||
});
|
||||
|
||||
test("hose-use context --json 输出完备的结构化数据", async () => {
|
||||
const res = await runCli(["context", "--json"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
|
||||
const data = JSON.parse(res.stdout);
|
||||
expect(data.tool).toBe("hose-use");
|
||||
expect(data.corporationsSummary).toBeDefined();
|
||||
expect(data.aiProGateway).toBeDefined();
|
||||
expect(data.aiProGateway.scopesCount).toBe(2);
|
||||
expect(data.aiProGateway.rulesCount).toBe(2);
|
||||
expect(data.runtime.mode).toBeDefined();
|
||||
expect(data.runtime.configFile).toBeDefined();
|
||||
});
|
||||
|
||||
test("hose-use status 与 whoami 别名成功解析至 context", async () => {
|
||||
const resStatus = await runCli(["status", "--json"]);
|
||||
expect(resStatus.exitCode).toBe(0);
|
||||
const dataStatus = JSON.parse(resStatus.stdout);
|
||||
expect(dataStatus.tool).toBe("hose-use");
|
||||
|
||||
const resWhoami = await runCli(["whoami", "--json"]);
|
||||
expect(resWhoami.exitCode).toBe(0);
|
||||
const dataWhoami = JSON.parse(resWhoami.stdout);
|
||||
expect(dataWhoami.tool).toBe("hose-use");
|
||||
});
|
||||
|
||||
test("hose-aipro status 输出 AI PRO 专属上下文", async () => {
|
||||
const res = await runAiProCli(["status"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("合思 AI PRO 确定性审批网关运行上下文");
|
||||
expect(res.stdout).toContain("规约场景库");
|
||||
expect(res.stdout).toContain("差旅报销");
|
||||
});
|
||||
|
||||
test("hose-aipro status --json 输出结构化数据", async () => {
|
||||
const res = await runAiProCli(["status", "--json"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
|
||||
const data = JSON.parse(res.stdout);
|
||||
expect(data.tool).toBe("hose-aipro");
|
||||
expect(data.ruleEngine.scopesCount).toBe(2);
|
||||
expect(data.ruleEngine.rulesCount).toBe(2);
|
||||
expect(data.sessions).toBeDefined();
|
||||
});
|
||||
|
||||
test("hose-use aipro status 双向桥接成功转发", async () => {
|
||||
const res = await runCli(["aipro", "status", "--json"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
|
||||
const data = JSON.parse(res.stdout);
|
||||
expect(data.tool).toBe("hose-aipro");
|
||||
expect(data.ruleEngine.scopesCount).toBe(2);
|
||||
});
|
||||
|
||||
test("hose-aipro 帮助页在顶部动态展示当前企业页眉", async () => {
|
||||
const res = await runAiProCli(["help"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("[当前");
|
||||
expect(res.stdout).toContain("hose-aipro status");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,152 @@
|
||||
import { getActiveAccount } from "../../core/auth/account-store.js";
|
||||
import {
|
||||
resolveGlobalConfigFile,
|
||||
resolvePrimaryEnterprisesDir,
|
||||
resolveWritableEnterprisesDir,
|
||||
getEnterprisesDirCandidates,
|
||||
} from "../../core/config/loader.js";
|
||||
import { ApprovalRepository } from "../../domains/approval/index.js";
|
||||
import { VERSION } from "../../version.js";
|
||||
import { formatExpiresAt, formatSourceLabel, printJson } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
|
||||
export async function handleContextCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const currentCorp = runtime.selectedCorp;
|
||||
const allCorps = runtime.corpContext.listCorps();
|
||||
const activeAccount = getActiveAccount();
|
||||
const isStateful = runtime.corpContext.isStateful();
|
||||
const configFile = resolveGlobalConfigFile();
|
||||
const enterprisesDir = resolvePrimaryEnterprisesDir() || resolveWritableEnterprisesDir();
|
||||
|
||||
let scopesCount = 0;
|
||||
let rulesCount = 0;
|
||||
let scopes: Array<{ index: number; scope: string; ruleCount: number }> = [];
|
||||
let totalRunsCount = 0;
|
||||
let pendingRunsCount = 0;
|
||||
|
||||
try {
|
||||
const repo = new ApprovalRepository();
|
||||
const loadedScopes = repo.listScopes("active");
|
||||
scopesCount = loadedScopes.length;
|
||||
scopes = loadedScopes.map((s) => ({
|
||||
index: s.index,
|
||||
scope: s.scope,
|
||||
ruleCount: s.ruleCount,
|
||||
}));
|
||||
const loadedRules = repo.listRules();
|
||||
rulesCount = loadedRules.length;
|
||||
|
||||
const runs = currentCorp?.id ? repo.listRuns({ corpId: currentCorp.id }) : repo.listRuns();
|
||||
totalRunsCount = runs.length;
|
||||
pendingRunsCount = runs.filter((r) => r.decision === "PENDING").length;
|
||||
} catch {
|
||||
// 容错处理(如 SQLite 尚未初始化等场景)
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const validCorps = allCorps.filter((c) => !c.expiresAt || c.expiresAt > now);
|
||||
const expiredCorps = allCorps.filter((c) => c.expiresAt && c.expiresAt <= now);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
tool: "hose-use",
|
||||
version: VERSION,
|
||||
account: activeAccount
|
||||
? {
|
||||
accountId: activeAccount.accountId,
|
||||
userId: activeAccount.userId || null,
|
||||
corporationCount: activeAccount.corporations.length,
|
||||
}
|
||||
: currentCorp?.accountId
|
||||
? {
|
||||
accountId: currentCorp.accountId,
|
||||
userId: null,
|
||||
corporationCount: allCorps.filter((c) => c.accountId === currentCorp.accountId).length,
|
||||
}
|
||||
: null,
|
||||
activeCorporation: currentCorp
|
||||
? {
|
||||
id: currentCorp.id,
|
||||
name: currentCorp.name,
|
||||
staffId: currentCorp.credentials?.staffId || currentCorp.staffId,
|
||||
userName: currentCorp.staffName || currentCorp.session?.staffName || null,
|
||||
source: currentCorp.source,
|
||||
expiresAt: currentCorp.auth?.expiresAt || currentCorp.session?.expTime,
|
||||
expired:
|
||||
(currentCorp.auth?.expiresAt || currentCorp.session?.expTime)
|
||||
? (currentCorp.auth?.expiresAt || currentCorp.session?.expTime)! <= now
|
||||
: false,
|
||||
baseUrl: currentCorp.baseUrl,
|
||||
accountId: currentCorp.accountId || null,
|
||||
}
|
||||
: null,
|
||||
corporationsSummary: {
|
||||
total: allCorps.length,
|
||||
validCount: validCorps.length,
|
||||
expiredCount: expiredCorps.length,
|
||||
activeCorpId: currentCorp?.id || null,
|
||||
},
|
||||
aiProGateway: {
|
||||
connectedCorpId: currentCorp?.id || null,
|
||||
scopesCount,
|
||||
rulesCount,
|
||||
scopes,
|
||||
pendingRunsCount,
|
||||
totalRunsCount,
|
||||
},
|
||||
runtime: {
|
||||
mode: isStateful ? "stateful" : "stateless",
|
||||
configFile,
|
||||
enterprisesDir,
|
||||
candidates: getEnterprisesDirCandidates(),
|
||||
},
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const accountStr = activeAccount?.accountId || currentCorp?.accountId || "-";
|
||||
const userIdStr = activeAccount?.userId ? ` (用户 ID: ${activeAccount.userId})` : "";
|
||||
const corpStaffId = currentCorp?.credentials?.staffId || currentCorp?.staffId || "-";
|
||||
const corpStaffName = currentCorp?.staffName || currentCorp?.session?.staffName || "-";
|
||||
const corpExpiresAt = currentCorp?.auth?.expiresAt || currentCorp?.session?.expTime;
|
||||
|
||||
const scopesStr =
|
||||
scopes.length > 0
|
||||
? `已加载 ${scopesCount} 个场景 (${scopes.map((s) => `#${s.index} ${s.scope}`).join(", ")}),共 ${rulesCount} 条仲裁规则`
|
||||
: "暂未配置场景规则 (可使用 hose-use rule add 添加)";
|
||||
|
||||
const lines = [
|
||||
`====== 全局运行上下文与身份诊断 (hose-use v${VERSION}) ======`,
|
||||
` 当前活跃账号 : ${accountStr}${userIdStr}`,
|
||||
` 当前激活企业 : ${currentCorp ? `${currentCorp.name} (${currentCorp.id})` : "⚠️ 未激活任何企业"}`,
|
||||
` 当前操作员工 : ${corpStaffId}`,
|
||||
` 员工真实姓名 : ${corpStaffName}`,
|
||||
` 凭证来源类型 : ${currentCorp ? formatSourceLabel(currentCorp.source) : "-"}`,
|
||||
` 凭证有效状态 : ${currentCorp ? formatExpiresAt(corpExpiresAt) : "-"}`,
|
||||
` 主站 BaseURL : ${currentCorp?.baseUrl || "-"}`,
|
||||
` 已配置企业总数: ${allCorps.length} 家 (有效: ${validCorps.length} 家, 已过期: ${expiredCorps.length} 家)`,
|
||||
` AI PRO 规约库 : ${scopesStr}`,
|
||||
` AI PRO 待决断 : ${pendingRunsCount} 个待决断会话 (当前企业历史总会话: ${totalRunsCount} 个)`,
|
||||
` 运行模式设置 : ${isStateful ? "有状态模式 (Stateful - 自动记忆当前企业)" : "无状态模式 (Stateless)"}`,
|
||||
` 全局配置文件 : ${configFile}`,
|
||||
` 企业凭证目录 : ${enterprisesDir}`,
|
||||
"",
|
||||
"提示:",
|
||||
" - hose-use 与 hose-aipro 默认共享同一套企业与身份凭证上下文,无须重复配置。",
|
||||
" - 切换全局默认企业: hose-use corps switch <企业ID>",
|
||||
" - 单次临时指定企业: hose-use --corp=<企业ID> <命令> 或 hose-aipro --corp=<企业ID> <子命令>",
|
||||
" - AI PRO 专属上下文: hose-aipro status",
|
||||
"",
|
||||
];
|
||||
|
||||
return { stdout: lines.join("\n"), stderr: "", exitCode: 0 };
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
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");
|
||||
});
|
||||
});
|
||||
|
||||
describe("cli/commands/corps > handleCorpsCommand search & aliases", () => {
|
||||
const mockCorps = [
|
||||
{
|
||||
id: "corpAlpha",
|
||||
name: "阿尔法网络科技有限公司",
|
||||
corpId: "alphaPhysicalId",
|
||||
staffId: "STAFF_001",
|
||||
staffName: "张三",
|
||||
accountId: "13800000001",
|
||||
source: "account",
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
credentials: {
|
||||
accessToken: "token-alpha",
|
||||
corpId: "alphaPhysicalId",
|
||||
staffId: "STAFF_001",
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "corpBeta@13900000002",
|
||||
name: "贝塔云端信息系统",
|
||||
corpId: "corpBeta",
|
||||
staffId: "STAFF_002",
|
||||
staffName: "李四",
|
||||
accountId: "13900000002",
|
||||
source: "link",
|
||||
baseUrl: "https://wx2.ekuaibao.com",
|
||||
credentials: {
|
||||
accessToken: "token-beta",
|
||||
corpId: "corpBeta",
|
||||
staffId: "STAFF_002",
|
||||
},
|
||||
session: {
|
||||
staffName: "李四",
|
||||
cellphone: "13900000002",
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const searchRuntime: CliRuntime = {
|
||||
corpContext: {
|
||||
getAllCorps: () => mockCorps,
|
||||
listCorps: () => mockCorps.map((c) => ({
|
||||
id: c.id,
|
||||
name: c.name,
|
||||
corpId: c.corpId,
|
||||
staffId: c.staffId,
|
||||
staffName: c.staffName,
|
||||
accountId: c.accountId,
|
||||
source: c.source,
|
||||
current: c.id === "corpAlpha",
|
||||
})),
|
||||
getCurrent: () => mockCorps[0],
|
||||
switchCorp: (id: string) => mockCorps.some((c) => c.id === id),
|
||||
resolve: () => mockCorps[0],
|
||||
} as any,
|
||||
selectedCorp: mockCorps[0] as any,
|
||||
jsonMode: false,
|
||||
};
|
||||
|
||||
it("returns error exit code when search keyword is empty", async () => {
|
||||
const res = await handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
action: "search",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["corps", "search"],
|
||||
},
|
||||
searchRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(1);
|
||||
expect(res.stderr).toContain("用法: hose-use corps search <关键词>");
|
||||
});
|
||||
|
||||
it("searches by name with case-insensitive substring match", async () => {
|
||||
const res = await handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
action: "search",
|
||||
args: ["阿尔法"],
|
||||
options: {},
|
||||
raw: ["corps", "search", "阿尔法"],
|
||||
},
|
||||
searchRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("[阿尔法网络科技有限公司]");
|
||||
expect(res.stdout).toContain("命中企业名称");
|
||||
expect(res.stdout).toContain("* 1"); // 当前激活标记
|
||||
});
|
||||
|
||||
it("searches by staffName and highlights the matched cell", async () => {
|
||||
const res = await handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
action: "search",
|
||||
args: ["李四"],
|
||||
options: {},
|
||||
raw: ["corps", "search", "李四"],
|
||||
},
|
||||
searchRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("[李四]");
|
||||
expect(res.stdout).toContain("命中员工姓名");
|
||||
expect(res.stdout).toContain("corpBeta");
|
||||
});
|
||||
|
||||
it("searches by staffId case-insensitively", async () => {
|
||||
const res = await handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
action: "search",
|
||||
args: ["staff_001"],
|
||||
options: {},
|
||||
raw: ["corps", "search", "staff_001"],
|
||||
},
|
||||
searchRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("[STAFF_001]");
|
||||
expect(res.stdout).toContain("命中员工工号");
|
||||
});
|
||||
|
||||
it("searches by physical corpId", async () => {
|
||||
const res = await handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
action: "search",
|
||||
args: ["alphaPhysicalId"],
|
||||
options: {},
|
||||
raw: ["corps", "search", "alphaPhysicalId"],
|
||||
},
|
||||
searchRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("阿尔法网络科技有限公司");
|
||||
expect(res.stdout).toContain("命中企业ID");
|
||||
});
|
||||
|
||||
it("searches by accountId", async () => {
|
||||
const res = await handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
action: "search",
|
||||
args: ["13900000002"],
|
||||
options: {},
|
||||
raw: ["corps", "search", "13900000002"],
|
||||
},
|
||||
searchRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("[13900000002]");
|
||||
expect(res.stdout).toContain("命中所属账号");
|
||||
});
|
||||
|
||||
it("supports find alias for search", async () => {
|
||||
const res = await handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
action: "find",
|
||||
args: ["阿尔法"],
|
||||
options: {},
|
||||
raw: ["corps", "find", "阿尔法"],
|
||||
},
|
||||
searchRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("[阿尔法网络科技有限公司]");
|
||||
});
|
||||
|
||||
it("outputs friendly message when no corps match", async () => {
|
||||
const res = await handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
action: "search",
|
||||
args: ["nonexistent_keyword"],
|
||||
options: {},
|
||||
raw: ["corps", "search", "nonexistent_keyword"],
|
||||
},
|
||||
searchRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toBe("未找到匹配 \"nonexistent_keyword\" 的企业配置\n");
|
||||
});
|
||||
|
||||
it("supports --json mode with structured output", async () => {
|
||||
const jsonRuntime = { ...searchRuntime, jsonMode: true };
|
||||
const res = await handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
action: "search",
|
||||
args: ["阿尔法"],
|
||||
options: { json: true },
|
||||
raw: ["corps", "search", "阿尔法", "--json"],
|
||||
},
|
||||
jsonRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
const data = JSON.parse(res.stdout);
|
||||
expect(data.keyword).toBe("阿尔法");
|
||||
expect(data.count).toBe(1);
|
||||
expect(data.activeCorpId).toBe("corpAlpha");
|
||||
expect(data.corporations).toHaveLength(1);
|
||||
expect(data.corporations[0].id).toBe("corpAlpha");
|
||||
expect(data.corporations[0].name).toBe("阿尔法网络科技有限公司");
|
||||
expect(data.corporations[0].matchedFields).toContain("name");
|
||||
});
|
||||
|
||||
it("outputs help message via corps help", async () => {
|
||||
const res = await handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
action: "help",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["corps", "help"],
|
||||
},
|
||||
searchRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("hose-use corps <子命令>");
|
||||
expect(res.stdout).toContain("search <关键词>");
|
||||
expect(res.stdout).toContain("find");
|
||||
});
|
||||
});
|
||||
+273
-2
@@ -1,6 +1,20 @@
|
||||
import { join } from "node:path";
|
||||
import { importFromLink } from "../../core/auth/login.js";
|
||||
import { resolveWritableEnterprisesDir } from "../../core/config/loader.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";
|
||||
|
||||
const FIELD_LABEL_MAP: Record<string, string> = {
|
||||
id: "配置ID",
|
||||
name: "企业名称",
|
||||
corpId: "企业ID",
|
||||
staffId: "员工工号",
|
||||
staffName: "员工姓名",
|
||||
accountId: "所属账号",
|
||||
};
|
||||
|
||||
export async function handleCorpsCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
@@ -9,21 +23,203 @@ export async function handleCorpsCommand(
|
||||
|
||||
switch (action) {
|
||||
case "list":
|
||||
case "ls":
|
||||
return handleList(parsed, runtime);
|
||||
case "search":
|
||||
case "find":
|
||||
case "query":
|
||||
case "filter":
|
||||
return handleSearch(parsed, runtime);
|
||||
case "switch":
|
||||
case "use":
|
||||
return handleSwitch(parsed, runtime);
|
||||
case "current":
|
||||
case "whoami":
|
||||
case "status":
|
||||
case "active":
|
||||
return handleCurrent(parsed, runtime);
|
||||
case "add-link":
|
||||
case "link":
|
||||
case "import-link":
|
||||
return handleAddLink(parsed, runtime);
|
||||
case "help":
|
||||
return handleCorpsHelp();
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 corps 子命令: ${action}。支持: list, switch, current\n`,
|
||||
stderr: `未知 corps 子命令: ${action}。支持: list, search, switch, current, add-link\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function printCorpsHelp(): string {
|
||||
return `
|
||||
用法:
|
||||
hose-use corps <子命令> [参数] [选项]
|
||||
|
||||
子命令:
|
||||
list 列出本地已保存的所有企业配置 (别名: ls)
|
||||
search <关键词> 根据关键词模糊搜索企业(支持 id, name, corpId, staffId, staffName, accountId,别名: find)
|
||||
switch <企业ID> 切换当前激活的工作企业 (别名: use)
|
||||
current 查看当前激活的企业配置与凭证详情
|
||||
add-link <URL> 从第三方协助/免密链接导入企业凭证
|
||||
|
||||
选项:
|
||||
--json, -j 以 JSON 格式输出
|
||||
--help, -h 查看帮助信息
|
||||
|
||||
示例:
|
||||
hose-use corps list
|
||||
hose-use corps search 某企业
|
||||
hose-use corps search 17718556446
|
||||
hose-use corps switch ID01MCcOgJl1td
|
||||
`.trim();
|
||||
}
|
||||
|
||||
function handleCorpsHelp(): CliResult {
|
||||
return {
|
||||
stdout: printCorpsHelp() + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const keyword = parsed.args[0] || stringOption(parsed.options, ["keyword", "query", "k", "q", "name", "id"]);
|
||||
if (!keyword || !keyword.trim()) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use corps search <关键词>\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const kw = keyword.trim().toLowerCase();
|
||||
|
||||
// 从 CorpContext 中获取企业列表
|
||||
const rawCorps = typeof runtime.corpContext.getAllCorps === "function"
|
||||
? runtime.corpContext.getAllCorps()
|
||||
: null;
|
||||
|
||||
const normalizedCorps = rawCorps
|
||||
? rawCorps.map((c) => ({
|
||||
id: c.id,
|
||||
name: c.name,
|
||||
corpId: c.corpId || c.credentials?.corpId || c.id,
|
||||
staffId: c.staffId || c.credentials?.staffId || "",
|
||||
staffName: c.staffName || c.session?.staffName || "",
|
||||
accountId: c.accountId || "",
|
||||
source: c.source || "manual",
|
||||
baseUrl: c.baseUrl,
|
||||
current: c.id === runtime.selectedCorp?.id,
|
||||
expiresAt: c.auth?.expiresAt || (c.session?.expTime ?? undefined),
|
||||
}))
|
||||
: runtime.corpContext.listCorps().map((c) => ({
|
||||
id: c.id,
|
||||
name: c.name,
|
||||
corpId: c.corpId || c.id,
|
||||
staffId: c.staffId || "",
|
||||
staffName: c.staffName || "",
|
||||
accountId: c.accountId || "",
|
||||
source: c.source || "manual",
|
||||
baseUrl: c.baseUrl,
|
||||
current: c.current || c.id === runtime.selectedCorp?.id,
|
||||
expiresAt: c.expiresAt,
|
||||
}));
|
||||
|
||||
const matches: Array<typeof normalizedCorps[number] & { matchedFields: string[] }> = [];
|
||||
|
||||
for (const corp of normalizedCorps) {
|
||||
const matchedFields: string[] = [];
|
||||
|
||||
if (corp.id && corp.id.toLowerCase().includes(kw)) {
|
||||
matchedFields.push("id");
|
||||
}
|
||||
if (corp.name && corp.name.toLowerCase().includes(kw)) {
|
||||
matchedFields.push("name");
|
||||
}
|
||||
if (corp.corpId && corp.corpId.toLowerCase().includes(kw) && !matchedFields.includes("corpId") && corp.corpId !== corp.id) {
|
||||
matchedFields.push("corpId");
|
||||
}
|
||||
if (corp.staffId && corp.staffId.toLowerCase().includes(kw)) {
|
||||
matchedFields.push("staffId");
|
||||
}
|
||||
if (corp.staffName && corp.staffName.toLowerCase().includes(kw)) {
|
||||
matchedFields.push("staffName");
|
||||
}
|
||||
if (corp.accountId && corp.accountId.toLowerCase().includes(kw)) {
|
||||
matchedFields.push("accountId");
|
||||
}
|
||||
|
||||
if (matchedFields.length > 0) {
|
||||
matches.push({ ...corp, matchedFields });
|
||||
}
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
keyword: keyword.trim(),
|
||||
count: matches.length,
|
||||
activeCorpId: runtime.selectedCorp?.id,
|
||||
corporations: matches.map((m) => ({
|
||||
id: m.id,
|
||||
name: m.name,
|
||||
corpId: m.corpId,
|
||||
staffId: m.staffId,
|
||||
staffName: m.staffName || undefined,
|
||||
accountId: m.accountId || undefined,
|
||||
source: m.source,
|
||||
baseUrl: m.baseUrl,
|
||||
current: m.current,
|
||||
expiresAt: m.expiresAt,
|
||||
matchedFields: m.matchedFields,
|
||||
})),
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (matches.length === 0) {
|
||||
return {
|
||||
stdout: `未找到匹配 "${keyword.trim()}" 的企业配置\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = matches.map((m, i) => {
|
||||
const isCurrent = m.current;
|
||||
const matchLabels = m.matchedFields.map((f) => FIELD_LABEL_MAP[f] || f);
|
||||
return [
|
||||
isCurrent ? `* ${i + 1}` : ` ${i + 1}`,
|
||||
m.matchedFields.includes("id") || m.matchedFields.includes("corpId") ? `[${m.id}]` : m.id,
|
||||
m.matchedFields.includes("name") ? `[${m.name}]` : m.name,
|
||||
m.matchedFields.includes("staffId") ? `[${m.staffId}]` : m.staffId,
|
||||
m.staffName ? (m.matchedFields.includes("staffName") ? `[${m.staffName}]` : m.staffName) : "-",
|
||||
m.accountId ? (m.matchedFields.includes("accountId") ? `[${m.accountId}]` : m.accountId) : "-",
|
||||
matchLabels.map((l) => `命中${l}`).join(", "),
|
||||
formatExpiresAt(m.expiresAt),
|
||||
];
|
||||
});
|
||||
|
||||
const table = printTable(
|
||||
["#", "企业 ID", "企业名称", "员工工号", "员工姓名", "所属账号", "匹配项", "Token 过期时间"],
|
||||
rows
|
||||
);
|
||||
|
||||
return {
|
||||
stdout: `====== 企业搜索结果 (关键词: "${keyword.trim()}", 找到 ${matches.length} 家) ======\n${table}\n\n提示:\n - 标记 * 为当前激活企业\n - 标记 [...] 为命中关键词的字段\n - 使用 hose-use corps switch <企业ID> 切换工作企业\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const corps = runtime.corpContext.listCorps();
|
||||
|
||||
@@ -61,7 +257,7 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
|
||||
);
|
||||
|
||||
return {
|
||||
stdout: `====== 已配置企业列表 (${corps.length} 家) ======\n${table}\n\n提示: 使用 hose-use corps switch <企业ID> 切换工作企业\n`,
|
||||
stdout: `====== 已配置企业列表 (${corps.length} 家) ======\n${table}\n\n提示:\n - 标记 * 为当前激活企业(同时作为 hose-use 与 hose-aipro 的统一默认执行上下文)\n - 使用 hose-use corps switch <企业ID> 切换工作企业\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
@@ -113,6 +309,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 +344,77 @@ 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);
|
||||
const ttl = stringOption(parsed.options, ["ttl"]);
|
||||
const expires = stringOption(parsed.options, ["expires", "days"]);
|
||||
|
||||
if (!linkUrl && process.stdin.isTTY) {
|
||||
linkUrl = await prompt("请输入第三方协助/免密登录链接 URL: ");
|
||||
}
|
||||
|
||||
if (!linkUrl) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "错误:必须提供协助/免密链接 URL!用法: hose-use corps add-link <url> [--name <企业别名>] [--ttl 3d|--expires 3] [--overwrite]\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const corp = await importFromLink(linkUrl, {
|
||||
name,
|
||||
overwrite,
|
||||
ttl,
|
||||
expires,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(corp, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const targetDir = resolveWritableEnterprisesDir();
|
||||
const savedPath = join(targetDir, `${corp.id}.json`);
|
||||
|
||||
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),
|
||||
"保存路径": savedPath,
|
||||
};
|
||||
|
||||
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,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,425 @@
|
||||
import { describe, it, expect, spyOn } from "bun:test";
|
||||
import { handleFeeTypeCommand } from "./feetype.js";
|
||||
import * as feetypeTools from "../../domains/feetype/tools.js";
|
||||
import type { CliRuntime } from "../types.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import { FeeTypeNode } from "../../domains/feetype/types.js";
|
||||
|
||||
describe("CLI - feetype 费用类型管理命令", () => {
|
||||
const dummyRuntimeNoCorp: CliRuntime = {
|
||||
corpContext: {
|
||||
listCorps: () => [],
|
||||
getCurrent: () => null,
|
||||
switchCorp: () => false,
|
||||
resolve: () => null,
|
||||
} as any,
|
||||
selectedCorp: null,
|
||||
jsonMode: false,
|
||||
};
|
||||
|
||||
const mockCorp: CorpConfig = {
|
||||
id: "corp_test",
|
||||
name: "测试科技企业",
|
||||
source: "account",
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
credentials: {
|
||||
accessToken: "mock-token",
|
||||
corpId: "corp_test",
|
||||
staffId: "mock-staff",
|
||||
},
|
||||
};
|
||||
|
||||
const dummyRuntimeWithCorp: CliRuntime = {
|
||||
corpContext: {
|
||||
listCorps: () => [mockCorp],
|
||||
getCurrent: () => mockCorp,
|
||||
switchCorp: () => true,
|
||||
resolve: () => mockCorp,
|
||||
} as any,
|
||||
selectedCorp: mockCorp,
|
||||
jsonMode: false,
|
||||
};
|
||||
|
||||
const mockTree = [
|
||||
{
|
||||
feeType: {
|
||||
id: "ft_travel",
|
||||
name: "差旅费用",
|
||||
code: "COST19",
|
||||
active: true,
|
||||
parentId: "",
|
||||
order: 1000,
|
||||
color: "#90caf9",
|
||||
icon: "https://images.ekuaibao.com/feetype/sf_100.png",
|
||||
description: "员工差旅相关费用",
|
||||
},
|
||||
children: [
|
||||
{
|
||||
feeType: {
|
||||
id: "ft_flight",
|
||||
name: "飞机票",
|
||||
code: "COST54",
|
||||
active: true,
|
||||
parentId: "ft_travel",
|
||||
order: 1001,
|
||||
color: "#90caf9",
|
||||
icon: "",
|
||||
description: "",
|
||||
},
|
||||
children: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
feeType: {
|
||||
id: "ft_disabled",
|
||||
name: "已停用费用",
|
||||
code: "COST99",
|
||||
active: false,
|
||||
parentId: "",
|
||||
order: 2000,
|
||||
color: "#ccc",
|
||||
icon: "",
|
||||
description: "",
|
||||
},
|
||||
children: [],
|
||||
},
|
||||
] as unknown as FeeTypeNode[];
|
||||
|
||||
it("未选中企业时抛出友好错误", async () => {
|
||||
expect(
|
||||
handleFeeTypeCommand(
|
||||
{
|
||||
area: "feetype",
|
||||
action: "list",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["feetype", "list"],
|
||||
},
|
||||
dummyRuntimeNoCorp
|
||||
)
|
||||
).rejects.toThrow("未指定或未找到有效企业");
|
||||
});
|
||||
|
||||
it("feetype list 默认以树形层级展示活跃费用类型", async () => {
|
||||
const spy = spyOn(feetypeTools, "listFeeTypes").mockResolvedValue({
|
||||
total: 3,
|
||||
items: mockTree,
|
||||
rawTree: mockTree,
|
||||
});
|
||||
|
||||
const res = await handleFeeTypeCommand(
|
||||
{
|
||||
area: "feetype",
|
||||
action: "list",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["feetype", "list"],
|
||||
},
|
||||
dummyRuntimeWithCorp
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("费用类型列表");
|
||||
expect(res.stdout).toContain("差旅费用");
|
||||
expect(res.stdout).toContain("飞机票");
|
||||
expect(res.stdout).toContain("COST19");
|
||||
expect(res.stdout).toContain("🟢 启用");
|
||||
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it("feetype list --json 支持结构化输出", async () => {
|
||||
const spy = spyOn(feetypeTools, "listFeeTypes").mockResolvedValue({
|
||||
total: 2,
|
||||
items: mockTree,
|
||||
rawTree: mockTree,
|
||||
});
|
||||
|
||||
const jsonRuntime = { ...dummyRuntimeWithCorp, jsonMode: true };
|
||||
const res = await handleFeeTypeCommand(
|
||||
{
|
||||
area: "feetype",
|
||||
action: "list",
|
||||
args: [],
|
||||
options: { json: true },
|
||||
raw: ["feetype", "list", "--json"],
|
||||
},
|
||||
jsonRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
const parsed = JSON.parse(res.stdout);
|
||||
expect(parsed.corpId).toBe("corp_test");
|
||||
expect(parsed.total).toBe(2);
|
||||
expect(parsed.items.length).toBe(2);
|
||||
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it("feetype get 查询单个费用类型详情及字段规格", async () => {
|
||||
const mockDetail = {
|
||||
feeType: {
|
||||
id: "ft_travel",
|
||||
name: "差旅费用",
|
||||
code: "COST19",
|
||||
active: true,
|
||||
parentId: "",
|
||||
path: "差旅费用",
|
||||
parentName: "顶级 (根节点)",
|
||||
childrenCount: 1,
|
||||
color: "#90caf9",
|
||||
icon: "https://images.ekuaibao.com/feetype/sf_100.png",
|
||||
description: "差旅综合报销",
|
||||
},
|
||||
specifications: {
|
||||
expenseComponents: [
|
||||
{ field: "amount", cnLabel: "报销金额", type: "money", optional: false },
|
||||
],
|
||||
requisitionComponents: [
|
||||
{ field: "amount", cnLabel: "预计金额", type: "money", optional: true },
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const spy = spyOn(feetypeTools, "getFeeTypeDetail").mockResolvedValue(mockDetail as any);
|
||||
|
||||
const res = await handleFeeTypeCommand(
|
||||
{
|
||||
area: "feetype",
|
||||
action: "get",
|
||||
args: ["差旅费用"],
|
||||
options: { specs: true },
|
||||
raw: ["feetype", "get", "差旅费用", "--specs"],
|
||||
},
|
||||
dummyRuntimeWithCorp
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("差旅费用");
|
||||
expect(res.stdout).toContain("COST19");
|
||||
expect(res.stdout).toContain("报销金额 (amount) - money [必填]");
|
||||
expect(res.stdout).toContain("预计金额 (amount) - money [选填]");
|
||||
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it("feetype create 创建费用类型并展示卡片", async () => {
|
||||
const mockCreated = {
|
||||
id: "ft_hotel",
|
||||
name: "酒店住宿",
|
||||
code: "COST66",
|
||||
active: true,
|
||||
parentId: "ft_travel",
|
||||
path: "差旅费用 / 酒店住宿",
|
||||
parentName: "差旅费用",
|
||||
childrenCount: 0,
|
||||
color: "#90caf9",
|
||||
icon: "",
|
||||
description: "出差酒店",
|
||||
};
|
||||
|
||||
const spy = spyOn(feetypeTools, "createFeeType").mockResolvedValue(mockCreated as any);
|
||||
|
||||
const res = await handleFeeTypeCommand(
|
||||
{
|
||||
area: "feetype",
|
||||
action: "create",
|
||||
args: [],
|
||||
options: {
|
||||
name: "酒店住宿",
|
||||
parent: "差旅费用",
|
||||
},
|
||||
raw: ["feetype", "create", "--name=酒店住宿", "--parent=差旅费用"],
|
||||
},
|
||||
dummyRuntimeWithCorp
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("费用类型创建成功");
|
||||
expect(res.stdout).toContain("酒店住宿");
|
||||
expect(res.stdout).toContain("COST66");
|
||||
expect(res.stdout).toContain("差旅费用 / 酒店住宿");
|
||||
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it("feetype update 修改费用类型属性", async () => {
|
||||
const mockUpdated = {
|
||||
id: "ft_hotel",
|
||||
name: "酒店住宿(改)",
|
||||
code: "COST66",
|
||||
active: true,
|
||||
parentId: "ft_travel",
|
||||
path: "差旅费用 / 酒店住宿(改)",
|
||||
parentName: "差旅费用",
|
||||
childrenCount: 0,
|
||||
color: "#90caf9",
|
||||
icon: "",
|
||||
description: "新说明",
|
||||
};
|
||||
|
||||
const spy = spyOn(feetypeTools, "updateFeeTypeInfo").mockResolvedValue(mockUpdated as any);
|
||||
|
||||
const res = await handleFeeTypeCommand(
|
||||
{
|
||||
area: "feetype",
|
||||
action: "update",
|
||||
args: ["酒店住宿"],
|
||||
options: { desc: "新说明" },
|
||||
raw: ["feetype", "update", "酒店住宿", "--desc=新说明"],
|
||||
},
|
||||
dummyRuntimeWithCorp
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("费用类型修改成功");
|
||||
expect(res.stdout).toContain("新说明");
|
||||
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it("feetype disable 停用费用类型", async () => {
|
||||
const spy = spyOn(feetypeTools, "disableFeeTypeItem").mockResolvedValue({
|
||||
success: true,
|
||||
item: {
|
||||
id: "ft_hotel",
|
||||
name: "酒店住宿",
|
||||
code: "COST66",
|
||||
active: false,
|
||||
} as any,
|
||||
});
|
||||
|
||||
const res = await handleFeeTypeCommand(
|
||||
{
|
||||
area: "feetype",
|
||||
action: "disable",
|
||||
args: ["酒店住宿"],
|
||||
options: { yes: true },
|
||||
raw: ["feetype", "disable", "酒店住宿", "--yes"],
|
||||
},
|
||||
dummyRuntimeWithCorp
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("已成功停用");
|
||||
expect(res.stdout).toContain("酒店住宿");
|
||||
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it("feetype enable 重新启用费用类型", async () => {
|
||||
const spy = spyOn(feetypeTools, "enableFeeTypeItem").mockResolvedValue({
|
||||
success: true,
|
||||
item: {
|
||||
id: "ft_hotel",
|
||||
name: "酒店住宿",
|
||||
code: "COST66",
|
||||
active: true,
|
||||
} as any,
|
||||
});
|
||||
|
||||
const res = await handleFeeTypeCommand(
|
||||
{
|
||||
area: "feetype",
|
||||
action: "enable",
|
||||
args: ["酒店住宿"],
|
||||
options: {},
|
||||
raw: ["feetype", "enable", "酒店住宿"],
|
||||
},
|
||||
dummyRuntimeWithCorp
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("已成功启用");
|
||||
expect(res.stdout).toContain("酒店住宿");
|
||||
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it("feetype move 移动费用类型父级节点", async () => {
|
||||
const spy = spyOn(feetypeTools, "moveFeeTypeItem").mockResolvedValue({
|
||||
success: true,
|
||||
item: {
|
||||
id: "ft_hotel",
|
||||
name: "酒店住宿",
|
||||
code: "COST66",
|
||||
active: true,
|
||||
path: "办公费 / 酒店住宿",
|
||||
} as any,
|
||||
parentName: "办公费",
|
||||
});
|
||||
|
||||
const res = await handleFeeTypeCommand(
|
||||
{
|
||||
area: "feetype",
|
||||
action: "move",
|
||||
args: ["酒店住宿"],
|
||||
options: { parent: "办公费" },
|
||||
raw: ["feetype", "move", "酒店住宿", "--parent=办公费"],
|
||||
},
|
||||
dummyRuntimeWithCorp
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("费用类型移动成功");
|
||||
expect(res.stdout).toContain("新所属父级 : 办公费");
|
||||
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it("feetype fields 打印报账与申请字段表格", async () => {
|
||||
const spy = spyOn(feetypeTools, "getFeeTypeFieldsList").mockResolvedValue({
|
||||
feeType: {
|
||||
id: "ft_travel",
|
||||
name: "差旅费用",
|
||||
code: "COST19",
|
||||
} as any,
|
||||
expenseFields: [
|
||||
{
|
||||
field: "amount",
|
||||
label: "金额",
|
||||
type: "money",
|
||||
required: true,
|
||||
editable: true,
|
||||
hidden: false,
|
||||
},
|
||||
],
|
||||
requisitionFields: [],
|
||||
});
|
||||
|
||||
const res = await handleFeeTypeCommand(
|
||||
{
|
||||
area: "feetype",
|
||||
action: "fields",
|
||||
args: ["差旅费用"],
|
||||
options: {},
|
||||
raw: ["feetype", "fields", "差旅费用"],
|
||||
},
|
||||
dummyRuntimeWithCorp
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("费用类型字段配置");
|
||||
expect(res.stdout).toContain("报账字段列表");
|
||||
expect(res.stdout).toContain("amount");
|
||||
expect(res.stdout).toContain("🔴 必填");
|
||||
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it("未知 feetype 子命令时抛出支持说明", async () => {
|
||||
expect(
|
||||
handleFeeTypeCommand(
|
||||
{
|
||||
area: "feetype",
|
||||
action: "invalidCmd",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["feetype", "invalidCmd"],
|
||||
},
|
||||
dummyRuntimeWithCorp
|
||||
)
|
||||
).rejects.toThrow("未知 feetype 子命令");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,516 @@
|
||||
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import { booleanOption, stringOption } from "../parser.js";
|
||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||
import {
|
||||
createFeeType,
|
||||
disableFeeTypeItem,
|
||||
enableFeeTypeItem,
|
||||
findFeeType,
|
||||
FlatFeeTypeItem,
|
||||
flattenFeeTypeTree,
|
||||
getFeeTypeDetail,
|
||||
getFeeTypeFieldsList,
|
||||
listFeeTypes,
|
||||
moveFeeTypeItem,
|
||||
updateFeeTypeInfo,
|
||||
} from "../../domains/feetype/tools.js";
|
||||
import { FeeTypeNode } from "../../domains/feetype/types.js";
|
||||
|
||||
/**
|
||||
* 递归渲染树形层级格式
|
||||
*/
|
||||
function renderTreeRows(
|
||||
nodes: FeeTypeNode[],
|
||||
depth = 0,
|
||||
prefix = "",
|
||||
isLast = true,
|
||||
acc: (string | number)[][] = []
|
||||
): (string | number)[][] {
|
||||
for (let i = 0; i < nodes.length; i++) {
|
||||
const node = nodes[i];
|
||||
const item = node.feeType;
|
||||
if (!item) continue;
|
||||
|
||||
const currentIsLast = i === nodes.length - 1;
|
||||
const branch = depth === 0 ? "" : isLast ? "└─ " : "├─ ";
|
||||
const indent = depth === 0 ? "" : prefix + branch;
|
||||
const nextPrefix = depth === 0 ? "" : prefix + (isLast ? " " : "│ ");
|
||||
|
||||
const children = Array.isArray(node.children) ? node.children : [];
|
||||
acc.push([
|
||||
acc.length + 1,
|
||||
`${indent}${item.name}`,
|
||||
item.code || "-",
|
||||
item.id,
|
||||
item.active ? "🟢 启用" : "🔴 停用",
|
||||
children.length ? `${children.length} 项` : "-",
|
||||
]);
|
||||
|
||||
if (children.length > 0) {
|
||||
renderTreeRows(children, depth + 1, nextPrefix, currentIsLast, acc);
|
||||
}
|
||||
}
|
||||
return acc;
|
||||
}
|
||||
|
||||
export async function handleFeeTypeCommand(
|
||||
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 action = (parsed.action?.toLowerCase() || "list").trim();
|
||||
|
||||
// ── 1. 列表 / 树形展示 (list / tree) ──────────────────────────────────────────
|
||||
if (["list", "tree", "all", "search"].includes(action)) {
|
||||
const includeAll =
|
||||
action === "all" ||
|
||||
booleanOption(parsed.options, ["all", "a", "include-disabled"]) ||
|
||||
false;
|
||||
const isFlat =
|
||||
booleanOption(parsed.options, ["flat", "flatten", "table"]) || false;
|
||||
const keyword =
|
||||
stringOption(parsed.options, ["keyword", "q", "query"]) || parsed.args[0];
|
||||
|
||||
const result = await listFeeTypes(client, corpId, {
|
||||
all: includeAll,
|
||||
flat: isFlat,
|
||||
keyword,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
total: result.total,
|
||||
includeDisabled: includeAll,
|
||||
keyword: keyword || null,
|
||||
items: result.items,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
let rows: (string | number)[][] = [];
|
||||
if (!isFlat && !keyword) {
|
||||
rows = renderTreeRows(result.rawTree);
|
||||
} else {
|
||||
const flatItems = (result.items as FlatFeeTypeItem[]) || [];
|
||||
rows = flatItems.map((item, idx) => [
|
||||
idx + 1,
|
||||
item.path || item.name,
|
||||
item.code || "-",
|
||||
item.id,
|
||||
item.active ? "🟢 启用" : "🔴 停用",
|
||||
item.childrenCount ? `${item.childrenCount} 项` : "-",
|
||||
]);
|
||||
}
|
||||
|
||||
const title = `====== 费用类型列表 (企业: ${corp.name} | 共 ${result.total} 个${
|
||||
includeAll ? ",含停用" : ""
|
||||
}${keyword ? `,过滤: "${keyword}"` : ""}) ======`;
|
||||
const tableStr = rows.length
|
||||
? printTable(["#", "名称 / 层级路径", "编码", "ID", "状态", "子节点"], rows)
|
||||
: "暂无匹配的费用类型";
|
||||
|
||||
return {
|
||||
stdout: `${title}\n${tableStr}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// ── 2. 单条详情 (get / show / detail) ─────────────────────────────────────────
|
||||
if (["get", "show", "detail", "info"].includes(action)) {
|
||||
const target =
|
||||
parsed.args[0] || stringOption(parsed.options, ["id", "code", "name"]);
|
||||
if (!target) {
|
||||
throw new Error("请提供费用类型 ID、编码或名称: hose-use feetype get <ID|编码|名称>");
|
||||
}
|
||||
|
||||
const includeSpecs = booleanOption(parsed.options, ["specs", "spec", "fields"]);
|
||||
const detail = await getFeeTypeDetail(client, corpId, target, { includeSpecs });
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
...detail,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const ft = detail.feeType;
|
||||
const lines = [
|
||||
`====== 费用类型详情 (${ft.name}) ======`,
|
||||
` 名称 : ${ft.name}${ft.enName ? ` (${ft.enName})` : ""}`,
|
||||
` 编码 : ${ft.code}`,
|
||||
` ID : ${ft.id}`,
|
||||
` 当前状态 : ${ft.active ? "🟢 启用中" : "🔴 已停用"}`,
|
||||
` 层级全路径 : ${ft.path || ft.name}`,
|
||||
` 父级节点 : ${ft.parentName || "顶级 (根节点)"} (${ft.parentId || "-"})`,
|
||||
` 子类型数量 : ${ft.childrenCount || 0} 项`,
|
||||
` 标识颜色 : ${ft.color || "-"}`,
|
||||
` 图标链接 : ${ft.icon || "-"}`,
|
||||
` 说明描述 : ${ft.description || "-"}`,
|
||||
];
|
||||
|
||||
if (includeSpecs && detail.specifications) {
|
||||
const exp = detail.specifications.expenseComponents || [];
|
||||
const req = detail.specifications.requisitionComponents || [];
|
||||
lines.push("");
|
||||
lines.push(` ── 报账字段列表 (${exp.length} 项) ──`);
|
||||
for (const c of exp) {
|
||||
const reqStr = c.optional === false ? "[必填]" : "[选填]";
|
||||
lines.push(` • ${c.cnLabel || c.label} (${c.field || "-"}) - ${c.type || "text"} ${reqStr}`);
|
||||
}
|
||||
lines.push("");
|
||||
lines.push(` ── 申请字段列表 (${req.length} 项) ──`);
|
||||
for (const c of req) {
|
||||
const reqStr = c.optional === false ? "[必填]" : "[选填]";
|
||||
lines.push(` • ${c.cnLabel || c.label} (${c.field || "-"}) - ${c.type || "text"} ${reqStr}`);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `${lines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// ── 3. 新建费用类型 (create / add) ──────────────────────────────────────────
|
||||
if (["create", "add", "new"].includes(action)) {
|
||||
const name =
|
||||
stringOption(parsed.options, ["name", "title"]) || parsed.args[0];
|
||||
if (!name?.trim()) {
|
||||
throw new Error(
|
||||
"请提供费用类型名称: hose-use feetype create --name=\"费用名称\" [--code=...] [--parent=...]"
|
||||
);
|
||||
}
|
||||
|
||||
const code = stringOption(parsed.options, ["code"]);
|
||||
const parent = stringOption(parsed.options, ["parent", "parent-id", "parentId"]);
|
||||
const enName = stringOption(parsed.options, ["en-name", "enName"]);
|
||||
const description = stringOption(parsed.options, ["desc", "description"]);
|
||||
const color = stringOption(parsed.options, ["color"]);
|
||||
const icon = stringOption(parsed.options, ["icon"]);
|
||||
|
||||
const created = await createFeeType(client, corpId, {
|
||||
name: name.trim(),
|
||||
code,
|
||||
parentId: parent,
|
||||
enName,
|
||||
description,
|
||||
color,
|
||||
icon,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
success: true,
|
||||
action: "create",
|
||||
corpId,
|
||||
feeType: created,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: [
|
||||
`🎉 费用类型创建成功!`,
|
||||
` 名称 : ${created.name}`,
|
||||
` 编码 : ${created.code}`,
|
||||
` ID : ${created.id}`,
|
||||
` 层级路径 : ${created.path}`,
|
||||
` 所属父级 : ${created.parentName || "顶级 (根节点)"}`,
|
||||
].join("\n") + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// ── 4. 更新费用类型 (update / edit / modify) ─────────────────────────────────
|
||||
if (["update", "edit", "modify", "set"].includes(action)) {
|
||||
const target =
|
||||
parsed.args[0] || stringOption(parsed.options, ["id", "code", "target"]);
|
||||
if (!target?.trim()) {
|
||||
throw new Error(
|
||||
"请指定待修改的费用类型: hose-use feetype update <ID|编码|名称> [--name=...] [--code=...] [--desc=...]"
|
||||
);
|
||||
}
|
||||
|
||||
const name = stringOption(parsed.options, ["name"]);
|
||||
const code = stringOption(parsed.options, ["code"]);
|
||||
const enName = stringOption(parsed.options, ["en-name", "enName"]);
|
||||
const description = stringOption(parsed.options, ["desc", "description"]);
|
||||
const color = stringOption(parsed.options, ["color"]);
|
||||
const icon = stringOption(parsed.options, ["icon"]);
|
||||
|
||||
if (
|
||||
name === undefined &&
|
||||
code === undefined &&
|
||||
enName === undefined &&
|
||||
description === undefined &&
|
||||
color === undefined &&
|
||||
icon === undefined
|
||||
) {
|
||||
throw new Error("请至少提供一个待更新的属性参数 (例如 --name, --code, --desc, --color)");
|
||||
}
|
||||
|
||||
const updated = await updateFeeTypeInfo(client, corpId, target, {
|
||||
name,
|
||||
code,
|
||||
enName,
|
||||
description,
|
||||
color,
|
||||
icon,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
success: true,
|
||||
action: "update",
|
||||
corpId,
|
||||
feeType: updated,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: [
|
||||
`✅ 费用类型修改成功!`,
|
||||
` 名称 : ${updated.name}`,
|
||||
` 编码 : ${updated.code}`,
|
||||
` ID : ${updated.id}`,
|
||||
` 说明描述 : ${updated.description || "-"}`,
|
||||
].join("\n") + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// ── 5. 停用费用类型 (disable / block / stop) ─────────────────────────────────
|
||||
if (["disable", "block", "stop"].includes(action)) {
|
||||
const target =
|
||||
parsed.args[0] || stringOption(parsed.options, ["id", "code", "target"]);
|
||||
if (!target?.trim()) {
|
||||
throw new Error("请指定待停用的费用类型: hose-use feetype disable <ID|编码|名称>");
|
||||
}
|
||||
|
||||
const res = await disableFeeTypeItem(client, corpId, target);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
success: res.success,
|
||||
action: "disable",
|
||||
corpId,
|
||||
feeType: res.item,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `🔴 费用类型 [${res.item.name}] (${res.item.code}) 已成功停用。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// ── 6. 启用费用类型 (enable / restore / start) ───────────────────────────────
|
||||
if (["enable", "restore", "start"].includes(action)) {
|
||||
const target =
|
||||
parsed.args[0] || stringOption(parsed.options, ["id", "code", "target"]);
|
||||
if (!target?.trim()) {
|
||||
throw new Error("请指定待启用的费用类型: hose-use feetype enable <ID|编码|名称>");
|
||||
}
|
||||
|
||||
const recursive =
|
||||
booleanOption(parsed.options, ["recursive", "r"]) !== false;
|
||||
|
||||
const res = await enableFeeTypeItem(client, corpId, target, { recursive });
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
success: res.success,
|
||||
action: "enable",
|
||||
corpId,
|
||||
feeType: res.item,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `🟢 费用类型 [${res.item.name}] (${res.item.code}) 已成功启用。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// ── 7. 移动费用类型层级 (move) ───────────────────────────────────────────────
|
||||
if (["move"].includes(action)) {
|
||||
const target =
|
||||
parsed.args[0] || stringOption(parsed.options, ["id", "code", "target"]);
|
||||
const parentTarget =
|
||||
stringOption(parsed.options, ["parent", "to"]) || parsed.args[1];
|
||||
|
||||
if (!target?.trim()) {
|
||||
throw new Error("请指定待移动的费用类型: hose-use feetype move <ID|编码|名称> --parent=<新父级|root>");
|
||||
}
|
||||
if (parentTarget === undefined) {
|
||||
throw new Error("请指定目标父级: --parent=<目标父级ID|编码|名称> 或 --parent=root (移至顶级)");
|
||||
}
|
||||
|
||||
const res = await moveFeeTypeItem(client, corpId, target, parentTarget);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
success: res.success,
|
||||
action: "move",
|
||||
corpId,
|
||||
feeType: res.item,
|
||||
parentName: res.parentName,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: [
|
||||
`🚚 费用类型移动成功!`,
|
||||
` 名称 : ${res.item.name} (${res.item.code})`,
|
||||
` 新所属父级 : ${res.parentName}`,
|
||||
` 更新后路径 : ${res.item.path}`,
|
||||
].join("\n") + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// ── 8. 查看表单字段配置 (fields / specs) ─────────────────────────────────────
|
||||
if (["fields", "specs", "schema"].includes(action)) {
|
||||
const target =
|
||||
parsed.args[0] || stringOption(parsed.options, ["id", "code", "target"]);
|
||||
if (!target?.trim()) {
|
||||
throw new Error("请指定费用类型: hose-use feetype fields <ID|编码|名称>");
|
||||
}
|
||||
|
||||
const res = await getFeeTypeFieldsList(client, corpId, target);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId,
|
||||
feeType: res.feeType,
|
||||
expenseFields: res.expenseFields,
|
||||
requisitionFields: res.requisitionFields,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const expRows = res.expenseFields.map((f, i) => [
|
||||
i + 1,
|
||||
f.label,
|
||||
f.field,
|
||||
f.type,
|
||||
f.required ? "🔴 必填" : "⚪ 选填",
|
||||
f.editable ? "是" : "只读",
|
||||
f.hidden ? "是" : "否",
|
||||
]);
|
||||
|
||||
const reqRows = res.requisitionFields.map((f, i) => [
|
||||
i + 1,
|
||||
f.label,
|
||||
f.field,
|
||||
f.type,
|
||||
f.required ? "🔴 必填" : "⚪ 选填",
|
||||
f.editable ? "是" : "只读",
|
||||
f.hidden ? "是" : "否",
|
||||
]);
|
||||
|
||||
const outLines = [
|
||||
`====== 费用类型字段配置 (${res.feeType.name} | ${res.feeType.code}) ======`,
|
||||
"",
|
||||
`── 报账字段列表 (${res.expenseFields.length} 个) ──`,
|
||||
expRows.length
|
||||
? printTable(["#", "字段显示名称", "字段属性名", "控件类型", "必填", "可编辑", "隐藏"], expRows)
|
||||
: "暂无自定义报账字段",
|
||||
"",
|
||||
`── 申请字段列表 (${res.requisitionFields.length} 个) ──`,
|
||||
reqRows.length
|
||||
? printTable(["#", "字段显示名称", "字段属性名", "控件类型", "必填", "可编辑", "隐藏"], reqRows)
|
||||
: "暂无自定义申请字段",
|
||||
];
|
||||
|
||||
return {
|
||||
stdout: `${outLines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`未知 feetype 子命令: "${action}"。\n支持的子命令:\n` +
|
||||
` • hose-use feetype list [--all] [--flat] [--keyword=...] (查看费用类型树)\n` +
|
||||
` • hose-use feetype get <ID|编码|名称> [--specs] (获取详情与字段配置)\n` +
|
||||
` • hose-use feetype create --name=... [--code=...] [--parent=...] (新建费用类型)\n` +
|
||||
` • hose-use feetype update <ID|编码|名称> [--name=...] [--desc=...] (修改属性)\n` +
|
||||
` • hose-use feetype disable <ID|编码|名称> (停用)\n` +
|
||||
` • hose-use feetype enable <ID|编码|名称> (启用)\n` +
|
||||
` • hose-use feetype move <ID|编码|名称> --parent=<新父级|root> (移动父级)\n` +
|
||||
` • hose-use feetype fields <ID|编码|名称> (查看报账与申请字段清单)`
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
import { describe, expect, test, spyOn } from "bun:test";
|
||||
import { handleKeysCommand } from "./keys.js";
|
||||
import { handleOpenApiCommand } from "./openapi.js";
|
||||
import type { CliRuntime, CliParsedArgs } from "../types.js";
|
||||
import * as storeTools from "../../domains/store/tools.js";
|
||||
|
||||
describe("CLI - keys 顶级命令与凭证提取", () => {
|
||||
const dummyCorp: any = {
|
||||
id: "test-corp-id",
|
||||
name: "测试企业A",
|
||||
corpId: "test-corp-id",
|
||||
credentials: { corpId: "test-corp-id", accessToken: "token123" },
|
||||
};
|
||||
|
||||
const createRuntime = (corp: any = dummyCorp, jsonMode = false): CliRuntime => ({
|
||||
corpContext: {} as any,
|
||||
selectedCorp: corp,
|
||||
jsonMode,
|
||||
});
|
||||
|
||||
test("未选中企业时返回提示并报错", async () => {
|
||||
const runtime = createRuntime(null);
|
||||
const parsed: CliParsedArgs = { area: "keys", options: {}, args: [], raw: ["keys"] };
|
||||
const res = await handleKeysCommand(parsed, runtime);
|
||||
expect(res.exitCode).toBe(1);
|
||||
expect(res.stderr).toContain("未选中企业");
|
||||
});
|
||||
|
||||
test("keys 默认脱敏显示 appSecurity 接入密码", async () => {
|
||||
const spy = spyOn(storeTools, "fetchOpenApiKeys").mockImplementation(() =>
|
||||
Promise.resolve([
|
||||
{
|
||||
id: "k-1",
|
||||
name: "开发测试密钥",
|
||||
appKey: "545f8b6a-75a7-4f99-86e1-bca747c985e7",
|
||||
appSecurity: "9bc91727-e96e-4924-abcb-d8ed77557f58",
|
||||
active: true,
|
||||
createTime: 1751357077503,
|
||||
updateTime: 1769063905460,
|
||||
},
|
||||
])
|
||||
);
|
||||
|
||||
const runtime = createRuntime(dummyCorp);
|
||||
const parsed: CliParsedArgs = { area: "keys", options: {}, args: [], raw: ["keys"] };
|
||||
const res = await handleKeysCommand(parsed, runtime);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("开发测试密钥");
|
||||
expect(res.stdout).toContain("545f8b6a-75a7-4f99-86e1-bca747c985e7");
|
||||
// 默认脱敏
|
||||
expect(res.stdout).toContain("9bc91727...7f58");
|
||||
expect(res.stdout).not.toContain("9bc91727-e96e-4924-abcb-d8ed77557f58");
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
test("keys --reveal 显式输出完整接入密码明文", async () => {
|
||||
const spy = spyOn(storeTools, "fetchOpenApiKeys").mockImplementation(() =>
|
||||
Promise.resolve([
|
||||
{
|
||||
id: "k-1",
|
||||
name: "生产密钥",
|
||||
appKey: "key-full-123",
|
||||
appSecurity: "secret-super-long-plain-text",
|
||||
active: true,
|
||||
createTime: 1751357077503,
|
||||
updateTime: 1769063905460,
|
||||
},
|
||||
])
|
||||
);
|
||||
|
||||
const runtime = createRuntime(dummyCorp);
|
||||
const parsed: CliParsedArgs = {
|
||||
area: "keys",
|
||||
options: { reveal: true },
|
||||
args: [],
|
||||
raw: ["keys", "--reveal"],
|
||||
};
|
||||
const res = await handleKeysCommand(parsed, runtime);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("secret-super-long-plain-text");
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
test("keys --json 模式正常序列化", async () => {
|
||||
const spy = spyOn(storeTools, "fetchOpenApiKeys").mockImplementation(() =>
|
||||
Promise.resolve([
|
||||
{
|
||||
id: "k-1",
|
||||
name: "JSON密钥",
|
||||
appKey: "json-app-key",
|
||||
appSecurity: "secret-for-json-test",
|
||||
active: true,
|
||||
createTime: 1751357077503,
|
||||
updateTime: 1769063905460,
|
||||
},
|
||||
])
|
||||
);
|
||||
|
||||
const runtime = createRuntime(dummyCorp, true);
|
||||
const parsed: CliParsedArgs = { area: "keys", options: { json: true }, args: [], raw: ["keys", "--json"] };
|
||||
const res = await handleKeysCommand(parsed, runtime);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
const data = JSON.parse(res.stdout);
|
||||
expect(Array.isArray(data)).toBe(true);
|
||||
expect(data[0].appKey).toBe("json-app-key");
|
||||
// 默认 json 脱敏
|
||||
expect(data[0].appSecurity).toContain("...");
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
test("openapi keys 子命令平滑转发至同一执行器", async () => {
|
||||
const spy = spyOn(storeTools, "fetchOpenApiKeys").mockImplementation(() =>
|
||||
Promise.resolve([
|
||||
{
|
||||
id: "k-1",
|
||||
name: "OpenAPI子命令测试",
|
||||
appKey: "sub-app-key",
|
||||
appSecurity: "sub-app-security-123456",
|
||||
active: true,
|
||||
createTime: 1751357077503,
|
||||
updateTime: 1769063905460,
|
||||
},
|
||||
])
|
||||
);
|
||||
|
||||
const runtime = createRuntime(dummyCorp);
|
||||
const parsed: CliParsedArgs = {
|
||||
area: "openapi",
|
||||
action: "keys",
|
||||
options: {},
|
||||
args: [],
|
||||
raw: ["openapi", "keys"],
|
||||
};
|
||||
const res = await handleOpenApiCommand(parsed, runtime);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("OpenAPI子命令测试");
|
||||
expect(res.stdout).toContain("sub-app-key");
|
||||
spy.mockRestore();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
import { fetchOpenApiKeys } from "../../domains/store/tools.js";
|
||||
import { booleanOption } from "../parser.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
|
||||
function formatDate(ts: number): string {
|
||||
if (!ts) return "-";
|
||||
const d = new Date(ts);
|
||||
if (isNaN(d.getTime())) return "-";
|
||||
const Y = d.getFullYear();
|
||||
const M = String(d.getMonth() + 1).padStart(2, "0");
|
||||
const D = String(d.getDate()).padStart(2, "0");
|
||||
const h = String(d.getHours()).padStart(2, "0");
|
||||
const m = String(d.getMinutes()).padStart(2, "0");
|
||||
return `${Y}/${M}/${D} ${h}:${m}`;
|
||||
}
|
||||
|
||||
function maskSecret(secret: string): string {
|
||||
if (!secret) return "-";
|
||||
if (secret.length <= 12) return "******";
|
||||
return `${secret.slice(0, 8)}...${secret.slice(-4)}`;
|
||||
}
|
||||
|
||||
export async function handleKeysCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const currentCorp = runtime.selectedCorp;
|
||||
if (!currentCorp) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const reveal =
|
||||
booleanOption(parsed.options, ["reveal", "r", "plain"]) ||
|
||||
parsed.action === "reveal" ||
|
||||
parsed.args[0] === "reveal";
|
||||
|
||||
try {
|
||||
const keys = await fetchOpenApiKeys(currentCorp);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
const outputData = reveal
|
||||
? keys
|
||||
: keys.map((k) => ({
|
||||
...k,
|
||||
appSecurity: maskSecret(k.appSecurity),
|
||||
}));
|
||||
return {
|
||||
stdout: printJson(outputData, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (keys.length === 0) {
|
||||
return {
|
||||
stdout: `企业 [${currentCorp.name}] 暂未创建 OpenAPI 密钥凭证\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = keys.map((k, i) => [
|
||||
i + 1,
|
||||
k.name || "-",
|
||||
k.appKey,
|
||||
reveal ? k.appSecurity : maskSecret(k.appSecurity),
|
||||
k.active ? "🟢 启用" : "⚪ 停用",
|
||||
formatDate(k.createTime),
|
||||
]);
|
||||
|
||||
const table = printTable(
|
||||
["#", "密钥备注", "接入账号 (appKey)", "接入密码 (appSecurity)", "状态", "创建时间"],
|
||||
rows
|
||||
);
|
||||
|
||||
const title = `====== [${currentCorp.name}] 企业 OpenAPI 接入密钥列表 (共 ${keys.length} 个) ======`;
|
||||
const hint = reveal
|
||||
? ""
|
||||
: "\n提示: 接入密码默认脱敏,附加 --reveal (或 -r) 可查看完整明文;使用 --json 可输出完整结构。\n";
|
||||
|
||||
return {
|
||||
stdout: `${title}\n\n${table}\n${hint}`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
} catch (err: any) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `获取企业 OpenAPI 密钥失败: ${err?.message || err}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
import { describe, it, expect, spyOn } from "bun:test";
|
||||
import { handleMenuCommand } from "./menu.js";
|
||||
import * as menuTools from "../../domains/menu/tools.js";
|
||||
import type { CliRuntime } from "../types.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
|
||||
describe("cli/commands/menu > handleMenuCommand", () => {
|
||||
const dummyRuntimeNoCorp: CliRuntime = {
|
||||
corpContext: {
|
||||
listCorps: () => [],
|
||||
getCurrent: () => null,
|
||||
switchCorp: () => false,
|
||||
resolve: () => null,
|
||||
} as any,
|
||||
selectedCorp: null,
|
||||
jsonMode: false,
|
||||
};
|
||||
|
||||
const mockCorp: CorpConfig = {
|
||||
id: "corp123",
|
||||
name: "转转二手交易网",
|
||||
source: "account",
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
credentials: {
|
||||
accessToken: "mock-token",
|
||||
corpId: "corp123",
|
||||
staffId: "mock-staff",
|
||||
},
|
||||
};
|
||||
|
||||
const dummyRuntimeWithCorp: CliRuntime = {
|
||||
corpContext: {
|
||||
listCorps: () => [mockCorp],
|
||||
getCurrent: () => mockCorp,
|
||||
switchCorp: () => true,
|
||||
resolve: () => mockCorp,
|
||||
} as any,
|
||||
selectedCorp: mockCorp,
|
||||
jsonMode: false,
|
||||
};
|
||||
|
||||
it("fails with exitCode 1 when no corp is selected", async () => {
|
||||
const res = await handleMenuCommand(
|
||||
{
|
||||
area: "menu",
|
||||
action: "list",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["menu", "list"],
|
||||
},
|
||||
dummyRuntimeNoCorp
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(1);
|
||||
expect(res.stderr).toContain("未选中企业");
|
||||
});
|
||||
|
||||
it("lists desktop menus in table format", async () => {
|
||||
const mockMenus = [
|
||||
{
|
||||
id: "newHomePage",
|
||||
label: "首页",
|
||||
appId: "100-home",
|
||||
href: "/home",
|
||||
children: [],
|
||||
},
|
||||
{
|
||||
id: "dataLink",
|
||||
label: "应用管理",
|
||||
appId: "160-datalink-platform",
|
||||
href: "/datalink",
|
||||
children: [
|
||||
{ id: "sub1", label: "用车补贴" },
|
||||
{ id: "sub2", label: "用车制度" },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const spy = spyOn(menuTools, "fetchDesktopMenus").mockResolvedValue(mockMenus as any);
|
||||
|
||||
const res = await handleMenuCommand(
|
||||
{
|
||||
area: "menu",
|
||||
action: "list",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["menu", "list"],
|
||||
},
|
||||
dummyRuntimeWithCorp
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("桌面端主框架导航与模块列表");
|
||||
expect(res.stdout).toContain("首页");
|
||||
expect(res.stdout).toContain("应用管理");
|
||||
expect(res.stdout).toContain("160-datalink-platform");
|
||||
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it("supports --json output for menu list", async () => {
|
||||
const mockMenus = [
|
||||
{
|
||||
id: "newHomePage",
|
||||
label: "首页",
|
||||
appId: "100-home",
|
||||
href: "/home",
|
||||
},
|
||||
];
|
||||
|
||||
const spy = spyOn(menuTools, "fetchDesktopMenus").mockResolvedValue(mockMenus as any);
|
||||
|
||||
const jsonRuntime = { ...dummyRuntimeWithCorp, jsonMode: true };
|
||||
const res = await handleMenuCommand(
|
||||
{
|
||||
area: "menu",
|
||||
action: "list",
|
||||
args: [],
|
||||
options: { json: true },
|
||||
raw: ["menu", "list", "--json"],
|
||||
},
|
||||
jsonRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
const parsed = JSON.parse(res.stdout);
|
||||
expect(parsed.count).toBe(1);
|
||||
expect(parsed.menus[0].id).toBe("newHomePage");
|
||||
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it("delegates menu apps to handleAppCommand", async () => {
|
||||
const mockApps = [
|
||||
{
|
||||
id: "SCGY:corp123",
|
||||
name: "用车补贴",
|
||||
code: "dataLinkItem",
|
||||
href: "/third-party-item/SCGY:corp123",
|
||||
},
|
||||
];
|
||||
|
||||
const spy = spyOn(menuTools, "fetchWorkbenchAppsList").mockResolvedValue(mockApps as any);
|
||||
|
||||
const res = await handleMenuCommand(
|
||||
{
|
||||
area: "menu",
|
||||
action: "apps",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["menu", "apps"],
|
||||
},
|
||||
dummyRuntimeWithCorp
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("工作台应用管理列表");
|
||||
expect(res.stdout).toContain("用车补贴");
|
||||
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it("returns error for unknown menu subcommand", async () => {
|
||||
const res = await handleMenuCommand(
|
||||
{
|
||||
area: "menu",
|
||||
action: "badsub",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["menu", "badsub"],
|
||||
},
|
||||
dummyRuntimeWithCorp
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(1);
|
||||
expect(res.stderr).toContain("未知 menu 子命令");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
import { fetchDesktopMenus } from "../../domains/menu/tools.js";
|
||||
import { handleAppCommand } from "./app.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
|
||||
export async function handleMenuCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
if (!runtime.selectedCorp) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const action = parsed.action || "list";
|
||||
|
||||
switch (action) {
|
||||
case "apps":
|
||||
case "workbench":
|
||||
return handleAppCommand(parsed, runtime);
|
||||
|
||||
case "list":
|
||||
case "ls":
|
||||
case "tree": {
|
||||
const items = await fetchDesktopMenus(runtime.selectedCorp);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId: runtime.selectedCorp.credentials.corpId,
|
||||
corpName: runtime.selectedCorp.name,
|
||||
count: items.length,
|
||||
menus: items,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const headers = ["#", "模块 ID", "导航名称", "模块标识 (appId)", "子菜单数", "默认路由"];
|
||||
const rows = items.map((m, i) => [
|
||||
i + 1,
|
||||
m.id,
|
||||
m.label,
|
||||
m.appId || "-",
|
||||
m.children?.length || 0,
|
||||
m.href || "-",
|
||||
]);
|
||||
|
||||
const title = `====== [${runtime.selectedCorp.name}] 桌面端主框架导航与模块列表 (共 ${items.length} 个一级导航) ======\n`;
|
||||
return {
|
||||
stdout: title + printTable(headers, rows) + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 menu 子命令: ${action}。支持: list, tree, apps\n用法: hose-use menu list\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -2,18 +2,24 @@ import { getOpenApiSchema, listOpenApiPaths, type OpenApiType } from "../../core
|
||||
import { booleanOption, stringOption } from "../parser.js";
|
||||
import { printJson, printKeyValue, printTable } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { handleKeysCommand } from "./keys.js";
|
||||
|
||||
export async function handleOpenApiCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const action = parsed.action?.toLowerCase();
|
||||
|
||||
if (action === "keys" || action === "key") {
|
||||
return handleKeysCommand(parsed, runtime);
|
||||
}
|
||||
|
||||
const isRaw =
|
||||
booleanOption(parsed.options, ["raw"]) ||
|
||||
parsed.action === "raw" ||
|
||||
parsed.args[0] === "raw";
|
||||
|
||||
const type: OpenApiType = isRaw ? "raw" : "wrapped";
|
||||
const action = parsed.action?.toLowerCase();
|
||||
|
||||
switch (action) {
|
||||
case "paths":
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
import { describe, expect, it, spyOn, afterEach } from "bun:test";
|
||||
import { handlePlatformCommand } from "./platform.js";
|
||||
import * as api from "../../domains/datalink/api.js";
|
||||
import * as services from "../../domains/datalink/services.js";
|
||||
import * as helpers from "../helpers.js";
|
||||
import type { CliRuntime } from "../types.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
|
||||
describe("CLI - platform 命令与 record 动作", () => {
|
||||
let spies: ReturnType<typeof spyOn>[] = [];
|
||||
afterEach(() => {
|
||||
for (const spy of spies) {
|
||||
spy.mockRestore();
|
||||
}
|
||||
spies = [];
|
||||
});
|
||||
const mockCorp: CorpConfig = {
|
||||
id: "corp-1",
|
||||
name: "测试企业",
|
||||
source: "account",
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
credentials: {
|
||||
accessToken: "mock-token",
|
||||
corpId: "corp-1",
|
||||
staffId: "staff-1",
|
||||
},
|
||||
};
|
||||
|
||||
const dummyRuntime: CliRuntime = {
|
||||
corpContext: {
|
||||
listCorps: () => [mockCorp],
|
||||
getCurrent: () => mockCorp,
|
||||
switchCorp: () => true,
|
||||
resolve: () => mockCorp,
|
||||
} as any,
|
||||
selectedCorp: mockCorp,
|
||||
jsonMode: false,
|
||||
};
|
||||
|
||||
const mockPlatform = {
|
||||
id: "platform-1",
|
||||
name: "项目台账",
|
||||
code: "PJ",
|
||||
active: true,
|
||||
adminIds: ["staff-1"],
|
||||
staffIds: [],
|
||||
roleIds: [],
|
||||
departmentIds: [],
|
||||
departmentsIncludeChildren: false,
|
||||
};
|
||||
|
||||
const mockEntity = {
|
||||
id: "entity-1",
|
||||
name: "项目",
|
||||
code: "PROJECT",
|
||||
type: "DIMENSION",
|
||||
active: true,
|
||||
fields: [
|
||||
{ name: "code", label: "编码", type: "text" },
|
||||
{ name: "name", label: "名称", type: "text" },
|
||||
{ name: "customField", label: "自定义字段", type: "text" },
|
||||
],
|
||||
actions: [],
|
||||
importMethod: [],
|
||||
};
|
||||
|
||||
it("未选中企业时报错并返回 exitCode 1", async () => {
|
||||
const res = await handlePlatformCommand(
|
||||
{ area: "platform", action: "list", args: [], options: {}, raw: [] },
|
||||
{ ...dummyRuntime, selectedCorp: null }
|
||||
);
|
||||
expect(res.exitCode).toBe(1);
|
||||
expect(res.stderr).toContain("未选中企业");
|
||||
});
|
||||
|
||||
it("records 正确解析嵌套 dataLink 的停启用状态和更新时间", async () => {
|
||||
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
|
||||
spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any));
|
||||
spies.push(spyOn(api, "searchEntityRecords").mockResolvedValue({
|
||||
total: 2,
|
||||
data: [
|
||||
{
|
||||
id: "r-1",
|
||||
dataLink: { id: "r-1", name: "项目1", code: "P1", active: false, updateTime: "2026-09-09" },
|
||||
},
|
||||
{
|
||||
id: "r-2",
|
||||
dataLink: { id: "r-2", name: "项目2", code: "P2", active: true, updateTime: "2026-09-09" },
|
||||
},
|
||||
],
|
||||
actions: [],
|
||||
components: [],
|
||||
path: null,
|
||||
template: null,
|
||||
}));
|
||||
|
||||
const res = await handlePlatformCommand(
|
||||
{ area: "platform", action: "records", args: ["platform-1", "entity-1"], options: {}, raw: [] },
|
||||
dummyRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("停用");
|
||||
expect(res.stdout).toContain("启用");
|
||||
});
|
||||
|
||||
it("record get 获取记录详情", async () => {
|
||||
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
|
||||
spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any));
|
||||
spies.push(spyOn(api, "getRecordDetail").mockResolvedValue({
|
||||
dataLink: {
|
||||
id: "r-1",
|
||||
name: "测试项目",
|
||||
code: "P-100",
|
||||
active: true,
|
||||
createTime: 12345678,
|
||||
updateTime: 12345679,
|
||||
form: { customField: "测试值" },
|
||||
},
|
||||
}));
|
||||
|
||||
const res = await handlePlatformCommand(
|
||||
{ area: "platform", action: "record", args: ["get", "platform-1", "entity-1", "r-1"], options: {}, raw: [] },
|
||||
dummyRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("测试项目");
|
||||
expect(res.stdout).toContain("P-100");
|
||||
expect(res.stdout).toContain("测试值");
|
||||
});
|
||||
|
||||
it("record toggle 切换停启用状态", async () => {
|
||||
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
|
||||
spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any));
|
||||
const toggleSpy = spyOn(api, "toggleRecordState").mockResolvedValue({ recordId: "r-1", active: true });
|
||||
spies.push(toggleSpy);
|
||||
|
||||
const res = await handlePlatformCommand(
|
||||
{ area: "platform", action: "record", args: ["toggle", "platform-1", "entity-1", "r-1"], options: {}, raw: [] },
|
||||
dummyRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("状态已成功切换为");
|
||||
expect(toggleSpy).toHaveBeenCalledWith(expect.anything(), "corp-1", "r-1", undefined);
|
||||
});
|
||||
|
||||
it("record edit 编辑字段", async () => {
|
||||
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
|
||||
spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any));
|
||||
const editSpy = spyOn(api, "editRecord").mockResolvedValue({ id: "r-1" } as any);
|
||||
spies.push(editSpy);
|
||||
|
||||
const res = await handlePlatformCommand(
|
||||
{
|
||||
area: "platform",
|
||||
action: "record",
|
||||
args: ["edit", "platform-1", "entity-1", "r-1"],
|
||||
options: { data: '{"name":"更新后的名称"}' },
|
||||
raw: [],
|
||||
},
|
||||
dummyRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("字段更新成功");
|
||||
expect(editSpy).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
"corp-1",
|
||||
expect.objectContaining({
|
||||
dataLinkEntityId: "entity-1",
|
||||
dataLinkId: "r-1",
|
||||
form: { name: "更新后的名称" },
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("record recompute 触发台账重算", async () => {
|
||||
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
|
||||
spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any));
|
||||
const recomputeSpy = spyOn(api, "recomputeRecordLedger").mockResolvedValue({ id: "ok" });
|
||||
spies.push(recomputeSpy);
|
||||
|
||||
const res = await handlePlatformCommand(
|
||||
{ area: "platform", action: "record", args: ["recompute", "platform-1", "entity-1", "r-1"], options: {}, raw: [] },
|
||||
dummyRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("台账重算任务已成功触发");
|
||||
expect(recomputeSpy).toHaveBeenCalledWith(expect.anything(), "corp-1", "r-1");
|
||||
});
|
||||
});
|
||||
+283
-40
@@ -1,64 +1,307 @@
|
||||
import * as api from "../../domains/platform/api.js";
|
||||
import * as api from "../../domains/datalink/api.js";
|
||||
import { buildKeywordFilter, resolveEntity, resolvePlatform, selectRecordFields } from "../../domains/datalink/services.js";
|
||||
import { createClientsForCorp } from "../helpers.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
|
||||
export async function handlePlatformCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const currentCorp = runtime.selectedCorp;
|
||||
if (!currentCorp) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
function requiredTarget(parsed: CliParsedArgs, index: number, usage: string): string {
|
||||
const target = parsed.args[index]?.trim();
|
||||
if (!target) throw new Error(`请提供目标参数: ${usage}`);
|
||||
return target;
|
||||
}
|
||||
|
||||
function splitFields(value?: string): string[] {
|
||||
return value ? value.split(",").map((field) => field.trim()).filter(Boolean) : [];
|
||||
}
|
||||
|
||||
function cell(value: unknown): string {
|
||||
if (value === undefined || value === null) return "";
|
||||
if (typeof value === "object") return JSON.stringify(value);
|
||||
return String(value);
|
||||
}
|
||||
|
||||
async function resolveAppAndEntity(parsed: CliParsedArgs, runtime: CliRuntime, appIndex = 0, entityIndex = 1) {
|
||||
const appTarget = requiredTarget(parsed, appIndex, "hose-use platform <子命令> <应用 ID|名称>");
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const corpId = runtime.selectedCorp!.credentials.corpId;
|
||||
const platform = await resolvePlatform(clients.ekbClient, corpId, appTarget);
|
||||
if (!platform) throw new Error(`[NOT FOUND] 当前企业下未找到自建应用: ${appTarget}`);
|
||||
|
||||
const entityTarget = parsed.args[entityIndex]?.trim();
|
||||
if (!entityTarget) return { clients, corpId, platform, entity: undefined };
|
||||
const entity = await resolveEntity(clients.ekbClient, corpId, platform, entityTarget);
|
||||
if (!entity) throw new Error(`[NOT FOUND] 应用 [${platform.name}] 下未找到业务对象: ${entityTarget}`);
|
||||
return { clients, corpId, platform, entity };
|
||||
}
|
||||
|
||||
export async function handlePlatformCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
if (!runtime.selectedCorp) {
|
||||
return { stdout: "", stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n", exitCode: 1 };
|
||||
}
|
||||
|
||||
const action = parsed.action || "list";
|
||||
const isWorkbench = action === "workbench" || booleanOption(parsed.options, ["workbench", "w"], false);
|
||||
if (isWorkbench) {
|
||||
const { handleAppCommand } = await import("./app.js");
|
||||
return handleAppCommand(parsed, runtime);
|
||||
}
|
||||
|
||||
switch (action) {
|
||||
case "list":
|
||||
case "ls":
|
||||
return handleList(parsed, runtime);
|
||||
case "apps": return handleList(parsed, runtime);
|
||||
case "get":
|
||||
case "show": return handleGet(parsed, runtime);
|
||||
case "entities":
|
||||
case "objects": return handleEntities(parsed, runtime);
|
||||
case "schema":
|
||||
case "fields": return handleSchema(parsed, runtime);
|
||||
case "records":
|
||||
case "data":
|
||||
case "search": return handleRecords(parsed, runtime);
|
||||
case "record":
|
||||
case "record-get":
|
||||
case "record-toggle":
|
||||
case "record-edit":
|
||||
case "record-recompute": return handleRecordAction(parsed, runtime);
|
||||
case "permissions":
|
||||
case "permission":
|
||||
case "auth": return handlePermissions(parsed, runtime);
|
||||
case "imports":
|
||||
case "import-jobs": return handleImports(parsed, runtime);
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 platform 子命令: ${action}。支持: list\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
return { stdout: "", stderr: `未知 platform 子命令: ${action}。支持: list, get, entities, schema, records, record, permissions, imports\n`, exitCode: 1 };
|
||||
}
|
||||
}
|
||||
|
||||
async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const platforms = await api.listPlatforms(clients.ekbClient, runtime.selectedCorp!.credentials.corpId);
|
||||
const isAll = booleanOption(parsed.options, ["all", "a"], false);
|
||||
const platforms = isAll
|
||||
? await api.listAllPlatforms(clients.ekbClient, runtime.selectedCorp!.credentials.corpId)
|
||||
: await api.listPlatforms(clients.ekbClient, runtime.selectedCorp!.credentials.corpId);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(platforms, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
if (runtime.jsonMode) return { stdout: printJson({ count: platforms.length, all: isAll, platforms }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
if (platforms.length === 0) return { stdout: `企业 [${runtime.selectedCorp!.name}] 下暂无自建应用\n`, stderr: "", exitCode: 0 };
|
||||
const rows = platforms.map((p, i) => [i + 1, p.id, p.name, p.code, p.active ? "🟢 已启用" : "⚪ 未启用"]);
|
||||
const label = isAll ? "自建应用与模板全量列表" : "自建应用列表";
|
||||
return { stdout: `====== [${runtime.selectedCorp!.name}] ${label} (共 ${platforms.length} 个) ======\n${printTable(["#", "自建应用 ID", "应用名称", "编码", "状态"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleGet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const { platform } = await resolveAppAndEntity(parsed, runtime);
|
||||
if (runtime.jsonMode) return { stdout: printJson(platform, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `====== 自建应用详情: ${platform.name} ======\n${printTable(["字段", "值"], [
|
||||
["ID", platform.id], ["编码", platform.code], ["状态", platform.active ? "已启用" : "未启用"],
|
||||
["管理员数量", platform.adminIds.length], ["可见人员数量", platform.staffIds.length],
|
||||
["可见角色数量", platform.roleIds.length], ["可见部门数量", platform.departmentIds.length],
|
||||
["包含子部门", platform.departmentsIncludeChildren ? "是" : "否"],
|
||||
])}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleEntities(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const { clients, corpId, platform } = await resolveAppAndEntity(parsed, runtime);
|
||||
const entities = await api.listPlatformEntities(clients.ekbClient, corpId, platform.id);
|
||||
const keyword = stringOption(parsed.options, ["keyword", "q"])?.toLowerCase();
|
||||
const filtered = keyword ? entities.filter((entity) => [entity.id, entity.name, entity.code].some((value) => value.toLowerCase().includes(keyword))) : entities;
|
||||
if (runtime.jsonMode) return { stdout: printJson({ platform, keyword, total: entities.length, count: filtered.length, entities: filtered }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows = filtered.map((entity, i) => [i + 1, entity.id, entity.name, entity.code, entity.fields.length, entity.active ? "🟢 已启用" : "⚪ 未启用"]);
|
||||
return { stdout: `====== 应用 [${platform.name}] 业务对象 (匹配 ${filtered.length} / 共 ${entities.length} 个) ======\n${printTable(["#", "对象 ID", "对象名称", "编码", "字段数", "状态"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleSchema(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime);
|
||||
const entities = resolved.entity ? [resolved.entity] : await api.listPlatformEntities(resolved.clients.ekbClient, resolved.corpId, resolved.platform.id);
|
||||
const fieldKeyword = stringOption(parsed.options, ["keyword", "field", "name"])?.toLowerCase();
|
||||
const output = entities.map((entity) => ({ ...entity, fields: fieldKeyword ? entity.fields.filter((field) => [field.name, field.label, field.type].some((value) => value.toLowerCase().includes(fieldKeyword))) : entity.fields }));
|
||||
if (runtime.jsonMode) return { stdout: printJson({ platform: resolved.platform, count: output.length, entities: output }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows = output.flatMap((entity) => entity.fields.map((field): Array<string | number | boolean | null | undefined> => [entity.name, field.name, field.label, field.type, field.optional === false ? "必填" : "可选", cell(field.entity)]));
|
||||
return { stdout: `====== 应用 [${resolved.platform.name}] 字段定义 ======\n${printTable(["业务对象", "字段名", "显示名", "类型", "必填性", "引用对象"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime);
|
||||
if (!resolved.entity) throw new Error("请提供业务对象 ID、编码或名称: hose-use platform records <应用> <业务对象>");
|
||||
const keyword = stringOption(parsed.options, ["keyword", "q", "query"]);
|
||||
const filterBy = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]) || (keyword ? buildKeywordFilter(keyword) : undefined);
|
||||
const start = numberOption(parsed.options, ["start", "offset"], 0);
|
||||
const count = numberOption(parsed.options, ["count", "limit"], 20);
|
||||
const fields = splitFields(stringOption(parsed.options, ["fields", "select"]));
|
||||
const page = await api.searchEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { start, count, filterBy });
|
||||
const data = fields.length ? page.data.map((item) => selectRecordFields(item, fields, resolved.entity!.fields)) : page.data;
|
||||
const result = { platform: resolved.platform, entity: resolved.entity, query: { start, count, filterBy, fields }, total: page.total, returned: data.length, data };
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const nameField = resolved.entity.fields.find((f) => f.label === "名称" || f.label.includes("名称") || f.name.endsWith("_name"));
|
||||
const codeField = resolved.entity.fields.find((f) => f.label === "编码" || f.label.includes("编码") || f.name.endsWith("_code"));
|
||||
const rows = data.map((item, i): Array<string | number | boolean | null | undefined> => {
|
||||
const source = item.dataLink && typeof item.dataLink === "object" && !Array.isArray(item.dataLink) ? (item.dataLink as Record<string, unknown>) : item;
|
||||
const id = source.id ?? item.id;
|
||||
const active = source.active ?? item.active;
|
||||
const updateTime = source.updateTime ?? item.updateTime;
|
||||
const nameVal = source.name ?? source["名称"] ?? (nameField ? source[nameField.name] : undefined) ?? source[`E_${resolved.entity!.id}_name`];
|
||||
const codeVal = source.code ?? source["编码"] ?? (codeField ? source[codeField.name] : undefined) ?? source[`E_${resolved.entity!.id}_code`];
|
||||
const formattedTime = typeof updateTime === "number" ? new Date(updateTime).toLocaleString("zh-CN", { hour12: false }) : cell(updateTime);
|
||||
return [i + 1, cell(id), cell(nameVal), cell(codeVal), active === false ? "停用" : "启用", formattedTime];
|
||||
});
|
||||
return { stdout: `====== [${resolved.platform.name}] ${resolved.entity.name} 记录 (总数: ${page.total}, 当前: ${data.length}) ======\n${printTable(["#", "记录 ID", "名称", "编码", "状态", "更新时间"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handlePermissions(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime);
|
||||
const appPermission = { adminIds: resolved.platform.adminIds, staffIds: resolved.platform.staffIds, roleIds: resolved.platform.roleIds, departmentIds: resolved.platform.departmentIds, departmentsIncludeChildren: resolved.platform.departmentsIncludeChildren };
|
||||
const result = resolved.entity ? { platform: resolved.platform, entity: resolved.entity, appPermission } : { platform: resolved.platform, appPermission };
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows: Array<Array<string | number | boolean | null | undefined>> = [["应用管理员", resolved.platform.adminIds.length], ["应用可见人员", resolved.platform.staffIds.length], ["应用可见角色", resolved.platform.roleIds.length], ["应用可见部门", resolved.platform.departmentIds.length]];
|
||||
if (resolved.entity) rows.push(["对象可见性", cell(resolved.entity.visibility)], ["首页可见性", cell(resolved.entity.homeVisibility)], ["导出权限", cell(resolved.entity.exportVisibility)], ["数据过滤", cell(resolved.entity.dataFilter)]);
|
||||
return { stdout: `====== 权限信息: ${resolved.platform.name}${resolved.entity ? ` / ${resolved.entity.name}` : ""} ======\n${printTable(["权限项", "值"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleImports(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime);
|
||||
if (!resolved.entity) throw new Error("请提供业务对象 ID、编码或名称: hose-use platform imports <应用> <业务对象>");
|
||||
const [jobs, latestResult] = await Promise.all([
|
||||
api.listImportJobs(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id),
|
||||
api.getImportResult(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id),
|
||||
]);
|
||||
const result = { platform: resolved.platform, entity: resolved.entity, jobs, latestResult };
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `====== 导入任务: ${resolved.platform.name} / ${resolved.entity.name} ======\n${printTable(["#", "任务"], jobs.map((job, i) => [i + 1, cell(job)]))}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const action = parsed.action?.toLowerCase() || "record";
|
||||
let subAction: string;
|
||||
let appIndex: number;
|
||||
let entityIndex: number;
|
||||
let recordIdIndex: number;
|
||||
|
||||
if (action.startsWith("record-")) {
|
||||
subAction = action.replace("record-", "");
|
||||
appIndex = 0;
|
||||
entityIndex = 1;
|
||||
recordIdIndex = 2;
|
||||
} else {
|
||||
const firstArg = parsed.args[0]?.toLowerCase();
|
||||
if (["get", "show", "detail", "toggle", "state", "edit", "update", "recompute", "recalc"].includes(firstArg)) {
|
||||
subAction = firstArg;
|
||||
appIndex = 1;
|
||||
entityIndex = 2;
|
||||
recordIdIndex = 3;
|
||||
} else {
|
||||
subAction = "get";
|
||||
appIndex = 0;
|
||||
entityIndex = 1;
|
||||
recordIdIndex = 2;
|
||||
}
|
||||
}
|
||||
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime, appIndex, entityIndex);
|
||||
if (!resolved.entity) throw new Error("请提供业务对象 ID、编码或名称: hose-use platform record <动作> <应用> <业务对象> <记录ID>");
|
||||
const recordId = requiredTarget(parsed, recordIdIndex, "hose-use platform record <动作> <应用> <业务对象> <记录ID>");
|
||||
|
||||
switch (subAction) {
|
||||
case "get":
|
||||
case "show":
|
||||
case "detail": {
|
||||
const detail = await api.getRecordDetail(resolved.clients.ekbClient, resolved.corpId, recordId);
|
||||
if (runtime.jsonMode) return { stdout: printJson(detail, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const record = ((detail.dataLink ?? (detail as any).data?.dataLink ?? detail) as Record<string, unknown>);
|
||||
const nameField = resolved.entity.fields.find((f) => f.label === "名称" || f.label.includes("名称") || f.name.endsWith("_name"));
|
||||
const codeField = resolved.entity.fields.find((f) => f.label === "编码" || f.label.includes("编码") || f.name.endsWith("_code"));
|
||||
const nameVal = record.name ?? record["名称"] ?? (nameField ? record[nameField.name] : undefined) ?? record[`E_${resolved.entity.id}_name`];
|
||||
const codeVal = record.code ?? record["编码"] ?? (codeField ? record[codeField.name] : undefined) ?? record[`E_${resolved.entity.id}_code`];
|
||||
|
||||
if (platforms.length === 0) {
|
||||
return {
|
||||
stdout: `企业 [${runtime.selectedCorp!.name}] 下暂无自建应用\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
const formatTime = (time: unknown) => typeof time === "number" ? new Date(time).toLocaleString("zh-CN", { hour12: false }) : cell(time);
|
||||
|
||||
const rows = platforms.map((p, i) => [
|
||||
i + 1,
|
||||
p.id,
|
||||
p.name,
|
||||
p.active ? "🟢 已启用" : "⚪ 未启用",
|
||||
]);
|
||||
const rows: Array<Array<string | number | boolean | null | undefined>> = [
|
||||
["记录 ID", cell(record.id ?? recordId)],
|
||||
["业务对象", `${resolved.entity.name} (${resolved.entity.id})`],
|
||||
["名称", cell(nameVal)],
|
||||
["编码", cell(codeVal)],
|
||||
["状态", record.active === false ? "🔴 停用" : "🟢 启用"],
|
||||
["创建时间", formatTime(record.createTime)],
|
||||
["更新时间", formatTime(record.updateTime)],
|
||||
];
|
||||
|
||||
const table = printTable(["#", "自建应用 ID", "应用名称", "状态"], rows);
|
||||
for (const field of resolved.entity.fields) {
|
||||
if (field.name === nameField?.name || field.name === codeField?.name) continue;
|
||||
const val = record[field.name] ?? record[`E_${resolved.entity.id}_${field.name}`] ?? (record.form as Record<string, unknown> | undefined)?.[field.name] ?? record[field.label];
|
||||
if (val !== undefined && val !== null && val !== "") {
|
||||
let displayVal = val;
|
||||
if (field.type === "date" && typeof val === "number") {
|
||||
displayVal = new Date(val).toLocaleDateString("zh-CN");
|
||||
} else if (field.type === "money" && typeof val === "object" && val !== null && "standard" in (val as any)) {
|
||||
displayVal = `${(val as any).standard} ${(val as any).standardStrCode || "CNY"}`;
|
||||
}
|
||||
rows.push([`${field.label} (${field.name})`, cell(displayVal)]);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `====== [${runtime.selectedCorp!.name}] 自建应用列表 (共 ${platforms.length} 个) ======\n${table}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
return {
|
||||
stdout: `====== 记录详情: [${resolved.platform.name}] ${resolved.entity.name} (${recordId}) ======\n${printTable(["字段/属性", "值"], rows)}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
case "toggle":
|
||||
case "state": {
|
||||
const explicitState = parsed.options.state !== undefined
|
||||
? booleanOption(parsed.options, ["state"], true)
|
||||
: parsed.options.active !== undefined
|
||||
? booleanOption(parsed.options, ["active"], true)
|
||||
: undefined;
|
||||
const res = await api.toggleRecordState(resolved.clients.ekbClient, resolved.corpId, recordId, explicitState);
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ success: true, recordId: res.recordId, active: res.active, app: resolved.platform.name, entity: resolved.entity.name }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
const label = res.active ? "🟢 启用" : "🔴 停用";
|
||||
return {
|
||||
stdout: `✅ 应用 [${resolved.platform.name}] 业务对象 [${resolved.entity.name}] 记录 [${recordId}] 状态已成功切换为 [${label}]。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
case "edit":
|
||||
case "update": {
|
||||
const dataStr = stringOption(parsed.options, ["data", "form", "d", "f"]);
|
||||
let form: Record<string, unknown> = {};
|
||||
if (dataStr) {
|
||||
try {
|
||||
form = JSON.parse(dataStr);
|
||||
} catch {
|
||||
throw new Error("提供的 --data 参数不是合法的 JSON 字符串");
|
||||
}
|
||||
}
|
||||
const activeOpt = parsed.options.active !== undefined ? booleanOption(parsed.options, ["active"], true) : undefined;
|
||||
const result = await api.editRecord(resolved.clients.ekbClient, resolved.corpId, {
|
||||
dataLinkEntityId: resolved.entity.id,
|
||||
dataLinkId: recordId,
|
||||
form,
|
||||
active: activeOpt,
|
||||
});
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return {
|
||||
stdout: `✅ 应用 [${resolved.platform.name}] 业务对象 [${resolved.entity.name}] 记录 [${recordId}] 字段更新成功。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
case "recompute":
|
||||
case "recalc": {
|
||||
const result = await api.recomputeRecordLedger(resolved.clients.ekbClient, resolved.corpId, recordId);
|
||||
if (runtime.jsonMode) return { stdout: printJson({ success: true, recordId, result }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return {
|
||||
stdout: `✅ 应用 [${resolved.platform.name}] 业务对象 [${resolved.entity.name}] 记录 [${recordId}] 台账重算任务已成功触发。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
default:
|
||||
throw new Error(`未知 record 动作: ${subAction}。支持: get, toggle, edit, recompute`);
|
||||
}
|
||||
}
|
||||
+47
-32
@@ -1,4 +1,5 @@
|
||||
import { createClientsForCorp } from "../helpers.js";
|
||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||
import { getEasoClient } from "../../core/auth/easo.js";
|
||||
import * as api from "../../domains/platform/api.js";
|
||||
import { printJson, printKeyValue, formatSourceLabel, formatExpiresAt } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
@@ -30,49 +31,63 @@ export async function handleProbeCommand(
|
||||
platformAccess: { status: "pending" },
|
||||
};
|
||||
|
||||
// 1. 独立测试 EKB 主站 Session
|
||||
let ekbClient: Awaited<ReturnType<typeof createEkbClient>> | null = null;
|
||||
try {
|
||||
const clients = await createClientsForCorp(currentCorp);
|
||||
ekbClient = await createEkbClient(currentCorp);
|
||||
const sessionRes = await ekbClient
|
||||
.get("api/account/v2/session")
|
||||
.json<{ value?: { userId?: string; loginStaffId?: string; expTime?: number } }>();
|
||||
|
||||
// 1. 测试 EKB 主站 Session
|
||||
results.ekbSession = {
|
||||
status: "ok",
|
||||
userId: sessionRes.value?.userId,
|
||||
loginStaffId: sessionRes.value?.loginStaffId,
|
||||
expTime: sessionRes.value?.expTime ? new Date(sessionRes.value.expTime).toLocaleString() : undefined,
|
||||
};
|
||||
} catch (e) {
|
||||
results.ekbSession = {
|
||||
status: "error",
|
||||
error: e instanceof Error ? e.message : String(e),
|
||||
};
|
||||
}
|
||||
|
||||
// 2. 独立测试自建应用列表访问
|
||||
let platforms: any[] = [];
|
||||
if (ekbClient) {
|
||||
try {
|
||||
const sessionRes = await clients.ekbClient
|
||||
.get("api/account/v2/session")
|
||||
.json<{ value?: { userId?: string; loginStaffId?: string; expTime?: number } }>();
|
||||
|
||||
results.ekbSession = {
|
||||
status: "ok",
|
||||
userId: sessionRes.value?.userId,
|
||||
loginStaffId: sessionRes.value?.loginStaffId,
|
||||
expTime: sessionRes.value?.expTime ? new Date(sessionRes.value.expTime).toLocaleString() : undefined,
|
||||
};
|
||||
} catch (e) {
|
||||
results.ekbSession = {
|
||||
status: "error",
|
||||
error: e instanceof Error ? e.message : String(e),
|
||||
};
|
||||
}
|
||||
|
||||
// 2. 测试 EASO Token 换取
|
||||
try {
|
||||
const platforms = await api.listPlatforms(clients.ekbClient, currentCorp.credentials.corpId);
|
||||
platforms = await api.listPlatforms(ekbClient, currentCorp.credentials.corpId);
|
||||
results.platformAccess = {
|
||||
status: "ok",
|
||||
totalPlatforms: platforms.length,
|
||||
};
|
||||
|
||||
const stats = await api.getWorkflowStats(clients.easoClient, platforms[0]?.id || "platform");
|
||||
results.easoToken = {
|
||||
status: "ok",
|
||||
message: "EASO 四步换票握手成功",
|
||||
};
|
||||
} catch (e) {
|
||||
results.easoToken = {
|
||||
results.platformAccess = {
|
||||
status: "error",
|
||||
error: e instanceof Error ? e.message : String(e),
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
results.error = error instanceof Error ? error.message : String(error);
|
||||
} else {
|
||||
results.platformAccess = {
|
||||
status: "error",
|
||||
error: "主站客户端未能初始化",
|
||||
};
|
||||
}
|
||||
|
||||
// 3. 独立测试 EASO Token 换取
|
||||
try {
|
||||
const { client: easoClient } = await getEasoClient(currentCorp);
|
||||
const targetPlatformId = platforms[0]?.id || currentCorp.credentials.corpId;
|
||||
await api.getWorkflowStats(easoClient, targetPlatformId);
|
||||
results.easoToken = {
|
||||
status: "ok",
|
||||
message: "EASO 四步换票握手成功",
|
||||
};
|
||||
} catch (e) {
|
||||
results.easoToken = {
|
||||
status: "error",
|
||||
error: e instanceof Error ? e.message : String(e),
|
||||
};
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
import { describe, expect, test, spyOn } from "bun:test";
|
||||
import { handleStoreCommand } from "./store.js";
|
||||
import type { CliRuntime, CliParsedArgs } from "../types.js";
|
||||
import * as storeTools from "../../domains/store/tools.js";
|
||||
|
||||
describe("CLI - store 应用中心与应用商店探查", () => {
|
||||
const dummyCorp: any = {
|
||||
id: "test-corp-id",
|
||||
name: "测试企业A",
|
||||
corpId: "test-corp-id",
|
||||
credentials: { corpId: "test-corp-id", accessToken: "token123" },
|
||||
};
|
||||
|
||||
const createRuntime = (corp: any = dummyCorp, jsonMode = false): CliRuntime => ({
|
||||
corpContext: {} as any,
|
||||
selectedCorp: corp,
|
||||
jsonMode,
|
||||
});
|
||||
|
||||
test("未选中企业时返回提示并报错", async () => {
|
||||
const runtime = createRuntime(null);
|
||||
const parsed: CliParsedArgs = { area: "store", options: {}, args: [], raw: ["store"] };
|
||||
const res = await handleStoreCommand(parsed, runtime);
|
||||
expect(res.exitCode).toBe(1);
|
||||
expect(res.stderr).toContain("未选中企业");
|
||||
});
|
||||
|
||||
test("store list 展示企业已购应用列表", async () => {
|
||||
const spy = spyOn(storeTools, "fetchClientGoods").mockImplementation(() =>
|
||||
Promise.resolve([
|
||||
{
|
||||
id: "g-1",
|
||||
name: "开放接口(新)",
|
||||
status: "OPENED",
|
||||
expireTime: 1914422399000,
|
||||
hasConfig: true,
|
||||
powers: [{ powerCode: "219904", powerName: "开放接口(新)" }],
|
||||
},
|
||||
] as any)
|
||||
);
|
||||
|
||||
const runtime = createRuntime(dummyCorp);
|
||||
const parsed: CliParsedArgs = {
|
||||
area: "store",
|
||||
action: "list",
|
||||
options: {},
|
||||
args: [],
|
||||
raw: ["store", "list"],
|
||||
};
|
||||
const res = await handleStoreCommand(parsed, runtime);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("开放接口(新)");
|
||||
expect(res.stdout).toContain("已开通");
|
||||
expect(res.stdout).toContain("支持配置");
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
test("store search 检索应用市场商品", async () => {
|
||||
const spy = spyOn(storeTools, "searchGoods").mockImplementation(() =>
|
||||
Promise.resolve({
|
||||
total: 1,
|
||||
items: [
|
||||
{
|
||||
id: "g-2",
|
||||
name: "纷享销客基础互联应用",
|
||||
status: "OPENED",
|
||||
summary: "连接纷享销客",
|
||||
},
|
||||
],
|
||||
} as any)
|
||||
);
|
||||
|
||||
const runtime = createRuntime(dummyCorp);
|
||||
const parsed: CliParsedArgs = {
|
||||
area: "store",
|
||||
action: "search",
|
||||
options: {},
|
||||
args: ["纷享"],
|
||||
raw: ["store", "search", "纷享"],
|
||||
};
|
||||
const res = await handleStoreCommand(parsed, runtime);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("纷享销客基础互联应用");
|
||||
expect(res.stdout).toContain("连接纷享销客");
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
test("store get 查看应用详情", async () => {
|
||||
const spy = spyOn(storeTools, "fetchGoodsDetail").mockImplementation(() =>
|
||||
Promise.resolve({
|
||||
id: "g-1",
|
||||
name: "开放接口(新)",
|
||||
status: "OPENED",
|
||||
hasConfig: true,
|
||||
configStyle: "SIDESLIP",
|
||||
powers: [{ powerCode: "219904", powerName: "开放接口(新)" }],
|
||||
summary: "OpenAPI提供标准化接口",
|
||||
} as any)
|
||||
);
|
||||
|
||||
const runtime = createRuntime(dummyCorp);
|
||||
const parsed: CliParsedArgs = {
|
||||
area: "store",
|
||||
action: "get",
|
||||
options: {},
|
||||
args: ["g-1"],
|
||||
raw: ["store", "get", "g-1"],
|
||||
};
|
||||
const res = await handleStoreCommand(parsed, runtime);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("开放接口(新)");
|
||||
expect(res.stdout).toContain("219904");
|
||||
expect(res.stdout).toContain("SIDESLIP");
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
test("store keys 转发至 keys 执行器", async () => {
|
||||
const spy = spyOn(storeTools, "fetchOpenApiKeys").mockImplementation(() =>
|
||||
Promise.resolve([
|
||||
{
|
||||
id: "k-1",
|
||||
name: "Store转发密钥",
|
||||
appKey: "store-key-123",
|
||||
appSecurity: "store-secret-456",
|
||||
active: true,
|
||||
createTime: 1751357077503,
|
||||
updateTime: 1769063905460,
|
||||
},
|
||||
])
|
||||
);
|
||||
|
||||
const runtime = createRuntime(dummyCorp);
|
||||
const parsed: CliParsedArgs = {
|
||||
area: "store",
|
||||
action: "keys",
|
||||
options: {},
|
||||
args: [],
|
||||
raw: ["store", "keys"],
|
||||
};
|
||||
const res = await handleStoreCommand(parsed, runtime);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("Store转发密钥");
|
||||
expect(res.stdout).toContain("store-key-123");
|
||||
spy.mockRestore();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,239 @@
|
||||
import {
|
||||
fetchClientGoods,
|
||||
searchGoods,
|
||||
fetchGoodsDetail,
|
||||
} from "../../domains/store/tools.js";
|
||||
import { booleanOption, stringOption } from "../parser.js";
|
||||
import { printJson, printKeyValue, printTable } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { handleKeysCommand } from "./keys.js";
|
||||
|
||||
function formatDate(ts: number | null | undefined): string {
|
||||
if (!ts) return "长期有效";
|
||||
const d = new Date(ts);
|
||||
if (isNaN(d.getTime())) return "-";
|
||||
const Y = d.getFullYear();
|
||||
const M = String(d.getMonth() + 1).padStart(2, "0");
|
||||
const D = String(d.getDate()).padStart(2, "0");
|
||||
return `${Y}/${M}/${D}`;
|
||||
}
|
||||
|
||||
function formatStatus(status: string | null | undefined): string {
|
||||
if (!status) return "-";
|
||||
switch (status.toUpperCase()) {
|
||||
case "OPENED":
|
||||
return "🟢 已开通";
|
||||
case "EXPIRE":
|
||||
return "🔴 已过期";
|
||||
case "APPLYING":
|
||||
return "🟡 申请中";
|
||||
case "CLOSED":
|
||||
return "⚪ 已关闭";
|
||||
default:
|
||||
return status;
|
||||
}
|
||||
}
|
||||
|
||||
export async function handleStoreCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const currentCorp = runtime.selectedCorp;
|
||||
if (!currentCorp) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const action = (parsed.action || "list").toLowerCase();
|
||||
|
||||
switch (action) {
|
||||
case "keys":
|
||||
case "key":
|
||||
return handleKeysCommand(parsed, runtime);
|
||||
|
||||
case "list":
|
||||
case "ls":
|
||||
return handleList(parsed, runtime);
|
||||
|
||||
case "search":
|
||||
case "find":
|
||||
return handleSearch(parsed, runtime);
|
||||
|
||||
case "get":
|
||||
case "info":
|
||||
case "detail":
|
||||
return handleGet(parsed, runtime);
|
||||
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 store 子命令: ${action}。支持: list, search, get, keys\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const currentCorp = runtime.selectedCorp!;
|
||||
const keyword = parsed.args[0] || stringOption(parsed.options, ["name", "keyword", "k"]);
|
||||
const isAll = booleanOption(parsed.options, ["all", "a"]);
|
||||
|
||||
try {
|
||||
const items = await fetchClientGoods(currentCorp, { keyword, isAll });
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(items, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (items.length === 0) {
|
||||
return {
|
||||
stdout: `企业 [${currentCorp.name}] 暂无匹配的已购应用${keyword ? ` (搜索: ${keyword})` : ""}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = items.map((item, i) => {
|
||||
const powersStr = (item.powers || [])
|
||||
.map((p) => (typeof p === "string" ? p : p.powerName || p.powerCode || ""))
|
||||
.filter(Boolean)
|
||||
.join(", ");
|
||||
|
||||
return [
|
||||
i + 1,
|
||||
item.id,
|
||||
item.name,
|
||||
formatStatus(item.status),
|
||||
formatDate(item.expireTime),
|
||||
item.hasConfig ? "支持配置" : "-",
|
||||
powersStr || "-",
|
||||
];
|
||||
});
|
||||
|
||||
const table = printTable(
|
||||
["#", "应用 ID", "应用名称", "开通状态", "有效期限", "配置支持", "绑定能力 (Powers)"],
|
||||
rows
|
||||
);
|
||||
|
||||
const title = `====== [${currentCorp.name}] 企业已开通/已购应用列表 (共 ${items.length} 个) ======`;
|
||||
|
||||
return {
|
||||
stdout: `${title}\n\n${table}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
} catch (err: any) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `查询企业已购应用失败: ${err?.message || err}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const currentCorp = runtime.selectedCorp!;
|
||||
const keyword = parsed.args[0] || stringOption(parsed.options, ["name", "keyword", "k"]) || "";
|
||||
|
||||
try {
|
||||
const result = await searchGoods(currentCorp, { keyword, count: 20 });
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(result, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (result.items.length === 0) {
|
||||
return {
|
||||
stdout: `应用商店未搜索到匹配应用${keyword ? ` (关键词: ${keyword})` : ""}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = result.items.map((item, i) => [
|
||||
i + 1,
|
||||
item.id,
|
||||
item.name,
|
||||
formatStatus(item.status),
|
||||
item.summary || "-",
|
||||
]);
|
||||
|
||||
const table = printTable(["#", "商品 ID", "应用名称", "企业状态", "应用简介"], rows);
|
||||
const title = `====== 合思应用商店搜索结果 (共 ${result.total} 条,当前展示 ${result.items.length} 条) ======`;
|
||||
|
||||
return {
|
||||
stdout: `${title}\n\n${table}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
} catch (err: any) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `搜索应用商店失败: ${err?.message || err}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function handleGet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const currentCorp = runtime.selectedCorp!;
|
||||
const goodsId = parsed.args[0] || stringOption(parsed.options, ["id"]);
|
||||
|
||||
if (!goodsId) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "请提供应用/商品 ID,例如: hose-use store get O1w2Hg000000qw\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const detail = await fetchGoodsDetail(currentCorp, goodsId);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(detail, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const powersStr = (detail.powers || [])
|
||||
.map((p) => `${p.powerName || p.powerCode || ""} (${p.powerCode || ""})`)
|
||||
.join(", ");
|
||||
|
||||
const out = printKeyValue({
|
||||
"应用 ID": detail.id,
|
||||
"应用名称": detail.name,
|
||||
"应用编码": detail.code || "-",
|
||||
"开通状态": formatStatus(detail.status),
|
||||
"有效期限": formatDate(detail.expireTime),
|
||||
"支持配置": detail.hasConfig ? `是 (${detail.configStyle || "默认"})` : "否",
|
||||
"绑定能力": powersStr || "-",
|
||||
"应用摘要": detail.summary || "-",
|
||||
});
|
||||
|
||||
return {
|
||||
stdout: `====== 应用详情: ${detail.name} ======\n${out}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
} catch (err: any) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `获取应用详情失败: ${err?.message || err}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -4,10 +4,25 @@ import {
|
||||
} from "../../domains/platform/services.js";
|
||||
import * as api from "../../domains/platform/api.js";
|
||||
import { stringOption, numberOption, booleanOption } from "../parser.js";
|
||||
import { createClientsForCorp } from "../helpers.js";
|
||||
import { createClientsForCorp, createPiperClientForCorp } from "../helpers.js";
|
||||
import { printJson, printTable, printKeyValue } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { analyzeWorkflow } from "../../domains/platform/analysis.js";
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { WorkflowDetailSchema } from "../../domains/platform/types.js";
|
||||
import {
|
||||
createWorkflowDraft,
|
||||
beginWorkflowSave,
|
||||
commitWorkflowSave,
|
||||
failWorkflowSave,
|
||||
hasWorkflowVersionConflict,
|
||||
applyWorkflowPathPatch,
|
||||
} from "../../domains/platform/workflow-state.js";
|
||||
import { WorkflowAlertStore } from "../../domains/platform/workflow-alert-store.js";
|
||||
|
||||
const WORKFLOW_STATE_DIR = process.env.HOSE_STATE_DIR || join(homedir(), ".config", "hose-use");
|
||||
|
||||
export async function handleWorkflowCommand(
|
||||
parsed: CliParsedArgs,
|
||||
@@ -38,23 +53,165 @@ export async function handleWorkflowCommand(
|
||||
return handleFind(parsed, runtime);
|
||||
case "toggle":
|
||||
return handleToggle(parsed, runtime);
|
||||
case "publish":
|
||||
case "enable":
|
||||
return handlePublish(parsed, runtime);
|
||||
case "save":
|
||||
case "update":
|
||||
return handleSave(parsed, runtime);
|
||||
case "patch":
|
||||
return handlePatch(parsed, runtime);
|
||||
case "history":
|
||||
case "snapshots":
|
||||
return handleHistory(parsed, runtime);
|
||||
case "logs":
|
||||
case "log":
|
||||
return handleLogs(parsed, runtime);
|
||||
case "check":
|
||||
case "health":
|
||||
return handleCheck(parsed, runtime);
|
||||
case "analyze":
|
||||
case "analyse":
|
||||
return handleAnalyze(parsed, runtime);
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, toggle\n`,
|
||||
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, history, logs, check\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function handlePatch(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
const file = stringOption(parsed.options, ["file", "input", "from"]);
|
||||
const path = stringOption(parsed.options, ["path", "field"]);
|
||||
const rawValue = parsed.options.value;
|
||||
const output = stringOption(parsed.options, ["output", "output-file", "outputFile"]);
|
||||
const inPlace = booleanOption(parsed.options, ["in-place", "inPlace"]);
|
||||
if (!pipelineId || !file || !path || typeof rawValue !== "string" || (!output && !inPlace)) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use workflow patch <pipelineId> --file=<workflow.json> --path=<tasks.0.code> --value=<值> (--output=<patched.json>|--in-place) [--value-json]\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
let source: unknown;
|
||||
try {
|
||||
source = JSON.parse(readFileSync(file, "utf8"));
|
||||
} catch (error) {
|
||||
throw new Error(`无法读取工作流 JSON 文件 [${file}]: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
const sourceWorkflow = WorkflowDetailSchema.parse(source);
|
||||
if (sourceWorkflow.id !== pipelineId) {
|
||||
throw new Error(`工作流 ID 不匹配:参数为 [${pipelineId}],文件中为 [${sourceWorkflow.id}]`);
|
||||
}
|
||||
|
||||
let value: unknown = rawValue;
|
||||
if (booleanOption(parsed.options, ["value-json", "valueJson"])) {
|
||||
try {
|
||||
value = JSON.parse(rawValue);
|
||||
} catch (error) {
|
||||
throw new Error(`--value-json 不是合法 JSON: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
}
|
||||
const patched = applyWorkflowPathPatch(sourceWorkflow, path, value);
|
||||
const target = inPlace ? file : output!;
|
||||
writeFileSync(target, `${JSON.stringify(patched, null, 2)}\n`, "utf8");
|
||||
const result = { success: true, pipelineId, path, output: target, tasksVersion: patched.tasksVersion };
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `✅ 已生成工作流草稿 [${target}],修改路径: ${path}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
const file = stringOption(parsed.options, ["file", "input", "from"]);
|
||||
if (!pipelineId || !file) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use workflow save <pipelineId> --file=<workflow.json> [--force-write]\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
let draftWorkflow: unknown;
|
||||
try {
|
||||
draftWorkflow = JSON.parse(readFileSync(file, "utf8"));
|
||||
} catch (error) {
|
||||
throw new Error(`无法读取工作流 JSON 文件 [${file}]: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
|
||||
const parsedWorkflow = WorkflowDetailSchema.parse(draftWorkflow);
|
||||
if (parsedWorkflow.id !== pipelineId) {
|
||||
throw new Error(`工作流 ID 不匹配:参数为 [${pipelineId}],文件中为 [${parsedWorkflow.id}]`);
|
||||
}
|
||||
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const platformId = await resolveWorkflowPlatformId(parsed, clients, pipelineId);
|
||||
const piperClient = await createPiperClientForCorp(runtime.selectedCorp!, platformId);
|
||||
const remote = await api.getWorkflowDetail(piperClient, pipelineId);
|
||||
let state = createWorkflowDraft(parsedWorkflow);
|
||||
state = {
|
||||
...state,
|
||||
revision: 1,
|
||||
status: "dirty",
|
||||
dirtyPaths: ["*"],
|
||||
};
|
||||
|
||||
const forceWrite = booleanOption(parsed.options, ["force-write", "forceWrite"]);
|
||||
if (!forceWrite && hasWorkflowVersionConflict(state, remote)) {
|
||||
throw new Error(
|
||||
`工作流版本已变化,拒绝覆盖:远端 tasksVersion=${remote.tasksVersion}, 文件 tasksVersion=${parsedWorkflow.tasksVersion}。确认来源后使用 --force-write。`
|
||||
);
|
||||
}
|
||||
|
||||
state = beginWorkflowSave(state);
|
||||
try {
|
||||
const payload = state.workflow.inputs?.length
|
||||
? state.workflow
|
||||
: { ...state.workflow, inputs: [{ key: "$platformId", value: platformId }] };
|
||||
const saved = await api.updateWorkflow(piperClient, payload);
|
||||
state = commitWorkflowSave(state, saved);
|
||||
const result = {
|
||||
success: true,
|
||||
pipelineId,
|
||||
status: state.status,
|
||||
tasksVersion: saved.tasksVersion,
|
||||
updateTime: saved.updateTime,
|
||||
};
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return {
|
||||
stdout: `✅ 工作流 [${pipelineId}] 草稿保存成功,tasksVersion=${saved.tasksVersion}。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
} catch (error) {
|
||||
state = failWorkflowSave(state, error);
|
||||
throw new Error(`工作流保存失败(${state.status}): ${state.error}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveWorkflowPlatformId(
|
||||
parsed: CliParsedArgs,
|
||||
clients: Awaited<ReturnType<typeof createClientsForCorp>>,
|
||||
pipelineId: string
|
||||
): Promise<string> {
|
||||
const explicit = stringOption(parsed.options, ["platform-id", "platformId"]);
|
||||
if (explicit) return explicit;
|
||||
const all = await listAllWorkflows(clients, { page: 1, pageSize: 100 });
|
||||
const match = all.workflows.find((workflow) => workflow.id === pipelineId);
|
||||
if (!match?.platformId) {
|
||||
throw new Error(`无法确定工作流 [${pipelineId}] 所属自建应用,请使用 --platform-id=<platformId>`);
|
||||
}
|
||||
return match.platformId;
|
||||
}
|
||||
|
||||
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-use workflow analyze <pipelineId>\n", exitCode: 1 };
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const detail = await api.getWorkflowDetail(clients.easoClient, pipelineId);
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const detail = await api.getWorkflowDetail(client, pipelineId);
|
||||
const result = analyzeWorkflow(detail);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const diagnosticRows = result.diagnostics.map((item) => [item.severity, item.code, item.path, item.message]);
|
||||
@@ -67,6 +224,89 @@ async function handleAnalyze(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
||||
].join("\n"), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleHistory(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow history <pipelineId> [--page=1] [--page-size=10]\n", exitCode: 1 };
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const page = numberOption(parsed.options, ["page"]) || 1;
|
||||
const pageSize = numberOption(parsed.options, ["page-size", "pageSize", "size"]) || 10;
|
||||
const result = await api.listWorkflowSnapshots(client, pipelineId, page, pageSize);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows = result.items.map((snapshot, index) => [
|
||||
(page - 1) * pageSize + index + 1,
|
||||
snapshot.version,
|
||||
snapshot.id,
|
||||
snapshot.updateTime,
|
||||
snapshot.staffName || snapshot.staffId || "-",
|
||||
]);
|
||||
return {
|
||||
stdout: `====== 工作流版本历史 [${pipelineId}](共 ${result.totalItems} 个) ======\n${printTable(["#", "版本", "快照 ID", "更新时间", "操作者"], rows)}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleLogs(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow logs <pipelineId> [--state=FAILED] [--start-time=YYYY-MM-DD] [--end-time=YYYY-MM-DD]\n", exitCode: 1 };
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const result = await api.listWorkflowLogs(client, pipelineId, {
|
||||
state: stringOption(parsed.options, ["state"]),
|
||||
page: numberOption(parsed.options, ["page"]),
|
||||
pageSize: numberOption(parsed.options, ["page-size", "pageSize", "size"]),
|
||||
startTime: stringOption(parsed.options, ["start-time", "startTime"]),
|
||||
endTime: stringOption(parsed.options, ["end-time", "endTime"]),
|
||||
});
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `====== 工作流运行日志 [${pipelineId}] ======\n${printKeyValue({ "执行次数": result.executeCount, "成功次数": result.successCount, "错误次数": result.errorCount, "日志条数": result.totalItems, "运行记录": result.jobList.length })}\n${printJson(result, runtime.outputOptions)}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleCheck(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const result = await listAllWorkflows(clients, { page: 1, pageSize: numberOption(parsed.options, ["page-size", "pageSize", "size"]) || 100 });
|
||||
const observedAt = Date.now();
|
||||
const logResults = await Promise.all(result.workflows.map(async (workflow) => {
|
||||
try {
|
||||
const piperClient = await createPiperClientForCorp(runtime.selectedCorp!, workflow.platformId);
|
||||
const log = await api.listWorkflowLogs(piperClient, workflow.id, { page: 1, pageSize: 1 });
|
||||
return { workflow, errorCount: log.errorCount };
|
||||
} catch (error) {
|
||||
return { workflow, errorCount: workflow.errorCount, error: error instanceof Error ? error.message : String(error) };
|
||||
}
|
||||
}));
|
||||
const logErrors = logResults.filter((item): item is typeof item & { error: string } => Boolean(item.error)).map((item) => ({ platformId: item.workflow.platformId, platformName: item.workflow.platformName, error: item.error }));
|
||||
const activeAlerts = logResults
|
||||
.filter(({ errorCount }) => errorCount > 0)
|
||||
.map(({ workflow, errorCount }) => ({
|
||||
id: `${runtime.selectedCorp!.id}:${workflow.platformId}:${workflow.id}`,
|
||||
pipelineId: workflow.id,
|
||||
platformId: workflow.platformId,
|
||||
pipelineName: workflow.pipelineName,
|
||||
errorCount,
|
||||
state: workflow.state,
|
||||
observedAt,
|
||||
}));
|
||||
const stateFile = stringOption(parsed.options, ["state-file", "stateFile"]) || join(WORKFLOW_STATE_DIR, `workflow-alerts-${runtime.selectedCorp!.id}.json`);
|
||||
const check = new WorkflowAlertStore(stateFile).observe(activeAlerts);
|
||||
const output = { corpId: runtime.selectedCorp!.id, observedAt, stateFile, activeAlerts: check.activeAlerts, newAlerts: check.newAlerts, scanErrors: [...result.errors, ...logErrors] };
|
||||
if (runtime.jsonMode) return { stdout: printJson(output, runtime.outputOptions), stderr: "", exitCode: booleanOption(parsed.options, ["fail-on-alert", "failOnAlert"]) && check.newAlerts.length > 0 ? 2 : 0 };
|
||||
const rows = check.activeAlerts.map((alert) => [alert.pipelineId, alert.pipelineName || "-", alert.errorCount, alert.state === 1 ? "启用" : "停用", check.newAlerts.some((item) => item.id === alert.id) ? "🔔 新提醒" : "已记录"]);
|
||||
const warning = check.newAlerts.length ? `\n🔔 新错误管道提醒 ${check.newAlerts.length} 条` : "\n暂无新的错误管道提醒";
|
||||
const scanErrorCount = result.errors.length + logErrors.length;
|
||||
const scanWarning = scanErrorCount ? `\n⚠️ 工作流扫描失败 ${scanErrorCount} 个` : "";
|
||||
return { stdout: `====== 工作流健康检查 [${runtime.selectedCorp!.name}] ======\n${rows.length ? printTable(["工作流 ID", "名称", "错误次数", "状态", "提醒"], rows) : "未发现错误管道"}${warning}${scanWarning}\n状态文件: ${stateFile}\n`, stderr: "", exitCode: booleanOption(parsed.options, ["fail-on-alert", "failOnAlert"]) && check.newAlerts.length > 0 ? 2 : 0 };
|
||||
}
|
||||
|
||||
async function handlePublish(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow publish <pipelineId>\n", exitCode: 1 };
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const result = await api.toggleWorkflow(client, pipelineId, 1);
|
||||
const output = { success: result.success, pipelineId, published: result.success, state: 1 };
|
||||
if (runtime.jsonMode) return { stdout: printJson(output, runtime.outputOptions), stderr: "", exitCode: result.success ? 0 : 1 };
|
||||
return { stdout: result.success ? `✅ 工作流 [${pipelineId}] 已发布并启用。\n` : `❌ 工作流 [${pipelineId}] 发布失败。\n`, stderr: "", exitCode: result.success ? 0 : 1 };
|
||||
}
|
||||
|
||||
async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const page = numberOption(parsed.options, ["page"]) || 1;
|
||||
@@ -113,8 +353,8 @@ async function handleGet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<Cl
|
||||
return { stdout: "", stderr: "用法: hose-use workflow get <pipelineId>\n", exitCode: 1 };
|
||||
}
|
||||
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const detail = await api.getWorkflowDetail(clients.easoClient, pipelineId);
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const detail = await api.getWorkflowDetail(client, pipelineId);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(detail, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
@@ -147,6 +387,21 @@ async function handleGet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<Cl
|
||||
};
|
||||
}
|
||||
|
||||
async function createWorkflowDetailClient(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime,
|
||||
pipelineId: string,
|
||||
): Promise<{ client: Awaited<ReturnType<typeof createPiperClientForCorp>> }> {
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const explicit = stringOption(parsed.options, ["platform-id", "platformId"]);
|
||||
let platformId = explicit;
|
||||
if (!platformId) {
|
||||
const all = await listAllWorkflows(clients, { page: 1, pageSize: 100 });
|
||||
platformId = all.workflows.find((workflow) => workflow.id === pipelineId)?.platformId;
|
||||
}
|
||||
return { client: platformId ? await createPiperClientForCorp(runtime.selectedCorp!, platformId) : clients.easoClient };
|
||||
}
|
||||
|
||||
async function handleFind(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const taskType = stringOption(parsed.options, ["task", "taskType", "type"]) || parsed.args[0];
|
||||
if (!taskType) {
|
||||
@@ -213,8 +468,8 @@ async function handleToggle(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
}
|
||||
|
||||
const state = (stateArg === "1" || stateArg === "true" ? 1 : 0) as 0 | 1;
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const result = await api.toggleWorkflow(clients.easoClient, pipelineId, state);
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const result = await api.toggleWorkflow(client, pipelineId, state);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
|
||||
@@ -4,6 +4,7 @@ import { CorpContext, resolveCorpConfig } from "../core/config/manager.js";
|
||||
import { CorpConfig } from "../core/config/types.js";
|
||||
import { createEkbClient } from "../core/auth/ekb.js";
|
||||
import { getEasoClient } from "../core/auth/easo.js";
|
||||
import { getPiperClient } from "../core/auth/piper.js";
|
||||
import { CliRuntime, OutputOptions } from "./types.js";
|
||||
|
||||
export function initCorpRuntime(
|
||||
@@ -64,6 +65,10 @@ export async function createClientsForCorp(corp: CorpConfig) {
|
||||
};
|
||||
}
|
||||
|
||||
export async function createPiperClientForCorp(corp: CorpConfig, platformId: string) {
|
||||
return getPiperClient(corp, platformId);
|
||||
}
|
||||
|
||||
export function prompt(question: string): Promise<string> {
|
||||
const rl = readline.createInterface({
|
||||
input: process.stdin,
|
||||
|
||||
+35
-6
@@ -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,16 +117,22 @@ export function printHelp(): string {
|
||||
hose-use <命令域> <子命令> [参数] [选项]
|
||||
|
||||
核心命令域:
|
||||
auth 认证与凭证管理 (login, status, refresh, import, accounts)
|
||||
corps 多企业租户管理 (list, switch, current)
|
||||
context 查看全局运行上下文与身份诊断 (context, status, whoami, env)
|
||||
auth 认证与凭证管理 (login, status, refresh, import, accounts, switch-account)
|
||||
corps 多企业租户管理 (list, search <关键词>, switch, current, add-link)
|
||||
aipro 合思 AI PRO 确定性审批仲裁网关入口 (status, scopes, bind, checklist, review, decide, logs)
|
||||
config 全局运行模式与路径诊断 (show, paths, mode <stateful|stateless>, set)
|
||||
workflow 工作流管理 (list, get, find, analyze, toggle)
|
||||
workflow 工作流管理 (list, get, find, analyze, toggle, publish, patch, save, history, logs, check)
|
||||
bill 单据检索与审批动作 (list, get <单号|ID> [--risk], approve|reject|transfer|add-node|comment <单号|ID> [选项], refs, relations, attachments, download, flow, risk, budget, schema, link)
|
||||
contact 企业通讯录与人员检索 (list, search <关键词>, get <staffId>)
|
||||
task 待办中心与审批任务 (todo, approved, records, submitted, cc)
|
||||
message 消息中心与通知管理 (list, count, read, read-all)
|
||||
platform 自建应用管理 (list)
|
||||
app 应用管理 (桌面端工作台业务应用: list [--keyword], get <应用ID|名称>)
|
||||
menu 桌面端主导航菜单树与模块 (list, tree, apps)
|
||||
platform 自建应用与数据模型 (开放平台业务对象、字段与底层记录: list, get, entities, schema, records, permissions, imports)
|
||||
datalink platform 的同义入口,面向 DataLink 业务对象查询
|
||||
dimension 系统/自定义档案维度 (list, items <维度>)
|
||||
feetype 费用类型管理与字段规格配置 (list, get, create, update, disable, enable, move, fields)
|
||||
role 角色定义与成员 (list, groups, members <角色>)
|
||||
permission 权限模型快照 (get)
|
||||
rule 本地 AI 审批规约管理 (scopes, scope <索引号|场景>, list, get, add, delete)
|
||||
@@ -132,7 +140,9 @@ export function printHelp(): string {
|
||||
skill Agent Skill 管理 (install, status, dump)
|
||||
probe 连通性诊断 (probe [corpId])
|
||||
update 版本自更新与发布记录 (update, update check, update --changelog, --github, --gitea, --repo=<owner/repo>)
|
||||
openapi OpenAPI 3.1.0 规范导出 (openapi, openapi --raw, openapi paths, openapi info)
|
||||
openapi OpenAPI 3.1.0 规范导出与凭证查看 (openapi, openapi --raw, openapi paths, openapi info, openapi keys)
|
||||
keys 企业 OpenAPI 接入凭证一键获取 (keys [--reveal|-r])
|
||||
store 应用中心已购应用与应用商店探查 (list, search <关键词>, get <ID>)
|
||||
http 启动轻量 HTTP Server 与交互式文档 (http [--port=8888] [--host=127.0.0.1])
|
||||
service 常驻守护进程管理 (service start|stop|restart|status|logs|poll)
|
||||
mcp MCP Server 运行 (serve)
|
||||
@@ -149,11 +159,14 @@ 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 # 查看多级企业配置目录链
|
||||
hose-use config mode stateless # 切换为无状态模式 (防止 Agent 误操作)
|
||||
hose-use corps list # 列出名下所有企业
|
||||
hose-use corps search 某企业 # 模糊搜索已保存的企业与员工信息
|
||||
hose-use corps switch ID01MCcOgJl1td # 切换工作企业
|
||||
hose-use contact search 张三 # 模糊搜索员工工号、邮箱与电话
|
||||
hose-use contact list --limit=20 # 采样查看企业通讯录(带防爆截断保护)
|
||||
@@ -166,6 +179,15 @@ export function printHelp(): string {
|
||||
hose-use message count # 查看未读消息数
|
||||
hose-use workflow list # 汇总查看全部工作流
|
||||
hose-use workflow find --task=code-js2 # 搜索包含自定义脚本的工作流
|
||||
hose-use app list # 查看应用管理列表(桌面端工作台开通的业务应用)
|
||||
hose-use app get 用车补贴 # 查看指定应用管理的详情与元数据配置
|
||||
hose-use menu list # 查看桌面端主框架一级导航树与功能模块
|
||||
hose-use platform list # 列出企业可见的自建应用平台
|
||||
hose-use platform entities <应用> # 查看应用下的业务对象
|
||||
hose-use platform schema <应用> <对象> # 查看对象字段(--keyword 可筛选字段)
|
||||
hose-use platform records <应用> <对象> --keyword 关键词 --fields 名称,编码 --json
|
||||
# 查询记录并只输出指定字段
|
||||
hose-use platform permissions <应用> [对象] # 查看应用/对象权限快照
|
||||
hose-use bill list # 查看当前企业单据与报销列表
|
||||
hose-use bill flow S26000001 # 查看单据审批历史与后续节点
|
||||
hose-use bill risk S26000001 # 查看风控预警、预算与发票风险
|
||||
@@ -176,6 +198,13 @@ export function printHelp(): string {
|
||||
hose-use bill download S26000001 --output-dir ./downloads # 下载单据附件到本地目录
|
||||
hose-use dimension list # 查看系统与自定义档案维度
|
||||
hose-use dimension items 项目 # 查看项目档案项
|
||||
hose-use feetype list # 查看费用类型树与层级关系
|
||||
hose-use feetype get 交通费 --specs # 查看费用类型详情与报账/申请字段
|
||||
hose-use feetype create --name="打车费" --parent="交通费" # 在指定父级下创建费用类型
|
||||
hose-use feetype update 打车费 --desc="滴滴打车" # 修改费用类型属性
|
||||
hose-use feetype disable 打车费 # 停用费用类型
|
||||
hose-use feetype enable 打车费 # 重新启用费用类型
|
||||
hose-use feetype move 打车费 --parent="差旅费用" # 移动费用类型到新的父级
|
||||
hose-use role list # 查看企业角色定义
|
||||
hose-use role groups # 查看角色组及其角色
|
||||
hose-use role members 财务主管 # 查看指定角色成员
|
||||
|
||||
+41
-1
@@ -7,6 +7,8 @@ import { handleCorpsCommand } from "./commands/corps.js";
|
||||
import { handleConfigCommand } from "./commands/config.js";
|
||||
import { handleWorkflowCommand } from "./commands/workflow.js";
|
||||
import { handlePlatformCommand } from "./commands/platform.js";
|
||||
import { handleAppCommand } from "./commands/app.js";
|
||||
import { handleMenuCommand } from "./commands/menu.js";
|
||||
import { handleSkillCommand } from "./commands/skill.js";
|
||||
import { handleProbeCommand } from "./commands/probe.js";
|
||||
import { handleMcpCommand } from "./commands/mcp.js";
|
||||
@@ -23,6 +25,10 @@ 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 { handleKeysCommand } from "./commands/keys.js";
|
||||
import { handleStoreCommand } from "./commands/store.js";
|
||||
import { handleFeeTypeCommand } from "./commands/feetype.js";
|
||||
import type { CliParsedArgs, CliResult, CliRunOptions } from "./types.js";
|
||||
|
||||
const STANDING_COMMANDS = new Set(["http", "server", "web", "mcp"]);
|
||||
@@ -143,6 +149,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);
|
||||
@@ -177,6 +194,14 @@ async function dispatchCli(
|
||||
case "archive":
|
||||
case "archives":
|
||||
return await handleDimensionCommand(parsed, runtime);
|
||||
case "feetype":
|
||||
case "feetypes":
|
||||
case "fee-type":
|
||||
case "fee-types":
|
||||
case "expense-type":
|
||||
case "expense-types":
|
||||
case "costtype":
|
||||
return await handleFeeTypeCommand(parsed, runtime);
|
||||
case "role":
|
||||
case "roles":
|
||||
return await handleRoleCommand(parsed, runtime);
|
||||
@@ -197,9 +222,16 @@ async function dispatchCli(
|
||||
return await handleMessageCommand(parsed, runtime);
|
||||
case "platform":
|
||||
case "platforms":
|
||||
case "datalink":
|
||||
case "data-link":
|
||||
return await handlePlatformCommand(parsed, runtime);
|
||||
case "app":
|
||||
case "apps":
|
||||
return await handlePlatformCommand(parsed, runtime);
|
||||
case "workbench":
|
||||
return await handleAppCommand(parsed, runtime);
|
||||
case "menu":
|
||||
case "menus":
|
||||
return await handleMenuCommand(parsed, runtime);
|
||||
case "skill":
|
||||
case "skills":
|
||||
return await handleSkillCommand(parsed, runtime);
|
||||
@@ -215,6 +247,14 @@ async function dispatchCli(
|
||||
case "schema":
|
||||
case "spec":
|
||||
return await handleOpenApiCommand(parsed, runtime);
|
||||
case "keys":
|
||||
case "key":
|
||||
case "secret":
|
||||
case "secrets":
|
||||
return await handleKeysCommand(parsed, runtime);
|
||||
case "store":
|
||||
case "market":
|
||||
return await handleStoreCommand(parsed, runtime);
|
||||
case "http":
|
||||
case "server":
|
||||
case "web":
|
||||
|
||||
+13
-2
@@ -1,6 +1,6 @@
|
||||
# Core 层说明
|
||||
|
||||
Core 层负责基础设施:企业配置管理、认证 Token 获取与缓存、HTTP 客户端工厂、统一异常语义。
|
||||
Core 层负责基础设施:企业配置管理、认证 Token 获取与缓存、统一数据库与版本迁移、多级协同缓存、HTTP 客户端工厂、统一异常语义。
|
||||
|
||||
## 代码结构
|
||||
|
||||
@@ -13,7 +13,16 @@ src/core/
|
||||
│ ├── ekb.ts # 快报主站三 Header 认证
|
||||
│ ├── easo.ts # EASO(unity.ekuaibao.com)四步认证
|
||||
│ ├── piper.ts # Piper(piper.ekuaibao.com)三步认证
|
||||
│ ├── token-store.ts # 动态 Token 缓存(~/.cache/ekb-mcp/tokens.json)
|
||||
│ ├── token-store.ts # 动态 Token 缓存(兼容 ~/.config/hose-use/tokens.json 与历史路径)
|
||||
│ └── types.ts
|
||||
├── cache/ # 统一多级协同缓存
|
||||
│ ├── memory.ts # L1 内存缓存(TTL、容量限制、按命名空间清理)
|
||||
│ ├── sqlite.ts # L2 SQLite 持久化缓存(跨 CLI 进程复用)
|
||||
│ ├── multi-level.ts # 多级联动门面与 withCache 透明包装器
|
||||
│ └── types.ts
|
||||
├── db/ # 统一 SQLite 数据库与结构化版本迁移
|
||||
│ ├── connection.ts # SQLite 单例、WAL 模式、文件权限 0o600 保护
|
||||
│ ├── migrations.ts # 结构化增量迁移运行器(_schema_migrations)
|
||||
│ └── types.ts
|
||||
├── config/ # 企业配置管理
|
||||
│ ├── loader.ts
|
||||
@@ -29,3 +38,5 @@ src/core/
|
||||
- `domains/*/api.ts` 只通过 `core/http/factory.ts` 或 `core/auth/*` 获取客户端
|
||||
- `domains/*` 层只抛 `EkbError` 子类
|
||||
- `server.ts` 负责把 `EkbError` 映射为 MCP error
|
||||
- 业务域如果需要缓存,统一使用 `core/cache/` 提供的多级缓存门面
|
||||
- 业务域如果需要持久化数据,统一接入 `core/db/` 并注册版本迁移
|
||||
+89
-7
@@ -7,26 +7,48 @@ 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,
|
||||
{ token: string; hoseToken: string; expiresAt: number }
|
||||
>();
|
||||
|
||||
const unityMemoryCache = new Map<
|
||||
string,
|
||||
{ token: string; expiresAt: number }
|
||||
>();
|
||||
|
||||
function isExpired(entry: { expiresAt: number }, refreshTtl: number): boolean {
|
||||
return Date.now() >= entry.expiresAt - refreshTtl * 1000;
|
||||
}
|
||||
|
||||
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 }>();
|
||||
@@ -36,13 +58,14 @@ async function fetchHoseToken(
|
||||
return response.data;
|
||||
}
|
||||
|
||||
async function fetchUnityJwt(
|
||||
export 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 +129,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,
|
||||
@@ -146,3 +173,58 @@ export async function getEasoClient(corp: CorpConfig): Promise<{
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
export async function getUnityClient(corp: CorpConfig): Promise<{
|
||||
client: ReturnType<typeof createAuthClient>;
|
||||
unityJwt: string;
|
||||
}> {
|
||||
const refreshTtl = corp.auth?.refreshTtl ?? 300;
|
||||
const cacheKey = `${corp.id}:unity`;
|
||||
|
||||
const mem = unityMemoryCache.get(cacheKey);
|
||||
if (mem && !isExpired(mem, refreshTtl)) {
|
||||
return {
|
||||
unityJwt: mem.token,
|
||||
client: createAuthClient({
|
||||
prefixUrl: EASO_BASE_URL,
|
||||
getHeaders: () => ({
|
||||
Authorization: `Bearer ${mem.token}`,
|
||||
}),
|
||||
onUnauthorized: () => {
|
||||
unityMemoryCache.delete(cacheKey);
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
const corpId = corp.corpId || corp.credentials.corpId;
|
||||
const staffId = corp.staffId || corp.credentials.staffId;
|
||||
const baseUrl = corp.baseUrl || EKB_BASE_URL;
|
||||
|
||||
const unityJwt = await fetchUnityJwt(
|
||||
corp.credentials.accessToken,
|
||||
corpId,
|
||||
staffId,
|
||||
baseUrl
|
||||
);
|
||||
|
||||
const entry = {
|
||||
token: unityJwt,
|
||||
expiresAt: Date.now() + 2 * 60 * 60 * 1000,
|
||||
};
|
||||
unityMemoryCache.set(cacheKey, entry);
|
||||
|
||||
return {
|
||||
unityJwt,
|
||||
client: createAuthClient({
|
||||
prefixUrl: EASO_BASE_URL,
|
||||
getHeaders: () => ({
|
||||
Authorization: `Bearer ${unityJwt}`,
|
||||
}),
|
||||
onUnauthorized: () => {
|
||||
unityMemoryCache.delete(cacheKey);
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { canRefreshCorpAccessToken, resolveLinkExpiresAt } from "./login.js";
|
||||
import { createEkbClient } from "./ekb.js";
|
||||
import type { CorpConfig } from "../config/types.js";
|
||||
|
||||
function corp(overrides: Partial<CorpConfig> = {}): CorpConfig {
|
||||
return {
|
||||
id: "corp-1",
|
||||
name: "测试企业",
|
||||
source: "link",
|
||||
credentials: { accessToken: "token", corpId: "corp-1", staffId: "staff-1" },
|
||||
...overrides,
|
||||
baseUrl: overrides.baseUrl ?? "https://app.ekuaibao.com",
|
||||
};
|
||||
}
|
||||
|
||||
describe("core/auth/ekb refresh policy", () => {
|
||||
it("only allows account credentials with an explicit account binding to refresh", () => {
|
||||
expect(canRefreshCorpAccessToken(corp())).toBe(false);
|
||||
expect(canRefreshCorpAccessToken(corp({ source: "browser", accountId: "86-1" }))).toBe(false);
|
||||
expect(canRefreshCorpAccessToken(corp({ source: "account" }))).toBe(false);
|
||||
expect(canRefreshCorpAccessToken(corp({ source: "account", accountId: "86-1" }))).toBe(true);
|
||||
expect(canRefreshCorpAccessToken(corp({ source: "account", accountId: "86-1", session: { isShortTermToken: true } }))).toBe(false);
|
||||
});
|
||||
|
||||
it("fails expired temporary credentials without retrying or refreshing", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
let calls = 0;
|
||||
globalThis.fetch = (async () => {
|
||||
calls += 1;
|
||||
return new Response("expired", { status: 401 });
|
||||
}) as unknown as typeof fetch;
|
||||
|
||||
try {
|
||||
const client = await createEkbClient(corp());
|
||||
await expect(client.get("api/test")).rejects.toThrow("临时凭证已过期,请使用 hose-use corps add-link 重新导入");
|
||||
expect(calls).toBe(1);
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("core/auth/login link expiry", () => {
|
||||
it("parses explicit ttl and expires durations", () => {
|
||||
const base = 1_700_000_000_000;
|
||||
expect(resolveLinkExpiresAt({ ttl: "72h" }, base)).toBe(base + 72 * 60 * 60 * 1000);
|
||||
expect(resolveLinkExpiresAt({ ttl: "3d" }, base)).toBe(base + 3 * 24 * 60 * 60 * 1000);
|
||||
expect(resolveLinkExpiresAt({ expires: "3" }, base)).toBe(base + 3 * 24 * 60 * 60 * 1000);
|
||||
expect(resolveLinkExpiresAt({}, base)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
+16
-6
@@ -1,6 +1,7 @@
|
||||
import { CorpConfig } from "../config/types.js";
|
||||
import { AuthenticationError } from "../errors.js";
|
||||
import { createAuthClient } from "../http/factory.js";
|
||||
import { refreshSingleCorpAccessToken } from "./login.js";
|
||||
import { canRefreshCorpAccessToken, refreshSingleCorpAccessToken } from "./login.js";
|
||||
|
||||
export function getEkbHeaders(corp: CorpConfig): Record<string, string> {
|
||||
return {
|
||||
@@ -11,20 +12,29 @@ export function getEkbHeaders(corp: CorpConfig): Record<string, string> {
|
||||
}
|
||||
|
||||
export async function createEkbClient(corp: CorpConfig) {
|
||||
const canRefresh = canRefreshCorpAccessToken(corp);
|
||||
|
||||
// 1. 预检:若 Token 即将过期 (提前 refreshTtl 秒),静默无感自动续杯
|
||||
if (corp.auth?.expiresAt) {
|
||||
if (canRefresh && corp.auth?.expiresAt) {
|
||||
const ttlMs = (corp.auth.refreshTtl || 300) * 1000;
|
||||
if (Date.now() >= corp.auth.expiresAt - ttlMs) {
|
||||
await refreshSingleCorpAccessToken(corp);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 使用带 401 自动重试与换票的 AuthClient
|
||||
// 2. 仅账号凭证启用 401 自动重试与换票;临时凭证直接给出可操作错误
|
||||
return createAuthClient({
|
||||
prefixUrl: corp.baseUrl || "https://app.ekuaibao.com",
|
||||
getHeaders: () => getEkbHeaders(corp),
|
||||
onUnauthorized: async () => {
|
||||
await refreshSingleCorpAccessToken(corp);
|
||||
},
|
||||
retryUnauthorized: canRefresh,
|
||||
...(canRefresh
|
||||
? {
|
||||
onUnauthorized: async () => {
|
||||
await refreshSingleCorpAccessToken(corp);
|
||||
},
|
||||
}
|
||||
: {
|
||||
onAuthFailure: () => new AuthenticationError("临时凭证已过期,请使用 hose-use corps add-link 重新导入"),
|
||||
}),
|
||||
});
|
||||
}
|
||||
+210
-63
@@ -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,50 @@ 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;
|
||||
ttl?: string | number;
|
||||
expires?: string | number;
|
||||
}
|
||||
|
||||
export interface ImportFromLinkOptions {
|
||||
name?: string;
|
||||
baseUrl?: string;
|
||||
enterprisesDir?: string;
|
||||
overwrite?: boolean;
|
||||
ttl?: string | number;
|
||||
expires?: string | number;
|
||||
}
|
||||
|
||||
export function canRefreshCorpAccessToken(corp: CorpConfig): boolean {
|
||||
return corp.source === "account" && !corp.session?.isShortTermToken && Boolean(corp.accountId);
|
||||
}
|
||||
|
||||
function parseDurationMs(value: string | number, defaultUnit: "hours" | "days"): number {
|
||||
const raw = String(value).trim().toLowerCase();
|
||||
const match = raw.match(/^(\d+(?:\.\d+)?)\s*(h|hr|hrs|hour|hours|d|day|days)?$/);
|
||||
if (!match) throw new AuthenticationError(`无效的有效期参数: ${value}(示例:3d、72h)`);
|
||||
const amount = Number(match[1]);
|
||||
if (!Number.isFinite(amount) || amount <= 0) {
|
||||
throw new AuthenticationError(`有效期必须是大于 0 的数字: ${value}`);
|
||||
}
|
||||
const unit = match[2];
|
||||
const isDays = unit ? ["d", "day", "days"].includes(unit) : defaultUnit === "days";
|
||||
return amount * (isDays ? 24 : 1) * 60 * 60 * 1000;
|
||||
}
|
||||
|
||||
export function resolveLinkExpiresAt(
|
||||
options: { ttl?: string | number; expires?: string | number },
|
||||
baseTime = Date.now()
|
||||
): number | undefined {
|
||||
if (options.ttl !== undefined) return baseTime + parseDurationMs(options.ttl, "hours");
|
||||
if (options.expires !== undefined) return baseTime + parseDurationMs(options.expires, "days");
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -234,6 +277,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 +326,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 +369,77 @@ 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;
|
||||
const requestedExpiresAt = resolveLinkExpiresAt(params);
|
||||
|
||||
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 +459,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 +494,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,15 +526,15 @@ export async function importCredentials(
|
||||
expiresAt = sessionData.expTime;
|
||||
} else if (jwtExpMs && jwtExpMs > 0) {
|
||||
expiresAt = jwtExpMs;
|
||||
} else if (sessionData?.isAssistPlatform && sessionData?.loginTime) {
|
||||
// 协助平台短期调试 Token 通常 2 小时有效
|
||||
expiresAt = sessionData.loginTime + 2 * 3600 * 1000;
|
||||
} else if (requestedExpiresAt) {
|
||||
expiresAt = requestedExpiresAt;
|
||||
}
|
||||
|
||||
const corpConfig: CorpConfig = {
|
||||
id: corpId,
|
||||
name: corpName || `企业-${corpId}`,
|
||||
baseUrl,
|
||||
cluster,
|
||||
source,
|
||||
staffName,
|
||||
credentials: {
|
||||
@@ -456,6 +568,39 @@ 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",
|
||||
ttl: options.ttl,
|
||||
expires: options.expires,
|
||||
});
|
||||
}
|
||||
|
||||
// 保持历史命名兼容
|
||||
export const importF12Credentials = importCredentials;
|
||||
|
||||
@@ -566,7 +711,9 @@ export async function refreshSingleCorpAccessToken(
|
||||
businessCenterUrl: string = DEFAULT_BUSINESS_CENTER_URL,
|
||||
idpUrl: string = DEFAULT_IDP_URL
|
||||
): Promise<boolean> {
|
||||
const account = corp.accountId ? getAccount(corp.accountId) : getActiveAccount();
|
||||
if (!canRefreshCorpAccessToken(corp)) return false;
|
||||
|
||||
const account = getAccount(corp.accountId!);
|
||||
if (!account?.cloudAuthToken) return false;
|
||||
|
||||
try {
|
||||
|
||||
+13
-6
@@ -2,6 +2,7 @@ import ky from "ky";
|
||||
import { CorpConfig } from "../../core/config/types.js";
|
||||
import { createAuthClient } from "../../core/http/factory.js";
|
||||
import { AuthenticationError } from "../../core/errors.js";
|
||||
import { resolveCorpCluster } from "./easo.js";
|
||||
|
||||
const PIPER_BASE_URL = "https://piper.ekuaibao.com";
|
||||
const BUSINESS_CENTER_URL = "https://business-center.ekuaibao.com";
|
||||
@@ -19,14 +20,15 @@ function isExpired(entry: { expiresAt: number }, refreshTtl: number): boolean {
|
||||
|
||||
async function fetchHoseToken(
|
||||
accessToken: string,
|
||||
corpId: string
|
||||
corpId: string,
|
||||
environment: string = "app"
|
||||
): Promise<string> {
|
||||
const response = await ky
|
||||
.get(`${BUSINESS_CENTER_URL}/auth/oauth2/grant/ekb/accessToken`, {
|
||||
searchParams: {
|
||||
corpId,
|
||||
ekbAccessToken: accessToken,
|
||||
environment: "app",
|
||||
environment,
|
||||
},
|
||||
})
|
||||
.json<{ data: string }>();
|
||||
@@ -39,10 +41,11 @@ async function fetchHoseToken(
|
||||
async function fetchEasoJwt(
|
||||
accessToken: string,
|
||||
corpId: string,
|
||||
staffId: string
|
||||
staffId: string,
|
||||
baseUrl: string = EKB_BASE_URL
|
||||
): Promise<string> {
|
||||
const response = await ky
|
||||
.get(`${EKB_BASE_URL}/api/engine/realm/$EASO/actions/jwt`, {
|
||||
.get(`${baseUrl}/api/engine/realm/$EASO/actions/jwt`, {
|
||||
searchParams: { corpId },
|
||||
headers: {
|
||||
accesstoken: accessToken,
|
||||
@@ -82,16 +85,20 @@ export async function getPiperClient(
|
||||
|
||||
const corpId = corp.corpId || corp.credentials.corpId;
|
||||
const staffId = corp.staffId || corp.credentials.staffId;
|
||||
const environment = resolveCorpCluster(corp);
|
||||
const baseUrl = corp.baseUrl || EKB_BASE_URL;
|
||||
|
||||
// 重新换取
|
||||
const hoseToken = await fetchHoseToken(
|
||||
corp.credentials.accessToken,
|
||||
corpId
|
||||
corpId,
|
||||
environment
|
||||
);
|
||||
const easoJwt = await fetchEasoJwt(
|
||||
corp.credentials.accessToken,
|
||||
corpId,
|
||||
staffId
|
||||
staffId,
|
||||
baseUrl
|
||||
);
|
||||
|
||||
const entry = {
|
||||
|
||||
@@ -1,31 +1,82 @@
|
||||
import { readFileSync, writeFileSync, mkdirSync } from "fs";
|
||||
import { join, dirname } from "path";
|
||||
import { chmodSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "fs";
|
||||
import { homedir } from "os";
|
||||
import { dirname, join } from "path";
|
||||
import { TokenStore, TokenStoreSchema } from "./types";
|
||||
|
||||
const TOKEN_CACHE_PATH = join(
|
||||
export const PRIMARY_TOKEN_CACHE_PATH = join(
|
||||
homedir(),
|
||||
".config",
|
||||
"hose-use",
|
||||
"tokens.json"
|
||||
);
|
||||
|
||||
export const LEGACY_TOKEN_CACHE_PATH = join(
|
||||
homedir(),
|
||||
".cache",
|
||||
"ekb-mcp",
|
||||
"tokens.json"
|
||||
);
|
||||
|
||||
function ensureDir(path: string): void {
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
function resolveTokenCachePath(): string {
|
||||
if (existsSync(PRIMARY_TOKEN_CACHE_PATH)) {
|
||||
return PRIMARY_TOKEN_CACHE_PATH;
|
||||
}
|
||||
if (existsSync(LEGACY_TOKEN_CACHE_PATH)) {
|
||||
return LEGACY_TOKEN_CACHE_PATH;
|
||||
}
|
||||
return PRIMARY_TOKEN_CACHE_PATH;
|
||||
}
|
||||
|
||||
export function loadTokenStore(): TokenStore {
|
||||
try {
|
||||
const content = readFileSync(TOKEN_CACHE_PATH, "utf-8");
|
||||
return TokenStoreSchema.parse(JSON.parse(content));
|
||||
} catch {
|
||||
return {};
|
||||
function ensureDir(path: string): void {
|
||||
const dir = dirname(path);
|
||||
if (!existsSync(dir)) {
|
||||
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
||||
}
|
||||
try {
|
||||
chmodSync(dir, 0o700);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
let memoryTokenCache: TokenStore | null = null;
|
||||
let lastMtimeMs = 0;
|
||||
|
||||
export function loadTokenStore(): TokenStore {
|
||||
const filePath = resolveTokenCachePath();
|
||||
|
||||
if (existsSync(filePath)) {
|
||||
try {
|
||||
const stats = statSync(filePath);
|
||||
if (memoryTokenCache && stats.mtimeMs === lastMtimeMs) {
|
||||
return memoryTokenCache;
|
||||
}
|
||||
const content = readFileSync(filePath, "utf-8");
|
||||
const parsed = TokenStoreSchema.parse(JSON.parse(content));
|
||||
memoryTokenCache = parsed;
|
||||
lastMtimeMs = stats.mtimeMs;
|
||||
return parsed;
|
||||
} catch {
|
||||
// 若已有内存缓存则保留,避免解析失败直接冲刷为 {}
|
||||
return memoryTokenCache ?? {};
|
||||
}
|
||||
}
|
||||
|
||||
return memoryTokenCache ?? {};
|
||||
}
|
||||
|
||||
export function saveTokenStore(store: TokenStore): void {
|
||||
ensureDir(TOKEN_CACHE_PATH);
|
||||
writeFileSync(TOKEN_CACHE_PATH, JSON.stringify(store, null, 2));
|
||||
memoryTokenCache = store;
|
||||
const targetPath = PRIMARY_TOKEN_CACHE_PATH;
|
||||
ensureDir(targetPath);
|
||||
|
||||
// MAJ-03: 强制写入 0o600 保护敏感凭证
|
||||
writeFileSync(targetPath, JSON.stringify(store, null, 2), {
|
||||
encoding: "utf-8",
|
||||
mode: 0o600,
|
||||
});
|
||||
try {
|
||||
chmodSync(targetPath, 0o600);
|
||||
lastMtimeMs = statSync(targetPath).mtimeMs;
|
||||
} catch {}
|
||||
}
|
||||
|
||||
export function getCorpTokens(corpId: string): TokenStore[string] | undefined {
|
||||
@@ -44,3 +95,11 @@ export function clearCorpTokens(corpId: string): void {
|
||||
delete store[corpId];
|
||||
saveTokenStore(store);
|
||||
}
|
||||
|
||||
/**
|
||||
* 重置内存 Token 缓存(测试隔离用)
|
||||
*/
|
||||
export function resetTokenStoreMemory(): void {
|
||||
memoryTokenCache = null;
|
||||
lastMtimeMs = 0;
|
||||
}
|
||||
Vendored
+162
@@ -0,0 +1,162 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { closeDatabase, getDatabase } from "../db/connection.js";
|
||||
import { MemoryCache } from "./memory.js";
|
||||
import { MultiLevelCache } from "./multi-level.js";
|
||||
import { SqliteCache } from "./sqlite.js";
|
||||
|
||||
describe("Core Cache - 多级缓存架构与淘汰机制 (加固测试)", () => {
|
||||
let db: Database;
|
||||
|
||||
beforeEach(() => {
|
||||
db = getDatabase(":memory:");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
closeDatabase();
|
||||
});
|
||||
|
||||
describe("L1: MemoryCache", () => {
|
||||
test("基础读写、删除与命名空间隔离", () => {
|
||||
const cache = new MemoryCache();
|
||||
cache.set("100", { name: "用户A" }, { namespace: "users" });
|
||||
cache.set("100", { title: "角色B" }, { namespace: "roles" });
|
||||
|
||||
// CRIT-02 验证:相同 key 在不同命名空间下完全隔离、互不覆写
|
||||
expect(cache.get<{ name: string }>("100", "users")).toEqual({ name: "用户A" });
|
||||
expect(cache.get<{ title: string }>("100", "roles")).toEqual({ title: "角色B" });
|
||||
expect(cache.has("100", "users")).toBe(true);
|
||||
expect(cache.has("100", "departments")).toBe(false);
|
||||
|
||||
// 按 namespace 清理
|
||||
cache.clear("users");
|
||||
expect(cache.get("100", "users")).toBeUndefined();
|
||||
expect(cache.get<{ title: string }>("100", "roles")).toEqual({ title: "角色B" });
|
||||
|
||||
// 单条删除
|
||||
cache.delete("100", "roles");
|
||||
expect(cache.get("100", "roles")).toBeUndefined();
|
||||
});
|
||||
|
||||
test("TTL 过期检查", async () => {
|
||||
const cache = new MemoryCache();
|
||||
cache.set("temp", "value", { ttlMs: 10 });
|
||||
expect(cache.get<string>("temp")).toBe("value");
|
||||
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
expect(cache.get("temp")).toBeUndefined();
|
||||
});
|
||||
|
||||
test("严格 LRU 访问热度调整与容量淘汰 (MAJ-08 & MAJ-09)", () => {
|
||||
const cache = new MemoryCache(3);
|
||||
cache.set("k1", "v1");
|
||||
cache.set("k2", "v2");
|
||||
cache.set("k3", "v3");
|
||||
|
||||
// 访问 k1,使 k1 成为最热的条目(移至队尾)
|
||||
expect(cache.get<string>("k1")).toBe("v1");
|
||||
|
||||
// 此时最冷的是 k2。插入 k4 触发容量超限(容量 3)
|
||||
cache.set("k4", "v4");
|
||||
|
||||
// 验证 k2 被淘汰,而最近被访问的 k1 依然存活
|
||||
expect(cache.get("k2")).toBeUndefined();
|
||||
expect(cache.get<string>("k1")).toBe("v1");
|
||||
expect(cache.get<string>("k3")).toBe("v3");
|
||||
expect(cache.get<string>("k4")).toBe("v4");
|
||||
|
||||
// 更新已有键不会增加容量,也不会误伤淘汰其他键
|
||||
cache.set("k1", "v1_updated");
|
||||
expect(cache.size()).toBe(3);
|
||||
expect(cache.get<string>("k1")).toBe("v1_updated");
|
||||
});
|
||||
});
|
||||
|
||||
describe("L2: SqliteCache", () => {
|
||||
test("复合主键 (namespace, key) 跨域存储与隔离 (CRIT-02)", () => {
|
||||
const cache = new SqliteCache(db);
|
||||
cache.set("id_1", { type: "dim" }, { namespace: "dimensions" });
|
||||
cache.set("id_1", { type: "role" }, { namespace: "roles" });
|
||||
|
||||
const dim = cache.get<{ type: string }>("id_1", "dimensions");
|
||||
const role = cache.get<{ type: string }>("id_1", "roles");
|
||||
|
||||
expect(dim?.type).toBe("dim");
|
||||
expect(role?.type).toBe("role");
|
||||
|
||||
// 验证底层 SQLite 表结构行记录
|
||||
const rows = db.query("SELECT namespace, key FROM cache_entries WHERE key = 'id_1'").all() as any[];
|
||||
expect(rows.length).toBe(2);
|
||||
|
||||
// 按 namespace 清除
|
||||
cache.clear("dimensions");
|
||||
expect(cache.get("id_1", "dimensions")).toBeUndefined();
|
||||
expect(cache.get("id_1", "roles")).toBeDefined();
|
||||
});
|
||||
|
||||
test("TTL 过期与 pruneExpired 清理", async () => {
|
||||
const cache = new SqliteCache(db);
|
||||
cache.set("expire_soon", "data", { ttlMs: 15 });
|
||||
expect(cache.get<string>("expire_soon")).toBe("data");
|
||||
|
||||
await new Promise((r) => setTimeout(r, 25));
|
||||
expect(cache.get("expire_soon")).toBeUndefined();
|
||||
|
||||
cache.set("stale", "foo", { ttlMs: 5 });
|
||||
await new Promise((r) => setTimeout(r, 15));
|
||||
const pruned = cache.pruneExpired();
|
||||
expect(pruned).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("MultiLevelCache 两级协同与防击穿 (MAJ-01)", () => {
|
||||
test("L1 miss 后从 L2 命中并自动回填至 L1", () => {
|
||||
const l1 = new MemoryCache();
|
||||
const l2 = new SqliteCache(db);
|
||||
const multi = new MultiLevelCache({ l1, l2 });
|
||||
|
||||
multi.set("order:100", { amount: 888 }, { namespace: "orders" });
|
||||
|
||||
// 手动清空 L1 模拟内存冷启动
|
||||
l1.clear();
|
||||
expect(l1.get("order:100", "orders")).toBeUndefined();
|
||||
|
||||
// 从多级缓存读取:从 L2 命中,并回填至 L1
|
||||
const val = multi.get<{ amount: number }>("order:100", "orders");
|
||||
expect(val).toEqual({ amount: 888 });
|
||||
|
||||
// 验证 L1 已被自动回填
|
||||
expect(l1.get<{ amount: number }>("order:100", "orders")).toEqual({ amount: 888 });
|
||||
});
|
||||
|
||||
test("并发防击穿 (Thundering Herd Protection / In-flight Deduplication)", async () => {
|
||||
const multi = new MultiLevelCache({ l2: new SqliteCache(db) });
|
||||
let fetchCount = 0;
|
||||
|
||||
const slowFetcher = async () => {
|
||||
fetchCount++;
|
||||
await new Promise((r) => setTimeout(r, 20)); // 模拟慢网络
|
||||
return { data: "fresh", fetchCount };
|
||||
};
|
||||
|
||||
// 模拟 10 个并发请求在缓存冷启动时同时调用 withCache
|
||||
const promises = Array.from({ length: 10 }).map(() =>
|
||||
multi.withCache("concurrent_key", slowFetcher, {
|
||||
namespace: "test_herd",
|
||||
ttlMs: 5000,
|
||||
})
|
||||
);
|
||||
|
||||
const results = await Promise.all(promises);
|
||||
|
||||
// 验证:所有并发请求获取到相同的数据
|
||||
expect(results.length).toBe(10);
|
||||
for (const res of results) {
|
||||
expect(res.fetchCount).toBe(1);
|
||||
}
|
||||
|
||||
// 核心断言:底层 slowFetcher 严格只被调用了 1 次!彻底防御了缓存击穿
|
||||
expect(fetchCount).toBe(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
Vendored
+35
@@ -0,0 +1,35 @@
|
||||
import { MultiLevelCache, type MultiLevelCacheOptions } from "./multi-level.js";
|
||||
|
||||
export * from "./types.js";
|
||||
export * from "./memory.js";
|
||||
export * from "./sqlite.js";
|
||||
export * from "./multi-level.js";
|
||||
|
||||
let defaultCacheInstance: MultiLevelCache | null = null;
|
||||
|
||||
/**
|
||||
* 获取全局默认多级缓存实例(单例)
|
||||
*/
|
||||
export function getGlobalCache(): MultiLevelCache {
|
||||
if (!defaultCacheInstance) {
|
||||
defaultCacheInstance = new MultiLevelCache();
|
||||
}
|
||||
return defaultCacheInstance;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建独立的多级缓存实例
|
||||
*/
|
||||
export function createMultiLevelCache(options?: MultiLevelCacheOptions): MultiLevelCache {
|
||||
return new MultiLevelCache(options);
|
||||
}
|
||||
|
||||
/**
|
||||
* 重置全局缓存实例(测试清理用)
|
||||
*/
|
||||
export function resetGlobalCache(): void {
|
||||
if (defaultCacheInstance) {
|
||||
defaultCacheInstance.clear();
|
||||
defaultCacheInstance = null;
|
||||
}
|
||||
}
|
||||
Vendored
+143
@@ -0,0 +1,143 @@
|
||||
import type { CacheEntry, CacheOptions, ICache } from "./types.js";
|
||||
|
||||
const DEFAULT_TTL_MS = 10 * 60 * 1000; // 10 分钟
|
||||
const DEFAULT_MAX_ENTRIES = 2000;
|
||||
|
||||
export class MemoryCache implements ICache {
|
||||
// Map 保持键的插入顺序,结合重新插入机制实现高效的 O(1) LRU 淘汰
|
||||
private map = new Map<string, CacheEntry<any>>();
|
||||
private maxEntries: number;
|
||||
|
||||
constructor(maxEntries = DEFAULT_MAX_ENTRIES) {
|
||||
this.maxEntries = maxEntries;
|
||||
}
|
||||
|
||||
/**
|
||||
* CRIT-02: 构建命名空间隔离的复合内存键,彻底规避跨域碰撞
|
||||
*/
|
||||
private toCompositeKey(key: string, namespace?: string): string {
|
||||
const ns = namespace || "default";
|
||||
return `${ns}:${key}`;
|
||||
}
|
||||
|
||||
public get<T>(key: string, namespace = "default"): T | undefined {
|
||||
const compositeKey = this.toCompositeKey(key, namespace);
|
||||
const entry = this.map.get(compositeKey);
|
||||
if (!entry) return undefined;
|
||||
|
||||
const now = Date.now();
|
||||
if (entry.expiresAt <= now) {
|
||||
this.map.delete(compositeKey);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// MAJ-09: 真正 LRU 访问刷新 —— 命中后移至 Map 末尾
|
||||
this.map.delete(compositeKey);
|
||||
this.map.set(compositeKey, entry);
|
||||
|
||||
return entry.value as T;
|
||||
}
|
||||
|
||||
public getEntry<T>(key: string, namespace = "default"): CacheEntry<T> | undefined {
|
||||
const compositeKey = this.toCompositeKey(key, namespace);
|
||||
const entry = this.map.get(compositeKey);
|
||||
if (!entry) return undefined;
|
||||
|
||||
const now = Date.now();
|
||||
if (entry.expiresAt <= now) {
|
||||
this.map.delete(compositeKey);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// 命中后移至 Map 末尾保持热度
|
||||
this.map.delete(compositeKey);
|
||||
this.map.set(compositeKey, entry);
|
||||
|
||||
return entry as CacheEntry<T>;
|
||||
}
|
||||
|
||||
public set<T>(key: string, value: T, options?: CacheOptions): void {
|
||||
const namespace = options?.namespace ?? "default";
|
||||
const compositeKey = this.toCompositeKey(key, namespace);
|
||||
const now = Date.now();
|
||||
const ttl = options?.ttlMs ?? DEFAULT_TTL_MS;
|
||||
|
||||
const entry: CacheEntry<T> = {
|
||||
value,
|
||||
expiresAt: now + ttl,
|
||||
updatedAt: now,
|
||||
namespace,
|
||||
};
|
||||
|
||||
// MAJ-08: 更新已有键时,先删后插调至末尾,不应误触发 LRU 淘汰
|
||||
if (this.map.has(compositeKey)) {
|
||||
this.map.delete(compositeKey);
|
||||
this.map.set(compositeKey, entry);
|
||||
return;
|
||||
}
|
||||
|
||||
// 若达到容量限制,执行 LRU 淘汰
|
||||
if (this.map.size >= this.maxEntries) {
|
||||
this.evict();
|
||||
}
|
||||
|
||||
this.map.set(compositeKey, entry);
|
||||
}
|
||||
|
||||
public setEntry<T>(key: string, entry: CacheEntry<T>): void {
|
||||
const compositeKey = this.toCompositeKey(key, entry.namespace);
|
||||
if (this.map.has(compositeKey)) {
|
||||
this.map.delete(compositeKey);
|
||||
} else if (this.map.size >= this.maxEntries) {
|
||||
this.evict();
|
||||
}
|
||||
this.map.set(compositeKey, entry);
|
||||
}
|
||||
|
||||
public delete(key: string, namespace = "default"): void {
|
||||
const compositeKey = this.toCompositeKey(key, namespace);
|
||||
this.map.delete(compositeKey);
|
||||
}
|
||||
|
||||
public clear(namespace?: string): void {
|
||||
if (!namespace) {
|
||||
this.map.clear();
|
||||
return;
|
||||
}
|
||||
|
||||
const prefix = `${namespace}:`;
|
||||
for (const k of this.map.keys()) {
|
||||
if (k.startsWith(prefix)) {
|
||||
this.map.delete(k);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public has(key: string, namespace = "default"): boolean {
|
||||
return this.get(key, namespace) !== undefined;
|
||||
}
|
||||
|
||||
public size(): number {
|
||||
return this.map.size;
|
||||
}
|
||||
|
||||
private evict(): void {
|
||||
const now = Date.now();
|
||||
// 1. 优先剔除已过期的死键
|
||||
for (const [k, v] of this.map.entries()) {
|
||||
if (v.expiresAt <= now) {
|
||||
this.map.delete(k);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 若仍然超限,按真正的 LRU(头部为最久未访问的条目)淘汰最早的条目
|
||||
while (this.map.size >= this.maxEntries) {
|
||||
const oldestKey = this.map.keys().next().value;
|
||||
if (oldestKey !== undefined) {
|
||||
this.map.delete(oldestKey);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+113
@@ -0,0 +1,113 @@
|
||||
import { MemoryCache } from "./memory.js";
|
||||
import { SqliteCache } from "./sqlite.js";
|
||||
import type { CacheOptions, ICache, WithCacheOptions } from "./types.js";
|
||||
|
||||
export interface MultiLevelCacheOptions {
|
||||
l1?: MemoryCache;
|
||||
l2?: SqliteCache | null;
|
||||
}
|
||||
|
||||
export class MultiLevelCache implements ICache {
|
||||
private l1: MemoryCache;
|
||||
private l2: SqliteCache | null;
|
||||
// MAJ-01: 防击穿 / 单飞并发请求去重表 (In-flight Promise Deduplication)
|
||||
private inFlight = new Map<string, Promise<any>>();
|
||||
|
||||
constructor(options?: MultiLevelCacheOptions) {
|
||||
this.l1 = options?.l1 ?? new MemoryCache();
|
||||
this.l2 = options?.l2 !== undefined ? options.l2 : new SqliteCache();
|
||||
}
|
||||
|
||||
public get<T>(key: string, namespace = "default"): T | undefined {
|
||||
// 1. 优先从 L1 (Memory) 获取
|
||||
const l1Value = this.l1.get<T>(key, namespace);
|
||||
if (l1Value !== undefined) {
|
||||
return l1Value;
|
||||
}
|
||||
|
||||
// 2. L1 穿透,查询 L2 (SQLite 持久化)
|
||||
if (this.l2) {
|
||||
const l2Entry = this.l2.getEntry<T>(key, namespace);
|
||||
if (l2Entry !== undefined) {
|
||||
// 回填至 L1,保持相同的到期时间与命名空间
|
||||
this.l1.setEntry(key, l2Entry);
|
||||
return l2Entry.value;
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
public set<T>(key: string, value: T, options?: CacheOptions): void {
|
||||
// 同时写入 L1 与 L2
|
||||
this.l1.set(key, value, options);
|
||||
if (this.l2) {
|
||||
this.l2.set(key, value, options);
|
||||
}
|
||||
}
|
||||
|
||||
public delete(key: string, namespace = "default"): void {
|
||||
this.l1.delete(key, namespace);
|
||||
if (this.l2) {
|
||||
this.l2.delete(key, namespace);
|
||||
}
|
||||
}
|
||||
|
||||
public clear(namespace?: string): void {
|
||||
this.l1.clear(namespace);
|
||||
if (this.l2) {
|
||||
this.l2.clear(namespace);
|
||||
}
|
||||
}
|
||||
|
||||
public has(key: string, namespace = "default"): boolean {
|
||||
return this.get(key, namespace) !== undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* MAJ-01: 业务透明包装器,自动多级缓存查验 + In-flight 请求合并防击穿
|
||||
*/
|
||||
public async withCache<T>(
|
||||
key: string,
|
||||
fetcher: () => Promise<T>,
|
||||
options?: WithCacheOptions
|
||||
): Promise<T> {
|
||||
const namespace = options?.namespace ?? "default";
|
||||
const lockKey = `${namespace}:${key}`;
|
||||
|
||||
if (!options?.forceRefresh) {
|
||||
const cached = this.get<T>(key, namespace);
|
||||
if (cached !== undefined) {
|
||||
return cached;
|
||||
}
|
||||
}
|
||||
|
||||
// 防击穿:检查是否已有相同命名空间与键的并发请求在执行中
|
||||
const ongoing = this.inFlight.get(lockKey);
|
||||
if (ongoing) {
|
||||
return ongoing as Promise<T>;
|
||||
}
|
||||
|
||||
const promise = (async () => {
|
||||
try {
|
||||
const fresh = await fetcher();
|
||||
this.set(key, fresh, options);
|
||||
return fresh;
|
||||
} finally {
|
||||
this.inFlight.delete(lockKey);
|
||||
}
|
||||
})();
|
||||
|
||||
this.inFlight.set(lockKey, promise);
|
||||
return promise;
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理过期条目(MIN-11: L1 与 L2 同步清理)
|
||||
*/
|
||||
public pruneExpired(): void {
|
||||
if (this.l2) {
|
||||
this.l2.pruneExpired();
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+128
@@ -0,0 +1,128 @@
|
||||
import type { Database } from "bun:sqlite";
|
||||
import { getDatabase } from "../db/connection.js";
|
||||
import type { CacheEntry, CacheOptions, ICache } from "./types.js";
|
||||
|
||||
const DEFAULT_TTL_MS = 10 * 60 * 1000; // 10 分钟
|
||||
|
||||
interface CacheRow {
|
||||
namespace: string;
|
||||
key: string;
|
||||
value: string;
|
||||
expires_at: number;
|
||||
updated_at: number;
|
||||
}
|
||||
|
||||
export class SqliteCache implements ICache {
|
||||
private db: Database;
|
||||
|
||||
constructor(db?: Database) {
|
||||
this.db = db ?? getDatabase();
|
||||
}
|
||||
|
||||
public get<T>(key: string, namespace = "default"): T | undefined {
|
||||
const entry = this.getEntry<T>(key, namespace);
|
||||
return entry ? entry.value : undefined;
|
||||
}
|
||||
|
||||
public getEntry<T>(key: string, namespace = "default"): CacheEntry<T> | undefined {
|
||||
try {
|
||||
const row = this.db
|
||||
.query(
|
||||
"SELECT namespace, key, value, expires_at, updated_at FROM cache_entries WHERE namespace = ? AND key = ?"
|
||||
)
|
||||
.get(namespace, key) as CacheRow | null;
|
||||
|
||||
if (!row) return undefined;
|
||||
|
||||
const now = Date.now();
|
||||
if (row.expires_at <= now) {
|
||||
this.delete(key, namespace);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const parsedValue = JSON.parse(row.value) as T;
|
||||
return {
|
||||
value: parsedValue,
|
||||
expiresAt: row.expires_at,
|
||||
updatedAt: row.updated_at,
|
||||
namespace: row.namespace,
|
||||
};
|
||||
} catch {
|
||||
// 容错处理损坏数据
|
||||
this.delete(key, namespace);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
public set<T>(key: string, value: T, options?: CacheOptions): void {
|
||||
if (value === undefined) {
|
||||
// MIN-05: undefined 语义等同于清除该键
|
||||
this.delete(key, options?.namespace);
|
||||
return;
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const ttl = options?.ttlMs ?? DEFAULT_TTL_MS;
|
||||
const namespace = options?.namespace ?? "default";
|
||||
const expiresAt = now + ttl;
|
||||
|
||||
try {
|
||||
const serialized = JSON.stringify(value);
|
||||
this.db.run(
|
||||
`
|
||||
INSERT INTO cache_entries (namespace, key, value, expires_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
ON CONFLICT(namespace, key) DO UPDATE SET
|
||||
value = excluded.value,
|
||||
expires_at = excluded.expires_at,
|
||||
updated_at = excluded.updated_at
|
||||
`,
|
||||
[namespace, key, serialized, expiresAt, now]
|
||||
);
|
||||
} catch (err) {
|
||||
console.error(`[cache] SqliteCache.set error for ${namespace}:${key}:`, err);
|
||||
}
|
||||
}
|
||||
|
||||
public delete(key: string, namespace = "default"): void {
|
||||
try {
|
||||
this.db.run(
|
||||
"DELETE FROM cache_entries WHERE namespace = ? AND key = ?",
|
||||
[namespace, key]
|
||||
);
|
||||
} catch {
|
||||
// 容错
|
||||
}
|
||||
}
|
||||
|
||||
public clear(namespace?: string): void {
|
||||
try {
|
||||
if (namespace) {
|
||||
this.db.run("DELETE FROM cache_entries WHERE namespace = ?", [namespace]);
|
||||
} else {
|
||||
this.db.run("DELETE FROM cache_entries");
|
||||
}
|
||||
} catch {
|
||||
// 容错
|
||||
}
|
||||
}
|
||||
|
||||
public has(key: string, namespace = "default"): boolean {
|
||||
return this.get(key, namespace) !== undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* 主动清理数据库中所有过期缓存记录
|
||||
*/
|
||||
public pruneExpired(): number {
|
||||
try {
|
||||
const result = this.db.run(
|
||||
"DELETE FROM cache_entries WHERE expires_at <= ?",
|
||||
[Date.now()]
|
||||
);
|
||||
return result.changes;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+32
@@ -0,0 +1,32 @@
|
||||
export interface CacheOptions {
|
||||
/**
|
||||
* 缓存有效时长(毫秒),默认 10 分钟 (600,000 ms)
|
||||
*/
|
||||
ttlMs?: number;
|
||||
/**
|
||||
* 命名空间,便于按业务模块隔离与批量失效(例如: 'dimensions', 'roles', 'bills')
|
||||
*/
|
||||
namespace?: string;
|
||||
}
|
||||
|
||||
export interface CacheEntry<T> {
|
||||
value: T;
|
||||
expiresAt: number;
|
||||
updatedAt: number;
|
||||
namespace: string;
|
||||
}
|
||||
|
||||
export interface ICache {
|
||||
get<T>(key: string): Promise<T | undefined> | T | undefined;
|
||||
set<T>(key: string, value: T, options?: CacheOptions): Promise<void> | void;
|
||||
delete(key: string): Promise<void> | void;
|
||||
clear(namespace?: string): Promise<void> | void;
|
||||
has(key: string): Promise<boolean> | boolean;
|
||||
}
|
||||
|
||||
export interface WithCacheOptions extends CacheOptions {
|
||||
/**
|
||||
* 是否强制穿透缓存刷新
|
||||
*/
|
||||
forceRefresh?: boolean;
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
saveCorpConfig,
|
||||
resolveEnterprisesDirs,
|
||||
resolveWritableEnterprisesDir,
|
||||
getEnterprisesDirCandidates,
|
||||
loadGlobalConfig,
|
||||
saveGlobalConfig,
|
||||
resolveGlobalConfigFile,
|
||||
@@ -39,6 +40,35 @@ describe("core/config/loader", () => {
|
||||
expect(dirs).toEqual([customDir]);
|
||||
});
|
||||
|
||||
test("resolveEnterprisesDirs does not include relative project enterprises dir", () => {
|
||||
delete process.env.HOSE_ENTERPRISES_DIR;
|
||||
delete process.env.HOSE_USER_ENTERPRISES_DIR;
|
||||
const customConfigFile = join(tempDir, "config.json");
|
||||
process.env.HOSE_CONFIG_FILE = customConfigFile;
|
||||
|
||||
const dirs = resolveEnterprisesDirs();
|
||||
// Must never contain relative "enterprises"
|
||||
expect(dirs).not.toContain("enterprises");
|
||||
});
|
||||
|
||||
test("resolveEnterprisesDirs prioritizes testEnterprisesDir from global config", () => {
|
||||
delete process.env.HOSE_ENTERPRISES_DIR;
|
||||
delete process.env.HOSE_USER_ENTERPRISES_DIR;
|
||||
const customConfigFile = join(tempDir, "config.json");
|
||||
process.env.HOSE_CONFIG_FILE = customConfigFile;
|
||||
|
||||
const customTestDir = join(tempDir, "my-test-enterprises");
|
||||
mkdirSync(customTestDir, { recursive: true });
|
||||
|
||||
saveGlobalConfig({ testEnterprisesDir: customTestDir });
|
||||
const dirs = resolveEnterprisesDirs();
|
||||
expect(dirs[0]).toBe(customTestDir);
|
||||
expect(resolveWritableEnterprisesDir()).toBe(customTestDir);
|
||||
|
||||
const candidates = getEnterprisesDirCandidates();
|
||||
expect(candidates).toContain(`testEnterprisesDir: ${customTestDir}`);
|
||||
});
|
||||
|
||||
test("resolveWritableEnterprisesDir respects HOSE_ENTERPRISES_DIR", () => {
|
||||
const customDir = join(tempDir, "writable-enterprises");
|
||||
mkdirSync(customDir, { recursive: true });
|
||||
|
||||
+13
-14
@@ -3,7 +3,6 @@ import { homedir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigSchema } from "./types.js";
|
||||
|
||||
const ENTERPRISES_DIR = "enterprises";
|
||||
const CONFIG_ENV = "HOSE_ENTERPRISES_DIR";
|
||||
const USER_DIR_ENV = "HOSE_USER_ENTERPRISES_DIR";
|
||||
const GLOBAL_CONFIG_ENV = "HOSE_CONFIG_FILE";
|
||||
@@ -26,13 +25,16 @@ export function resolveEnterprisesDirs(): string[] {
|
||||
}
|
||||
|
||||
const configuredUserDir = process.env[USER_DIR_ENV]?.trim();
|
||||
if (configuredUserDir) {
|
||||
return [ENTERPRISES_DIR, configuredUserDir].filter((dir) => existsSync(dir));
|
||||
}
|
||||
const userDirs = configuredUserDir
|
||||
? (existsSync(configuredUserDir) ? [configuredUserDir] : [])
|
||||
: [PRIMARY_USER_ENTERPRISES_DIR, LEGACY_USER_ENTERPRISES_DIR];
|
||||
|
||||
const dirs = [ENTERPRISES_DIR, PRIMARY_USER_ENTERPRISES_DIR, LEGACY_USER_ENTERPRISES_DIR];
|
||||
const globalConfig = loadGlobalConfig();
|
||||
const testDir = globalConfig.testEnterprisesDir?.trim();
|
||||
|
||||
const candidates = testDir ? [testDir, ...userDirs] : userDirs;
|
||||
const uniqueExisting: string[] = [];
|
||||
for (const d of dirs) {
|
||||
for (const d of candidates) {
|
||||
if (existsSync(d) && !uniqueExisting.includes(d)) {
|
||||
uniqueExisting.push(d);
|
||||
}
|
||||
@@ -41,12 +43,7 @@ export function resolveEnterprisesDirs(): string[] {
|
||||
}
|
||||
|
||||
export function resolvePrimaryEnterprisesDir(): string | undefined {
|
||||
const configured = process.env[CONFIG_ENV]?.trim();
|
||||
if (configured) return existsSync(configured) ? configured : undefined;
|
||||
if (existsSync(ENTERPRISES_DIR)) return ENTERPRISES_DIR;
|
||||
if (existsSync(PRIMARY_USER_ENTERPRISES_DIR)) return PRIMARY_USER_ENTERPRISES_DIR;
|
||||
if (existsSync(LEGACY_USER_ENTERPRISES_DIR)) return LEGACY_USER_ENTERPRISES_DIR;
|
||||
return undefined;
|
||||
return resolveEnterprisesDirs()[0];
|
||||
}
|
||||
|
||||
export function resolveWritableEnterprisesDir(): string {
|
||||
@@ -54,14 +51,16 @@ export function resolveWritableEnterprisesDir(): string {
|
||||
if (configured) return configured;
|
||||
const configuredUserDir = process.env[USER_DIR_ENV]?.trim();
|
||||
if (configuredUserDir) return configuredUserDir;
|
||||
if (existsSync(ENTERPRISES_DIR)) return ENTERPRISES_DIR;
|
||||
const testDir = loadGlobalConfig().testEnterprisesDir?.trim();
|
||||
if (testDir && existsSync(testDir)) return testDir;
|
||||
return PRIMARY_USER_ENTERPRISES_DIR;
|
||||
}
|
||||
|
||||
export function getEnterprisesDirCandidates(): string[] {
|
||||
const testDir = loadGlobalConfig().testEnterprisesDir?.trim();
|
||||
return [
|
||||
`${CONFIG_ENV}=<path>`,
|
||||
ENTERPRISES_DIR,
|
||||
...(testDir ? [`testEnterprisesDir: ${testDir}`] : []),
|
||||
PRIMARY_USER_ENTERPRISES_DIR,
|
||||
LEGACY_USER_ENTERPRISES_DIR,
|
||||
];
|
||||
|
||||
@@ -4,6 +4,8 @@ import { saveGlobalConfig } from "./loader.js";
|
||||
export interface CorpSummary {
|
||||
id: string;
|
||||
name: string;
|
||||
corpId?: string;
|
||||
staffName?: string;
|
||||
source?: string;
|
||||
accountId?: string;
|
||||
staffId: string;
|
||||
@@ -143,16 +145,22 @@ export class CorpContext {
|
||||
return true;
|
||||
}
|
||||
|
||||
getAllCorps(): CorpConfig[] {
|
||||
return Array.from(this.corps.values());
|
||||
}
|
||||
|
||||
listCorps(): CorpSummary[] {
|
||||
return Array.from(this.corps.values()).map((corp) => ({
|
||||
id: corp.id,
|
||||
name: corp.name,
|
||||
corpId: corp.corpId || corp.credentials.corpId,
|
||||
staffId: corp.credentials.staffId,
|
||||
staffName: corp.staffName || corp.session?.staffName || undefined,
|
||||
source: corp.source || "manual",
|
||||
accountId: corp.accountId,
|
||||
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),
|
||||
}));
|
||||
}
|
||||
}
|
||||
+18
-15
@@ -4,6 +4,7 @@ export const CredentialSourceSchema = z.enum([
|
||||
"account", // 官方统一认证中心 (IDP) 账密/短信登录
|
||||
"assist", // 官方协助/代客平台 (Assist Platform) 调试授权会话
|
||||
"browser", // 浏览器会话 / Cookie 同步
|
||||
"link", // 协助/免密链接导入 (thirdparty.html / assistance link)
|
||||
"manual", // 手动配置
|
||||
"curl", // cURL 抓包 / HTTP Headers 导入
|
||||
"f12", // 兼容旧版抓包标识
|
||||
@@ -23,20 +24,20 @@ export const CorpAuthConfigSchema = z.object({
|
||||
});
|
||||
|
||||
export const CorpSessionInfoSchema = z.object({
|
||||
platform: z.string().optional().describe("官方会话平台类型 (如 ASSIST, WEB, MOBILE, OPENAPI)"),
|
||||
isAssistPlatform: z.boolean().optional().describe("是否为官方协助/代客平台登录"),
|
||||
isShortTermToken: z.boolean().optional().describe("是否为短期临时 Token"),
|
||||
assistId: z.string().optional().describe("协助会话/工单 ID"),
|
||||
operationUserId: z.string().optional().describe("协助操作人 ID (如内部运维/实施账号)"),
|
||||
operationUserName: z.string().optional().describe("协助操作人姓名"),
|
||||
staffName: z.string().optional().describe("当前员工真实姓名"),
|
||||
cellphone: z.string().optional().describe("绑定手机号"),
|
||||
isAdmin: z.boolean().optional().describe("是否管理员"),
|
||||
deviceType: z.string().optional().describe("设备类型"),
|
||||
loginAccountType: z.string().optional().describe("登录账号类型"),
|
||||
loginTime: z.number().optional().describe("登录时间戳 (ms)"),
|
||||
expTime: z.number().optional().describe("过期时间戳 (ms)"),
|
||||
sourceChannel: z.string().optional().describe("来源渠道 (如 APP, WEB)"),
|
||||
platform: z.string().nullable().optional().describe("官方会话平台类型 (如 ASSIST, WEB, MOBILE, OPENAPI)"),
|
||||
isAssistPlatform: z.boolean().nullable().optional().describe("是否为官方协助/代客平台登录"),
|
||||
isShortTermToken: z.boolean().nullable().optional().describe("是否为短期临时 Token"),
|
||||
assistId: z.string().nullable().optional().describe("协助会话/工单 ID"),
|
||||
operationUserId: z.string().nullable().optional().describe("协助操作人 ID (如内部运维/实施账号)"),
|
||||
operationUserName: z.string().nullable().optional().describe("协助操作人姓名"),
|
||||
staffName: z.string().nullable().optional().describe("当前员工真实姓名"),
|
||||
cellphone: z.string().nullable().optional().describe("绑定手机号"),
|
||||
isAdmin: z.boolean().nullable().optional().describe("是否管理员"),
|
||||
deviceType: z.string().nullable().optional().describe("设备类型"),
|
||||
loginAccountType: z.string().nullable().optional().describe("登录账号类型"),
|
||||
loginTime: z.number().nullable().optional().describe("登录时间戳 (ms)"),
|
||||
expTime: z.number().nullable().optional().describe("过期时间戳 (ms)"),
|
||||
sourceChannel: z.string().nullable().optional().describe("来源渠道 (如 APP, WEB)"),
|
||||
});
|
||||
export type CorpSessionInfo = z.infer<typeof CorpSessionInfoSchema>;
|
||||
|
||||
@@ -48,7 +49,8 @@ export const CorpConfigSchema = z.object({
|
||||
staffId: z.string().optional().describe("员工工号 (默认取 credentials.staffId)"),
|
||||
staffName: z.string().optional().describe("员工真实姓名"),
|
||||
baseUrl: z.string().url().optional().default("https://app.ekuaibao.com"),
|
||||
source: CredentialSourceSchema.optional().default("manual").describe("凭证来源: account/assist/browser/manual/curl/f12"),
|
||||
cluster: z.string().optional().describe("企业部署集群 (如 app, wx2, wx)"),
|
||||
source: CredentialSourceSchema.optional().default("manual").describe("凭证来源: account/assist/browser/link/manual/curl/f12"),
|
||||
accountId: z.string().optional().describe("所属主账号标识(如手机号)"),
|
||||
credentials: CorpCredentialsSchema,
|
||||
auth: CorpAuthConfigSchema.optional(),
|
||||
@@ -65,6 +67,7 @@ export const GlobalConfigSchema = z.object({
|
||||
stateful: z.boolean().default(true).describe("是否为有状态模式 (true 记忆默认企业,false 无状态需显式传 --corp)"),
|
||||
defaultCorpId: z.string().optional().describe("默认工作企业 ID"),
|
||||
defaultAccountId: z.string().optional().describe("默认主账号"),
|
||||
testEnterprisesDir: z.string().min(1).optional().describe("测试/自定义企业目录(仅用于开发测试重载,优先于全局用户目录)"),
|
||||
updateRepo: z.string().optional().describe("默认自更新的 GitHub 仓库 (owner/repo)"),
|
||||
updateSource: z.enum(["auto", "github", "gitea"]).optional().default("auto").describe("默认自更新源通道偏好 (auto/github/gitea)"),
|
||||
});
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import { chmodSync, existsSync, mkdirSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { runMigrations } from "./migrations.js";
|
||||
import type { DatabaseConnectionOptions } from "./types.js";
|
||||
|
||||
export const DEFAULT_DB_PATH = join(
|
||||
homedir(),
|
||||
".config",
|
||||
"hose-use",
|
||||
"approval.db"
|
||||
);
|
||||
|
||||
export function resolveDatabasePath(): string {
|
||||
const envPath = process.env.HOSE_APPROVAL_DB?.trim();
|
||||
if (envPath) {
|
||||
return envPath;
|
||||
}
|
||||
return DEFAULT_DB_PATH;
|
||||
}
|
||||
|
||||
let activeDb: Database | null = null;
|
||||
let currentDbPath: string | null = null;
|
||||
|
||||
/**
|
||||
* 获取或创建 SQLite 数据库连接单例,自动执行版本迁移
|
||||
*/
|
||||
export function getDatabase(options?: DatabaseConnectionOptions | string): Database {
|
||||
const customPath = typeof options === "string" ? options : options?.customPath;
|
||||
const targetPath = customPath ?? resolveDatabasePath();
|
||||
|
||||
if (activeDb && currentDbPath === targetPath) {
|
||||
return activeDb;
|
||||
}
|
||||
|
||||
// 若存在旧的不同路径连接,先优雅关闭释放文件句柄 (MAJ-12)
|
||||
if (activeDb && currentDbPath !== targetPath) {
|
||||
closeDatabase();
|
||||
}
|
||||
|
||||
// 内存数据库无需创建物理目录
|
||||
if (targetPath !== ":memory:") {
|
||||
const dir = dirname(targetPath);
|
||||
if (!existsSync(dir)) {
|
||||
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
||||
}
|
||||
try {
|
||||
chmodSync(dir, 0o700);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
const db = new Database(targetPath);
|
||||
|
||||
if (targetPath !== ":memory:") {
|
||||
// 保护敏感业务规则、缓存、会话与审计数据 (0o600)
|
||||
try {
|
||||
chmodSync(targetPath, 0o600);
|
||||
} catch {
|
||||
// 容错处理
|
||||
}
|
||||
}
|
||||
|
||||
// 启用 WAL 模式与并发优化
|
||||
db.run("PRAGMA journal_mode = WAL;");
|
||||
db.run("PRAGMA foreign_keys = ON;");
|
||||
// 关键:避免 0ms 锁超时崩溃,允许并发等待 5000ms (MAJ-02)
|
||||
db.run("PRAGMA busy_timeout = 5000;");
|
||||
db.run("PRAGMA synchronous = NORMAL;");
|
||||
|
||||
try {
|
||||
// 自动执行结构化原子迁移
|
||||
runMigrations(db);
|
||||
} catch (err) {
|
||||
// CRIT-03: 若迁移失败,坚决不激活单例缓存,关闭句柄并向外抛出错误
|
||||
try {
|
||||
db.close();
|
||||
} catch {}
|
||||
activeDb = null;
|
||||
currentDbPath = null;
|
||||
throw err;
|
||||
}
|
||||
|
||||
// 迁移彻底成功后,才正式激活单例
|
||||
currentDbPath = targetPath;
|
||||
activeDb = db;
|
||||
|
||||
return db;
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭并清理当前活跃数据库连接
|
||||
*/
|
||||
export function closeDatabase(): void {
|
||||
if (activeDb) {
|
||||
try {
|
||||
activeDb.close();
|
||||
} catch {
|
||||
// 容错
|
||||
}
|
||||
activeDb = null;
|
||||
currentDbPath = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { closeDatabase, getDatabase } from "./connection.js";
|
||||
import { runMigrations } from "./migrations.js";
|
||||
|
||||
describe("Core DB - 数据库连接与结构化迁移机制 (加固测试)", () => {
|
||||
let db: Database;
|
||||
|
||||
beforeEach(() => {
|
||||
db = getDatabase(":memory:");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
closeDatabase();
|
||||
});
|
||||
|
||||
test("数据库初始化时自动应用所有版本迁移并记录到 _schema_migrations", () => {
|
||||
const rows = db.query("SELECT version, name FROM _schema_migrations ORDER BY version ASC").all() as Array<{
|
||||
version: number;
|
||||
name: string;
|
||||
}>;
|
||||
expect(rows.length).toBeGreaterThanOrEqual(1);
|
||||
expect(rows[0].version).toBe(1);
|
||||
expect(rows[0].name).toBe("001_core_schema_and_approval_tables");
|
||||
});
|
||||
|
||||
test("核心数据表与新增的多级缓存表结构完备且索引有效", () => {
|
||||
// 检查表是否存在
|
||||
const tables = db
|
||||
.query("SELECT name FROM sqlite_master WHERE type = 'table'")
|
||||
.all() as Array<{ name: string }>;
|
||||
const tableNames = new Set(tables.map((t) => t.name));
|
||||
|
||||
expect(tableNames.has("rules")).toBe(true);
|
||||
expect(tableNames.has("preferences")).toBe(true);
|
||||
expect(tableNames.has("approval_runs")).toBe(true);
|
||||
expect(tableNames.has("approval_findings")).toBe(true);
|
||||
expect(tableNames.has("aipro_logs")).toBe(true);
|
||||
expect(tableNames.has("cache_entries")).toBe(true);
|
||||
|
||||
// 检查加固索引:UPPER(short_id)、findings(rule_id)
|
||||
const indices = db
|
||||
.query("SELECT name FROM sqlite_master WHERE type = 'index'")
|
||||
.all() as Array<{ name: string }>;
|
||||
const indexNames = new Set(indices.map((i) => i.name));
|
||||
|
||||
expect(indexNames.has("idx_runs_corp_id")).toBe(true);
|
||||
expect(indexNames.has("idx_runs_expires_at")).toBe(true);
|
||||
expect(indexNames.has("idx_runs_flow_id")).toBe(true);
|
||||
expect(indexNames.has("idx_runs_short_id_upper")).toBe(true);
|
||||
expect(indexNames.has("idx_findings_rule_id")).toBe(true);
|
||||
expect(indexNames.has("idx_cache_namespace")).toBe(true);
|
||||
expect(indexNames.has("idx_cache_expires_at")).toBe(true);
|
||||
});
|
||||
|
||||
test("cache_entries 具备复合主键 (namespace, key) 约束", () => {
|
||||
db.run(
|
||||
"INSERT INTO cache_entries (namespace, key, value, expires_at, updated_at) VALUES ('n1', 'k1', 'v1', 9999, 1000)"
|
||||
);
|
||||
// 相同 key 但不同 namespace 可以成功插入
|
||||
db.run(
|
||||
"INSERT INTO cache_entries (namespace, key, value, expires_at, updated_at) VALUES ('n2', 'k1', 'v2', 9999, 1000)"
|
||||
);
|
||||
|
||||
const countRow = db.query("SELECT COUNT(*) AS c FROM cache_entries WHERE key = 'k1'").get() as { c: number };
|
||||
expect(countRow.c).toBe(2);
|
||||
});
|
||||
|
||||
test("再次执行 runMigrations 保证幂等且不抛错", () => {
|
||||
expect(() => runMigrations(db)).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,3 @@
|
||||
export * from "./types.js";
|
||||
export * from "./connection.js";
|
||||
export * from "./migrations.js";
|
||||
@@ -0,0 +1,211 @@
|
||||
import type { Database } from "bun:sqlite";
|
||||
import type { DatabaseMigration } from "./types.js";
|
||||
|
||||
function hasColumn(db: Database, tableName: string, columnName: string): boolean {
|
||||
try {
|
||||
const rows = db.query(`PRAGMA table_info(${tableName})`).all() as Array<{ name: string }>;
|
||||
return rows.some((r) => r.name === columnName);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export const migrations: DatabaseMigration[] = [
|
||||
{
|
||||
version: 1,
|
||||
name: "001_core_schema_and_approval_tables",
|
||||
up(db: Database): void {
|
||||
// 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
|
||||
);
|
||||
`);
|
||||
|
||||
// 增量兼容老库缺省列
|
||||
if (!hasColumn(db, "approval_runs", "scope")) {
|
||||
try { db.run("ALTER TABLE approval_runs ADD COLUMN scope TEXT;"); } catch {}
|
||||
}
|
||||
if (!hasColumn(db, "approval_runs", "short_id")) {
|
||||
try { db.run("ALTER TABLE approval_runs ADD COLUMN short_id TEXT;"); } catch {}
|
||||
}
|
||||
if (!hasColumn(db, "approval_runs", "expires_at")) {
|
||||
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);");
|
||||
// MAJ-06: 支持 UPPER(short_id) 大小写不敏感快速定位
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_runs_short_id_upper ON approval_runs(UPPER(short_id));");
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_runs_created_at ON approval_runs(created_at);");
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_runs_corp_id ON approval_runs(corp_id);");
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_runs_flow_id ON approval_runs(flow_id);");
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_runs_expires_at ON approval_runs(expires_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);");
|
||||
// MAJ-07: 补充外键索引,防止外键删除全表扫描
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_findings_rule_id ON approval_findings(rule_id);");
|
||||
|
||||
// 5. 全流程操作与审计流水表
|
||||
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
|
||||
);
|
||||
`);
|
||||
if (!hasColumn(db, "aipro_logs", "run_id")) {
|
||||
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);");
|
||||
|
||||
// 6. 多级缓存持久化表 (L2 Persistent Cache)
|
||||
// CRIT-02: 采用复合主键 (namespace, key),彻底杜绝跨命名空间键碰撞
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS cache_entries (
|
||||
namespace TEXT NOT NULL,
|
||||
key TEXT NOT NULL,
|
||||
value TEXT NOT NULL,
|
||||
expires_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (namespace, key)
|
||||
);
|
||||
`);
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_cache_namespace ON cache_entries(namespace);");
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_cache_expires_at ON cache_entries(expires_at);");
|
||||
|
||||
// 种子数据:初始化默认偏好(CRIT-05: 使用 INSERT OR IGNORE 保证多进程启动绝对幂等)
|
||||
seedDefaultPreference(db);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
function seedDefaultPreference(db: Database): void {
|
||||
const now = Date.now();
|
||||
// CRIT-05: 使用 INSERT OR IGNORE 消除多进程并发启动 UNIQUE 冲突
|
||||
db.run(
|
||||
`
|
||||
INSERT OR IGNORE INTO preferences (
|
||||
id, name, is_default, rules_reject, rules_review, rules_pass_note, rules_approve, updated_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`,
|
||||
[
|
||||
"default",
|
||||
"标准财务审批偏好",
|
||||
1,
|
||||
"确认触犯任何 @{硬性} 条款(刚性底线,直接阻断)",
|
||||
"触发任何 @{特殊} 条款;未满足 @{弹性} 条款且单据金额 > 500 元;未满足 @{弹性} 累计达 3 处以上;单据未命中任何已有规则",
|
||||
"未满足 @{弹性} 条款但单据金额 <= 500 元(企业尺度豁免放行);未满足 @{建议} 条款(倡导性要求,附温馨提示)",
|
||||
"所有条款全部满足,秒级免审全自动通过",
|
||||
now,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行迁移:自动检测并按序原子执行未应用的 migration (CRIT-04)
|
||||
*/
|
||||
export function runMigrations(db: Database): void {
|
||||
// 创建迁移历史版本表
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS _schema_migrations (
|
||||
version INTEGER PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
applied_at INTEGER NOT NULL
|
||||
);
|
||||
`);
|
||||
|
||||
const appliedRows = db
|
||||
.query("SELECT version FROM _schema_migrations ORDER BY version ASC")
|
||||
.all() as Array<{ version: number }>;
|
||||
const appliedVersions = new Set(appliedRows.map((r) => r.version));
|
||||
|
||||
// 按版本号升序排列依次执行
|
||||
const sortedMigrations = [...migrations].sort((a, b) => a.version - b.version);
|
||||
|
||||
for (const migration of sortedMigrations) {
|
||||
if (!appliedVersions.has(migration.version)) {
|
||||
// CRIT-04: 使用 BEGIN IMMEDIATE 事务原子包裹
|
||||
db.run("BEGIN IMMEDIATE;");
|
||||
try {
|
||||
migration.up(db);
|
||||
db.run(
|
||||
"INSERT INTO _schema_migrations (version, name, applied_at) VALUES (?, ?, ?)",
|
||||
[migration.version, migration.name, Date.now()]
|
||||
);
|
||||
db.run("COMMIT;");
|
||||
} catch (err) {
|
||||
try {
|
||||
db.run("ROLLBACK;");
|
||||
} catch {}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { Database } from "bun:sqlite";
|
||||
|
||||
export interface DatabaseMigration {
|
||||
version: number;
|
||||
name: string;
|
||||
up: (db: Database) => void;
|
||||
}
|
||||
|
||||
export interface DatabaseConnectionOptions {
|
||||
customPath?: string;
|
||||
readOnly?: boolean;
|
||||
}
|
||||
@@ -27,6 +27,11 @@ 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");
|
||||
expect(EMBEDDED_SKILL_FILES["references/feetype.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/feetype.md"]).toContain("feetype");
|
||||
});
|
||||
|
||||
test("installSkillFiles 递归保留层级结构并落盘到目标目录", () => {
|
||||
@@ -34,12 +39,14 @@ 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(13);
|
||||
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", "feetype.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "role.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "workflow.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "service.md"))).toBe(true);
|
||||
|
||||
@@ -13,12 +13,16 @@ 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" };
|
||||
import refFeeType from "../../skills/hose-use/references/feetype.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/feetype.md": refFeeType,
|
||||
"references/contact.md": refContact,
|
||||
"references/task.md": refTask,
|
||||
"references/message.md": refMessage,
|
||||
|
||||
@@ -20,3 +20,10 @@ export class AuthenticationError extends EkbError {
|
||||
super(message, "AUTH_FAILED", 401);
|
||||
}
|
||||
}
|
||||
|
||||
export class BusinessError extends EkbError {
|
||||
constructor(message: string, code = "BUSINESS_ERROR", status = 400) {
|
||||
super(message, code, status);
|
||||
this.name = "BusinessError";
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,8 @@ export interface CreateAuthClientOptions {
|
||||
prefixUrl: string;
|
||||
getHeaders: () => Promise<Record<string, string>> | Record<string, string>;
|
||||
onUnauthorized?: () => Promise<void> | void;
|
||||
onAuthFailure?: (response: Response) => Error;
|
||||
retryUnauthorized?: boolean;
|
||||
}
|
||||
|
||||
export function createClient(options: CreateClientOptions): KyInstance {
|
||||
@@ -22,7 +24,7 @@ export function createAuthClient(options: CreateAuthClientOptions): KyInstance {
|
||||
return ky.create({
|
||||
prefix: options.prefixUrl,
|
||||
retry: {
|
||||
limit: 1,
|
||||
limit: options.retryUnauthorized === false ? 0 : 1,
|
||||
methods: ["get", "post", "put", "delete", "patch"],
|
||||
statusCodes: [401],
|
||||
},
|
||||
@@ -59,6 +61,9 @@ export function createAuthClient(options: CreateAuthClientOptions): KyInstance {
|
||||
}
|
||||
return ky(request);
|
||||
}
|
||||
if (isAuthError && options.onAuthFailure) {
|
||||
throw options.onAuthFailure(response);
|
||||
}
|
||||
return response;
|
||||
},
|
||||
],
|
||||
|
||||
@@ -7,7 +7,10 @@
|
||||
| 域 | 说明 | 详细文档 |
|
||||
|---|---|---|
|
||||
| `platform/` | 自建应用(DataLink Platform)与工作流(EASO/Piper) | [README.platform.md](./platform/README.platform.md) |
|
||||
| `datalink/` | 自建应用下的业务对象、字段、记录、权限与导入状态 | [README.datalink.md](./datalink/README.datalink.md) |
|
||||
| `bill/` | 费控单据、报销单、发票与 DataLink 实体字典 | [README.bill.md](./bill/README.bill.md) |
|
||||
| `store/` | 企业应用中心/应用商店与 OpenAPI 密钥凭证 | [README.store.md](./store/README.store.md) |
|
||||
| `feetype/` | 企业费用类型全生命周期管理与字段规格配置 | [README.feetype.md](./feetype/README.feetype.md) |
|
||||
|
||||
## 分层规则
|
||||
|
||||
|
||||
+16
-181
@@ -1,200 +1,35 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import { chmodSync, existsSync, mkdirSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import type { Database } from "bun:sqlite";
|
||||
import {
|
||||
DEFAULT_DB_PATH,
|
||||
closeDatabase,
|
||||
getDatabase,
|
||||
resolveDatabasePath,
|
||||
runMigrations,
|
||||
} from "../../core/db/index.js";
|
||||
|
||||
export const DEFAULT_APPROVAL_DB_PATH = join(
|
||||
homedir(),
|
||||
".config",
|
||||
"hose-use",
|
||||
"approval.db"
|
||||
);
|
||||
export const DEFAULT_APPROVAL_DB_PATH = DEFAULT_DB_PATH;
|
||||
|
||||
export function resolveApprovalDbPath(): string {
|
||||
const envPath = process.env.HOSE_APPROVAL_DB?.trim();
|
||||
if (envPath) {
|
||||
return envPath;
|
||||
}
|
||||
return DEFAULT_APPROVAL_DB_PATH;
|
||||
return resolveDatabasePath();
|
||||
}
|
||||
|
||||
let activeDb: Database | null = null;
|
||||
let currentDbPath: string | null = null;
|
||||
|
||||
/**
|
||||
* 获取或创建 SQLite 数据库连接单例
|
||||
* 获取或创建 SQLite 数据库连接单例(兼容原接口,底层使用 core/db)
|
||||
*/
|
||||
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;
|
||||
return getDatabase(customPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭并清理当前数据库连接(用于测试重置或进程退出)
|
||||
* 关闭并清理当前数据库连接
|
||||
*/
|
||||
export function closeApprovalDatabase(): void {
|
||||
if (activeDb) {
|
||||
activeDb.close();
|
||||
activeDb = null;
|
||||
currentDbPath = null;
|
||||
}
|
||||
closeDatabase();
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化表结构与默认数据
|
||||
* 初始化表结构与默认数据(兼容原接口,委托给 runMigrations)
|
||||
*/
|
||||
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
|
||||
]
|
||||
);
|
||||
}
|
||||
runMigrations(db);
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import {
|
||||
analyzeFindings,
|
||||
validateGatewayAction,
|
||||
evaluateGatewayPolicy,
|
||||
ApprovalGatewayPolicy,
|
||||
GatewayPolicyConfig,
|
||||
} from "./gateway.js";
|
||||
import { ApprovalFindingRecord, ApprovalGatewayBlockedError } from "./types.js";
|
||||
|
||||
function makeFinding(partial: Partial<ApprovalFindingRecord>): ApprovalFindingRecord {
|
||||
return {
|
||||
id: crypto.randomUUID(),
|
||||
runId: "test-run",
|
||||
clauseText: partial.clauseText ?? "测试条款",
|
||||
strictness: partial.strictness ?? "硬性",
|
||||
checkStatus: partial.checkStatus ?? "PASS",
|
||||
evidence: partial.evidence ?? null,
|
||||
reasoning: partial.reasoning ?? null,
|
||||
createdAt: Date.now(),
|
||||
};
|
||||
}
|
||||
|
||||
describe("Approval Gateway Policy - 可配置审批网关规则测试", () => {
|
||||
// ── 1. 硬性违规场景 ────────────────────────────────────────────────────────
|
||||
test("硬性违规:必须驳回,绝对禁止同意放行", () => {
|
||||
const findings: ApprovalFindingRecord[] = [
|
||||
makeFinding({ clauseText: "必须上传真实发票", strictness: "硬性", checkStatus: "FAIL", evidence: "无发票" }),
|
||||
makeFinding({ clauseText: "建议填写出差事由", strictness: "建议", checkStatus: "PASS" }),
|
||||
];
|
||||
|
||||
// 1.1 尝试 approve 必须被网关强力阻断
|
||||
expect(() => {
|
||||
validateGatewayAction({
|
||||
documentSn: "DOC-001",
|
||||
findings,
|
||||
requestedAction: "approve",
|
||||
opinion: "尝试放行",
|
||||
});
|
||||
}).toThrow(ApprovalGatewayBlockedError);
|
||||
|
||||
// 1.2 尝试 reject 可以正常放行
|
||||
expect(() => {
|
||||
validateGatewayAction({
|
||||
documentSn: "DOC-001",
|
||||
findings,
|
||||
requestedAction: "reject",
|
||||
opinion: "缺少发票予以驳回",
|
||||
});
|
||||
}).not.toThrow();
|
||||
|
||||
// 1.3 默认仲裁决断结果必须为 REJECT
|
||||
const result = evaluateGatewayPolicy({
|
||||
documentSn: "DOC-001",
|
||||
findings,
|
||||
});
|
||||
expect(result.decision).toBe("REJECT");
|
||||
expect(result.hardFailedCount).toBe(1);
|
||||
expect(result.decisionSummary).toContain("触犯硬性刚性条款,决策锁定为【驳回】");
|
||||
});
|
||||
|
||||
// ── 2. 零违规(全通过)场景 ────────────────────────────────────────────────
|
||||
test("零违规:没有硬性或弹性违规不能驳回,必须同意放行", () => {
|
||||
const findings: ApprovalFindingRecord[] = [
|
||||
makeFinding({ clauseText: "必须上传真实发票", strictness: "硬性", checkStatus: "PASS" }),
|
||||
makeFinding({ clauseText: "尽量上传付款水单", strictness: "弹性", checkStatus: "PASS" }),
|
||||
makeFinding({ clauseText: "建议补充事由", strictness: "建议", checkStatus: "SKIP" }),
|
||||
];
|
||||
|
||||
// 2.1 尝试 reject 必须被网关阻断(禁止无因驳回)
|
||||
expect(() => {
|
||||
validateGatewayAction({
|
||||
documentSn: "DOC-002",
|
||||
findings,
|
||||
requestedAction: "reject",
|
||||
opinion: "恶意驳回",
|
||||
});
|
||||
}).toThrow(ApprovalGatewayBlockedError);
|
||||
|
||||
try {
|
||||
validateGatewayAction({
|
||||
documentSn: "DOC-002",
|
||||
findings,
|
||||
requestedAction: "reject",
|
||||
opinion: "恶意驳回",
|
||||
});
|
||||
} catch (err: any) {
|
||||
expect(err.message).toContain("不存在任何【硬性】或【弹性】违规条款");
|
||||
}
|
||||
|
||||
// 2.2 尝试 approve 正常放行
|
||||
expect(() => {
|
||||
validateGatewayAction({
|
||||
documentSn: "DOC-002",
|
||||
findings,
|
||||
requestedAction: "approve",
|
||||
opinion: "合规通过",
|
||||
});
|
||||
}).not.toThrow();
|
||||
|
||||
// 2.3 决策结果为 APPROVE
|
||||
const result = evaluateGatewayPolicy({
|
||||
documentSn: "DOC-002",
|
||||
findings,
|
||||
});
|
||||
expect(result.decision).toBe("APPROVE");
|
||||
expect(result.decisionSummary).toContain("决策锁定为【同意通过】");
|
||||
});
|
||||
|
||||
// ── 3. 仅建议项违规场景 ────────────────────────────────────────────────────
|
||||
test("仅建议项违规:不构成驳回理由,禁止驳回,决断为备注通过", () => {
|
||||
const findings: ApprovalFindingRecord[] = [
|
||||
makeFinding({ clauseText: "必须上传真实发票", strictness: "硬性", checkStatus: "PASS" }),
|
||||
makeFinding({ clauseText: "建议补充说明消费事由", strictness: "建议", checkStatus: "FAIL", evidence: "事由偏简略" }),
|
||||
];
|
||||
|
||||
// 3.1 尝试驳回:建议项不能作为驳回理由,必须阻断
|
||||
expect(() => {
|
||||
validateGatewayAction({
|
||||
documentSn: "DOC-003",
|
||||
findings,
|
||||
requestedAction: "reject",
|
||||
opinion: "因事由简略驳回",
|
||||
});
|
||||
}).toThrow("建议项不构成驳回理由");
|
||||
|
||||
// 3.2 尝试同意:放行
|
||||
expect(() => {
|
||||
validateGatewayAction({
|
||||
documentSn: "DOC-003",
|
||||
findings,
|
||||
requestedAction: "approve",
|
||||
opinion: "备注事由后放行",
|
||||
});
|
||||
}).not.toThrow();
|
||||
|
||||
// 3.3 决断结果为 PASS_WITH_NOTE
|
||||
const result = evaluateGatewayPolicy({
|
||||
documentSn: "DOC-003",
|
||||
findings,
|
||||
});
|
||||
expect(result.decision).toBe("PASS_WITH_NOTE");
|
||||
expect(result.decisionSummary).toContain("决策锁定为【备注通过】");
|
||||
});
|
||||
|
||||
// ── 4. 弹性违规场景 ────────────────────────────────────────────────────────
|
||||
test("弹性违规:允许驳回;数量 <= 2 时为备注通过,>= 3 时建议人工复核", () => {
|
||||
// 4.1 存在 1 项弹性违规
|
||||
const findings1: ApprovalFindingRecord[] = [
|
||||
makeFinding({ clauseText: "必须上传发票", strictness: "硬性", checkStatus: "PASS" }),
|
||||
makeFinding({ clauseText: "尽量上传水单", strictness: "弹性", checkStatus: "FAIL", evidence: "未提供水单" }),
|
||||
];
|
||||
|
||||
// 因为有弹性违规,允许驳回
|
||||
expect(() => {
|
||||
validateGatewayAction({
|
||||
documentSn: "DOC-004-1",
|
||||
findings: findings1,
|
||||
requestedAction: "reject",
|
||||
opinion: "未提供水单予以驳回",
|
||||
});
|
||||
}).not.toThrow();
|
||||
|
||||
// 自动决断为 PASS_WITH_NOTE(弹性超标未达阈值)
|
||||
const result1 = evaluateGatewayPolicy({
|
||||
documentSn: "DOC-004-1",
|
||||
findings: findings1,
|
||||
});
|
||||
expect(result1.decision).toBe("PASS_WITH_NOTE");
|
||||
|
||||
// 4.2 存在 3 项弹性违规(达到阈值)
|
||||
const findings3: ApprovalFindingRecord[] = [
|
||||
makeFinding({ clauseText: "必须上传发票", strictness: "硬性", checkStatus: "PASS" }),
|
||||
makeFinding({ clauseText: "尽量上传水单1", strictness: "弹性", checkStatus: "FAIL" }),
|
||||
makeFinding({ clauseText: "尽量上传水单2", strictness: "弹性", checkStatus: "FAIL" }),
|
||||
makeFinding({ clauseText: "尽量上传水单3", strictness: "弹性", checkStatus: "FAIL" }),
|
||||
];
|
||||
|
||||
const result3 = evaluateGatewayPolicy({
|
||||
documentSn: "DOC-004-3",
|
||||
findings: findings3,
|
||||
});
|
||||
expect(result3.decision).toBe("REVIEW");
|
||||
expect(result3.decisionSummary).toContain("建议人工复核");
|
||||
});
|
||||
|
||||
// ── 5. 特殊项违规场景 ──────────────────────────────────────────────────────
|
||||
test("特殊项命中:转人工复核,禁止直接驳回", () => {
|
||||
const findings: ApprovalFindingRecord[] = [
|
||||
makeFinding({ clauseText: "必须上传发票", strictness: "硬性", checkStatus: "PASS" }),
|
||||
makeFinding({ clauseText: "大额争议须法务审核", strictness: "特殊", checkStatus: "FAIL", evidence: "单据超10万" }),
|
||||
];
|
||||
|
||||
expect(() => {
|
||||
validateGatewayAction({
|
||||
documentSn: "DOC-005",
|
||||
findings,
|
||||
requestedAction: "reject",
|
||||
opinion: "法务未审直接驳回",
|
||||
});
|
||||
}).toThrow("特殊");
|
||||
|
||||
const result = evaluateGatewayPolicy({
|
||||
documentSn: "DOC-005",
|
||||
findings,
|
||||
});
|
||||
expect(result.decision).toBe("REVIEW");
|
||||
});
|
||||
|
||||
// ── 6. 待核验(PENDING)漏检拦截 ───────────────────────────────────────────
|
||||
test("待核验漏检保护:存在 PENDING 要点时,同意和驳回均被阻断", () => {
|
||||
const findings: ApprovalFindingRecord[] = [
|
||||
makeFinding({ clauseText: "发票检查", strictness: "硬性", checkStatus: "PASS" }),
|
||||
makeFinding({ clauseText: "住宿限额检查", strictness: "硬性", checkStatus: "PENDING" }),
|
||||
];
|
||||
|
||||
// 同意被阻断
|
||||
expect(() => {
|
||||
validateGatewayAction({
|
||||
documentSn: "DOC-006",
|
||||
findings,
|
||||
requestedAction: "approve",
|
||||
opinion: "盲目同意",
|
||||
});
|
||||
}).toThrow("PENDING 待核验状态");
|
||||
|
||||
// 驳回也被阻断(必须先完成核验)
|
||||
expect(() => {
|
||||
validateGatewayAction({
|
||||
documentSn: "DOC-006",
|
||||
findings,
|
||||
requestedAction: "reject",
|
||||
opinion: "盲目驳回",
|
||||
});
|
||||
}).toThrow("PENDING 待核验状态");
|
||||
});
|
||||
|
||||
// ── 7. 审批意见长度边角限制 ───────────────────────────────────────────────
|
||||
test("审批意见长度控制:超过 150 字符时抛错阻断", () => {
|
||||
const findings: ApprovalFindingRecord[] = [
|
||||
makeFinding({ clauseText: "发票检查", strictness: "硬性", checkStatus: "FAIL" }),
|
||||
];
|
||||
|
||||
const overLength = "超长意见内容".repeat(35); // > 150 字
|
||||
expect(() => {
|
||||
validateGatewayAction({
|
||||
documentSn: "DOC-007",
|
||||
findings,
|
||||
requestedAction: "reject",
|
||||
opinion: overLength,
|
||||
});
|
||||
}).toThrow("不可超过 150 字符");
|
||||
});
|
||||
|
||||
// ── 8. 自定义逻辑扩展钩子 (customHook) ────────────────────────────────────
|
||||
test("支持配置自定义网关钩子覆盖或扩展逻辑", () => {
|
||||
const findings: ApprovalFindingRecord[] = [
|
||||
makeFinding({ clauseText: "普通合规检查", strictness: "建议", checkStatus: "PASS" }),
|
||||
];
|
||||
|
||||
const policy = new ApprovalGatewayPolicy({
|
||||
customHook: (context, analysis, config) => {
|
||||
if (context.documentSn.startsWith("VIP-")) {
|
||||
return {
|
||||
decision: "APPROVE",
|
||||
decisionSummary: "VIP 单据走免审专属绿色通道",
|
||||
analysis,
|
||||
hardFailedCount: 0,
|
||||
elasticFailedCount: 0,
|
||||
suggestFailedCount: 0,
|
||||
specialFailedCount: 0,
|
||||
};
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const result = policy.evaluate({
|
||||
documentSn: "VIP-88888",
|
||||
findings,
|
||||
});
|
||||
|
||||
expect(result.decision).toBe("APPROVE");
|
||||
expect(result.decisionSummary).toBe("VIP 单据走免审专属绿色通道");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,334 @@
|
||||
import {
|
||||
ApprovalDecision,
|
||||
ApprovalFindingRecord,
|
||||
ApprovalGatewayBlockedError,
|
||||
StrictnessTier,
|
||||
} from "./types.js";
|
||||
|
||||
/**
|
||||
* 审批仲裁网关策略配置接口
|
||||
*/
|
||||
export interface GatewayPolicyConfig {
|
||||
/**
|
||||
* 弹性违规项允许的最大数量。超过此数量自动转为建议人工复核 (默认: 2)
|
||||
*/
|
||||
maxElasticViolationsForPassWithNote: number;
|
||||
|
||||
/**
|
||||
* 是否严格禁止在无硬性违规且无弹性违规时执行驳回 (默认: true)
|
||||
* 业务铁律:没有硬性违反或弹性违反不能驳回,物理切断恶意/无故驳回分支
|
||||
*/
|
||||
blockRejectWithoutHardOrElasticFailure: boolean;
|
||||
|
||||
/**
|
||||
* 是否在存在硬性违规时一票否决,物理切断同意分支 (默认: true)
|
||||
* 业务铁律:有硬性违反必须驳回(或复核),绝对禁止放行同意
|
||||
*/
|
||||
blockApproveWithHardFailure: boolean;
|
||||
|
||||
/**
|
||||
* 审批意见的最大字符数限制 (默认: 150)
|
||||
*/
|
||||
maxOpinionLength: number;
|
||||
|
||||
/**
|
||||
* 可配置的自定义逻辑扩展钩子。
|
||||
* 返回具体结果时直接作为最终裁决;返回 void 或 undefined 时继续执行标准裁决矩阵。
|
||||
*/
|
||||
customHook?: (
|
||||
context: GatewayContext,
|
||||
analysis: FindingsAnalysis,
|
||||
config: GatewayPolicyConfig
|
||||
) => GatewayDecisionResult | void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 网关默认策略配置
|
||||
*/
|
||||
export const DEFAULT_GATEWAY_CONFIG: GatewayPolicyConfig = {
|
||||
maxElasticViolationsForPassWithNote: 2,
|
||||
blockRejectWithoutHardOrElasticFailure: true,
|
||||
blockApproveWithHardFailure: true,
|
||||
maxOpinionLength: 150,
|
||||
};
|
||||
|
||||
/**
|
||||
* 网关裁决输入上下文
|
||||
*/
|
||||
export interface GatewayContext {
|
||||
documentSn: string;
|
||||
findings: ApprovalFindingRecord[];
|
||||
requestedAction?: "approve" | "reject" | "comment";
|
||||
opinion?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 要点事实核验分析结果
|
||||
*/
|
||||
export interface FindingsAnalysis {
|
||||
allFindings: ApprovalFindingRecord[];
|
||||
pendingFindings: ApprovalFindingRecord[];
|
||||
passedFindings: ApprovalFindingRecord[];
|
||||
failedFindings: ApprovalFindingRecord[];
|
||||
skippedFindings: ApprovalFindingRecord[];
|
||||
hardFailed: ApprovalFindingRecord[];
|
||||
elasticFailed: ApprovalFindingRecord[];
|
||||
suggestFailed: ApprovalFindingRecord[];
|
||||
specialFailed: ApprovalFindingRecord[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 网关综合判定结果
|
||||
*/
|
||||
export interface GatewayDecisionResult {
|
||||
decision: ApprovalDecision;
|
||||
decisionSummary: string;
|
||||
analysis: FindingsAnalysis;
|
||||
hardFailedCount: number;
|
||||
elasticFailedCount: number;
|
||||
suggestFailedCount: number;
|
||||
specialFailedCount: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 分析审核要点状态与严格度分布
|
||||
*/
|
||||
export function analyzeFindings(findings: ApprovalFindingRecord[]): FindingsAnalysis {
|
||||
const pendingFindings: ApprovalFindingRecord[] = [];
|
||||
const passedFindings: ApprovalFindingRecord[] = [];
|
||||
const failedFindings: ApprovalFindingRecord[] = [];
|
||||
const skippedFindings: ApprovalFindingRecord[] = [];
|
||||
const hardFailed: ApprovalFindingRecord[] = [];
|
||||
const elasticFailed: ApprovalFindingRecord[] = [];
|
||||
const suggestFailed: ApprovalFindingRecord[] = [];
|
||||
const specialFailed: ApprovalFindingRecord[] = [];
|
||||
|
||||
for (const f of findings) {
|
||||
if (f.checkStatus === "PENDING") {
|
||||
pendingFindings.push(f);
|
||||
} else if (f.checkStatus === "PASS") {
|
||||
passedFindings.push(f);
|
||||
} else if (f.checkStatus === "SKIP") {
|
||||
skippedFindings.push(f);
|
||||
} else if (f.checkStatus === "FAIL") {
|
||||
failedFindings.push(f);
|
||||
if (f.strictness === "硬性") {
|
||||
hardFailed.push(f);
|
||||
} else if (f.strictness === "弹性") {
|
||||
elasticFailed.push(f);
|
||||
} else if (f.strictness === "建议") {
|
||||
suggestFailed.push(f);
|
||||
} else if (f.strictness === "特殊") {
|
||||
specialFailed.push(f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
allFindings: findings,
|
||||
pendingFindings,
|
||||
passedFindings,
|
||||
failedFindings,
|
||||
skippedFindings,
|
||||
hardFailed,
|
||||
elasticFailed,
|
||||
suggestFailed,
|
||||
specialFailed,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验网关拟执行的动作是否合法(前置门禁防御)
|
||||
*
|
||||
* 包含核心卡点:
|
||||
* 1. 空要点清单拦截:未注入要点前物理切断审批链路
|
||||
* 2. 审批意见长度校验:超长直接拦截
|
||||
* 3. 待核验拦截:存在 PENDING 要点时禁止提前决断
|
||||
* 4. 硬性一票否决:有硬性违规绝对禁止同意放行
|
||||
* 5. 无因驳回拦截:无硬性违规且无弹性违规时绝对禁止驳回
|
||||
*
|
||||
* @throws {ApprovalGatewayBlockedError} 当任一门禁被触发时抛出
|
||||
*/
|
||||
export function validateGatewayAction(
|
||||
context: GatewayContext,
|
||||
userConfig?: Partial<GatewayPolicyConfig>
|
||||
): FindingsAnalysis {
|
||||
const config = { ...DEFAULT_GATEWAY_CONFIG, ...userConfig };
|
||||
|
||||
// ── 门禁 1: 空要点清单拦截 ────────────────────────────────────────────────
|
||||
if (!context.findings || context.findings.length === 0) {
|
||||
throw new ApprovalGatewayBlockedError(
|
||||
`[审批链路阻断] 单据 [${context.documentSn}] 尚未注入任何明细级审核要点(要点列表为空)!\n` +
|
||||
`网关卡点生效:审核要点未注入前,审批链路物理切断,绝对禁止进入审批决策!\n` +
|
||||
`请先执行: hose-aipro bind 挂载审核要点清单。`
|
||||
);
|
||||
}
|
||||
|
||||
// ── 门禁 2: 审批意见长度边角检查 ──────────────────────────────────────────
|
||||
if (context.opinion && context.opinion.length > config.maxOpinionLength) {
|
||||
throw new ApprovalGatewayBlockedError(
|
||||
`[参数校验阻断] 审批意见不可超过 ${config.maxOpinionLength} 字符,当前长度为 ${context.opinion.length} 字符,请精简。`
|
||||
);
|
||||
}
|
||||
|
||||
// ── 门禁 3: 漏检拦截(存在待核验项)───────────────────────────────────────
|
||||
const analysis = analyzeFindings(context.findings);
|
||||
if (analysis.pendingFindings.length > 0) {
|
||||
const pendingIndices = analysis.pendingFindings
|
||||
.map((f) => `#${context.findings.indexOf(f) + 1} [${f.strictness}] ${f.clauseText}`)
|
||||
.join(";");
|
||||
throw new ApprovalGatewayBlockedError(
|
||||
`[审批链路阻断] 单据 [${context.documentSn}] 尚有 ${analysis.pendingFindings.length} 处审核要点处于 PENDING 待核验状态!\n` +
|
||||
`网关卡点生效:禁止在核验未全部闭环前提前决断。\n` +
|
||||
`待核验项: ${pendingIndices}`
|
||||
);
|
||||
}
|
||||
|
||||
// ── 门禁 4: 硬性条款刚性底线(有硬性违规时绝对禁止同意)─────────────────
|
||||
if (context.requestedAction === "approve" && config.blockApproveWithHardFailure && analysis.hardFailed.length > 0) {
|
||||
const violatedNames = analysis.hardFailed
|
||||
.map((f) => `【#${context.findings.indexOf(f) + 1} ${f.clauseText}】`)
|
||||
.join("、");
|
||||
throw new ApprovalGatewayBlockedError(
|
||||
`[网关强力阻断] 单据 [${context.documentSn}] 存在硬性违规条款未通过(${violatedNames})!\n` +
|
||||
`网关物理切断“同意”流转,绝对禁止放行通过!当前只允许执行驳回 (reject) 或建议复核。`
|
||||
);
|
||||
}
|
||||
|
||||
// ── 门禁 5: 无因驳回拦截(没有硬性或弹性违规不能驳回)────────────────────
|
||||
if (
|
||||
context.requestedAction === "reject" &&
|
||||
config.blockRejectWithoutHardOrElasticFailure &&
|
||||
analysis.hardFailed.length === 0 &&
|
||||
analysis.elasticFailed.length === 0
|
||||
) {
|
||||
let detail = "单据所有核验要点均已通过";
|
||||
if (analysis.suggestFailed.length > 0) {
|
||||
const suggestNames = analysis.suggestFailed
|
||||
.map((f) => `【#${context.findings.indexOf(f) + 1} ${f.clauseText}】`)
|
||||
.join("、");
|
||||
detail = `单据仅存在倡导性的【建议】项未满足(${suggestNames}),建议项不构成驳回理由`;
|
||||
} else if (analysis.specialFailed.length > 0) {
|
||||
const specialNames = analysis.specialFailed
|
||||
.map((f) => `【#${context.findings.indexOf(f) + 1} ${f.clauseText}】`)
|
||||
.join("、");
|
||||
detail = `单据命中【特殊】条款(${specialNames}),按规则须提交人工复核,不能直接驳回`;
|
||||
}
|
||||
|
||||
throw new ApprovalGatewayBlockedError(
|
||||
`[网关安全阻断] 单据 [${context.documentSn}] 不存在任何【硬性】或【弹性】违规条款(${detail})!\n` +
|
||||
`网关物理切断驳回分支,严禁无故或恶意驳回!当前只允许执行同意 (approve) 或转人工复核。`
|
||||
);
|
||||
}
|
||||
|
||||
return analysis;
|
||||
}
|
||||
|
||||
/**
|
||||
* 确定性网关仲裁:执行所有校验并计算最终决策结果与审查报告
|
||||
*/
|
||||
export function evaluateGatewayPolicy(
|
||||
context: GatewayContext,
|
||||
userConfig?: Partial<GatewayPolicyConfig>
|
||||
): GatewayDecisionResult {
|
||||
const config = { ...DEFAULT_GATEWAY_CONFIG, ...userConfig };
|
||||
|
||||
// 1. 前置动作合法性校验(拦截非法同意、非法驳回、未闭环核验等)
|
||||
const analysis = validateGatewayAction(context, config);
|
||||
|
||||
// 2. 优先执行用户自定义逻辑钩子
|
||||
if (config.customHook) {
|
||||
const customResult = config.customHook(context, analysis, config);
|
||||
if (customResult) {
|
||||
return customResult;
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 执行标准确定性裁决矩阵
|
||||
let decision: ApprovalDecision;
|
||||
if (analysis.hardFailed.length > 0) {
|
||||
decision = "REJECT";
|
||||
} else if (analysis.specialFailed.length > 0) {
|
||||
decision = "REVIEW";
|
||||
} else if (analysis.elasticFailed.length > 0) {
|
||||
decision =
|
||||
analysis.elasticFailed.length > config.maxElasticViolationsForPassWithNote
|
||||
? "REVIEW"
|
||||
: "PASS_WITH_NOTE";
|
||||
} else if (analysis.suggestFailed.length > 0) {
|
||||
decision = "PASS_WITH_NOTE";
|
||||
} else {
|
||||
decision = "APPROVE";
|
||||
}
|
||||
|
||||
// 4. 组装格式化合规审查报告
|
||||
const summaryLines: string[] = [];
|
||||
summaryLines.push(`【合思 AI 确定性网关审查报告】`);
|
||||
summaryLines.push(`单号: ${context.documentSn} | 审核要点总数: ${context.findings.length} 项`);
|
||||
summaryLines.push(``);
|
||||
summaryLines.push(`[逐项核验事实]`);
|
||||
context.findings.forEach((f, idx) => {
|
||||
const icon = f.checkStatus === "PASS" ? "✅" : f.checkStatus === "FAIL" ? "❌" : "➖";
|
||||
const reason = f.evidence || f.reasoning ? ` (${[f.evidence, f.reasoning].filter(Boolean).join(" - ")})` : "";
|
||||
summaryLines.push(` ${icon} #${idx + 1} [${f.strictness}] ${f.clauseText}${reason}`);
|
||||
});
|
||||
summaryLines.push(``);
|
||||
|
||||
if (decision === "REJECT") {
|
||||
summaryLines.push(`[网关结论] ❌ 触犯硬性刚性条款,决策锁定为【驳回】`);
|
||||
} else if (decision === "REVIEW") {
|
||||
summaryLines.push(`[网关结论] ⚠️ 触发特殊或弹性超标条款,决策锁定为【建议人工复核】`);
|
||||
} else if (decision === "PASS_WITH_NOTE") {
|
||||
summaryLines.push(`[网关结论] 💡 满足核心要求,包含弹性/建议提示,决策锁定为【备注通过】`);
|
||||
} else {
|
||||
summaryLines.push(`[网关结论] ✅ 所有规则判定全部通过,决策锁定为【同意通过】`);
|
||||
}
|
||||
|
||||
if (context.opinion) {
|
||||
summaryLines.push(`[审批附加说明] ${context.opinion}`);
|
||||
}
|
||||
|
||||
const decisionSummary = summaryLines.join("\n");
|
||||
|
||||
return {
|
||||
decision,
|
||||
decisionSummary,
|
||||
analysis,
|
||||
hardFailedCount: analysis.hardFailed.length,
|
||||
elasticFailedCount: analysis.elasticFailed.length,
|
||||
suggestFailedCount: analysis.suggestFailed.length,
|
||||
specialFailedCount: analysis.specialFailed.length,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 可配置的审批仲裁网关策略类
|
||||
*/
|
||||
export class ApprovalGatewayPolicy {
|
||||
private config: GatewayPolicyConfig;
|
||||
|
||||
constructor(config?: Partial<GatewayPolicyConfig>) {
|
||||
this.config = { ...DEFAULT_GATEWAY_CONFIG, ...config };
|
||||
}
|
||||
|
||||
public getConfig(): GatewayPolicyConfig {
|
||||
return { ...this.config };
|
||||
}
|
||||
|
||||
public updateConfig(updates: Partial<GatewayPolicyConfig>): void {
|
||||
this.config = { ...this.config, ...updates };
|
||||
}
|
||||
|
||||
public validate(context: GatewayContext): FindingsAnalysis {
|
||||
return validateGatewayAction(context, this.config);
|
||||
}
|
||||
|
||||
public evaluate(context: GatewayContext): GatewayDecisionResult {
|
||||
return evaluateGatewayPolicy(context, this.config);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 全局默认网关单例
|
||||
*/
|
||||
export const defaultGatewayPolicy = new ApprovalGatewayPolicy();
|
||||
@@ -3,3 +3,4 @@ export * from "./parser.js";
|
||||
export * from "./db.js";
|
||||
export * from "./repository.js";
|
||||
export * from "./service.js";
|
||||
export * from "./gateway.js";
|
||||
@@ -398,6 +398,33 @@ export class ApprovalRepository {
|
||||
return row ? this.mapRunRow(row) : null;
|
||||
}
|
||||
|
||||
public listRuns(filter?: { corpId?: string; decision?: ApprovalDecision; limit?: number }): ApprovalRunRecord[] {
|
||||
const conditions: string[] = [];
|
||||
const params: (string | number)[] = [];
|
||||
|
||||
if (filter?.corpId !== undefined) {
|
||||
conditions.push("corp_id = ?");
|
||||
params.push(filter.corpId);
|
||||
}
|
||||
if (filter?.decision !== undefined) {
|
||||
conditions.push("decision = ?");
|
||||
params.push(filter.decision);
|
||||
}
|
||||
|
||||
let sql = "SELECT * FROM approval_runs";
|
||||
if (conditions.length > 0) {
|
||||
sql += " WHERE " + conditions.join(" AND ");
|
||||
}
|
||||
sql += " ORDER BY created_at DESC";
|
||||
if (filter?.limit) {
|
||||
sql += " LIMIT ?";
|
||||
params.push(filter.limit);
|
||||
}
|
||||
|
||||
const rows = this.db.query(sql).all(...params) as any[];
|
||||
return rows.map((r) => this.mapRunRow(r));
|
||||
}
|
||||
|
||||
public updateApprovalRun(
|
||||
id: string,
|
||||
updates: Partial<Omit<ApprovalRunRecord, "id" | "documentSn" | "createdAt">>
|
||||
|
||||
@@ -8,6 +8,12 @@ import {
|
||||
ApprovalRunRecord,
|
||||
FindingCheckStatus,
|
||||
} from "./types.js";
|
||||
import {
|
||||
ApprovalGatewayPolicy,
|
||||
defaultGatewayPolicy,
|
||||
evaluateGatewayPolicy,
|
||||
GatewayPolicyConfig,
|
||||
} from "./gateway.js";
|
||||
import { getBillByCodeOrId, approveBill, rejectBill, commentBill } from "../bill/tools.js";
|
||||
import type { FormattedBill } from "../bill/types.js";
|
||||
|
||||
@@ -22,6 +28,7 @@ export interface DecideAuditOptions {
|
||||
requestedAction?: "approve" | "reject" | "comment";
|
||||
apply?: boolean;
|
||||
comment?: string;
|
||||
gatewayConfig?: Partial<GatewayPolicyConfig>;
|
||||
}
|
||||
|
||||
export interface DecideAuditResult {
|
||||
@@ -38,9 +45,11 @@ export interface DecideAuditResult {
|
||||
|
||||
export class ApprovalService {
|
||||
private repo: ApprovalRepository;
|
||||
private gatewayPolicy: ApprovalGatewayPolicy;
|
||||
|
||||
constructor(repo?: ApprovalRepository) {
|
||||
constructor(repo?: ApprovalRepository, gatewayPolicy?: ApprovalGatewayPolicy) {
|
||||
this.repo = repo ?? new ApprovalRepository();
|
||||
this.gatewayPolicy = gatewayPolicy ?? defaultGatewayPolicy;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -207,8 +216,7 @@ export class ApprovalService {
|
||||
): Promise<DecideAuditResult> {
|
||||
const { run, findings } = this.repo.getAuditChecklist(documentSn, corpId);
|
||||
|
||||
// ── 核心门禁 1:如果审核要点列表为空,审批链路物理不通! ────────────────────
|
||||
if (!run || findings.length === 0) {
|
||||
if (!run) {
|
||||
throw new ApprovalGatewayBlockedError(
|
||||
`[审批链路阻断] 单据 [${documentSn}] 尚未注入任何明细级审核要点(要点列表为空)!\n` +
|
||||
`网关卡点生效:审核要点未注入前,审批链路物理切断,绝对禁止进入审批决策!\n` +
|
||||
@@ -216,80 +224,31 @@ export class ApprovalService {
|
||||
);
|
||||
}
|
||||
|
||||
// ── 核心门禁 2:检查是否有未完成事实核验的 PENDING 要点 ──────────────────────
|
||||
const pendingFindings = findings.filter((f) => f.checkStatus === "PENDING");
|
||||
if (pendingFindings.length > 0) {
|
||||
throw new ApprovalGatewayBlockedError(
|
||||
`[审批链路阻断] 单据 [${documentSn}] 尚有 ${pendingFindings.length} 处审核要点处于 PENDING 待核验状态!\n` +
|
||||
`网关卡点生效:禁止在核验未全部闭环前提前决断。\n` +
|
||||
`待核验项: ${pendingFindings.map((f, i) => `#${i + 1} [${f.strictness}] ${f.clauseText}`).join(";")}`
|
||||
);
|
||||
}
|
||||
// 确定性网关仲裁:由独立的可配置网关策略脚本执行(执行核心门禁与裁决计算)
|
||||
const gatewayResult = evaluateGatewayPolicy(
|
||||
{
|
||||
documentSn,
|
||||
findings,
|
||||
requestedAction: options.requestedAction,
|
||||
opinion: options.comment,
|
||||
},
|
||||
options.gatewayConfig ?? this.gatewayPolicy.getConfig()
|
||||
);
|
||||
|
||||
// ── 核心门禁 3:梯度级别与硬性刚性防线 ───────────────────────────────────────
|
||||
const failedFindings = findings.filter((f) => f.checkStatus === "FAIL");
|
||||
const hardFailed = failedFindings.filter((f) => f.strictness === "硬性");
|
||||
const specialFailed = failedFindings.filter((f) => f.strictness === "特殊");
|
||||
const elasticFailed = failedFindings.filter((f) => f.strictness === "弹性");
|
||||
const suggestFailed = failedFindings.filter((f) => f.strictness === "建议");
|
||||
|
||||
// 硬性条款违规拦截:物理切断 approve 通道
|
||||
if (hardFailed.length > 0 && options.requestedAction === "approve") {
|
||||
const violatedNames = hardFailed.map((f) => `【${f.clauseText}】`).join("、");
|
||||
throw new ApprovalGatewayBlockedError(
|
||||
`[网关强力阻断] 单据 [${documentSn}] 触犯刚性底线【硬性】违规条款: ${violatedNames}!\n` +
|
||||
`网关物理切断同意分支,绝对禁止放行通过!当前只允许执行驳回 (reject) 或建议复核。`
|
||||
);
|
||||
}
|
||||
|
||||
// 计算网关裁决决策
|
||||
let decision: ApprovalDecision;
|
||||
if (hardFailed.length > 0) {
|
||||
decision = "REJECT";
|
||||
} else if (specialFailed.length > 0) {
|
||||
decision = "REVIEW";
|
||||
} else if (elasticFailed.length > 0) {
|
||||
decision = elasticFailed.length >= 3 ? "REVIEW" : "PASS_WITH_NOTE";
|
||||
} else if (suggestFailed.length > 0) {
|
||||
decision = "PASS_WITH_NOTE";
|
||||
} else {
|
||||
decision = "APPROVE";
|
||||
}
|
||||
|
||||
// 组装格式化合规意见报告
|
||||
const summaryLines: string[] = [];
|
||||
summaryLines.push(`【合思 AI 确定性网关审查报告】`);
|
||||
summaryLines.push(`单号: ${documentSn} | 审核要点总数: ${findings.length} 项`);
|
||||
summaryLines.push(``);
|
||||
summaryLines.push(`[逐项核验事实]`);
|
||||
findings.forEach((f, idx) => {
|
||||
const icon = f.checkStatus === "PASS" ? "✅" : f.checkStatus === "FAIL" ? "❌" : "➖";
|
||||
const reason = f.evidence || f.reasoning ? ` (${[f.evidence, f.reasoning].filter(Boolean).join(" - ")})` : "";
|
||||
summaryLines.push(` ${icon} #${idx + 1} [${f.strictness}] ${f.clauseText}${reason}`);
|
||||
});
|
||||
summaryLines.push(``);
|
||||
|
||||
if (decision === "REJECT") {
|
||||
summaryLines.push(`[网关结论] ❌ 触犯硬性刚性条款,决策锁定为【驳回】`);
|
||||
} else if (decision === "REVIEW") {
|
||||
summaryLines.push(`[网关结论] ⚠️ 触发特殊或弹性超标条款,决策锁定为【建议人工复核】`);
|
||||
} else if (decision === "PASS_WITH_NOTE") {
|
||||
summaryLines.push(`[网关结论] 💡 满足核心要求,包含弹性/建议提示,决策锁定为【备注通过】`);
|
||||
} else {
|
||||
summaryLines.push(`[网关结论] ✅ 所有规则判定全部通过,决策锁定为【同意通过】`);
|
||||
}
|
||||
|
||||
if (options.comment) {
|
||||
summaryLines.push(`[审批附加说明] ${options.comment}`);
|
||||
}
|
||||
|
||||
const decisionSummary = summaryLines.join("\n");
|
||||
const {
|
||||
decision,
|
||||
decisionSummary,
|
||||
hardFailedCount,
|
||||
elasticFailedCount,
|
||||
suggestFailedCount,
|
||||
specialFailedCount,
|
||||
} = gatewayResult;
|
||||
|
||||
// 4. 更新数据库中的运行记录状态
|
||||
this.repo.updateApprovalRun(run.id, {
|
||||
decision,
|
||||
decisionSummary,
|
||||
failedRulesCount: failedFindings.length,
|
||||
failedRulesCount: gatewayResult.analysis.failedFindings.length,
|
||||
});
|
||||
|
||||
let appliedAction = options.requestedAction;
|
||||
@@ -332,10 +291,10 @@ export class ApprovalService {
|
||||
run: updatedRun,
|
||||
decision,
|
||||
decisionSummary,
|
||||
hardFailedCount: hardFailed.length,
|
||||
elasticFailedCount: elasticFailed.length,
|
||||
suggestFailedCount: suggestFailed.length,
|
||||
specialFailedCount: specialFailed.length,
|
||||
hardFailedCount,
|
||||
elasticFailedCount,
|
||||
suggestFailedCount,
|
||||
specialFailedCount,
|
||||
appliedAction,
|
||||
actionResult,
|
||||
};
|
||||
|
||||
+42
-1
@@ -18,7 +18,7 @@ function flowLookupSelect(): string {
|
||||
}
|
||||
|
||||
function flowDetailSelect(): string {
|
||||
return "flowId(form(`...`),logs(operatorId,nextOperatorId,`...`),plan(`...`),`...`),`...`";
|
||||
return "flowId(form(specificationId(id,name,code),`...`),logs(operatorId,nextOperatorId,`...`),plan(`...`),`...`),`...`";
|
||||
}
|
||||
|
||||
export async function listActiveStaffCatalog(
|
||||
@@ -396,3 +396,44 @@ export async function listEntitySchemas(
|
||||
const parsed = EntityListResponseSchema.parse(json);
|
||||
return parsed.items;
|
||||
}
|
||||
|
||||
// ── 发票票面查验详情与商品明细 API ──────────────────────────────────────────────
|
||||
|
||||
export async function getInvoiceValidationDetail(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
invoiceId: string
|
||||
): Promise<Record<string, unknown> | undefined> {
|
||||
try {
|
||||
const response = await client.get(`api/v2/invoice/validation/$${encodeURIComponent(invoiceId)}`, {
|
||||
searchParams: { masterId: invoiceId, corpId }
|
||||
});
|
||||
return (await response.json()) as Record<string, unknown>;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// ── 数据连接业务对象与卡片详情 API ──────────────────────────────────────────────
|
||||
|
||||
export async function getDatalinkCard(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
entityId: string,
|
||||
type = "CARD"
|
||||
): Promise<Record<string, unknown> | undefined> {
|
||||
try {
|
||||
const response = await client.get(`api/v2/datalink/detail/$${encodeURIComponent(entityId)}/$${encodeURIComponent(type)}`, {
|
||||
searchParams: {
|
||||
entityId,
|
||||
type,
|
||||
join: "data.dataLink.entityId,entity,/v2/datalink/entity",
|
||||
corpId,
|
||||
}
|
||||
});
|
||||
const json = (await response.json()) as { value?: Record<string, unknown> };
|
||||
return json?.value ?? undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -210,6 +210,39 @@ describe("Bill Domain", () => {
|
||||
expect(result?.history[1]?.skipped).toBe(true);
|
||||
});
|
||||
|
||||
it("translates flow actions, states, Ebot operators and print reminders", async () => {
|
||||
const client = {
|
||||
post: async (path: string) => {
|
||||
if (path.includes("backlogs/search")) {
|
||||
return new Response(JSON.stringify({ items: [{ id: "backlog-i18n", flowId: { id: "flow-i18n", form: { code: "B26000001" } } }] }));
|
||||
}
|
||||
return new Response(JSON.stringify({ value: {
|
||||
id: "backlog-i18n",
|
||||
state: "APPROVING",
|
||||
flowId: {
|
||||
id: "flow-i18n",
|
||||
state: "APPROVING",
|
||||
form: { code: "B26000001" },
|
||||
logs: [
|
||||
{ action: "freeflow.submit", state: "SUBMITTED", operatorId: "staff-1", attributes: { nodeName: "提交" } },
|
||||
{ action: "freeflow.autoAgree", state: "APPROVED", operatorId: "ebot", attributes: { isEbotNode: true } },
|
||||
{ action: "freeflow.print", state: "COMPLETED", attributes: { isAuto: true } },
|
||||
],
|
||||
plan: { nodes: [{ id: "node-next", name: "财务审批", type: "APPROVAL" }] },
|
||||
},
|
||||
} }));
|
||||
},
|
||||
} as any;
|
||||
|
||||
const result = await getBillFlow(client, "corp-i18n", "B26000001");
|
||||
expect(result?.state).toBe("审批中");
|
||||
expect(result?.history.map((entry) => entry.action)).toEqual(["提交送审", "自动同意", "打印单据"]);
|
||||
expect(result?.history[1]?.operator?.name).toBe("Ebot (智能审批)");
|
||||
expect(result?.history[2]?.nodeName).toBe("打印提醒");
|
||||
expect(result?.history[0]?.rawAction).toBe("freeflow.submit");
|
||||
expect(result?.history[0]?.rawState).toBe("SUBMITTED");
|
||||
});
|
||||
|
||||
it("builds the captured approve, reject, transfer, add-node and comment payloads", async () => {
|
||||
const calls: Array<{ path: string; options: any }> = [];
|
||||
const client = {
|
||||
@@ -323,4 +356,187 @@ describe("Bill Domain", () => {
|
||||
expect(markdown).toContain("- **城市**: 辽宁省/大连市/大连市区");
|
||||
expect(markdown).toContain("- **消费事由**: `今日在大连见客户`");
|
||||
});
|
||||
|
||||
it("modular translator formatting functions format scalar and complex types properly", () => {
|
||||
const {
|
||||
formatAmountValue,
|
||||
formatDateValue,
|
||||
formatPersonValue,
|
||||
formatDepartmentValue,
|
||||
formatReferenceOrObject,
|
||||
formatApportionSplits,
|
||||
formatInlineAttachments,
|
||||
formatInlineInvoices,
|
||||
} = require("./translator.js");
|
||||
|
||||
// Amount
|
||||
expect(formatAmountValue({ standard: "350", standardStrCode: "CNY" })).toBe("CNY 350.00");
|
||||
expect(formatAmountValue(12.5)).toBe("CNY 12.50");
|
||||
expect(formatAmountValue("¥100")).toBe("CNY 100.00");
|
||||
|
||||
// Date
|
||||
expect(formatDateValue(1788364800000)).toMatch(/2026-09-03/);
|
||||
expect(formatDateValue(1788364800000, true)).toMatch(/2026-09-03 \d{2}:\d{2}/);
|
||||
|
||||
// Person
|
||||
const staffMap = new Map([["staff-1", { name: "张三", code: "ZS01" }]]);
|
||||
expect(formatPersonValue("staff-1", staffMap)).toBe("张三(ZS01)");
|
||||
expect(formatPersonValue({ name: "李四", code: "LS02" })).toBe("李四(LS02)");
|
||||
|
||||
// Department
|
||||
const deptMap = new Map([["dept-1", { path: "总公司/财务部" }]]);
|
||||
expect(formatDepartmentValue("dept-1", deptMap)).toBe("总公司/财务部");
|
||||
expect(formatDepartmentValue({ fullPath: "总公司/研发部" })).toBe("总公司/研发部");
|
||||
|
||||
// Reference & Objects (Supplier, Bank, Dimension)
|
||||
const dimMap = new Map([
|
||||
["ID_dim_1", { name: "钰泰半导体股份有限公司", code: "ETA" }],
|
||||
["ID_biz_1", { name: "费用", code: "CODE2" }],
|
||||
]);
|
||||
expect(formatReferenceOrObject("ID_dim_1", dimMap)).toBe("钰泰半导体股份有限公司(code=ETA)");
|
||||
expect(formatReferenceOrObject("ID_biz_1", dimMap)).toBe("费用(code=CODE2)");
|
||||
expect(formatReferenceOrObject({
|
||||
supplierName: "上海戴维迪",
|
||||
account: "03365200040008552",
|
||||
bank: "农业银行",
|
||||
})).toBe("供应商名称=上海戴维迪;账号=03365200040008552;银行=农业银行");
|
||||
|
||||
// Apportion splits
|
||||
const apportions = [
|
||||
{
|
||||
apportionForm: {
|
||||
apportionPercent: "100.00",
|
||||
apportionMoney: { standard: "350", standardStrCode: "CNY" },
|
||||
expenseDepartment: "dept-1",
|
||||
},
|
||||
},
|
||||
];
|
||||
expect(formatApportionSplits(apportions, deptMap)).toBe("分摊比例=100.00%;分摊金额=CNY 350.00;报销部门=总公司/财务部");
|
||||
|
||||
// Inline attachments
|
||||
const attachments = [
|
||||
{ fileName: "协议书.pdf", fileId: "file-01" },
|
||||
{ fileName: "账单.pdf", fileId: "file-02" },
|
||||
];
|
||||
const attLines = formatInlineAttachments(attachments);
|
||||
expect(attLines[0]).toBe("- **附件Attachment**:");
|
||||
expect(attLines[1]).toBe(" 1. `协议书.pdf` (fileId=\"file-01\")");
|
||||
expect(attLines[2]).toBe(" 2. `账单.pdf` (fileId=\"file-02\")");
|
||||
|
||||
// Inline invoices
|
||||
const invoices = [
|
||||
{
|
||||
invoiceCode: "26312000005586052981",
|
||||
fileInfo: { fileName: "发票原件.pdf", fileId: "inv-01" },
|
||||
buyer: "钰泰半导体",
|
||||
seller: "上海戴维迪",
|
||||
approveAmount: { standard: "350.00" },
|
||||
taxAmount: { standard: "19.81" },
|
||||
},
|
||||
];
|
||||
const invLines = formatInlineInvoices(invoices);
|
||||
expect(invLines[0]).toBe("- **发票列表**(1):");
|
||||
expect(invLines.join("\n")).toContain("发票号码: 26312000005586052981");
|
||||
expect(invLines.join("\n")).toContain("原始文件名: 发票原件.pdf");
|
||||
expect(invLines.join("\n")).toContain("购方: 钰泰半导体");
|
||||
expect(invLines.join("\n")).toContain("销方: 上海戴维迪");
|
||||
expect(invLines.join("\n")).toContain("价税合计: CNY 350.00");
|
||||
});
|
||||
|
||||
it("translates full bill preserving relative attachment and invoice positions", () => {
|
||||
const { translateBillFlowToMarkdown } = require("./translator.js");
|
||||
const complexFlow = {
|
||||
flowId: {
|
||||
state: "APPROVING",
|
||||
form: {
|
||||
code: "B26002288",
|
||||
title: "方镕霖的8月图文快印的对公付款",
|
||||
specificationId: "ID_PAYMENT",
|
||||
submitDate: 1788415807829,
|
||||
description: "戴维迪图文快印8月月结费用,¥350.00",
|
||||
法人实体: "dim_eta",
|
||||
expenseDepartment: "dept_admin",
|
||||
u_提交人部门: "dept_admin",
|
||||
u_经常交易供应商: "上海戴维迪图文制作有限公司",
|
||||
payMoney: { standard: "350.00", standardStrCode: "CNY" },
|
||||
expenseMoney: { standard: "350.00", standardStrCode: "CNY" },
|
||||
u_本单税额: { standard: "19.81", standardStrCode: "CNY" },
|
||||
details: [
|
||||
{
|
||||
feeTypeId: "fee_print",
|
||||
feeTypeForm: {
|
||||
amount: { standard: "350.00", standardStrCode: "CNY" },
|
||||
feeDate: 1788364800000,
|
||||
consumptionReasons: "8月图文快印",
|
||||
detailId: "DETAIL_01",
|
||||
detailNo: 1,
|
||||
u_业务类型: "dim_biz_fee",
|
||||
attachments: [
|
||||
{ fileName: "18-1-服务框架协议书.pdf", fileId: "ID01TvInwhsEwf" },
|
||||
{ fileName: "钰泰账单.pdf", fileId: "ID01VWUmNcRryf" },
|
||||
],
|
||||
invoiceForm: {
|
||||
invoices: [
|
||||
{
|
||||
invoiceCode: "26312000005586052981",
|
||||
buyer: "钰泰半导体股份有限公司",
|
||||
seller: "上海戴维迪图文制作有限公司",
|
||||
approveAmount: { standard: "350.00", standardStrCode: "CNY" },
|
||||
taxAmount: { standard: "19.81", standardStrCode: "CNY" },
|
||||
},
|
||||
],
|
||||
},
|
||||
apportions: [
|
||||
{
|
||||
apportionForm: {
|
||||
apportionPercent: "100.00",
|
||||
apportionMoney: { standard: "350.00", standardStrCode: "CNY" },
|
||||
expenseDepartment: "dept_admin",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const options = {
|
||||
dimensionItemMap: new Map([
|
||||
["dim_eta", { name: "钰泰半导体股份有限公司", code: "ETA" }],
|
||||
["dim_biz_fee", { name: "费用", code: "CODE2" }],
|
||||
]),
|
||||
departmentMap: new Map([
|
||||
["dept_admin", { path: "钰泰半导体/行政中心/人事行政部" }],
|
||||
]),
|
||||
feeTypeMap: new Map([
|
||||
["fee_print", { name: "图文快印费", path: "办公费/图文快印费" }],
|
||||
]),
|
||||
};
|
||||
|
||||
const md = translateBillFlowToMarkdown(complexFlow, options);
|
||||
// 验证顶层关键字段不再丢失
|
||||
expect(md).toContain("- **单号**: `B26002288`");
|
||||
expect(md).toContain("- **法人实体**: 钰泰半导体股份有限公司(code=ETA)");
|
||||
expect(md).toContain("- **费用承担部门**: 钰泰半导体/行政中心/人事行政部");
|
||||
expect(md).toContain("- **提交人部门**: 钰泰半导体/行政中心/人事行政部");
|
||||
expect(md).toContain("- **事由**: `戴维迪图文快印8月月结费用,¥350.00`");
|
||||
expect(md).toContain("- **经常交易供应商**: 上海戴维迪图文制作有限公司");
|
||||
expect(md).toContain("- **本单税额**: CNY 19.81");
|
||||
expect(md).toContain("- **支付金额**: CNY 350.00");
|
||||
|
||||
// 验证明细 1 内部原位挂载发票列表与附件列表
|
||||
expect(md).toContain("#### 明细 1");
|
||||
expect(md).toContain("- **费用类型**: 办公费/图文快印费(name=图文快印费)");
|
||||
expect(md).toContain("- **发票列表**(1):");
|
||||
expect(md).toContain("发票号码: 26312000005586052981");
|
||||
expect(md).toContain("购方: 钰泰半导体股份有限公司");
|
||||
expect(md).toContain("销方: 上海戴维迪图文制作有限公司");
|
||||
expect(md).toContain("- **业务类型**: 费用(code=CODE2)");
|
||||
expect(md).toContain("- **费用归属分摊**: 分摊比例=100.00%;分摊金额=CNY 350.00;报销部门=钰泰半导体/行政中心/人事行政部");
|
||||
expect(md).toContain("- **附件Attachment**:");
|
||||
expect(md).toContain("1. `18-1-服务框架协议书.pdf` (fileId=\"ID01TvInwhsEwf\")");
|
||||
expect(md).toContain("2. `钰泰账单.pdf` (fileId=\"ID01VWUmNcRryf\")");
|
||||
});
|
||||
});
|
||||
+231
-37
@@ -3,6 +3,7 @@ import { KyInstance } from "ky";
|
||||
import { existsSync } from "node:fs";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { basename, extname, join, resolve } from "node:path";
|
||||
import { getGlobalCache } from "../../core/cache/index.js";
|
||||
import {
|
||||
searchRawBills,
|
||||
getRawBillsByIds,
|
||||
@@ -18,9 +19,17 @@ import {
|
||||
transferBillAction,
|
||||
addNodeBillAction,
|
||||
commentBillAction,
|
||||
getInvoiceValidationDetail,
|
||||
getDatalinkCard,
|
||||
type BillActionOptions,
|
||||
type BillActionTarget,
|
||||
} from "./api.js";
|
||||
import {
|
||||
formatBillFlowOperator,
|
||||
translateBillFlowAction,
|
||||
translateBillFlowState,
|
||||
type TranslatorOptions,
|
||||
} from "./translator.js";
|
||||
import {
|
||||
type RawBillItem,
|
||||
type FormattedBill,
|
||||
@@ -90,9 +99,8 @@ const COMMON_FIELD_LABELS: Record<string, string> = {
|
||||
ownerAndApproverPrintNodeFlag: "节点打印控制标识",
|
||||
};
|
||||
|
||||
// ── 字段元数据内存缓存 ─────────────────────────────────────────────────────────
|
||||
// ── 字段元数据与关联目录多级缓存 ─────────────────────────────────────────────
|
||||
|
||||
const schemaCache = new Map<string, { timestamp: number; dictionary: Map<string, { label: string; type: string }>; entities: EntityMeta[] }>();
|
||||
const CACHE_TTL_MS = 10 * 60 * 1000; // 10 分钟缓存
|
||||
|
||||
type ReferenceCatalog = {
|
||||
@@ -102,22 +110,20 @@ type ReferenceCatalog = {
|
||||
feeTypes: Map<string, Record<string, unknown>>;
|
||||
};
|
||||
|
||||
const referenceCatalogCache = new Map<string, ReferenceCatalog>();
|
||||
|
||||
export async function getFieldDictionary(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
forceRefresh = false
|
||||
): Promise<{ dictionary: Map<string, { label: string; type: string }>; entities: EntityMeta[] }> {
|
||||
const cached = schemaCache.get(corpId);
|
||||
if (!forceRefresh && cached && Date.now() - cached.timestamp < CACHE_TTL_MS) {
|
||||
return cached;
|
||||
}
|
||||
const cache = getGlobalCache();
|
||||
const rawEntities = await cache.withCache(
|
||||
`bill:entities:${corpId}`,
|
||||
() => listEntitySchemas(client, corpId, { start: 0, count: 100 }),
|
||||
{ namespace: "bills", ttlMs: CACHE_TTL_MS, forceRefresh }
|
||||
);
|
||||
|
||||
const entities = await listEntitySchemas(client, corpId, { start: 0, count: 100 });
|
||||
const dictionary = new Map<string, { label: string; type: string }>();
|
||||
|
||||
for (const entity of entities) {
|
||||
for (const entity of rawEntities) {
|
||||
for (const field of entity.fields) {
|
||||
if (field.name && field.label) {
|
||||
dictionary.set(field.name, { label: field.label, type: field.type });
|
||||
@@ -125,9 +131,7 @@ export async function getFieldDictionary(
|
||||
}
|
||||
}
|
||||
|
||||
const result = { timestamp: Date.now(), dictionary, entities };
|
||||
schemaCache.set(corpId, result);
|
||||
return result;
|
||||
return { dictionary, entities: rawEntities };
|
||||
}
|
||||
|
||||
function referenceId(value: unknown): string | undefined {
|
||||
@@ -138,10 +142,14 @@ function referenceId(value: unknown): string | undefined {
|
||||
}
|
||||
|
||||
function referenceObject(value: unknown): Record<string, unknown> | undefined {
|
||||
return value && typeof value === "object" ? value as Record<string, unknown> : undefined;
|
||||
return value && typeof value === "object" ? (value as Record<string, unknown>) : undefined;
|
||||
}
|
||||
|
||||
function flattenDepartments(items: Record<string, unknown>[], parentPath = "", output = new Map<string, { item: Record<string, unknown>; path: string }>()): Map<string, { item: Record<string, unknown>; path: string }> {
|
||||
function flattenDepartments(
|
||||
items: Record<string, unknown>[],
|
||||
parentPath = "",
|
||||
output = new Map<string, { item: Record<string, unknown>; path: string }>()
|
||||
): Map<string, { item: Record<string, unknown>; path: string }> {
|
||||
for (const item of items) {
|
||||
const name = typeof item.name === "string" ? item.name : "";
|
||||
const path = name ? (parentPath ? `${parentPath}/${name}` : name) : parentPath;
|
||||
@@ -155,7 +163,10 @@ function flattenDepartments(items: Record<string, unknown>[], parentPath = "", o
|
||||
return output;
|
||||
}
|
||||
|
||||
function flattenFeeTypes(items: Record<string, unknown>[], output = new Map<string, Record<string, unknown>>()): Map<string, Record<string, unknown>> {
|
||||
function flattenFeeTypes(
|
||||
items: Record<string, unknown>[],
|
||||
output = new Map<string, Record<string, unknown>>()
|
||||
): Map<string, Record<string, unknown>> {
|
||||
for (const item of items) {
|
||||
const feeType = referenceObject(item.feeType) ?? item;
|
||||
const id = typeof feeType.id === "string" ? feeType.id : undefined;
|
||||
@@ -169,29 +180,35 @@ function flattenFeeTypes(items: Record<string, unknown>[], output = new Map<stri
|
||||
}
|
||||
|
||||
async function getReferenceCatalog(client: KyInstance, corpId: string): Promise<ReferenceCatalog> {
|
||||
const cached = referenceCatalogCache.get(corpId);
|
||||
if (cached && Date.now() - cached.timestamp < CACHE_TTL_MS) return cached;
|
||||
const [staffs, departments, feeTypes] = await Promise.all([
|
||||
listActiveStaffCatalog(client, corpId),
|
||||
getDepartmentTree(client, corpId),
|
||||
getFeeTypeTree(client, corpId),
|
||||
]);
|
||||
const cache = getGlobalCache();
|
||||
const raw = await cache.withCache(
|
||||
`bill:ref_raw:${corpId}`,
|
||||
async () => {
|
||||
const [staffs, departments, feeTypes] = await Promise.all([
|
||||
listActiveStaffCatalog(client, corpId),
|
||||
getDepartmentTree(client, corpId),
|
||||
getFeeTypeTree(client, corpId),
|
||||
]);
|
||||
return { staffs, departments, feeTypes };
|
||||
},
|
||||
{ namespace: "bills", ttlMs: CACHE_TTL_MS }
|
||||
);
|
||||
|
||||
const staff = new Map<string, Record<string, unknown>>();
|
||||
for (const item of staffs) {
|
||||
for (const item of raw.staffs) {
|
||||
if (typeof item.id === "string") {
|
||||
staff.set(item.id, item);
|
||||
const userId = typeof item.userId === "string" ? item.userId : undefined;
|
||||
if (userId) staff.set(userId, item);
|
||||
}
|
||||
}
|
||||
const result = {
|
||||
|
||||
return {
|
||||
timestamp: Date.now(),
|
||||
staff,
|
||||
departments: flattenDepartments(departments),
|
||||
feeTypes: flattenFeeTypes(feeTypes),
|
||||
departments: flattenDepartments(raw.departments),
|
||||
feeTypes: flattenFeeTypes(raw.feeTypes),
|
||||
};
|
||||
referenceCatalogCache.set(corpId, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
function toReference(
|
||||
@@ -872,17 +889,30 @@ export async function getBillFlow(
|
||||
const nextOperators = Array.isArray(log.nextOperatorIds)
|
||||
? log.nextOperatorIds.map(flowPerson).filter((person): person is NonNullable<typeof person> => Boolean(person))
|
||||
: [];
|
||||
const operator = flowPerson(log.operatorId);
|
||||
const isEbot = attributes.isEbotNode === true || `${operator?.id || ""} ${operator?.name || ""}`.toLowerCase().includes("ebot");
|
||||
const labeledOperator = isEbot
|
||||
? { ...(operator || { id: "ebot" }), name: "Ebot (智能审批)" }
|
||||
: operator;
|
||||
const rawAction = typeof log.action === "string" ? log.action : undefined;
|
||||
const rawState = typeof log.state === "string" ? log.state : undefined;
|
||||
return {
|
||||
id: typeof log.id === "string" ? log.id : undefined,
|
||||
time: currentTime,
|
||||
durationMs,
|
||||
state: typeof log.state === "string" ? log.state : undefined,
|
||||
action: typeof log.action === "string" ? log.action : undefined,
|
||||
nodeName: typeof attributes.nodeName === "string" ? attributes.nodeName : typeof attributes.nextName === "string" ? attributes.nextName : undefined,
|
||||
state: translateBillFlowState(rawState),
|
||||
rawState,
|
||||
action: translateBillFlowAction(rawAction),
|
||||
rawAction,
|
||||
nodeName: typeof attributes.nodeName === "string" && attributes.nodeName
|
||||
? attributes.nodeName
|
||||
: typeof attributes.nextName === "string" && attributes.nextName
|
||||
? attributes.nextName
|
||||
: translateBillFlowAction(rawAction) === "打印单据" ? "打印提醒" : undefined,
|
||||
comment: typeof attributes.comment === "string" && attributes.comment ? attributes.comment : undefined,
|
||||
automatic: attributes.isEbotNode === true || attributes.isAuto === true || !log.operatorId,
|
||||
skipped: attributes.isSkip === true || attributes.skipped === true || log.state === "SKIPPED",
|
||||
operator: flowPerson(log.operatorId),
|
||||
operator: labeledOperator,
|
||||
nextOperators,
|
||||
};
|
||||
});
|
||||
@@ -900,7 +930,7 @@ export async function getBillFlow(
|
||||
id: typeof node.id === "string" ? node.id : undefined,
|
||||
name: typeof node.name === "string" ? node.name : undefined,
|
||||
type: typeof node.type === "string" ? node.type : undefined,
|
||||
state: typeof node.id === "string" && node.id === nextNodeId || typeof node.name === "string" && node.name === currentNode ? "current" : "planned",
|
||||
state: typeof node.id === "string" && node.id === nextNodeId || typeof node.name === "string" && node.name === currentNode ? "当前" : "后续",
|
||||
approver,
|
||||
approvers,
|
||||
};
|
||||
@@ -913,7 +943,7 @@ export async function getBillFlow(
|
||||
flowId: typeof flow.id === "string" ? flow.id : undefined,
|
||||
billCode: typeof form.code === "string" ? form.code : undefined,
|
||||
title: typeof form.title === "string" ? form.title : undefined,
|
||||
state: typeof raw.state === "string" ? raw.state : typeof flow.state === "string" ? flow.state : undefined,
|
||||
state: translateBillFlowState(typeof raw.state === "string" ? raw.state : typeof flow.state === "string" ? flow.state : undefined),
|
||||
currentNode: currentNode ?? (typeof lastAttributes.nextName === "string" ? lastAttributes.nextName : undefined),
|
||||
history,
|
||||
pending,
|
||||
@@ -1271,4 +1301,168 @@ export const billTools = [
|
||||
},
|
||||
];
|
||||
|
||||
export { translateBillFlowToMarkdown } from "./translator.js";
|
||||
export async function getTranslatorContext(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
rawFlow?: Record<string, unknown>
|
||||
): Promise<TranslatorOptions> {
|
||||
const [feeTypeTree, catalog, dimEntity, dimBiz, dimBool] = await Promise.allSettled([
|
||||
getFeeTypeTree(client, corpId),
|
||||
getReferenceCatalog(client, corpId),
|
||||
resolveDimension(client, corpId, "法人实体"),
|
||||
resolveDimension(client, corpId, "业务类型"),
|
||||
resolveDimension(client, corpId, "是否"),
|
||||
]);
|
||||
|
||||
const feeTypeMap = new Map<string, { name?: string; path?: string }>();
|
||||
if (feeTypeTree.status === "fulfilled") {
|
||||
const flat = flattenFeeTypes(feeTypeTree.value);
|
||||
for (const [id, val] of flat.entries()) {
|
||||
feeTypeMap.set(id, { name: val.name as string, path: val.path as string });
|
||||
}
|
||||
}
|
||||
|
||||
const staffMap = catalog.status === "fulfilled" ? catalog.value.staff : undefined;
|
||||
const departmentMap = catalog.status === "fulfilled" ? catalog.value.departments : undefined;
|
||||
|
||||
const dimensionItemMap = new Map<string, { name?: string; code?: string; label?: string }>();
|
||||
for (const dimRes of [dimEntity, dimBiz, dimBool]) {
|
||||
if (dimRes.status === "fulfilled" && dimRes.value?.items) {
|
||||
for (const item of dimRes.value.items) {
|
||||
dimensionItemMap.set(item.id, { name: item.name, code: item.code });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const invoiceDetailMap = new Map<string, Record<string, unknown>>();
|
||||
const datalinkCardMap = new Map<string, string>();
|
||||
|
||||
if (rawFlow) {
|
||||
const flowIdObj = (rawFlow.flowId && typeof rawFlow.flowId === "object" ? rawFlow.flowId : rawFlow) as Record<string, any>;
|
||||
const form = (flowIdObj.form && typeof flowIdObj.form === "object" ? flowIdObj.form : {}) as Record<string, any>;
|
||||
|
||||
// 1. 扫描所有发票 invoiceId
|
||||
const invoiceIds = new Set<string>();
|
||||
const details = Array.isArray(form.details) ? form.details : [];
|
||||
for (const d of details) {
|
||||
const ftf = d?.feeTypeForm || d || {};
|
||||
const invs = ftf.invoiceForm?.invoices || ftf.invoices || [];
|
||||
if (Array.isArray(invs)) {
|
||||
for (const inv of invs) {
|
||||
const id = inv.invoiceId || inv.id;
|
||||
if (typeof id === "string" && id) invoiceIds.add(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const invoiceFetches = Array.from(invoiceIds).map(async (id) => {
|
||||
const detail = await getInvoiceValidationDetail(client, corpId, id);
|
||||
if (detail) invoiceDetailMap.set(id, detail);
|
||||
});
|
||||
|
||||
// 2. 扫描数据连接/卡片 ID (例如供应商 ID01...,payeeId 等)
|
||||
const cardCandidateIds = new Set<string>();
|
||||
for (const [_, v] of Object.entries(form)) {
|
||||
if (typeof v === "string" && v.startsWith("ID01")) {
|
||||
if (!dimensionItemMap.has(v)) {
|
||||
cardCandidateIds.add(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const cardFetches = Array.from(cardCandidateIds).map(async (cardId) => {
|
||||
const cardVal = await getDatalinkCard(client, corpId, cardId);
|
||||
const cardObj = (cardVal?.data as any)?.dataLink || (cardVal?.data as any)?.form || cardVal?.data;
|
||||
if (cardObj && typeof cardObj === "object") {
|
||||
const parts: string[] = [];
|
||||
let suppName = "";
|
||||
let suppCode = "";
|
||||
let bankCard = "";
|
||||
let payeeInfoStr = "";
|
||||
let payeeInfoDirect = "";
|
||||
|
||||
for (const [fieldKey, fieldVal] of Object.entries(cardObj)) {
|
||||
if (fieldKey.endsWith("_name") || fieldKey.includes("供应商名称")) {
|
||||
suppName = String(fieldVal);
|
||||
} else if (fieldKey.endsWith("_code") || fieldKey.includes("供应商编码")) {
|
||||
suppCode = String(fieldVal);
|
||||
} else if (fieldKey.includes("银行卡号") || fieldKey.includes("卡号")) {
|
||||
bankCard = String(fieldVal);
|
||||
} else if (fieldKey.includes("收款信息") && typeof fieldVal === "object" && fieldVal !== null) {
|
||||
const pi = fieldVal as Record<string, any>;
|
||||
const piParts: string[] = [];
|
||||
const directParts: string[] = [];
|
||||
const accountName = pi.name || pi.accountName || pi.accountOwner;
|
||||
const accountNo = pi.cardNo || pi.account;
|
||||
const accountType = (pi.type || pi.accountType) === "PUBLIC" ? "对公账户" : (pi.type || pi.accountType);
|
||||
const accountSort = pi.sort || pi.accountCategory || pi.accountClass;
|
||||
const bankName = pi.bank || pi.bankName;
|
||||
const branchName = pi.branch || pi.openBankName;
|
||||
|
||||
if (accountName) piParts.push(`开户名=${accountName}`);
|
||||
if (accountNo) piParts.push(`账号=${accountNo}`);
|
||||
if (accountType) piParts.push(`账户类型=${accountType}`);
|
||||
if (accountSort) piParts.push(`账户类别=${accountSort}`);
|
||||
if (bankName) piParts.push(`银行=${bankName}`);
|
||||
if (branchName) piParts.push(`开户网点=${branchName}`);
|
||||
if (piParts.length > 0) {
|
||||
payeeInfoStr = piParts.join(";");
|
||||
}
|
||||
|
||||
if (accountNo) directParts.push(`账号=${accountNo}`);
|
||||
if (bankName) directParts.push(`银行=${bankName}`);
|
||||
if (accountName) directParts.push(`开户名=${accountName}`);
|
||||
if (branchName) directParts.push(`开户网点=${branchName}`);
|
||||
if (accountType) directParts.push(`账户类型=${accountType}`);
|
||||
if (accountSort) directParts.push(`账户类别=${accountSort}`);
|
||||
if (directParts.length > 0) {
|
||||
payeeInfoDirect = directParts.join(";");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (suppName) parts.push(`供应商名称=${suppName}`);
|
||||
if (suppCode) parts.push(`供应商编码=${suppCode}`);
|
||||
if (bankCard) parts.push(`银行卡号=${bankCard}`);
|
||||
if (payeeInfoStr) parts.push(`收款信息=${payeeInfoStr}`);
|
||||
|
||||
if (parts.length > 0) {
|
||||
datalinkCardMap.set(cardId, parts.join(";"));
|
||||
}
|
||||
if (payeeInfoDirect || payeeInfoStr) {
|
||||
const valToSet = payeeInfoDirect || payeeInfoStr;
|
||||
datalinkCardMap.set(`payeeInfo:${cardId}`, valToSet);
|
||||
if (suppCode) datalinkCardMap.set(suppCode, valToSet);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
await Promise.allSettled([...invoiceFetches, ...cardFetches]);
|
||||
}
|
||||
|
||||
return {
|
||||
feeTypeMap,
|
||||
staffMap,
|
||||
departmentMap,
|
||||
dimensionItemMap,
|
||||
invoiceDetailMap,
|
||||
datalinkCardMap,
|
||||
};
|
||||
}
|
||||
|
||||
export {
|
||||
translateBillFlowToMarkdown,
|
||||
formatBillFlowOperator,
|
||||
translateBillFlowAction,
|
||||
translateBillFlowState,
|
||||
formatAmountValue,
|
||||
formatDateValue,
|
||||
formatPersonValue,
|
||||
formatDepartmentValue,
|
||||
formatReferenceOrObject,
|
||||
formatApportionSplits,
|
||||
formatInlineInvoices,
|
||||
formatInlineAttachments,
|
||||
formatDynamicField,
|
||||
type TranslatorOptions,
|
||||
} from "./translator.js";
|
||||
+632
-80
@@ -1,91 +1,518 @@
|
||||
import { KyInstance } from "ky";
|
||||
import { getRawBillFlow } from "./api.js";
|
||||
import { getFeeTypeTree } from "./api.js";
|
||||
|
||||
function formatDate(val: unknown): string {
|
||||
if (!val) return "";
|
||||
if (typeof val === "number" || (typeof val === "string" && /^\d+$/.test(val))) {
|
||||
const d = new Date(Number(val));
|
||||
if (!isNaN(d.getTime())) {
|
||||
const year = d.getFullYear();
|
||||
const month = String(d.getMonth() + 1).padStart(2, "0");
|
||||
const day = String(d.getDate()).padStart(2, "0");
|
||||
return `${year}-${month}-${day}`;
|
||||
}
|
||||
}
|
||||
if (typeof val === "string") {
|
||||
const match = val.match(/^(\d{4})[-/](\d{1,2})[-/](\d{1,2})/);
|
||||
if (match) {
|
||||
return `${match[1]}-${match[2].padStart(2, "0")}-${match[3].padStart(2, "0")}`;
|
||||
}
|
||||
return val;
|
||||
}
|
||||
return String(val);
|
||||
export interface TranslatorOptions {
|
||||
feeTypeMap?: Map<string, { name?: string; path?: string }>;
|
||||
staffMap?: Map<string, Record<string, unknown>>;
|
||||
departmentMap?: Map<string, { path?: string; item?: Record<string, unknown> }>;
|
||||
dimensionItemMap?: Map<string, { name?: string; code?: string; label?: string; path?: string }>;
|
||||
dictionary?: Map<string, { label: string; type?: string }>;
|
||||
corpName?: string;
|
||||
}
|
||||
|
||||
function formatDateTime(val: unknown): string {
|
||||
if (!val) return "";
|
||||
if (typeof val === "number" || (typeof val === "string" && /^\d+$/.test(val))) {
|
||||
const d = new Date(Number(val));
|
||||
if (!isNaN(d.getTime())) {
|
||||
const year = d.getFullYear();
|
||||
const month = String(d.getMonth() + 1).padStart(2, "0");
|
||||
const day = String(d.getDate()).padStart(2, "0");
|
||||
const hours = String(d.getHours()).padStart(2, "0");
|
||||
const minutes = String(d.getMinutes()).padStart(2, "0");
|
||||
return `${year}-${month}-${day} ${hours}:${minutes}`;
|
||||
}
|
||||
}
|
||||
return String(val);
|
||||
}
|
||||
// ── 1. 金额格式化 ─────────────────────────────────────────────────────────────
|
||||
|
||||
function parseCity(cityVal: unknown): string {
|
||||
if (!cityVal) return "";
|
||||
if (typeof cityVal === "string") {
|
||||
try {
|
||||
const parsed = JSON.parse(cityVal);
|
||||
if (Array.isArray(parsed) && parsed[0]?.label) {
|
||||
return parsed[0].label;
|
||||
}
|
||||
} catch {}
|
||||
return cityVal;
|
||||
}
|
||||
if (Array.isArray(cityVal) && cityVal[0]?.label) {
|
||||
return cityVal[0].label;
|
||||
}
|
||||
return String(cityVal);
|
||||
}
|
||||
|
||||
function formatAmount(money: any): string {
|
||||
if (!money) return "CNY 0.00";
|
||||
export function formatAmountValue(money: unknown): string {
|
||||
if (money === null || money === undefined || money === "") return "CNY 0.00";
|
||||
if (typeof money === "number") return `CNY ${money.toFixed(2)}`;
|
||||
if (typeof money === "string") {
|
||||
const n = parseFloat(money.replace(/[^0-9.-]/g, ""));
|
||||
return isNaN(n) ? money : `CNY ${n.toFixed(2)}`;
|
||||
const trimmed = money.trim();
|
||||
if (!trimmed) return "CNY 0.00";
|
||||
const n = parseFloat(trimmed.replace(/[^0-9.-]/g, ""));
|
||||
if (isNaN(n)) return trimmed;
|
||||
const currencyMatch = trimmed.match(/^([A-Za-z]{3}|¥|\$)/);
|
||||
const curr = currencyMatch ? (currencyMatch[1] === "¥" ? "CNY" : currencyMatch[1]) : "CNY";
|
||||
return `${curr} ${n.toFixed(2)}`;
|
||||
}
|
||||
if (typeof money === "object") {
|
||||
const currency = money.standardStrCode || money.currency || "CNY";
|
||||
const amountNum = parseFloat(money.standard || money.amount || 0);
|
||||
return `${currency} ${isNaN(amountNum) ? "0.00" : amountNum.toFixed(2)}`;
|
||||
const obj = money as Record<string, unknown>;
|
||||
const curr = (obj.standardStrCode || obj.currency || (obj.standardSymbol === "¥" ? "CNY" : obj.standardSymbol) || "CNY") as string;
|
||||
const val = obj.standard ?? obj.amount ?? obj.value ?? 0;
|
||||
const n = typeof val === "number" ? val : parseFloat(String(val).replace(/[^0-9.-]/g, ""));
|
||||
return `${curr} ${isNaN(n) ? "0.00" : n.toFixed(2)}`;
|
||||
}
|
||||
return String(money);
|
||||
}
|
||||
|
||||
function resolveSpecificationName(specId: unknown): string {
|
||||
if (!specId || typeof specId !== "string") return "未知模板";
|
||||
// ── 2. 日期时间格式化 ─────────────────────────────────────────────────────────
|
||||
|
||||
export function formatDateValue(val: unknown, withTime = false): string {
|
||||
if (!val) return "";
|
||||
let d: Date | undefined;
|
||||
if (typeof val === "number" || (typeof val === "string" && /^\d+$/.test(val.trim()))) {
|
||||
const num = Number(val);
|
||||
if (!isNaN(num) && num > 0) d = new Date(num);
|
||||
} else if (typeof val === "string") {
|
||||
const match = val.match(/^(\d{4})[-/](\d{1,2})[-/](\d{1,2})(?:[ T](\d{1,2}):(\d{1,2}))?/);
|
||||
if (match) {
|
||||
const year = match[1];
|
||||
const month = match[2].padStart(2, "0");
|
||||
const day = match[3].padStart(2, "0");
|
||||
if (withTime && match[4] !== undefined && match[5] !== undefined) {
|
||||
return `${year}-${month}-${day} ${match[4].padStart(2, "0")}:${match[5].padStart(2, "0")}`;
|
||||
}
|
||||
return `${year}-${month}-${day}`;
|
||||
}
|
||||
const parsed = Date.parse(val);
|
||||
if (!isNaN(parsed)) d = new Date(parsed);
|
||||
}
|
||||
|
||||
if (d && !isNaN(d.getTime())) {
|
||||
const formatter = new Intl.DateTimeFormat("zh-CN", {
|
||||
timeZone: "Asia/Shanghai",
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
...(withTime ? { hour: "2-digit", minute: "2-digit", hour12: false } : {}),
|
||||
});
|
||||
const parts = formatter.formatToParts(d);
|
||||
const partMap: Record<string, string> = {};
|
||||
for (const p of parts) partMap[p.type] = p.value;
|
||||
const dateStr = `${partMap.year}-${partMap.month}-${partMap.day}`;
|
||||
if (withTime && partMap.hour !== undefined && partMap.minute !== undefined) {
|
||||
return `${dateStr} ${partMap.hour}:${partMap.minute}`;
|
||||
}
|
||||
return dateStr;
|
||||
}
|
||||
return String(val);
|
||||
}
|
||||
|
||||
// ── 3. 城市解析 ───────────────────────────────────────────────────────────────
|
||||
|
||||
export function parseCityValue(cityVal: unknown): string {
|
||||
if (!cityVal) return "";
|
||||
if (typeof cityVal === "string") {
|
||||
try {
|
||||
const parsed = JSON.parse(cityVal);
|
||||
if (Array.isArray(parsed) && parsed[0]?.label) return parsed[0].label;
|
||||
} catch {}
|
||||
return cityVal;
|
||||
}
|
||||
if (Array.isArray(cityVal) && cityVal[0]?.label) {
|
||||
return String(cityVal[0].label);
|
||||
}
|
||||
return String(cityVal);
|
||||
}
|
||||
|
||||
// ── 4. 员工/人员格式化 ─────────────────────────────────────────────────────────
|
||||
|
||||
export function formatPersonValue(
|
||||
val: unknown,
|
||||
staffMap?: Map<string, Record<string, unknown>>
|
||||
): string {
|
||||
if (!val) return "未知";
|
||||
if (Array.isArray(val)) {
|
||||
return val.map((v) => formatPersonValue(v, staffMap)).join("、");
|
||||
}
|
||||
if (typeof val === "string") {
|
||||
const trimmed = val.trim();
|
||||
if (staffMap?.has(trimmed)) {
|
||||
const match = staffMap.get(trimmed)!;
|
||||
const name = (match.name || match.nickName || trimmed) as string;
|
||||
const code = match.code ? `(${match.code})` : "";
|
||||
return `${name}${code}`;
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
if (typeof val === "object") {
|
||||
const obj = val as Record<string, unknown>;
|
||||
const name = (obj.name || obj.nickName || obj.staffName || "") as string;
|
||||
const code = obj.code ? `(${obj.code})` : "";
|
||||
if (name) return `${name}${code}`;
|
||||
}
|
||||
return String(val);
|
||||
}
|
||||
|
||||
export interface TranslatorOptions {
|
||||
corpName?: string;
|
||||
feeTypeMap?: Map<string, { name?: string; path?: string }>;
|
||||
staffMap?: Map<string, Record<string, unknown>>;
|
||||
departmentMap?: Map<string, { path?: string; item?: Record<string, unknown> }>;
|
||||
dimensionItemMap?: Map<string, { name?: string; code?: string; label?: string; path?: string }>;
|
||||
invoiceDetailMap?: Map<string, Record<string, unknown>>;
|
||||
datalinkCardMap?: Map<string, string>;
|
||||
}
|
||||
|
||||
const BILL_FLOW_ACTION_LABELS: Record<string, string> = {
|
||||
"freeflow.submit": "提交送审",
|
||||
"freeflow.agree": "审批同意",
|
||||
"freeflow.autoAgree": "自动同意",
|
||||
"freeflow.reject": "审批驳回",
|
||||
"freeflow.print": "打印单据",
|
||||
"freeflow.retract": "单据撤回",
|
||||
"freeflow.addnode": "加签/转交",
|
||||
"freeflow.comment": "发表评论",
|
||||
};
|
||||
|
||||
const BILL_FLOW_STATE_LABELS: Record<string, string> = {
|
||||
APPROVING: "审批中",
|
||||
APPROVED: "审批通过",
|
||||
REJECTED: "审批驳回",
|
||||
REVOKED: "已撤回",
|
||||
CANCELED: "已取消",
|
||||
CANCELLED: "已取消",
|
||||
SKIPPED: "已跳过",
|
||||
SUBMITTED: "已提交",
|
||||
PENDING: "待审批",
|
||||
WAITING: "待处理",
|
||||
COMPLETED: "已完成",
|
||||
DRAFT: "草稿",
|
||||
};
|
||||
|
||||
export function translateBillFlowAction(action?: string): string | undefined {
|
||||
if (!action) return undefined;
|
||||
return BILL_FLOW_ACTION_LABELS[action] || action;
|
||||
}
|
||||
|
||||
export function translateBillFlowState(state?: string): string | undefined {
|
||||
if (!state) return undefined;
|
||||
return BILL_FLOW_STATE_LABELS[state.toUpperCase()] || state;
|
||||
}
|
||||
|
||||
export function formatBillFlowOperator(
|
||||
operator?: { id?: string; name?: string },
|
||||
automatic = false,
|
||||
isEbot = false
|
||||
): string {
|
||||
const raw = `${operator?.id || ""} ${operator?.name || ""}`.toLowerCase();
|
||||
if (isEbot || raw.includes("ebot")) return "Ebot (智能审批)";
|
||||
return operator?.name || (automatic ? "系统" : "-");
|
||||
}
|
||||
|
||||
// ── 5. 部门全路径格式化 ───────────────────────────────────────────────────────
|
||||
|
||||
export function formatDepartmentValue(
|
||||
val: unknown,
|
||||
departmentMap?: Map<string, { path?: string; item?: Record<string, unknown> }>
|
||||
): string {
|
||||
if (!val) return "";
|
||||
if (Array.isArray(val)) {
|
||||
return val.map((v) => formatDepartmentValue(v, departmentMap)).join("、");
|
||||
}
|
||||
if (typeof val === "string") {
|
||||
const trimmed = val.trim();
|
||||
if (departmentMap?.has(trimmed)) {
|
||||
const match = departmentMap.get(trimmed)!;
|
||||
return match.path || (match.item?.name as string) || trimmed;
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
if (typeof val === "object") {
|
||||
const obj = val as Record<string, unknown>;
|
||||
const id = (obj.id || obj.deptId || obj.departmentId || "") as string;
|
||||
if (id) {
|
||||
const match = departmentMap?.get(id) ?? departmentMap?.get(id.split(":").at(-1) ?? id);
|
||||
if (match?.path) return match.path;
|
||||
if (match?.item?.name) return match.item.name as string;
|
||||
}
|
||||
return (obj.fullPath || obj.path || obj.name || "") as string;
|
||||
}
|
||||
return String(val);
|
||||
}
|
||||
|
||||
// ── 6. 复杂对象与引用字典格式化 (供应商/银行卡号/枚举/档案项) ──────────────────
|
||||
|
||||
export function formatReferenceOrObject(
|
||||
val: unknown,
|
||||
dimensionMap?: Map<string, { name?: string; code?: string; label?: string; path?: string }>,
|
||||
datalinkCardMap?: Map<string, string>
|
||||
): string {
|
||||
if (val === null || val === undefined) return "";
|
||||
if (typeof val === "boolean") return val ? "是" : "否";
|
||||
if (typeof val === "number") return String(val);
|
||||
|
||||
if (typeof val === "string") {
|
||||
const trimmed = val.trim();
|
||||
if (datalinkCardMap?.has(trimmed)) {
|
||||
return datalinkCardMap.get(trimmed)!;
|
||||
}
|
||||
if (dimensionMap?.has(trimmed)) {
|
||||
const match = dimensionMap.get(trimmed)!;
|
||||
const title = match.name || match.label || match.path || trimmed;
|
||||
return match.code ? `${title}(code=${match.code})` : title;
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
if (Array.isArray(val)) {
|
||||
const city = parseCityValue(val);
|
||||
if (city && city !== String(val)) return city;
|
||||
return val.map((item) => formatReferenceOrObject(item, dimensionMap, datalinkCardMap)).join(";");
|
||||
}
|
||||
|
||||
if (typeof val === "object") {
|
||||
const obj = val as Record<string, unknown>;
|
||||
// 金额对象判断
|
||||
if ("standard" in obj || "standardStrCode" in obj) {
|
||||
return formatAmountValue(obj);
|
||||
}
|
||||
// 标准枚举/档案节点判断
|
||||
if (obj.name || obj.label) {
|
||||
const title = (obj.name || obj.label || "") as string;
|
||||
const code = obj.code ? `(code=${obj.code})` : "";
|
||||
return `${title}${code}`;
|
||||
}
|
||||
// 供应商/银行账户解构
|
||||
const parts: string[] = [];
|
||||
if (obj.supplierName) parts.push(`供应商名称=${obj.supplierName}`);
|
||||
if (obj.supplierCode) parts.push(`供应商编码=${obj.supplierCode}`);
|
||||
if (obj.accountName || obj.accountOwner) parts.push(`开户名=${obj.accountName || obj.accountOwner}`);
|
||||
if (obj.account || obj.cardNo || obj.bankCardNo) parts.push(`账号=${obj.account || obj.cardNo || obj.bankCardNo}`);
|
||||
if (obj.bankCardNumber) parts.push(`银行卡号=${obj.bankCardNumber}`);
|
||||
if (obj.accountType) parts.push(`账户类型=${obj.accountType}`);
|
||||
if (obj.accountCategory) parts.push(`账户类别=${obj.accountCategory}`);
|
||||
if (obj.bank || obj.bankName) parts.push(`银行=${obj.bank || obj.bankName}`);
|
||||
if (obj.openBankName || obj.branchBank) parts.push(`开户网点=${obj.openBankName || obj.branchBank}`);
|
||||
if (parts.length > 0) return parts.join(";");
|
||||
|
||||
// 默认键值对铺平
|
||||
const entries = Object.entries(obj).filter(([k, v]) => v !== null && v !== undefined && v !== "");
|
||||
if (entries.length === 0) return "";
|
||||
return entries.map(([k, v]) => `${k}=${typeof v === "object" ? formatReferenceOrObject(v, dimensionMap) : v}`).join(";");
|
||||
}
|
||||
|
||||
return String(val);
|
||||
}
|
||||
|
||||
// ── 7. 费用归属分摊格式化 ─────────────────────────────────────────────────────
|
||||
|
||||
export function formatApportionSplits(
|
||||
apportions: unknown[],
|
||||
departmentMap?: Map<string, { path?: string; item?: Record<string, unknown> }>
|
||||
): string {
|
||||
if (!Array.isArray(apportions) || apportions.length === 0) return "";
|
||||
const parts: string[] = [];
|
||||
for (const item of apportions) {
|
||||
if (!item || typeof item !== "object") continue;
|
||||
const form = (item as Record<string, unknown>).apportionForm && typeof (item as Record<string, unknown>).apportionForm === "object"
|
||||
? (item as Record<string, unknown>).apportionForm as Record<string, unknown>
|
||||
: (item as Record<string, unknown>);
|
||||
|
||||
const subParts: string[] = [];
|
||||
let percent = form.apportionPercent || form.percent;
|
||||
if (percent !== undefined && percent !== null && percent !== "") {
|
||||
const pStr = String(percent);
|
||||
subParts.push(`分摊比例=${pStr.endsWith("%") ? pStr : `${pStr}%`}`);
|
||||
}
|
||||
const money = form.apportionMoney || form.money || form.amount;
|
||||
if (money !== undefined && money !== null) {
|
||||
subParts.push(`分摊金额=${formatAmountValue(money)}`);
|
||||
}
|
||||
const dept = form.expenseDepartment || form.department;
|
||||
if (dept) {
|
||||
subParts.push(`报销部门=${formatDepartmentValue(dept, departmentMap)}`);
|
||||
}
|
||||
if (subParts.length > 0) {
|
||||
parts.push(subParts.join(";"));
|
||||
}
|
||||
}
|
||||
return parts.join(" | ");
|
||||
}
|
||||
|
||||
// ── 8. 明细发票列表行内格式化 ─────────────────────────────────────────────────
|
||||
|
||||
export function formatInlineInvoices(
|
||||
invoices: unknown[],
|
||||
invoiceDetailMap?: Map<string, Record<string, unknown>>
|
||||
): string[] {
|
||||
if (!Array.isArray(invoices) || invoices.length === 0) return [];
|
||||
const lines: string[] = [];
|
||||
lines.push(`- **发票列表**(${invoices.length}):`);
|
||||
|
||||
invoices.forEach((invItem: any, idx: number) => {
|
||||
const num = idx + 1;
|
||||
const inv = invItem.invoice || invItem;
|
||||
const rawInvoiceId = String(inv.invoiceId || inv.id || "");
|
||||
const detailFromMap = (rawInvoiceId && invoiceDetailMap?.get(rawInvoiceId)) || undefined;
|
||||
const master = detailFromMap?.master as Record<string, unknown> | undefined;
|
||||
const masterForm = (master?.form as Record<string, unknown>) || {};
|
||||
const goodsDetails = Array.isArray(detailFromMap?.details) ? detailFromMap.details : [];
|
||||
|
||||
const verify = inv.verifyResult || inv;
|
||||
const fileInfo = inv.fileInfo || {};
|
||||
let code = inv.invoiceCode || inv.invoiceNo || inv.invoiceNumber || verify.invoiceNo || (masterForm["E_system_发票主体_发票号码"] as string) || inv.invoiceId || `发票-${num}`;
|
||||
if (typeof code === "string" && code.includes("::")) {
|
||||
code = code.split("::").at(-1) || code;
|
||||
}
|
||||
|
||||
const fileId = fileInfo.fileId || inv.fileId || inv.invoiceId || "";
|
||||
let fileName = fileInfo.fileName || inv.fileName || "";
|
||||
if (!fileName && masterForm["E_system_发票主体_图片"]) {
|
||||
try {
|
||||
fileName = decodeURIComponent(String(masterForm["E_system_发票主体_图片"]));
|
||||
} catch {
|
||||
fileName = String(masterForm["E_system_发票主体_图片"]);
|
||||
}
|
||||
}
|
||||
const fileType = fileInfo.fileType || inv.fileType || "invoice";
|
||||
const rawDate = inv.invoiceDate || verify.invoiceDate || masterForm["E_system_发票主体_发票日期"];
|
||||
const invoiceDate = formatDateValue(rawDate);
|
||||
const verifyStatus = inv.verifyState || verify.verifyStatus || (masterForm["E_system_发票主体_验真"] ? "verified" : undefined) || "verified";
|
||||
const buyer = verify.buyer || inv.buyer || masterForm["E_system_发票主体_购买方名称"] || "";
|
||||
const buyerTax = verify.buyerTaxNo || inv.buyerTaxNo || masterForm["E_system_发票主体_购买方纳税人识别号"] || "";
|
||||
const seller = verify.seller || inv.seller || masterForm["E_system_发票主体_销售方名称"] || "";
|
||||
const sellerTax = verify.sellerTaxNo || inv.sellerTaxNo || masterForm["E_system_发票主体_销售方纳税人识别号"] || "";
|
||||
|
||||
let invoiceType = inv.invoiceType || verify.invoiceType;
|
||||
if (!invoiceType && masterForm["E_system_发票主体_发票类别"]) {
|
||||
const cat = String(masterForm["E_system_发票主体_发票类别"]);
|
||||
if (cat.includes("SPECIAL") || cat.includes("专票")) {
|
||||
invoiceType = "电子发票(增值税专用发票)";
|
||||
} else {
|
||||
invoiceType = "电子发票";
|
||||
}
|
||||
}
|
||||
invoiceType = invoiceType || "电子发票";
|
||||
|
||||
const remark = (masterForm["E_system_发票主体_备注"] as string) || inv.remark || "";
|
||||
const totalAmount = formatAmountValue(inv.approveAmount || inv.totalAmount || verify.amount || inv.amount || masterForm["E_system_发票主体_价税合计"]);
|
||||
const taxAmount = formatAmountValue(inv.taxAmount || verify.taxAmount || masterForm["E_system_发票主体_税额"]);
|
||||
|
||||
lines.push(` ${num}. **发票号码: ${code}**`);
|
||||
if (fileId) lines.push(` 原始文件fileId: ${fileId}`);
|
||||
if (fileName) lines.push(` 原始文件名: ${fileName}`);
|
||||
if (fileType) lines.push(` 原始文件类型: ${fileType}`);
|
||||
if (invoiceDate) lines.push(` 发票日期: ${invoiceDate}`);
|
||||
if (verifyStatus) lines.push(` 验真状态: ${verifyStatus}`);
|
||||
if (buyer) lines.push(` 购方: ${buyer}${buyerTax ? `,税号: ${buyerTax}` : ""}`);
|
||||
if (seller) lines.push(` 销方: ${seller}${sellerTax ? `,税号: ${sellerTax}` : ""}`);
|
||||
if (invoiceType) lines.push(` 发票类型: ${invoiceType}`);
|
||||
if (remark) lines.push(` 备注: ${remark}`);
|
||||
lines.push(` 价税合计: ${totalAmount}`);
|
||||
if (taxAmount && taxAmount !== "CNY 0.00") lines.push(` 税额: ${taxAmount}`);
|
||||
|
||||
const items = verify.items || inv.items || (goodsDetails.length > 0 ? goodsDetails.map((gd: any) => {
|
||||
const f = gd.form || {};
|
||||
return {
|
||||
名称: gd.name || f["E_system_发票明细_name"] || "",
|
||||
单位: f["E_system_发票明细_单位"] || "",
|
||||
数量: String(f["E_system_发票明细_数量"] || ""),
|
||||
单价: formatAmountValue(f["E_system_发票明细_单价"]),
|
||||
金额: formatAmountValue(f["E_system_发票明细_金额"]),
|
||||
税率: f["E_system_发票明细_税率"] || "",
|
||||
税额: formatAmountValue(f["E_system_发票明细_税额"]),
|
||||
};
|
||||
}) : undefined);
|
||||
|
||||
if (Array.isArray(items) && items.length > 0) {
|
||||
lines.push(` 发票明细(${items.length}):`);
|
||||
for (const it of items) {
|
||||
lines.push(` - ${JSON.stringify(it)}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (master && Object.keys(masterForm).length > 0) {
|
||||
const invInfoObj = {
|
||||
销售方地址电话: masterForm["E_system_发票主体_销售方地址电话"] || "",
|
||||
是否有发票原件: masterForm["E_system_发票主体_是否有发票原件"] ? "是" : "否",
|
||||
收票状态: masterForm["E_system_收票状态"] || "NORECEIVE",
|
||||
可抵扣税额: formatAmountValue(masterForm["E_税额"] || masterForm["E_system_发票主体_税额"]),
|
||||
名称: masterForm["E_system_发票主体_name"] || code,
|
||||
发票号码: code,
|
||||
发票日期: invoiceDate,
|
||||
购买方名称: buyer,
|
||||
购买方纳税人识别号: buyerTax,
|
||||
发票金额: formatAmountValue(masterForm["E_不计税金额"] || masterForm["E_system_发票主体_发票金额"]),
|
||||
税额: taxAmount,
|
||||
价税合计: totalAmount,
|
||||
销售方名称: seller,
|
||||
销售方纳税人识别号: sellerTax,
|
||||
销售方开户行及账号: masterForm["E_system_发票主体_销售方开户行及账号"] || "",
|
||||
备注: remark,
|
||||
发票类别: invoiceType,
|
||||
不计税金额: formatAmountValue(masterForm["E_不计税金额"] || masterForm["E_system_发票主体_发票金额"]),
|
||||
发票状态: masterForm["E_system_发票主体_发票状态"] || "NORMAL_BLUE",
|
||||
是否电子票: masterForm["E_system_发票主体_是否电子票"] ? "是" : "否",
|
||||
};
|
||||
lines.push(` 发票信息: ${JSON.stringify(invInfoObj)}`);
|
||||
}
|
||||
});
|
||||
|
||||
return lines;
|
||||
}
|
||||
|
||||
// ── 9. 明细附件列表行内格式化 ─────────────────────────────────────────────────
|
||||
|
||||
export function formatInlineAttachments(attachments: unknown[]): string[] {
|
||||
if (!Array.isArray(attachments) || attachments.length === 0) return [];
|
||||
const valid = attachments.filter((item): item is Record<string, unknown> => Boolean(item && typeof item === "object"));
|
||||
if (valid.length === 0) return [];
|
||||
|
||||
const lines: string[] = [];
|
||||
lines.push(`- **附件Attachment**:`);
|
||||
valid.forEach((att: any, idx: number) => {
|
||||
const num = idx + 1;
|
||||
const name = att.fileName || att.name || "未命名附件";
|
||||
const fileId = att.fileId ? ` (fileId="${att.fileId}")` : "";
|
||||
lines.push(` ${num}. \`${name}\`${fileId}`);
|
||||
});
|
||||
return lines;
|
||||
}
|
||||
|
||||
// ── 10. 模板名称标准化 ────────────────────────────────────────────────────────
|
||||
|
||||
export function resolveSpecificationName(specId: unknown): string {
|
||||
if (!specId) return "未知模板";
|
||||
if (typeof specId === "object") {
|
||||
const obj = specId as Record<string, unknown>;
|
||||
if (typeof obj.name === "string" && obj.name) return obj.name;
|
||||
if (typeof obj.id === "string") return resolveSpecificationName(obj.id);
|
||||
}
|
||||
if (typeof specId !== "string") return "未知模板";
|
||||
if (specId.includes("REQUISITION_TRIP") || specId.includes("trip")) return "差旅申请单";
|
||||
if (specId.includes("REIMBURSEMENT") || specId.includes("expense")) return "报销单";
|
||||
if (specId.includes("LOAN") || specId.includes("loan")) return "借款单";
|
||||
if (specId.includes("PAYMENT") || specId.includes("payment")) return "对公付款单";
|
||||
if (specId.includes("PAYMENT") || specId.includes("payment")) return "对公付款";
|
||||
return specId;
|
||||
}
|
||||
|
||||
// ── 11. 动态表单字段过滤与格式化 ──────────────────────────────────────────────
|
||||
|
||||
const BUILTIN_SYSTEM_KEYS = new Set([
|
||||
"code", "title", "specificationId", "details", "itineraries", "logs", "flowPlanId",
|
||||
"actions", "threadId", "pipeline", "grayver", "dbVersion", "active", "version",
|
||||
"sourceSign", "createTime", "updateTime", "printState", "printCount", "onlyOwnerPrint",
|
||||
"ownerAndApproverPrintNodeFlag", "rejectionNum", "reviewStatus", "voucherStatus",
|
||||
"voucherCreateTime", "preApprovedNodeName", "preNodeApprovedTime", "submitterId",
|
||||
"expenseDate", "requisitionDate", "submitDate", "description", "expenseMoney",
|
||||
"payMoney", "amount", "requisitionMoney", "companyRealPay", "writtenOffMoney",
|
||||
"法人实体", "expenseDepartment", "u_提交人部门", "voucherNo", "payeeId",
|
||||
"u_发票金额", "u_本单税额", "u_本单不含税", "u_是否有纸质票据", "u_经常交易供应商"
|
||||
]);
|
||||
|
||||
export function formatDynamicField(
|
||||
key: string,
|
||||
val: unknown,
|
||||
options?: TranslatorOptions
|
||||
): { label: string; text: string } | undefined {
|
||||
if (BUILTIN_SYSTEM_KEYS.has(key)) return undefined;
|
||||
if (val === null || val === undefined || val === "") return undefined;
|
||||
|
||||
let label = (options as any)?.dictionary?.get(key)?.label || key.replace(/^u_/, "");
|
||||
const lowerKey = key.toLowerCase();
|
||||
|
||||
let text: string;
|
||||
if (lowerKey.includes("money") || lowerKey.includes("amount") || lowerKey.includes("金额") || lowerKey.includes("税额")) {
|
||||
text = formatAmountValue(val);
|
||||
} else if (lowerKey.includes("date") || lowerKey.includes("time") || lowerKey.includes("日期") || lowerKey.includes("时间")) {
|
||||
text = formatDateValue(val);
|
||||
} else if (lowerKey.includes("department") || lowerKey.includes("部门")) {
|
||||
text = formatDepartmentValue(val, options?.departmentMap);
|
||||
} else if (lowerKey.includes("person") || lowerKey.includes("staff") || lowerKey.includes("submitter")) {
|
||||
text = formatPersonValue(val, options?.staffMap);
|
||||
} else {
|
||||
text = formatReferenceOrObject(val, options?.dimensionItemMap, options?.datalinkCardMap);
|
||||
}
|
||||
|
||||
if (!text) return undefined;
|
||||
return { label, text };
|
||||
}
|
||||
|
||||
// ── 12. 主入口:全量单据流转译 Markdown ───────────────────────────────────────
|
||||
|
||||
/**
|
||||
* 将合思原始单据流对象转译为标准 LLM / 审核视图 Markdown (单据字段转译器)
|
||||
*/
|
||||
export function translateBillFlowToMarkdown(
|
||||
rawFlow: Record<string, unknown>,
|
||||
feeTypeMap?: Map<string, { name?: string; path?: string }>
|
||||
options?: TranslatorOptions
|
||||
): string {
|
||||
const flowIdObj = (rawFlow.flowId && typeof rawFlow.flowId === "object" ? rawFlow.flowId : rawFlow) as Record<string, any>;
|
||||
const form = (flowIdObj.form && typeof flowIdObj.form === "object" ? flowIdObj.form : {}) as Record<string, any>;
|
||||
@@ -94,11 +521,10 @@ export function translateBillFlowToMarkdown(
|
||||
const title = form.title || flowIdObj.title || "<无标题>";
|
||||
const rawState = flowIdObj.state || "approving";
|
||||
const stateLabel = String(rawState).toUpperCase() === "APPROVING" ? "审批中" : rawState;
|
||||
const submitTime = formatDate(form.submitDate || flowIdObj.createTime);
|
||||
const submitTime = formatDateValue(form.submitDate || flowIdObj.createTime);
|
||||
const templateName = resolveSpecificationName(form.specificationId);
|
||||
const submitterName = form.submitterId?.name || (typeof form.submitterId === "string" ? form.submitterId : "未知");
|
||||
const requisitionDate = formatDate(form.requisitionDate);
|
||||
const totalMoney = formatAmount(form.requisitionMoney || form.amount);
|
||||
const submitterName = formatPersonValue(form.submitterId, options?.staffMap);
|
||||
const requisitionDate = formatDateValue(form.requisitionDate || form.expenseDate);
|
||||
|
||||
const lines: string[] = [];
|
||||
lines.push(`# 单据:${code}`);
|
||||
@@ -113,20 +539,110 @@ export function translateBillFlowToMarkdown(
|
||||
lines.push(`- **单据模板**: \`${templateName}\``);
|
||||
lines.push(`- **补充申请**: <无>`);
|
||||
lines.push(`- **标题**: \`${title}\``);
|
||||
lines.push(`- **提交人**: ${submitterName}`);
|
||||
if (requisitionDate) {
|
||||
lines.push(`- **申请日期**: ${requisitionDate}`);
|
||||
}
|
||||
lines.push(`- **提交人**: ${submitterName}`);
|
||||
|
||||
// 法人实体
|
||||
const legalEntityVal = form.法人实体 ?? form.legalEntity;
|
||||
if (legalEntityVal) {
|
||||
const formattedEntity = formatReferenceOrObject(legalEntityVal, options?.dimensionItemMap, options?.datalinkCardMap);
|
||||
lines.push(`- **法人实体**: ${formattedEntity}`);
|
||||
} else if (options?.corpName) {
|
||||
lines.push(`- **法人实体**: ${options.corpName}`);
|
||||
}
|
||||
|
||||
// 部门
|
||||
const expenseDept = form.expenseDepartment;
|
||||
if (expenseDept) {
|
||||
lines.push(`- **费用承担部门**: ${formatDepartmentValue(expenseDept, options?.departmentMap)}`);
|
||||
}
|
||||
const submitterDept = form.u_提交人部门 ?? form.submitterDepartment;
|
||||
if (submitterDept) {
|
||||
lines.push(`- **提交人部门**: ${formatDepartmentValue(submitterDept, options?.departmentMap)}`);
|
||||
}
|
||||
|
||||
// 事由说明
|
||||
const desc = form.description || form.reason;
|
||||
if (desc) {
|
||||
lines.push(`- **事由**: \`${desc}\``);
|
||||
}
|
||||
|
||||
// 是否有纸质票据
|
||||
const paperInvoice = form.u_是否有纸质票据;
|
||||
if (paperInvoice !== undefined && paperInvoice !== null && paperInvoice !== "") {
|
||||
lines.push(`- **是否有纸质票据**: ${formatReferenceOrObject(paperInvoice, options?.dimensionItemMap, options?.datalinkCardMap)}`);
|
||||
}
|
||||
|
||||
// 经常交易供应商
|
||||
const vendor = form.u_经常交易供应商 ?? form.payeeId;
|
||||
if (vendor) {
|
||||
lines.push(`- **经常交易供应商**: ${formatReferenceOrObject(vendor, options?.dimensionItemMap, options?.datalinkCardMap)}`);
|
||||
}
|
||||
|
||||
// 收款信息
|
||||
const payeeAccount = form.payeeAccountId ?? form.payeeInfo;
|
||||
if (payeeAccount) {
|
||||
lines.push(`- **收款信息**: ${formatReferenceOrObject(payeeAccount, options?.dimensionItemMap, options?.datalinkCardMap)}`);
|
||||
} else if (vendor && typeof vendor === "string" && options?.datalinkCardMap?.has(`payeeInfo:${vendor}`)) {
|
||||
lines.push(`- **收款信息**: ${options.datalinkCardMap.get(`payeeInfo:${vendor}`)}`);
|
||||
}
|
||||
|
||||
// 发票金额-总、税额、不含税
|
||||
if (form.u_发票金额) {
|
||||
lines.push(`- **发票金额-总**: ${formatAmountValue(form.u_发票金额)}`);
|
||||
}
|
||||
if (form.u_本单税额) {
|
||||
lines.push(`- **本单税额**: ${formatAmountValue(form.u_本单税额)}`);
|
||||
}
|
||||
if (form.u_本单不含税) {
|
||||
lines.push(`- **本单不含税**: ${formatAmountValue(form.u_本单不含税)}`);
|
||||
}
|
||||
|
||||
// 动态扩展字段追加
|
||||
for (const [k, v] of Object.entries(form)) {
|
||||
const formatted = formatDynamicField(k, v, options);
|
||||
if (formatted) {
|
||||
lines.push(`- **${formatted.label}**: ${formatted.text}`);
|
||||
}
|
||||
}
|
||||
|
||||
lines.push(`- **单号**: \`${code}\``);
|
||||
if (form.payMoney) {
|
||||
lines.push(`- **支付金额**: ${formatAmountValue(form.payMoney)}`);
|
||||
}
|
||||
lines.push(`- **提交日期**: ${submitTime}`);
|
||||
lines.push(`- **申请金额**: ${totalMoney}`);
|
||||
|
||||
if (form.requisitionMoney) {
|
||||
lines.push(`- **申请金额**: ${formatAmountValue(form.requisitionMoney)}`);
|
||||
}
|
||||
if (form.expenseMoney) {
|
||||
lines.push(`- **报销金额**: ${formatAmountValue(form.expenseMoney)}`);
|
||||
} else if (!form.requisitionMoney && (form.amount || form.payMoney)) {
|
||||
lines.push(`- **申请金额**: ${formatAmountValue(form.amount || form.payMoney)}`);
|
||||
}
|
||||
|
||||
if (form.companyRealPay !== undefined) {
|
||||
lines.push(`- **公司实付金额**: ${formatAmountValue(form.companyRealPay)}`);
|
||||
}
|
||||
if (form.writtenOffMoney !== undefined) {
|
||||
lines.push(`- **核销金额**: ${formatAmountValue(form.writtenOffMoney)}`);
|
||||
}
|
||||
lines.push("");
|
||||
|
||||
// 行程规划
|
||||
const itineraries = Array.isArray(form.itineraries) ? form.itineraries : [];
|
||||
lines.push(`### 行程规划(共 ${itineraries.length} 条)`);
|
||||
// 关联申请
|
||||
const requisitions = Array.isArray(form.requisitionIds) ? form.requisitionIds : [];
|
||||
lines.push(`### 关联申请(共 ${requisitions.length} 条)`);
|
||||
lines.push("");
|
||||
|
||||
// 行程规划 (仅在有行程时输出)
|
||||
const itineraries = Array.isArray(form.itineraries) ? form.itineraries : [];
|
||||
if (itineraries.length > 0) {
|
||||
lines.push(`### 行程规划(共 ${itineraries.length} 条)`);
|
||||
lines.push("");
|
||||
}
|
||||
|
||||
// 费用明细
|
||||
const details = Array.isArray(form.details) ? form.details : [];
|
||||
lines.push(`### 费用明细(共 ${details.length} 条)`);
|
||||
@@ -142,8 +658,8 @@ export function translateBillFlowToMarkdown(
|
||||
let feeTypeName = "住宿费";
|
||||
let feeTypePath = "差旅报销/住宿费";
|
||||
|
||||
if (feeTypeMap?.has(feeTypeId)) {
|
||||
const match = feeTypeMap.get(feeTypeId)!;
|
||||
if (options?.feeTypeMap?.has(feeTypeId)) {
|
||||
const match = options.feeTypeMap.get(feeTypeId)!;
|
||||
feeTypeName = match.name || feeTypeName;
|
||||
feeTypePath = match.path || feeTypeName;
|
||||
} else if (typeof feeTypeId === "string") {
|
||||
@@ -156,25 +672,61 @@ export function translateBillFlowToMarkdown(
|
||||
} else if (feeTypeId.includes("traffic") || feeTypeId.includes("交通")) {
|
||||
feeTypeName = "市内交通费";
|
||||
feeTypePath = "差旅报销/市内交通费";
|
||||
} else if (feeTypeId.includes("3iPhCno9HdI") || feeTypeId.includes("办公")) {
|
||||
feeTypeName = "办公用品";
|
||||
feeTypePath = "办公费/办公用品";
|
||||
}
|
||||
}
|
||||
|
||||
lines.push(`- **费用类型**: ${feeTypePath}(name=${feeTypeName})`);
|
||||
lines.push(`- **金额**: ${formatAmount(feeForm.amount)}`);
|
||||
if (feeForm.feeDate) {
|
||||
lines.push(`- **日期**: ${formatDateTime(feeForm.feeDate)}`);
|
||||
lines.push(`- **日期**: ${formatDateValue(feeForm.feeDate, true)}`);
|
||||
}
|
||||
const city = parseCity(feeForm.city);
|
||||
lines.push(`- **金额**: ${formatAmountValue(feeForm.amount)}`);
|
||||
|
||||
// 明细发票列表(内嵌相对位置)
|
||||
const invoiceList = feeForm.invoiceForm?.invoices || feeForm.invoices;
|
||||
if (Array.isArray(invoiceList) && invoiceList.length > 0) {
|
||||
lines.push(...formatInlineInvoices(invoiceList, options?.invoiceDetailMap));
|
||||
}
|
||||
|
||||
const city = parseCityValue(feeForm.city);
|
||||
if (city) {
|
||||
lines.push(`- **城市**: ${city}`);
|
||||
}
|
||||
if (feeForm.consumptionReasons) {
|
||||
lines.push(`- **消费事由**: \`${feeForm.consumptionReasons}\``);
|
||||
}
|
||||
if (feeForm.invoice) {
|
||||
lines.push(`- **发票张数**: ${feeForm.invoice}`);
|
||||
}
|
||||
if (feeForm.u_发票金额) {
|
||||
lines.push(`- **发票金额**: ${formatAmountValue(feeForm.u_发票金额)}`);
|
||||
}
|
||||
if (feeForm.taxAmount) {
|
||||
lines.push(`- **税额**: ${formatAmountValue(feeForm.taxAmount)}`);
|
||||
}
|
||||
|
||||
// 明细费用归属分摊
|
||||
if (Array.isArray(feeForm.apportions) && feeForm.apportions.length > 0) {
|
||||
lines.push(`- **费用归属分摊**: ${formatApportionSplits(feeForm.apportions, options?.departmentMap)}`);
|
||||
}
|
||||
|
||||
// 明细自定义业务字段
|
||||
if (feeForm.u_业务类型) {
|
||||
lines.push(`- **业务类型**: ${formatReferenceOrObject(feeForm.u_业务类型, options?.dimensionItemMap)}`);
|
||||
}
|
||||
|
||||
if (feeForm.detailId) {
|
||||
lines.push(`- **费用ID**: \`${feeForm.detailId}\``);
|
||||
}
|
||||
lines.push(`- **明细序号**: ${feeForm.detailNo || num}`);
|
||||
|
||||
// 明细附件列表(内嵌相对位置)
|
||||
if (Array.isArray(feeForm.attachments) && feeForm.attachments.length > 0) {
|
||||
lines.push(...formatInlineAttachments(feeForm.attachments));
|
||||
}
|
||||
|
||||
lines.push("");
|
||||
});
|
||||
|
||||
|
||||
@@ -109,7 +109,9 @@ export interface BillFlowEntry {
|
||||
time?: number;
|
||||
durationMs?: number;
|
||||
state?: string;
|
||||
rawState?: string;
|
||||
action?: string;
|
||||
rawAction?: string;
|
||||
nodeName?: string;
|
||||
comment?: string;
|
||||
automatic?: boolean;
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
# DataLink 域说明
|
||||
|
||||
DataLink 域负责跨企业查询当前账号可见的自建应用、业务对象、字段定义、业务记录、权限快照和导入状态。
|
||||
|
||||
## 代码结构
|
||||
|
||||
```text
|
||||
src/domains/datalink/
|
||||
├── types.ts # 应用详情、对象字段、记录分页与权限模型
|
||||
├── api.ts # DataLink HTTP 传输层
|
||||
├── services.ts # 应用/对象名称解析与查询表达式辅助
|
||||
└── tools.ts # MCP tool 注册
|
||||
```
|
||||
|
||||
## 查询链路
|
||||
|
||||
```text
|
||||
platform/search
|
||||
└─ platform/{platformId} 应用详情与管理权限
|
||||
└─ entity/platformId/{platformId} 业务对象与字段定义
|
||||
└─ searchPlatformDataLinkWithChild/{entityId} 业务记录
|
||||
```
|
||||
|
||||
应用列表和应用详情使用 EKB client。记录查询的 `filterBy` 原样支持 DataLink 过滤表达式;CLI 另提供 `--keyword`,自动生成名称/编码模糊查询。
|
||||
|
||||
## CLI
|
||||
|
||||
```bash
|
||||
hose-use platform list
|
||||
hose-use platform get <应用 ID|名称>
|
||||
hose-use platform entities <应用 ID|名称>
|
||||
hose-use platform schema <应用 ID|名称> [对象 ID|名称] [--keyword <字段关键词>]
|
||||
hose-use platform records <应用 ID|名称> <对象 ID|名称> [--keyword <关键词>] [--filter <表达式>] [--fields <字段列表>]
|
||||
hose-use platform record get <应用> <业务对象> <记录ID>
|
||||
hose-use platform record toggle <应用> <业务对象> <记录ID> [--state=true|false]
|
||||
hose-use platform record edit <应用> <业务对象> <记录ID> --data='{"field": "val"}'
|
||||
hose-use platform record recompute <应用> <业务对象> <记录ID>
|
||||
hose-use platform permissions <应用 ID|名称> [对象 ID|名称]
|
||||
hose-use platform imports <应用 ID|名称> <对象 ID|名称>
|
||||
```
|
||||
|
||||
也可以使用 `datalink` / `data-link` 作为同义命令域。
|
||||
|
||||
单条业务对象记录支持通过 `record get`(详情)、`record toggle`(启停用)、`record edit`(字段编辑更新)以及 `record recompute`(台账重算)进行维护。Excel 批量上传与流程引擎触发暂不在本域开放。
|
||||
@@ -0,0 +1,280 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import {
|
||||
DatalinkEntitySchema,
|
||||
DatalinkPlatformDetailSchema,
|
||||
type DatalinkEntity,
|
||||
type DatalinkImportJob,
|
||||
type DatalinkPlatformDetail,
|
||||
type DatalinkRecord,
|
||||
type DatalinkRecordDetail,
|
||||
type DatalinkRecordEditPayload,
|
||||
type DatalinkRecordPage,
|
||||
type DatalinkRecordQuery,
|
||||
} from "./types.js";
|
||||
|
||||
function asRecord(value: unknown): Record<string, any> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as Record<string, any>)
|
||||
: {};
|
||||
}
|
||||
|
||||
function numberOr(value: unknown, fallback: number): number {
|
||||
const parsed = typeof value === "number" ? value : Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : fallback;
|
||||
}
|
||||
|
||||
function parseEntity(value: unknown): DatalinkEntity {
|
||||
return DatalinkEntitySchema.parse(asRecord(value));
|
||||
}
|
||||
|
||||
function sanitizePlatformDetail(value: unknown): Record<string, unknown> {
|
||||
const platform = asRecord(value);
|
||||
const admin = Array.isArray(platform.admin)
|
||||
? platform.admin.map((item) => {
|
||||
const staff = asRecord(item);
|
||||
return {
|
||||
id: staff.id,
|
||||
name: staff.name,
|
||||
code: staff.code,
|
||||
active: staff.active,
|
||||
};
|
||||
})
|
||||
: platform.admin;
|
||||
return { ...platform, admin };
|
||||
}
|
||||
|
||||
/** 列出当前企业可见的启用自建应用。 */
|
||||
export async function listPlatforms(client: KyInstance, corpId: string) {
|
||||
const response = await client.get("api/v2/datalink/platform/search", {
|
||||
searchParams: { scope: "enable", corpId },
|
||||
});
|
||||
const json = asRecord(await response.json());
|
||||
const items = Array.isArray(json.items) ? json.items.map(sanitizePlatformDetail) : [];
|
||||
return z.array(DatalinkPlatformDetailSchema).parse(items);
|
||||
}
|
||||
|
||||
/** 列出当前企业全量自建应用与模板平台(包含 HAB 模板与全部自建应用)。 */
|
||||
export async function listAllPlatforms(client: KyInstance, corpId: string) {
|
||||
const response = await client.get("api/v2/datalink/platform", {
|
||||
searchParams: { corpId },
|
||||
});
|
||||
const json = asRecord(await response.json());
|
||||
const rawList = Array.isArray(json) ? json : Array.isArray(json.items) ? json.items : [];
|
||||
const items = rawList.map(sanitizePlatformDetail);
|
||||
return z.array(DatalinkPlatformDetailSchema).parse(items);
|
||||
}
|
||||
|
||||
/** 获取单个应用详情以及应用级人员/角色/部门权限。 */
|
||||
export async function getPlatform(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
platformId: string
|
||||
): Promise<DatalinkPlatformDetail> {
|
||||
const normalizedId = platformId.startsWith("$") ? platformId : `$${platformId}`;
|
||||
const bareId = platformId.startsWith("$") ? platformId.slice(1) : platformId;
|
||||
const response = await client.get(`api/v2/datalink/platform/${normalizedId}`, {
|
||||
// 前端实际使用两个 join,并且详情接口要求同时传 id。
|
||||
searchParams: new URLSearchParams([
|
||||
["id", bareId],
|
||||
["join", "icon.fileId,fileId,/v1/attachment/attachments"],
|
||||
["corpId", corpId],
|
||||
["join", "adminIds,admin,/v1/organization/staffs"],
|
||||
]),
|
||||
});
|
||||
const json = asRecord(await response.json());
|
||||
return DatalinkPlatformDetailSchema.parse(sanitizePlatformDetail(json.value ?? json.data ?? json));
|
||||
}
|
||||
|
||||
/** 获取应用下的业务对象目录及完整字段定义。 */
|
||||
export async function listPlatformEntities(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
platformId: string
|
||||
): Promise<DatalinkEntity[]> {
|
||||
const normalizedId = platformId.startsWith("$") ? platformId : `$${platformId}`;
|
||||
const response = await client.post(`api/v2/datalink/entity/platformId/${normalizedId}`, {
|
||||
searchParams: { corpId },
|
||||
// 该 POST 即使没有筛选条件也要求发送空 JSON body;前端会发送 {}。
|
||||
json: {},
|
||||
});
|
||||
const json = asRecord(await response.json());
|
||||
const rawItems = Array.isArray(json.items)
|
||||
? json.items
|
||||
: Array.isArray(asRecord(json.value).items)
|
||||
? asRecord(json.value).items
|
||||
: [];
|
||||
return rawItems.map(parseEntity);
|
||||
}
|
||||
|
||||
/** 分页检索指定业务对象的记录。filterBy 使用 DataLink 原生表达式。 */
|
||||
export async function searchEntityRecords(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
entityId: string,
|
||||
query: DatalinkRecordQuery = {}
|
||||
): Promise<DatalinkRecordPage> {
|
||||
const normalizedId = entityId.startsWith("$") ? entityId : `$${entityId}`;
|
||||
const limit = {
|
||||
start: query.start ?? 0,
|
||||
count: query.count ?? 20,
|
||||
};
|
||||
const nativeQuery: Record<string, unknown> = {
|
||||
filterBy: query.filterBy?.trim() || "(active.in(true,false))",
|
||||
limit,
|
||||
};
|
||||
if (query.orderBy !== undefined) nativeQuery.orderBy = query.orderBy;
|
||||
|
||||
const response = await client.post(
|
||||
`api/v2/datalink/searchPlatformDataLinkWithChild/${normalizedId}`,
|
||||
{
|
||||
searchParams: { corpId },
|
||||
json: { query: nativeQuery, entityId },
|
||||
}
|
||||
);
|
||||
const json = asRecord(await response.json());
|
||||
const payload = asRecord(json.items && !Array.isArray(json.items) ? json.items : json.value ?? json);
|
||||
const rawData = Array.isArray(payload.data)
|
||||
? payload.data
|
||||
: Array.isArray(payload.items)
|
||||
? payload.items
|
||||
: Array.isArray(json.items)
|
||||
? json.items
|
||||
: [];
|
||||
|
||||
return {
|
||||
total: numberOr(payload.total ?? json.total, rawData.length),
|
||||
data: rawData.filter((item): item is DatalinkRecord => item !== null && typeof item === "object"),
|
||||
actions: Array.isArray(payload.actions) ? payload.actions : [],
|
||||
components: Array.isArray(payload.components) ? payload.components : [],
|
||||
path: payload.path,
|
||||
template: payload.template,
|
||||
};
|
||||
}
|
||||
|
||||
/** 查询对象导入任务状态。 */
|
||||
export async function listImportJobs(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
entityId: string
|
||||
): Promise<DatalinkImportJob[]> {
|
||||
const response = await client.get("api/engine/easo/batchJobs", {
|
||||
searchParams: { entityId, corpId },
|
||||
});
|
||||
const json = asRecord(await response.json());
|
||||
const items = json.items ?? asRecord(json.value).items ?? json.value ?? [];
|
||||
return Array.isArray(items) ? items.filter((item): item is DatalinkImportJob => item !== null && typeof item === "object") : [];
|
||||
}
|
||||
|
||||
/** 查询对象最近一次 Excel 导入结果。 */
|
||||
export async function getImportResult(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
entityId: string
|
||||
): Promise<Record<string, unknown>> {
|
||||
const normalizedId = entityId.startsWith("$") ? entityId : `$${entityId}`;
|
||||
const response = await client.get(`api/v1/datalink/excel/import/result/${normalizedId}`, {
|
||||
searchParams: { entityId, corpId },
|
||||
});
|
||||
return asRecord(await response.json());
|
||||
}
|
||||
|
||||
/** 切换业务对象记录的停启用状态 (active: true <-> false)。若未指定 state 则自动反转当前状态。 */
|
||||
export async function toggleRecordState(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
recordId: string,
|
||||
state?: boolean
|
||||
): Promise<{ recordId: string; active: boolean }> {
|
||||
const normalizedId = recordId.startsWith("$") ? recordId : `$${recordId}`;
|
||||
const bareId = recordId.startsWith("$") ? recordId.slice(1) : recordId;
|
||||
let targetState = state;
|
||||
if (targetState === undefined) {
|
||||
const detail = await getRecordDetail(client, corpId, recordId);
|
||||
const record = ((detail.dataLink ?? (detail as any).data?.dataLink ?? detail) as Record<string, unknown>);
|
||||
targetState = !(record.active ?? true);
|
||||
}
|
||||
|
||||
await client.put(`api/supplier/v3/contract/${normalizedId}/state`, {
|
||||
searchParams: { corpId },
|
||||
json: { id: bareId, state: targetState },
|
||||
});
|
||||
|
||||
return { recordId: bareId, active: targetState };
|
||||
}
|
||||
|
||||
/** 获取单条业务对象记录的完整详情(包含展示模板、字段值、可见性及审批历史等)。 */
|
||||
export async function getRecordDetail(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
recordId: string
|
||||
): Promise<DatalinkRecordDetail> {
|
||||
const normalizedId = recordId.startsWith("$") ? recordId : `$${recordId}`;
|
||||
const bareId = recordId.startsWith("$") ? recordId.slice(1) : recordId;
|
||||
const response = await client.get(`api/v2/datalink/detail/${normalizedId}/$DETAIL`, {
|
||||
searchParams: {
|
||||
dataLinkId: bareId,
|
||||
type: "DETAIL",
|
||||
corpId,
|
||||
},
|
||||
});
|
||||
const json = asRecord(await response.json());
|
||||
return (json.value ?? json.data ?? json) as DatalinkRecordDetail;
|
||||
}
|
||||
|
||||
/** 获取业务对象编辑表单的字段结构定义。 */
|
||||
export async function getRecordFormSchema(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
entityId: string
|
||||
): Promise<Record<string, unknown>> {
|
||||
const normalizedId = entityId.startsWith("$") ? entityId : `$${entityId}`;
|
||||
const bareId = entityId.startsWith("$") ? entityId.slice(1) : entityId;
|
||||
const response = await client.get(`api/v2/datalink/entityEdit/entityForm/${normalizedId}/$true`, {
|
||||
searchParams: {
|
||||
entityId: bareId,
|
||||
isInsert: "true",
|
||||
needFormula: "true",
|
||||
corpId,
|
||||
},
|
||||
});
|
||||
return asRecord(await response.json());
|
||||
}
|
||||
|
||||
/** 编辑更新业务对象记录字段。 */
|
||||
export async function editRecord(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
payload: DatalinkRecordEditPayload
|
||||
): Promise<Record<string, unknown>> {
|
||||
const bareEntityId = payload.dataLinkEntityId.startsWith("$")
|
||||
? payload.dataLinkEntityId.slice(1)
|
||||
: payload.dataLinkEntityId;
|
||||
const bareRecordId = payload.dataLinkId.startsWith("$")
|
||||
? payload.dataLinkId.slice(1)
|
||||
: payload.dataLinkId;
|
||||
|
||||
const response = await client.post("api/v2/datalink/entityEdit/edit", {
|
||||
searchParams: { corpId },
|
||||
json: {
|
||||
...payload,
|
||||
dataLinkEntityId: bareEntityId,
|
||||
dataLinkId: bareRecordId,
|
||||
},
|
||||
});
|
||||
const json = asRecord(await response.json());
|
||||
return (json.value ?? json.data ?? json) as Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** 重算业务对象记录下的台账信息。 */
|
||||
export async function recomputeRecordLedger(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
recordId: string
|
||||
): Promise<Record<string, unknown>> {
|
||||
const normalizedId = recordId.startsWith("$") ? recordId : `$${recordId}`;
|
||||
const response = await client.post(`api/v2/ledger/recompute/${normalizedId}`, {
|
||||
searchParams: { corpId },
|
||||
});
|
||||
return asRecord(await response.json());
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import {
|
||||
editRecord,
|
||||
getPlatform,
|
||||
getRecordDetail,
|
||||
listPlatformEntities,
|
||||
listPlatforms,
|
||||
recomputeRecordLedger,
|
||||
searchEntityRecords,
|
||||
toggleRecordState,
|
||||
} from "./api.js";
|
||||
import { buildKeywordFilter, selectRecordFields } from "./services.js";
|
||||
|
||||
const platform = {
|
||||
id: "platform-1",
|
||||
name: "业务应用",
|
||||
corporationId: "corp-1",
|
||||
active: true,
|
||||
adminIds: ["staff-1"],
|
||||
};
|
||||
|
||||
describe("DataLink Domain - 应用、业务对象与记录查询", () => {
|
||||
test("列出应用并为权限数组提供稳定默认值", async () => {
|
||||
const client = {
|
||||
get: async (url: string, options: any) => {
|
||||
expect(url).toBe("api/v2/datalink/platform/search");
|
||||
expect(options.searchParams).toEqual({ scope: "enable", corpId: "corp-1" });
|
||||
return { json: async () => ({ items: [platform] }) };
|
||||
},
|
||||
} as any;
|
||||
|
||||
const result = await listPlatforms(client, "corp-1");
|
||||
expect(result[0]?.name).toBe("业务应用");
|
||||
expect(result[0]?.staffIds).toEqual([]);
|
||||
expect(result[0]?.departmentIds).toEqual([]);
|
||||
});
|
||||
|
||||
test("获取应用详情时请求管理员关联", async () => {
|
||||
const client = {
|
||||
get: async (url: string, options: any) => {
|
||||
expect(url).toBe("api/v2/datalink/platform/$platform-1");
|
||||
expect(options.searchParams).toBeInstanceOf(URLSearchParams);
|
||||
expect(options.searchParams.get("id")).toBe("platform-1");
|
||||
expect(options.searchParams.getAll("join")).toEqual([
|
||||
"icon.fileId,fileId,/v1/attachment/attachments",
|
||||
"adminIds,admin,/v1/organization/staffs",
|
||||
]);
|
||||
expect(options.searchParams.get("corpId")).toBe("corp-1");
|
||||
return { json: async () => ({ value: { ...platform, staffIds: ["staff-1"], roleIds: ["role-1"], departmentIds: [], admin: [{ id: "staff-1", name: "管理员", code: "A-1", cellphone: "13800000000" }] } }) };
|
||||
},
|
||||
} as any;
|
||||
|
||||
const result = await getPlatform(client, "corp-1", "platform-1");
|
||||
expect(result.adminIds).toEqual(["staff-1"]);
|
||||
expect(result.roleIds).toEqual(["role-1"]);
|
||||
expect(result.admin).toEqual([{ id: "staff-1", name: "管理员", code: "A-1", active: undefined }]);
|
||||
expect(JSON.stringify(result)).not.toContain("13800000000");
|
||||
});
|
||||
|
||||
test("获取对象字段元数据并保留扩展属性", async () => {
|
||||
const client = {
|
||||
post: async (url: string, options: any) => {
|
||||
expect(url).toBe("api/v2/datalink/entity/platformId/$platform-1");
|
||||
expect(options.searchParams.corpId).toBe("corp-1");
|
||||
expect(options.json).toEqual({});
|
||||
return { json: async () => ({ items: [{ id: "entity-1", name: "供应商", fields: [{ name: "code", label: "编码", type: "text", optional: false, customFlag: true }] }] }) };
|
||||
},
|
||||
} as any;
|
||||
|
||||
const result = await listPlatformEntities(client, "corp-1", "platform-1");
|
||||
expect(result[0]?.fields[0]?.label).toBe("编码");
|
||||
expect(result[0]?.fields[0]?.customFlag).toBe(true);
|
||||
});
|
||||
|
||||
test("分页查询记录并生成标准化分页结果", async () => {
|
||||
const client = {
|
||||
post: async (url: string, options: any) => {
|
||||
expect(url).toBe("api/v2/datalink/searchPlatformDataLinkWithChild/$entity-1");
|
||||
expect(options.searchParams.corpId).toBe("corp-1");
|
||||
expect(options.json).toEqual({
|
||||
entityId: "entity-1",
|
||||
query: { filterBy: 'code == "A-1"', limit: { start: 10, count: 5 } },
|
||||
});
|
||||
return { json: async () => ({ items: { total: 1, data: [{ id: "record-1", dataLink: { code: "A-1" } }] } }) };
|
||||
},
|
||||
} as any;
|
||||
|
||||
const result = await searchEntityRecords(client, "corp-1", "entity-1", { start: 10, count: 5, filterBy: 'code == "A-1"' });
|
||||
expect(result.total).toBe(1);
|
||||
expect(result.data[0]?.dataLink?.code).toBe("A-1");
|
||||
});
|
||||
|
||||
test("关键词过滤和字段投影可用于通用 CLI 查询", () => {
|
||||
expect(buildKeywordFilter('A"1')).toContain('A\\"1');
|
||||
expect(selectRecordFields({ id: "r-1", dataLink: { code: "A-1" } }, ["编码"], [{ name: "code", label: "编码", type: "text" }])).toEqual({ id: "r-1", dataLink: { 编码: "A-1" } });
|
||||
});
|
||||
|
||||
test("切换记录停启用状态调用 PUT contract state 接口", async () => {
|
||||
let calledUrl = "";
|
||||
let calledParams: any = null;
|
||||
let calledJson: any = null;
|
||||
const client = {
|
||||
get: async () => ({
|
||||
json: async () => ({ value: { id: "record-1", active: true } }),
|
||||
}),
|
||||
put: async (url: string, options: any) => {
|
||||
calledUrl = url;
|
||||
calledParams = options.searchParams;
|
||||
calledJson = options.json;
|
||||
return { status: 204 };
|
||||
},
|
||||
} as any;
|
||||
|
||||
const res = await toggleRecordState(client, "corp-1", "record-1");
|
||||
expect(calledUrl).toBe("api/supplier/v3/contract/$record-1/state");
|
||||
expect(calledParams).toEqual({ corpId: "corp-1" });
|
||||
expect(calledJson).toEqual({ id: "record-1", state: false });
|
||||
expect(res).toEqual({ recordId: "record-1", active: false });
|
||||
});
|
||||
|
||||
test("获取记录详情调用 GET datalink detail 接口", async () => {
|
||||
const client = {
|
||||
get: async (url: string, options: any) => {
|
||||
expect(url).toBe("api/v2/datalink/detail/$record-1/$DETAIL");
|
||||
expect(options.searchParams).toEqual({
|
||||
dataLinkId: "record-1",
|
||||
type: "DETAIL",
|
||||
corpId: "corp-1",
|
||||
});
|
||||
return { json: async () => ({ value: { id: "record-1", name: "记录1" } }) };
|
||||
},
|
||||
} as any;
|
||||
|
||||
const result = await getRecordDetail(client, "corp-1", "record-1");
|
||||
expect((result as any).name).toBe("记录1");
|
||||
});
|
||||
|
||||
test("编辑业务对象记录调用 POST entityEdit edit 接口", async () => {
|
||||
const client = {
|
||||
post: async (url: string, options: any) => {
|
||||
expect(url).toBe("api/v2/datalink/entityEdit/edit");
|
||||
expect(options.searchParams).toEqual({ corpId: "corp-1" });
|
||||
expect(options.json.dataLinkEntityId).toBe("entity-1");
|
||||
expect(options.json.dataLinkId).toBe("record-1");
|
||||
expect(options.json.form).toEqual({ name: "新名称" });
|
||||
return { json: async () => ({ value: { id: "record-1", name: "新名称" } }) };
|
||||
},
|
||||
} as any;
|
||||
|
||||
const result = await editRecord(client, "corp-1", {
|
||||
dataLinkEntityId: "$entity-1",
|
||||
dataLinkId: "$record-1",
|
||||
form: { name: "新名称" },
|
||||
});
|
||||
expect((result as any).name).toBe("新名称");
|
||||
});
|
||||
|
||||
test("重算台账调用 POST ledger recompute 接口", async () => {
|
||||
const client = {
|
||||
post: async (url: string, options: any) => {
|
||||
expect(url).toBe("api/v2/ledger/recompute/$record-1");
|
||||
expect(options.searchParams).toEqual({ corpId: "corp-1" });
|
||||
return { json: async () => ({ id: "ok" }) };
|
||||
},
|
||||
} as any;
|
||||
|
||||
const result = await recomputeRecordLedger(client, "corp-1", "record-1");
|
||||
expect(result.id).toBe("ok");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import * as api from "./api.js";
|
||||
import type { DatalinkEntity, DatalinkField, DatalinkPlatformDetail } from "./types.js";
|
||||
|
||||
function matches(value: unknown, target: string): boolean {
|
||||
return typeof value === "string" && value.toLowerCase() === target.toLowerCase();
|
||||
}
|
||||
|
||||
export async function resolvePlatform(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string
|
||||
): Promise<DatalinkPlatformDetail | undefined> {
|
||||
const platforms = await api.listPlatforms(client, corpId);
|
||||
const found = platforms.find((platform) =>
|
||||
[platform.id, platform.name, platform.code].some((value) => matches(value, target))
|
||||
);
|
||||
return found ? api.getPlatform(client, corpId, found.id) : undefined;
|
||||
}
|
||||
|
||||
export async function resolveEntity(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
platform: DatalinkPlatformDetail,
|
||||
target: string
|
||||
): Promise<DatalinkEntity | undefined> {
|
||||
const entities = await api.listPlatformEntities(client, corpId, platform.id);
|
||||
return entities.find((entity) =>
|
||||
[entity.id, entity.name, entity.code].some((value) => matches(value, target))
|
||||
);
|
||||
}
|
||||
|
||||
export function buildKeywordFilter(keyword: string): string {
|
||||
const escaped = keyword.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
|
||||
return `(name.containsIgnoreCase("${escaped}")||code.containsIgnoreCase("${escaped}"))&&(active.in(true,false))`;
|
||||
}
|
||||
|
||||
export function selectRecordFields(record: Record<string, unknown>, fields: string[], definitions: DatalinkField[] = []): Record<string, unknown> {
|
||||
if (fields.length === 0) return record;
|
||||
const dataLink = record.dataLink && typeof record.dataLink === "object" && !Array.isArray(record.dataLink)
|
||||
? (record.dataLink as Record<string, unknown>)
|
||||
: record;
|
||||
const selected: Record<string, unknown> = {};
|
||||
for (const selector of fields) {
|
||||
const definition = definitions.find((field) => field.name === selector || field.label === selector);
|
||||
const sourceName = definition?.name ?? selector;
|
||||
if (sourceName in dataLink) selected[definition?.label || selector] = dataLink[sourceName];
|
||||
}
|
||||
return record.dataLink && typeof record.dataLink === "object"
|
||||
? { ...record, dataLink: selected }
|
||||
: selected;
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import { z } from "zod";
|
||||
import * as api from "./api.js";
|
||||
|
||||
const clientSchema = z.object({
|
||||
corp: z.object({ credentials: z.object({ corpId: z.string() }) }).passthrough(),
|
||||
ekbClient: z.any(),
|
||||
});
|
||||
|
||||
export const datalinkTools = [
|
||||
{
|
||||
name: "datalink_platform_list",
|
||||
description: "列出当前企业账号可见的启用自建应用(可传入 all=true 查看包含模板平台的完整列表)",
|
||||
parameters: z.object({
|
||||
all: z.boolean().optional().describe("是否拉取包含 HAB 模板与全量平台列表"),
|
||||
}),
|
||||
handler: async (clients: unknown, params: { all?: boolean } = {}) => {
|
||||
const { corp, ekbClient } = clientSchema.parse(clients);
|
||||
const platforms = params.all
|
||||
? await api.listAllPlatforms(ekbClient, corp.credentials.corpId)
|
||||
: await api.listPlatforms(ekbClient, corp.credentials.corpId);
|
||||
return { platforms };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "datalink_platform_get",
|
||||
description: "获取自建应用详情以及应用管理员、人员、角色和部门可见权限",
|
||||
parameters: z.object({ platformId: z.string().describe("自建应用 ID") }),
|
||||
handler: async (clients: unknown, params: { platformId: string }) => {
|
||||
const { corp, ekbClient } = clientSchema.parse(clients);
|
||||
return api.getPlatform(ekbClient, corp.credentials.corpId, params.platformId);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "datalink_entity_list",
|
||||
description: "获取一个自建应用下的业务对象目录、字段、操作和可见性配置",
|
||||
parameters: z.object({ platformId: z.string().describe("自建应用 ID") }),
|
||||
handler: async (clients: unknown, params: { platformId: string }) => {
|
||||
const { corp, ekbClient } = clientSchema.parse(clients);
|
||||
return { entities: await api.listPlatformEntities(ekbClient, corp.credentials.corpId, params.platformId) };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "datalink_record_search",
|
||||
description: "分页检索业务对象记录,支持 DataLink filterBy 表达式",
|
||||
parameters: z.object({
|
||||
entityId: z.string().describe("业务对象 ID"),
|
||||
start: z.number().int().min(0).optional(),
|
||||
count: z.number().int().min(1).max(1000).optional(),
|
||||
filterBy: z.string().optional().describe("DataLink 原生过滤表达式"),
|
||||
}),
|
||||
handler: async (clients: unknown, params: { entityId: string; start?: number; count?: number; filterBy?: string }) => {
|
||||
const { corp, ekbClient } = clientSchema.parse(clients);
|
||||
return api.searchEntityRecords(ekbClient, corp.credentials.corpId, params.entityId, params);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "datalink_import_jobs",
|
||||
description: "查看业务对象的导入任务和最近导入结果",
|
||||
parameters: z.object({ entityId: z.string().describe("业务对象 ID") }),
|
||||
handler: async (clients: unknown, params: { entityId: string }) => {
|
||||
const { corp, ekbClient } = clientSchema.parse(clients);
|
||||
const [jobs, result] = await Promise.all([
|
||||
api.listImportJobs(ekbClient, corp.credentials.corpId, params.entityId),
|
||||
api.getImportResult(ekbClient, corp.credentials.corpId, params.entityId),
|
||||
]);
|
||||
return { jobs, latestResult: result };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "datalink_record_get",
|
||||
description: "获取单条业务对象记录的完整详情(模板、字段值、可见性及历史等)",
|
||||
parameters: z.object({
|
||||
recordId: z.string().describe("业务对象记录 ID (dataLinkId)"),
|
||||
}),
|
||||
handler: async (clients: unknown, params: { recordId: string }) => {
|
||||
const { corp, ekbClient } = clientSchema.parse(clients);
|
||||
return api.getRecordDetail(ekbClient, corp.credentials.corpId, params.recordId);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "datalink_record_toggle",
|
||||
description: "切换业务对象记录的停启用状态 (active: true <-> false)",
|
||||
parameters: z.object({
|
||||
recordId: z.string().describe("业务对象记录 ID (dataLinkId)"),
|
||||
state: z.boolean().optional().describe("目标状态 (true 为启用,false 为停用,不传则自动翻转)"),
|
||||
}),
|
||||
handler: async (clients: unknown, params: { recordId: string; state?: boolean }) => {
|
||||
const { corp, ekbClient } = clientSchema.parse(clients);
|
||||
const result = await api.toggleRecordState(ekbClient, corp.credentials.corpId, params.recordId, params.state);
|
||||
return { success: true, ...result };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "datalink_record_edit",
|
||||
description: "编辑更新业务对象记录的字段值",
|
||||
parameters: z.object({
|
||||
entityId: z.string().describe("业务对象 ID"),
|
||||
recordId: z.string().describe("业务对象记录 ID (dataLinkId)"),
|
||||
form: z.record(z.string(), z.unknown()).describe("待更新的表单字段键值对"),
|
||||
active: z.boolean().optional().describe("停启用状态"),
|
||||
visibility: z.record(z.string(), z.unknown()).optional().describe("可见性配置"),
|
||||
}),
|
||||
handler: async (
|
||||
clients: unknown,
|
||||
params: {
|
||||
entityId: string;
|
||||
recordId: string;
|
||||
form: Record<string, unknown>;
|
||||
active?: boolean;
|
||||
visibility?: Record<string, unknown>;
|
||||
}
|
||||
) => {
|
||||
const { corp, ekbClient } = clientSchema.parse(clients);
|
||||
return api.editRecord(ekbClient, corp.credentials.corpId, {
|
||||
dataLinkEntityId: params.entityId,
|
||||
dataLinkId: params.recordId,
|
||||
form: params.form,
|
||||
active: params.active,
|
||||
visibility: params.visibility,
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "datalink_record_recompute",
|
||||
description: "重新计算指定业务对象记录下的全部台账信息",
|
||||
parameters: z.object({
|
||||
recordId: z.string().describe("业务对象记录 ID (dataLinkId)"),
|
||||
}),
|
||||
handler: async (clients: unknown, params: { recordId: string }) => {
|
||||
const { corp, ekbClient } = clientSchema.parse(clients);
|
||||
return api.recomputeRecordLedger(ekbClient, corp.credentials.corpId, params.recordId);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
export type DatalinkTool = (typeof datalinkTools)[number];
|
||||
@@ -0,0 +1,121 @@
|
||||
import { z } from "zod";
|
||||
import { PlatformSchema } from "../platform/types.js";
|
||||
|
||||
const NullableBoolean = z.boolean().nullable().optional();
|
||||
|
||||
/** DataLink 字段元数据。保留服务端未建模的扩展字段,避免丢失配置。 */
|
||||
export const DatalinkFieldSchema = z
|
||||
.object({
|
||||
name: z.string().default(""),
|
||||
label: z.string().default(""),
|
||||
type: z.string().default("text"),
|
||||
optional: NullableBoolean,
|
||||
regex: z.string().nullable().optional(),
|
||||
source: z.string().nullable().optional(),
|
||||
formula: z.boolean().nullable().optional(),
|
||||
calculation: z.record(z.string(), z.unknown()).nullable().optional(),
|
||||
entity: z.string().nullable().optional(),
|
||||
withTime: z.boolean().nullable().optional(),
|
||||
scale: z.number().nullable().optional(),
|
||||
unit: z.string().nullable().optional(),
|
||||
index: z.boolean().nullable().optional(),
|
||||
systemField: z.boolean().nullable().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export const DatalinkEntitySchema = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
code: z.string().default(""),
|
||||
name: z.string().default(""),
|
||||
type: z.string().default(""),
|
||||
active: z.boolean().default(true),
|
||||
fields: z.array(DatalinkFieldSchema).default([]),
|
||||
actions: z.array(z.unknown()).default([]),
|
||||
importMethod: z.array(z.string()).default([]),
|
||||
visibility: z.unknown().optional(),
|
||||
homeVisibility: z.unknown().optional(),
|
||||
exportVisibility: z.unknown().optional(),
|
||||
dataFilter: z.unknown().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export const DatalinkPlatformDetailSchema = PlatformSchema.passthrough().extend({
|
||||
staffIds: z.array(z.string()).nullish().transform((value) => value ?? []),
|
||||
roleIds: z.array(z.string()).nullish().transform((value) => value ?? []),
|
||||
departmentIds: z.array(z.string()).nullish().transform((value) => value ?? []),
|
||||
departmentsIncludeChildren: z.boolean().nullish().transform((value) => value ?? false),
|
||||
});
|
||||
|
||||
export interface DatalinkRecordQuery {
|
||||
start?: number;
|
||||
count?: number;
|
||||
filterBy?: string;
|
||||
/** 服务端支持的排序表达式,原样透传。 */
|
||||
orderBy?: unknown;
|
||||
}
|
||||
|
||||
export interface DatalinkRecord {
|
||||
id?: string;
|
||||
entityId?: string;
|
||||
dataLink?: Record<string, unknown>;
|
||||
fieldAuth?: Record<string, unknown>;
|
||||
visibility?: unknown;
|
||||
active?: boolean;
|
||||
ownerId?: string;
|
||||
createTime?: number | string;
|
||||
updateTime?: number | string;
|
||||
actions?: unknown[];
|
||||
source?: unknown;
|
||||
sourceId?: unknown;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface DatalinkRecordPage {
|
||||
total: number;
|
||||
data: DatalinkRecord[];
|
||||
actions: unknown[];
|
||||
components: unknown[];
|
||||
path: unknown;
|
||||
template: unknown;
|
||||
}
|
||||
|
||||
export interface DatalinkImportJob {
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export type DatalinkField = z.infer<typeof DatalinkFieldSchema>;
|
||||
export type DatalinkEntity = z.infer<typeof DatalinkEntitySchema>;
|
||||
export type DatalinkPlatformDetail = z.infer<typeof DatalinkPlatformDetailSchema>;
|
||||
|
||||
export interface DatalinkPermissionSnapshot {
|
||||
platform: DatalinkPlatformDetail;
|
||||
entity?: DatalinkEntity;
|
||||
}
|
||||
|
||||
export interface DatalinkRecordDetail {
|
||||
dataLink?: DatalinkRecord;
|
||||
template?: unknown;
|
||||
entity?: unknown;
|
||||
actions?: unknown[];
|
||||
flowCounts?: Record<string, unknown>;
|
||||
ledger?: Record<string, unknown>;
|
||||
ledgers?: unknown[];
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface DatalinkRecordEditPayload {
|
||||
dataLinkEntityId: string;
|
||||
dataLinkId: string;
|
||||
active?: boolean;
|
||||
form: Record<string, unknown>;
|
||||
visibility?: {
|
||||
fullVisible?: boolean;
|
||||
staffs?: string[];
|
||||
roles?: string[];
|
||||
departments?: string[];
|
||||
departmentsIncludeChildren?: boolean;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
[key: string]: unknown;
|
||||
}
|
||||
@@ -1,37 +1,53 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import { getGlobalCache } from "../../core/cache/index.js";
|
||||
import { listDimensionCatalogs, listDimensionItems } from "./api.js";
|
||||
import type { DimensionCatalog, DimensionItem, DimensionQuery } from "./types.js";
|
||||
|
||||
const cache = new Map<string, { timestamp: number; catalogs: DimensionCatalog[]; items: Map<string, DimensionItem[]> }>();
|
||||
const CACHE_TTL_MS = 10 * 60 * 1000;
|
||||
|
||||
async function getCached(client: KyInstance, corpId: string): Promise<{ catalogs: DimensionCatalog[]; items: Map<string, DimensionItem[]> }> {
|
||||
const existing = cache.get(corpId);
|
||||
if (existing && Date.now() - existing.timestamp < CACHE_TTL_MS) return existing;
|
||||
const catalogs = await listDimensionCatalogs(client, corpId);
|
||||
const result = { timestamp: Date.now(), catalogs, items: new Map<string, DimensionItem[]>() };
|
||||
cache.set(corpId, result);
|
||||
return result;
|
||||
async function getCachedCatalogs(client: KyInstance, corpId: string): Promise<DimensionCatalog[]> {
|
||||
const cache = getGlobalCache();
|
||||
return cache.withCache(
|
||||
`dimensions:catalogs:${corpId}`,
|
||||
() => listDimensionCatalogs(client, corpId),
|
||||
{ namespace: "dimensions", ttlMs: CACHE_TTL_MS }
|
||||
);
|
||||
}
|
||||
|
||||
export async function searchDimensions(client: KyInstance, corpId: string, query: DimensionQuery = {}): Promise<DimensionCatalog[]> {
|
||||
const { catalogs } = await getCached(client, corpId);
|
||||
export async function searchDimensions(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
query: DimensionQuery = {}
|
||||
): Promise<DimensionCatalog[]> {
|
||||
const catalogs = await getCachedCatalogs(client, corpId);
|
||||
const keyword = (query.name || query.code || query.id || "").trim().toLowerCase();
|
||||
if (!keyword) return catalogs;
|
||||
return catalogs.filter((item) => [item.id, item.name, item.code].some((value) => value.toLowerCase().includes(keyword)));
|
||||
return catalogs.filter((item) =>
|
||||
[item.id, item.name, item.code].some((value) => value.toLowerCase().includes(keyword))
|
||||
);
|
||||
}
|
||||
|
||||
export async function getDimensionItems(client: KyInstance, corpId: string, dimension: DimensionCatalog, start = 0, count = 100): Promise<DimensionItem[]> {
|
||||
const catalog = await getCached(client, corpId);
|
||||
const cached = catalog.items.get(dimension.id);
|
||||
if (cached && start === 0 && count >= cached.length) return cached;
|
||||
const items = await listDimensionItems(client, corpId, dimension.id, start, count);
|
||||
if (start === 0) catalog.items.set(dimension.id, items);
|
||||
return items;
|
||||
export async function getDimensionItems(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
dimension: DimensionCatalog,
|
||||
start = 0,
|
||||
count = 100
|
||||
): Promise<DimensionItem[]> {
|
||||
const cache = getGlobalCache();
|
||||
return cache.withCache(
|
||||
`dimensions:items:${corpId}:${dimension.id}:${start}:${count}`,
|
||||
() => listDimensionItems(client, corpId, dimension.id, start, count),
|
||||
{ namespace: "dimensions", ttlMs: CACHE_TTL_MS }
|
||||
);
|
||||
}
|
||||
|
||||
export async function resolveDimension(client: KyInstance, corpId: string, target: string): Promise<{ dimension: DimensionCatalog; items: DimensionItem[] } | undefined> {
|
||||
export async function resolveDimension(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string
|
||||
): Promise<{ dimension: DimensionCatalog; items: DimensionItem[] } | undefined> {
|
||||
const matches = await searchDimensions(client, corpId, { id: target, code: target, name: target });
|
||||
const dimension = matches[0];
|
||||
if (!dimension) return undefined;
|
||||
@@ -46,7 +62,11 @@ export const dimensionTools = [
|
||||
handler: async ({ corpContext }: any, params: { keyword?: string; count?: number }) => {
|
||||
const corp = corpContext.getCurrent();
|
||||
if (!corp) throw new Error("未配置活跃企业上下文");
|
||||
const items = await searchDimensions(await import("../../core/auth/ekb.js").then((m) => m.createEkbClient(corp)), corp.corpId || corp.id, { name: params.keyword });
|
||||
const items = await searchDimensions(
|
||||
await import("../../core/auth/ekb.js").then((m) => m.createEkbClient(corp)),
|
||||
corp.corpId || corp.id,
|
||||
{ name: params.keyword }
|
||||
);
|
||||
return { count: items.length, dimensions: items.slice(0, params.count ?? 100) };
|
||||
},
|
||||
},
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
# FeeType (费用类型) 域说明
|
||||
|
||||
费用类型域负责合思/易快报企业费用类型的全生命周期管理,涵盖:
|
||||
- 费用类型树与平铺目录查询(活跃 / 包含停用)
|
||||
- 费用类型增删查改(新建、属性修改、软停用、级联启用、移动层级)
|
||||
- 费用类型表单字段规格解析(报账字段与申请字段元数据)
|
||||
|
||||
## 架构职责
|
||||
|
||||
```text
|
||||
CLI (feetype.ts) / MCP (feetypeTools in server.ts)
|
||||
│
|
||||
▼
|
||||
domains/feetype/tools.ts (业务编排:树展开、路径计算、字段规格继承、增删查改封装)
|
||||
│
|
||||
▼
|
||||
domains/feetype/api.ts (HTTP 传输层:直连 /api/v1/form/feeTypes 与 /api/form/v2/specifications)
|
||||
│
|
||||
▼
|
||||
core/auth/ekb.ts (企业身份认证与凭证管理)
|
||||
```
|
||||
|
||||
## 接口路由映射
|
||||
|
||||
| 操作 | HTTP 方法与路径 | 说明 |
|
||||
|---|---|---|
|
||||
| 获取活跃树 | `GET /api/v1/form/feeTypes/tree/active` | 获取用户端可见的活跃费用类型树 |
|
||||
| 获取全量树 | `GET /api/v1/form/feeTypes/tree` | 包含已停用的全量费用类型树 |
|
||||
| 获取单项详情 | `GET /api/v1/form/feeTypes/$id` | 精准获取持久化配置 |
|
||||
| 获取表单规格 | `GET /api/form/v2/specifications/feeType/[id]` | 获取报账与申请字段定义 |
|
||||
| 获取默认模板 | `GET /api/form/v2/specifications/default/$type` | 获取 expense / requisition 预置字段 |
|
||||
| 新建费用类型 | `POST /api/v1/form/feeTypes` | 批量/单个创建,支持字段规则继承 |
|
||||
| 更新费用类型 | `PUT /api/v1/form/feeTypes/$id` | 更新名称、编码、英文名、图标、颜色 |
|
||||
| 停用费用类型 | `PUT /api/v1/form/feeTypes/[ids]/disable` | 软删除停用 |
|
||||
| 启用费用类型 | `PUT /api/v1/form/feeTypes/$id/restore` | 重新启用(可级联) |
|
||||
| 移动父级节点 | `PUT /api/v1/form/feeTypes/[ids]/parent` | 调整层级关系 |
|
||||
|
||||
## CLI 命令速查
|
||||
|
||||
```bash
|
||||
# 查看费用类型树
|
||||
hose-use feetype list
|
||||
hose-use feetype list --all
|
||||
hose-use feetype list --keyword="差旅"
|
||||
hose-use feetype list --flat
|
||||
|
||||
# 查看单个费用类型详情
|
||||
hose-use feetype get 交通费
|
||||
hose-use feetype get 交通费 --specs
|
||||
|
||||
# 创建费用类型
|
||||
hose-use feetype create --name="办公杂费"
|
||||
hose-use feetype create --name="市内打车" --parent="交通费"
|
||||
|
||||
# 修改费用类型
|
||||
hose-use feetype update 市内打车 --desc="滴滴企业版"
|
||||
|
||||
# 停用与启用
|
||||
hose-use feetype disable 市内打车
|
||||
hose-use feetype enable 市内打车
|
||||
|
||||
# 移动层级
|
||||
hose-use feetype move 市内打车 --parent="差旅费用"
|
||||
hose-use feetype move 市内打车 --parent=root
|
||||
|
||||
# 查看表单字段配置
|
||||
hose-use feetype fields 交通费
|
||||
```
|
||||
@@ -0,0 +1,294 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import {
|
||||
FeeTypeDetailResponseSchema,
|
||||
FeeTypeSpecificationResponseSchema,
|
||||
FeeTypeTreeResponseSchema,
|
||||
FeeTypeCreateResultSchema,
|
||||
DefaultSpecResponseSchema,
|
||||
FeeTypeNode,
|
||||
FeeTypeItem,
|
||||
FeeTypeSpecificationItem,
|
||||
FeeTypeCreateResult,
|
||||
FeeTypeComponent,
|
||||
} from "./types.js";
|
||||
import { BusinessError } from "../../core/errors.js";
|
||||
|
||||
/**
|
||||
* 获取活跃费用类型树 (GET api/v1/form/feeTypes/tree/active)
|
||||
*/
|
||||
export async function getActiveFeeTypeTree(
|
||||
client: KyInstance,
|
||||
corpId: string
|
||||
): Promise<FeeTypeNode[]> {
|
||||
try {
|
||||
const raw = await client
|
||||
.get("api/v1/form/feeTypes/tree/active", {
|
||||
searchParams: { corpId },
|
||||
})
|
||||
.json();
|
||||
const parsed = FeeTypeTreeResponseSchema.safeParse(raw);
|
||||
if (parsed.success) return parsed.data.items;
|
||||
if (Array.isArray(raw)) {
|
||||
return raw.filter((item): item is FeeTypeNode => Boolean(item && typeof item === "object"));
|
||||
}
|
||||
return [];
|
||||
} catch (err: any) {
|
||||
throw new BusinessError(
|
||||
`获取活跃费用类型树失败: ${err.message || String(err)}`,
|
||||
"GET_ACTIVE_FEETYPE_FAILED"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取全量费用类型树 (含已停用) (GET api/v1/form/feeTypes/tree)
|
||||
*/
|
||||
export async function getFullFeeTypeTree(
|
||||
client: KyInstance,
|
||||
corpId: string
|
||||
): Promise<FeeTypeNode[]> {
|
||||
try {
|
||||
const raw = await client
|
||||
.get("api/v1/form/feeTypes/tree", {
|
||||
searchParams: {
|
||||
corpId,
|
||||
join: "id,feetypeTemplate,/form/v2/specifications/feeType",
|
||||
join$2: "children.id,feetypeTemplate,/form/v2/specifications/feeType",
|
||||
},
|
||||
})
|
||||
.json();
|
||||
const parsed = FeeTypeTreeResponseSchema.safeParse(raw);
|
||||
if (parsed.success) return parsed.data.items;
|
||||
if (Array.isArray(raw)) {
|
||||
return raw.filter((item): item is FeeTypeNode => Boolean(item && typeof item === "object"));
|
||||
}
|
||||
return [];
|
||||
} catch (err: any) {
|
||||
throw new BusinessError(
|
||||
`获取全量费用类型树失败: ${err.message || String(err)}`,
|
||||
"GET_FULL_FEETYPE_FAILED"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取单条费用类型详情 (GET api/v1/form/feeTypes/$id)
|
||||
*/
|
||||
export async function getFeeTypeById(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
id: string
|
||||
): Promise<FeeTypeItem> {
|
||||
try {
|
||||
const raw = await client
|
||||
.get(`api/v1/form/feeTypes/$${id}`, {
|
||||
searchParams: { corpId },
|
||||
})
|
||||
.json();
|
||||
const parsed = FeeTypeDetailResponseSchema.safeParse(raw);
|
||||
if (parsed.success) return parsed.data.value;
|
||||
if (raw && typeof raw === "object" && "value" in raw) {
|
||||
return (raw as any).value as FeeTypeItem;
|
||||
}
|
||||
return raw as FeeTypeItem;
|
||||
} catch (err: any) {
|
||||
throw new BusinessError(
|
||||
`获取费用类型 [${id}] 详情失败: ${err.message || String(err)}`,
|
||||
"GET_FEETYPE_DETAIL_FAILED"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取费用类型的表单字段规格定义 (GET api/form/v2/specifications/feeType/[id])
|
||||
*/
|
||||
export async function getFeeTypeSpecification(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
id: string
|
||||
): Promise<FeeTypeSpecificationItem | undefined> {
|
||||
try {
|
||||
const raw = await client
|
||||
.get(`api/form/v2/specifications/feeType/[${id}]`, {
|
||||
searchParams: { id, corpId },
|
||||
})
|
||||
.json();
|
||||
const parsed = FeeTypeSpecificationResponseSchema.safeParse(raw);
|
||||
if (parsed.success && parsed.data.items.length > 0) {
|
||||
return parsed.data.items[0];
|
||||
}
|
||||
if (raw && typeof raw === "object" && Array.isArray((raw as any).items)) {
|
||||
return (raw as any).items[0];
|
||||
}
|
||||
return undefined;
|
||||
} catch (err: any) {
|
||||
throw new BusinessError(
|
||||
`获取费用类型 [${id}] 字段规格失败: ${err.message || String(err)}`,
|
||||
"GET_FEETYPE_SPEC_FAILED"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取默认报账字段模板 (GET api/form/v2/specifications/default/$feeType_expense)
|
||||
*/
|
||||
export async function getDefaultExpenseSpec(
|
||||
client: KyInstance,
|
||||
corpId: string
|
||||
): Promise<FeeTypeComponent[]> {
|
||||
try {
|
||||
const raw = await client
|
||||
.get("api/form/v2/specifications/default/$feeType_expense", {
|
||||
searchParams: { type: "feeType_expense", corpId },
|
||||
})
|
||||
.json();
|
||||
const parsed = DefaultSpecResponseSchema.safeParse(raw);
|
||||
return parsed.success ? (parsed.data.components ?? []) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取默认申请字段模板 (GET api/form/v2/specifications/default/$feeType_requisition)
|
||||
*/
|
||||
export async function getDefaultRequisitionSpec(
|
||||
client: KyInstance,
|
||||
corpId: string
|
||||
): Promise<FeeTypeComponent[]> {
|
||||
try {
|
||||
const raw = await client
|
||||
.get("api/form/v2/specifications/default/$feeType_requisition", {
|
||||
searchParams: { type: "feeType_requisition", corpId },
|
||||
})
|
||||
.json();
|
||||
const parsed = DefaultSpecResponseSchema.safeParse(raw);
|
||||
return parsed.success ? (parsed.data.components ?? []) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量创建费用类型 (POST api/v1/form/feeTypes)
|
||||
*/
|
||||
export async function createFeeTypes(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
items: Record<string, unknown>[]
|
||||
): Promise<FeeTypeCreateResult> {
|
||||
try {
|
||||
const raw = await client
|
||||
.post("api/v1/form/feeTypes", {
|
||||
searchParams: { corpId },
|
||||
json: { data: items },
|
||||
})
|
||||
.json();
|
||||
const parsed = FeeTypeCreateResultSchema.safeParse(raw);
|
||||
if (parsed.success) return parsed.data;
|
||||
return raw as FeeTypeCreateResult;
|
||||
} catch (err: any) {
|
||||
throw new BusinessError(
|
||||
`创建费用类型失败: ${err.message || String(err)}`,
|
||||
"CREATE_FEETYPE_FAILED"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新费用类型基本信息 (PUT api/v1/form/feeTypes/$id)
|
||||
*/
|
||||
export async function updateFeeType(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
id: string,
|
||||
body: Record<string, unknown>
|
||||
): Promise<FeeTypeItem> {
|
||||
try {
|
||||
const raw = await client
|
||||
.put(`api/v1/form/feeTypes/$${id}`, {
|
||||
searchParams: { corpId },
|
||||
json: body,
|
||||
})
|
||||
.json();
|
||||
const parsed = FeeTypeDetailResponseSchema.safeParse(raw);
|
||||
if (parsed.success) return parsed.data.value;
|
||||
if (raw && typeof raw === "object" && "value" in raw) {
|
||||
return (raw as any).value as FeeTypeItem;
|
||||
}
|
||||
return raw as FeeTypeItem;
|
||||
} catch (err: any) {
|
||||
throw new BusinessError(
|
||||
`更新费用类型 [${id}] 失败: ${err.message || String(err)}`,
|
||||
"UPDATE_FEETYPE_FAILED"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量停用费用类型 (PUT api/v1/form/feeTypes/[ids]/disable)
|
||||
*/
|
||||
export async function disableFeeTypes(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
ids: string[]
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const idsParam = `[${ids.join(",")}]`;
|
||||
const res = await client.put(`api/v1/form/feeTypes/${idsParam}/disable`, {
|
||||
searchParams: { corpId },
|
||||
});
|
||||
return res.status === 200 || res.status === 204;
|
||||
} catch (err: any) {
|
||||
throw new BusinessError(
|
||||
`停用费用类型 [${ids.join(", ")}] 失败: ${err.message || String(err)}`,
|
||||
"DISABLE_FEETYPE_FAILED"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 启用已停用的费用类型 (PUT api/v1/form/feeTypes/$id/restore)
|
||||
*/
|
||||
export async function restoreFeeType(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
id: string,
|
||||
recursive = true
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const res = await client.put(`api/v1/form/feeTypes/$${id}/restore`, {
|
||||
searchParams: { corpId, recursive: String(recursive) },
|
||||
});
|
||||
return res.status === 200 || res.status === 204;
|
||||
} catch (err: any) {
|
||||
throw new BusinessError(
|
||||
`启用费用类型 [${id}] 失败: ${err.message || String(err)}`,
|
||||
"RESTORE_FEETYPE_FAILED"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 移动费用类型父级 (PUT api/v1/form/feeTypes/[ids]/parent)
|
||||
*/
|
||||
export async function moveFeeTypes(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
ids: string[],
|
||||
parentId: string
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const idsParam = `[${ids.join(",")}]`;
|
||||
const res = await client.put(`api/v1/form/feeTypes/${idsParam}/parent`, {
|
||||
searchParams: { corpId },
|
||||
json: { parentId: parentId || "" },
|
||||
});
|
||||
return res.status === 200 || res.status === 204;
|
||||
} catch (err: any) {
|
||||
throw new BusinessError(
|
||||
`移动费用类型 [${ids.join(", ")}] 失败: ${err.message || String(err)}`,
|
||||
"MOVE_FEETYPE_FAILED"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { describe, it, expect } from "bun:test";
|
||||
import { flattenFeeTypeTree } from "./tools.js";
|
||||
import { FeeTypeNode } from "./types.js";
|
||||
|
||||
describe("domains/feetype > tools & helpers", () => {
|
||||
const sampleTree = [
|
||||
{
|
||||
feeType: {
|
||||
id: "node_1",
|
||||
name: "差旅费",
|
||||
code: "COST01",
|
||||
active: true,
|
||||
parentId: "",
|
||||
},
|
||||
children: [
|
||||
{
|
||||
feeType: {
|
||||
id: "node_1_1",
|
||||
name: "机票",
|
||||
code: "COST01_1",
|
||||
active: true,
|
||||
parentId: "node_1",
|
||||
},
|
||||
children: [
|
||||
{
|
||||
feeType: {
|
||||
id: "node_1_1_1",
|
||||
name: "退改签",
|
||||
code: "COST01_1_1",
|
||||
active: true,
|
||||
parentId: "node_1_1",
|
||||
},
|
||||
children: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
feeType: {
|
||||
id: "node_2",
|
||||
name: "办公费",
|
||||
code: "COST02",
|
||||
active: false,
|
||||
parentId: "",
|
||||
},
|
||||
children: [],
|
||||
},
|
||||
] as unknown as FeeTypeNode[];
|
||||
|
||||
it("flattenFeeTypeTree 正确递归展开全路径与父级关系", () => {
|
||||
const flat = flattenFeeTypeTree(sampleTree);
|
||||
expect(flat.length).toBe(4);
|
||||
|
||||
expect(flat[0].name).toBe("差旅费");
|
||||
expect(flat[0].path).toBe("差旅费");
|
||||
expect(flat[0].childrenCount).toBe(1);
|
||||
|
||||
expect(flat[1].name).toBe("机票");
|
||||
expect(flat[1].path).toBe("差旅费 / 机票");
|
||||
expect(flat[1].parentName).toBe("差旅费");
|
||||
expect(flat[1].childrenCount).toBe(1);
|
||||
|
||||
expect(flat[2].name).toBe("退改签");
|
||||
expect(flat[2].path).toBe("差旅费 / 机票 / 退改签");
|
||||
expect(flat[2].parentName).toBe("机票");
|
||||
expect(flat[2].childrenCount).toBe(0);
|
||||
|
||||
expect(flat[3].name).toBe("办公费");
|
||||
expect(flat[3].path).toBe("办公费");
|
||||
expect(flat[3].parentName).toBe("");
|
||||
expect(flat[3].active).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,548 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
FeeTypeComponent,
|
||||
FeeTypeCreateInput,
|
||||
FeeTypeItem,
|
||||
FeeTypeNode,
|
||||
FeeTypeQueryOptions,
|
||||
FeeTypeUpdateInput,
|
||||
FeeTypeView,
|
||||
} from "./types.js";
|
||||
import {
|
||||
createFeeTypes,
|
||||
disableFeeTypes,
|
||||
getActiveFeeTypeTree,
|
||||
getDefaultExpenseSpec,
|
||||
getDefaultRequisitionSpec,
|
||||
getFeeTypeById,
|
||||
getFeeTypeSpecification,
|
||||
getFullFeeTypeTree,
|
||||
moveFeeTypes,
|
||||
restoreFeeType,
|
||||
updateFeeType,
|
||||
} from "./api.js";
|
||||
import { BusinessError } from "../../core/errors.js";
|
||||
|
||||
// ── 树遍历与平铺辅助 ─────────────────────────────────────────────────────────
|
||||
|
||||
export interface FlatFeeTypeItem extends FeeTypeItem {
|
||||
path: string;
|
||||
parentName: string;
|
||||
childrenCount: number;
|
||||
}
|
||||
|
||||
export function flattenFeeTypeTree(
|
||||
nodes: FeeTypeNode[],
|
||||
parentPath = "",
|
||||
parentName = ""
|
||||
): FlatFeeTypeItem[] {
|
||||
const result: FlatFeeTypeItem[] = [];
|
||||
|
||||
for (const node of nodes) {
|
||||
const item = node.feeType;
|
||||
if (!item || !item.id) continue;
|
||||
|
||||
const currentPath = parentPath ? `${parentPath} / ${item.name}` : item.name;
|
||||
const children = Array.isArray(node.children) ? node.children : [];
|
||||
|
||||
result.push({
|
||||
...item,
|
||||
path: currentPath,
|
||||
parentName,
|
||||
childrenCount: children.length,
|
||||
});
|
||||
|
||||
if (children.length > 0) {
|
||||
result.push(...flattenFeeTypeTree(children, currentPath, item.name));
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理组件字段 (参照易快报前端规范:删除内部状态与只读引用)
|
||||
*/
|
||||
function cleanComponents(list: FeeTypeComponent[]): Record<string, unknown>[] {
|
||||
return list.map((item) => {
|
||||
const copy = { ...item } as Record<string, unknown>;
|
||||
delete copy.id;
|
||||
delete copy.dataType;
|
||||
delete copy.showValue;
|
||||
delete copy.status;
|
||||
delete copy.entityInfo;
|
||||
delete copy.isLinkageFilter;
|
||||
return copy;
|
||||
});
|
||||
}
|
||||
|
||||
// ── 核心业务编排 ─────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* 模糊或精准解析单个费用类型节点 (支持按 ID, Code, Name 查找)
|
||||
*/
|
||||
export async function findFeeType(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string,
|
||||
options: { all?: boolean } = {}
|
||||
): Promise<FlatFeeTypeItem | undefined> {
|
||||
const clean = target.trim();
|
||||
if (!clean) return undefined;
|
||||
|
||||
const tree = options.all
|
||||
? await getFullFeeTypeTree(client, corpId)
|
||||
: await getActiveFeeTypeTree(client, corpId);
|
||||
const flat = flattenFeeTypeTree(tree);
|
||||
|
||||
// 1. 精确 ID 匹配
|
||||
const byId = flat.find((item) => item.id === clean);
|
||||
if (byId) return byId;
|
||||
|
||||
// 2. 精确 Code 匹配 (不区分大小写)
|
||||
const byCode = flat.find((item) => item.code.toLowerCase() === clean.toLowerCase());
|
||||
if (byCode) return byCode;
|
||||
|
||||
// 3. 精确 Name 匹配
|
||||
const byName = flat.find((item) => item.name === clean);
|
||||
if (byName) return byName;
|
||||
|
||||
// 4. 包含匹配 (Name / Spell / EnName)
|
||||
const byPartial = flat.find(
|
||||
(item) =>
|
||||
item.name.includes(clean) ||
|
||||
(item.enName && item.enName.toLowerCase().includes(clean.toLowerCase()))
|
||||
);
|
||||
return byPartial;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询费用类型列表 (树形或平铺)
|
||||
*/
|
||||
export async function listFeeTypes(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
options: FeeTypeQueryOptions = {}
|
||||
): Promise<{
|
||||
total: number;
|
||||
items: FlatFeeTypeItem[] | FeeTypeNode[];
|
||||
rawTree: FeeTypeNode[];
|
||||
}> {
|
||||
const rawTree = options.all
|
||||
? await getFullFeeTypeTree(client, corpId)
|
||||
: await getActiveFeeTypeTree(client, corpId);
|
||||
|
||||
let flat = flattenFeeTypeTree(rawTree);
|
||||
|
||||
if (options.keyword?.trim()) {
|
||||
const kw = options.keyword.trim().toLowerCase();
|
||||
flat = flat.filter(
|
||||
(item) =>
|
||||
item.name.toLowerCase().includes(kw) ||
|
||||
item.code.toLowerCase().includes(kw) ||
|
||||
(item.enName && item.enName.toLowerCase().includes(kw)) ||
|
||||
item.path.toLowerCase().includes(kw)
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
total: flat.length,
|
||||
items: options.flat ? flat : (options.keyword ? flat : rawTree),
|
||||
rawTree,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取费用类型详细信息 (含字段规格)
|
||||
*/
|
||||
export async function getFeeTypeDetail(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string,
|
||||
options: { includeSpecs?: boolean } = {}
|
||||
): Promise<{
|
||||
feeType: FlatFeeTypeItem;
|
||||
specifications?: {
|
||||
expenseComponents: FeeTypeComponent[];
|
||||
requisitionComponents: FeeTypeComponent[];
|
||||
};
|
||||
}> {
|
||||
const found = await findFeeType(client, corpId, target, { all: true });
|
||||
if (!found) {
|
||||
throw new BusinessError(
|
||||
`未找到匹配的费用类型: "${target}" (可尝试按编码或全称检索)`,
|
||||
"FEETYPE_NOT_FOUND"
|
||||
);
|
||||
}
|
||||
|
||||
// 获取最新的精确持久化属性
|
||||
const fresh = await getFeeTypeById(client, corpId, found.id);
|
||||
const resultItem: FlatFeeTypeItem = {
|
||||
...fresh,
|
||||
path: found.path,
|
||||
parentName: found.parentName,
|
||||
childrenCount: found.childrenCount,
|
||||
};
|
||||
|
||||
if (!options.includeSpecs) {
|
||||
return { feeType: resultItem };
|
||||
}
|
||||
|
||||
const spec = await getFeeTypeSpecification(client, corpId, found.id);
|
||||
return {
|
||||
feeType: resultItem,
|
||||
specifications: {
|
||||
expenseComponents: spec?.expenseComponents ?? [],
|
||||
requisitionComponents: spec?.requisitionComponents ?? [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建费用类型 (支持自动/指定编码、父级继承与字段规格适配)
|
||||
*/
|
||||
export async function createFeeType(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
input: FeeTypeCreateInput
|
||||
): Promise<FlatFeeTypeItem> {
|
||||
const name = input.name.trim();
|
||||
if (!name) {
|
||||
throw new BusinessError("费用类型名称不能为空", "INVALID_FEETYPE_NAME");
|
||||
}
|
||||
|
||||
let resolvedParentId = "";
|
||||
let inheritedExpenseComponents: Record<string, unknown>[] = [];
|
||||
let inheritedRequisitionComponents: Record<string, unknown>[] = [];
|
||||
|
||||
if (input.parentId?.trim()) {
|
||||
const parent = await findFeeType(client, corpId, input.parentId.trim(), { all: true });
|
||||
if (!parent) {
|
||||
throw new BusinessError(
|
||||
`指定的父级费用类型 "${input.parentId}" 不存在`,
|
||||
"PARENT_FEETYPE_NOT_FOUND"
|
||||
);
|
||||
}
|
||||
resolvedParentId = parent.id;
|
||||
// 继承父级费用类型的字段设置
|
||||
const parentSpec = await getFeeTypeSpecification(client, corpId, parent.id);
|
||||
if (parentSpec) {
|
||||
inheritedExpenseComponents = cleanComponents(parentSpec.expenseComponents ?? []);
|
||||
inheritedRequisitionComponents = cleanComponents(parentSpec.requisitionComponents ?? []);
|
||||
}
|
||||
}
|
||||
|
||||
// 若无父级或父级无规格,加载系统预置默认字段规格
|
||||
if (!inheritedExpenseComponents.length) {
|
||||
const defaultExp = await getDefaultExpenseSpec(client, corpId);
|
||||
inheritedExpenseComponents = cleanComponents(defaultExp);
|
||||
}
|
||||
if (!inheritedRequisitionComponents.length) {
|
||||
const defaultReq = await getDefaultRequisitionSpec(client, corpId);
|
||||
inheritedRequisitionComponents = cleanComponents(defaultReq);
|
||||
}
|
||||
|
||||
// 确定唯一编码
|
||||
let code = input.code?.trim();
|
||||
if (!code) {
|
||||
const allTree = await getFullFeeTypeTree(client, corpId);
|
||||
const flat = flattenFeeTypeTree(allTree);
|
||||
const existingCodes = new Set(flat.map((item) => item.code.toUpperCase()));
|
||||
let seq = flat.length + 1;
|
||||
code = `COST${seq}`;
|
||||
while (existingCodes.has(code)) {
|
||||
seq++;
|
||||
code = `COST${seq}`;
|
||||
}
|
||||
}
|
||||
|
||||
const payloadItem = {
|
||||
type: "ALL",
|
||||
name,
|
||||
enName: input.enName?.trim() || "",
|
||||
code,
|
||||
parentId: resolvedParentId,
|
||||
description: input.description?.trim() || "",
|
||||
color: input.color || "#90caf9",
|
||||
icon: input.icon || "https://images.ekuaibao.com/feetype/sf_100.png",
|
||||
expenseComponents: input.expenseComponents?.length
|
||||
? input.expenseComponents
|
||||
: inheritedExpenseComponents,
|
||||
requisitionComponents: input.requisitionComponents?.length
|
||||
? input.requisitionComponents
|
||||
: inheritedRequisitionComponents,
|
||||
};
|
||||
|
||||
const createRes = await createFeeTypes(client, corpId, [payloadItem]);
|
||||
if (createRes.value?.errorMsgs?.length) {
|
||||
throw new BusinessError(
|
||||
`创建费用类型失败: ${createRes.value.errorMsgs.join("; ")}`,
|
||||
"CREATE_FEETYPE_REJECTED"
|
||||
);
|
||||
}
|
||||
|
||||
const newId = createRes.value?.ids?.[0];
|
||||
if (!newId) {
|
||||
throw new BusinessError("创建接口未返回新增的费用类型 ID", "CREATE_FEETYPE_NO_ID");
|
||||
}
|
||||
|
||||
const created = await getFeeTypeDetail(client, corpId, newId);
|
||||
return created.feeType;
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改费用类型属性 (名称、编码、英文名、图标、颜色、描述)
|
||||
*/
|
||||
export async function updateFeeTypeInfo(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string,
|
||||
patch: FeeTypeUpdateInput
|
||||
): Promise<FlatFeeTypeItem> {
|
||||
const found = await findFeeType(client, corpId, target, { all: true });
|
||||
if (!found) {
|
||||
throw new BusinessError(`未找到费用类型: "${target}"`, "FEETYPE_NOT_FOUND");
|
||||
}
|
||||
|
||||
const current = await getFeeTypeById(client, corpId, found.id);
|
||||
const updatedBody: Record<string, unknown> = {
|
||||
id: found.id,
|
||||
type: "FEETYPE",
|
||||
name: patch.name !== undefined ? patch.name.trim() : current.name,
|
||||
code: patch.code !== undefined ? patch.code.trim() : current.code,
|
||||
enName: patch.enName !== undefined ? patch.enName.trim() : (current.enName || ""),
|
||||
description: patch.description !== undefined ? patch.description.trim() : (current.description || ""),
|
||||
color: patch.color !== undefined ? patch.color.trim() : (current.color || "#90caf9"),
|
||||
icon: patch.icon !== undefined ? patch.icon.trim() : (current.icon || "https://images.ekuaibao.com/feetype/sf_100.png"),
|
||||
};
|
||||
|
||||
await updateFeeType(client, corpId, found.id, updatedBody);
|
||||
const fresh = await getFeeTypeDetail(client, corpId, found.id);
|
||||
return fresh.feeType;
|
||||
}
|
||||
|
||||
/**
|
||||
* 停用费用类型 (软删除)
|
||||
*/
|
||||
export async function disableFeeTypeItem(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string
|
||||
): Promise<{ success: boolean; item: FlatFeeTypeItem }> {
|
||||
const found = await findFeeType(client, corpId, target, { all: true });
|
||||
if (!found) {
|
||||
throw new BusinessError(`未找到费用类型: "${target}"`, "FEETYPE_NOT_FOUND");
|
||||
}
|
||||
|
||||
if (!found.active) {
|
||||
return { success: true, item: found };
|
||||
}
|
||||
|
||||
const ok = await disableFeeTypes(client, corpId, [found.id]);
|
||||
const fresh = await getFeeTypeDetail(client, corpId, found.id);
|
||||
return { success: ok, item: fresh.feeType };
|
||||
}
|
||||
|
||||
/**
|
||||
* 启用费用类型 (可级联恢复)
|
||||
*/
|
||||
export async function enableFeeTypeItem(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string,
|
||||
options: { recursive?: boolean } = { recursive: true }
|
||||
): Promise<{ success: boolean; item: FlatFeeTypeItem }> {
|
||||
const found = await findFeeType(client, corpId, target, { all: true });
|
||||
if (!found) {
|
||||
throw new BusinessError(`未找到费用类型: "${target}"`, "FEETYPE_NOT_FOUND");
|
||||
}
|
||||
|
||||
if (found.active) {
|
||||
return { success: true, item: found };
|
||||
}
|
||||
|
||||
const ok = await restoreFeeType(client, corpId, found.id, options.recursive ?? true);
|
||||
const fresh = await getFeeTypeDetail(client, corpId, found.id);
|
||||
return { success: ok, item: fresh.feeType };
|
||||
}
|
||||
|
||||
/**
|
||||
* 移动费用类型父级节点
|
||||
*/
|
||||
export async function moveFeeTypeItem(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string,
|
||||
parentTarget?: string
|
||||
): Promise<{ success: boolean; item: FlatFeeTypeItem; parentName: string }> {
|
||||
const found = await findFeeType(client, corpId, target, { all: true });
|
||||
if (!found) {
|
||||
throw new BusinessError(`未找到费用类型: "${target}"`, "FEETYPE_NOT_FOUND");
|
||||
}
|
||||
|
||||
let newParentId = "";
|
||||
let newParentName = "根节点 (顶级)";
|
||||
|
||||
if (parentTarget && parentTarget !== "root" && parentTarget !== "0") {
|
||||
const parent = await findFeeType(client, corpId, parentTarget, { all: true });
|
||||
if (!parent) {
|
||||
throw new BusinessError(
|
||||
`目标父级费用类型 "${parentTarget}" 不存在`,
|
||||
"PARENT_FEETYPE_NOT_FOUND"
|
||||
);
|
||||
}
|
||||
if (parent.id === found.id) {
|
||||
throw new BusinessError("不能将费用类型移动到其自身之下", "INVALID_MOVE_TARGET");
|
||||
}
|
||||
newParentId = parent.id;
|
||||
newParentName = parent.name;
|
||||
}
|
||||
|
||||
const ok = await moveFeeTypes(client, corpId, [found.id], newParentId);
|
||||
const fresh = await getFeeTypeDetail(client, corpId, found.id);
|
||||
return { success: ok, item: fresh.feeType, parentName: newParentName };
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取费用类型的表单字段明细清单 (报账与申请字段)
|
||||
*/
|
||||
export async function getFeeTypeFieldsList(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string
|
||||
): Promise<{
|
||||
feeType: FlatFeeTypeItem;
|
||||
expenseFields: {
|
||||
field: string;
|
||||
label: string;
|
||||
type: string;
|
||||
required: boolean;
|
||||
editable: boolean;
|
||||
hidden: boolean;
|
||||
}[];
|
||||
requisitionFields: {
|
||||
field: string;
|
||||
label: string;
|
||||
type: string;
|
||||
required: boolean;
|
||||
editable: boolean;
|
||||
hidden: boolean;
|
||||
}[];
|
||||
}> {
|
||||
const detail = await getFeeTypeDetail(client, corpId, target, { includeSpecs: true });
|
||||
|
||||
const mapComponent = (c: FeeTypeComponent) => ({
|
||||
field: c.field || "-",
|
||||
label: c.cnLabel || c.label || "-",
|
||||
type: c.type || "text",
|
||||
required: !c.optional,
|
||||
editable: c.editable !== false,
|
||||
hidden: Boolean(c.hide),
|
||||
});
|
||||
|
||||
return {
|
||||
feeType: detail.feeType,
|
||||
expenseFields: (detail.specifications?.expenseComponents ?? []).map(mapComponent),
|
||||
requisitionFields: (detail.specifications?.requisitionComponents ?? []).map(mapComponent),
|
||||
};
|
||||
}
|
||||
|
||||
// ── MCP Tool Definitions ─────────────────────────────────────────────────────
|
||||
|
||||
export const feetypeTools = [
|
||||
{
|
||||
name: "feetype_list",
|
||||
description: "查询企业费用类型树或平铺列表 (可按关键词筛选、包含已停用)",
|
||||
parameters: z.object({
|
||||
corpId: z.string().describe("企业 ID"),
|
||||
keyword: z.string().optional().describe("搜索关键词 (名称/编码/全路径)"),
|
||||
all: z.boolean().optional().default(false).describe("是否包含已停用的费用类型"),
|
||||
flat: z.boolean().optional().default(false).describe("是否以平铺列表格式返回"),
|
||||
}),
|
||||
handler: async (client: KyInstance, args: any) => {
|
||||
return listFeeTypes(client, args.corpId, {
|
||||
keyword: args.keyword,
|
||||
all: args.all,
|
||||
flat: args.flat,
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "feetype_get",
|
||||
description: "获取单个费用类型的详细配置与字段规格",
|
||||
parameters: z.object({
|
||||
corpId: z.string().describe("企业 ID"),
|
||||
target: z.string().describe("费用类型 ID、编码或名称"),
|
||||
includeSpecs: z.boolean().optional().default(false).describe("是否包含报账与申请字段规格定义"),
|
||||
}),
|
||||
handler: async (client: KyInstance, args: any) => {
|
||||
return getFeeTypeDetail(client, args.corpId, args.target, {
|
||||
includeSpecs: args.includeSpecs,
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "feetype_create",
|
||||
description: "新建费用类型 (支持指定父级节点、编码自增与继承字段规则)",
|
||||
parameters: z.object({
|
||||
corpId: z.string().describe("企业 ID"),
|
||||
name: z.string().describe("费用类型名称"),
|
||||
code: z.string().optional().describe("费用编码 (不提供则系统自增生成)"),
|
||||
parentId: z.string().optional().describe("父级费用类型 ID、编码或名称 (不提供则建为顶级)"),
|
||||
enName: z.string().optional().describe("英文名称"),
|
||||
description: z.string().optional().describe("描述信息"),
|
||||
color: z.string().optional().describe("标识颜色 (如 #90caf9)"),
|
||||
}),
|
||||
handler: async (client: KyInstance, args: any) => {
|
||||
return createFeeType(client, args.corpId, args);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "feetype_update",
|
||||
description: "修改费用类型属性 (名称、编码、英文名、颜色、图标或描述)",
|
||||
parameters: z.object({
|
||||
corpId: z.string().describe("企业 ID"),
|
||||
target: z.string().describe("费用类型 ID、编码或名称"),
|
||||
name: z.string().optional().describe("新名称"),
|
||||
code: z.string().optional().describe("新编码"),
|
||||
enName: z.string().optional().describe("新英文名"),
|
||||
description: z.string().optional().describe("新描述"),
|
||||
color: z.string().optional().describe("新颜色"),
|
||||
}),
|
||||
handler: async (client: KyInstance, args: any) => {
|
||||
return updateFeeTypeInfo(client, args.corpId, args.target, args);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "feetype_toggle",
|
||||
description: "停用或启用费用类型",
|
||||
parameters: z.object({
|
||||
corpId: z.string().describe("企业 ID"),
|
||||
target: z.string().describe("费用类型 ID、编码或名称"),
|
||||
action: z.enum(["disable", "enable"]).describe("执行动作: disable 停用, enable 启用"),
|
||||
recursive: z.boolean().optional().default(true).describe("启用时是否递归启用子节点"),
|
||||
}),
|
||||
handler: async (client: KyInstance, args: any) => {
|
||||
if (args.action === "disable") {
|
||||
return disableFeeTypeItem(client, args.corpId, args.target);
|
||||
} else {
|
||||
return enableFeeTypeItem(client, args.corpId, args.target, {
|
||||
recursive: args.recursive,
|
||||
});
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "feetype_move",
|
||||
description: "移动费用类型至新的父级节点 (传入 root 移至根目录)",
|
||||
parameters: z.object({
|
||||
corpId: z.string().describe("企业 ID"),
|
||||
target: z.string().describe("待移动的费用类型 ID、编码或名称"),
|
||||
parent: z.string().describe("目标父级费用类型 ID、编码或名称 (传入 'root' 为移至顶级)"),
|
||||
}),
|
||||
handler: async (client: KyInstance, args: any) => {
|
||||
return moveFeeTypeItem(client, args.corpId, args.target, args.parent);
|
||||
},
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,169 @@
|
||||
import { z } from "zod";
|
||||
|
||||
// ── 费用类型基础实体 ─────────────────────────────────────────────────────────
|
||||
|
||||
export const FeeTypeItemSchema = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
code: z.string(),
|
||||
enName: z.string().nullish().default(""),
|
||||
parentId: z.string().nullish().default(""),
|
||||
active: z.boolean().default(true),
|
||||
order: z.number().nullish().default(1000000),
|
||||
color: z.string().nullish().default("#90caf9"),
|
||||
icon: z.string().nullish().default(""),
|
||||
description: z.string().nullish().default(""),
|
||||
corporationId: z.string().optional(),
|
||||
expenseSpecificationId: z.string().nullish(),
|
||||
requisitionSpecificationId: z.string().nullish(),
|
||||
receiptSpecificationId: z.string().nullish(),
|
||||
showPoint: z.boolean().nullish().default(false),
|
||||
createTime: z.number().nullish(),
|
||||
updateTime: z.number().nullish(),
|
||||
permissions: z
|
||||
.array(
|
||||
z.object({
|
||||
name: z.string(),
|
||||
auth: z.boolean(),
|
||||
})
|
||||
)
|
||||
.nullish()
|
||||
.default([]),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export type FeeTypeItem = z.infer<typeof FeeTypeItemSchema>;
|
||||
|
||||
// ── 树节点模型 ─────────────────────────────────────────────────────────────
|
||||
|
||||
export interface FeeTypeNode {
|
||||
feeType: FeeTypeItem;
|
||||
children: FeeTypeNode[];
|
||||
}
|
||||
|
||||
export const FeeTypeNodeSchema: z.ZodType<FeeTypeNode> = z.lazy(() =>
|
||||
z.object({
|
||||
feeType: FeeTypeItemSchema,
|
||||
children: z.array(FeeTypeNodeSchema).default([]),
|
||||
})
|
||||
);
|
||||
|
||||
export const FeeTypeTreeResponseSchema = z.object({
|
||||
items: z.array(FeeTypeNodeSchema).default([]),
|
||||
});
|
||||
|
||||
export type FeeTypeTreeResponse = z.infer<typeof FeeTypeTreeResponseSchema>;
|
||||
|
||||
export const FeeTypeDetailResponseSchema = z.object({
|
||||
value: FeeTypeItemSchema,
|
||||
});
|
||||
|
||||
export type FeeTypeDetailResponse = z.infer<typeof FeeTypeDetailResponseSchema>;
|
||||
|
||||
export const FeeTypeCreateResultSchema = z.object({
|
||||
value: z
|
||||
.object({
|
||||
ids: z.array(z.string()).default([]),
|
||||
names: z.record(z.string(), z.string()).optional(),
|
||||
errorMsgs: z.array(z.string()).nullish().default([]),
|
||||
})
|
||||
.default({ ids: [], errorMsgs: [] }),
|
||||
});
|
||||
|
||||
export type FeeTypeCreateResult = z.infer<typeof FeeTypeCreateResultSchema>;
|
||||
|
||||
// ── 字段配置与规格模型 ───────────────────────────────────────────────────────
|
||||
|
||||
export const FeeTypeComponentSchema = z
|
||||
.object({
|
||||
field: z.string().optional(),
|
||||
label: z.string().optional(),
|
||||
cnLabel: z.string().nullish(),
|
||||
enLabel: z.string().nullish(),
|
||||
type: z.string().optional(),
|
||||
placeholder: z.string().nullish(),
|
||||
readonly: z.boolean().nullish().default(false),
|
||||
editable: z.boolean().nullish().default(true),
|
||||
optional: z.boolean().nullish().default(true),
|
||||
hide: z.boolean().nullish().default(false),
|
||||
showInDetails: z.boolean().nullish().default(false),
|
||||
defaultField: z.boolean().nullish().default(false),
|
||||
defaultValue: z.record(z.string(), z.any()).nullish(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export type FeeTypeComponent = z.infer<typeof FeeTypeComponentSchema>;
|
||||
|
||||
export const FeeTypeSpecificationItemSchema = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
expenseComponents: z.array(FeeTypeComponentSchema).nullish().default([]),
|
||||
requisitionComponents: z.array(FeeTypeComponentSchema).nullish().default([]),
|
||||
receiptComponents: z.array(FeeTypeComponentSchema).nullish().default([]),
|
||||
expenseRules: z.array(z.any()).nullish().default([]),
|
||||
requisitionRules: z.array(z.any()).nullish().default([]),
|
||||
receiptRules: z.array(z.any()).nullish().default([]),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export type FeeTypeSpecificationItem = z.infer<typeof FeeTypeSpecificationItemSchema>;
|
||||
|
||||
export const FeeTypeSpecificationResponseSchema = z.object({
|
||||
items: z.array(FeeTypeSpecificationItemSchema).default([]),
|
||||
});
|
||||
|
||||
export type FeeTypeSpecificationResponse = z.infer<typeof FeeTypeSpecificationResponseSchema>;
|
||||
|
||||
export const DefaultSpecResponseSchema = z
|
||||
.object({
|
||||
components: z.array(FeeTypeComponentSchema).nullish().default([]),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export type DefaultSpecResponse = z.infer<typeof DefaultSpecResponseSchema>;
|
||||
|
||||
// ── 业务输入参数 ────────────────────────────────────────────────────────────
|
||||
|
||||
export interface FeeTypeCreateInput {
|
||||
name: string;
|
||||
code?: string;
|
||||
enName?: string;
|
||||
parentId?: string;
|
||||
description?: string;
|
||||
color?: string;
|
||||
icon?: string;
|
||||
expenseComponents?: Record<string, unknown>[];
|
||||
requisitionComponents?: Record<string, unknown>[];
|
||||
}
|
||||
|
||||
export interface FeeTypeUpdateInput {
|
||||
name?: string;
|
||||
code?: string;
|
||||
enName?: string;
|
||||
description?: string;
|
||||
color?: string;
|
||||
icon?: string;
|
||||
order?: number;
|
||||
}
|
||||
|
||||
export interface FeeTypeQueryOptions {
|
||||
all?: boolean;
|
||||
keyword?: string;
|
||||
flat?: boolean;
|
||||
}
|
||||
|
||||
export interface FeeTypeView {
|
||||
id: string;
|
||||
name: string;
|
||||
code: string;
|
||||
enName: string;
|
||||
active: boolean;
|
||||
parentId: string;
|
||||
parentName?: string;
|
||||
path: string;
|
||||
description: string;
|
||||
color: string;
|
||||
icon: string;
|
||||
childrenCount: number;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
# Menu 域说明(桌面端主框架菜单与工作台业务应用)
|
||||
|
||||
Menu 域负责获取合思桌面端全站主框架导航菜单树(`MAIN_FRAME_DESKTOP`)以及业务工作台【应用管理】下的业务应用集成列表。
|
||||
|
||||
## 业务背景
|
||||
|
||||
在合思产品体系中:
|
||||
1. **应用中心 -> 自建应用**(由 `platform` / `datalink` 域负责):属于开发者与 PaaS 容器层(`groupType: NORMAL`),主要用于自定义实体建模和脚本工作流;
|
||||
2. **顶层一级导航【应用管理】**(由本 `menu` 域负责):属于用户业务工作台层,聚合了租户开通的**全部前台业务落地应用**,既包括挂载了对象视图的自建应用(如新转转集团、差旅申请、项目预算),也包含官方业务套件(如用车补贴 `SCGY:...`、用车制度)与金融扩展(如 E商卡管理)。
|
||||
|
||||
## 核心接口
|
||||
|
||||
| 接口 | 方法 | 说明 |
|
||||
|---|---|---|
|
||||
| `api/menu/v2/menus/byDeviceTypeAndAppId/$MAIN_FRAME_DESKTOP` | `GET` | 获取桌面端全站主框架导航菜单树 |
|
||||
|
||||
## 代码结构
|
||||
|
||||
```text
|
||||
src/domains/menu/
|
||||
├── types.ts # 菜单树节点与 WorkbenchApp 视图模型
|
||||
├── api.ts # HTTP 传输层
|
||||
└── tools.ts # 服务层聚合函数与导出
|
||||
```
|
||||
|
||||
## CLI 对应命令
|
||||
|
||||
```bash
|
||||
# 查看顶层【应用管理】下的业务应用列表
|
||||
hose-use app list [--corp=<id>]
|
||||
|
||||
# 查看桌面端主框架菜单树
|
||||
hose-use menu tree [--corp=<id>]
|
||||
```
|
||||
@@ -0,0 +1,125 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import {
|
||||
fetchDesktopMenuTree,
|
||||
fetchWorkbenchApps,
|
||||
fetchAppCenterMenus,
|
||||
} from "./api.js";
|
||||
|
||||
const mockMenuPayload = {
|
||||
items: [
|
||||
{
|
||||
id: "newHomePage",
|
||||
label: "首页",
|
||||
appId: "100-home",
|
||||
href: "/home",
|
||||
children: [],
|
||||
},
|
||||
{
|
||||
id: "dataLink",
|
||||
label: "应用管理",
|
||||
appId: "160-datalink-platform",
|
||||
children: [
|
||||
{
|
||||
id: "SCGY:corp-test",
|
||||
label: "用车补贴",
|
||||
code: "dataLinkItem",
|
||||
href: "/third-party-item/SCGY:corp-test",
|
||||
appId: "160-datalink-platform",
|
||||
type: "MENU",
|
||||
fromWay: "SYSTEM",
|
||||
},
|
||||
{
|
||||
id: "ID01PIqCA1Di0v",
|
||||
label: "用车制度",
|
||||
code: "dataLinkItem",
|
||||
href: "/third-party-item/ID01PIqCA1Di0v",
|
||||
appId: "160-datalink-platform",
|
||||
type: "MENU",
|
||||
fromWay: "SYSTEM",
|
||||
},
|
||||
{
|
||||
id: "ID01RKbEvQsWbd",
|
||||
label: "新转转集团",
|
||||
code: "dataLinkItem",
|
||||
href: "/third-party-item/ID01RKbEvQsWbd",
|
||||
appId: "160-datalink-platform",
|
||||
type: "MENU",
|
||||
fromWay: "SYSTEM",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "appcenter",
|
||||
label: "应用中心",
|
||||
appId: "150-appcenter",
|
||||
children: [
|
||||
{
|
||||
id: "selfBuiltApplication",
|
||||
label: "自建应用",
|
||||
code: "selfBuiltApplication",
|
||||
href: "/expense-center-new/self_built_app",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
describe("Domains/Menu - API 单元测试", () => {
|
||||
test("fetchDesktopMenuTree 成功解析全站桌面端菜单响应", async () => {
|
||||
const mockClient = {
|
||||
get: async (url: string, opts: any) => {
|
||||
expect(url).toBe("api/menu/v2/menus/byDeviceTypeAndAppId/$MAIN_FRAME_DESKTOP");
|
||||
expect(opts.searchParams.corpId).toBe("corp-test");
|
||||
return {
|
||||
json: async () => mockMenuPayload,
|
||||
};
|
||||
},
|
||||
} as any;
|
||||
|
||||
const items = await fetchDesktopMenuTree(mockClient, "corp-test");
|
||||
expect(items.length).toBe(3);
|
||||
expect(items[0].label).toBe("首页");
|
||||
expect(items[1].label).toBe("应用管理");
|
||||
expect(items[2].label).toBe("应用中心");
|
||||
});
|
||||
|
||||
test("fetchWorkbenchApps 成功提取应用管理下的 7/N 个业务应用", async () => {
|
||||
const mockClient = {
|
||||
get: async () => ({
|
||||
json: async () => mockMenuPayload,
|
||||
}),
|
||||
} as any;
|
||||
|
||||
const apps = await fetchWorkbenchApps(mockClient, "corp-test");
|
||||
expect(apps.length).toBe(3);
|
||||
expect(apps[0].id).toBe("SCGY:corp-test");
|
||||
expect(apps[0].name).toBe("用车补贴");
|
||||
expect(apps[0].href).toBe("/third-party-item/SCGY:corp-test");
|
||||
expect(apps[1].name).toBe("用车制度");
|
||||
expect(apps[2].name).toBe("新转转集团");
|
||||
});
|
||||
|
||||
test("fetchAppCenterMenus 成功提取应用中心子栏目", async () => {
|
||||
const mockClient = {
|
||||
get: async () => ({
|
||||
json: async () => mockMenuPayload,
|
||||
}),
|
||||
} as any;
|
||||
|
||||
const menus = await fetchAppCenterMenus(mockClient, "corp-test");
|
||||
expect(menus.length).toBe(1);
|
||||
expect(menus[0].id).toBe("selfBuiltApplication");
|
||||
expect(menus[0].label).toBe("自建应用");
|
||||
});
|
||||
|
||||
test("当菜单树无 dataLink 节点时安全返回空数组", async () => {
|
||||
const mockClient = {
|
||||
get: async () => ({
|
||||
json: async () => ({ items: [] }),
|
||||
}),
|
||||
} as any;
|
||||
|
||||
const apps = await fetchWorkbenchApps(mockClient, "corp-test");
|
||||
expect(apps).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { DesktopMenuResponseSchema, type MenuItem, type WorkbenchApp } from "./types.js";
|
||||
|
||||
/** 获取桌面端全站主框架导航菜单树 */
|
||||
export async function fetchDesktopMenuTree(
|
||||
client: KyInstance,
|
||||
corpId: string
|
||||
): Promise<MenuItem[]> {
|
||||
const response = await client.get(
|
||||
"api/menu/v2/menus/byDeviceTypeAndAppId/$MAIN_FRAME_DESKTOP",
|
||||
{
|
||||
searchParams: { corpId },
|
||||
}
|
||||
);
|
||||
const json = await response.json();
|
||||
const parsed = DesktopMenuResponseSchema.parse(json);
|
||||
return parsed.items;
|
||||
}
|
||||
|
||||
/** 获取工作台【应用管理】下的业务应用列表(包括套件、模板与自建应用) */
|
||||
export async function fetchWorkbenchApps(
|
||||
client: KyInstance,
|
||||
corpId: string
|
||||
): Promise<WorkbenchApp[]> {
|
||||
const items = await fetchDesktopMenuTree(client, corpId);
|
||||
const dataLinkNode = items.find(
|
||||
(i) =>
|
||||
i.id === "dataLink" ||
|
||||
i.appId === "160-datalink-platform" ||
|
||||
i.label === "应用管理"
|
||||
);
|
||||
|
||||
if (!dataLinkNode || !Array.isArray(dataLinkNode.children)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return dataLinkNode.children.map((child) => ({
|
||||
id: child.id,
|
||||
name: child.label,
|
||||
code: child.code || "dataLinkItem",
|
||||
href: child.href || `/third-party-item/${child.id}`,
|
||||
appId: child.appId || "160-datalink-platform",
|
||||
type: child.type || "MENU",
|
||||
fromWay: child.fromWay || "SYSTEM",
|
||||
}));
|
||||
}
|
||||
|
||||
/** 获取【应用中心】下的子栏目菜单列表(如应用商店、已购应用、自建应用等) */
|
||||
export async function fetchAppCenterMenus(
|
||||
client: KyInstance,
|
||||
corpId: string
|
||||
): Promise<MenuItem[]> {
|
||||
const items = await fetchDesktopMenuTree(client, corpId);
|
||||
const appCenterNode = items.find(
|
||||
(i) =>
|
||||
i.id === "appcenter" ||
|
||||
i.appId === "150-appcenter" ||
|
||||
i.label === "应用中心"
|
||||
);
|
||||
|
||||
return appCenterNode?.children || [];
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import {
|
||||
fetchDesktopMenuTree,
|
||||
fetchWorkbenchApps,
|
||||
fetchAppCenterMenus,
|
||||
} from "./api.js";
|
||||
import type { MenuItem, WorkbenchApp } from "./types.js";
|
||||
|
||||
/** 获取桌面端工作台【应用管理】下的业务应用列表 */
|
||||
export async function fetchWorkbenchAppsList(
|
||||
corp: CorpConfig
|
||||
): Promise<WorkbenchApp[]> {
|
||||
const client = await createEkbClient(corp);
|
||||
const corpId = corp.corpId || corp.credentials.corpId;
|
||||
return fetchWorkbenchApps(client, corpId);
|
||||
}
|
||||
|
||||
/** 获取桌面端全站主框架导航菜单树 */
|
||||
export async function fetchDesktopMenus(
|
||||
corp: CorpConfig
|
||||
): Promise<MenuItem[]> {
|
||||
const client = await createEkbClient(corp);
|
||||
const corpId = corp.corpId || corp.credentials.corpId;
|
||||
return fetchDesktopMenuTree(client, corpId);
|
||||
}
|
||||
|
||||
/** 获取【应用中心】下的子栏目 */
|
||||
export async function fetchAppCenterSubMenus(
|
||||
corp: CorpConfig
|
||||
): Promise<MenuItem[]> {
|
||||
const client = await createEkbClient(corp);
|
||||
const corpId = corp.corpId || corp.credentials.corpId;
|
||||
return fetchAppCenterMenus(client, corpId);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export interface MenuItem {
|
||||
id: string;
|
||||
label: string;
|
||||
code?: string | null;
|
||||
href?: string | null;
|
||||
appId?: string | null;
|
||||
type?: string | null;
|
||||
fromWay?: string | null;
|
||||
icon?: string | null;
|
||||
iconFill?: string | null;
|
||||
selected?: boolean | null;
|
||||
children?: MenuItem[];
|
||||
}
|
||||
|
||||
export const MenuItemSchema: z.ZodType<MenuItem> = z.lazy(() =>
|
||||
z.object({
|
||||
id: z.string(),
|
||||
label: z.string().default(""),
|
||||
code: z.string().nullable().optional(),
|
||||
href: z.string().nullable().optional(),
|
||||
appId: z.string().nullable().optional(),
|
||||
type: z.string().nullable().optional(),
|
||||
fromWay: z.string().nullable().optional(),
|
||||
icon: z.string().nullable().optional(),
|
||||
iconFill: z.string().nullable().optional(),
|
||||
selected: z.boolean().nullable().optional(),
|
||||
children: z.array(MenuItemSchema).optional().default([]),
|
||||
})
|
||||
);
|
||||
|
||||
export const DesktopMenuResponseSchema = z.object({
|
||||
items: z.array(MenuItemSchema).default([]),
|
||||
});
|
||||
export type DesktopMenuResponse = z.infer<typeof DesktopMenuResponseSchema>;
|
||||
|
||||
export const WorkbenchAppSchema = z.object({
|
||||
id: z.string().describe("业务应用 ID (如 SCGY:corpId 或 自建应用物理ID)"),
|
||||
name: z.string().describe("应用名称"),
|
||||
code: z.string().optional().describe("功能代码 (如 dataLinkItem)"),
|
||||
href: z.string().describe("Web 端直达路由路径"),
|
||||
appId: z.string().default("160-datalink-platform").describe("所属主框架模块"),
|
||||
type: z.string().optional().describe("菜单或应用类型"),
|
||||
fromWay: z.string().optional().describe("来源方式 (如 SYSTEM, MANUAL)"),
|
||||
});
|
||||
export type WorkbenchApp = z.infer<typeof WorkbenchAppSchema>;
|
||||
@@ -1,6 +1,6 @@
|
||||
# Platform 域说明
|
||||
|
||||
Platform 域负责自建应用(DataLink Platform)和工作流(EASO/Piper)相关能力。
|
||||
Platform 域负责工作流(EASO/Piper)以及自建应用容器的兼容能力。自建应用下的业务对象、字段、记录和权限查询统一放在 [DataLink 域](../datalink/README.datalink.md)。
|
||||
|
||||
## 代码结构
|
||||
|
||||
|
||||
Loaded 100 of 113 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user