Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cf5d12b0a5 | ||
|
|
535404871c | ||
|
|
269b7e8f0f | ||
|
|
c99c5d98ec | ||
|
|
4fbd737402 | ||
|
|
40b3b29ca5 | ||
|
|
04d3dbcc02 | ||
|
|
39fb3a47f5 | ||
|
|
aa2a61d44f | ||
|
|
507bf6ab91 | ||
|
|
9ddbd0390d | ||
|
|
a2d078aafe | ||
|
|
85bbc9bbb4 | ||
|
|
e84cae7f80 | ||
|
|
2b4bf49663 | ||
|
|
06da94152d | ||
|
|
17e5418005 | ||
|
|
a5bfaafa10 | ||
|
|
84e6fa58fd | ||
|
|
f72deb01b1 | ||
|
|
acd187b616 | ||
|
|
43d923f567 | ||
|
|
e44b120cc2 | ||
|
|
7d9f656567 | ||
|
|
c14338f1bc | ||
|
|
9d351ed15d | ||
|
|
373fb11a81 | ||
|
|
2a06cf58b7 | ||
|
|
6d61ece8cd | ||
|
|
3d963e9a7e | ||
|
|
96d28da862 | ||
|
|
1d1170526b | ||
|
|
1f3334bfbd | ||
|
|
a0d13ca36a | ||
|
|
9e1a13c1fe | ||
|
|
334c72617c | ||
|
|
0514291d2d | ||
|
|
cbeeca746b | ||
|
|
7a8f2f6931 | ||
|
|
3df9201a5e | ||
|
|
60866efa2e | ||
|
|
dbf8dd942e | ||
|
|
6468710730 | ||
|
|
85d5f8f13a | ||
|
|
a8bdb67293 | ||
|
|
155f179fcd | ||
|
|
621c8cb7dc | ||
|
|
0be1365289 | ||
|
|
97abdb4f96 | ||
|
|
12247fd350 | ||
|
|
49b0359adb | ||
|
|
1ef611eeab | ||
|
|
d28b0c92d9 | ||
|
|
6c0f4dc567 | ||
|
|
8aa401ab79 | ||
|
|
a381fa2698 | ||
|
|
88e8c384a6 |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.5.2",
|
||||
"version": "0.6.1",
|
||||
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
|
||||
"author": {
|
||||
"name": "yingqing"
|
||||
|
||||
@@ -89,3 +89,38 @@ CLI (src/cli.ts) / MCP (src/server.ts)
|
||||
- 目录细节写进对应目录的 `README.{dirname}.md`
|
||||
- 文件细节写进对应文件旁的说明文档
|
||||
- 子域的 API 路径、枚举值、字段语义不要继续回填到根目录
|
||||
|
||||
## 分支管理与 PR 合并规范(严格对标 seal-use)
|
||||
|
||||
为了保证代码变更可追溯、CI 校验完备与版本安全,本仓库实施**硬性约束(通过 Git pre-push hook 与 PR 流程双重卡点)**:
|
||||
|
||||
1. **严禁直接推送到 `main` 分支**:
|
||||
- 仓库已内置 `.git/hooks/pre-push` 钩子,本地直接执行 `git push origin main` 将被直接拦截拒绝;
|
||||
- 日常功能开发、Bug 修复和版本发布必须且只能走独立分支;
|
||||
2. **分支命名规范**:
|
||||
- 特性分支:`feat/<feature-name>` 或 `codex/issue-<id>-<name>`
|
||||
- 发布分支:`codex/release-v<X.Y.Z>` 或 `release/v<X.Y.Z>`
|
||||
- 维护优化:`chore/<task-name>` 或 `fix/<issue-name>`
|
||||
3. **Pull Request 提交流程**:
|
||||
- 本地必须验证:`bun test && bun run check`(全绿方可提交);
|
||||
- 推送分支至远端:`git push origin <branch>`;
|
||||
- 发起 PR:`gh pr create --base main --head <branch> --title "..." --body "..."`(如有对应 Issue 需关联 `Fixes #...`);
|
||||
- 等待 CI 检查:`gh pr checks <pr-number> --watch`;
|
||||
- 审查通过后合入:`gh pr merge <pr-number> --merge --delete-branch`;
|
||||
4. **版本发布与 Tag 推送标准流程(严格对齐 seal-use)**:
|
||||
- PR 合并后,切回本地 `main` 分支并同步:
|
||||
```bash
|
||||
git switch main
|
||||
git pull --ff-only origin main
|
||||
git push home main
|
||||
```
|
||||
- 打 Release Tag:
|
||||
```bash
|
||||
git tag -a vX.Y.Z -m "🚀 Release summary text describing key changes"
|
||||
```
|
||||
- **推送顺序极关键**:先推 `home` (Gitea),再推 `origin` (GitHub)。最后推 GitHub 触发 Release Action:
|
||||
```bash
|
||||
git push home refs/tags/vX.Y.Z
|
||||
git push origin refs/tags/vX.Y.Z
|
||||
```
|
||||
- 监控云端 Release 构建并验证产物发布完成。
|
||||
@@ -1,4 +1,4 @@
|
||||
# hose-use (v0.5.2)
|
||||
# hose-use (v0.6.1)
|
||||
|
||||
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
|
||||
|
||||
|
||||
Vendored
+1
-1
@@ -2,7 +2,7 @@
|
||||
"openapi": "3.1.0",
|
||||
"info": {
|
||||
"title": "hose-use API & MCP Tools Specification",
|
||||
"version": "0.5.2",
|
||||
"version": "0.6.1",
|
||||
"description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."
|
||||
},
|
||||
"servers": [
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
openapi: 3.1.0
|
||||
info:
|
||||
title: hose-use API & MCP Tools Specification
|
||||
version: 0.5.2
|
||||
version: 0.6.1
|
||||
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.5.2",
|
||||
"version": "0.6.1",
|
||||
"module": "src/server.ts",
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
---
|
||||
name: hose-use
|
||||
description: "v0.5.1: 合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号 API 登录、租户切换、单据费用检索与下钻、工作流跨域扫描、内置 HTTP 交互文档与常驻守护进程。"
|
||||
description: "v0.6.0: 合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号 API 登录、租户切换、单据检索与审批动作、工作流跨域扫描、内置 HTTP 交互文档与常驻守护进程。"
|
||||
metadata:
|
||||
version: 0.5.1
|
||||
short-description: 合思/易快报企业级 CLI 工具与底层 SDK (v0.5.1)
|
||||
version: 0.6.0
|
||||
short-description: 合思/易快报企业级 CLI 工具与底层 SDK (v0.6.0)
|
||||
---
|
||||
|
||||
# hose-use (v0.5.2)
|
||||
# hose-use (v0.6.1)
|
||||
|
||||
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
|
||||
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
|
||||
@@ -32,14 +32,29 @@ metadata:
|
||||
| 首次登录 / 账密认证 / Token过期 / 多账号 | `hose auth login`, `hose auth status`, `hose auth refresh` | [references/auth.md](references/auth.md) |
|
||||
| 代客协助凭证导入 / 探针连通性诊断 | `hose auth import`, `hose probe` | [references/auth.md](references/auth.md) |
|
||||
| 企业租户切换 / 查看当前企业 | `hose corps list`, `hose corps switch <id>` | [references/auth.md](references/auth.md) |
|
||||
| 报销单据检索 / 费用明细下钻 / 中文字典 | `hose bill list`, `hose bill get <单号|ID>` | [references/bill.md](references/bill.md) |
|
||||
| 报销单据检索 / 费用明细下钻 / 中文字典 | `hose bill list`, `hose bill get <单号|ID> [--risk]` | [references/bill.md](references/bill.md) |
|
||||
| 单据审批动作(同意/驳回/转交/加签/评论) | `hose bill approve|reject|transfer|add-node|comment <单号|ID> --yes` | [references/bill.md](references/bill.md) |
|
||||
| 单据审批历史 / 当前节点 / 后续流程 | `hose bill flow <单号|ID>` | [references/bill.md](references/bill.md) |
|
||||
| 单据风控预警 / 预算状态 / 发票风险 | `hose bill risk <单号|ID>` | [references/bill.md](references/bill.md) |
|
||||
| 单据引用 ID 二级解析(人员/部门/费用类型) | `hose bill refs <单号|ID>` | [references/bill.md](references/bill.md) |
|
||||
| 单据关联关系 / 冲借款与前置申请追溯 | `hose bill relations <单号|ID>` | [references/bill.md](references/bill.md) |
|
||||
| 单据预算状态 / 超预算与占用信息 | `hose bill budget <单号|ID>` | [references/bill.md](references/bill.md) |
|
||||
| 单据附件 / 发票原件标准列表 | `hose bill attachments <单号|ID>` | [references/bill.md](references/bill.md) |
|
||||
| 单据附件下载 | `hose bill download <单号|ID> --output-dir <目录>` | [references/bill.md](references/bill.md) |
|
||||
| 系统/自定义档案维度与档案项 | `hose dimension list`, `hose dimension items <维度>` | [references/dimension.md](references/dimension.md) |
|
||||
| 企业角色、角色组与角色成员 | `hose role list`, `hose role groups`, `hose role members <角色>` | [references/role.md](references/role.md) |
|
||||
| 角色权限只读快照 | `hose permission get` | [references/role.md](references/role.md) |
|
||||
| 单据 Web 详情直达链接生成 | `hose bill link <单号|ID>` | [references/bill.md](references/bill.md) |
|
||||
| 单据实体模型与字段元数据查询 | `hose bill schema` | [references/bill.md](references/bill.md) |
|
||||
| 企业通讯录检索 / 员工档案 / 防爆保护 | `hose contact search`, `hose contact list`, `hose contact get` | [references/contact.md](references/contact.md) |
|
||||
| 待办中心 / 已审批 / 我发起的 / 审批记录 / 抄送 | `hose task todo`, `hose task submitted`, `hose task records`, `hose task cc` | [references/task.md](references/task.md) |
|
||||
| 消息中心 / 未读统计 / 标记已读 / 类型过滤 | `hose message list [--all]`, `hose message count`, `hose message read` | [references/message.md](references/message.md) |
|
||||
| 跨自建应用工作流聚合检索 | `hose workflow list`, `hose platform list` | [references/workflow.md](references/workflow.md) |
|
||||
| 特定任务节点扫描 (如脚本/Webhook) | `hose workflow find --task=code-js2` | [references/workflow.md](references/workflow.md) |
|
||||
| 工作流详情与开通切换 | `hose workflow get`, `hose workflow toggle` | [references/workflow.md](references/workflow.md) |
|
||||
| 工作流节点树、代码依赖与静态诊断 | `hose workflow analyze <pipelineId>` | [references/workflow.md](references/workflow.md) |
|
||||
| 常驻守护进程管理 / 后台运行 | `hose service start`, `hose service status` | [references/service.md](references/service.md) |
|
||||
| 待办/消息事件轮询与去重 | `hose service poll --corp=<id>` | [references/service.md](references/service.md) |
|
||||
| 启动本地 HTTP 服务 / 打开可视化交互文档 | `hose http --port=8888` (访问 `/docs`) | [references/service.md](references/service.md) |
|
||||
| CLI 同进程执行网关 / REST 接口调用 | `POST /api/cli`, `GET /v1/corps` | [references/service.md](references/service.md) |
|
||||
| 导出标准 OpenAPI 3.1.0 JSON 规范 | `hose openapi`, `hose openapi --raw` | [references/service.md](references/service.md) |
|
||||
@@ -68,18 +83,44 @@ hose bill list # 查看最新单据与报
|
||||
hose bill link CL20260901001 # 生成官方 Web 详情直达免密跳转链接
|
||||
hose bill list --json -o /tmp/bills.json # 导出全量单据报文至本地磁盘
|
||||
hose bill get n0GMIM0dkQmKbS # 精准查询单据详情 (中文字段映射)
|
||||
hose bill get S26000001 --risk # 在详情中附加费控风控与发票风险快照
|
||||
hose bill approve S26000001 --yes # 同意当前待办
|
||||
hose bill reject S26000001 --comment "金额不符" --yes # 驳回并写明原因
|
||||
hose bill transfer S26000001 --approver-id 111 --yes # 转交给工号/员工 ID/唯一姓名
|
||||
hose bill add-node S26000001 --approver-id 111 --mode pre --yes # 前加签;--mode post 为后加签
|
||||
hose bill comment S26000001 --comment "请补充发票" --yes # 追加单据评论
|
||||
hose bill refs S26000001 # 解析提交人、归属人、部门、法人实体与费用类型
|
||||
hose bill relations S26000001 # 追溯冲借款、事前申请和合同关联
|
||||
hose bill budget S26000001 # 查看单据预算超限和预算接口状态
|
||||
hose bill attachments S26000001 # 查看附件和发票原件列表
|
||||
hose bill download S26000001 --output-dir ./downloads # 下载附件到本地目录
|
||||
hose dimension list # 查看系统与自定义档案维度
|
||||
hose dimension items 项目 # 查看项目、成本中心等档案项
|
||||
hose role list # 查看企业角色定义
|
||||
hose role groups # 查看角色组及其角色
|
||||
hose role members 财务主管 # 查看指定角色成员
|
||||
hose permission get # 查看角色权限开关(只读)
|
||||
hose bill schema # 查询单据实体元数据字典
|
||||
|
||||
# 4. 自建应用与工作流
|
||||
# 4. 待办与消息
|
||||
hose task submitted # 查看我发起的单据
|
||||
hose message list --unread # 查看未读消息
|
||||
hose message list --all # 合并查看已读和未读消息
|
||||
hose message count # 查看未读数量
|
||||
hose message read <messageId> # 标记单条消息已读
|
||||
|
||||
# 5. 自建应用与工作流
|
||||
hose platform list # 查看自建应用列表
|
||||
hose workflow list # 聚合扫描全部应用下的工作流
|
||||
hose workflow find --task=code-js2 # 查找部署了代码节点的工作流
|
||||
hose workflow get wf_01k83y... # 查看指定工作流节点拓扑
|
||||
hose workflow analyze wf_01k83y... --json # 输出节点树、引用依赖与静态诊断
|
||||
|
||||
# 5. 服务与守护进程
|
||||
# 6. 服务与守护进程
|
||||
hose http --port=8888 # 启动前台 HTTP 服务与交互式文档
|
||||
hose service start # 后台启动常驻守护进程服务
|
||||
hose service status # 查看常驻守护进程运行状态与端点
|
||||
hose service poll --corp=ID01ofWoOC1wiX --json # 轮询待办/消息并去重落盘
|
||||
hose service logs # 查看常驻守护进程日志
|
||||
hose service stop # 停止后台常驻守护进程
|
||||
```
|
||||
|
||||
@@ -35,6 +35,14 @@ hose-use bill list --type=TRAVEL_EXPENSE --status=APPROVED --limit=50
|
||||
```bash
|
||||
hose-use bill get n0GMIM0dkQmKbS
|
||||
hose-use bill get CL20260903001 --json
|
||||
hose-use bill flow CL20260903001
|
||||
```
|
||||
|
||||
在详情中附加风控与合规快照时加 `--risk`。该选项会沿用审批详情页的风控、预算和发票风险接口,并在 JSON 的每个单据项中增加 `risk` 字段:
|
||||
|
||||
```bash
|
||||
hose bill get S26000001 --risk
|
||||
hose bill get S26000001 --risk --json
|
||||
```
|
||||
|
||||
### 中文字段智能映射字典
|
||||
@@ -48,7 +56,89 @@ hose-use bill get CL20260903001 --json
|
||||
|
||||
---
|
||||
|
||||
## 3. 单据实体元数据字典 (`bill schema`)
|
||||
## 3. 单据审批流程 (`bill flow`)
|
||||
|
||||
读取单据右侧审批流程面板的真实业务接口,输出历史流转日志、处理人、审批意见、节点停留时长、自动跳过标记、当前节点和后续节点;使用 `--json` 可获得结构化时间线。
|
||||
|
||||
```bash
|
||||
hose-use bill flow CL20260903001
|
||||
hose-use bill flow CL20260903001 --json
|
||||
hose-use bill risk CL20260903001
|
||||
```
|
||||
|
||||
`bill risk` 聚合审批页“审查”面板的风控预警、信用规则、预算状态与发票风险接口;默认只输出摘要,`--json` 保留结构化原始结果。
|
||||
|
||||
## 4. 单据审批动作套件
|
||||
|
||||
审批动作直接复用合思 Web 点击时的业务接口。写操作必须显式带 `--yes`;交互终端未带该参数时会进行二次确认,非交互终端会直接拒绝,避免脚本误写业务状态。
|
||||
|
||||
```bash
|
||||
# 同意:可附带纯文本审批意见
|
||||
hose bill approve S26000001 --comment "同意" --yes
|
||||
|
||||
# 驳回:原因是必填项;默认退回提交人,可用 --reject-to 指定目标
|
||||
hose bill reject S26000001 --comment "请补充发票" --yes
|
||||
|
||||
# 转交:--approver-id 支持完整员工 ID、工号或唯一姓名
|
||||
hose bill transfer S26000001 --approver-id 111 --yes
|
||||
|
||||
# 加签:默认前加签,--mode post 表示后加签
|
||||
hose bill add-node S26000001 --approver-id 111 --mode pre --comment "请协助复核" --yes
|
||||
|
||||
# 评论:支持 --participants 传入逗号分隔的人员 ID
|
||||
hose bill comment S26000001 --comment "补充说明" --participants <staffId> --yes
|
||||
```
|
||||
|
||||
动作解析流程会先通过审批 backlog 详情定位 `backlogId`、`flowId` 和当前节点 ID;当响应包含 `flow.actions` 时,会校验当前登录员工是否拥有对应的 `freeflow.*` 动作。底层请求对应:`freeflow.agree`、`freeflow.reject`、`freeflow.addnode` 和 `freeflow.comment`。
|
||||
|
||||
### 单据引用 ID 二级解析 (`bill refs`)
|
||||
|
||||
读取审批详情并联动组织架构、部门树和费用类型目录,将底层 ID 转为姓名、工号、部门全路径或费用类型名称,同时保留原始 ID:
|
||||
|
||||
```bash
|
||||
hose bill refs S26000001
|
||||
hose bill refs S26000001 --json
|
||||
```
|
||||
|
||||
JSON 输出包含 `submitter`、`owner`、`department`、`legalEntity`、`feeTypes`、`dimensions` 和 `unresolved`。单据里出现法人实体、项目或成本中心 ID 时,会联动 `dimension` 目录补充名称与编码;目录在当前进程内按企业缓存 10 分钟。
|
||||
|
||||
### 单据关联链 (`bill relations`)
|
||||
|
||||
从审批详情中的冲借款、前置申请、合同和费用关联字段抽取关系树:
|
||||
|
||||
```bash
|
||||
hose bill relations S26000001
|
||||
hose bill relations S26000001 --json
|
||||
```
|
||||
|
||||
表格模式按树形缩进显示关联 ID、单号、标题和金额;JSON 模式保留每个节点的原始字段,便于继续下钻。
|
||||
|
||||
### 单据预算状态 (`bill budget`)
|
||||
|
||||
读取审批页使用的预算状态接口,查看单据是否超预算及接口返回的可用/占用金额字段:
|
||||
|
||||
```bash
|
||||
hose bill budget S26000001
|
||||
hose bill budget S26000001 --json
|
||||
```
|
||||
|
||||
### 单据附件列表 (`bill attachments`)
|
||||
|
||||
从审批详情中递归提取普通附件与发票原件的文件名、`fileId`、`key`、URL 和来源字段,并通过附件文件服务补齐可下载地址:
|
||||
|
||||
```bash
|
||||
hose bill attachments S26000001
|
||||
hose bill attachments S26000001 --json
|
||||
```
|
||||
|
||||
需要落盘时使用 `bill download`。命令会创建目标目录、清理文件名中的路径字符,并返回本地路径和字节数;指定 `--file-id` 可只下载一个附件:
|
||||
|
||||
```bash
|
||||
hose bill download S26000001 --output-dir ./downloads
|
||||
hose bill download S26000001 --file-id ID01THIU98FNyT --output-dir ./downloads --json
|
||||
```
|
||||
|
||||
## 5. 单据实体元数据字典 (`bill schema`)
|
||||
|
||||
用于探查当前企业所有单据实体、字段类型与扩展属性定义:
|
||||
|
||||
@@ -59,7 +149,7 @@ hose-use bill schema --json
|
||||
|
||||
---
|
||||
|
||||
## 4. 上下文防爆保护与安全转储
|
||||
## 6. 上下文防爆保护与安全转储
|
||||
|
||||
合思复杂的报销单通常携带大量明细行、发票 OCR 原生报文与附件列表,查询结果动辄数万行(几百 KB 到数 MB)。
|
||||
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
# 自定义档案与核算维度
|
||||
|
||||
合思前端“系统配置 → 档案设置 → 扩展档案 → 自定义档案”对应 CLI 的 `dimension` 域。
|
||||
|
||||
```bash
|
||||
# 查看系统/自定义档案维度目录
|
||||
hose dimension list
|
||||
hose dimension list --keyword=项目
|
||||
|
||||
# 查看某个维度的档案项(支持维度 ID、编码或名称)
|
||||
hose dimension items 项目
|
||||
hose dimension items DA001 --json
|
||||
```
|
||||
|
||||
目录来源于 `/api/v1/basedata/dimensions/active`,档案项来源于 `/api/v1/basedata/dimensionItems/$<dimensionId>`。结果在同一进程内按企业缓存 10 分钟,JSON 会保留底层 ID、编码、父项 ID 和表单字段。
|
||||
@@ -0,0 +1,15 @@
|
||||
# 消息中心
|
||||
|
||||
消息中心是 CLI-only 能力,不新增 MCP tool。命令默认查询未读消息。
|
||||
|
||||
```bash
|
||||
hose message list --unread
|
||||
hose message list --read
|
||||
hose message list --all
|
||||
hose message list --type=Approve
|
||||
hose message count
|
||||
hose message read <messageId>
|
||||
hose message read-all
|
||||
```
|
||||
|
||||
`message list --json` 返回消息 ID、标题、内容、消息类型、已读状态和原始字段;`--all` 会并行拉取已读与未读页面并去重后按时间排序;`--type` 在 CLI 层按 `messageType`、`msgType`、`msgTypeName` 或 `msgName` 做兼容过滤。`message read-all` 会分页读取全部未读消息再逐条标记,避免只处理首 100 条。
|
||||
@@ -0,0 +1,20 @@
|
||||
# 角色与角色组
|
||||
|
||||
角色页对应的只读 CLI:
|
||||
|
||||
```bash
|
||||
hose role list
|
||||
hose role list --keyword=财务
|
||||
hose role groups
|
||||
hose role members 财务主管
|
||||
hose role members CODE15 --json
|
||||
```
|
||||
|
||||
接口来自系统配置 → 角色页面:角色定义列表、角色组及指定角色成员。成员查询支持角色 ID、编码或名称。
|
||||
|
||||
权限页的角色权限快照:
|
||||
|
||||
```bash
|
||||
hose permission get
|
||||
hose permission get --json
|
||||
```
|
||||
@@ -33,6 +33,15 @@ hose-use service run
|
||||
每次执行 `service status` 或 `service start` 时,系统会自动探测记录的 PID:
|
||||
- 若进程已终止(孤儿 PID)或 PID 被其它非 `hose` 进程复用,系统会自动执行自愈逻辑,清理失效的 PID 文件。
|
||||
|
||||
### 事件轮询与去重 (`service poll`)
|
||||
|
||||
单次读取待办和未读消息,按事件 ID 写入 `~/.config/hose-use/events-<corpId>.json`,重复轮询不会重复返回已观察事件:
|
||||
|
||||
```bash
|
||||
hose-use service poll --corp=<corpId>
|
||||
hose-use service poll --corp=<corpId> --limit=100 --json
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. 前台 HTTP 服务 (`http` / `serve`)
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
# hose-use 专卷:待办中心与审批任务
|
||||
|
||||
## CLI
|
||||
|
||||
```bash
|
||||
hose task todo # 待我审批
|
||||
hose task approved # 我已审批
|
||||
hose task records # 审批记录
|
||||
hose task submitted # 我发起的单据
|
||||
hose task cc --unread # 未读抄送
|
||||
hose task cc --read # 已读抄送
|
||||
hose task todo --staff <员工工号或ID> # 在当前页结果中按人员过滤
|
||||
hose task todo --json --count 50
|
||||
hose task records --from 2026-01-01 --to 2026-09-05
|
||||
```
|
||||
|
||||
任务结果包含任务 ID、流程 ID、单号、标题、单据模板、提交人、金额、状态、当前节点和可用动作。分页使用 `--start` 与 `--count`。
|
||||
|
||||
当前实现对接合思 Web 待办工作台实际使用的业务接口:待审批/审批记录走 `/api/flow/v2/backlogs/search`,已审批走 `/api/flow/v1/flows/approved`。接口响应的完整原始对象保留在 JSON 结果的 `raw` 字段中,便于后续接入“我发起的”和“抄送我的”视图。
|
||||
|
||||
当前只通过 CLI 暴露任务查询;MCP 不新增待办专用工具。
|
||||
@@ -73,3 +73,11 @@ hose-use workflow toggle wf_01k83y... --enable
|
||||
# 停用指定工作流
|
||||
hose-use workflow toggle wf_01k83y... --disable
|
||||
```
|
||||
|
||||
## 6. 工作流静态分析 (`workflow analyze`)
|
||||
|
||||
从应用中心的具体自建应用进入工作流详情后,CLI 可以读取同一份详情并生成递归节点树、代码表达式引用依赖和明显配置诊断;该命令只读,不执行工作流:
|
||||
|
||||
```bash
|
||||
hose-use workflow analyze wf_01k83y... --json
|
||||
```
|
||||
+342
-3
@@ -1,11 +1,23 @@
|
||||
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import { stringOption, numberOption } from "../parser.js";
|
||||
import { booleanOption, stringOption, numberOption } from "../parser.js";
|
||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||
import {
|
||||
searchAndFormatBills,
|
||||
getBillByCodeOrId,
|
||||
getBillFlow,
|
||||
getBillRisk,
|
||||
getBillReferences,
|
||||
getBillRelations,
|
||||
getBillAttachments,
|
||||
downloadBillAttachments,
|
||||
getFieldDictionary,
|
||||
approveBill,
|
||||
rejectBill,
|
||||
transferBill,
|
||||
addNodeBill,
|
||||
commentBill,
|
||||
resolveBillStaffIds,
|
||||
} from "../../domains/bill/tools.js";
|
||||
|
||||
export async function handleBillCommand(
|
||||
@@ -23,7 +35,98 @@ export async function handleBillCommand(
|
||||
const action = parsed.action?.toLowerCase();
|
||||
const corpId = corp.corpId || corp.id;
|
||||
|
||||
const actionTarget = () => parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
const requireWriteConfirmation = async () => {
|
||||
if (booleanOption(parsed.options, ["yes", "y", "confirm", "force-write"])) return;
|
||||
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
||||
throw new Error("审批动作会改变单据状态。请显式添加 --yes(或 --confirm)后重试。");
|
||||
}
|
||||
const { prompt } = await import("../helpers.js");
|
||||
const answer = await prompt("该操作会改变单据状态,确认继续?输入 yes 继续: ");
|
||||
if (!/^(y|yes|是)$/i.test(answer.trim())) throw new Error("已取消审批动作");
|
||||
};
|
||||
const listOption = (keys: string[]): string[] | undefined => {
|
||||
const value = stringOption(parsed.options, keys);
|
||||
if (!value) return undefined;
|
||||
const values = value.split(",").map((item) => item.trim()).filter(Boolean);
|
||||
return values.length ? values : undefined;
|
||||
};
|
||||
const actionOptions = () => ({
|
||||
currentStaffId: corp.staffId || corp.credentials.staffId,
|
||||
reminder: booleanOption(parsed.options, ["reminder", "remind"]),
|
||||
keepItSecret: booleanOption(parsed.options, ["keep-it-secret", "secret", "private"]),
|
||||
comment: stringOption(parsed.options, ["comment", "message", "opinion"]),
|
||||
participants: listOption(["participant", "participants"]),
|
||||
approverIds: listOption(["approver", "approver-id", "approverIds", "staff", "staff-id", "to"]),
|
||||
rejectTo: stringOption(parsed.options, ["reject-to", "rejectTo"]),
|
||||
resubmitMethod: (stringOption(parsed.options, ["resubmit-method", "resubmitMethod"]) || "TO_REJECTOR").toUpperCase() as "TO_REJECTOR" | "FROM_START",
|
||||
addNodeType: ((): "PRE_ADD_NODE" | "AFT_ADD_NODE" => {
|
||||
const mode = (stringOption(parsed.options, ["mode", "add-node-type", "addNodeType"]) || "pre").toLowerCase();
|
||||
return mode === "post" || mode === "after" || mode === "aft" || mode === "aft_add_node" ? "AFT_ADD_NODE" : "PRE_ADD_NODE";
|
||||
})(),
|
||||
});
|
||||
const resolveApproverIds = async (values: string[] | undefined): Promise<string[]> => {
|
||||
if (!values?.length) throw new Error("请通过 --approver-id、--staff 或 --to 指定员工 ID、工号或姓名");
|
||||
return resolveBillStaffIds(client, corpId, values);
|
||||
};
|
||||
|
||||
switch (action) {
|
||||
case "approve":
|
||||
case "agree": {
|
||||
await requireWriteConfirmation();
|
||||
const target = actionTarget();
|
||||
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose bill approve <单号|ID> --yes");
|
||||
const result = await approveBill(client, corpId, target, actionOptions());
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `审批同意成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "reject":
|
||||
case "deny": {
|
||||
await requireWriteConfirmation();
|
||||
const target = actionTarget();
|
||||
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose bill reject <单号|ID> --comment <原因> --yes");
|
||||
const options = actionOptions();
|
||||
if (!options.comment?.trim()) throw new Error("驳回原因不能为空,请通过 --comment 提供原因");
|
||||
const result = await rejectBill(client, corpId, target, options);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `驳回成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "transfer":
|
||||
case "shift": {
|
||||
await requireWriteConfirmation();
|
||||
const target = actionTarget();
|
||||
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose bill transfer <单号|ID> --approver-id <员工ID> --yes");
|
||||
const options = { ...actionOptions(), approverIds: await resolveApproverIds(actionOptions().approverIds) };
|
||||
const result = await transferBill(client, corpId, target, options);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `转交审批成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "add-node":
|
||||
case "addnode":
|
||||
case "countersign":
|
||||
case "counter-sign": {
|
||||
await requireWriteConfirmation();
|
||||
const target = actionTarget();
|
||||
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose bill add-node <单号|ID> --approver-id <员工ID> --yes");
|
||||
const options = { ...actionOptions(), approverIds: await resolveApproverIds(actionOptions().approverIds) };
|
||||
const result = await addNodeBill(client, corpId, target, options);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `加签审批成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "comment":
|
||||
case "remark": {
|
||||
await requireWriteConfirmation();
|
||||
const target = actionTarget();
|
||||
if (!target) throw new Error("请提供单号或单据 ID: hose bill comment <单号|ID> --comment <内容> --yes");
|
||||
const result = await commentBill(client, corpId, target, actionOptions());
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `单据评论成功\n单号: ${result.billCode || target}\n流程 ID: ${result.flowId}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "list":
|
||||
case "search":
|
||||
case undefined: {
|
||||
@@ -105,6 +208,11 @@ export async function handleBillCommand(
|
||||
};
|
||||
}
|
||||
|
||||
const withRisk = booleanOption(parsed.options, ["risk", "with-risk", "audit"]);
|
||||
const riskReports = withRisk
|
||||
? await Promise.all(bills.map((bill) => getBillRisk(client, corpId, bill.billId || bill.billCode)))
|
||||
: [];
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
@@ -112,7 +220,7 @@ export async function handleBillCommand(
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
count: bills.length,
|
||||
bills,
|
||||
bills: bills.map((bill, index) => withRisk ? { ...bill, risk: riskReports[index] ?? null } : bill),
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
@@ -147,6 +255,25 @@ export async function handleBillCommand(
|
||||
outputs.push(` ${k.padEnd(maxKeyLen + 2)}: ${formattedVal}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (withRisk) {
|
||||
const risk = riskReports[i];
|
||||
outputs.push(`\n --- 费控风控与合规风险提示 ---`);
|
||||
if (!risk) {
|
||||
outputs.push(" (未找到审批流程风控快照)");
|
||||
} else {
|
||||
outputs.push(` 风控流程 ID : ${risk.flowId}`);
|
||||
outputs.push(` 预算超限 : ${risk.budgetExceeded ? "是" : "否"}`);
|
||||
if (risk.warnings.length === 0 && risk.invoiceWarnings.length === 0) {
|
||||
outputs.push(" 风险预警 : (暂无风险预警)");
|
||||
} else {
|
||||
for (const warning of risk.warnings) {
|
||||
outputs.push(` [${warning.riskLevel || "提示"}] ${warning.controlName || warning.title || warning.type || "风控规则"}: ${warning.messages.join(";") || "-"}`);
|
||||
}
|
||||
outputs.push(` 发票风险 : ${risk.invoiceWarnings.length} 条`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -195,6 +322,218 @@ export async function handleBillCommand(
|
||||
};
|
||||
}
|
||||
|
||||
case "flow":
|
||||
case "records":
|
||||
case "timeline": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要查询流程的单号或单据 ID: hose bill flow <单号|ID>");
|
||||
const flow = await getBillFlow(client, corpId, target);
|
||||
if (!flow) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到单据流程: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId, corpName: corp.name, ...flow }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const historyRows = flow.history.map((entry) => [
|
||||
entry.time ? new Date(entry.time).toLocaleString("zh-CN") : "-",
|
||||
entry.nodeName || "-",
|
||||
entry.action || "-",
|
||||
entry.operator?.name || (entry.automatic ? "系统" : "-"),
|
||||
entry.durationMs !== undefined ? `${Math.round(entry.durationMs / 1000)} 秒` : "-",
|
||||
entry.skipped ? "自动跳过" : entry.automatic ? "自动" : "",
|
||||
entry.comment || "-",
|
||||
]);
|
||||
const pendingRows = flow.pending.map((node) => [
|
||||
node.state || "-",
|
||||
node.name || "-",
|
||||
node.type || "-",
|
||||
node.approver?.name || node.approvers?.map((person) => person.name).filter(Boolean).join(", ") || "-",
|
||||
]);
|
||||
const output = [
|
||||
`====== 审批流程 (单号: ${flow.billCode || target} | 状态: ${flow.state || "-"}) ======`,
|
||||
`流程 ID: ${flow.flowId || "-"} 当前节点: ${flow.currentNode || "-"}`,
|
||||
"",
|
||||
"--- 历史流转 ---",
|
||||
flow.history.length ? printTable(["时间", "节点", "动作", "处理人", "停留时长", "标记", "意见"], historyRows) : " (暂无历史记录)",
|
||||
"",
|
||||
"--- 后续节点 ---",
|
||||
flow.pending.length ? printTable(["状态", "节点", "类型", "审批人"], pendingRows) : " (暂无后续节点)",
|
||||
"",
|
||||
].join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "risk":
|
||||
case "review":
|
||||
case "warnings": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要查询风控结果的单号或单据 ID: hose bill risk <单号|ID>");
|
||||
const report = await getBillRisk(client, corpId, target);
|
||||
if (!report) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到单据风控结果: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId, corpName: corp.name, ...report }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const warningRows = report.warnings.map((warning) => [
|
||||
warning.riskLevel || "-",
|
||||
warning.type || "-",
|
||||
warning.controlName || warning.title || "-",
|
||||
warning.messages.join(";") || "-",
|
||||
]);
|
||||
const output = [
|
||||
`====== 单据风控审查 (流程: ${report.flowId}) ======`,
|
||||
`预算超限: ${report.budgetExceeded ? "是" : "否"}`,
|
||||
"",
|
||||
"--- 风险预警 ---",
|
||||
report.warnings.length ? printTable(["等级", "类型", "规则", "提示"], warningRows) : " (暂无风险预警)",
|
||||
`发票风险: ${report.invoiceWarnings.length} 条`,
|
||||
"",
|
||||
].join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "budget":
|
||||
case "budgets": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要查询预算状态的单号或单据 ID: hose bill budget <单号|ID>");
|
||||
const report = await getBillRisk(client, corpId, target);
|
||||
if (!report) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到单据预算状态: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId, corpName: corp.name, flowId: report.flowId, budgetExceeded: report.budgetExceeded, budget: report.budget || {} }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const budget = report.budget || {};
|
||||
const output = [
|
||||
`====== 单据预算状态 (流程: ${report.flowId}) ======`,
|
||||
`预算超限: ${report.budgetExceeded ? "是" : "否"}`,
|
||||
`状态: ${typeof budget.status === "string" ? budget.status : "-"}`,
|
||||
`可用余额: ${budget.availableAmount ?? budget.available ?? "-"}`,
|
||||
`占用金额: ${budget.occupiedAmount ?? budget.occupied ?? "-"}`,
|
||||
`预算明细: ${Object.keys(budget).length ? JSON.stringify(budget) : "-"}`,
|
||||
"",
|
||||
].join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "refs":
|
||||
case "references":
|
||||
case "resolve": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要解析引用的单号或单据 ID: hose bill refs <单号|ID>");
|
||||
const report = await getBillReferences(client, corpId, target);
|
||||
if (!report) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到单据引用: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId, corpName: corp.name, ...report }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const person = (value: typeof report.submitter) => value ? `${value.name || "未解析"}${value.code ? ` (${value.code})` : ""} [${value.id}]` : "-";
|
||||
const output = [
|
||||
`====== 单据引用解析 (单号: ${report.billCode || target}) ======`,
|
||||
`标题: ${report.title || "-"}`,
|
||||
`提交人: ${person(report.submitter)}`,
|
||||
`归属人: ${person(report.owner)}`,
|
||||
`费用承担部门: ${report.department?.path || report.department?.name || "-"}${report.department?.id ? ` [${report.department.id}]` : ""}`,
|
||||
`法人实体: ${report.legalEntity ? `${report.legalEntity.name || "未解析"}${report.legalEntity.id ? ` [${report.legalEntity.id}]` : ""}` : "-"}`,
|
||||
`费用类型: ${report.feeTypes.length ? report.feeTypes.map((item) => `${item.name || "未解析"}${item.code ? ` (${item.code})` : ""} [${item.id}]`).join("、") : "-"}`,
|
||||
`核算维度: ${report.dimensions.length ? report.dimensions.map((item) => `${item.name || "未解析"}${item.code ? ` (${item.code})` : ""} [${item.id}]`).join("、") : "-"}`,
|
||||
report.unresolved.length ? `未解析 ID: ${report.unresolved.join("、")}` : "引用均已解析",
|
||||
"",
|
||||
].join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "relations":
|
||||
case "relation":
|
||||
case "links": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要查询关联关系的单号或单据 ID: hose bill relations <单号|ID>");
|
||||
const report = await getBillRelations(client, corpId, target);
|
||||
if (!report) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到单据关联关系: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId, corpName: corp.name, ...report }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const rows: string[][] = [];
|
||||
const visit = (node: typeof report.relations[number], depth = 0) => {
|
||||
rows.push([
|
||||
`${" ".repeat(depth)}${node.relation}`,
|
||||
node.code || node.id || "-",
|
||||
node.title || "-",
|
||||
node.amount || "-",
|
||||
]);
|
||||
for (const child of node.children) visit(child, depth + 1);
|
||||
};
|
||||
for (const node of report.relations) visit(node);
|
||||
const output = [
|
||||
`====== 单据关联关系 (单号: ${report.billCode || target}) ======`,
|
||||
`标题: ${report.title || "-"}`,
|
||||
rows.length ? printTable(["关系", "关联 ID/单号", "标题/名称", "金额"], rows) : "暂无可识别的前置单据、冲借款或合同关联",
|
||||
"",
|
||||
].join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "attachments":
|
||||
case "attachment":
|
||||
case "files": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要查询附件的单号或单据 ID: hose bill attachments <单号|ID>");
|
||||
const report = await getBillAttachments(client, corpId, target);
|
||||
if (!report) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到单据附件: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId, corpName: corp.name, ...report }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const rows = report.attachments.map((item) => [item.fileName || "-", item.fileId || "-", item.key || "-", item.url || "-"]);
|
||||
const output = [
|
||||
`====== 单据附件 (单号: ${report.billCode || target}) ======`,
|
||||
report.attachments.length ? printTable(["文件名", "fileId", "key", "URL"], rows) : "暂无附件或发票原件",
|
||||
"",
|
||||
].join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "download":
|
||||
case "file-download": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要下载附件的单号或单据 ID: hose bill download <单号|ID>");
|
||||
const outputDir = stringOption(parsed.options, ["output-dir", "dir"]) || `${process.cwd()}/downloads`;
|
||||
const fileId = stringOption(parsed.options, ["file-id", "file"]);
|
||||
const result = await downloadBillAttachments(client, corpId, target, outputDir, fileId);
|
||||
const summary = {
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
target: result.target,
|
||||
outputDir: result.outputDir,
|
||||
requestedFileId: result.requestedFileId,
|
||||
downloaded: result.downloaded,
|
||||
skipped: result.skipped,
|
||||
};
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(summary, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const rows = result.downloaded.map((item) => [item.fileName || item.key || item.fileId || "-", item.bytes, item.path]);
|
||||
const output = [
|
||||
`====== 单据附件下载 (单号: ${target}) ======`,
|
||||
`输出目录: ${result.outputDir}`,
|
||||
rows.length ? printTable(["文件名", "字节数", "本地路径"], rows) : "没有可下载的附件",
|
||||
result.skipped ? `跳过 ${result.skipped} 个缺少下载地址的附件` : "",
|
||||
"",
|
||||
].filter(Boolean).join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "link":
|
||||
case "url": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id", "c"]);
|
||||
@@ -257,6 +596,6 @@ export async function handleBillCommand(
|
||||
}
|
||||
|
||||
default:
|
||||
throw new Error(`未知 bill 子命令: ${action}。支持: list, get <单号>, schema, link <单号>`);
|
||||
throw new Error(`未知 bill 子命令: ${action}。支持: list, get <单号> [--risk], refs <单号>, relations <单号>, attachments <单号>, download <单号>, flow <单号>, risk <单号>, budget <单号>, schema, link <单号>`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import { numberOption, stringOption } from "../parser.js";
|
||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||
import { searchDimensions, resolveDimension } from "../../domains/dimension/tools.js";
|
||||
|
||||
export async function handleDimensionCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const corp = runtime.selectedCorp;
|
||||
if (!corp) throw new Error("未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose auth login 登录。");
|
||||
const client = await createEkbClient(corp);
|
||||
const corpId = corp.corpId || corp.id;
|
||||
const action = parsed.action?.toLowerCase() || "list";
|
||||
if (["list", "search", "catalogs", undefined].includes(action)) {
|
||||
const keyword = stringOption(parsed.options, ["keyword", "q", "query"]) || parsed.args[0];
|
||||
const dimensions = await searchDimensions(client, corpId, { name: keyword });
|
||||
if (runtime.jsonMode) return { stdout: printJson({ corpId, corpName: corp.name, count: dimensions.length, dimensions }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows = dimensions.map((item, index) => [index + 1, item.name, item.code || "-", item.id, item.type || "-", item.active ? "启用" : "停用"]);
|
||||
return { stdout: `====== 企业档案维度目录 (企业: ${corp.name} | 共 ${dimensions.length} 个) ======\n${rows.length ? printTable(["#", "名称", "编码", "ID", "类型", "状态"], rows) : "暂无匹配档案维度"}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
if (["items", "get", "show"].includes(action)) {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["dimension", "id", "code", "name"]);
|
||||
if (!target) throw new Error("请提供档案维度 ID、编码或名称: hose dimension items <维度>");
|
||||
const result = await resolveDimension(client, corpId, target);
|
||||
if (!result) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到档案维度: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
const count = numberOption(parsed.options, ["count", "limit", "n"], 100) || 100;
|
||||
const items = count >= result.items.length ? result.items : result.items.slice(0, count);
|
||||
if (runtime.jsonMode) return { stdout: printJson({ corpId, corpName: corp.name, dimension: result.dimension, count: items.length, items }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows = items.map((item, index) => [index + 1, item.name, item.code || "-", item.id, item.parentId || "-", item.fullPath || "-"]);
|
||||
return { stdout: `====== 档案项 (维度: ${result.dimension.name} | 共 ${items.length} 条) ======\n${rows.length ? printTable(["#", "名称", "编码", "ID", "上级 ID", "全路径"], rows) : "暂无档案项"}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
throw new Error(`未知 dimension 子命令: ${action}。支持: list, items <维度 ID|编码|名称>`);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||
import { filterMessages, listMessages, mergeMessages, readMessage } from "../../domains/message/tools.js";
|
||||
import type { MessageItem } from "../../domains/message/types.js";
|
||||
|
||||
function formatTime(value: number | undefined): string {
|
||||
return value === undefined ? "-" : new Date(value).toISOString().replace("T", " ").slice(0, 16);
|
||||
}
|
||||
|
||||
function renderItems(items: MessageItem[]): string {
|
||||
const headers = ["消息 ID", "时间", "类型", "标题", "内容", "状态"];
|
||||
const rows = items.map((item) => [
|
||||
item.id,
|
||||
formatTime(item.sortTime ?? item.createTime),
|
||||
item.msgTypeName || item.messageType || "-",
|
||||
item.title || "-",
|
||||
item.content || "-",
|
||||
item.read ? "已读" : "未读",
|
||||
]);
|
||||
return printTable(headers, rows);
|
||||
}
|
||||
|
||||
export async function handleMessageCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const corp = runtime.selectedCorp;
|
||||
if (!corp) throw new Error("未指定或未找到有效企业。请运行 hose corps list 或指定 --corp=<id>");
|
||||
const action = parsed.action || parsed.args[0] || "list";
|
||||
const client = await createEkbClient(corp);
|
||||
const corpId = corp.corpId || corp.id;
|
||||
|
||||
if (action === "count" || action === "unread") {
|
||||
const result = await listMessages(client, corpId, { start: 0, count: 1, read: false });
|
||||
if (runtime.jsonMode) return { stdout: printJson({ corpId, unread: result.total }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `未读消息: ${result.total}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
if (action === "read" || action === "mark-read") {
|
||||
const messageId = parsed.args[0] || stringOption(parsed.options, ["id", "message-id"]);
|
||||
if (!messageId) return { stdout: "", stderr: "用法: hose message read <messageId>\n", exitCode: 1 };
|
||||
await readMessage(client, corpId, messageId);
|
||||
if (runtime.jsonMode) return { stdout: printJson({ corpId, id: messageId, read: true }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `已标记消息为已读: ${messageId}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
if (action === "read-all" || action === "mark-all-read") {
|
||||
const ids: string[] = [];
|
||||
let start = 0;
|
||||
let total = 0;
|
||||
do {
|
||||
const page = await listMessages(client, corpId, { start, count: 100, read: false });
|
||||
total = page.total;
|
||||
ids.push(...page.items.map((item) => item.id));
|
||||
start += page.items.length;
|
||||
if (page.items.length === 0) break;
|
||||
} while (start < total);
|
||||
for (const id of ids) await readMessage(client, corpId, id);
|
||||
if (runtime.jsonMode) return { stdout: printJson({ corpId, requested: ids.length, read: ids.length, totalUnreadBefore: total }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `已标记 ${ids.length} 条消息为已读。\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
if (action !== "list") {
|
||||
return { stdout: "", stderr: `未知消息子命令: ${action}。支持: list, count, read <messageId>, read-all\n`, exitCode: 1 };
|
||||
}
|
||||
|
||||
const read = booleanOption(parsed.options, ["read"]);
|
||||
const unread = booleanOption(parsed.options, ["unread"]);
|
||||
const all = booleanOption(parsed.options, ["all"]);
|
||||
const readFilter = read && !unread;
|
||||
const count = numberOption(parsed.options, ["count", "limit", "n"], 20) ?? 20;
|
||||
const start = numberOption(parsed.options, ["start", "offset"], 0) ?? 0;
|
||||
const type = stringOption(parsed.options, ["type", "message-type"]);
|
||||
const result = all
|
||||
? await (async () => {
|
||||
const [unreadPage, readPage] = await Promise.all([
|
||||
listMessages(client, corpId, { start: 0, count: Math.max(100, start + count), read: false }),
|
||||
listMessages(client, corpId, { start: 0, count: Math.max(100, start + count), read: true }),
|
||||
]);
|
||||
const merged = mergeMessages([...unreadPage.items, ...readPage.items]);
|
||||
return { total: unreadPage.total + readPage.total, start, count, read: false, items: merged.slice(start, start + count) };
|
||||
})()
|
||||
: await listMessages(client, corpId, { start, count, read: readFilter });
|
||||
const items = filterMessages(result.items, type);
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId, total: type ? items.length : result.total, start: result.start, count: result.count, read: all ? "all" : readFilter, items }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
return {
|
||||
stdout: `====== ${all ? "全部" : readFilter ? "已读" : "未读"}消息 (企业: ${corp.name} | 总数: ${type ? items.length : result.total} | 当前返回: ${items.length}) ======\n${items.length ? renderItems(items) : " (暂无数据)"}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||
import { getPermissions } from "../../domains/permission/tools.js";
|
||||
|
||||
export async function handlePermissionCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const corp = runtime.selectedCorp;
|
||||
if (!corp) throw new Error("未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose auth login 登录。");
|
||||
const action = parsed.action?.toLowerCase() || "get";
|
||||
if (!["get", "list", "show"].includes(action)) throw new Error(`未知 permission 子命令: ${action}。支持: get`);
|
||||
const client = await createEkbClient(corp);
|
||||
const report = await getPermissions(client, corp.corpId || corp.id);
|
||||
if (runtime.jsonMode) return { stdout: printJson({ corpId: corp.corpId || corp.id, corpName: corp.name, ...report }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows = report.permissions.map((item) => [item.name, item.auth ? "启用" : "停用"]);
|
||||
return { stdout: `====== 角色权限快照 (权限模型: ${report.type || "-"}) ======\n${rows.length ? printTable(["权限", "状态"], rows) : "暂无权限项"}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { numberOption, stringOption } from "../parser.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||
import { getRoleGroups, getRoleMembers, searchRoles } from "../../domains/role/tools.js";
|
||||
|
||||
export async function handleRoleCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const corp = runtime.selectedCorp;
|
||||
if (!corp) throw new Error("未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose auth login 登录。");
|
||||
const client = await createEkbClient(corp), corpId = corp.corpId || corp.id;
|
||||
const action = parsed.action?.toLowerCase() || "list";
|
||||
if (["list", "search"].includes(action)) {
|
||||
const keyword = stringOption(parsed.options, ["keyword", "q", "query"]) || parsed.args[0];
|
||||
const roles = await searchRoles(client, corpId, { keyword });
|
||||
const count = numberOption(parsed.options, ["count", "limit", "n"], roles.length) || roles.length;
|
||||
const items = roles.slice(0, count);
|
||||
if (runtime.jsonMode) return { stdout: printJson({ corpId, corpName: corp.name, count: items.length, roles: items }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows = items.map((role) => [role.name, role.code || "-", role.id, role.scope.name || "-", role.roleGroupId || "-"]);
|
||||
return { stdout: `====== 企业角色 (共 ${items.length} 个) ======\n${rows.length ? printTable(["名称", "编码", "ID", "角色类型", "角色组 ID"], rows) : "暂无匹配角色"}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
if (["groups", "group"].includes(action)) {
|
||||
const groups = await getRoleGroups(client, corpId);
|
||||
if (runtime.jsonMode) return { stdout: printJson({ corpId, corpName: corp.name, count: groups.length, groups }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows = groups.map((group) => [group.name, group.id, group.roleDefs.length, group.roleDefs.map((role) => role.name).join(", ") || "-"]);
|
||||
return { stdout: `====== 角色组 (共 ${groups.length} 个) ======\n${rows.length ? printTable(["名称", "ID", "角色数", "角色"], rows) : "暂无角色组"}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
if (["members", "member", "staffs", "staff"].includes(action)) {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["role", "id", "code", "name"]);
|
||||
if (!target) throw new Error("请提供角色 ID、编码或名称: hose role members <角色>");
|
||||
const report = await getRoleMembers(client, corpId, target);
|
||||
if (!report) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到角色: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) return { stdout: printJson({ corpId, corpName: corp.name, ...report, count: report.members.length }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows = report.members.map((member) => [member.name, member.code || "-", member.id, member.email || "-", member.cellphone || "-"]);
|
||||
return { stdout: `====== 角色成员 (角色: ${report.role.name} | 共 ${rows.length} 人) ======\n${rows.length ? printTable(["姓名", "工号", "staffId", "邮箱", "手机号"], rows) : "暂无成员"}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
throw new Error(`未知 role 子命令: ${action}。支持: list, groups, members <角色 ID|编码|名称>`);
|
||||
}
|
||||
@@ -5,6 +5,9 @@ import { runServiceCommand, ServiceConfig, getPidFile, getLogFile } from "../ser
|
||||
import { printJson, printKeyValue } from "../printer.js";
|
||||
import { numberOption, stringOption } from "../parser.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||
import { EventStore } from "../../domains/events/store.js";
|
||||
import { pollEvents } from "../../domains/events/poller.js";
|
||||
|
||||
export const SERVICE_STATE_DIR = process.env.HOSE_STATE_DIR || join(homedir(), ".config", "hose-use");
|
||||
|
||||
@@ -16,6 +19,18 @@ export async function handleServiceCommand(
|
||||
const port = numberOption(parsed.options, ["port", "p"]);
|
||||
const host = stringOption(parsed.options, ["host", "h"]);
|
||||
|
||||
if (action === "poll") {
|
||||
const corp = runtime.selectedCorp;
|
||||
if (!corp) throw new Error("事件轮询需要企业上下文,请通过 --corp=<id> 指定企业。");
|
||||
const corpId = corp.corpId || corp.id;
|
||||
const client = await createEkbClient(corp);
|
||||
const limit = numberOption(parsed.options, ["limit", "count", "n"], 50) || 50;
|
||||
const store = new EventStore(join(SERVICE_STATE_DIR, `events-${corpId}.json`));
|
||||
const result = await pollEvents(client, corpId, store, limit);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `====== 事件轮询 (企业: ${corp.name}) ======\n${printKeyValue({ "待办扫描": result.scanned.todo, "未读消息扫描": result.scanned.messages, "新增事件": result.newEvents.length, "重复事件": result.duplicateCount, "事件状态文件": join(SERVICE_STATE_DIR, `events-${corpId}.json`) })}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const config: ServiceConfig = {
|
||||
appRoot: runtime.appRoot || process.cwd(),
|
||||
entryFile: runtime.entryFile || join(runtime.appRoot || process.cwd(), "src", "cli.ts"),
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||
import { listTasks } from "../../domains/task/tools.js";
|
||||
import type { TaskView } from "../../domains/task/types.js";
|
||||
|
||||
function dateOption(value: string | undefined): number | undefined {
|
||||
if (!value) return undefined;
|
||||
const numeric = Number(value);
|
||||
if (Number.isFinite(numeric)) return numeric;
|
||||
const parsed = Date.parse(value);
|
||||
return Number.isNaN(parsed) ? undefined : parsed;
|
||||
}
|
||||
|
||||
export async function handleTaskCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const corp = runtime.selectedCorp;
|
||||
if (!corp) throw new Error("未指定或未找到有效企业。请运行 hose corps list 或指定 --corp=<id>");
|
||||
const action = parsed.action || parsed.args[0] || "todo";
|
||||
const view: TaskView | undefined = action === "todo" || action === "pending"
|
||||
? "todo"
|
||||
: action === "approved" || action === "done"
|
||||
? "approved"
|
||||
: action === "processed" || action === "records" || action === "history"
|
||||
? "processed"
|
||||
: action === "cc" || action === "carboncopy" || action === "carbon-copy"
|
||||
? "cc"
|
||||
: action === "submitted" || action === "mine" || action === "created"
|
||||
? "submitted"
|
||||
: undefined;
|
||||
if (!view) {
|
||||
throw new Error("未知 task 子命令。支持: todo, approved, records, submitted, cc");
|
||||
}
|
||||
const count = numberOption(parsed.options, ["count", "limit", "n"], 20);
|
||||
const start = numberOption(parsed.options, ["start", "offset"], 0);
|
||||
const staffId = stringOption(parsed.options, ["staff", "staff-id", "staffId"]);
|
||||
const from = dateOption(stringOption(parsed.options, ["from", "start-date"]));
|
||||
const to = dateOption(stringOption(parsed.options, ["to", "end-date"]));
|
||||
const read = booleanOption(parsed.options, ["read"]);
|
||||
const unread = booleanOption(parsed.options, ["unread"]);
|
||||
// Carbon copy defaults to unread, while the other views do not use this flag.
|
||||
const readFilter = view === "cc" ? read && !unread : undefined;
|
||||
const result = await listTasks(await createEkbClient(corp), corp.corpId || corp.id, view, { start, count, staffId, from, to, read: readFilter });
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId: corp.corpId || corp.id, corpName: corp.name, ...result }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const headers = ["#", "任务 ID", "单号", "标题", "模板", "提交人", "金额", "状态", "当前节点", "动作"];
|
||||
const rows = result.items.map((item, index) => [
|
||||
index + 1,
|
||||
item.taskId,
|
||||
item.billCode || "-",
|
||||
item.title || "-",
|
||||
item.templateName || "-",
|
||||
item.submitter ? `${item.submitter.name || "-"}${item.submitter.code ? `(${item.submitter.code})` : ""}` : "-",
|
||||
item.amount ? `${item.amount.symbol || ""}${item.amount.value} ${item.amount.currency || ""}`.trim() : "-",
|
||||
item.state || "-",
|
||||
item.nodeName || "-",
|
||||
item.action || "-",
|
||||
]);
|
||||
const labels: Record<TaskView, string> = {
|
||||
todo: "待审批",
|
||||
approved: "已审批",
|
||||
processed: "审批记录",
|
||||
submitted: "我发起的",
|
||||
cc: readFilter ? "抄送(已读)" : "抄送(未读)",
|
||||
};
|
||||
return {
|
||||
stdout: `====== ${labels[view]}任务 (企业: ${corp.name} | 总数: ${result.total} | 当前返回: ${result.items.length}) ======\n${printTable(headers, rows)}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import { stringOption, numberOption, booleanOption } from "../parser.js";
|
||||
import { createClientsForCorp } 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";
|
||||
|
||||
export async function handleWorkflowCommand(
|
||||
parsed: CliParsedArgs,
|
||||
@@ -37,6 +38,9 @@ export async function handleWorkflowCommand(
|
||||
return handleFind(parsed, runtime);
|
||||
case "toggle":
|
||||
return handleToggle(parsed, runtime);
|
||||
case "analyze":
|
||||
case "analyse":
|
||||
return handleAnalyze(parsed, runtime);
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
@@ -46,6 +50,23 @@ export async function handleWorkflowCommand(
|
||||
}
|
||||
}
|
||||
|
||||
async function handleAnalyze(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
if (!pipelineId) return { stdout: "", stderr: "用法: hose workflow analyze <pipelineId>\n", exitCode: 1 };
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const detail = await api.getWorkflowDetail(clients.easoClient, 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]);
|
||||
const dependencyRows = result.dependencies.map((item) => [item.path, item.taskType, item.references.join(", ")]);
|
||||
return { stdout: [
|
||||
`====== 工作流静态分析 (${detail.label || detail.id}) ======`,
|
||||
printKeyValue({ "工作流 ID": detail.id, "根节点数": result.ast.length, "依赖节点数": result.dependencies.length, "诊断数": result.diagnostics.length }),
|
||||
`\n依赖引用:\n${dependencyRows.length ? printTable(["节点路径", "类型", "引用"], dependencyRows) : "暂无代码引用"}`,
|
||||
`\n诊断:\n${diagnosticRows.length ? printTable(["级别", "代码", "节点路径", "说明"], diagnosticRows) : "未发现明显配置问题"}`, "",
|
||||
].join("\n"), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const page = numberOption(parsed.options, ["page"]) || 1;
|
||||
|
||||
+15
-5
@@ -8,6 +8,7 @@ const KNOWN_BOOLEAN_FLAGS = new Set([
|
||||
"h",
|
||||
"version",
|
||||
"v",
|
||||
"V",
|
||||
"force",
|
||||
"f",
|
||||
"stateless",
|
||||
@@ -23,6 +24,9 @@ const KNOWN_BOOLEAN_FLAGS = new Set([
|
||||
"allow-full",
|
||||
"allowFull",
|
||||
"summary",
|
||||
"yes",
|
||||
"confirm",
|
||||
"force-write",
|
||||
]);
|
||||
|
||||
export function parseArgs(rawArgs: string[]): CliParsedArgs {
|
||||
@@ -45,8 +49,10 @@ export function parseArgs(rawArgs: string[]): CliParsedArgs {
|
||||
options[key] = val;
|
||||
} else {
|
||||
const key = arg.slice(2);
|
||||
if (KNOWN_BOOLEAN_FLAGS.has(key)) {
|
||||
const keyLower = key.toLowerCase();
|
||||
if (KNOWN_BOOLEAN_FLAGS.has(key) || KNOWN_BOOLEAN_FLAGS.has(keyLower)) {
|
||||
options[key] = true;
|
||||
if (key !== keyLower) options[keyLower] = true;
|
||||
} else {
|
||||
const next = rawArgs[i + 1];
|
||||
if (next && !next.startsWith("-")) {
|
||||
@@ -62,10 +68,14 @@ export function parseArgs(rawArgs: string[]): CliParsedArgs {
|
||||
|
||||
if (arg.startsWith("-") && arg.length > 1) {
|
||||
const flag = arg.slice(1);
|
||||
if (flag === "h") options.help = true;
|
||||
else if (flag === "j") options.json = true;
|
||||
else if (flag === "v") options.version = true;
|
||||
else if (flag === "o") {
|
||||
const flagLower = flag.toLowerCase();
|
||||
if (flagLower === "h" || flag === "?") {
|
||||
options.help = true;
|
||||
} else if (flagLower === "j") {
|
||||
options.json = true;
|
||||
} else if (flagLower === "v") {
|
||||
options.version = true;
|
||||
} else if (flag === "o") {
|
||||
const next = rawArgs[i + 1];
|
||||
if (next && !next.startsWith("-")) {
|
||||
options.outputFile = next;
|
||||
|
||||
@@ -21,6 +21,15 @@ describe("cli/printer - 上下文防爆与敏感脱敏", () => {
|
||||
expect(redacted).toContain("corpId=corpxx");
|
||||
});
|
||||
|
||||
test("脱敏对象存储签名 URL 中的临时凭证", () => {
|
||||
const input = "https://files.example/a.png?Expires=1&OSSAccessKeyId=key&Signature=sig&security-token=secret";
|
||||
const redacted = redactSensitiveText(input);
|
||||
expect(redacted).toContain("OSSAccessKeyId=<redacted>");
|
||||
expect(redacted).toContain("Signature=<redacted>");
|
||||
expect(redacted).toContain("security-token=<redacted>");
|
||||
expect(redacted).not.toContain("secret");
|
||||
});
|
||||
|
||||
test("脱敏 Authorization Bearer token", () => {
|
||||
const input = "Request headers: Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.xyz";
|
||||
const redacted = redactSensitiveText(input);
|
||||
|
||||
+37
-4
@@ -6,7 +6,7 @@ export const DEFAULT_OUTPUT_BYTES_LIMIT = 200_000;
|
||||
|
||||
export function redactSensitiveText(value: string): string {
|
||||
return value
|
||||
.replace(/([?&](?:accessToken|token|returnToken)=)[^&\s"']+/gi, "$1<redacted>")
|
||||
.replace(/([?&](?:accessToken|token|returnToken|security-token|x-amz-security-token|signature|x-amz-signature|ossaccesskeyid|x-amz-credential)=)[^&\s"']+/gi, "$1<redacted>")
|
||||
.replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi, "$1<redacted>")
|
||||
.replace(/((?:password|passwd|secret|appSecurity)["']?\s*[:=]\s*["']?)[^"',\s}]+/gi, "$1<redacted>");
|
||||
}
|
||||
@@ -118,16 +118,21 @@ export function printHelp(): string {
|
||||
auth 认证与凭证管理 (login, status, refresh, import, accounts)
|
||||
corps 多企业租户管理 (list, switch, current)
|
||||
config 全局运行模式与路径诊断 (show, paths, mode <stateful|stateless>, set)
|
||||
workflow 工作流管理 (list, get, find, toggle)
|
||||
bill 单据与费用明细检索 (list, get <单号|ID>, schema, link <单号|ID>)
|
||||
workflow 工作流管理 (list, get, find, analyze, toggle)
|
||||
bill 单据检索与审批动作 (list, get <单号|ID> [--risk], approve|reject|transfer|add-node|comment <单号|ID> [选项], refs, relations, attachments, download, flow, risk, budget, schema, link)
|
||||
contact 企业通讯录与人员检索 (list, search <关键词>, get <staffId>)
|
||||
task 待办中心与审批任务 (todo, approved, records, submitted, cc)
|
||||
message 消息中心与通知管理 (list, count, read, read-all)
|
||||
platform 自建应用管理 (list)
|
||||
dimension 系统/自定义档案维度 (list, items <维度>)
|
||||
role 角色定义与成员 (list, groups, members <角色>)
|
||||
permission 权限模型快照 (get)
|
||||
skill Agent Skill 管理 (install, status, dump)
|
||||
probe 连通性诊断 (probe [corpId])
|
||||
update 版本自更新与发布记录 (update, update check, update --changelog)
|
||||
openapi OpenAPI 3.1.0 规范导出 (openapi, openapi --raw, openapi paths, openapi info)
|
||||
http 启动轻量 HTTP Server 与交互式文档 (http [--port=8888] [--host=127.0.0.1])
|
||||
service 常驻守护进程管理 (service start|stop|restart|status|logs)
|
||||
service 常驻守护进程管理 (service start|stop|restart|status|logs|poll)
|
||||
mcp MCP Server 运行 (serve)
|
||||
version 查看版本信息
|
||||
|
||||
@@ -138,6 +143,7 @@ export function printHelp(): string {
|
||||
--full 允许全量输出大体积 JSON (绕过 200KB 防爆拦截)
|
||||
--stateless 单次强制以无状态模式执行
|
||||
--stateful 单次强制以有状态模式执行
|
||||
--yes, -y 确认执行会改变单据状态的审批动作
|
||||
--help, -h 查看帮助信息
|
||||
|
||||
常用示例:
|
||||
@@ -149,15 +155,42 @@ export function printHelp(): string {
|
||||
hose-use corps switch ID01MCcOgJl1td # 切换工作企业
|
||||
hose-use contact search 张三 # 模糊搜索员工工号、邮箱与电话
|
||||
hose-use contact list --limit=20 # 采样查看企业通讯录(带防爆截断保护)
|
||||
hose-use task todo --json # 查看当前待我审批任务
|
||||
hose-use task approved # 查看我已审批任务
|
||||
hose-use task submitted # 查看我发起的单据
|
||||
hose-use task cc --unread # 查看未读抄送
|
||||
hose-use message list --unread # 查看未读消息
|
||||
hose-use message list --all # 合并查看已读和未读消息
|
||||
hose-use message count # 查看未读消息数
|
||||
hose-use workflow list # 汇总查看全部工作流
|
||||
hose-use workflow find --task=code-js2 # 搜索包含自定义脚本的工作流
|
||||
hose-use bill list # 查看当前企业单据与报销列表
|
||||
hose-use bill flow S26000001 # 查看单据审批历史与后续节点
|
||||
hose-use bill risk S26000001 # 查看风控预警、预算与发票风险
|
||||
hose-use bill refs S26000001 # 二级解析提交人、部门、法人实体与费用类型引用
|
||||
hose-use bill relations S26000001 # 追溯冲借款、事前申请和合同关联
|
||||
hose-use bill budget S26000001 # 查看单据预算超限和预算接口状态
|
||||
hose-use bill attachments S26000001 # 查看单据附件和发票原件标准列表
|
||||
hose-use bill download S26000001 --output-dir ./downloads # 下载单据附件到本地目录
|
||||
hose-use dimension list # 查看系统与自定义档案维度
|
||||
hose-use dimension items 项目 # 查看项目档案项
|
||||
hose-use role list # 查看企业角色定义
|
||||
hose-use role groups # 查看角色组及其角色
|
||||
hose-use role members 财务主管 # 查看指定角色成员
|
||||
hose-use permission get # 查看角色权限开关
|
||||
hose-use bill link CL20260901001 # 获取单据 Web 详情直达免密跳转链接
|
||||
hose-use bill list --json -o /tmp/bills.json # 导出单据报文到本地磁盘并防爆
|
||||
hose-use bill get n0GMIM0dkQmKbS # 根据单号精准查询单据结构化详情
|
||||
hose-use bill get S26000001 --risk # 在详情中附加费控风控与发票风险快照
|
||||
hose-use bill approve S26000001 --yes # 同意待审批单据
|
||||
hose-use bill reject S26000001 --comment "金额不符" --yes # 驳回并填写原因
|
||||
hose-use bill transfer S26000001 --approver-id <员工ID> --yes # 转交审批
|
||||
hose-use bill add-node S26000001 --approver-id <员工ID> --mode pre --yes # 前加签
|
||||
hose-use bill comment S26000001 --comment "请补充发票" --yes # 添加单据评论
|
||||
hose-use http --port=8888 # 启动本地 HTTP 服务与可视化交互文档
|
||||
hose-use service start # 后台启动常驻守护进程服务
|
||||
hose-use service status # 查看守护进程运行状态与接口地址
|
||||
hose-use service poll --corp=<id> # 轮询待办/消息并持久化去重事件
|
||||
hose-use probe # 诊断当前企业鉴权连通性
|
||||
hose-use skill install # 安装 Agent 技能到用户目录
|
||||
hose-use update # 自动检查并升级到最新版本
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { runCli } from "./runner.js";
|
||||
import { VERSION } from "../version.js";
|
||||
|
||||
describe("CLI runner - version and help aliases", () => {
|
||||
const versionVariants = [
|
||||
["version"],
|
||||
["verSion"],
|
||||
["versioN"],
|
||||
["VERSION"],
|
||||
["Version"],
|
||||
["v"],
|
||||
["V"],
|
||||
["-v"],
|
||||
["-V"],
|
||||
["--version"],
|
||||
["--verSion"],
|
||||
["--VERSION"],
|
||||
["--v"],
|
||||
["--V"],
|
||||
];
|
||||
|
||||
for (const args of versionVariants) {
|
||||
it(`correctly outputs version for "${args.join(" ")}"`, async () => {
|
||||
const result = await runCli(args);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stderr).toBe("");
|
||||
expect(result.stdout).toBe(`hose-use v${VERSION}\n`);
|
||||
});
|
||||
}
|
||||
|
||||
const helpVariants = [
|
||||
[],
|
||||
["help"],
|
||||
["HeLp"],
|
||||
["HELP"],
|
||||
["h"],
|
||||
["H"],
|
||||
["-h"],
|
||||
["-H"],
|
||||
["--help"],
|
||||
["--HeLp"],
|
||||
["--HELP"],
|
||||
["?"],
|
||||
["-?"],
|
||||
];
|
||||
|
||||
for (const args of helpVariants) {
|
||||
it(`correctly outputs help for "${args.join(" ") || "<empty>"}"`, async () => {
|
||||
const result = await runCli(args);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stderr).toBe("");
|
||||
expect(result.stdout).toContain(`合思/易快报企业级 CLI 工具 (hose-use) v${VERSION}`);
|
||||
expect(result.stdout).toContain("用法:");
|
||||
});
|
||||
}
|
||||
|
||||
it("handles unknown commands gracefully", async () => {
|
||||
const result = await runCli(["unknown-command-xyz"]);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain("未知命令域: unknown-command-xyz");
|
||||
});
|
||||
});
|
||||
+54
-3
@@ -16,7 +16,12 @@ import { handleBillCommand } from "./commands/bill.js";
|
||||
import { handleContactCommand } from "./commands/contact.js";
|
||||
import { handleServiceCommand } from "./commands/service.js";
|
||||
import { handleHttpCommand } from "./commands/http.js";
|
||||
import type { CliResult, CliRunOptions } from "./types.js";
|
||||
import { handleTaskCommand } from "./commands/task.js";
|
||||
import { handleMessageCommand } from "./commands/message.js";
|
||||
import { handleDimensionCommand } from "./commands/dimension.js";
|
||||
import { handleRoleCommand } from "./commands/role.js";
|
||||
import { handlePermissionCommand } from "./commands/permission.js";
|
||||
import type { CliParsedArgs, CliResult, CliRunOptions } from "./types.js";
|
||||
|
||||
const STANDING_COMMANDS = new Set(["http", "server", "web", "mcp"]);
|
||||
|
||||
@@ -77,17 +82,43 @@ async function runCliOnce(
|
||||
}
|
||||
}
|
||||
|
||||
function isHelpRequested(parsed: CliParsedArgs): boolean {
|
||||
const normArea = (parsed.area || "").replace(/^-+/, "").toLowerCase();
|
||||
if (normArea === "help" || normArea === "h" || normArea === "?") return true;
|
||||
|
||||
for (const [key, val] of Object.entries(parsed.options)) {
|
||||
const normKey = key.replace(/^-+/, "").toLowerCase();
|
||||
if (normKey === "help" || normKey === "h" || normKey === "?") {
|
||||
if (val === true || val === "true" || val === "") return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isVersionRequested(parsed: CliParsedArgs): boolean {
|
||||
const normArea = (parsed.area || "").replace(/^-+/, "").toLowerCase();
|
||||
if (normArea === "version" || normArea === "v") return true;
|
||||
|
||||
for (const [key, val] of Object.entries(parsed.options)) {
|
||||
const normKey = key.replace(/^-+/, "").toLowerCase();
|
||||
if (normKey === "version" || normKey === "v") {
|
||||
if (val === true || val === "true" || val === "") return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
async function dispatchCli(
|
||||
rawArgs: string[],
|
||||
options: CliRunOptions = {}
|
||||
): Promise<CliResult> {
|
||||
const parsed = parseArgs(rawArgs);
|
||||
|
||||
if (booleanOption(parsed.options, ["help", "h"]) || parsed.area === "help") {
|
||||
if (isHelpRequested(parsed)) {
|
||||
return { stdout: printHelp() + "\n", stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
if (booleanOption(parsed.options, ["version", "v"]) || parsed.area === "version") {
|
||||
if (isVersionRequested(parsed)) {
|
||||
return { stdout: `hose-use v${VERSION}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
@@ -135,6 +166,26 @@ async function dispatchCli(
|
||||
case "staff":
|
||||
case "staffs":
|
||||
return await handleContactCommand(parsed, runtime);
|
||||
case "task":
|
||||
case "tasks":
|
||||
case "todo":
|
||||
return await handleTaskCommand(parsed, runtime);
|
||||
case "dimension":
|
||||
case "dimensions":
|
||||
case "archive":
|
||||
case "archives":
|
||||
return await handleDimensionCommand(parsed, runtime);
|
||||
case "role":
|
||||
case "roles":
|
||||
return await handleRoleCommand(parsed, runtime);
|
||||
case "permission":
|
||||
case "permissions":
|
||||
return await handlePermissionCommand(parsed, runtime);
|
||||
case "message":
|
||||
case "messages":
|
||||
case "notify":
|
||||
case "notifications":
|
||||
return await handleMessageCommand(parsed, runtime);
|
||||
case "platform":
|
||||
case "platforms":
|
||||
case "app":
|
||||
|
||||
+1
-1
@@ -39,7 +39,7 @@ export async function runServiceCommand(
|
||||
case undefined:
|
||||
return serviceStatus(config);
|
||||
default:
|
||||
throw new Error("用法: hose service <start|stop|restart|status|logs>");
|
||||
throw new Error("用法: hose service <start|stop|restart|status|logs|poll>");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -34,12 +34,13 @@ describe("embedded-skill - 多文件内嵌 Skill 体系", () => {
|
||||
try {
|
||||
const res = installSkillFiles(tmp);
|
||||
expect(res.targetDir).toBe(tmp);
|
||||
expect(res.files.length).toBe(7);
|
||||
expect(res.files.length).toBe(11);
|
||||
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", "bill.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "contact.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);
|
||||
} finally {
|
||||
|
||||
@@ -9,6 +9,10 @@ import refBill from "../../skills/hose-use/references/bill.md" with { type: "tex
|
||||
import refWorkflow from "../../skills/hose-use/references/workflow.md" with { type: "text" };
|
||||
import refService from "../../skills/hose-use/references/service.md" with { type: "text" };
|
||||
import refContact from "../../skills/hose-use/references/contact.md" with { type: "text" };
|
||||
import refTask from "../../skills/hose-use/references/task.md" with { type: "text" };
|
||||
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" };
|
||||
|
||||
export const EMBEDDED_SKILL_FILES: Record<string, string> = {
|
||||
"SKILL.md": skillMain,
|
||||
@@ -16,6 +20,10 @@ export const EMBEDDED_SKILL_FILES: Record<string, string> = {
|
||||
"references/auth.md": refAuth,
|
||||
"references/bill.md": refBill,
|
||||
"references/contact.md": refContact,
|
||||
"references/task.md": refTask,
|
||||
"references/message.md": refMessage,
|
||||
"references/dimension.md": refDimension,
|
||||
"references/role.md": refRole,
|
||||
"references/workflow.md": refWorkflow,
|
||||
"references/service.md": refService,
|
||||
};
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
# Bill 域说明
|
||||
|
||||
本目录负责合思/易快报(ekuaibao)费控单据、报销单、借款单、发票与数据实体元数据字典的检索与格式化。
|
||||
本目录负责合思/易快报(ekuaibao)费控单据、报销单、借款单、发票、关联引用、审批动作与数据实体元数据字典的检索、执行与格式化。
|
||||
|
||||
## 文件结构
|
||||
|
||||
```text
|
||||
src/domains/bill/
|
||||
├── api.ts # 传输层:调用 /api/v2/invoice/search, /api/v2/invoice, /api/v2/datalink/entity/search
|
||||
├── tools.ts # 业务编排层:DataLink 字段字典映射、单号匹配、格式化与 MCP tools
|
||||
├── api.ts # 传输层:调用单据、审批详情、审批动作、组织架构和费用类型目录 API
|
||||
├── tools.ts # 业务编排层:DataLink 字段字典映射、单号匹配、格式化与动作编排
|
||||
├── types.ts # 模型层:Zod Schema 与 TypeScript 类型定义
|
||||
├── bill.test.ts # 单元测试
|
||||
└── README.bill.md # 本说明文件
|
||||
@@ -22,3 +22,18 @@ src/domains/bill/
|
||||
- 根据业务单号(如 `n0GMIM0dkQmKbS`)或单据 ID(如 `ID01TRzg7HMLcb`)查询单据。
|
||||
3. **DataLink 字段元数据字典 (`getFieldDictionary`)**:
|
||||
- 自动拉取企业全部实体模型定义,将混淆代码字段(如 `E_ae10..._payMoney`)还原为人类友好的中文字段名(如 `报销金额`)。
|
||||
4. **关联引用二级解析 (`getBillReferences`)**:
|
||||
- 通过审批详情、组织架构和费用类型目录批量解析提交人、归属人、费用承担部门与费用类型;
|
||||
- 保留原始 ID,并在 JSON 中提供 `name`、`code`、部门 `path` 与未解析 ID;目录在进程内按企业缓存 10 分钟。
|
||||
5. **单据关联链 (`getBillRelations`)**:
|
||||
- 从审批详情中的 `expenseLink`、`loan`、`requisition`、`contract` 等关系字段抽取前置单据树,保留原始对象供 JSON 下钻。
|
||||
6. **附件标准化 (`getBillAttachments`)**:
|
||||
- 递归识别表单中的 `attachments`、`fileId`、`fileName`、`key` 与原件 URL,统一输出附件清单并去重。
|
||||
7. **审批动作套件**:
|
||||
- `approveBill` 调用 `POST /api/flow/v2/backlogs/$<backlogId>`,使用 `freeflow.agree` 节点报文;
|
||||
- `rejectBill` 调用 `POST /api/flow/v2/backlogs/approveListWithNode`,使用 `freeflow.reject` 批量报文,评论会转为 `<p>...</p>`;
|
||||
- `transferBill` 与 `addNodeBill` 共用 backlog 动作接口,分别使用 `SHIFT_NODE`、`PRE_ADD_NODE`/`AFT_ADD_NODE`;
|
||||
- `commentBill` 调用 `POST /api/flow/v1/flows/comment/$<flowId>`,使用 `freeflow.comment`,保留参与人和私密评论参数;
|
||||
- 动作执行前从审批详情解析 backlog ID、流程 ID、当前节点 ID,并可依据 `flow.actions` 校验当前身份是否具备该动作权限。
|
||||
|
||||
CLI 入口为 `hose bill approve|reject|transfer|add-node|comment <单号|ID>`。所有会改变状态的动作都要求 `--yes`(交互终端未提供时会拒绝执行);转交和加签的 `--approver-id` 支持完整员工 ID、工号或唯一姓名匹配,驳回强制要求 `--comment`。
|
||||
@@ -1,4 +1,5 @@
|
||||
import { KyInstance } from "ky";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
RawBillSearchResponseSchema,
|
||||
RawBillBatchGetResponseSchema,
|
||||
@@ -8,6 +9,305 @@ import {
|
||||
type EntityMeta,
|
||||
} from "./types.js";
|
||||
|
||||
function quoted(value: string): string {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
function flowLookupSelect(): string {
|
||||
return "flowId(form(code,title),`...`),`...`";
|
||||
}
|
||||
|
||||
function flowDetailSelect(): string {
|
||||
return "flowId(form(`...`),logs(operatorId,nextOperatorId,`...`),plan(`...`),`...`),`...`";
|
||||
}
|
||||
|
||||
export async function listActiveStaffCatalog(
|
||||
client: KyInstance,
|
||||
corpId: string
|
||||
): Promise<Record<string, unknown>[]> {
|
||||
const response = await client.get("api/v1/organization/staffs/actives", {
|
||||
searchParams: { start: "0", count: "2999", corpId },
|
||||
});
|
||||
const json = (await response.json()) as { items?: unknown[] };
|
||||
return Array.isArray(json.items) ? json.items.filter((item): item is Record<string, unknown> => Boolean(item && typeof item === "object")) : [];
|
||||
}
|
||||
|
||||
export async function getDepartmentTree(
|
||||
client: KyInstance,
|
||||
corpId: string
|
||||
): Promise<Record<string, unknown>[]> {
|
||||
const response = await client.get("api/v1/organization/departments/tree/actives", {
|
||||
searchParams: { corpId },
|
||||
});
|
||||
const json = (await response.json()) as { items?: unknown[] } | unknown[];
|
||||
if (Array.isArray(json)) return json.filter((item): item is Record<string, unknown> => Boolean(item && typeof item === "object"));
|
||||
return Array.isArray(json.items) ? json.items.filter((item): item is Record<string, unknown> => Boolean(item && typeof item === "object")) : [];
|
||||
}
|
||||
|
||||
export async function getFeeTypeTree(
|
||||
client: KyInstance,
|
||||
corpId: string
|
||||
): Promise<Record<string, unknown>[]> {
|
||||
const response = await client.get("api/v1/form/feeTypes/tree/active", {
|
||||
searchParams: { corpId },
|
||||
});
|
||||
const json = (await response.json()) as { items?: unknown[] } | unknown[];
|
||||
if (Array.isArray(json)) return json.filter((item): item is Record<string, unknown> => Boolean(item && typeof item === "object"));
|
||||
return Array.isArray(json.items) ? json.items.filter((item): item is Record<string, unknown> => Boolean(item && typeof item === "object")) : [];
|
||||
}
|
||||
|
||||
export async function getRawBillFlow(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string
|
||||
): Promise<Record<string, unknown> | undefined> {
|
||||
let match: Record<string, unknown> | undefined;
|
||||
const filters = [
|
||||
`(id==${quoted(target)})||((flowId.id==${quoted(target)})||(flowId.form.code==${quoted(target)}))`,
|
||||
`(state.in("APPROVING","PROCESSED","REJECTED","DRAFT"))`,
|
||||
];
|
||||
for (const filterBy of filters) {
|
||||
try {
|
||||
const lookup = await client.post("api/flow/v2/backlogs/search", {
|
||||
searchParams: { corpId },
|
||||
json: {
|
||||
filterBy,
|
||||
limit: { start: 0, count: 100 },
|
||||
select: flowLookupSelect(),
|
||||
},
|
||||
});
|
||||
const lookupJson = (await lookup.json()) as { items?: Record<string, unknown>[] };
|
||||
match = (lookupJson.items ?? []).find((item) => {
|
||||
const flow = item.flowId && typeof item.flowId === "object" ? item.flowId as Record<string, unknown> : {};
|
||||
const form = flow.form && typeof flow.form === "object" ? flow.form as Record<string, unknown> : {};
|
||||
return item.id === target || flow.id === target || form.code === target;
|
||||
});
|
||||
if (match) break;
|
||||
} catch {
|
||||
// Fall through to the broad status lookup or direct detail request.
|
||||
}
|
||||
}
|
||||
const backlogId = typeof match?.id === "string" ? match.id : target;
|
||||
|
||||
const detail = await client.post("api/flow/v2/backlogs/id", {
|
||||
searchParams: (() => {
|
||||
const params = new URLSearchParams({ corpId });
|
||||
for (const join of [
|
||||
"flowId.form.submitterId,submitterId,/v1/organization/staffs?join=defaultDepartment,defaultDepartment,/v1/organization/departments",
|
||||
"flowId.form.ownerId,ownerId,/v1/organization/staffs?select=id,name,code",
|
||||
"flowId.form.expenseDepartment,expenseDepartment,/v1/organization/departments",
|
||||
"flowId.logs.operatorId,operatorId,/v1/organization/staffs?select=id,name,code",
|
||||
"flowId.logs.nextOperatorId,nextOperatorId,/v1/organization/staffs?select=id,name,code",
|
||||
"flowId.plan.nodes.approverId,approverId,/v1/organization/staffs?select=id,name,code",
|
||||
"flowId.plan.nodes.counterSigners.signerId,signerId,/v1/organization/staffs?select=id,name,code",
|
||||
]) params.append("join", join);
|
||||
return params;
|
||||
})(),
|
||||
json: {
|
||||
filterBy: `(id==${quoted(backlogId)})`,
|
||||
select: flowDetailSelect(),
|
||||
},
|
||||
});
|
||||
const json = (await detail.json()) as { value?: Record<string, unknown>; items?: Record<string, unknown>[] };
|
||||
return json.value ?? json.items?.[0];
|
||||
}
|
||||
|
||||
export interface BillActionTarget {
|
||||
backlogId: string;
|
||||
flowId: string;
|
||||
billId?: string;
|
||||
billCode?: string;
|
||||
nodeId?: string;
|
||||
nodeName?: string;
|
||||
raw: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface BillActionOptions {
|
||||
currentStaffId?: string;
|
||||
reminder?: boolean;
|
||||
keepItSecret?: boolean;
|
||||
comment?: string;
|
||||
participants?: string[];
|
||||
approverIds?: string[];
|
||||
rejectTo?: string | null;
|
||||
resubmitMethod?: string;
|
||||
addNodeType?: "PRE_ADD_NODE" | "AFT_ADD_NODE";
|
||||
}
|
||||
|
||||
async function readActionResponse(response: Response): Promise<unknown> {
|
||||
if (response.status === 204) return undefined;
|
||||
const text = await response.text();
|
||||
if (!text) return undefined;
|
||||
try {
|
||||
return JSON.parse(text) as unknown;
|
||||
} catch {
|
||||
return text;
|
||||
}
|
||||
}
|
||||
|
||||
function htmlComment(comment: string | undefined): string {
|
||||
const value = comment ?? "";
|
||||
return `<p>${value
|
||||
.replaceAll("&", "&")
|
||||
.replaceAll("<", "<")
|
||||
.replaceAll(">", ">")
|
||||
.replaceAll('"', """)
|
||||
.replaceAll("'", "'")}</p>`;
|
||||
}
|
||||
|
||||
function backlogSearchParams(corpId: string): Record<string, string> {
|
||||
return { messageCode: "debug", corpId };
|
||||
}
|
||||
|
||||
export async function approveBillAction(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: BillActionTarget,
|
||||
options: BillActionOptions = {},
|
||||
): Promise<unknown> {
|
||||
const response = await client.post(`api/flow/v2/backlogs/$${target.backlogId}`, {
|
||||
searchParams: backlogSearchParams(corpId),
|
||||
json: {
|
||||
node: {
|
||||
flowId: target.flowId,
|
||||
id: target.nodeId,
|
||||
name: "freeflow.agree",
|
||||
},
|
||||
reminder: options.reminder ?? false,
|
||||
keepItSecret: options.keepItSecret ?? false,
|
||||
comment: options.comment ?? "",
|
||||
participants: options.participants ?? [],
|
||||
isSingle: true,
|
||||
id: target.backlogId,
|
||||
name: "freeflow.agree",
|
||||
},
|
||||
});
|
||||
return readActionResponse(response);
|
||||
}
|
||||
|
||||
export async function rejectBillAction(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: BillActionTarget,
|
||||
options: BillActionOptions = {},
|
||||
): Promise<unknown> {
|
||||
const response = await client.post("api/flow/v2/backlogs/approveListWithNode", {
|
||||
searchParams: backlogSearchParams(corpId),
|
||||
json: {
|
||||
data: [{
|
||||
id: target.backlogId,
|
||||
resubmitMethod: options.resubmitMethod ?? "TO_REJECTOR",
|
||||
reminder: options.reminder ?? false,
|
||||
keepItSecret: options.keepItSecret ?? false,
|
||||
rejectTo: options.rejectTo ?? null,
|
||||
comment: htmlComment(options.comment),
|
||||
participants: options.participants ?? [],
|
||||
name: "freeflow.reject",
|
||||
}],
|
||||
},
|
||||
});
|
||||
return readActionResponse(response);
|
||||
}
|
||||
|
||||
export async function transferBillAction(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: BillActionTarget,
|
||||
options: BillActionOptions = {},
|
||||
): Promise<unknown> {
|
||||
const response = await client.post(`api/flow/v2/backlogs/$${target.backlogId}`, {
|
||||
searchParams: backlogSearchParams(corpId),
|
||||
json: {
|
||||
reminder: options.reminder ?? false,
|
||||
keepItSecret: options.keepItSecret ?? false,
|
||||
approverId: options.approverIds ?? [],
|
||||
type: "SHIFT_NODE",
|
||||
autographImageId: "",
|
||||
comment: options.comment ? htmlComment(options.comment) : "",
|
||||
participants: options.participants ?? [],
|
||||
id: target.backlogId,
|
||||
name: "freeflow.addnode",
|
||||
},
|
||||
});
|
||||
return readActionResponse(response);
|
||||
}
|
||||
|
||||
export async function addNodeBillAction(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: BillActionTarget,
|
||||
options: BillActionOptions = {},
|
||||
): Promise<unknown> {
|
||||
const response = await client.post(`api/flow/v2/backlogs/$${target.backlogId}`, {
|
||||
searchParams: backlogSearchParams(corpId),
|
||||
json: {
|
||||
reminder: options.reminder ?? false,
|
||||
keepItSecret: options.keepItSecret ?? false,
|
||||
approverId: options.approverIds ?? [],
|
||||
type: options.addNodeType ?? "PRE_ADD_NODE",
|
||||
autographImageId: "",
|
||||
comment: htmlComment(options.comment),
|
||||
participants: options.participants ?? [],
|
||||
id: target.backlogId,
|
||||
name: "freeflow.addnode",
|
||||
},
|
||||
});
|
||||
return readActionResponse(response);
|
||||
}
|
||||
|
||||
export async function commentBillAction(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: BillActionTarget,
|
||||
options: BillActionOptions = {},
|
||||
): Promise<unknown> {
|
||||
const response = await client.post(`api/flow/v1/flows/comment/$${target.flowId}`, {
|
||||
searchParams: { messageCode: "debug", corpId },
|
||||
json: {
|
||||
id: target.flowId,
|
||||
params: {
|
||||
comment: htmlComment(options.comment),
|
||||
participants: options.participants ?? [],
|
||||
attachments: [],
|
||||
keepItSecret: options.keepItSecret ?? false,
|
||||
},
|
||||
name: "freeflow.comment",
|
||||
},
|
||||
});
|
||||
return readActionResponse(response);
|
||||
}
|
||||
|
||||
export async function getRawBillRisk(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
flowId: string,
|
||||
submitterId?: string
|
||||
): Promise<Record<string, unknown>> {
|
||||
const searchParams = (extra: Record<string, string> = {}) => ({ corpId, ...extra });
|
||||
const requests: Array<Promise<unknown>> = [
|
||||
client.get("api/credit/v2/model", { searchParams: searchParams() }).then((response) => response.json()),
|
||||
client.get(`api/credit/v2/rules/byFlowId/withGroup/$${flowId}`, { searchParams: searchParams({ flowId }) }).then((response) => response.json()),
|
||||
client.get(`api/credit/v2/notes/byFlowId/$${flowId}`, { searchParams: searchParams({ flowId }) }).then((response) => response.json()),
|
||||
client.get(`api/flow/v2/riskwarning/coalition/info/$${flowId}`, { searchParams: searchParams({ flowId, privilegeId: "", newUI: "v2" }) }).then((response) => response.json()),
|
||||
client.get(`api/flow/v3/riskwarning/invoice/riskWarning/[${flowId}]`, { searchParams: searchParams({ flowId }) }).then((response) => response.json()),
|
||||
client.get(`api/v1/budget/report/flow/$${flowId}/status`, { searchParams: searchParams({ id: flowId }) }).then((response) => response.json()),
|
||||
];
|
||||
if (submitterId) {
|
||||
requests.push(client.get(`api/credit/v2/stafflog/point/$${submitterId}`, { searchParams: searchParams({ submitterId }) }).then((response) => response.json()));
|
||||
}
|
||||
const results = await Promise.allSettled(requests);
|
||||
const values = results.map((result) => result.status === "fulfilled" ? result.value : {});
|
||||
return {
|
||||
creditModel: values[0] as Record<string, unknown>,
|
||||
rules: values[1] as Record<string, unknown>,
|
||||
notes: values[2] as Record<string, unknown>,
|
||||
coalition: values[3] as Record<string, unknown>,
|
||||
invoice: values[4] as Record<string, unknown>,
|
||||
budget: values[5] as Record<string, unknown>,
|
||||
staff: (submitterId ? values[6] : {}) as Record<string, unknown>,
|
||||
};
|
||||
}
|
||||
|
||||
// ── 原始单据检索 API ──────────────────────────────────────────────────────────
|
||||
|
||||
export async function searchRawBills(
|
||||
@@ -48,6 +348,33 @@ export async function getRawBillsByIds(
|
||||
return parsed.items;
|
||||
}
|
||||
|
||||
// ── 附件文件元数据与签名下载地址 API ──────────────────────────────────────────
|
||||
|
||||
const AttachmentFileSchema = z.object({
|
||||
id: z.string(),
|
||||
key: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
url: z.string().optional(),
|
||||
thumbUrl: z.string().optional(),
|
||||
});
|
||||
|
||||
export type AttachmentFile = z.infer<typeof AttachmentFileSchema>;
|
||||
|
||||
export async function resolveAttachmentFiles(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
ids: string[],
|
||||
): Promise<AttachmentFile[]> {
|
||||
if (ids.length === 0) return [];
|
||||
|
||||
const response = await client.post("api/v1/attachment/attachments/ids", {
|
||||
searchParams: { corpId },
|
||||
json: { ids },
|
||||
});
|
||||
const json = (await response.json()) as { items?: unknown[] };
|
||||
return z.array(AttachmentFileSchema).parse(json.items ?? []);
|
||||
}
|
||||
|
||||
// ── 单据实体与字段元数据字典 API ───────────────────────────────────────────────
|
||||
|
||||
export async function listEntitySchemas(
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from "bun:test";
|
||||
import { formatSingleBill } from "./tools.js";
|
||||
import { formatSingleBill, getBillReferences, getBillRelations, getBillAttachments, getBillRisk, getBillFlow, approveBill, rejectBill, transferBill, addNodeBill, commentBill, resolveBillStaffIds } from "./tools.js";
|
||||
import { RawBillItemSchema, EntitySchema } from "./types.js";
|
||||
|
||||
describe("Bill Domain", () => {
|
||||
@@ -66,4 +66,219 @@ describe("Bill Domain", () => {
|
||||
expect(formatted.amount).toBe("¥100.00 CNY");
|
||||
expect(formatted.details["客户等级"]).toBe("VIP客户");
|
||||
});
|
||||
|
||||
it("resolves approval references from staff, department and fee type catalogs", async () => {
|
||||
const responses = [
|
||||
{
|
||||
id: "backlog-1",
|
||||
state: "APPROVING",
|
||||
flowId: {
|
||||
id: "flow-1",
|
||||
form: {
|
||||
code: "S26000001",
|
||||
title: "团建申请",
|
||||
submitterId: "corp:staff-1",
|
||||
expenseDepartment: "corp:dept-2",
|
||||
details: { feeTypeId: "fee-1" },
|
||||
},
|
||||
},
|
||||
},
|
||||
];
|
||||
const client = {
|
||||
post: async () => new Response(JSON.stringify({ items: responses })),
|
||||
get: async (path: string) => {
|
||||
if (path.includes("staffs/actives")) {
|
||||
return new Response(JSON.stringify({ items: [{ id: "corp:staff-1", userId: "staff-1", name: "张三", code: "1001" }] }));
|
||||
}
|
||||
if (path.includes("departments/tree")) {
|
||||
return new Response(JSON.stringify({ items: [{ id: "corp", name: "总公司", children: [{ id: "corp:dept-2", name: "研发部", children: [] }] }] }));
|
||||
}
|
||||
return new Response(JSON.stringify({ items: [{ id: "fee-1", name: "差旅费", code: "COST01", children: [] }] }));
|
||||
},
|
||||
} as any;
|
||||
|
||||
const result = await getBillReferences(client, "corp", "S26000001");
|
||||
expect(result?.submitter?.name).toBe("张三");
|
||||
expect(result?.department?.path).toBe("总公司/研发部");
|
||||
expect(result?.feeTypes[0]?.name).toBe("差旅费");
|
||||
expect(result?.unresolved).toEqual([]);
|
||||
});
|
||||
|
||||
it("extracts linked loan and requisition nodes as a relation tree", async () => {
|
||||
const client = {
|
||||
post: async () => new Response(JSON.stringify({ value: {
|
||||
id: "backlog-2",
|
||||
flowId: {
|
||||
id: "flow-2",
|
||||
form: {
|
||||
code: "E26000001",
|
||||
title: "费用报销",
|
||||
expenseLink: { id: "loan-1", code: "J26000001", title: "员工借款", loanMoney: { standard: "500" } },
|
||||
linkRequisitionInfo: { id: "req-1", code: "Q26000001", title: "出差申请" },
|
||||
},
|
||||
},
|
||||
} })),
|
||||
} as any;
|
||||
const result = await getBillRelations(client, "corp-relations", "E26000001");
|
||||
expect(result?.relations.map((item) => item.id)).toEqual(["loan-1", "req-1"]);
|
||||
expect(result?.relations[0]?.amount).toContain("500");
|
||||
});
|
||||
|
||||
it("normalizes nested bill attachments and removes duplicates", async () => {
|
||||
const client = {
|
||||
post: async () => new Response(JSON.stringify({ value: {
|
||||
id: "backlog-3",
|
||||
flowId: {
|
||||
form: {
|
||||
code: "E26000002",
|
||||
title: "带附件报销",
|
||||
attachments: [
|
||||
{ fileId: "file-1", key: "receipt.pdf", fileName: "receipt.pdf" },
|
||||
{ fileId: "file-1", key: "receipt.pdf", fileName: "receipt.pdf" },
|
||||
],
|
||||
},
|
||||
},
|
||||
} })),
|
||||
} as any;
|
||||
const result = await getBillAttachments(client, "corp-files", "E26000002");
|
||||
expect(result?.attachments).toHaveLength(1);
|
||||
expect(result?.attachments[0]?.fileId).toBe("file-1");
|
||||
expect(result?.attachments[0]?.fileName).toBe("receipt.pdf");
|
||||
});
|
||||
|
||||
it("enriches attachment metadata with file-service download URLs", async () => {
|
||||
const client = {
|
||||
post: async (path: string) => {
|
||||
if (path.includes("attachment/attachments/ids")) {
|
||||
return new Response(JSON.stringify({
|
||||
items: [{ id: "file-2", key: "receipt-key", name: "receipt.pdf", url: "https://files.example/receipt.pdf", thumbUrl: "https://files.example/thumb" }],
|
||||
}));
|
||||
}
|
||||
if (path.includes("backlogs/search")) {
|
||||
return new Response(JSON.stringify({ items: [{ id: "backlog-4", flowId: { form: { code: "E26000003", title: "附件元数据", attachments: [{ fileId: "file-2" }] } } }] }));
|
||||
}
|
||||
return new Response(JSON.stringify({ value: { id: "backlog-4", flowId: { form: { code: "E26000003", title: "附件元数据", attachments: [{ fileId: "file-2" }] } } } }));
|
||||
},
|
||||
} as any;
|
||||
const result = await getBillAttachments(client, "corp-files", "E26000003");
|
||||
expect(result?.attachments[0]).toMatchObject({
|
||||
fileId: "file-2",
|
||||
fileName: "receipt.pdf",
|
||||
key: "receipt-key",
|
||||
url: "https://files.example/receipt.pdf",
|
||||
thumbUrl: "https://files.example/thumb",
|
||||
});
|
||||
});
|
||||
|
||||
it("normalizes risk warnings, budget state and invoice warnings", async () => {
|
||||
const client = {
|
||||
post: async (path: string) => {
|
||||
if (path.includes("backlogs/search")) {
|
||||
return new Response(JSON.stringify({ items: [{ id: "backlog-risk", flowId: { id: "flow-risk", form: { code: "S26000004", submitterId: { id: "staff-1" } } } }] }));
|
||||
}
|
||||
return new Response(JSON.stringify({ value: { id: "backlog-risk", flowId: { id: "flow-risk", form: { code: "S26000004", submitterId: { id: "staff-1" } } } } }));
|
||||
},
|
||||
get: async (path: string) => {
|
||||
if (path.includes("coalition")) return new Response(JSON.stringify({ riskWarning: [{ riskLevel: "WARNING", controlName: "重复报销", messages: ["命中测试规则"] }] }));
|
||||
if (path.includes("budget/report")) return new Response(JSON.stringify({ value: true, status: "OVER" }));
|
||||
if (path.includes("invoice/riskWarning")) return new Response(JSON.stringify({ items: [{ type: "invoice", message: "发票抬头不一致" }] }));
|
||||
return new Response(JSON.stringify({}));
|
||||
},
|
||||
} as any;
|
||||
const result = await getBillRisk(client, "corp-risk", "S26000004");
|
||||
expect(result?.flowId).toBe("flow-risk");
|
||||
expect(result?.budgetExceeded).toBe(true);
|
||||
expect(result?.warnings[0]?.controlName).toBe("重复报销");
|
||||
expect(result?.invoiceWarnings).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("calculates approval-node dwell time and automatic skip markers", async () => {
|
||||
const client = {
|
||||
post: async (path: string) => {
|
||||
if (path.includes("backlogs/search")) {
|
||||
return new Response(JSON.stringify({ items: [{ id: "backlog-flow", flowId: { id: "flow-flow", form: { code: "S26000005", title: "流程时长" } } }] }));
|
||||
}
|
||||
return new Response(JSON.stringify({ value: { id: "backlog-flow", state: "APPROVING", nodeName: "财务审批", flowId: { id: "flow-flow", form: { code: "S26000005", title: "流程时长" }, logs: [
|
||||
{ id: "log-1", time: 1000, operatorId: "staff-1", attributes: { nodeName: "提交" } },
|
||||
{ id: "log-2", time: 2500, operatorId: null, state: "SKIPPED", attributes: { nodeName: "自动校验", isAuto: true, isSkip: true } },
|
||||
], plan: { nodes: [] } } } }));
|
||||
},
|
||||
} as any;
|
||||
const result = await getBillFlow(client, "corp-flow", "S26000005");
|
||||
expect(result?.history[0]?.durationMs).toBe(1500);
|
||||
expect(result?.history[1]?.automatic).toBe(true);
|
||||
expect(result?.history[1]?.skipped).toBe(true);
|
||||
});
|
||||
|
||||
it("builds the captured approve, reject, transfer, add-node and comment payloads", async () => {
|
||||
const calls: Array<{ path: string; options: any }> = [];
|
||||
const client = {
|
||||
post: async (path: string, options: any) => {
|
||||
calls.push({ path, options });
|
||||
if (path.includes("backlogs/search")) {
|
||||
return new Response(JSON.stringify({ items: [{ id: "backlog-action", flowId: { id: "flow-action", form: { code: "E26000007" } } }] }));
|
||||
}
|
||||
if (path.includes("backlogs/id")) {
|
||||
return new Response(JSON.stringify({ value: {
|
||||
id: "backlog-action",
|
||||
nodeId: "FLOW:node-action",
|
||||
nodeName: "直接领导审批",
|
||||
state: "APPROVING",
|
||||
flowId: { id: "flow-action", form: { code: "E26000007" }, plan: { nodes: [] } },
|
||||
} }));
|
||||
}
|
||||
return new Response(null, { status: 204 });
|
||||
},
|
||||
} as any;
|
||||
|
||||
await approveBill(client, "corp-action", "E26000007", { comment: "同意" });
|
||||
const approveCall = calls.at(-1);
|
||||
expect(approveCall?.path).toBe("api/flow/v2/backlogs/$backlog-action");
|
||||
expect(approveCall?.options.json).toMatchObject({
|
||||
node: { flowId: "flow-action", id: "FLOW:node-action", name: "freeflow.agree" },
|
||||
comment: "同意",
|
||||
name: "freeflow.agree",
|
||||
});
|
||||
|
||||
await rejectBill(client, "corp-action", "E26000007", { comment: "金额 < 不符" });
|
||||
expect(calls.at(-1)?.path).toBe("api/flow/v2/backlogs/approveListWithNode");
|
||||
expect(calls.at(-1)?.options.json.data[0]).toMatchObject({
|
||||
id: "backlog-action",
|
||||
comment: "<p>金额 < 不符</p>",
|
||||
name: "freeflow.reject",
|
||||
});
|
||||
|
||||
await transferBill(client, "corp-action", "E26000007", { approverIds: ["staff-2"] });
|
||||
expect(calls.at(-1)?.options.json).toMatchObject({
|
||||
approverId: ["staff-2"],
|
||||
type: "SHIFT_NODE",
|
||||
name: "freeflow.addnode",
|
||||
});
|
||||
|
||||
await addNodeBill(client, "corp-action", "E26000007", { approverIds: ["staff-3"], comment: "请协助", addNodeType: "AFT_ADD_NODE" });
|
||||
expect(calls.at(-1)?.options.json).toMatchObject({
|
||||
approverId: ["staff-3"],
|
||||
type: "AFT_ADD_NODE",
|
||||
comment: "<p>请协助</p>",
|
||||
name: "freeflow.addnode",
|
||||
});
|
||||
|
||||
await commentBill(client, "corp-action", "E26000007", { comment: "补充说明" });
|
||||
expect(calls.at(-1)?.path).toBe("api/flow/v1/flows/comment/$flow-action");
|
||||
expect(calls.at(-1)?.options.json).toMatchObject({
|
||||
id: "flow-action",
|
||||
params: { comment: "<p>补充说明</p>", participants: [], attachments: [], keepItSecret: false },
|
||||
name: "freeflow.comment",
|
||||
});
|
||||
});
|
||||
|
||||
it("resolves transfer and add-node people by full ID, employee code or unique name", async () => {
|
||||
const client = {
|
||||
get: async () => new Response(JSON.stringify({ items: [
|
||||
{ id: "corp:staff-1", userId: "user-1", code: "101", name: "谢子豪" },
|
||||
{ id: "corp:staff-2", userId: "user-2", code: "111", name: "沈玥妍" },
|
||||
] })),
|
||||
} as any;
|
||||
await expect(resolveBillStaffIds(client, "corp-action", ["111", "谢子豪"])).resolves.toEqual(["corp:staff-2", "corp:staff-1"]);
|
||||
});
|
||||
});
|
||||
+745
-1
@@ -1,15 +1,47 @@
|
||||
import { z } from "zod";
|
||||
import { KyInstance } from "ky";
|
||||
import { searchRawBills, getRawBillsByIds, listEntitySchemas } from "./api.js";
|
||||
import { existsSync } from "node:fs";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { basename, extname, join, resolve } from "node:path";
|
||||
import {
|
||||
searchRawBills,
|
||||
getRawBillsByIds,
|
||||
listEntitySchemas,
|
||||
getRawBillFlow,
|
||||
getRawBillRisk,
|
||||
listActiveStaffCatalog,
|
||||
getDepartmentTree,
|
||||
getFeeTypeTree,
|
||||
resolveAttachmentFiles,
|
||||
approveBillAction,
|
||||
rejectBillAction,
|
||||
transferBillAction,
|
||||
addNodeBillAction,
|
||||
commentBillAction,
|
||||
type BillActionOptions,
|
||||
type BillActionTarget,
|
||||
} from "./api.js";
|
||||
import {
|
||||
type RawBillItem,
|
||||
type FormattedBill,
|
||||
type BillPageResult,
|
||||
type EntityMeta,
|
||||
type BillQueryParams,
|
||||
type BillFlowEntry,
|
||||
type BillFlowNode,
|
||||
type BillFlowTimeline,
|
||||
type BillRiskReport,
|
||||
type BillRiskWarning,
|
||||
type BillReference,
|
||||
type BillReferenceReport,
|
||||
type BillRelationNode,
|
||||
type BillRelationsReport,
|
||||
type BillAttachment,
|
||||
type BillAttachmentReport,
|
||||
} from "./types.js";
|
||||
import { CorpContext } from "../../core/config/manager.js";
|
||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||
import { resolveDimension } from "../dimension/tools.js";
|
||||
|
||||
// ── 通用内置字段中文 Label 字典 ───────────────────────────────────────────────
|
||||
|
||||
@@ -63,6 +95,15 @@ const COMMON_FIELD_LABELS: Record<string, string> = {
|
||||
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 = {
|
||||
timestamp: number;
|
||||
staff: Map<string, Record<string, unknown>>;
|
||||
departments: Map<string, { item: Record<string, unknown>; path: string }>;
|
||||
feeTypes: Map<string, Record<string, unknown>>;
|
||||
};
|
||||
|
||||
const referenceCatalogCache = new Map<string, ReferenceCatalog>();
|
||||
|
||||
export async function getFieldDictionary(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
@@ -89,6 +130,436 @@ export async function getFieldDictionary(
|
||||
return result;
|
||||
}
|
||||
|
||||
function referenceId(value: unknown): string | undefined {
|
||||
if (typeof value === "string" && value.trim()) return value.trim();
|
||||
if (!value || typeof value !== "object") return undefined;
|
||||
const id = (value as Record<string, unknown>).id;
|
||||
return typeof id === "string" && id.trim() ? id.trim() : undefined;
|
||||
}
|
||||
|
||||
function referenceObject(value: unknown): 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 }> {
|
||||
for (const item of items) {
|
||||
const name = typeof item.name === "string" ? item.name : "";
|
||||
const path = name ? (parentPath ? `${parentPath}/${name}` : name) : parentPath;
|
||||
const id = typeof item.id === "string" ? item.id : undefined;
|
||||
if (id) output.set(id, { item, path });
|
||||
const children = Array.isArray(item.children)
|
||||
? item.children.filter((child): child is Record<string, unknown> => Boolean(child && typeof child === "object"))
|
||||
: [];
|
||||
flattenDepartments(children, path, output);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
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;
|
||||
if (id) output.set(id, feeType);
|
||||
const children = Array.isArray(item.children)
|
||||
? item.children.filter((child): child is Record<string, unknown> => Boolean(child && typeof child === "object"))
|
||||
: [];
|
||||
flattenFeeTypes(children, output);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
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 staff = new Map<string, Record<string, unknown>>();
|
||||
for (const item of 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 = {
|
||||
timestamp: Date.now(),
|
||||
staff,
|
||||
departments: flattenDepartments(departments),
|
||||
feeTypes: flattenFeeTypes(feeTypes),
|
||||
};
|
||||
referenceCatalogCache.set(corpId, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
function toReference(
|
||||
value: unknown,
|
||||
kind: BillReference["kind"],
|
||||
source: BillReference["source"],
|
||||
catalog?: Record<string, unknown>,
|
||||
path?: string,
|
||||
): BillReference | undefined {
|
||||
const id = referenceId(value);
|
||||
if (!id) return undefined;
|
||||
const object = referenceObject(value);
|
||||
const sourceObject = object ?? catalog;
|
||||
return {
|
||||
id,
|
||||
name: typeof sourceObject?.name === "string" ? sourceObject.name : undefined,
|
||||
code: typeof sourceObject?.code === "string" ? sourceObject.code : undefined,
|
||||
path,
|
||||
kind,
|
||||
source,
|
||||
};
|
||||
}
|
||||
|
||||
function collectFeeTypeIds(value: unknown, output = new Set<string>()): Set<string> {
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) collectFeeTypeIds(item, output);
|
||||
return output;
|
||||
}
|
||||
if (!value || typeof value !== "object") return output;
|
||||
for (const [key, nested] of Object.entries(value as Record<string, unknown>)) {
|
||||
if (key === "feeTypeId" || key.endsWith("_feeTypeId")) {
|
||||
const id = referenceId(nested);
|
||||
if (id) output.add(id);
|
||||
}
|
||||
collectFeeTypeIds(nested, output);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
export async function getBillReferences(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string,
|
||||
): Promise<BillReferenceReport | undefined> {
|
||||
const raw = await getRawBillFlow(client, corpId, target);
|
||||
if (!raw || !raw.flowId || typeof raw.flowId !== "object") return undefined;
|
||||
const flow = raw.flowId as Record<string, unknown>;
|
||||
const form = flow.form && typeof flow.form === "object" ? flow.form as Record<string, unknown> : {};
|
||||
const catalog = await getReferenceCatalog(client, corpId);
|
||||
const unresolved: string[] = [];
|
||||
const resolveStaff = (value: unknown, fallbackKind: BillReference["kind"]): BillReference | undefined => {
|
||||
const id = referenceId(value);
|
||||
if (!id) return undefined;
|
||||
const found = catalog.staff.get(id) ?? catalog.staff.get(id.split(":").at(-1) ?? id);
|
||||
const reference = toReference(value, fallbackKind, found ? "catalog" : "raw", found);
|
||||
if (!reference?.name) unresolved.push(id);
|
||||
return reference;
|
||||
};
|
||||
const departmentValue = form.expenseDepartment;
|
||||
const departmentId = referenceId(departmentValue);
|
||||
const departmentFound = departmentId ? catalog.departments.get(departmentId) ?? catalog.departments.get(departmentId.split(":").at(-1) ?? departmentId) : undefined;
|
||||
const department = toReference(departmentValue, "department", departmentFound ? "catalog" : "raw", departmentFound?.item, departmentFound?.path);
|
||||
if (departmentId && !department?.name) unresolved.push(departmentId);
|
||||
|
||||
const legalEntityValue = form.legalEntity;
|
||||
const submitterObject = referenceObject(form.submitterId);
|
||||
const submitterLegalEntity = submitterObject?.defaultDepartment && typeof submitterObject.defaultDepartment === "object"
|
||||
? referenceObject(submitterObject.defaultDepartment)?.form && typeof referenceObject(submitterObject.defaultDepartment)?.form === "object"
|
||||
? (referenceObject(submitterObject.defaultDepartment)?.form as Record<string, unknown>).legalEntity
|
||||
: undefined
|
||||
: undefined;
|
||||
const legalEntityId = referenceId(legalEntityValue) || referenceId(submitterLegalEntity);
|
||||
const legalEntityCatalog = legalEntityId ? await resolveDimension(client, corpId, "FRST") : undefined;
|
||||
const legalEntityItem = legalEntityCatalog?.items.find((item) => item.id === legalEntityId || item.id.endsWith(`:${legalEntityId}`));
|
||||
const legalEntity = toReference(legalEntityValue || submitterLegalEntity || legalEntityId, "legalEntity", legalEntityItem ? "catalog" : "joined", legalEntityItem as unknown as Record<string, unknown> | undefined);
|
||||
if (referenceId(legalEntityValue) && !legalEntity?.name) unresolved.push(referenceId(legalEntityValue)!);
|
||||
|
||||
const feeTypes = [...collectFeeTypeIds(form)].map((id) => {
|
||||
const found = catalog.feeTypes.get(id) ?? catalog.feeTypes.get(id.split(":").at(-1) ?? id);
|
||||
const reference = toReference(id, "feeType", found ? "catalog" : "raw", found);
|
||||
if (!reference?.name) unresolved.push(id);
|
||||
return reference;
|
||||
}).filter((item): item is BillReference => Boolean(item));
|
||||
|
||||
const dimensions: BillReference[] = [];
|
||||
const dimensionTargets: Array<[RegExp, string]> = [[/project|项目/i, "DA001"], [/cost.?center|成本中心/i, "costCenter"]];
|
||||
for (const [keyPattern, dimensionCode] of dimensionTargets) {
|
||||
for (const [key, value] of Object.entries(form)) {
|
||||
if (!keyPattern.test(key)) continue;
|
||||
const id = referenceId(value);
|
||||
if (!id) continue;
|
||||
const resolved = await resolveDimension(client, corpId, dimensionCode);
|
||||
const item = resolved?.items.find((entry) => entry.id === id || entry.id.endsWith(`:${id}`));
|
||||
const reference = toReference(value, "dimension", item ? "catalog" : "raw", item as unknown as Record<string, unknown> | undefined);
|
||||
if (reference) dimensions.push(reference);
|
||||
if (!reference?.name) unresolved.push(id);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
target,
|
||||
billId: typeof raw.id === "string" ? raw.id : undefined,
|
||||
billCode: typeof form.code === "string" ? form.code : undefined,
|
||||
title: typeof form.title === "string" ? form.title : undefined,
|
||||
submitter: resolveStaff(form.submitterId, "staff"),
|
||||
owner: resolveStaff(form.ownerId, "staff"),
|
||||
department,
|
||||
legalEntity,
|
||||
feeTypes,
|
||||
dimensions,
|
||||
unresolved: [...new Set(unresolved)],
|
||||
raw: { form },
|
||||
};
|
||||
}
|
||||
|
||||
function relationAmount(value: Record<string, unknown>): string | undefined {
|
||||
for (const key of ["amount", "money", "expenseMoney", "loanMoney", "requisitionMoney", "payMoney", "writtenOffAmount"]) {
|
||||
const candidate = value[key];
|
||||
if (typeof candidate === "number" || typeof candidate === "string") return String(candidate);
|
||||
if (candidate && typeof candidate === "object") {
|
||||
const money = candidate as Record<string, unknown>;
|
||||
if (money.standard !== undefined) return `${money.standardSymbol || "¥"}${money.standard} ${money.standardStrCode || "CNY"}`.trim();
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function relationNode(relation: string, value: unknown): BillRelationNode | undefined {
|
||||
if (!value || typeof value !== "object") return undefined;
|
||||
const object = value as Record<string, unknown>;
|
||||
const children: BillRelationNode[] = [];
|
||||
for (const [key, nested] of Object.entries(object)) {
|
||||
if (key === "id" || key === "code" || key === "title" || key === "name") continue;
|
||||
if (Array.isArray(nested)) {
|
||||
for (const item of nested) {
|
||||
const arrayChild = relationNode(key, item);
|
||||
if (arrayChild) children.push(arrayChild);
|
||||
}
|
||||
} else if (nested && typeof nested === "object") {
|
||||
const child = relationNode(key, nested);
|
||||
if (child) children.push(child);
|
||||
}
|
||||
}
|
||||
const id = typeof object.id === "string" ? object.id : undefined;
|
||||
const code = typeof object.code === "string" ? object.code : undefined;
|
||||
const title = typeof object.title === "string" ? object.title : typeof object.name === "string" ? object.name : undefined;
|
||||
if (!id && !code && !title && children.length === 0) return undefined;
|
||||
return { relation, id, code, title, amount: relationAmount(object), children, raw: object };
|
||||
}
|
||||
|
||||
export async function getBillRelations(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string,
|
||||
): Promise<BillRelationsReport | undefined> {
|
||||
const raw = await getRawBillFlow(client, corpId, target);
|
||||
if (!raw || !raw.flowId || typeof raw.flowId !== "object") return undefined;
|
||||
const flow = raw.flowId as Record<string, unknown>;
|
||||
const form = flow.form && typeof flow.form === "object" ? flow.form as Record<string, unknown> : {};
|
||||
const relations: BillRelationNode[] = [];
|
||||
const seen = new Set<string>();
|
||||
const relationPattern = /(link|loan|requisition|contract|pre.?apply|advance)/i;
|
||||
for (const [key, value] of Object.entries(form)) {
|
||||
if (!relationPattern.test(key)) continue;
|
||||
const values = Array.isArray(value) ? value : [value];
|
||||
for (const candidate of values) {
|
||||
const node = relationNode(key, candidate);
|
||||
if (!node) continue;
|
||||
const dedupeKey = `${node.relation}:${node.id || node.code || node.title || JSON.stringify(node.raw)}`;
|
||||
if (seen.has(dedupeKey)) continue;
|
||||
seen.add(dedupeKey);
|
||||
relations.push(node);
|
||||
}
|
||||
}
|
||||
return {
|
||||
target,
|
||||
billId: typeof raw.id === "string" ? raw.id : undefined,
|
||||
billCode: typeof form.code === "string" ? form.code : undefined,
|
||||
title: typeof form.title === "string" ? form.title : undefined,
|
||||
relations,
|
||||
raw: { form },
|
||||
};
|
||||
}
|
||||
|
||||
function attachmentFromValue(sourceField: string, value: unknown): BillAttachment | undefined {
|
||||
if (!value || typeof value !== "object") return undefined;
|
||||
const object = value as Record<string, unknown>;
|
||||
const nestedFile = object.fileId && typeof object.fileId === "object" ? object.fileId as Record<string, unknown> : undefined;
|
||||
const fileId = typeof object.fileId === "string" ? object.fileId : typeof nestedFile?.id === "string" ? nestedFile.id : undefined;
|
||||
const key = typeof object.key === "string" ? object.key : typeof nestedFile?.key === "string" ? nestedFile.key : undefined;
|
||||
const fileName = typeof object.fileName === "string" ? object.fileName : typeof object.name === "string" ? object.name : undefined;
|
||||
const url = typeof object.url === "string" ? object.url : typeof nestedFile?.url === "string" ? nestedFile.url : undefined;
|
||||
const thumbUrl = typeof object.thumbUrl === "string" ? object.thumbUrl : typeof nestedFile?.thumbUrl === "string" ? nestedFile.thumbUrl : undefined;
|
||||
if (!fileId && !key && !fileName && !url) return undefined;
|
||||
return { fileId, key, fileName, url, thumbUrl, sourceField, raw: object };
|
||||
}
|
||||
|
||||
function collectAttachments(sourceField: string, value: unknown, output: BillAttachment[]): void {
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) collectAttachments(sourceField, item, output);
|
||||
return;
|
||||
}
|
||||
if (!value || typeof value !== "object") return;
|
||||
const object = value as Record<string, unknown>;
|
||||
const looksLikeAttachment = sourceField.toLowerCase().includes("attachment") || "fileId" in object || "fileName" in object || "thumbUrl" in object;
|
||||
if (looksLikeAttachment) {
|
||||
const attachment = attachmentFromValue(sourceField, value);
|
||||
if (attachment) output.push(attachment);
|
||||
}
|
||||
for (const [key, nested] of Object.entries(object)) {
|
||||
if (key === "fileId" || key === "fileName" || key === "url" || key === "thumbUrl" || key === "key") continue;
|
||||
if (nested && typeof nested === "object") collectAttachments(sourceField === "form" ? key : `${sourceField}.${key}`, nested, output);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getBillAttachments(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string,
|
||||
): Promise<BillAttachmentReport | undefined> {
|
||||
const raw = await getRawBillFlow(client, corpId, target);
|
||||
let billId: string | undefined;
|
||||
let billCode: string | undefined;
|
||||
let title: string | undefined;
|
||||
let form: Record<string, unknown> = {};
|
||||
if (raw?.flowId && typeof raw.flowId === "object") {
|
||||
billId = typeof raw.id === "string" ? raw.id : undefined;
|
||||
const flow = raw.flowId as Record<string, unknown>;
|
||||
form = flow.form && typeof flow.form === "object" ? flow.form as Record<string, unknown> : {};
|
||||
billCode = typeof form.code === "string" ? form.code : undefined;
|
||||
title = typeof form.title === "string" ? form.title : undefined;
|
||||
} else {
|
||||
const search = await searchRawBills(client, corpId, { count: 100 });
|
||||
const item = search.items.find((candidate) => candidate.id === target || candidate.code === target);
|
||||
if (!item) return undefined;
|
||||
billId = item.id;
|
||||
billCode = item.code;
|
||||
title = item.form?.title as string | undefined;
|
||||
form = item.form || {};
|
||||
}
|
||||
const attachments: BillAttachment[] = [];
|
||||
collectAttachments("form", form, attachments);
|
||||
const deduped = [...new Map(attachments.map((item) => [`${item.fileId || ""}|${item.key || ""}|${item.fileName || ""}`, item])).values()];
|
||||
const fileIds = deduped
|
||||
.map((item) => item.fileId)
|
||||
.filter((fileId): fileId is string => Boolean(fileId));
|
||||
let resolved: Awaited<ReturnType<typeof resolveAttachmentFiles>> = [];
|
||||
try {
|
||||
resolved = await resolveAttachmentFiles(client, corpId, fileIds);
|
||||
} catch {
|
||||
// 附件元数据接口不可用时,仍返回审批详情中已经拿到的原始字段。
|
||||
}
|
||||
const resolvedById = new Map(resolved.map((item) => [item.id, item]));
|
||||
const enriched = deduped.map((item) => {
|
||||
const metadata = item.fileId ? resolvedById.get(item.fileId) : undefined;
|
||||
if (!metadata) return item;
|
||||
return {
|
||||
...item,
|
||||
key: item.key ?? metadata.key,
|
||||
fileName: item.fileName ?? metadata.name,
|
||||
url: item.url ?? metadata.url,
|
||||
thumbUrl: item.thumbUrl ?? metadata.thumbUrl,
|
||||
raw: { ...item.raw, resolved: metadata },
|
||||
};
|
||||
});
|
||||
return {
|
||||
target,
|
||||
billId,
|
||||
billCode,
|
||||
title,
|
||||
attachments: enriched,
|
||||
raw: { form },
|
||||
};
|
||||
}
|
||||
|
||||
export interface DownloadedBillAttachment {
|
||||
fileId?: string;
|
||||
fileName?: string;
|
||||
key?: string;
|
||||
path: string;
|
||||
bytes: number;
|
||||
}
|
||||
|
||||
function safeAttachmentName(value: string): string {
|
||||
const cleaned = basename(value)
|
||||
.replace(/[\\/?%*:|"<>]/g, "_")
|
||||
.replace(/^\.+/, "_")
|
||||
.trim();
|
||||
return cleaned || "attachment";
|
||||
}
|
||||
|
||||
function uniqueAttachmentPath(outputDir: string, fileName: string, fileId: string | undefined, used: Set<string>): string {
|
||||
const extension = extname(fileName);
|
||||
const stem = extension ? fileName.slice(0, -extension.length) : fileName;
|
||||
let index = 0;
|
||||
while (true) {
|
||||
const suffix = index === 0 ? "" : fileId ? `-${fileId}${index > 1 ? `-${index}` : ""}` : `-copy${index > 1 ? `-${index}` : ""}`;
|
||||
const candidate = join(outputDir, `${stem}${suffix}${extension}`);
|
||||
if (!used.has(candidate) && !existsSync(candidate)) {
|
||||
used.add(candidate);
|
||||
return candidate;
|
||||
}
|
||||
index++;
|
||||
}
|
||||
}
|
||||
|
||||
export async function downloadBillAttachments(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string,
|
||||
outputDir: string,
|
||||
fileId?: string,
|
||||
): Promise<{
|
||||
target: string;
|
||||
outputDir: string;
|
||||
requestedFileId?: string;
|
||||
downloaded: DownloadedBillAttachment[];
|
||||
skipped: number;
|
||||
report: BillAttachmentReport;
|
||||
}> {
|
||||
const report = await getBillAttachments(client, corpId, target);
|
||||
if (!report) throw new Error(`未找到单据附件: ${target}`);
|
||||
|
||||
const selected = fileId
|
||||
? report.attachments.filter((item) => item.fileId === fileId)
|
||||
: report.attachments;
|
||||
if (fileId && selected.length === 0) {
|
||||
throw new Error(`单据 ${target} 中未找到附件 fileId: ${fileId}`);
|
||||
}
|
||||
|
||||
const destination = resolve(outputDir);
|
||||
await mkdir(destination, { recursive: true });
|
||||
const usedPaths = new Set<string>();
|
||||
const downloaded: DownloadedBillAttachment[] = [];
|
||||
let skipped = 0;
|
||||
|
||||
for (const attachment of selected) {
|
||||
if (!attachment.url) {
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
const sourceName = attachment.fileName || attachment.key || attachment.fileId || "attachment";
|
||||
const path = uniqueAttachmentPath(destination, safeAttachmentName(sourceName), attachment.fileId, usedPaths);
|
||||
const response = await fetch(attachment.url);
|
||||
if (!response.ok) {
|
||||
throw new Error(`附件下载失败 (${response.status}): ${sourceName}`);
|
||||
}
|
||||
const content = new Uint8Array(await response.arrayBuffer());
|
||||
await writeFile(path, content);
|
||||
downloaded.push({
|
||||
fileId: attachment.fileId,
|
||||
fileName: attachment.fileName,
|
||||
key: attachment.key,
|
||||
path,
|
||||
bytes: content.byteLength,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
target,
|
||||
outputDir: destination,
|
||||
requestedFileId: fileId,
|
||||
downloaded,
|
||||
skipped,
|
||||
report,
|
||||
};
|
||||
}
|
||||
|
||||
// ── 格式化单据数据 ─────────────────────────────────────────────────────────────
|
||||
|
||||
export function formatSingleBill(
|
||||
@@ -217,6 +688,279 @@ export async function getBillByCodeOrId(
|
||||
return matched.map((it) => formatSingleBill(it, dictionary));
|
||||
}
|
||||
|
||||
function flowPerson(value: unknown): { id?: string; name?: string; code?: string } | undefined {
|
||||
if (typeof value === "string") return { id: value };
|
||||
if (!value || typeof value !== "object") return undefined;
|
||||
const person = value as Record<string, unknown>;
|
||||
return {
|
||||
id: typeof person.id === "string" ? person.id : undefined,
|
||||
name: typeof person.name === "string" ? person.name : undefined,
|
||||
code: typeof person.code === "string" ? person.code : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function unwrapValue(value: unknown): Record<string, unknown> {
|
||||
if (!value || typeof value !== "object") return {};
|
||||
const object = value as Record<string, unknown>;
|
||||
return object.value && typeof object.value === "object" ? object.value as Record<string, unknown> : object;
|
||||
}
|
||||
|
||||
export async function getBillFlow(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string
|
||||
): Promise<BillFlowTimeline | undefined> {
|
||||
const raw = await getRawBillFlow(client, corpId, target);
|
||||
if (!raw) return undefined;
|
||||
const flow = raw.flowId && typeof raw.flowId === "object" ? raw.flowId as Record<string, unknown> : {};
|
||||
const form = flow.form && typeof flow.form === "object" ? flow.form as Record<string, unknown> : {};
|
||||
const nodeState = raw.nodeState && typeof raw.nodeState === "object" ? raw.nodeState as Record<string, unknown> : {};
|
||||
const logs = Array.isArray(flow.logs) ? flow.logs : [];
|
||||
const history: BillFlowEntry[] = logs.map((value, index) => {
|
||||
const log = value && typeof value === "object" ? value as Record<string, unknown> : {};
|
||||
const attributes = log.attributes && typeof log.attributes === "object" ? log.attributes as Record<string, unknown> : {};
|
||||
const currentTime = typeof log.time === "number" ? log.time : undefined;
|
||||
const nextLog = logs[index + 1] && typeof logs[index + 1] === "object" ? logs[index + 1] as Record<string, unknown> : undefined;
|
||||
const nextTime = typeof nextLog?.time === "number" ? nextLog.time : undefined;
|
||||
const durationMs = currentTime !== undefined && nextTime !== undefined && nextTime >= currentTime ? nextTime - currentTime : undefined;
|
||||
const nextOperators = Array.isArray(log.nextOperatorIds)
|
||||
? log.nextOperatorIds.map(flowPerson).filter((person): person is NonNullable<typeof person> => Boolean(person))
|
||||
: [];
|
||||
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,
|
||||
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),
|
||||
nextOperators,
|
||||
};
|
||||
});
|
||||
const plan = flow.plan && typeof flow.plan === "object" ? flow.plan as Record<string, unknown> : {};
|
||||
const nextNodeId = typeof plan.nextNodeId === "string" ? plan.nextNodeId : undefined;
|
||||
const currentNode = typeof raw.nodeName === "string" ? raw.nodeName : typeof nodeState.nodeName === "string" ? nodeState.nodeName : undefined;
|
||||
const nodes = Array.isArray(plan.nodes) ? plan.nodes : [];
|
||||
const pending: BillFlowNode[] = nodes.map((value) => {
|
||||
const node = value && typeof value === "object" ? value as Record<string, unknown> : {};
|
||||
const approvers = Array.isArray(node.counterSigners)
|
||||
? node.counterSigners.map(flowPerson).filter((person): person is NonNullable<typeof person> => Boolean(person))
|
||||
: [];
|
||||
const approver = flowPerson(node.approverId);
|
||||
return {
|
||||
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",
|
||||
approver,
|
||||
approvers,
|
||||
};
|
||||
});
|
||||
const lastAttributes = logs.at(-1) && typeof logs.at(-1) === "object" && (logs.at(-1) as Record<string, unknown>).attributes && typeof (logs.at(-1) as Record<string, unknown>).attributes === "object"
|
||||
? (logs.at(-1) as Record<string, unknown>).attributes as Record<string, unknown>
|
||||
: {};
|
||||
return {
|
||||
backlogId: typeof raw.id === "string" ? raw.id : target,
|
||||
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,
|
||||
currentNode: currentNode ?? (typeof lastAttributes.nextName === "string" ? lastAttributes.nextName : undefined),
|
||||
history,
|
||||
pending,
|
||||
raw,
|
||||
};
|
||||
}
|
||||
|
||||
function actionTarget(raw: Record<string, unknown>, fallback: string): BillActionTarget {
|
||||
const flow = raw.flowId && typeof raw.flowId === "object" ? raw.flowId as Record<string, unknown> : {};
|
||||
const form = flow.form && typeof flow.form === "object" ? flow.form as Record<string, unknown> : {};
|
||||
const backlogId = typeof raw.id === "string" ? raw.id : fallback;
|
||||
const flowId = typeof flow.id === "string" ? flow.id : undefined;
|
||||
if (!flowId) throw new Error(`未找到单据流程 ID: ${fallback}`);
|
||||
const plan = flow.plan && typeof flow.plan === "object" ? flow.plan as Record<string, unknown> : {};
|
||||
const nodes = Array.isArray(plan.nodes) ? plan.nodes : [];
|
||||
const nodeName = typeof raw.nodeName === "string" ? raw.nodeName : undefined;
|
||||
const currentNode = nodes.find((value) => {
|
||||
const node = value && typeof value === "object" ? value as Record<string, unknown> : {};
|
||||
return typeof raw.nodeId === "string" && node.id === raw.nodeId || nodeName && node.name === nodeName;
|
||||
});
|
||||
return {
|
||||
backlogId,
|
||||
flowId,
|
||||
billId: flowId,
|
||||
billCode: typeof form.code === "string" ? form.code : undefined,
|
||||
nodeId: typeof raw.nodeId === "string" ? raw.nodeId : currentNode && typeof currentNode === "object" && typeof (currentNode as Record<string, unknown>).id === "string" ? (currentNode as Record<string, unknown>).id as string : undefined,
|
||||
nodeName,
|
||||
raw,
|
||||
};
|
||||
}
|
||||
|
||||
async function resolveActionTarget(client: KyInstance, corpId: string, target: string): Promise<BillActionTarget> {
|
||||
const raw = await getRawBillFlow(client, corpId, target);
|
||||
if (!raw) throw new Error(`未找到单据或审批任务: ${target}`);
|
||||
return actionTarget(raw, target);
|
||||
}
|
||||
|
||||
export interface BillActionResult {
|
||||
action: "approve" | "reject" | "transfer" | "add-node" | "comment";
|
||||
corpId: string;
|
||||
target: string;
|
||||
backlogId: string;
|
||||
flowId: string;
|
||||
billId?: string;
|
||||
billCode?: string;
|
||||
nodeId?: string;
|
||||
response?: unknown;
|
||||
}
|
||||
|
||||
export async function resolveBillStaffIds(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
values: string[],
|
||||
): Promise<string[]> {
|
||||
const catalog = await listActiveStaffCatalog(client, corpId);
|
||||
const normalized = (value: string) => value.trim().toLowerCase();
|
||||
const matchesFor = (value: string) => {
|
||||
const target = normalized(value);
|
||||
return catalog.filter((staff) => {
|
||||
const id = typeof staff.id === "string" ? staff.id : "";
|
||||
const userId = typeof staff.userId === "string" ? staff.userId : "";
|
||||
const name = typeof staff.name === "string" ? staff.name : "";
|
||||
const code = typeof staff.code === "string" ? staff.code : "";
|
||||
return [id, userId, name, code].some((candidate) => {
|
||||
const lowered = normalized(candidate);
|
||||
return lowered === target || lowered.endsWith(`:${target}`);
|
||||
});
|
||||
});
|
||||
};
|
||||
const result: string[] = [];
|
||||
for (const value of values) {
|
||||
const matches = matchesFor(value);
|
||||
if (matches.length !== 1) {
|
||||
if (matches.length > 1) throw new Error(`员工关键词 [${value}] 匹配到多人,请改用员工 ID 或工号`);
|
||||
throw new Error(`未找到员工 [${value}]`);
|
||||
}
|
||||
const id = typeof matches[0]?.id === "string" ? matches[0].id : undefined;
|
||||
if (!id) throw new Error(`员工 [${value}] 缺少可用 ID`);
|
||||
result.push(id);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async function runBillAction(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string,
|
||||
action: BillActionResult["action"],
|
||||
options: BillActionOptions = {},
|
||||
): Promise<BillActionResult> {
|
||||
const resolved = await resolveActionTarget(client, corpId, target);
|
||||
if (options.currentStaffId && action !== "comment") {
|
||||
const flow = resolved.raw.flowId && typeof resolved.raw.flowId === "object" ? resolved.raw.flowId as Record<string, unknown> : {};
|
||||
const actions = flow.actions && typeof flow.actions === "object" ? flow.actions as Record<string, unknown> : undefined;
|
||||
if (actions && Object.keys(actions).length > 0) {
|
||||
const current = options.currentStaffId;
|
||||
const currentTail = current.split(":").at(-1) || current;
|
||||
const entry = Object.entries(actions).find(([staffId]) => {
|
||||
const staffTail = staffId.split(":").at(-1) || staffId;
|
||||
return staffId === current || staffId.endsWith(`:${current}`) || current.endsWith(`:${staffId}`) || staffTail === currentTail;
|
||||
});
|
||||
const allowed = entry?.[1];
|
||||
const requiredAction = action === "approve" ? "freeflow.agree" : action === "reject" ? "freeflow.reject" : "freeflow.addnode";
|
||||
if (!Array.isArray(allowed) || !allowed.includes(requiredAction)) {
|
||||
throw new Error(`当前账号不是该节点的合法待办人,不能执行 ${action} 动作`);
|
||||
}
|
||||
}
|
||||
}
|
||||
let response: unknown;
|
||||
if (action === "approve") response = await approveBillAction(client, corpId, resolved, options);
|
||||
else if (action === "reject") response = await rejectBillAction(client, corpId, resolved, options);
|
||||
else if (action === "transfer") response = await transferBillAction(client, corpId, resolved, options);
|
||||
else if (action === "add-node") response = await addNodeBillAction(client, corpId, resolved, options);
|
||||
else response = await commentBillAction(client, corpId, resolved, options);
|
||||
return {
|
||||
action,
|
||||
corpId,
|
||||
target,
|
||||
backlogId: resolved.backlogId,
|
||||
flowId: resolved.flowId,
|
||||
billId: resolved.billId,
|
||||
billCode: resolved.billCode,
|
||||
nodeId: resolved.nodeId,
|
||||
response,
|
||||
};
|
||||
}
|
||||
|
||||
export function approveBill(client: KyInstance, corpId: string, target: string, options: BillActionOptions = {}) {
|
||||
return runBillAction(client, corpId, target, "approve", options);
|
||||
}
|
||||
|
||||
export function rejectBill(client: KyInstance, corpId: string, target: string, options: BillActionOptions = {}) {
|
||||
if (!options.comment?.trim()) throw new Error("驳回原因不能为空");
|
||||
return runBillAction(client, corpId, target, "reject", options);
|
||||
}
|
||||
|
||||
export function transferBill(client: KyInstance, corpId: string, target: string, options: BillActionOptions = {}) {
|
||||
if (!options.approverIds?.length) throw new Error("转交审批至少需要一个 approverId");
|
||||
return runBillAction(client, corpId, target, "transfer", options);
|
||||
}
|
||||
|
||||
export function addNodeBill(client: KyInstance, corpId: string, target: string, options: BillActionOptions = {}) {
|
||||
if (!options.approverIds?.length) throw new Error("加签审批至少需要一个 approverId");
|
||||
return runBillAction(client, corpId, target, "add-node", options);
|
||||
}
|
||||
|
||||
export function commentBill(client: KyInstance, corpId: string, target: string, options: BillActionOptions = {}) {
|
||||
if (!options.comment?.trim()) throw new Error("评论内容不能为空");
|
||||
return runBillAction(client, corpId, target, "comment", options);
|
||||
}
|
||||
|
||||
export async function getBillRisk(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string
|
||||
): Promise<BillRiskReport | undefined> {
|
||||
const rawFlow = await getRawBillFlow(client, corpId, target);
|
||||
if (!rawFlow || !rawFlow.flowId || typeof rawFlow.flowId !== "object") return undefined;
|
||||
const flow = rawFlow.flowId as Record<string, unknown>;
|
||||
const flowId = typeof flow.id === "string" ? flow.id : undefined;
|
||||
if (!flowId) return undefined;
|
||||
const form = flow.form && typeof flow.form === "object" ? flow.form as Record<string, unknown> : {};
|
||||
const submitter = form.submitterId && typeof form.submitterId === "object" ? form.submitterId as Record<string, unknown> : {};
|
||||
const submitterId = typeof submitter.id === "string" ? submitter.id : undefined;
|
||||
const rawRisk = await getRawBillRisk(client, corpId, flowId, submitterId);
|
||||
const coalition = unwrapValue(rawRisk.coalition);
|
||||
const rawWarnings = Array.isArray(coalition.riskWarning) ? coalition.riskWarning : [];
|
||||
const warnings: BillRiskWarning[] = rawWarnings.map((value) => {
|
||||
const item = value && typeof value === "object" ? value as Record<string, unknown> : {};
|
||||
return {
|
||||
riskLevel: typeof item.riskLevel === "string" ? item.riskLevel : undefined,
|
||||
type: typeof item.type === "string" ? item.type : undefined,
|
||||
title: typeof item.title === "string" ? item.title : undefined,
|
||||
controlName: typeof item.controlName === "string" ? item.controlName : undefined,
|
||||
messages: Array.isArray(item.messages) ? item.messages.filter((message): message is string => typeof message === "string") : [],
|
||||
raw: item,
|
||||
};
|
||||
});
|
||||
const invoice = unwrapValue(rawRisk.invoice);
|
||||
const budget = unwrapValue(rawRisk.budget);
|
||||
return {
|
||||
flowId,
|
||||
budgetExceeded: budget.value === true,
|
||||
budget,
|
||||
credit: unwrapValue(rawRisk.staff),
|
||||
rules: unwrapValue(rawRisk.rules),
|
||||
notes: unwrapValue(rawRisk.notes),
|
||||
warnings,
|
||||
invoiceWarnings: Array.isArray(invoice.items) ? invoice.items.filter((item): item is Record<string, unknown> => Boolean(item && typeof item === "object")) : [],
|
||||
raw: rawRisk,
|
||||
};
|
||||
}
|
||||
|
||||
// ── 业务操作:多条件搜索与分页单据 ─────────────────────────────────────────────
|
||||
|
||||
export async function searchAndFormatBills(
|
||||
|
||||
@@ -103,3 +103,121 @@ export interface BillQueryParams {
|
||||
start?: number;
|
||||
count?: number;
|
||||
}
|
||||
|
||||
export interface BillFlowEntry {
|
||||
id?: string;
|
||||
time?: number;
|
||||
durationMs?: number;
|
||||
state?: string;
|
||||
action?: string;
|
||||
nodeName?: string;
|
||||
comment?: string;
|
||||
automatic?: boolean;
|
||||
skipped?: boolean;
|
||||
operator?: { id?: string; name?: string; code?: string };
|
||||
nextOperators?: Array<{ id?: string; name?: string; code?: string }>;
|
||||
}
|
||||
|
||||
export interface BillFlowNode {
|
||||
id?: string;
|
||||
name?: string;
|
||||
type?: string;
|
||||
state?: string;
|
||||
approver?: { id?: string; name?: string; code?: string };
|
||||
approvers?: Array<{ id?: string; name?: string; code?: string }>;
|
||||
}
|
||||
|
||||
export interface BillFlowTimeline {
|
||||
backlogId: string;
|
||||
flowId?: string;
|
||||
billCode?: string;
|
||||
title?: string;
|
||||
state?: string;
|
||||
currentNode?: string;
|
||||
history: BillFlowEntry[];
|
||||
pending: BillFlowNode[];
|
||||
raw: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface BillRiskWarning {
|
||||
riskLevel?: string;
|
||||
type?: string;
|
||||
title?: string;
|
||||
controlName?: string;
|
||||
messages: string[];
|
||||
raw: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface BillRiskReport {
|
||||
flowId: string;
|
||||
budgetExceeded?: boolean;
|
||||
budget?: Record<string, unknown>;
|
||||
credit?: Record<string, unknown>;
|
||||
rules?: Record<string, unknown>;
|
||||
notes?: Record<string, unknown>;
|
||||
warnings: BillRiskWarning[];
|
||||
invoiceWarnings: Record<string, unknown>[];
|
||||
raw: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface BillReference {
|
||||
id: string;
|
||||
name?: string;
|
||||
code?: string;
|
||||
path?: string;
|
||||
kind: "staff" | "department" | "feeType" | "legalEntity" | "dimension" | "unknown";
|
||||
source: "joined" | "catalog" | "raw";
|
||||
}
|
||||
|
||||
export interface BillReferenceReport {
|
||||
target: string;
|
||||
billId?: string;
|
||||
billCode?: string;
|
||||
title?: string;
|
||||
submitter?: BillReference;
|
||||
owner?: BillReference;
|
||||
department?: BillReference;
|
||||
legalEntity?: BillReference;
|
||||
feeTypes: BillReference[];
|
||||
dimensions: BillReference[];
|
||||
unresolved: string[];
|
||||
raw: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface BillRelationNode {
|
||||
relation: string;
|
||||
id?: string;
|
||||
code?: string;
|
||||
title?: string;
|
||||
amount?: string;
|
||||
children: BillRelationNode[];
|
||||
raw: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface BillRelationsReport {
|
||||
target: string;
|
||||
billId?: string;
|
||||
billCode?: string;
|
||||
title?: string;
|
||||
relations: BillRelationNode[];
|
||||
raw: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface BillAttachment {
|
||||
fileId?: string;
|
||||
key?: string;
|
||||
fileName?: string;
|
||||
url?: string;
|
||||
thumbUrl?: string;
|
||||
sourceField: string;
|
||||
raw: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface BillAttachmentReport {
|
||||
target: string;
|
||||
billId?: string;
|
||||
billCode?: string;
|
||||
title?: string;
|
||||
attachments: BillAttachment[];
|
||||
raw: Record<string, unknown>;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
# Dimension 域说明
|
||||
|
||||
Dimension 域负责“系统配置 → 档案设置 → 扩展档案 → 自定义档案”目录和档案项查询。
|
||||
|
||||
- `listDimensionCatalogs` 调用组织权限目录后,分别拉取系统档案 (`preset==1`) 与自定义档案 (`preset==0`);
|
||||
- `listDimensionItems` 调用档案项接口并保留 `id`、`code`、`name`、`parentId`、`fullPath` 和 `form`;
|
||||
- `tools.ts` 按企业在进程内缓存目录与档案项 10 分钟。
|
||||
@@ -0,0 +1,36 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import { DimensionCatalogSchema, DimensionItemSchema, type DimensionCatalog, type DimensionItem } from "./types.js";
|
||||
|
||||
export async function listDimensionCatalogs(client: KyInstance, corpId: string, start = 0, count = 100): Promise<DimensionCatalog[]> {
|
||||
const organizationResponse = await client.get("api/authority/v2/organization/list/$DIMENSION", {
|
||||
searchParams: { start: String(start), count: String(count), model: "DIMENSION", corpId },
|
||||
});
|
||||
const organizationJson = (await organizationResponse.json()) as { items?: Array<{ id?: string }> };
|
||||
const orgId = organizationJson.items?.[0]?.id;
|
||||
if (!orgId) return [];
|
||||
const responses = await Promise.all([0, 1].map((preset) => client.post("api/v1/basedata/dimensions/active", {
|
||||
searchParams: { orgId, corpId },
|
||||
json: {
|
||||
limit: { start, count },
|
||||
select: "id,label,enLabel,code,name,state,type,active",
|
||||
orderBy: [{ value: "createTime", order: "DESC" }],
|
||||
filterBy: `preset==${preset}`,
|
||||
},
|
||||
})));
|
||||
const items: unknown[] = [];
|
||||
for (const response of responses) {
|
||||
const json = (await response.json()) as { items?: unknown[] };
|
||||
items.push(...(json.items ?? []));
|
||||
}
|
||||
return z.array(DimensionCatalogSchema).parse(items);
|
||||
}
|
||||
|
||||
export async function listDimensionItems(client: KyInstance, corpId: string, dimensionId: string, start = 0, count = 100): Promise<DimensionItem[]> {
|
||||
const response = await client.post(`api/v1/basedata/dimensionItems/$${dimensionId}`, {
|
||||
searchParams: { corpId, dimensionItemId: "" },
|
||||
json: { filterBy: "(active == true)", limit: { start, count } },
|
||||
});
|
||||
const json = (await response.json()) as { items?: unknown[] };
|
||||
return z.array(DimensionItemSchema).parse(json.items ?? []);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { searchDimensions, resolveDimension } from "./tools.js";
|
||||
|
||||
describe("Dimension Domain - 自定义档案目录", () => {
|
||||
it("loads preset and custom dimension catalogs and filters by name", async () => {
|
||||
const client = {
|
||||
get: async () => new Response(JSON.stringify({ items: [{ id: "org-1" }] })),
|
||||
post: async (_path: string, options: any) => new Response(JSON.stringify({ items: [
|
||||
options.json.filterBy === "preset==0" ? { id: "dim-custom", name: "项目", code: "DA001", type: "normal", active: true } : { id: "dim-system", name: "法人实体", code: "FRST", type: "legal_entity", active: true },
|
||||
] })),
|
||||
} as any;
|
||||
const result = await searchDimensions(client, "corp-dimension", { name: "项目" });
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]?.code).toBe("DA001");
|
||||
});
|
||||
|
||||
it("loads dimension items by catalog ID", async () => {
|
||||
const client = {
|
||||
get: async () => new Response(JSON.stringify({ items: [{ id: "org-2" }] })),
|
||||
post: async (path: string) => new Response(JSON.stringify(path.includes("dimensionItems") ? { items: [{ id: "item-1", name: "研发项目", code: "P001", parentId: "", active: true }] } : { items: [{ id: "dim-project", name: "项目", code: "DA001", type: "normal", active: true }] })),
|
||||
} as any;
|
||||
const result = await resolveDimension(client, "corp-items", "项目");
|
||||
expect(result?.dimension.id).toBe("dim-project");
|
||||
expect(result?.items[0]?.name).toBe("研发项目");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
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;
|
||||
}
|
||||
|
||||
export async function searchDimensions(client: KyInstance, corpId: string, query: DimensionQuery = {}): Promise<DimensionCatalog[]> {
|
||||
const { catalogs } = await getCached(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)));
|
||||
}
|
||||
|
||||
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 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;
|
||||
return { dimension, items: await getDimensionItems(client, corpId, dimension) };
|
||||
}
|
||||
|
||||
export const dimensionTools = [
|
||||
{
|
||||
name: "dimension_list",
|
||||
description: "列出企业档案管理中的系统/自定义档案维度目录",
|
||||
parameters: z.object({ keyword: z.string().optional(), count: z.number().optional() }),
|
||||
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 });
|
||||
return { count: items.length, dimensions: items.slice(0, params.count ?? 100) };
|
||||
},
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,33 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const DimensionCatalogSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string().default(""),
|
||||
code: z.string().optional().default(""),
|
||||
type: z.string().optional().default(""),
|
||||
active: z.boolean().optional().default(true),
|
||||
state: z.string().nullable().optional().transform((value) => value ?? ""),
|
||||
});
|
||||
|
||||
export const DimensionItemSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string().default(""),
|
||||
code: z.string().optional().default(""),
|
||||
parentId: z.string().optional().default(""),
|
||||
dimensionId: z.string().optional().default(""),
|
||||
active: z.boolean().optional().default(true),
|
||||
deleted: z.boolean().optional().default(false),
|
||||
fullPath: z.string().nullable().optional(),
|
||||
form: z.record(z.string(), z.any()).optional().default({}),
|
||||
});
|
||||
|
||||
export type DimensionCatalog = z.infer<typeof DimensionCatalogSchema>;
|
||||
export type DimensionItem = z.infer<typeof DimensionItemSchema>;
|
||||
|
||||
export interface DimensionQuery {
|
||||
id?: string;
|
||||
code?: string;
|
||||
name?: string;
|
||||
start?: number;
|
||||
count?: number;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { EventStore } from "./store.js";
|
||||
import { pollEvents } from "./poller.js";
|
||||
|
||||
describe("Event poller", () => {
|
||||
it("persists dedupe keys and only returns new events", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "hose-events-"));
|
||||
try {
|
||||
const store = new EventStore(join(dir, "events.json"));
|
||||
const client = { get: async (path: string) => new Response(JSON.stringify(path.includes("messages") ? { count: 1, items: [{ id: "m-1", title: "新消息", read: false, updateTime: 10 }] } : { count: 0, items: [] }),), post: async () => new Response(JSON.stringify({ count: 1, items: [{ id: "t-1", updateTime: 11, flowId: { form: { title: "待审单据" } } }] })) } as any;
|
||||
const first = await pollEvents(client, "corp-1", store, 10);
|
||||
const second = await pollEvents(client, "corp-1", store, 10);
|
||||
expect(first.newEvents).toHaveLength(2); expect(second.newEvents).toHaveLength(0); expect(second.duplicateCount).toBe(2);
|
||||
expect(JSON.parse(readFileSync(join(dir, "events.json"), "utf8")).version).toBe(1);
|
||||
} finally { rmSync(dir, { recursive: true, force: true }); }
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { listMessages } from "../message/tools.js";
|
||||
import { listTasks } from "../task/tools.js";
|
||||
import { EventStore } from "./store.js";
|
||||
import type { EventPollResult, EventRecord } from "./types.js";
|
||||
|
||||
function eventId(kind: EventRecord["kind"], id: string, updatedAt?: number): string { return `${kind}:${id}:${updatedAt ?? 0}`; }
|
||||
|
||||
export async function pollEvents(client: KyInstance, corpId: string, store: EventStore, count = 50): Promise<EventPollResult> {
|
||||
const observedAt = Date.now();
|
||||
const [todo, messages] = await Promise.all([
|
||||
listTasks(client, corpId, "todo", { start: 0, count }),
|
||||
listMessages(client, corpId, { start: 0, count, read: false }),
|
||||
]);
|
||||
const candidates: EventRecord[] = [
|
||||
...todo.items.map((payload) => ({ id: eventId("todo", payload.taskId, payload.updatedAt || payload.actionTime), kind: "todo" as const, corpId, observedAt, payload })),
|
||||
...messages.items.map((payload) => ({ id: eventId("message", payload.id, payload.updateTime || payload.createTime), kind: "message" as const, corpId, observedAt, payload })),
|
||||
];
|
||||
const newEvents = candidates.filter((event) => !store.has(event.id));
|
||||
store.commit(candidates);
|
||||
return { corpId, observedAt, scanned: { todo: todo.items.length, messages: messages.items.length }, newEvents, duplicateCount: candidates.length - newEvents.length };
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { dirname } from "node:path";
|
||||
import type { EventRecord } from "./types.js";
|
||||
|
||||
interface PersistedEvents { version: 1; events: Record<string, number>; }
|
||||
const MAX_EVENTS = 2000;
|
||||
|
||||
export class EventStore {
|
||||
constructor(private readonly filePath: string) {}
|
||||
private read(): PersistedEvents {
|
||||
if (!existsSync(this.filePath)) return { version: 1, events: {} };
|
||||
try {
|
||||
const parsed = JSON.parse(readFileSync(this.filePath, "utf8")) as Partial<PersistedEvents>;
|
||||
return { version: 1, events: parsed.events && typeof parsed.events === "object" ? parsed.events : {} };
|
||||
} catch { return { version: 1, events: {} }; }
|
||||
}
|
||||
has(id: string): boolean { return Object.prototype.hasOwnProperty.call(this.read().events, id); }
|
||||
commit(records: EventRecord[]): void {
|
||||
if (!records.length) return;
|
||||
const data = this.read();
|
||||
const merged = { ...data.events };
|
||||
for (const record of records) merged[record.id] = record.observedAt;
|
||||
const entries = Object.entries(merged).sort((a, b) => a[1] - b[1]).slice(-MAX_EVENTS);
|
||||
mkdirSync(dirname(this.filePath), { recursive: true, mode: 0o700 });
|
||||
writeFileSync(this.filePath, `${JSON.stringify({ version: 1, events: Object.fromEntries(entries) }, null, 2)}\n`, { mode: 0o600 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import type { MessageItem } from "../message/types.js";
|
||||
import type { TaskItem } from "../task/types.js";
|
||||
|
||||
export type EventKind = "todo" | "message";
|
||||
export interface EventRecord { id: string; kind: EventKind; corpId: string; observedAt: number; payload: TaskItem | MessageItem; }
|
||||
export interface EventPollResult { corpId: string; observedAt: number; scanned: { todo: number; messages: number }; newEvents: EventRecord[]; duplicateCount: number; }
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import type { MessageQueryOptions } from "./types.js";
|
||||
|
||||
export async function fetchMessagePage(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
options: MessageQueryOptions = {}
|
||||
): Promise<{ count: number; items: Record<string, unknown>[] }> {
|
||||
const start = options.start ?? 0;
|
||||
const count = options.count ?? 20;
|
||||
const read = options.read ?? false;
|
||||
const response = await client.get("api/message/v1/messages", {
|
||||
searchParams: {
|
||||
read: String(read),
|
||||
start: String(start),
|
||||
count: String(count),
|
||||
corpId,
|
||||
},
|
||||
});
|
||||
const json = (await response.json()) as { count?: number; items?: Record<string, unknown>[] };
|
||||
return { count: json.count ?? json.items?.length ?? 0, items: json.items ?? [] };
|
||||
}
|
||||
|
||||
export async function markMessageRead(client: KyInstance, corpId: string, messageId: string): Promise<void> {
|
||||
// The downstream route accepts the compound ID with its colon separators intact.
|
||||
await client.put(`api/message/v1/messages/$${messageId}`, {
|
||||
searchParams: { corpId },
|
||||
json: { id: messageId },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { filterMessages, mergeMessages, normalizeMessage } from "./tools.js";
|
||||
|
||||
describe("Message Domain - 消息中心模型", () => {
|
||||
test("normalizes message fields and filters by type", () => {
|
||||
const item = normalizeMessage({
|
||||
id: "msg-1",
|
||||
title: "你的单据被驳回",
|
||||
content: "单据:有效性。",
|
||||
messageType: "INFO",
|
||||
msgTypeName: "审批通知",
|
||||
read: false,
|
||||
sortTime: 1776052034000,
|
||||
});
|
||||
expect(item.id).toBe("msg-1");
|
||||
expect(item.read).toBe(false);
|
||||
expect(filterMessages([item], "审批")).toHaveLength(1);
|
||||
expect(filterMessages([item], "Loan_Repayment")).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("merges read and unread pages by ID and newest time", () => {
|
||||
const older = normalizeMessage({ id: "msg-1", title: "旧标题", read: false, sortTime: 10 });
|
||||
const newer = normalizeMessage({ id: "msg-1", title: "新标题", read: true, sortTime: 20 });
|
||||
const second = normalizeMessage({ id: "msg-2", title: "第二条", read: false, sortTime: 15 });
|
||||
const merged = mergeMessages([older, second, newer]);
|
||||
expect(merged.map((item) => item.id)).toEqual(["msg-2", "msg-1"]);
|
||||
expect(merged[1]?.title).toBe("旧标题");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { fetchMessagePage, markMessageRead } from "./api.js";
|
||||
import type { MessageItem, MessagePageResult, MessageQueryOptions } from "./types.js";
|
||||
|
||||
export function normalizeMessage(raw: Record<string, unknown>): MessageItem {
|
||||
return {
|
||||
id: String(raw.id ?? ""),
|
||||
title: typeof raw.title === "string" ? raw.title : undefined,
|
||||
content: typeof raw.content === "string" ? raw.content : undefined,
|
||||
messageType: typeof raw.messageType === "string" ? raw.messageType : undefined,
|
||||
msgType: typeof raw.msgType === "string" ? raw.msgType : undefined,
|
||||
msgTypeName: typeof raw.msgTypeName === "string" ? raw.msgTypeName : undefined,
|
||||
msgName: typeof raw.msgName === "string" ? raw.msgName : undefined,
|
||||
read: raw.read === true,
|
||||
createTime: typeof raw.createTime === "number" ? raw.createTime : undefined,
|
||||
updateTime: typeof raw.updateTime === "number" ? raw.updateTime : undefined,
|
||||
sortTime: typeof raw.sortTime === "number" ? raw.sortTime : undefined,
|
||||
sourceId: typeof raw.sourceId === "string" || raw.sourceId === null ? raw.sourceId : undefined,
|
||||
sourceType: typeof raw.sourceType === "string" ? raw.sourceType : undefined,
|
||||
sourceStatus: typeof raw.sourceStatus === "string" || raw.sourceStatus === null ? raw.sourceStatus : undefined,
|
||||
url: typeof raw.url === "string" ? raw.url : undefined,
|
||||
raw,
|
||||
};
|
||||
}
|
||||
|
||||
export async function listMessages(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
options: MessageQueryOptions = {}
|
||||
): Promise<MessagePageResult> {
|
||||
const page = await fetchMessagePage(client, corpId, options);
|
||||
return {
|
||||
total: page.count,
|
||||
start: options.start ?? 0,
|
||||
count: options.count ?? 20,
|
||||
read: options.read ?? false,
|
||||
items: page.items.map(normalizeMessage),
|
||||
};
|
||||
}
|
||||
|
||||
export async function readMessage(client: KyInstance, corpId: string, messageId: string): Promise<void> {
|
||||
await markMessageRead(client, corpId, messageId);
|
||||
}
|
||||
|
||||
export function filterMessages(items: MessageItem[], messageType?: string): MessageItem[] {
|
||||
if (!messageType) return items;
|
||||
const target = messageType.toLowerCase();
|
||||
return items.filter((item) => [item.messageType, item.msgType, item.msgTypeName, item.msgName]
|
||||
.filter(Boolean)
|
||||
.some((value) => String(value).toLowerCase() === target || String(value).toLowerCase().includes(target)));
|
||||
}
|
||||
|
||||
export function mergeMessages(items: MessageItem[]): MessageItem[] {
|
||||
return [...items]
|
||||
.filter((item, index, all) => all.findIndex((candidate) => candidate.id === item.id) === index)
|
||||
.sort((left, right) => (right.sortTime ?? right.createTime ?? 0) - (left.sortTime ?? left.createTime ?? 0));
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
export interface MessageQueryOptions {
|
||||
start?: number;
|
||||
count?: number;
|
||||
read?: boolean;
|
||||
}
|
||||
|
||||
export interface MessageItem {
|
||||
id: string;
|
||||
title?: string;
|
||||
content?: string;
|
||||
messageType?: string;
|
||||
msgType?: string;
|
||||
msgTypeName?: string;
|
||||
msgName?: string;
|
||||
read: boolean;
|
||||
createTime?: number;
|
||||
updateTime?: number;
|
||||
sortTime?: number;
|
||||
sourceId?: string | null;
|
||||
sourceType?: string;
|
||||
sourceStatus?: string | null;
|
||||
url?: string;
|
||||
raw: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface MessagePageResult {
|
||||
total: number;
|
||||
start: number;
|
||||
count: number;
|
||||
read: boolean;
|
||||
items: MessageItem[];
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
# Permission Domain
|
||||
|
||||
权限域当前提供系统配置 → 权限页面的角色模型权限快照,只读查询:
|
||||
|
||||
- `GET /api/glue/v1/organization/permissions/query?model=ROLE&corpId=...`
|
||||
|
||||
CLI 入口为 `hose permission get`(也支持 `hose permissions get`)。写入权限仍需通过 Web 端明确操作,CLI 不提供写操作。
|
||||
@@ -0,0 +1,9 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import { PermissionReportSchema, type PermissionReport } from "./types.js";
|
||||
|
||||
export async function getRolePermissions(client: KyInstance, corpId: string): Promise<PermissionReport> {
|
||||
const response = await client.get("api/glue/v1/organization/permissions/query", { searchParams: { model: "ROLE", corpId } });
|
||||
const json = (await response.json()) as { value?: unknown };
|
||||
return PermissionReportSchema.parse(json.value ?? {});
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { getPermissions } from "./tools.js";
|
||||
|
||||
describe("Permission Domain - 角色权限", () => {
|
||||
it("parses the role permission snapshot", async () => {
|
||||
const client = { get: async () => new Response(JSON.stringify({ value: { type: "FREEDOM", permissions: [{ name: "CREATE", auth: true }, { name: "EDIT", auth: false }] } })) } as any;
|
||||
const result = await getPermissions(client, "corp-1");
|
||||
expect(result.type).toBe("FREEDOM"); expect(result.permissions).toHaveLength(2); expect(result.permissions[0]?.auth).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import { getRolePermissions } from "./api.js";
|
||||
|
||||
export async function getPermissions(client: KyInstance, corpId: string) { return getRolePermissions(client, corpId); }
|
||||
|
||||
export const permissionTools = [{
|
||||
name: "permission_role_get",
|
||||
description: "读取当前企业角色模型的权限开关(只读)",
|
||||
parameters: z.object({}),
|
||||
handler: async ({ corpContext }: any) => {
|
||||
const corp = corpContext.getCurrent(); if (!corp) throw new Error("未配置活跃企业上下文");
|
||||
const client = await import("../../core/auth/ekb.js").then((m) => m.createEkbClient(corp));
|
||||
return getPermissions(client, corp.corpId || corp.id);
|
||||
},
|
||||
}];
|
||||
@@ -0,0 +1,6 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const PermissionEntrySchema = z.object({ name: z.string(), auth: z.boolean().default(false) });
|
||||
export const PermissionReportSchema = z.object({ type: z.string().default(""), permissions: z.array(PermissionEntrySchema).default([]) });
|
||||
export type PermissionEntry = z.infer<typeof PermissionEntrySchema>;
|
||||
export type PermissionReport = z.infer<typeof PermissionReportSchema>;
|
||||
@@ -0,0 +1,20 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { analyzeWorkflow } from "./analysis.js";
|
||||
import { PlatformSchema } from "./types.js";
|
||||
|
||||
describe("Workflow static analysis", () => {
|
||||
it("accepts nullable app center metadata", () => {
|
||||
const platform = PlatformSchema.parse({ id: "app-1", name: "测试应用", corporationId: "corp-1", adminIds: null, importMethod: null });
|
||||
expect(platform.adminIds).toEqual([]);
|
||||
expect(platform.importMethod).toEqual([]);
|
||||
});
|
||||
|
||||
it("builds a recursive AST and extracts code references", () => {
|
||||
const result = analyzeWorkflow({ id: "wf-1", label: "审批", state: 1, version: "3", tasks: [{ name: "条件", type: "condition", label: "条件", groupName: "", orderIndex: 0, levelIndex: [0], status: "", tasks: [{ name: "脚本", type: "code-js2", label: "脚本", groupName: "", orderIndex: 1, levelIndex: [0, 0], status: "", code: "return {{bill.amount}} + ctx.user.id;" }] }] } as any);
|
||||
expect(result.ast[0]?.children[0]?.path).toBe("0.0"); expect(result.dependencies[0]?.references).toEqual(["bill.amount", "user.id"]); expect(result.diagnostics).toHaveLength(0);
|
||||
});
|
||||
it("reports empty scripts and branches", () => {
|
||||
const result = analyzeWorkflow({ id: "wf-2", label: "异常", state: 0, version: "", tasks: [{ name: "脚本", type: "code", label: "", groupName: "", orderIndex: 0, levelIndex: [0], status: "", code: "" }, { name: "条件", type: "condition", label: "", groupName: "", orderIndex: 1, levelIndex: [1], status: "", tasks: [] }] } as any);
|
||||
expect(result.diagnostics.map((item) => item.code)).toEqual(["EMPTY_CODE", "EMPTY_BRANCH"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { WorkflowDetail, WorkflowTask } from "./types.js";
|
||||
|
||||
export interface WorkflowAstNode { type: string; name: string; label: string; path: string; orderIndex: number; levelIndex: number[]; children: WorkflowAstNode[]; }
|
||||
export interface WorkflowDependency { path: string; taskType: string; references: string[]; }
|
||||
export interface WorkflowDiagnostic { severity: "warning" | "error"; code: string; path: string; message: string; }
|
||||
export interface WorkflowAnalysis { workflow: { id: string; label: string; state: number; version: string }; ast: WorkflowAstNode[]; dependencies: WorkflowDependency[]; diagnostics: WorkflowDiagnostic[]; }
|
||||
|
||||
const KNOWN_TYPES = new Set(["webhook", "condition", "every", "stop", "http", "flow-detail", "code", "code-js2", "ekuaibao-datalink-filter", "ekuaibao-datalink-create", "data-convert", "flow-create-task"]);
|
||||
function referencesFromTask(task: WorkflowTask): string[] {
|
||||
const code = typeof task.code === "string" ? task.code : "";
|
||||
const values = [...code.matchAll(/\{\{\s*([^{}]+?)\s*\}\}|\b(?:ctx|input|output|context)\.([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)/g)].map((match) => (match[1] || match[2] || "").trim()).filter(Boolean);
|
||||
return [...new Set(values)];
|
||||
}
|
||||
function toAst(tasks: WorkflowTask[], parentPath = ""): WorkflowAstNode[] { return tasks.map((task, index) => { const path = parentPath ? `${parentPath}.${index}` : String(index); return { type: task.type, name: task.name, label: task.label || task.displayName || "", path, orderIndex: task.orderIndex, levelIndex: task.levelIndex, children: toAst(task.tasks || [], path) }; }); }
|
||||
export function analyzeWorkflow(detail: WorkflowDetail): WorkflowAnalysis {
|
||||
const ast = toAst(detail.tasks); const dependencies: WorkflowDependency[] = []; const diagnostics: WorkflowDiagnostic[] = [];
|
||||
const visit = (tasks: WorkflowTask[], parentPath = "") => tasks.forEach((task, index) => { const path = parentPath ? `${parentPath}.${index}` : String(index); const refs = referencesFromTask(task); if (refs.length) dependencies.push({ path, taskType: task.type, references: refs }); if ((task.type === "code" || task.type === "code-js2") && !String(task.code || "").trim()) diagnostics.push({ severity: "error", code: "EMPTY_CODE", path, message: "代码节点没有可执行脚本" }); if ((task.type === "condition" || task.type === "every") && !(task.tasks || []).length) diagnostics.push({ severity: "warning", code: "EMPTY_BRANCH", path, message: `${task.type} 控制节点没有子节点` }); if (!KNOWN_TYPES.has(task.type)) diagnostics.push({ severity: "warning", code: "UNKNOWN_TASK_TYPE", path, message: `未收录的节点类型: ${task.type}` }); visit(task.tasks || [], path); });
|
||||
visit(detail.tasks); return { workflow: { id: detail.id, label: detail.label, state: detail.state, version: detail.version }, ast, dependencies, diagnostics };
|
||||
}
|
||||
@@ -14,9 +14,9 @@ export const PlatformSchema = z.object({
|
||||
groupType: z.string().default(""),
|
||||
platformType: z.string().default(""),
|
||||
source: z.string().default(""),
|
||||
adminIds: z.array(z.string()).default([]),
|
||||
adminIds: z.array(z.string()).nullish().transform((value) => value ?? []),
|
||||
desc: z.string().nullable().optional(),
|
||||
importMethod: z.array(z.string()).default([]),
|
||||
importMethod: z.array(z.string()).nullish().transform((value) => value ?? []),
|
||||
createTime: z.number().default(0),
|
||||
updateTime: z.number().default(0),
|
||||
});
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
# Role Domain
|
||||
|
||||
角色域提供企业角色定义、角色组和角色成员的只读查询。
|
||||
|
||||
- `GET /api/v1/organization/roles?start=0&count=2999&corpId=...`:角色定义列表
|
||||
- `GET /api/v1/organization/roleGroups?corpId=...`:角色组及其角色定义
|
||||
- `GET /api/v1/organization/staffs/byRole?roleDefId=...&corpId=...`:指定角色的员工成员
|
||||
|
||||
CLI 入口为 `hose role list`、`hose role groups` 和 `hose role members <角色 ID|编码|名称>`。
|
||||
@@ -0,0 +1,22 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import { RoleGroupSchema, RoleMemberSchema, RoleSchema, type Role, type RoleGroup, type RoleMember } from "./types.js";
|
||||
|
||||
export async function listRoles(client: KyInstance, corpId: string, start = 0, count = 2999): Promise<Role[]> {
|
||||
const response = await client.get("api/v1/organization/roles", { searchParams: { start: String(start), count: String(count), corpId } });
|
||||
const json = (await response.json()) as { items?: unknown[] };
|
||||
return z.array(RoleSchema).parse(json.items ?? []);
|
||||
}
|
||||
|
||||
export async function listRoleGroups(client: KyInstance, corpId: string): Promise<RoleGroup[]> {
|
||||
const response = await client.get("api/v1/organization/roleGroups", { searchParams: { corpId } });
|
||||
const json = (await response.json()) as { items?: unknown[] };
|
||||
return z.array(RoleGroupSchema).parse(json.items ?? []);
|
||||
}
|
||||
|
||||
export async function listRoleMembers(client: KyInstance, corpId: string, roleDefId: string): Promise<RoleMember[]> {
|
||||
const response = await client.get("api/v1/organization/staffs/byRole", { searchParams: { roleDefId, corpId } });
|
||||
const json = (await response.json()) as { items?: unknown[] };
|
||||
const items = (json.items ?? []).map((item: any) => item?.staff ?? item);
|
||||
return z.array(RoleMemberSchema).parse(items);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { getRoleMembers, getRoleGroups, searchRoles } from "./tools.js";
|
||||
|
||||
describe("Role Domain - 角色定义与成员", () => {
|
||||
it("loads and filters roles", async () => {
|
||||
const client = { get: async (path: string) => new Response(JSON.stringify(path.includes("roleGroups")
|
||||
? { items: [{ id: "group-1", name: "未分组", roleDefs: [{ id: "role-1", name: "财务主管", code: "FIN" }] }] }
|
||||
: { items: [{ id: "role-1", name: "财务主管", code: "FIN", roleGroupId: "group-1", scope: { name: "普通角色", properties: {} } }] })) } as any;
|
||||
const roles = await searchRoles(client, "corp-1", { keyword: "财务" });
|
||||
expect(roles).toHaveLength(1); expect(roles[0]?.id).toBe("role-1");
|
||||
expect((await getRoleGroups(client, "corp-1"))[0]?.name).toBe("未分组");
|
||||
});
|
||||
|
||||
it("resolves a role and loads its members", async () => {
|
||||
const client = { get: async (path: string) => new Response(JSON.stringify(path.includes("staffs/byRole")
|
||||
? { items: [{ id: "staff-1", name: "张三", code: "1001", departments: [] }] }
|
||||
: path.includes("roleGroups") ? { items: [] }
|
||||
: { items: [{ id: "role-1", name: "财务主管", code: "FIN", scope: { name: "普通角色", properties: {} } }] })) } as any;
|
||||
const report = await getRoleMembers(client, "corp-2", "FIN");
|
||||
expect(report?.role.name).toBe("财务主管"); expect(report?.members[0]?.name).toBe("张三");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import { listRoleGroups, listRoleMembers, listRoles } from "./api.js";
|
||||
import type { Role, RoleGroup, RoleMemberReport, RoleQuery } from "./types.js";
|
||||
|
||||
const cache = new Map<string, { timestamp: number; roles: Role[]; groups: RoleGroup[] }>();
|
||||
const CACHE_TTL_MS = 10 * 60 * 1000;
|
||||
async function getCatalog(client: KyInstance, corpId: string): Promise<{ roles: Role[]; groups: RoleGroup[] }> {
|
||||
const existing = cache.get(corpId);
|
||||
if (existing && Date.now() - existing.timestamp < CACHE_TTL_MS) return existing;
|
||||
const [roles, groups] = await Promise.all([listRoles(client, corpId), listRoleGroups(client, corpId)]);
|
||||
const result = { timestamp: Date.now(), roles, groups }; cache.set(corpId, result); return result;
|
||||
}
|
||||
|
||||
export async function searchRoles(client: KyInstance, corpId: string, query: RoleQuery = {}): Promise<Role[]> {
|
||||
const { roles } = await getCatalog(client, corpId);
|
||||
const keyword = (query.keyword || query.id || query.code || query.name || "").trim().toLowerCase();
|
||||
if (!keyword) return roles;
|
||||
return roles.filter((role) => [role.id, role.name, role.code, role.purposeName, role.scope.name].some((value) => value.toLowerCase().includes(keyword)));
|
||||
}
|
||||
export async function getRoleGroups(client: KyInstance, corpId: string): Promise<RoleGroup[]> { return (await getCatalog(client, corpId)).groups; }
|
||||
export async function resolveRole(client: KyInstance, corpId: string, target: string): Promise<Role | undefined> {
|
||||
const matches = await searchRoles(client, corpId, { keyword: target });
|
||||
return matches.find((role) => role.id === target || role.code === target || role.name === target) || matches[0];
|
||||
}
|
||||
export async function getRoleMembers(client: KyInstance, corpId: string, target: string): Promise<RoleMemberReport | undefined> {
|
||||
const role = await resolveRole(client, corpId, target); if (!role) return undefined;
|
||||
return { role, members: await listRoleMembers(client, corpId, role.id) };
|
||||
}
|
||||
|
||||
export const roleTools = [{
|
||||
name: "role_list", description: "列出当前企业角色定义与角色组",
|
||||
parameters: z.object({ keyword: z.string().optional(), count: z.number().optional() }),
|
||||
handler: async ({ corpContext }: any, params: { keyword?: string; count?: number }) => {
|
||||
const corp = corpContext.getCurrent(); if (!corp) throw new Error("未配置活跃企业上下文");
|
||||
const client = await import("../../core/auth/ekb.js").then((m) => m.createEkbClient(corp));
|
||||
const roles = await searchRoles(client, corp.corpId || corp.id, { keyword: params.keyword });
|
||||
return { count: roles.length, roles: roles.slice(0, params.count ?? 100) };
|
||||
},
|
||||
}];
|
||||
@@ -0,0 +1,38 @@
|
||||
import { z } from "zod";
|
||||
|
||||
const RoleScopeSchema = z.object({
|
||||
name: z.string().optional().default(""),
|
||||
enName: z.string().nullable().optional().default(""),
|
||||
properties: z.record(z.string(), z.string()).optional().default({}),
|
||||
});
|
||||
|
||||
export const RoleSchema = z.object({
|
||||
id: z.string(), name: z.string().default(""), code: z.string().optional().default(""),
|
||||
active: z.boolean().optional().default(true), corporationId: z.string().optional().default(""),
|
||||
roleGroupId: z.string().optional().default(""), scope: RoleScopeSchema.optional().default({ name: "", enName: "", properties: {} }),
|
||||
sourceType: z.string().optional().default(""), sourceTypeValue: z.string().nullable().optional(),
|
||||
purposeType: z.string().optional().default(""), purposeName: z.string().optional().default(""),
|
||||
locked: z.boolean().optional().default(false), containSubDept: z.boolean().optional().default(false),
|
||||
applicableToSubDepartments: z.boolean().optional().default(false),
|
||||
});
|
||||
|
||||
export const RoleGroupSchema = z.object({
|
||||
id: z.string(), name: z.string().default(""), code: z.string().optional().default(""),
|
||||
active: z.boolean().optional().default(true), corporationId: z.string().optional().default(""),
|
||||
roleDefs: z.array(RoleSchema).optional().default([]),
|
||||
});
|
||||
|
||||
export const RoleMemberSchema = z.object({
|
||||
id: z.string(), userId: z.string().optional().default(""), name: z.string().default(""),
|
||||
code: z.string().optional().default(""), enName: z.string().nullable().optional(),
|
||||
email: z.string().nullable().optional(), cellphone: z.string().nullable().optional(),
|
||||
active: z.boolean().optional().default(true), departments: z.array(z.string()).optional().default([]),
|
||||
defaultDepartment: z.string().nullable().optional(), external: z.boolean().optional().default(false),
|
||||
admin: z.boolean().optional().default(false),
|
||||
});
|
||||
|
||||
export type Role = z.infer<typeof RoleSchema>;
|
||||
export type RoleGroup = z.infer<typeof RoleGroupSchema>;
|
||||
export type RoleMember = z.infer<typeof RoleMemberSchema>;
|
||||
export interface RoleQuery { keyword?: string; id?: string; code?: string; name?: string; }
|
||||
export interface RoleMemberReport { role: Role; members: RoleMember[]; }
|
||||
@@ -0,0 +1,124 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import type { TaskQueryOptions, TaskView } from "./types.js";
|
||||
|
||||
const JOIN = [
|
||||
"flowId.form.payMoney.standardNumCode,standardNumCode,/v1/basedata/enumItems",
|
||||
"flowId.form.expenseMoney.standardNumCode,standardNumCode,/v1/basedata/enumItems",
|
||||
"flowId.form.loanMoney.standardNumCode,standardNumCode,/v1/basedata/enumItems",
|
||||
"flowId.form.requisitionMoney.standardNumCode,standardNumCode,/v1/basedata/enumItems",
|
||||
"flowId.id,nodeState,/flow/v2/backlogs/state",
|
||||
];
|
||||
|
||||
function dateFilter(options: TaskQueryOptions): string {
|
||||
if (options.from === undefined && options.to === undefined) return "";
|
||||
const from = options.from ?? 0;
|
||||
const to = options.to ?? 32503680000000;
|
||||
return `&&((updateTime > ${from}) && (updateTime < ${to}))`;
|
||||
}
|
||||
|
||||
function approvedDateFilter(options: TaskQueryOptions): string {
|
||||
if (options.from === undefined && options.to === undefined) return "";
|
||||
const from = options.from ?? 0;
|
||||
const to = options.to ?? 32503680000000;
|
||||
return `&&((approvedFlow.updateTime > ${from}) && (approvedFlow.updateTime < ${to}))`;
|
||||
}
|
||||
|
||||
function submittedDateFilter(options: TaskQueryOptions): string {
|
||||
if (options.from === undefined && options.to === undefined) return "";
|
||||
const from = options.from ?? 0;
|
||||
const to = options.to ?? 32503680000000;
|
||||
return `&&((form.submitDate > ${from}) && (form.submitDate < ${to}))`;
|
||||
}
|
||||
|
||||
function selectForBacklog(): string {
|
||||
return "flowId(ownerId(id,name,enName),form(title,code,specificationId(active,id,name,enName,nameSpell,code),submitDate,submitterId(id,name,enName,nickName,code,email,cellphone,note),reviewStatus,expenseMoney,loanMoney,requisitionMoney,payMoney),`...`),`...`";
|
||||
}
|
||||
|
||||
function selectForCarbonCopy(): string {
|
||||
return "flowId(ownerId(id,name,enName),form(title,code,specificationId(active,id,name,enName,nameSpell,code),submitDate,submitterId(id,name,enName,nickName,code,email,cellphone,note),reviewStatus,expenseMoney,loanMoney,requisitionMoney,payMoney),`...`),`...`";
|
||||
}
|
||||
|
||||
export async function fetchTaskPage(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
view: TaskView,
|
||||
options: TaskQueryOptions = {}
|
||||
): Promise<{ count: number; items: Record<string, unknown>[] }> {
|
||||
const start = options.start ?? 0;
|
||||
const count = options.count ?? 20;
|
||||
|
||||
if (view === "submitted") {
|
||||
const response = await client.post("api/flow/v1/flows/my", {
|
||||
searchParams: {
|
||||
type: "home5",
|
||||
delegatedFilter: "DELEGATE_TO_ME",
|
||||
corpId,
|
||||
},
|
||||
json: {
|
||||
filterBy: `(state.in("rejected","draft","sending","receiving","receivingExcep","approving","pending","paying","paid"))&&(INSTR(form.specificationId,"${corpId}:system:对账单")==0)${submittedDateFilter(options)}`,
|
||||
limit: { start, count },
|
||||
orderBy: [{ value: "form.submitDate", order: "DESC" }],
|
||||
},
|
||||
});
|
||||
const json = (await response.json()) as { count?: number; items?: Record<string, unknown>[] };
|
||||
return { count: json.count ?? json.items?.length ?? 0, items: json.items ?? [] };
|
||||
}
|
||||
|
||||
if (view === "cc") {
|
||||
const searchParams = new URLSearchParams({ corpId });
|
||||
searchParams.append("join", "flowId.id,nodeState,/flow/v2/backlogs/state");
|
||||
const state = options.read ? "READ" : "UNREAD";
|
||||
const response = await client.post("api/flow/v2/carbonCopy/search", {
|
||||
searchParams,
|
||||
json: {
|
||||
filterBy: `(state.in(\"${state}\"))&&((type != \"permit\"))`,
|
||||
limit: { start, count },
|
||||
select: selectForCarbonCopy(),
|
||||
orderBy: [{ value: "updateTime", order: "ASC" }],
|
||||
},
|
||||
});
|
||||
const json = (await response.json()) as { count?: number; items?: Record<string, unknown>[] };
|
||||
return { count: json.count ?? json.items?.length ?? 0, items: json.items ?? [] };
|
||||
}
|
||||
|
||||
if (view === "approved") {
|
||||
const response = await client.post("api/flow/v1/flows/approved", {
|
||||
searchParams: {
|
||||
join: "id,nodeState,/flow/v2/backlogs/state",
|
||||
corpId,
|
||||
},
|
||||
json: {
|
||||
query: {
|
||||
filterBy: `(approvedFlow.action==\"APPROVED\")&&((formType != \"permit\"))${approvedDateFilter(options)}`,
|
||||
limit: { start, count },
|
||||
select: "ownerId(id,name,enName),form(title,code,specificationId(active,id,name,enName,nameSpell,code),submitDate,submitterId(id,name,enName,nickName,code,email,cellphone,note),reviewStatus,expenseMoney,loanMoney,requisitionMoney,payMoney,`...`),`...`",
|
||||
},
|
||||
},
|
||||
});
|
||||
const json = (await response.json()) as { count?: number; items?: Record<string, unknown>[] };
|
||||
return { count: json.count ?? json.items?.length ?? 0, items: json.items ?? [] };
|
||||
}
|
||||
|
||||
const state = view === "todo" ? "APPROVING" : "PROCESSED";
|
||||
const orderBy = view === "todo"
|
||||
? [
|
||||
{ value: "flowId.state", order: "ASC" },
|
||||
{ value: "isUrgent", order: "DESC" },
|
||||
{ value: "updateTime", order: "ASC" },
|
||||
]
|
||||
: [{ value: "updateTime", order: "DESC" }];
|
||||
const searchParams = new URLSearchParams({ corpId });
|
||||
for (const join of JOIN) searchParams.append("join", join);
|
||||
const response = await client.post("api/flow/v2/backlogs/search", {
|
||||
searchParams,
|
||||
json: {
|
||||
filterBy: `(state.in(\"${state}\"))${dateFilter(options)}`,
|
||||
limit: { start, count },
|
||||
select: selectForBacklog(),
|
||||
orderBy,
|
||||
...(view === "todo" ? { creditSearch: true } : {}),
|
||||
},
|
||||
});
|
||||
const json = (await response.json()) as { count?: number; items?: Record<string, unknown>[] };
|
||||
return { count: json.count ?? json.items?.length ?? 0, items: json.items ?? [] };
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { normalizeTask } from "./tools.js";
|
||||
|
||||
describe("Task Domain - 待办任务模型", () => {
|
||||
test("normalizes backlog and preserves approval actions", () => {
|
||||
const item = normalizeTask({
|
||||
id: "backlog-1",
|
||||
state: "APPROVING",
|
||||
nodeState: { nodeName: "主管审批" },
|
||||
actions: { "staff-1": ["freeflow.agree", "freeflow.reject"] },
|
||||
flowId: {
|
||||
id: "flow-1",
|
||||
formType: "expense",
|
||||
ownerId: { id: "staff-1", name: "张三" },
|
||||
form: {
|
||||
code: "BX26000001",
|
||||
title: "差旅报销",
|
||||
specificationId: { name: "报销单" },
|
||||
submitterId: { id: "staff-2", name: "李四", code: "1002" },
|
||||
expenseMoney: { standard: "120.00", standardStrCode: "CNY", standardSymbol: "¥" },
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(item.taskId).toBe("backlog-1");
|
||||
expect(item.flowId).toBe("flow-1");
|
||||
expect(item.billCode).toBe("BX26000001");
|
||||
expect(item.submitter?.name).toBe("李四");
|
||||
expect(item.amount?.value).toBe("120.00");
|
||||
expect(item.actions).toEqual(["freeflow.agree", "freeflow.reject"]);
|
||||
});
|
||||
|
||||
test("normalizes flows returned by the submitted-bills endpoint", () => {
|
||||
const item = normalizeTask({
|
||||
flow: {
|
||||
id: "flow-submitted-1",
|
||||
state: "approving",
|
||||
ownerId: { id: "staff-1", name: "张三" },
|
||||
},
|
||||
form: {
|
||||
code: "BX26000002",
|
||||
title: "差旅报销",
|
||||
specification: { name: "差旅报销单" },
|
||||
submitterId: { id: "staff-1", name: "张三", code: "1001" },
|
||||
amount: { standard: "88.00", standardStrCode: "CNY", standardSymbol: "¥" },
|
||||
},
|
||||
});
|
||||
expect(item.taskId).toBe("flow-submitted-1");
|
||||
expect(item.state).toBe("approving");
|
||||
expect(item.templateName).toBe("差旅报销单");
|
||||
expect(item.amount?.value).toBe("88.00");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { fetchTaskPage } from "./api.js";
|
||||
import type { TaskItem, TaskPageResult, TaskPerson, TaskQueryOptions, TaskView } from "./types.js";
|
||||
|
||||
function record(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" ? value as Record<string, unknown> : {};
|
||||
}
|
||||
|
||||
function person(value: unknown): TaskPerson | undefined {
|
||||
const item = record(value);
|
||||
if (!Object.keys(item).length) return undefined;
|
||||
return {
|
||||
id: typeof item.id === "string" ? item.id : undefined,
|
||||
name: typeof item.name === "string" ? item.name : undefined,
|
||||
code: typeof item.code === "string" ? item.code : undefined,
|
||||
email: typeof item.email === "string" ? item.email : undefined,
|
||||
cellphone: typeof item.cellphone === "string" ? item.cellphone : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function money(value: unknown): TaskItem["amount"] {
|
||||
const item = record(value);
|
||||
if (item.standard === undefined) return undefined;
|
||||
return {
|
||||
value: String(item.standard),
|
||||
currency: typeof item.standardStrCode === "string" ? item.standardStrCode : undefined,
|
||||
symbol: typeof item.standardSymbol === "string" ? item.standardSymbol : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeTask(raw: Record<string, unknown>): TaskItem {
|
||||
const flow = record(raw.flowId ?? raw.flow);
|
||||
const form = record(flow.form ?? raw.form);
|
||||
const nodeState = record(raw.nodeState ?? flow.nodeState);
|
||||
const amount = money(form.expenseMoney ?? form.payMoney ?? form.requisitionMoney ?? form.loanMoney ?? form.amount);
|
||||
const specification = record(form.specificationId ?? form.specification);
|
||||
const submitter = person(form.submitterId);
|
||||
const owner = person(flow.ownerId ?? raw.ownerId);
|
||||
const actionsByStaff = record(flow.actions ?? raw.actions);
|
||||
const actionValues = Object.values(actionsByStaff).flatMap((value) => Array.isArray(value) ? value : []);
|
||||
const logs = Array.isArray(flow.logs) ? flow.logs : [];
|
||||
const logIndex = typeof raw.logId === "number" ? raw.logId : -1;
|
||||
const log = record(logs[logIndex] ?? logs[logs.length - 1]);
|
||||
const attributes = record(log.attributes);
|
||||
return {
|
||||
taskId: String(raw.id ?? flow.id ?? ""),
|
||||
flowId: typeof flow.id === "string" ? flow.id : typeof raw.id === "string" ? raw.id : undefined,
|
||||
billId: typeof flow.id === "string" ? flow.id : undefined,
|
||||
billCode: typeof form.code === "string" ? form.code : undefined,
|
||||
title: typeof form.title === "string" ? form.title : undefined,
|
||||
templateName: typeof specification.name === "string" ? specification.name : undefined,
|
||||
formType: typeof flow.formType === "string" ? flow.formType : typeof raw.type === "string" ? raw.type : undefined,
|
||||
state: typeof raw.state === "string" ? raw.state : typeof flow.state === "string" ? flow.state : undefined,
|
||||
action: typeof log.action === "string" ? log.action : typeof raw.action === "string" ? raw.action : undefined,
|
||||
actionTime: typeof log.time === "number" ? log.time : undefined,
|
||||
comment: typeof attributes.comment === "string" ? attributes.comment : undefined,
|
||||
nodeName: typeof nodeState.nodeName === "string" ? nodeState.nodeName : typeof raw.nodeName === "string" ? raw.nodeName : undefined,
|
||||
submitDate: typeof form.submitDate === "number" ? form.submitDate : undefined,
|
||||
submitter,
|
||||
owner,
|
||||
amount,
|
||||
actions: actionValues.filter((value): value is string => typeof value === "string"),
|
||||
updatedAt: typeof flow.updateTime === "number" ? flow.updateTime : typeof raw.updateTime === "number" ? raw.updateTime : undefined,
|
||||
raw,
|
||||
};
|
||||
}
|
||||
|
||||
export async function listTasks(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
view: TaskView,
|
||||
options: TaskQueryOptions = {}
|
||||
): Promise<TaskPageResult> {
|
||||
const page = await fetchTaskPage(client, corpId, view, options);
|
||||
let items = page.items.map(normalizeTask);
|
||||
if (options.staffId) {
|
||||
const target = options.staffId.toLowerCase();
|
||||
items = items.filter((item) => [item.submitter?.id, item.submitter?.code, item.owner?.id, item.owner?.code]
|
||||
.filter(Boolean)
|
||||
.some((value) => String(value).toLowerCase().includes(target)));
|
||||
}
|
||||
return {
|
||||
view,
|
||||
total: page.count,
|
||||
start: options.start ?? 0,
|
||||
count: options.count ?? 20,
|
||||
items,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const TaskViewSchema = z.enum(["todo", "approved", "processed", "cc", "submitted"]);
|
||||
export type TaskView = z.infer<typeof TaskViewSchema>;
|
||||
|
||||
export interface TaskQueryOptions {
|
||||
start?: number;
|
||||
count?: number;
|
||||
from?: number;
|
||||
to?: number;
|
||||
staffId?: string;
|
||||
read?: boolean;
|
||||
}
|
||||
|
||||
export interface TaskPerson {
|
||||
id?: string;
|
||||
name?: string;
|
||||
code?: string;
|
||||
email?: string;
|
||||
cellphone?: string;
|
||||
}
|
||||
|
||||
export interface TaskItem {
|
||||
taskId: string;
|
||||
flowId?: string;
|
||||
billId?: string;
|
||||
billCode?: string;
|
||||
title?: string;
|
||||
templateName?: string;
|
||||
formType?: string;
|
||||
state?: string;
|
||||
action?: string;
|
||||
actionTime?: number;
|
||||
comment?: string;
|
||||
nodeName?: string;
|
||||
submitDate?: number;
|
||||
submitter?: TaskPerson;
|
||||
owner?: TaskPerson;
|
||||
amount?: { value: string; currency?: string; symbol?: string };
|
||||
actions?: string[];
|
||||
updatedAt?: number;
|
||||
raw: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface TaskPageResult {
|
||||
view: TaskView;
|
||||
total: number;
|
||||
start: number;
|
||||
count: number;
|
||||
items: TaskItem[];
|
||||
}
|
||||
+1
-1
@@ -1 +1 @@
|
||||
export const VERSION = "0.5.2";
|
||||
export const VERSION = "0.6.1";
|
||||
Reference in new issue
Block a user