Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cd7bb44f04 | ||
|
|
0cdd62161f | ||
|
|
9f9f3abe22 | ||
|
|
fb700a4c86 |
No files matched your search
@@ -1,4 +1,4 @@
|
||||
# hose-use (v0.8.4)
|
||||
# hose-use (v0.8.5)
|
||||
|
||||
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
|
||||
|
||||
@@ -47,6 +47,12 @@ hose-use workflow list # 汇总查看全部工作流列
|
||||
hose-use workflow get <pipelineId> # 获取工作流详情与节点结构
|
||||
hose-use workflow find --task=code-js2 # 搜索包含特定节点类型的工作流
|
||||
hose-use workflow toggle <pipelineId> --state=1 # 启用/停用工作流
|
||||
hose-use workflow save <pipelineId> --file=workflow.json # 按完整快照保存草稿
|
||||
hose-use workflow patch <pipelineId> --file=workflow.json --path=tasks.0.code --value='return 2;' --output=patched.json
|
||||
hose-use workflow history <pipelineId> # 查看服务端版本快照历史
|
||||
hose-use workflow logs <pipelineId> --state=FAILED # 查看工作流运行错误日志
|
||||
hose-use workflow check --json --fail-on-alert # 检查错误管道并按错误计数去重提醒
|
||||
hose-use workflow publish <pipelineId> # 保存后的发布/启用
|
||||
hose-use platform list # 查看企业下所有启用的自建应用
|
||||
|
||||
# 5. 单据与费用明细管理 (DataLink 字典自动还原 & 200KB 防爆拦截)
|
||||
|
||||
@@ -66,6 +66,12 @@ CLI 入口保持在 `platform` 命令域,支持 `list`、`get`、`entities`、
|
||||
| `platform_workflow_charge` | 查询企业工作流用量配额 | EASO |
|
||||
| `platform_workflow_detail` | 获取工作流详情(含节点配置) | EASO / Piper |
|
||||
| `platform_workflow_toggle` | 启用/停用工作流 | EASO / Piper |
|
||||
| `workflow save` (CLI) | 按完整快照保存工作流草稿并校验版本 | Piper |
|
||||
| `workflow history` (CLI) | 读取工作流服务端版本快照历史 | Piper |
|
||||
| `workflow patch` (CLI) | 在本地完整快照上修改节点路径,生成新草稿文件 | 本地 |
|
||||
| `workflow logs` (CLI) | 查询指定工作流运行日志 | Piper |
|
||||
| `workflow check` (CLI) | 扫描错误管道并持久化去重提醒 | 本地 + EASO |
|
||||
| `workflow publish` (CLI) | 将已保存的工作流状态切换为启用 | Piper |
|
||||
| `platform_workflow_jobs` | 查询工作流运行中的任务 | EASO / Piper |
|
||||
| `platform_workflow_dsl` | 获取工作流 DSL 配置列表 | EASO / Piper |
|
||||
| `platform_workflow_staffs` | 获取企业员工列表 | EASO / Piper |
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.8.4",
|
||||
"version": "0.8.5",
|
||||
"module": "src/server.ts",
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
---
|
||||
name: hose-use
|
||||
description: "v0.8.4: 合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号 API 登录、租户切换、单据检索与审批动作、工作流跨域扫描、内置 HTTP 交互文档与常驻守护进程。"
|
||||
description: "v0.8.5: 合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号 API 登录、租户切换、单据检索与审批动作、工作流跨域扫描、内置 HTTP 交互文档与常驻守护进程。"
|
||||
metadata:
|
||||
version: 0.8.4
|
||||
short-description: 合思/易快报企业级 CLI 工具与底层 SDK (v0.8.4)
|
||||
version: 0.8.5
|
||||
short-description: 合思/易快报企业级 CLI 工具与底层 SDK (v0.8.5)
|
||||
---
|
||||
|
||||
# hose-use (v0.8.4)
|
||||
# hose-use (v0.8.5)
|
||||
|
||||
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
|
||||
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
|
||||
@@ -49,6 +49,7 @@ metadata:
|
||||
| 单据附件 / 发票原件标准列表 | `hose-use bill attachments <单号|ID>` | [references/bill.md](references/bill.md) |
|
||||
| 单据附件下载 | `hose-use bill download <单号|ID> --output-dir <目录>` | [references/bill.md](references/bill.md) |
|
||||
| 系统/自定义档案维度与档案项 | `hose-use dimension list`, `hose-use dimension items <维度>` | [references/dimension.md](references/dimension.md) |
|
||||
| 费用类型全生命周期与表单规格 (增删查改/停启用/移动/字段) | `hose-use feetype list`, `hose-use feetype create`, `hose-use feetype get <ID>` | [references/feetype.md](references/feetype.md) |
|
||||
| 企业角色、角色组与角色成员 | `hose-use role list`, `hose-use role groups`, `hose-use role members <角色>` | [references/role.md](references/role.md) |
|
||||
| 角色权限只读快照 | `hose-use permission get` | [references/role.md](references/role.md) |
|
||||
| 单据 Web 详情直达链接生成 | `hose-use bill link <单号|ID>` | [references/bill.md](references/bill.md) |
|
||||
@@ -62,8 +63,9 @@ metadata:
|
||||
| 桌面端全站主导航与一级模块树 | `hose-use menu list`, `hose-use menu tree` | [references/workflow.md](references/workflow.md) |
|
||||
| 模糊搜索已保存的企业与员工信息 | `hose-use corps search <关键词>` | [references/auth.md](references/auth.md) |
|
||||
| 特定任务节点扫描 (如脚本/Webhook) | `hose-use workflow find --task=code-js2` | [references/workflow.md](references/workflow.md) |
|
||||
| 工作流详情与开通切换 | `hose-use workflow get`, `hose-use workflow toggle` | [references/workflow.md](references/workflow.md) |
|
||||
| 工作流详情、节点草稿修改、草稿保存、版本历史、运行日志、发布与开通切换 | `hose-use workflow get`, `hose-use workflow patch`, `hose-use workflow save`, `hose-use workflow publish`, `hose-use workflow history`, `hose-use workflow logs`, `hose-use workflow toggle` | [references/workflow.md](references/workflow.md) |
|
||||
| 工作流节点树、代码依赖与静态诊断 | `hose-use workflow analyze <pipelineId>` | [references/workflow.md](references/workflow.md) |
|
||||
| 工作流错误管道扫描与本地去重提醒 | `hose-use workflow check [--fail-on-alert]` | [references/workflow.md](references/workflow.md) |
|
||||
| 常驻守护进程管理 / 后台运行 | `hose-use service start`, `hose-use service status` | [references/service.md](references/service.md) |
|
||||
| 待办/消息事件轮询与去重 | `hose-use service poll --corp=<id>` | [references/service.md](references/service.md) |
|
||||
| 启动本地 HTTP 服务 / 打开可视化交互文档 | `hose-use http --port=8888` (访问 `/docs`) | [references/service.md](references/service.md) |
|
||||
@@ -113,6 +115,13 @@ hose-use bill attachments S26000001 # 查看附件和发票
|
||||
hose-use bill download S26000001 --output-dir ./downloads # 下载附件到本地目录
|
||||
hose-use dimension list # 查看系统与自定义档案维度
|
||||
hose-use dimension items 项目 # 查看项目、成本中心等档案项
|
||||
hose-use feetype list # 树形层级查看企业费用类型
|
||||
hose-use feetype get 交通费 --specs # 查看费用类型详情与报账/申请字段
|
||||
hose-use feetype create --name="市内打车" --parent="交通费" # 在指定父级下新建费用类型
|
||||
hose-use feetype update 市内打车 --desc="滴滴企业版" # 修改费用类型属性
|
||||
hose-use feetype disable 市内打车 # 停用费用类型 (软删除)
|
||||
hose-use feetype enable 市内打车 # 重新启用费用类型
|
||||
hose-use feetype move 市内打车 --parent="差旅费用" # 移动费用类型到新父级
|
||||
hose-use role list # 查看企业角色定义
|
||||
hose-use role groups # 查看角色组及其角色
|
||||
hose-use role members 财务主管 # 查看指定角色成员
|
||||
@@ -141,6 +150,12 @@ hose-use workflow list # 聚合扫描全部自
|
||||
hose-use workflow find --task=code-js2 # 查找部署了代码节点的工作流
|
||||
hose-use workflow get wf_01k83y... # 查看指定工作流节点拓扑
|
||||
hose-use workflow analyze wf_01k83y... --json # 输出节点树、引用依赖与静态诊断
|
||||
hose-use workflow save wf_01k83y... --file=workflow.json # 按完整快照保存草稿并做版本保护
|
||||
hose-use workflow patch wf_01k83y... --file=workflow.json --path=tasks.0.code --value='return 2;' --output=patched.json
|
||||
hose-use workflow history wf_01k83y... --json # 查看服务端版本快照历史
|
||||
hose-use workflow logs wf_01k83y... --state=FAILED # 查看运行错误日志
|
||||
hose-use workflow check --json --fail-on-alert # 扫描错误管道并只提醒新增错误计数
|
||||
hose-use workflow publish wf_01k83y... # 将保存后的工作流发布/启用
|
||||
|
||||
# 6. 服务与守护进程
|
||||
hose-use http --port=8888 # 启动前台 HTTP 服务与交互式文档
|
||||
|
||||
@@ -11,6 +11,6 @@ tools:
|
||||
properties:
|
||||
command:
|
||||
type: "string"
|
||||
description: "完整的 hose-use 命令字符串,例如 'bill list --json', 'workflow find --task=code-js2', 'service status'"
|
||||
description: "完整的 hose-use 命令字符串,例如 'bill list --json', 'workflow check --json', 'workflow get <pipelineId> --json -o workflow.json', 'workflow save <pipelineId> --file=workflow.json', 'service status'"
|
||||
required:
|
||||
- "command"
|
||||
@@ -0,0 +1,33 @@
|
||||
# 费用类型与表单字段规格管理 (feetype)
|
||||
|
||||
费用类型 (FeeType) 是合思/易快报费控系统的底层核心业务实体,涵盖企业报销科目树、单据表单字段规则规格以及申请/报账控件配置。
|
||||
|
||||
## 常用命令
|
||||
|
||||
```bash
|
||||
# 1. 列表与树形层级
|
||||
hose-use feetype list # 树形层级展示当前企业所有活跃费用类型
|
||||
hose-use feetype list --all # 包含已停用的全量费用类型
|
||||
hose-use feetype list --keyword="差旅" # 模糊搜索名称、编码或路径
|
||||
hose-use feetype list --flat # 以平铺表格格式展示
|
||||
hose-use feetype list --json # JSON 结构化输出 (Agent 推荐)
|
||||
|
||||
# 2. 单项详情与字段规格
|
||||
hose-use feetype get 交通费 # 查看费用类型基本配置、层级与父子节点
|
||||
hose-use feetype get 交通费 --specs # 同时输出报账字段与申请字段配置摘要
|
||||
hose-use feetype fields 交通费 # 查看完整的报账与申请字段表格 (字段名、类型、必填、可编辑)
|
||||
|
||||
# 3. 创建与修改 (增改)
|
||||
hose-use feetype create --name="市内打车费" --parent="交通费" # 在指定父级下创建,自动继承父级字段规则
|
||||
hose-use feetype create --name="公杂费" --code="COST88" # 自定义编码并建在顶级
|
||||
hose-use feetype update 市内打车费 --desc="包含出租车与网约车" # 修改描述或属性
|
||||
hose-use feetype update 市内打车费 --color="#4caf50" # 修改标识颜色
|
||||
|
||||
# 4. 停用与启用 (删查)
|
||||
hose-use feetype disable 市内打车费 # 停用费用类型 (软删除,用户端隐藏)
|
||||
hose-use feetype enable 市内打车费 # 重新启用费用类型 (支持 --recursive 级联启用)
|
||||
|
||||
# 5. 调整层级结构
|
||||
hose-use feetype move 市内打车费 --parent="差旅费用" # 移动至差旅费用之下
|
||||
hose-use feetype move 市内打车费 --parent=root # 移至企业顶级根节点
|
||||
```
|
||||
@@ -131,3 +131,64 @@ hose-use workflow toggle wf_01k83y... --disable
|
||||
```bash
|
||||
hose-use workflow analyze wf_01k83y... --json
|
||||
```
|
||||
|
||||
## 8. 工作流草稿保存 (`workflow save`)
|
||||
|
||||
Web 端“保存更新”是对完整 pipeline 的 PUT,而不是单节点 PATCH。推荐先导出详情,再修改 JSON,最后按版本保护保存:
|
||||
|
||||
```bash
|
||||
hose-use workflow get <pipelineId> --json -o workflow.json
|
||||
# 修改 workflow.json 中的 tasks / inputs / $snapshot 等字段
|
||||
hose-use workflow save <pipelineId> --file=workflow.json
|
||||
```
|
||||
|
||||
命令会先重新读取远端版本;若 `version` 或 `tasksVersion` 已变化会拒绝覆盖。确认需要强制覆盖时显式使用 `--force-write`。
|
||||
|
||||
## 9. 本地节点草稿修改 (`workflow patch`)
|
||||
|
||||
网页编辑器最终提交的是完整 pipeline,因此节点修改先在完整 JSON 草稿上完成,再交给 `workflow save` 做版本保护和服务端持久化:
|
||||
|
||||
```bash
|
||||
hose-use workflow patch <pipelineId> \\
|
||||
--file=workflow.json \\
|
||||
--path=tasks.1.form.title \\
|
||||
--value="新的标题" \\
|
||||
--output=workflow.patched.json
|
||||
```
|
||||
|
||||
数组也可以使用 `tasks[1].form.title`。需要写入数字、布尔值或对象时加 `--value-json`;使用 `--in-place` 才会覆盖输入文件。该命令只修改本地草稿,不直接触发远端写入。
|
||||
|
||||
## 10. 工作流版本历史 (`workflow history`)
|
||||
|
||||
服务端每次完整保存都会生成一个版本快照,可用以下命令读取审计历史:
|
||||
|
||||
```bash
|
||||
hose-use workflow history <pipelineId> --json
|
||||
```
|
||||
|
||||
## 11. 运行日志与错误管道提醒
|
||||
|
||||
查询单个工作流的运行日志:
|
||||
|
||||
```bash
|
||||
hose-use workflow logs <pipelineId> --state=FAILED --json
|
||||
```
|
||||
|
||||
扫描企业内工作流列表中的 `errorCount`,并把已提醒的错误计数保存在本地状态文件;同一错误计数不会重复提醒,错误计数增加时才产生新提醒:
|
||||
|
||||
```bash
|
||||
hose-use workflow check --json
|
||||
hose-use workflow check --json --fail-on-alert
|
||||
```
|
||||
|
||||
默认状态文件为 `~/.config/hose-use/workflow-alerts-<corp>.json`,可用 `--state-file` 指定。`--fail-on-alert` 适合被常驻服务或外部调度器检测;它只改变退出码,不自动向外部人员发送消息。
|
||||
|
||||
## 12. 发布工作流 (`workflow publish`)
|
||||
|
||||
网页端发布动作对应 Piper 的状态接口:`PUT /api/easo/pipelines/state/{pipelineId}?state=1`。CLI 提供同等入口:
|
||||
|
||||
```bash
|
||||
hose-use workflow publish <pipelineId>
|
||||
```
|
||||
|
||||
建议先执行 `workflow save`,确认保存成功后再执行 `workflow publish`;发布只切换启用状态,不替代完整配置保存。
|
||||
@@ -0,0 +1,425 @@
|
||||
import { describe, it, expect, spyOn } from "bun:test";
|
||||
import { handleFeeTypeCommand } from "./feetype.js";
|
||||
import * as feetypeTools from "../../domains/feetype/tools.js";
|
||||
import type { CliRuntime } from "../types.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import { FeeTypeNode } from "../../domains/feetype/types.js";
|
||||
|
||||
describe("CLI - feetype 费用类型管理命令", () => {
|
||||
const dummyRuntimeNoCorp: CliRuntime = {
|
||||
corpContext: {
|
||||
listCorps: () => [],
|
||||
getCurrent: () => null,
|
||||
switchCorp: () => false,
|
||||
resolve: () => null,
|
||||
} as any,
|
||||
selectedCorp: null,
|
||||
jsonMode: false,
|
||||
};
|
||||
|
||||
const mockCorp: CorpConfig = {
|
||||
id: "corp_test",
|
||||
name: "测试科技企业",
|
||||
source: "account",
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
credentials: {
|
||||
accessToken: "mock-token",
|
||||
corpId: "corp_test",
|
||||
staffId: "mock-staff",
|
||||
},
|
||||
};
|
||||
|
||||
const dummyRuntimeWithCorp: CliRuntime = {
|
||||
corpContext: {
|
||||
listCorps: () => [mockCorp],
|
||||
getCurrent: () => mockCorp,
|
||||
switchCorp: () => true,
|
||||
resolve: () => mockCorp,
|
||||
} as any,
|
||||
selectedCorp: mockCorp,
|
||||
jsonMode: false,
|
||||
};
|
||||
|
||||
const mockTree = [
|
||||
{
|
||||
feeType: {
|
||||
id: "ft_travel",
|
||||
name: "差旅费用",
|
||||
code: "COST19",
|
||||
active: true,
|
||||
parentId: "",
|
||||
order: 1000,
|
||||
color: "#90caf9",
|
||||
icon: "https://images.ekuaibao.com/feetype/sf_100.png",
|
||||
description: "员工差旅相关费用",
|
||||
},
|
||||
children: [
|
||||
{
|
||||
feeType: {
|
||||
id: "ft_flight",
|
||||
name: "飞机票",
|
||||
code: "COST54",
|
||||
active: true,
|
||||
parentId: "ft_travel",
|
||||
order: 1001,
|
||||
color: "#90caf9",
|
||||
icon: "",
|
||||
description: "",
|
||||
},
|
||||
children: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
feeType: {
|
||||
id: "ft_disabled",
|
||||
name: "已停用费用",
|
||||
code: "COST99",
|
||||
active: false,
|
||||
parentId: "",
|
||||
order: 2000,
|
||||
color: "#ccc",
|
||||
icon: "",
|
||||
description: "",
|
||||
},
|
||||
children: [],
|
||||
},
|
||||
] as unknown as FeeTypeNode[];
|
||||
|
||||
it("未选中企业时抛出友好错误", async () => {
|
||||
expect(
|
||||
handleFeeTypeCommand(
|
||||
{
|
||||
area: "feetype",
|
||||
action: "list",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["feetype", "list"],
|
||||
},
|
||||
dummyRuntimeNoCorp
|
||||
)
|
||||
).rejects.toThrow("未指定或未找到有效企业");
|
||||
});
|
||||
|
||||
it("feetype list 默认以树形层级展示活跃费用类型", async () => {
|
||||
const spy = spyOn(feetypeTools, "listFeeTypes").mockResolvedValue({
|
||||
total: 3,
|
||||
items: mockTree,
|
||||
rawTree: mockTree,
|
||||
});
|
||||
|
||||
const res = await handleFeeTypeCommand(
|
||||
{
|
||||
area: "feetype",
|
||||
action: "list",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["feetype", "list"],
|
||||
},
|
||||
dummyRuntimeWithCorp
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("费用类型列表");
|
||||
expect(res.stdout).toContain("差旅费用");
|
||||
expect(res.stdout).toContain("飞机票");
|
||||
expect(res.stdout).toContain("COST19");
|
||||
expect(res.stdout).toContain("🟢 启用");
|
||||
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it("feetype list --json 支持结构化输出", async () => {
|
||||
const spy = spyOn(feetypeTools, "listFeeTypes").mockResolvedValue({
|
||||
total: 2,
|
||||
items: mockTree,
|
||||
rawTree: mockTree,
|
||||
});
|
||||
|
||||
const jsonRuntime = { ...dummyRuntimeWithCorp, jsonMode: true };
|
||||
const res = await handleFeeTypeCommand(
|
||||
{
|
||||
area: "feetype",
|
||||
action: "list",
|
||||
args: [],
|
||||
options: { json: true },
|
||||
raw: ["feetype", "list", "--json"],
|
||||
},
|
||||
jsonRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
const parsed = JSON.parse(res.stdout);
|
||||
expect(parsed.corpId).toBe("corp_test");
|
||||
expect(parsed.total).toBe(2);
|
||||
expect(parsed.items.length).toBe(2);
|
||||
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it("feetype get 查询单个费用类型详情及字段规格", async () => {
|
||||
const mockDetail = {
|
||||
feeType: {
|
||||
id: "ft_travel",
|
||||
name: "差旅费用",
|
||||
code: "COST19",
|
||||
active: true,
|
||||
parentId: "",
|
||||
path: "差旅费用",
|
||||
parentName: "顶级 (根节点)",
|
||||
childrenCount: 1,
|
||||
color: "#90caf9",
|
||||
icon: "https://images.ekuaibao.com/feetype/sf_100.png",
|
||||
description: "差旅综合报销",
|
||||
},
|
||||
specifications: {
|
||||
expenseComponents: [
|
||||
{ field: "amount", cnLabel: "报销金额", type: "money", optional: false },
|
||||
],
|
||||
requisitionComponents: [
|
||||
{ field: "amount", cnLabel: "预计金额", type: "money", optional: true },
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const spy = spyOn(feetypeTools, "getFeeTypeDetail").mockResolvedValue(mockDetail as any);
|
||||
|
||||
const res = await handleFeeTypeCommand(
|
||||
{
|
||||
area: "feetype",
|
||||
action: "get",
|
||||
args: ["差旅费用"],
|
||||
options: { specs: true },
|
||||
raw: ["feetype", "get", "差旅费用", "--specs"],
|
||||
},
|
||||
dummyRuntimeWithCorp
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("差旅费用");
|
||||
expect(res.stdout).toContain("COST19");
|
||||
expect(res.stdout).toContain("报销金额 (amount) - money [必填]");
|
||||
expect(res.stdout).toContain("预计金额 (amount) - money [选填]");
|
||||
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it("feetype create 创建费用类型并展示卡片", async () => {
|
||||
const mockCreated = {
|
||||
id: "ft_hotel",
|
||||
name: "酒店住宿",
|
||||
code: "COST66",
|
||||
active: true,
|
||||
parentId: "ft_travel",
|
||||
path: "差旅费用 / 酒店住宿",
|
||||
parentName: "差旅费用",
|
||||
childrenCount: 0,
|
||||
color: "#90caf9",
|
||||
icon: "",
|
||||
description: "出差酒店",
|
||||
};
|
||||
|
||||
const spy = spyOn(feetypeTools, "createFeeType").mockResolvedValue(mockCreated as any);
|
||||
|
||||
const res = await handleFeeTypeCommand(
|
||||
{
|
||||
area: "feetype",
|
||||
action: "create",
|
||||
args: [],
|
||||
options: {
|
||||
name: "酒店住宿",
|
||||
parent: "差旅费用",
|
||||
},
|
||||
raw: ["feetype", "create", "--name=酒店住宿", "--parent=差旅费用"],
|
||||
},
|
||||
dummyRuntimeWithCorp
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("费用类型创建成功");
|
||||
expect(res.stdout).toContain("酒店住宿");
|
||||
expect(res.stdout).toContain("COST66");
|
||||
expect(res.stdout).toContain("差旅费用 / 酒店住宿");
|
||||
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it("feetype update 修改费用类型属性", async () => {
|
||||
const mockUpdated = {
|
||||
id: "ft_hotel",
|
||||
name: "酒店住宿(改)",
|
||||
code: "COST66",
|
||||
active: true,
|
||||
parentId: "ft_travel",
|
||||
path: "差旅费用 / 酒店住宿(改)",
|
||||
parentName: "差旅费用",
|
||||
childrenCount: 0,
|
||||
color: "#90caf9",
|
||||
icon: "",
|
||||
description: "新说明",
|
||||
};
|
||||
|
||||
const spy = spyOn(feetypeTools, "updateFeeTypeInfo").mockResolvedValue(mockUpdated as any);
|
||||
|
||||
const res = await handleFeeTypeCommand(
|
||||
{
|
||||
area: "feetype",
|
||||
action: "update",
|
||||
args: ["酒店住宿"],
|
||||
options: { desc: "新说明" },
|
||||
raw: ["feetype", "update", "酒店住宿", "--desc=新说明"],
|
||||
},
|
||||
dummyRuntimeWithCorp
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("费用类型修改成功");
|
||||
expect(res.stdout).toContain("新说明");
|
||||
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it("feetype disable 停用费用类型", async () => {
|
||||
const spy = spyOn(feetypeTools, "disableFeeTypeItem").mockResolvedValue({
|
||||
success: true,
|
||||
item: {
|
||||
id: "ft_hotel",
|
||||
name: "酒店住宿",
|
||||
code: "COST66",
|
||||
active: false,
|
||||
} as any,
|
||||
});
|
||||
|
||||
const res = await handleFeeTypeCommand(
|
||||
{
|
||||
area: "feetype",
|
||||
action: "disable",
|
||||
args: ["酒店住宿"],
|
||||
options: { yes: true },
|
||||
raw: ["feetype", "disable", "酒店住宿", "--yes"],
|
||||
},
|
||||
dummyRuntimeWithCorp
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("已成功停用");
|
||||
expect(res.stdout).toContain("酒店住宿");
|
||||
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it("feetype enable 重新启用费用类型", async () => {
|
||||
const spy = spyOn(feetypeTools, "enableFeeTypeItem").mockResolvedValue({
|
||||
success: true,
|
||||
item: {
|
||||
id: "ft_hotel",
|
||||
name: "酒店住宿",
|
||||
code: "COST66",
|
||||
active: true,
|
||||
} as any,
|
||||
});
|
||||
|
||||
const res = await handleFeeTypeCommand(
|
||||
{
|
||||
area: "feetype",
|
||||
action: "enable",
|
||||
args: ["酒店住宿"],
|
||||
options: {},
|
||||
raw: ["feetype", "enable", "酒店住宿"],
|
||||
},
|
||||
dummyRuntimeWithCorp
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("已成功启用");
|
||||
expect(res.stdout).toContain("酒店住宿");
|
||||
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it("feetype move 移动费用类型父级节点", async () => {
|
||||
const spy = spyOn(feetypeTools, "moveFeeTypeItem").mockResolvedValue({
|
||||
success: true,
|
||||
item: {
|
||||
id: "ft_hotel",
|
||||
name: "酒店住宿",
|
||||
code: "COST66",
|
||||
active: true,
|
||||
path: "办公费 / 酒店住宿",
|
||||
} as any,
|
||||
parentName: "办公费",
|
||||
});
|
||||
|
||||
const res = await handleFeeTypeCommand(
|
||||
{
|
||||
area: "feetype",
|
||||
action: "move",
|
||||
args: ["酒店住宿"],
|
||||
options: { parent: "办公费" },
|
||||
raw: ["feetype", "move", "酒店住宿", "--parent=办公费"],
|
||||
},
|
||||
dummyRuntimeWithCorp
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("费用类型移动成功");
|
||||
expect(res.stdout).toContain("新所属父级 : 办公费");
|
||||
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it("feetype fields 打印报账与申请字段表格", async () => {
|
||||
const spy = spyOn(feetypeTools, "getFeeTypeFieldsList").mockResolvedValue({
|
||||
feeType: {
|
||||
id: "ft_travel",
|
||||
name: "差旅费用",
|
||||
code: "COST19",
|
||||
} as any,
|
||||
expenseFields: [
|
||||
{
|
||||
field: "amount",
|
||||
label: "金额",
|
||||
type: "money",
|
||||
required: true,
|
||||
editable: true,
|
||||
hidden: false,
|
||||
},
|
||||
],
|
||||
requisitionFields: [],
|
||||
});
|
||||
|
||||
const res = await handleFeeTypeCommand(
|
||||
{
|
||||
area: "feetype",
|
||||
action: "fields",
|
||||
args: ["差旅费用"],
|
||||
options: {},
|
||||
raw: ["feetype", "fields", "差旅费用"],
|
||||
},
|
||||
dummyRuntimeWithCorp
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("费用类型字段配置");
|
||||
expect(res.stdout).toContain("报账字段列表");
|
||||
expect(res.stdout).toContain("amount");
|
||||
expect(res.stdout).toContain("🔴 必填");
|
||||
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it("未知 feetype 子命令时抛出支持说明", async () => {
|
||||
expect(
|
||||
handleFeeTypeCommand(
|
||||
{
|
||||
area: "feetype",
|
||||
action: "invalidCmd",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["feetype", "invalidCmd"],
|
||||
},
|
||||
dummyRuntimeWithCorp
|
||||
)
|
||||
).rejects.toThrow("未知 feetype 子命令");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,516 @@
|
||||
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import { booleanOption, stringOption } from "../parser.js";
|
||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||
import {
|
||||
createFeeType,
|
||||
disableFeeTypeItem,
|
||||
enableFeeTypeItem,
|
||||
findFeeType,
|
||||
FlatFeeTypeItem,
|
||||
flattenFeeTypeTree,
|
||||
getFeeTypeDetail,
|
||||
getFeeTypeFieldsList,
|
||||
listFeeTypes,
|
||||
moveFeeTypeItem,
|
||||
updateFeeTypeInfo,
|
||||
} from "../../domains/feetype/tools.js";
|
||||
import { FeeTypeNode } from "../../domains/feetype/types.js";
|
||||
|
||||
/**
|
||||
* 递归渲染树形层级格式
|
||||
*/
|
||||
function renderTreeRows(
|
||||
nodes: FeeTypeNode[],
|
||||
depth = 0,
|
||||
prefix = "",
|
||||
isLast = true,
|
||||
acc: (string | number)[][] = []
|
||||
): (string | number)[][] {
|
||||
for (let i = 0; i < nodes.length; i++) {
|
||||
const node = nodes[i];
|
||||
const item = node.feeType;
|
||||
if (!item) continue;
|
||||
|
||||
const currentIsLast = i === nodes.length - 1;
|
||||
const branch = depth === 0 ? "" : isLast ? "└─ " : "├─ ";
|
||||
const indent = depth === 0 ? "" : prefix + branch;
|
||||
const nextPrefix = depth === 0 ? "" : prefix + (isLast ? " " : "│ ");
|
||||
|
||||
const children = Array.isArray(node.children) ? node.children : [];
|
||||
acc.push([
|
||||
acc.length + 1,
|
||||
`${indent}${item.name}`,
|
||||
item.code || "-",
|
||||
item.id,
|
||||
item.active ? "🟢 启用" : "🔴 停用",
|
||||
children.length ? `${children.length} 项` : "-",
|
||||
]);
|
||||
|
||||
if (children.length > 0) {
|
||||
renderTreeRows(children, depth + 1, nextPrefix, currentIsLast, acc);
|
||||
}
|
||||
}
|
||||
return acc;
|
||||
}
|
||||
|
||||
export async function handleFeeTypeCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const corp = runtime.selectedCorp;
|
||||
if (!corp) {
|
||||
throw new Error(
|
||||
"未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose-use auth login 登录。"
|
||||
);
|
||||
}
|
||||
|
||||
const client = await createEkbClient(corp);
|
||||
const corpId = corp.corpId || corp.id;
|
||||
const action = (parsed.action?.toLowerCase() || "list").trim();
|
||||
|
||||
// ── 1. 列表 / 树形展示 (list / tree) ──────────────────────────────────────────
|
||||
if (["list", "tree", "all", "search"].includes(action)) {
|
||||
const includeAll =
|
||||
action === "all" ||
|
||||
booleanOption(parsed.options, ["all", "a", "include-disabled"]) ||
|
||||
false;
|
||||
const isFlat =
|
||||
booleanOption(parsed.options, ["flat", "flatten", "table"]) || false;
|
||||
const keyword =
|
||||
stringOption(parsed.options, ["keyword", "q", "query"]) || parsed.args[0];
|
||||
|
||||
const result = await listFeeTypes(client, corpId, {
|
||||
all: includeAll,
|
||||
flat: isFlat,
|
||||
keyword,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
total: result.total,
|
||||
includeDisabled: includeAll,
|
||||
keyword: keyword || null,
|
||||
items: result.items,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
let rows: (string | number)[][] = [];
|
||||
if (!isFlat && !keyword) {
|
||||
rows = renderTreeRows(result.rawTree);
|
||||
} else {
|
||||
const flatItems = (result.items as FlatFeeTypeItem[]) || [];
|
||||
rows = flatItems.map((item, idx) => [
|
||||
idx + 1,
|
||||
item.path || item.name,
|
||||
item.code || "-",
|
||||
item.id,
|
||||
item.active ? "🟢 启用" : "🔴 停用",
|
||||
item.childrenCount ? `${item.childrenCount} 项` : "-",
|
||||
]);
|
||||
}
|
||||
|
||||
const title = `====== 费用类型列表 (企业: ${corp.name} | 共 ${result.total} 个${
|
||||
includeAll ? ",含停用" : ""
|
||||
}${keyword ? `,过滤: "${keyword}"` : ""}) ======`;
|
||||
const tableStr = rows.length
|
||||
? printTable(["#", "名称 / 层级路径", "编码", "ID", "状态", "子节点"], rows)
|
||||
: "暂无匹配的费用类型";
|
||||
|
||||
return {
|
||||
stdout: `${title}\n${tableStr}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// ── 2. 单条详情 (get / show / detail) ─────────────────────────────────────────
|
||||
if (["get", "show", "detail", "info"].includes(action)) {
|
||||
const target =
|
||||
parsed.args[0] || stringOption(parsed.options, ["id", "code", "name"]);
|
||||
if (!target) {
|
||||
throw new Error("请提供费用类型 ID、编码或名称: hose-use feetype get <ID|编码|名称>");
|
||||
}
|
||||
|
||||
const includeSpecs = booleanOption(parsed.options, ["specs", "spec", "fields"]);
|
||||
const detail = await getFeeTypeDetail(client, corpId, target, { includeSpecs });
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
...detail,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const ft = detail.feeType;
|
||||
const lines = [
|
||||
`====== 费用类型详情 (${ft.name}) ======`,
|
||||
` 名称 : ${ft.name}${ft.enName ? ` (${ft.enName})` : ""}`,
|
||||
` 编码 : ${ft.code}`,
|
||||
` ID : ${ft.id}`,
|
||||
` 当前状态 : ${ft.active ? "🟢 启用中" : "🔴 已停用"}`,
|
||||
` 层级全路径 : ${ft.path || ft.name}`,
|
||||
` 父级节点 : ${ft.parentName || "顶级 (根节点)"} (${ft.parentId || "-"})`,
|
||||
` 子类型数量 : ${ft.childrenCount || 0} 项`,
|
||||
` 标识颜色 : ${ft.color || "-"}`,
|
||||
` 图标链接 : ${ft.icon || "-"}`,
|
||||
` 说明描述 : ${ft.description || "-"}`,
|
||||
];
|
||||
|
||||
if (includeSpecs && detail.specifications) {
|
||||
const exp = detail.specifications.expenseComponents || [];
|
||||
const req = detail.specifications.requisitionComponents || [];
|
||||
lines.push("");
|
||||
lines.push(` ── 报账字段列表 (${exp.length} 项) ──`);
|
||||
for (const c of exp) {
|
||||
const reqStr = c.optional === false ? "[必填]" : "[选填]";
|
||||
lines.push(` • ${c.cnLabel || c.label} (${c.field || "-"}) - ${c.type || "text"} ${reqStr}`);
|
||||
}
|
||||
lines.push("");
|
||||
lines.push(` ── 申请字段列表 (${req.length} 项) ──`);
|
||||
for (const c of req) {
|
||||
const reqStr = c.optional === false ? "[必填]" : "[选填]";
|
||||
lines.push(` • ${c.cnLabel || c.label} (${c.field || "-"}) - ${c.type || "text"} ${reqStr}`);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `${lines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// ── 3. 新建费用类型 (create / add) ──────────────────────────────────────────
|
||||
if (["create", "add", "new"].includes(action)) {
|
||||
const name =
|
||||
stringOption(parsed.options, ["name", "title"]) || parsed.args[0];
|
||||
if (!name?.trim()) {
|
||||
throw new Error(
|
||||
"请提供费用类型名称: hose-use feetype create --name=\"费用名称\" [--code=...] [--parent=...]"
|
||||
);
|
||||
}
|
||||
|
||||
const code = stringOption(parsed.options, ["code"]);
|
||||
const parent = stringOption(parsed.options, ["parent", "parent-id", "parentId"]);
|
||||
const enName = stringOption(parsed.options, ["en-name", "enName"]);
|
||||
const description = stringOption(parsed.options, ["desc", "description"]);
|
||||
const color = stringOption(parsed.options, ["color"]);
|
||||
const icon = stringOption(parsed.options, ["icon"]);
|
||||
|
||||
const created = await createFeeType(client, corpId, {
|
||||
name: name.trim(),
|
||||
code,
|
||||
parentId: parent,
|
||||
enName,
|
||||
description,
|
||||
color,
|
||||
icon,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
success: true,
|
||||
action: "create",
|
||||
corpId,
|
||||
feeType: created,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: [
|
||||
`🎉 费用类型创建成功!`,
|
||||
` 名称 : ${created.name}`,
|
||||
` 编码 : ${created.code}`,
|
||||
` ID : ${created.id}`,
|
||||
` 层级路径 : ${created.path}`,
|
||||
` 所属父级 : ${created.parentName || "顶级 (根节点)"}`,
|
||||
].join("\n") + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// ── 4. 更新费用类型 (update / edit / modify) ─────────────────────────────────
|
||||
if (["update", "edit", "modify", "set"].includes(action)) {
|
||||
const target =
|
||||
parsed.args[0] || stringOption(parsed.options, ["id", "code", "target"]);
|
||||
if (!target?.trim()) {
|
||||
throw new Error(
|
||||
"请指定待修改的费用类型: hose-use feetype update <ID|编码|名称> [--name=...] [--code=...] [--desc=...]"
|
||||
);
|
||||
}
|
||||
|
||||
const name = stringOption(parsed.options, ["name"]);
|
||||
const code = stringOption(parsed.options, ["code"]);
|
||||
const enName = stringOption(parsed.options, ["en-name", "enName"]);
|
||||
const description = stringOption(parsed.options, ["desc", "description"]);
|
||||
const color = stringOption(parsed.options, ["color"]);
|
||||
const icon = stringOption(parsed.options, ["icon"]);
|
||||
|
||||
if (
|
||||
name === undefined &&
|
||||
code === undefined &&
|
||||
enName === undefined &&
|
||||
description === undefined &&
|
||||
color === undefined &&
|
||||
icon === undefined
|
||||
) {
|
||||
throw new Error("请至少提供一个待更新的属性参数 (例如 --name, --code, --desc, --color)");
|
||||
}
|
||||
|
||||
const updated = await updateFeeTypeInfo(client, corpId, target, {
|
||||
name,
|
||||
code,
|
||||
enName,
|
||||
description,
|
||||
color,
|
||||
icon,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
success: true,
|
||||
action: "update",
|
||||
corpId,
|
||||
feeType: updated,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: [
|
||||
`✅ 费用类型修改成功!`,
|
||||
` 名称 : ${updated.name}`,
|
||||
` 编码 : ${updated.code}`,
|
||||
` ID : ${updated.id}`,
|
||||
` 说明描述 : ${updated.description || "-"}`,
|
||||
].join("\n") + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// ── 5. 停用费用类型 (disable / block / stop) ─────────────────────────────────
|
||||
if (["disable", "block", "stop"].includes(action)) {
|
||||
const target =
|
||||
parsed.args[0] || stringOption(parsed.options, ["id", "code", "target"]);
|
||||
if (!target?.trim()) {
|
||||
throw new Error("请指定待停用的费用类型: hose-use feetype disable <ID|编码|名称>");
|
||||
}
|
||||
|
||||
const res = await disableFeeTypeItem(client, corpId, target);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
success: res.success,
|
||||
action: "disable",
|
||||
corpId,
|
||||
feeType: res.item,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `🔴 费用类型 [${res.item.name}] (${res.item.code}) 已成功停用。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// ── 6. 启用费用类型 (enable / restore / start) ───────────────────────────────
|
||||
if (["enable", "restore", "start"].includes(action)) {
|
||||
const target =
|
||||
parsed.args[0] || stringOption(parsed.options, ["id", "code", "target"]);
|
||||
if (!target?.trim()) {
|
||||
throw new Error("请指定待启用的费用类型: hose-use feetype enable <ID|编码|名称>");
|
||||
}
|
||||
|
||||
const recursive =
|
||||
booleanOption(parsed.options, ["recursive", "r"]) !== false;
|
||||
|
||||
const res = await enableFeeTypeItem(client, corpId, target, { recursive });
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
success: res.success,
|
||||
action: "enable",
|
||||
corpId,
|
||||
feeType: res.item,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `🟢 费用类型 [${res.item.name}] (${res.item.code}) 已成功启用。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// ── 7. 移动费用类型层级 (move) ───────────────────────────────────────────────
|
||||
if (["move"].includes(action)) {
|
||||
const target =
|
||||
parsed.args[0] || stringOption(parsed.options, ["id", "code", "target"]);
|
||||
const parentTarget =
|
||||
stringOption(parsed.options, ["parent", "to"]) || parsed.args[1];
|
||||
|
||||
if (!target?.trim()) {
|
||||
throw new Error("请指定待移动的费用类型: hose-use feetype move <ID|编码|名称> --parent=<新父级|root>");
|
||||
}
|
||||
if (parentTarget === undefined) {
|
||||
throw new Error("请指定目标父级: --parent=<目标父级ID|编码|名称> 或 --parent=root (移至顶级)");
|
||||
}
|
||||
|
||||
const res = await moveFeeTypeItem(client, corpId, target, parentTarget);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
success: res.success,
|
||||
action: "move",
|
||||
corpId,
|
||||
feeType: res.item,
|
||||
parentName: res.parentName,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: [
|
||||
`🚚 费用类型移动成功!`,
|
||||
` 名称 : ${res.item.name} (${res.item.code})`,
|
||||
` 新所属父级 : ${res.parentName}`,
|
||||
` 更新后路径 : ${res.item.path}`,
|
||||
].join("\n") + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// ── 8. 查看表单字段配置 (fields / specs) ─────────────────────────────────────
|
||||
if (["fields", "specs", "schema"].includes(action)) {
|
||||
const target =
|
||||
parsed.args[0] || stringOption(parsed.options, ["id", "code", "target"]);
|
||||
if (!target?.trim()) {
|
||||
throw new Error("请指定费用类型: hose-use feetype fields <ID|编码|名称>");
|
||||
}
|
||||
|
||||
const res = await getFeeTypeFieldsList(client, corpId, target);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId,
|
||||
feeType: res.feeType,
|
||||
expenseFields: res.expenseFields,
|
||||
requisitionFields: res.requisitionFields,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const expRows = res.expenseFields.map((f, i) => [
|
||||
i + 1,
|
||||
f.label,
|
||||
f.field,
|
||||
f.type,
|
||||
f.required ? "🔴 必填" : "⚪ 选填",
|
||||
f.editable ? "是" : "只读",
|
||||
f.hidden ? "是" : "否",
|
||||
]);
|
||||
|
||||
const reqRows = res.requisitionFields.map((f, i) => [
|
||||
i + 1,
|
||||
f.label,
|
||||
f.field,
|
||||
f.type,
|
||||
f.required ? "🔴 必填" : "⚪ 选填",
|
||||
f.editable ? "是" : "只读",
|
||||
f.hidden ? "是" : "否",
|
||||
]);
|
||||
|
||||
const outLines = [
|
||||
`====== 费用类型字段配置 (${res.feeType.name} | ${res.feeType.code}) ======`,
|
||||
"",
|
||||
`── 报账字段列表 (${res.expenseFields.length} 个) ──`,
|
||||
expRows.length
|
||||
? printTable(["#", "字段显示名称", "字段属性名", "控件类型", "必填", "可编辑", "隐藏"], expRows)
|
||||
: "暂无自定义报账字段",
|
||||
"",
|
||||
`── 申请字段列表 (${res.requisitionFields.length} 个) ──`,
|
||||
reqRows.length
|
||||
? printTable(["#", "字段显示名称", "字段属性名", "控件类型", "必填", "可编辑", "隐藏"], reqRows)
|
||||
: "暂无自定义申请字段",
|
||||
];
|
||||
|
||||
return {
|
||||
stdout: `${outLines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`未知 feetype 子命令: "${action}"。\n支持的子命令:\n` +
|
||||
` • hose-use feetype list [--all] [--flat] [--keyword=...] (查看费用类型树)\n` +
|
||||
` • hose-use feetype get <ID|编码|名称> [--specs] (获取详情与字段配置)\n` +
|
||||
` • hose-use feetype create --name=... [--code=...] [--parent=...] (新建费用类型)\n` +
|
||||
` • hose-use feetype update <ID|编码|名称> [--name=...] [--desc=...] (修改属性)\n` +
|
||||
` • hose-use feetype disable <ID|编码|名称> (停用)\n` +
|
||||
` • hose-use feetype enable <ID|编码|名称> (启用)\n` +
|
||||
` • hose-use feetype move <ID|编码|名称> --parent=<新父级|root> (移动父级)\n` +
|
||||
` • hose-use feetype fields <ID|编码|名称> (查看报账与申请字段清单)`
|
||||
);
|
||||
}
|
||||
@@ -4,10 +4,25 @@ import {
|
||||
} from "../../domains/platform/services.js";
|
||||
import * as api from "../../domains/platform/api.js";
|
||||
import { stringOption, numberOption, booleanOption } from "../parser.js";
|
||||
import { createClientsForCorp } from "../helpers.js";
|
||||
import { createClientsForCorp, createPiperClientForCorp } from "../helpers.js";
|
||||
import { printJson, printTable, printKeyValue } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { analyzeWorkflow } from "../../domains/platform/analysis.js";
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { WorkflowDetailSchema } from "../../domains/platform/types.js";
|
||||
import {
|
||||
createWorkflowDraft,
|
||||
beginWorkflowSave,
|
||||
commitWorkflowSave,
|
||||
failWorkflowSave,
|
||||
hasWorkflowVersionConflict,
|
||||
applyWorkflowPathPatch,
|
||||
} from "../../domains/platform/workflow-state.js";
|
||||
import { WorkflowAlertStore } from "../../domains/platform/workflow-alert-store.js";
|
||||
|
||||
const WORKFLOW_STATE_DIR = process.env.HOSE_STATE_DIR || join(homedir(), ".config", "hose-use");
|
||||
|
||||
export async function handleWorkflowCommand(
|
||||
parsed: CliParsedArgs,
|
||||
@@ -38,23 +53,165 @@ export async function handleWorkflowCommand(
|
||||
return handleFind(parsed, runtime);
|
||||
case "toggle":
|
||||
return handleToggle(parsed, runtime);
|
||||
case "publish":
|
||||
case "enable":
|
||||
return handlePublish(parsed, runtime);
|
||||
case "save":
|
||||
case "update":
|
||||
return handleSave(parsed, runtime);
|
||||
case "patch":
|
||||
return handlePatch(parsed, runtime);
|
||||
case "history":
|
||||
case "snapshots":
|
||||
return handleHistory(parsed, runtime);
|
||||
case "logs":
|
||||
case "log":
|
||||
return handleLogs(parsed, runtime);
|
||||
case "check":
|
||||
case "health":
|
||||
return handleCheck(parsed, runtime);
|
||||
case "analyze":
|
||||
case "analyse":
|
||||
return handleAnalyze(parsed, runtime);
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, toggle\n`,
|
||||
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, history, logs, check\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function handlePatch(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
const file = stringOption(parsed.options, ["file", "input", "from"]);
|
||||
const path = stringOption(parsed.options, ["path", "field"]);
|
||||
const rawValue = parsed.options.value;
|
||||
const output = stringOption(parsed.options, ["output", "output-file", "outputFile"]);
|
||||
const inPlace = booleanOption(parsed.options, ["in-place", "inPlace"]);
|
||||
if (!pipelineId || !file || !path || typeof rawValue !== "string" || (!output && !inPlace)) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use workflow patch <pipelineId> --file=<workflow.json> --path=<tasks.0.code> --value=<值> (--output=<patched.json>|--in-place) [--value-json]\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
let source: unknown;
|
||||
try {
|
||||
source = JSON.parse(readFileSync(file, "utf8"));
|
||||
} catch (error) {
|
||||
throw new Error(`无法读取工作流 JSON 文件 [${file}]: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
const sourceWorkflow = WorkflowDetailSchema.parse(source);
|
||||
if (sourceWorkflow.id !== pipelineId) {
|
||||
throw new Error(`工作流 ID 不匹配:参数为 [${pipelineId}],文件中为 [${sourceWorkflow.id}]`);
|
||||
}
|
||||
|
||||
let value: unknown = rawValue;
|
||||
if (booleanOption(parsed.options, ["value-json", "valueJson"])) {
|
||||
try {
|
||||
value = JSON.parse(rawValue);
|
||||
} catch (error) {
|
||||
throw new Error(`--value-json 不是合法 JSON: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
}
|
||||
const patched = applyWorkflowPathPatch(sourceWorkflow, path, value);
|
||||
const target = inPlace ? file : output!;
|
||||
writeFileSync(target, `${JSON.stringify(patched, null, 2)}\n`, "utf8");
|
||||
const result = { success: true, pipelineId, path, output: target, tasksVersion: patched.tasksVersion };
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `✅ 已生成工作流草稿 [${target}],修改路径: ${path}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
const file = stringOption(parsed.options, ["file", "input", "from"]);
|
||||
if (!pipelineId || !file) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use workflow save <pipelineId> --file=<workflow.json> [--force-write]\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
let draftWorkflow: unknown;
|
||||
try {
|
||||
draftWorkflow = JSON.parse(readFileSync(file, "utf8"));
|
||||
} catch (error) {
|
||||
throw new Error(`无法读取工作流 JSON 文件 [${file}]: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
|
||||
const parsedWorkflow = WorkflowDetailSchema.parse(draftWorkflow);
|
||||
if (parsedWorkflow.id !== pipelineId) {
|
||||
throw new Error(`工作流 ID 不匹配:参数为 [${pipelineId}],文件中为 [${parsedWorkflow.id}]`);
|
||||
}
|
||||
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const platformId = await resolveWorkflowPlatformId(parsed, clients, pipelineId);
|
||||
const piperClient = await createPiperClientForCorp(runtime.selectedCorp!, platformId);
|
||||
const remote = await api.getWorkflowDetail(piperClient, pipelineId);
|
||||
let state = createWorkflowDraft(parsedWorkflow);
|
||||
state = {
|
||||
...state,
|
||||
revision: 1,
|
||||
status: "dirty",
|
||||
dirtyPaths: ["*"],
|
||||
};
|
||||
|
||||
const forceWrite = booleanOption(parsed.options, ["force-write", "forceWrite"]);
|
||||
if (!forceWrite && hasWorkflowVersionConflict(state, remote)) {
|
||||
throw new Error(
|
||||
`工作流版本已变化,拒绝覆盖:远端 tasksVersion=${remote.tasksVersion}, 文件 tasksVersion=${parsedWorkflow.tasksVersion}。确认来源后使用 --force-write。`
|
||||
);
|
||||
}
|
||||
|
||||
state = beginWorkflowSave(state);
|
||||
try {
|
||||
const payload = state.workflow.inputs?.length
|
||||
? state.workflow
|
||||
: { ...state.workflow, inputs: [{ key: "$platformId", value: platformId }] };
|
||||
const saved = await api.updateWorkflow(piperClient, payload);
|
||||
state = commitWorkflowSave(state, saved);
|
||||
const result = {
|
||||
success: true,
|
||||
pipelineId,
|
||||
status: state.status,
|
||||
tasksVersion: saved.tasksVersion,
|
||||
updateTime: saved.updateTime,
|
||||
};
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return {
|
||||
stdout: `✅ 工作流 [${pipelineId}] 草稿保存成功,tasksVersion=${saved.tasksVersion}。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
} catch (error) {
|
||||
state = failWorkflowSave(state, error);
|
||||
throw new Error(`工作流保存失败(${state.status}): ${state.error}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveWorkflowPlatformId(
|
||||
parsed: CliParsedArgs,
|
||||
clients: Awaited<ReturnType<typeof createClientsForCorp>>,
|
||||
pipelineId: string
|
||||
): Promise<string> {
|
||||
const explicit = stringOption(parsed.options, ["platform-id", "platformId"]);
|
||||
if (explicit) return explicit;
|
||||
const all = await listAllWorkflows(clients, { page: 1, pageSize: 100 });
|
||||
const match = all.workflows.find((workflow) => workflow.id === pipelineId);
|
||||
if (!match?.platformId) {
|
||||
throw new Error(`无法确定工作流 [${pipelineId}] 所属自建应用,请使用 --platform-id=<platformId>`);
|
||||
}
|
||||
return match.platformId;
|
||||
}
|
||||
|
||||
async function handleAnalyze(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow analyze <pipelineId>\n", exitCode: 1 };
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const detail = await api.getWorkflowDetail(clients.easoClient, pipelineId);
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const detail = await api.getWorkflowDetail(client, pipelineId);
|
||||
const result = analyzeWorkflow(detail);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const diagnosticRows = result.diagnostics.map((item) => [item.severity, item.code, item.path, item.message]);
|
||||
@@ -67,6 +224,89 @@ async function handleAnalyze(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
||||
].join("\n"), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleHistory(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow history <pipelineId> [--page=1] [--page-size=10]\n", exitCode: 1 };
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const page = numberOption(parsed.options, ["page"]) || 1;
|
||||
const pageSize = numberOption(parsed.options, ["page-size", "pageSize", "size"]) || 10;
|
||||
const result = await api.listWorkflowSnapshots(client, pipelineId, page, pageSize);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows = result.items.map((snapshot, index) => [
|
||||
(page - 1) * pageSize + index + 1,
|
||||
snapshot.version,
|
||||
snapshot.id,
|
||||
snapshot.updateTime,
|
||||
snapshot.staffName || snapshot.staffId || "-",
|
||||
]);
|
||||
return {
|
||||
stdout: `====== 工作流版本历史 [${pipelineId}](共 ${result.totalItems} 个) ======\n${printTable(["#", "版本", "快照 ID", "更新时间", "操作者"], rows)}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleLogs(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow logs <pipelineId> [--state=FAILED] [--start-time=YYYY-MM-DD] [--end-time=YYYY-MM-DD]\n", exitCode: 1 };
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const result = await api.listWorkflowLogs(client, pipelineId, {
|
||||
state: stringOption(parsed.options, ["state"]),
|
||||
page: numberOption(parsed.options, ["page"]),
|
||||
pageSize: numberOption(parsed.options, ["page-size", "pageSize", "size"]),
|
||||
startTime: stringOption(parsed.options, ["start-time", "startTime"]),
|
||||
endTime: stringOption(parsed.options, ["end-time", "endTime"]),
|
||||
});
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `====== 工作流运行日志 [${pipelineId}] ======\n${printKeyValue({ "执行次数": result.executeCount, "成功次数": result.successCount, "错误次数": result.errorCount, "日志条数": result.totalItems, "运行记录": result.jobList.length })}\n${printJson(result, runtime.outputOptions)}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleCheck(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const result = await listAllWorkflows(clients, { page: 1, pageSize: numberOption(parsed.options, ["page-size", "pageSize", "size"]) || 100 });
|
||||
const observedAt = Date.now();
|
||||
const logResults = await Promise.all(result.workflows.map(async (workflow) => {
|
||||
try {
|
||||
const piperClient = await createPiperClientForCorp(runtime.selectedCorp!, workflow.platformId);
|
||||
const log = await api.listWorkflowLogs(piperClient, workflow.id, { page: 1, pageSize: 1 });
|
||||
return { workflow, errorCount: log.errorCount };
|
||||
} catch (error) {
|
||||
return { workflow, errorCount: workflow.errorCount, error: error instanceof Error ? error.message : String(error) };
|
||||
}
|
||||
}));
|
||||
const logErrors = logResults.filter((item): item is typeof item & { error: string } => Boolean(item.error)).map((item) => ({ platformId: item.workflow.platformId, platformName: item.workflow.platformName, error: item.error }));
|
||||
const activeAlerts = logResults
|
||||
.filter(({ errorCount }) => errorCount > 0)
|
||||
.map(({ workflow, errorCount }) => ({
|
||||
id: `${runtime.selectedCorp!.id}:${workflow.platformId}:${workflow.id}`,
|
||||
pipelineId: workflow.id,
|
||||
platformId: workflow.platformId,
|
||||
pipelineName: workflow.pipelineName,
|
||||
errorCount,
|
||||
state: workflow.state,
|
||||
observedAt,
|
||||
}));
|
||||
const stateFile = stringOption(parsed.options, ["state-file", "stateFile"]) || join(WORKFLOW_STATE_DIR, `workflow-alerts-${runtime.selectedCorp!.id}.json`);
|
||||
const check = new WorkflowAlertStore(stateFile).observe(activeAlerts);
|
||||
const output = { corpId: runtime.selectedCorp!.id, observedAt, stateFile, activeAlerts: check.activeAlerts, newAlerts: check.newAlerts, scanErrors: [...result.errors, ...logErrors] };
|
||||
if (runtime.jsonMode) return { stdout: printJson(output, runtime.outputOptions), stderr: "", exitCode: booleanOption(parsed.options, ["fail-on-alert", "failOnAlert"]) && check.newAlerts.length > 0 ? 2 : 0 };
|
||||
const rows = check.activeAlerts.map((alert) => [alert.pipelineId, alert.pipelineName || "-", alert.errorCount, alert.state === 1 ? "启用" : "停用", check.newAlerts.some((item) => item.id === alert.id) ? "🔔 新提醒" : "已记录"]);
|
||||
const warning = check.newAlerts.length ? `\n🔔 新错误管道提醒 ${check.newAlerts.length} 条` : "\n暂无新的错误管道提醒";
|
||||
const scanErrorCount = result.errors.length + logErrors.length;
|
||||
const scanWarning = scanErrorCount ? `\n⚠️ 工作流扫描失败 ${scanErrorCount} 个` : "";
|
||||
return { stdout: `====== 工作流健康检查 [${runtime.selectedCorp!.name}] ======\n${rows.length ? printTable(["工作流 ID", "名称", "错误次数", "状态", "提醒"], rows) : "未发现错误管道"}${warning}${scanWarning}\n状态文件: ${stateFile}\n`, stderr: "", exitCode: booleanOption(parsed.options, ["fail-on-alert", "failOnAlert"]) && check.newAlerts.length > 0 ? 2 : 0 };
|
||||
}
|
||||
|
||||
async function handlePublish(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow publish <pipelineId>\n", exitCode: 1 };
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const result = await api.toggleWorkflow(client, pipelineId, 1);
|
||||
const output = { success: result.success, pipelineId, published: result.success, state: 1 };
|
||||
if (runtime.jsonMode) return { stdout: printJson(output, runtime.outputOptions), stderr: "", exitCode: result.success ? 0 : 1 };
|
||||
return { stdout: result.success ? `✅ 工作流 [${pipelineId}] 已发布并启用。\n` : `❌ 工作流 [${pipelineId}] 发布失败。\n`, stderr: "", exitCode: result.success ? 0 : 1 };
|
||||
}
|
||||
|
||||
async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const page = numberOption(parsed.options, ["page"]) || 1;
|
||||
@@ -113,8 +353,8 @@ async function handleGet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<Cl
|
||||
return { stdout: "", stderr: "用法: hose-use workflow get <pipelineId>\n", exitCode: 1 };
|
||||
}
|
||||
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const detail = await api.getWorkflowDetail(clients.easoClient, pipelineId);
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const detail = await api.getWorkflowDetail(client, pipelineId);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(detail, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
@@ -147,6 +387,21 @@ async function handleGet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<Cl
|
||||
};
|
||||
}
|
||||
|
||||
async function createWorkflowDetailClient(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime,
|
||||
pipelineId: string,
|
||||
): Promise<{ client: Awaited<ReturnType<typeof createPiperClientForCorp>> }> {
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const explicit = stringOption(parsed.options, ["platform-id", "platformId"]);
|
||||
let platformId = explicit;
|
||||
if (!platformId) {
|
||||
const all = await listAllWorkflows(clients, { page: 1, pageSize: 100 });
|
||||
platformId = all.workflows.find((workflow) => workflow.id === pipelineId)?.platformId;
|
||||
}
|
||||
return { client: platformId ? await createPiperClientForCorp(runtime.selectedCorp!, platformId) : clients.easoClient };
|
||||
}
|
||||
|
||||
async function handleFind(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const taskType = stringOption(parsed.options, ["task", "taskType", "type"]) || parsed.args[0];
|
||||
if (!taskType) {
|
||||
@@ -213,8 +468,8 @@ async function handleToggle(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
}
|
||||
|
||||
const state = (stateArg === "1" || stateArg === "true" ? 1 : 0) as 0 | 1;
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const result = await api.toggleWorkflow(clients.easoClient, pipelineId, state);
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const result = await api.toggleWorkflow(client, pipelineId, state);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
|
||||
@@ -4,6 +4,7 @@ import { CorpContext, resolveCorpConfig } from "../core/config/manager.js";
|
||||
import { CorpConfig } from "../core/config/types.js";
|
||||
import { createEkbClient } from "../core/auth/ekb.js";
|
||||
import { getEasoClient } from "../core/auth/easo.js";
|
||||
import { getPiperClient } from "../core/auth/piper.js";
|
||||
import { CliRuntime, OutputOptions } from "./types.js";
|
||||
|
||||
export function initCorpRuntime(
|
||||
@@ -64,6 +65,10 @@ export async function createClientsForCorp(corp: CorpConfig) {
|
||||
};
|
||||
}
|
||||
|
||||
export async function createPiperClientForCorp(corp: CorpConfig, platformId: string) {
|
||||
return getPiperClient(corp, platformId);
|
||||
}
|
||||
|
||||
export function prompt(question: string): Promise<string> {
|
||||
const rl = readline.createInterface({
|
||||
input: process.stdin,
|
||||
|
||||
+9
-1
@@ -122,7 +122,7 @@ export function printHelp(): string {
|
||||
corps 多企业租户管理 (list, search <关键词>, switch, current, add-link)
|
||||
aipro 合思 AI PRO 确定性审批仲裁网关入口 (status, scopes, bind, checklist, review, decide, logs)
|
||||
config 全局运行模式与路径诊断 (show, paths, mode <stateful|stateless>, set)
|
||||
workflow 工作流管理 (list, get, find, analyze, toggle)
|
||||
workflow 工作流管理 (list, get, find, analyze, toggle, publish, patch, save, history, logs, check)
|
||||
bill 单据检索与审批动作 (list, get <单号|ID> [--risk], approve|reject|transfer|add-node|comment <单号|ID> [选项], refs, relations, attachments, download, flow, risk, budget, schema, link)
|
||||
contact 企业通讯录与人员检索 (list, search <关键词>, get <staffId>)
|
||||
task 待办中心与审批任务 (todo, approved, records, submitted, cc)
|
||||
@@ -132,6 +132,7 @@ export function printHelp(): string {
|
||||
platform 自建应用与数据模型 (开放平台业务对象、字段与底层记录: list, get, entities, schema, records, permissions, imports)
|
||||
datalink platform 的同义入口,面向 DataLink 业务对象查询
|
||||
dimension 系统/自定义档案维度 (list, items <维度>)
|
||||
feetype 费用类型管理与字段规格配置 (list, get, create, update, disable, enable, move, fields)
|
||||
role 角色定义与成员 (list, groups, members <角色>)
|
||||
permission 权限模型快照 (get)
|
||||
rule 本地 AI 审批规约管理 (scopes, scope <索引号|场景>, list, get, add, delete)
|
||||
@@ -197,6 +198,13 @@ export function printHelp(): string {
|
||||
hose-use bill download S26000001 --output-dir ./downloads # 下载单据附件到本地目录
|
||||
hose-use dimension list # 查看系统与自定义档案维度
|
||||
hose-use dimension items 项目 # 查看项目档案项
|
||||
hose-use feetype list # 查看费用类型树与层级关系
|
||||
hose-use feetype get 交通费 --specs # 查看费用类型详情与报账/申请字段
|
||||
hose-use feetype create --name="打车费" --parent="交通费" # 在指定父级下创建费用类型
|
||||
hose-use feetype update 打车费 --desc="滴滴打车" # 修改费用类型属性
|
||||
hose-use feetype disable 打车费 # 停用费用类型
|
||||
hose-use feetype enable 打车费 # 重新启用费用类型
|
||||
hose-use feetype move 打车费 --parent="差旅费用" # 移动费用类型到新的父级
|
||||
hose-use role list # 查看企业角色定义
|
||||
hose-use role groups # 查看角色组及其角色
|
||||
hose-use role members 财务主管 # 查看指定角色成员
|
||||
|
||||
@@ -28,6 +28,7 @@ import { handleApprovalCommand } from "./commands/approval.js";
|
||||
import { handleContextCommand } from "./commands/context.js";
|
||||
import { handleKeysCommand } from "./commands/keys.js";
|
||||
import { handleStoreCommand } from "./commands/store.js";
|
||||
import { handleFeeTypeCommand } from "./commands/feetype.js";
|
||||
import type { CliParsedArgs, CliResult, CliRunOptions } from "./types.js";
|
||||
|
||||
const STANDING_COMMANDS = new Set(["http", "server", "web", "mcp"]);
|
||||
@@ -193,6 +194,14 @@ async function dispatchCli(
|
||||
case "archive":
|
||||
case "archives":
|
||||
return await handleDimensionCommand(parsed, runtime);
|
||||
case "feetype":
|
||||
case "feetypes":
|
||||
case "fee-type":
|
||||
case "fee-types":
|
||||
case "expense-type":
|
||||
case "expense-types":
|
||||
case "costtype":
|
||||
return await handleFeeTypeCommand(parsed, runtime);
|
||||
case "role":
|
||||
case "roles":
|
||||
return await handleRoleCommand(parsed, runtime);
|
||||
|
||||
@@ -30,6 +30,8 @@ describe("embedded-skill - 多文件内嵌 Skill 体系", () => {
|
||||
|
||||
expect(EMBEDDED_SKILL_FILES["references/approval.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/approval.md"]).toContain("hose-aipro");
|
||||
expect(EMBEDDED_SKILL_FILES["references/feetype.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/feetype.md"]).toContain("feetype");
|
||||
});
|
||||
|
||||
test("installSkillFiles 递归保留层级结构并落盘到目标目录", () => {
|
||||
@@ -37,13 +39,14 @@ describe("embedded-skill - 多文件内嵌 Skill 体系", () => {
|
||||
try {
|
||||
const res = installSkillFiles(tmp);
|
||||
expect(res.targetDir).toBe(tmp);
|
||||
expect(res.files.length).toBe(12);
|
||||
expect(res.files.length).toBe(13);
|
||||
expect(existsSync(join(tmp, "SKILL.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "agents", "openai.yaml"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "auth.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "approval.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "bill.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "contact.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "feetype.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "role.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "workflow.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "service.md"))).toBe(true);
|
||||
|
||||
@@ -14,6 +14,7 @@ import refMessage from "../../skills/hose-use/references/message.md" with { type
|
||||
import refDimension from "../../skills/hose-use/references/dimension.md" with { type: "text" };
|
||||
import refRole from "../../skills/hose-use/references/role.md" with { type: "text" };
|
||||
import refApproval from "../../skills/hose-use/references/approval.md" with { type: "text" };
|
||||
import refFeeType from "../../skills/hose-use/references/feetype.md" with { type: "text" };
|
||||
|
||||
export const EMBEDDED_SKILL_FILES: Record<string, string> = {
|
||||
"SKILL.md": skillMain,
|
||||
@@ -21,6 +22,7 @@ export const EMBEDDED_SKILL_FILES: Record<string, string> = {
|
||||
"references/auth.md": refAuth,
|
||||
"references/approval.md": refApproval,
|
||||
"references/bill.md": refBill,
|
||||
"references/feetype.md": refFeeType,
|
||||
"references/contact.md": refContact,
|
||||
"references/task.md": refTask,
|
||||
"references/message.md": refMessage,
|
||||
|
||||
@@ -20,3 +20,10 @@ export class AuthenticationError extends EkbError {
|
||||
super(message, "AUTH_FAILED", 401);
|
||||
}
|
||||
}
|
||||
|
||||
export class BusinessError extends EkbError {
|
||||
constructor(message: string, code = "BUSINESS_ERROR", status = 400) {
|
||||
super(message, code, status);
|
||||
this.name = "BusinessError";
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@
|
||||
| `datalink/` | 自建应用下的业务对象、字段、记录、权限与导入状态 | [README.datalink.md](./datalink/README.datalink.md) |
|
||||
| `bill/` | 费控单据、报销单、发票与 DataLink 实体字典 | [README.bill.md](./bill/README.bill.md) |
|
||||
| `store/` | 企业应用中心/应用商店与 OpenAPI 密钥凭证 | [README.store.md](./store/README.store.md) |
|
||||
| `feetype/` | 企业费用类型全生命周期管理与字段规格配置 | [README.feetype.md](./feetype/README.feetype.md) |
|
||||
|
||||
## 分层规则
|
||||
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
# FeeType (费用类型) 域说明
|
||||
|
||||
费用类型域负责合思/易快报企业费用类型的全生命周期管理,涵盖:
|
||||
- 费用类型树与平铺目录查询(活跃 / 包含停用)
|
||||
- 费用类型增删查改(新建、属性修改、软停用、级联启用、移动层级)
|
||||
- 费用类型表单字段规格解析(报账字段与申请字段元数据)
|
||||
|
||||
## 架构职责
|
||||
|
||||
```text
|
||||
CLI (feetype.ts) / MCP (feetypeTools in server.ts)
|
||||
│
|
||||
▼
|
||||
domains/feetype/tools.ts (业务编排:树展开、路径计算、字段规格继承、增删查改封装)
|
||||
│
|
||||
▼
|
||||
domains/feetype/api.ts (HTTP 传输层:直连 /api/v1/form/feeTypes 与 /api/form/v2/specifications)
|
||||
│
|
||||
▼
|
||||
core/auth/ekb.ts (企业身份认证与凭证管理)
|
||||
```
|
||||
|
||||
## 接口路由映射
|
||||
|
||||
| 操作 | HTTP 方法与路径 | 说明 |
|
||||
|---|---|---|
|
||||
| 获取活跃树 | `GET /api/v1/form/feeTypes/tree/active` | 获取用户端可见的活跃费用类型树 |
|
||||
| 获取全量树 | `GET /api/v1/form/feeTypes/tree` | 包含已停用的全量费用类型树 |
|
||||
| 获取单项详情 | `GET /api/v1/form/feeTypes/$id` | 精准获取持久化配置 |
|
||||
| 获取表单规格 | `GET /api/form/v2/specifications/feeType/[id]` | 获取报账与申请字段定义 |
|
||||
| 获取默认模板 | `GET /api/form/v2/specifications/default/$type` | 获取 expense / requisition 预置字段 |
|
||||
| 新建费用类型 | `POST /api/v1/form/feeTypes` | 批量/单个创建,支持字段规则继承 |
|
||||
| 更新费用类型 | `PUT /api/v1/form/feeTypes/$id` | 更新名称、编码、英文名、图标、颜色 |
|
||||
| 停用费用类型 | `PUT /api/v1/form/feeTypes/[ids]/disable` | 软删除停用 |
|
||||
| 启用费用类型 | `PUT /api/v1/form/feeTypes/$id/restore` | 重新启用(可级联) |
|
||||
| 移动父级节点 | `PUT /api/v1/form/feeTypes/[ids]/parent` | 调整层级关系 |
|
||||
|
||||
## CLI 命令速查
|
||||
|
||||
```bash
|
||||
# 查看费用类型树
|
||||
hose-use feetype list
|
||||
hose-use feetype list --all
|
||||
hose-use feetype list --keyword="差旅"
|
||||
hose-use feetype list --flat
|
||||
|
||||
# 查看单个费用类型详情
|
||||
hose-use feetype get 交通费
|
||||
hose-use feetype get 交通费 --specs
|
||||
|
||||
# 创建费用类型
|
||||
hose-use feetype create --name="办公杂费"
|
||||
hose-use feetype create --name="市内打车" --parent="交通费"
|
||||
|
||||
# 修改费用类型
|
||||
hose-use feetype update 市内打车 --desc="滴滴企业版"
|
||||
|
||||
# 停用与启用
|
||||
hose-use feetype disable 市内打车
|
||||
hose-use feetype enable 市内打车
|
||||
|
||||
# 移动层级
|
||||
hose-use feetype move 市内打车 --parent="差旅费用"
|
||||
hose-use feetype move 市内打车 --parent=root
|
||||
|
||||
# 查看表单字段配置
|
||||
hose-use feetype fields 交通费
|
||||
```
|
||||
@@ -0,0 +1,294 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import {
|
||||
FeeTypeDetailResponseSchema,
|
||||
FeeTypeSpecificationResponseSchema,
|
||||
FeeTypeTreeResponseSchema,
|
||||
FeeTypeCreateResultSchema,
|
||||
DefaultSpecResponseSchema,
|
||||
FeeTypeNode,
|
||||
FeeTypeItem,
|
||||
FeeTypeSpecificationItem,
|
||||
FeeTypeCreateResult,
|
||||
FeeTypeComponent,
|
||||
} from "./types.js";
|
||||
import { BusinessError } from "../../core/errors.js";
|
||||
|
||||
/**
|
||||
* 获取活跃费用类型树 (GET api/v1/form/feeTypes/tree/active)
|
||||
*/
|
||||
export async function getActiveFeeTypeTree(
|
||||
client: KyInstance,
|
||||
corpId: string
|
||||
): Promise<FeeTypeNode[]> {
|
||||
try {
|
||||
const raw = await client
|
||||
.get("api/v1/form/feeTypes/tree/active", {
|
||||
searchParams: { corpId },
|
||||
})
|
||||
.json();
|
||||
const parsed = FeeTypeTreeResponseSchema.safeParse(raw);
|
||||
if (parsed.success) return parsed.data.items;
|
||||
if (Array.isArray(raw)) {
|
||||
return raw.filter((item): item is FeeTypeNode => Boolean(item && typeof item === "object"));
|
||||
}
|
||||
return [];
|
||||
} catch (err: any) {
|
||||
throw new BusinessError(
|
||||
`获取活跃费用类型树失败: ${err.message || String(err)}`,
|
||||
"GET_ACTIVE_FEETYPE_FAILED"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取全量费用类型树 (含已停用) (GET api/v1/form/feeTypes/tree)
|
||||
*/
|
||||
export async function getFullFeeTypeTree(
|
||||
client: KyInstance,
|
||||
corpId: string
|
||||
): Promise<FeeTypeNode[]> {
|
||||
try {
|
||||
const raw = await client
|
||||
.get("api/v1/form/feeTypes/tree", {
|
||||
searchParams: {
|
||||
corpId,
|
||||
join: "id,feetypeTemplate,/form/v2/specifications/feeType",
|
||||
join$2: "children.id,feetypeTemplate,/form/v2/specifications/feeType",
|
||||
},
|
||||
})
|
||||
.json();
|
||||
const parsed = FeeTypeTreeResponseSchema.safeParse(raw);
|
||||
if (parsed.success) return parsed.data.items;
|
||||
if (Array.isArray(raw)) {
|
||||
return raw.filter((item): item is FeeTypeNode => Boolean(item && typeof item === "object"));
|
||||
}
|
||||
return [];
|
||||
} catch (err: any) {
|
||||
throw new BusinessError(
|
||||
`获取全量费用类型树失败: ${err.message || String(err)}`,
|
||||
"GET_FULL_FEETYPE_FAILED"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取单条费用类型详情 (GET api/v1/form/feeTypes/$id)
|
||||
*/
|
||||
export async function getFeeTypeById(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
id: string
|
||||
): Promise<FeeTypeItem> {
|
||||
try {
|
||||
const raw = await client
|
||||
.get(`api/v1/form/feeTypes/$${id}`, {
|
||||
searchParams: { corpId },
|
||||
})
|
||||
.json();
|
||||
const parsed = FeeTypeDetailResponseSchema.safeParse(raw);
|
||||
if (parsed.success) return parsed.data.value;
|
||||
if (raw && typeof raw === "object" && "value" in raw) {
|
||||
return (raw as any).value as FeeTypeItem;
|
||||
}
|
||||
return raw as FeeTypeItem;
|
||||
} catch (err: any) {
|
||||
throw new BusinessError(
|
||||
`获取费用类型 [${id}] 详情失败: ${err.message || String(err)}`,
|
||||
"GET_FEETYPE_DETAIL_FAILED"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取费用类型的表单字段规格定义 (GET api/form/v2/specifications/feeType/[id])
|
||||
*/
|
||||
export async function getFeeTypeSpecification(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
id: string
|
||||
): Promise<FeeTypeSpecificationItem | undefined> {
|
||||
try {
|
||||
const raw = await client
|
||||
.get(`api/form/v2/specifications/feeType/[${id}]`, {
|
||||
searchParams: { id, corpId },
|
||||
})
|
||||
.json();
|
||||
const parsed = FeeTypeSpecificationResponseSchema.safeParse(raw);
|
||||
if (parsed.success && parsed.data.items.length > 0) {
|
||||
return parsed.data.items[0];
|
||||
}
|
||||
if (raw && typeof raw === "object" && Array.isArray((raw as any).items)) {
|
||||
return (raw as any).items[0];
|
||||
}
|
||||
return undefined;
|
||||
} catch (err: any) {
|
||||
throw new BusinessError(
|
||||
`获取费用类型 [${id}] 字段规格失败: ${err.message || String(err)}`,
|
||||
"GET_FEETYPE_SPEC_FAILED"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取默认报账字段模板 (GET api/form/v2/specifications/default/$feeType_expense)
|
||||
*/
|
||||
export async function getDefaultExpenseSpec(
|
||||
client: KyInstance,
|
||||
corpId: string
|
||||
): Promise<FeeTypeComponent[]> {
|
||||
try {
|
||||
const raw = await client
|
||||
.get("api/form/v2/specifications/default/$feeType_expense", {
|
||||
searchParams: { type: "feeType_expense", corpId },
|
||||
})
|
||||
.json();
|
||||
const parsed = DefaultSpecResponseSchema.safeParse(raw);
|
||||
return parsed.success ? (parsed.data.components ?? []) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取默认申请字段模板 (GET api/form/v2/specifications/default/$feeType_requisition)
|
||||
*/
|
||||
export async function getDefaultRequisitionSpec(
|
||||
client: KyInstance,
|
||||
corpId: string
|
||||
): Promise<FeeTypeComponent[]> {
|
||||
try {
|
||||
const raw = await client
|
||||
.get("api/form/v2/specifications/default/$feeType_requisition", {
|
||||
searchParams: { type: "feeType_requisition", corpId },
|
||||
})
|
||||
.json();
|
||||
const parsed = DefaultSpecResponseSchema.safeParse(raw);
|
||||
return parsed.success ? (parsed.data.components ?? []) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量创建费用类型 (POST api/v1/form/feeTypes)
|
||||
*/
|
||||
export async function createFeeTypes(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
items: Record<string, unknown>[]
|
||||
): Promise<FeeTypeCreateResult> {
|
||||
try {
|
||||
const raw = await client
|
||||
.post("api/v1/form/feeTypes", {
|
||||
searchParams: { corpId },
|
||||
json: { data: items },
|
||||
})
|
||||
.json();
|
||||
const parsed = FeeTypeCreateResultSchema.safeParse(raw);
|
||||
if (parsed.success) return parsed.data;
|
||||
return raw as FeeTypeCreateResult;
|
||||
} catch (err: any) {
|
||||
throw new BusinessError(
|
||||
`创建费用类型失败: ${err.message || String(err)}`,
|
||||
"CREATE_FEETYPE_FAILED"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新费用类型基本信息 (PUT api/v1/form/feeTypes/$id)
|
||||
*/
|
||||
export async function updateFeeType(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
id: string,
|
||||
body: Record<string, unknown>
|
||||
): Promise<FeeTypeItem> {
|
||||
try {
|
||||
const raw = await client
|
||||
.put(`api/v1/form/feeTypes/$${id}`, {
|
||||
searchParams: { corpId },
|
||||
json: body,
|
||||
})
|
||||
.json();
|
||||
const parsed = FeeTypeDetailResponseSchema.safeParse(raw);
|
||||
if (parsed.success) return parsed.data.value;
|
||||
if (raw && typeof raw === "object" && "value" in raw) {
|
||||
return (raw as any).value as FeeTypeItem;
|
||||
}
|
||||
return raw as FeeTypeItem;
|
||||
} catch (err: any) {
|
||||
throw new BusinessError(
|
||||
`更新费用类型 [${id}] 失败: ${err.message || String(err)}`,
|
||||
"UPDATE_FEETYPE_FAILED"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量停用费用类型 (PUT api/v1/form/feeTypes/[ids]/disable)
|
||||
*/
|
||||
export async function disableFeeTypes(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
ids: string[]
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const idsParam = `[${ids.join(",")}]`;
|
||||
const res = await client.put(`api/v1/form/feeTypes/${idsParam}/disable`, {
|
||||
searchParams: { corpId },
|
||||
});
|
||||
return res.status === 200 || res.status === 204;
|
||||
} catch (err: any) {
|
||||
throw new BusinessError(
|
||||
`停用费用类型 [${ids.join(", ")}] 失败: ${err.message || String(err)}`,
|
||||
"DISABLE_FEETYPE_FAILED"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 启用已停用的费用类型 (PUT api/v1/form/feeTypes/$id/restore)
|
||||
*/
|
||||
export async function restoreFeeType(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
id: string,
|
||||
recursive = true
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const res = await client.put(`api/v1/form/feeTypes/$${id}/restore`, {
|
||||
searchParams: { corpId, recursive: String(recursive) },
|
||||
});
|
||||
return res.status === 200 || res.status === 204;
|
||||
} catch (err: any) {
|
||||
throw new BusinessError(
|
||||
`启用费用类型 [${id}] 失败: ${err.message || String(err)}`,
|
||||
"RESTORE_FEETYPE_FAILED"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 移动费用类型父级 (PUT api/v1/form/feeTypes/[ids]/parent)
|
||||
*/
|
||||
export async function moveFeeTypes(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
ids: string[],
|
||||
parentId: string
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const idsParam = `[${ids.join(",")}]`;
|
||||
const res = await client.put(`api/v1/form/feeTypes/${idsParam}/parent`, {
|
||||
searchParams: { corpId },
|
||||
json: { parentId: parentId || "" },
|
||||
});
|
||||
return res.status === 200 || res.status === 204;
|
||||
} catch (err: any) {
|
||||
throw new BusinessError(
|
||||
`移动费用类型 [${ids.join(", ")}] 失败: ${err.message || String(err)}`,
|
||||
"MOVE_FEETYPE_FAILED"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { describe, it, expect } from "bun:test";
|
||||
import { flattenFeeTypeTree } from "./tools.js";
|
||||
import { FeeTypeNode } from "./types.js";
|
||||
|
||||
describe("domains/feetype > tools & helpers", () => {
|
||||
const sampleTree = [
|
||||
{
|
||||
feeType: {
|
||||
id: "node_1",
|
||||
name: "差旅费",
|
||||
code: "COST01",
|
||||
active: true,
|
||||
parentId: "",
|
||||
},
|
||||
children: [
|
||||
{
|
||||
feeType: {
|
||||
id: "node_1_1",
|
||||
name: "机票",
|
||||
code: "COST01_1",
|
||||
active: true,
|
||||
parentId: "node_1",
|
||||
},
|
||||
children: [
|
||||
{
|
||||
feeType: {
|
||||
id: "node_1_1_1",
|
||||
name: "退改签",
|
||||
code: "COST01_1_1",
|
||||
active: true,
|
||||
parentId: "node_1_1",
|
||||
},
|
||||
children: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
feeType: {
|
||||
id: "node_2",
|
||||
name: "办公费",
|
||||
code: "COST02",
|
||||
active: false,
|
||||
parentId: "",
|
||||
},
|
||||
children: [],
|
||||
},
|
||||
] as unknown as FeeTypeNode[];
|
||||
|
||||
it("flattenFeeTypeTree 正确递归展开全路径与父级关系", () => {
|
||||
const flat = flattenFeeTypeTree(sampleTree);
|
||||
expect(flat.length).toBe(4);
|
||||
|
||||
expect(flat[0].name).toBe("差旅费");
|
||||
expect(flat[0].path).toBe("差旅费");
|
||||
expect(flat[0].childrenCount).toBe(1);
|
||||
|
||||
expect(flat[1].name).toBe("机票");
|
||||
expect(flat[1].path).toBe("差旅费 / 机票");
|
||||
expect(flat[1].parentName).toBe("差旅费");
|
||||
expect(flat[1].childrenCount).toBe(1);
|
||||
|
||||
expect(flat[2].name).toBe("退改签");
|
||||
expect(flat[2].path).toBe("差旅费 / 机票 / 退改签");
|
||||
expect(flat[2].parentName).toBe("机票");
|
||||
expect(flat[2].childrenCount).toBe(0);
|
||||
|
||||
expect(flat[3].name).toBe("办公费");
|
||||
expect(flat[3].path).toBe("办公费");
|
||||
expect(flat[3].parentName).toBe("");
|
||||
expect(flat[3].active).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,548 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
FeeTypeComponent,
|
||||
FeeTypeCreateInput,
|
||||
FeeTypeItem,
|
||||
FeeTypeNode,
|
||||
FeeTypeQueryOptions,
|
||||
FeeTypeUpdateInput,
|
||||
FeeTypeView,
|
||||
} from "./types.js";
|
||||
import {
|
||||
createFeeTypes,
|
||||
disableFeeTypes,
|
||||
getActiveFeeTypeTree,
|
||||
getDefaultExpenseSpec,
|
||||
getDefaultRequisitionSpec,
|
||||
getFeeTypeById,
|
||||
getFeeTypeSpecification,
|
||||
getFullFeeTypeTree,
|
||||
moveFeeTypes,
|
||||
restoreFeeType,
|
||||
updateFeeType,
|
||||
} from "./api.js";
|
||||
import { BusinessError } from "../../core/errors.js";
|
||||
|
||||
// ── 树遍历与平铺辅助 ─────────────────────────────────────────────────────────
|
||||
|
||||
export interface FlatFeeTypeItem extends FeeTypeItem {
|
||||
path: string;
|
||||
parentName: string;
|
||||
childrenCount: number;
|
||||
}
|
||||
|
||||
export function flattenFeeTypeTree(
|
||||
nodes: FeeTypeNode[],
|
||||
parentPath = "",
|
||||
parentName = ""
|
||||
): FlatFeeTypeItem[] {
|
||||
const result: FlatFeeTypeItem[] = [];
|
||||
|
||||
for (const node of nodes) {
|
||||
const item = node.feeType;
|
||||
if (!item || !item.id) continue;
|
||||
|
||||
const currentPath = parentPath ? `${parentPath} / ${item.name}` : item.name;
|
||||
const children = Array.isArray(node.children) ? node.children : [];
|
||||
|
||||
result.push({
|
||||
...item,
|
||||
path: currentPath,
|
||||
parentName,
|
||||
childrenCount: children.length,
|
||||
});
|
||||
|
||||
if (children.length > 0) {
|
||||
result.push(...flattenFeeTypeTree(children, currentPath, item.name));
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理组件字段 (参照易快报前端规范:删除内部状态与只读引用)
|
||||
*/
|
||||
function cleanComponents(list: FeeTypeComponent[]): Record<string, unknown>[] {
|
||||
return list.map((item) => {
|
||||
const copy = { ...item } as Record<string, unknown>;
|
||||
delete copy.id;
|
||||
delete copy.dataType;
|
||||
delete copy.showValue;
|
||||
delete copy.status;
|
||||
delete copy.entityInfo;
|
||||
delete copy.isLinkageFilter;
|
||||
return copy;
|
||||
});
|
||||
}
|
||||
|
||||
// ── 核心业务编排 ─────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* 模糊或精准解析单个费用类型节点 (支持按 ID, Code, Name 查找)
|
||||
*/
|
||||
export async function findFeeType(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string,
|
||||
options: { all?: boolean } = {}
|
||||
): Promise<FlatFeeTypeItem | undefined> {
|
||||
const clean = target.trim();
|
||||
if (!clean) return undefined;
|
||||
|
||||
const tree = options.all
|
||||
? await getFullFeeTypeTree(client, corpId)
|
||||
: await getActiveFeeTypeTree(client, corpId);
|
||||
const flat = flattenFeeTypeTree(tree);
|
||||
|
||||
// 1. 精确 ID 匹配
|
||||
const byId = flat.find((item) => item.id === clean);
|
||||
if (byId) return byId;
|
||||
|
||||
// 2. 精确 Code 匹配 (不区分大小写)
|
||||
const byCode = flat.find((item) => item.code.toLowerCase() === clean.toLowerCase());
|
||||
if (byCode) return byCode;
|
||||
|
||||
// 3. 精确 Name 匹配
|
||||
const byName = flat.find((item) => item.name === clean);
|
||||
if (byName) return byName;
|
||||
|
||||
// 4. 包含匹配 (Name / Spell / EnName)
|
||||
const byPartial = flat.find(
|
||||
(item) =>
|
||||
item.name.includes(clean) ||
|
||||
(item.enName && item.enName.toLowerCase().includes(clean.toLowerCase()))
|
||||
);
|
||||
return byPartial;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询费用类型列表 (树形或平铺)
|
||||
*/
|
||||
export async function listFeeTypes(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
options: FeeTypeQueryOptions = {}
|
||||
): Promise<{
|
||||
total: number;
|
||||
items: FlatFeeTypeItem[] | FeeTypeNode[];
|
||||
rawTree: FeeTypeNode[];
|
||||
}> {
|
||||
const rawTree = options.all
|
||||
? await getFullFeeTypeTree(client, corpId)
|
||||
: await getActiveFeeTypeTree(client, corpId);
|
||||
|
||||
let flat = flattenFeeTypeTree(rawTree);
|
||||
|
||||
if (options.keyword?.trim()) {
|
||||
const kw = options.keyword.trim().toLowerCase();
|
||||
flat = flat.filter(
|
||||
(item) =>
|
||||
item.name.toLowerCase().includes(kw) ||
|
||||
item.code.toLowerCase().includes(kw) ||
|
||||
(item.enName && item.enName.toLowerCase().includes(kw)) ||
|
||||
item.path.toLowerCase().includes(kw)
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
total: flat.length,
|
||||
items: options.flat ? flat : (options.keyword ? flat : rawTree),
|
||||
rawTree,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取费用类型详细信息 (含字段规格)
|
||||
*/
|
||||
export async function getFeeTypeDetail(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string,
|
||||
options: { includeSpecs?: boolean } = {}
|
||||
): Promise<{
|
||||
feeType: FlatFeeTypeItem;
|
||||
specifications?: {
|
||||
expenseComponents: FeeTypeComponent[];
|
||||
requisitionComponents: FeeTypeComponent[];
|
||||
};
|
||||
}> {
|
||||
const found = await findFeeType(client, corpId, target, { all: true });
|
||||
if (!found) {
|
||||
throw new BusinessError(
|
||||
`未找到匹配的费用类型: "${target}" (可尝试按编码或全称检索)`,
|
||||
"FEETYPE_NOT_FOUND"
|
||||
);
|
||||
}
|
||||
|
||||
// 获取最新的精确持久化属性
|
||||
const fresh = await getFeeTypeById(client, corpId, found.id);
|
||||
const resultItem: FlatFeeTypeItem = {
|
||||
...fresh,
|
||||
path: found.path,
|
||||
parentName: found.parentName,
|
||||
childrenCount: found.childrenCount,
|
||||
};
|
||||
|
||||
if (!options.includeSpecs) {
|
||||
return { feeType: resultItem };
|
||||
}
|
||||
|
||||
const spec = await getFeeTypeSpecification(client, corpId, found.id);
|
||||
return {
|
||||
feeType: resultItem,
|
||||
specifications: {
|
||||
expenseComponents: spec?.expenseComponents ?? [],
|
||||
requisitionComponents: spec?.requisitionComponents ?? [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建费用类型 (支持自动/指定编码、父级继承与字段规格适配)
|
||||
*/
|
||||
export async function createFeeType(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
input: FeeTypeCreateInput
|
||||
): Promise<FlatFeeTypeItem> {
|
||||
const name = input.name.trim();
|
||||
if (!name) {
|
||||
throw new BusinessError("费用类型名称不能为空", "INVALID_FEETYPE_NAME");
|
||||
}
|
||||
|
||||
let resolvedParentId = "";
|
||||
let inheritedExpenseComponents: Record<string, unknown>[] = [];
|
||||
let inheritedRequisitionComponents: Record<string, unknown>[] = [];
|
||||
|
||||
if (input.parentId?.trim()) {
|
||||
const parent = await findFeeType(client, corpId, input.parentId.trim(), { all: true });
|
||||
if (!parent) {
|
||||
throw new BusinessError(
|
||||
`指定的父级费用类型 "${input.parentId}" 不存在`,
|
||||
"PARENT_FEETYPE_NOT_FOUND"
|
||||
);
|
||||
}
|
||||
resolvedParentId = parent.id;
|
||||
// 继承父级费用类型的字段设置
|
||||
const parentSpec = await getFeeTypeSpecification(client, corpId, parent.id);
|
||||
if (parentSpec) {
|
||||
inheritedExpenseComponents = cleanComponents(parentSpec.expenseComponents ?? []);
|
||||
inheritedRequisitionComponents = cleanComponents(parentSpec.requisitionComponents ?? []);
|
||||
}
|
||||
}
|
||||
|
||||
// 若无父级或父级无规格,加载系统预置默认字段规格
|
||||
if (!inheritedExpenseComponents.length) {
|
||||
const defaultExp = await getDefaultExpenseSpec(client, corpId);
|
||||
inheritedExpenseComponents = cleanComponents(defaultExp);
|
||||
}
|
||||
if (!inheritedRequisitionComponents.length) {
|
||||
const defaultReq = await getDefaultRequisitionSpec(client, corpId);
|
||||
inheritedRequisitionComponents = cleanComponents(defaultReq);
|
||||
}
|
||||
|
||||
// 确定唯一编码
|
||||
let code = input.code?.trim();
|
||||
if (!code) {
|
||||
const allTree = await getFullFeeTypeTree(client, corpId);
|
||||
const flat = flattenFeeTypeTree(allTree);
|
||||
const existingCodes = new Set(flat.map((item) => item.code.toUpperCase()));
|
||||
let seq = flat.length + 1;
|
||||
code = `COST${seq}`;
|
||||
while (existingCodes.has(code)) {
|
||||
seq++;
|
||||
code = `COST${seq}`;
|
||||
}
|
||||
}
|
||||
|
||||
const payloadItem = {
|
||||
type: "ALL",
|
||||
name,
|
||||
enName: input.enName?.trim() || "",
|
||||
code,
|
||||
parentId: resolvedParentId,
|
||||
description: input.description?.trim() || "",
|
||||
color: input.color || "#90caf9",
|
||||
icon: input.icon || "https://images.ekuaibao.com/feetype/sf_100.png",
|
||||
expenseComponents: input.expenseComponents?.length
|
||||
? input.expenseComponents
|
||||
: inheritedExpenseComponents,
|
||||
requisitionComponents: input.requisitionComponents?.length
|
||||
? input.requisitionComponents
|
||||
: inheritedRequisitionComponents,
|
||||
};
|
||||
|
||||
const createRes = await createFeeTypes(client, corpId, [payloadItem]);
|
||||
if (createRes.value?.errorMsgs?.length) {
|
||||
throw new BusinessError(
|
||||
`创建费用类型失败: ${createRes.value.errorMsgs.join("; ")}`,
|
||||
"CREATE_FEETYPE_REJECTED"
|
||||
);
|
||||
}
|
||||
|
||||
const newId = createRes.value?.ids?.[0];
|
||||
if (!newId) {
|
||||
throw new BusinessError("创建接口未返回新增的费用类型 ID", "CREATE_FEETYPE_NO_ID");
|
||||
}
|
||||
|
||||
const created = await getFeeTypeDetail(client, corpId, newId);
|
||||
return created.feeType;
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改费用类型属性 (名称、编码、英文名、图标、颜色、描述)
|
||||
*/
|
||||
export async function updateFeeTypeInfo(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string,
|
||||
patch: FeeTypeUpdateInput
|
||||
): Promise<FlatFeeTypeItem> {
|
||||
const found = await findFeeType(client, corpId, target, { all: true });
|
||||
if (!found) {
|
||||
throw new BusinessError(`未找到费用类型: "${target}"`, "FEETYPE_NOT_FOUND");
|
||||
}
|
||||
|
||||
const current = await getFeeTypeById(client, corpId, found.id);
|
||||
const updatedBody: Record<string, unknown> = {
|
||||
id: found.id,
|
||||
type: "FEETYPE",
|
||||
name: patch.name !== undefined ? patch.name.trim() : current.name,
|
||||
code: patch.code !== undefined ? patch.code.trim() : current.code,
|
||||
enName: patch.enName !== undefined ? patch.enName.trim() : (current.enName || ""),
|
||||
description: patch.description !== undefined ? patch.description.trim() : (current.description || ""),
|
||||
color: patch.color !== undefined ? patch.color.trim() : (current.color || "#90caf9"),
|
||||
icon: patch.icon !== undefined ? patch.icon.trim() : (current.icon || "https://images.ekuaibao.com/feetype/sf_100.png"),
|
||||
};
|
||||
|
||||
await updateFeeType(client, corpId, found.id, updatedBody);
|
||||
const fresh = await getFeeTypeDetail(client, corpId, found.id);
|
||||
return fresh.feeType;
|
||||
}
|
||||
|
||||
/**
|
||||
* 停用费用类型 (软删除)
|
||||
*/
|
||||
export async function disableFeeTypeItem(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string
|
||||
): Promise<{ success: boolean; item: FlatFeeTypeItem }> {
|
||||
const found = await findFeeType(client, corpId, target, { all: true });
|
||||
if (!found) {
|
||||
throw new BusinessError(`未找到费用类型: "${target}"`, "FEETYPE_NOT_FOUND");
|
||||
}
|
||||
|
||||
if (!found.active) {
|
||||
return { success: true, item: found };
|
||||
}
|
||||
|
||||
const ok = await disableFeeTypes(client, corpId, [found.id]);
|
||||
const fresh = await getFeeTypeDetail(client, corpId, found.id);
|
||||
return { success: ok, item: fresh.feeType };
|
||||
}
|
||||
|
||||
/**
|
||||
* 启用费用类型 (可级联恢复)
|
||||
*/
|
||||
export async function enableFeeTypeItem(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string,
|
||||
options: { recursive?: boolean } = { recursive: true }
|
||||
): Promise<{ success: boolean; item: FlatFeeTypeItem }> {
|
||||
const found = await findFeeType(client, corpId, target, { all: true });
|
||||
if (!found) {
|
||||
throw new BusinessError(`未找到费用类型: "${target}"`, "FEETYPE_NOT_FOUND");
|
||||
}
|
||||
|
||||
if (found.active) {
|
||||
return { success: true, item: found };
|
||||
}
|
||||
|
||||
const ok = await restoreFeeType(client, corpId, found.id, options.recursive ?? true);
|
||||
const fresh = await getFeeTypeDetail(client, corpId, found.id);
|
||||
return { success: ok, item: fresh.feeType };
|
||||
}
|
||||
|
||||
/**
|
||||
* 移动费用类型父级节点
|
||||
*/
|
||||
export async function moveFeeTypeItem(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string,
|
||||
parentTarget?: string
|
||||
): Promise<{ success: boolean; item: FlatFeeTypeItem; parentName: string }> {
|
||||
const found = await findFeeType(client, corpId, target, { all: true });
|
||||
if (!found) {
|
||||
throw new BusinessError(`未找到费用类型: "${target}"`, "FEETYPE_NOT_FOUND");
|
||||
}
|
||||
|
||||
let newParentId = "";
|
||||
let newParentName = "根节点 (顶级)";
|
||||
|
||||
if (parentTarget && parentTarget !== "root" && parentTarget !== "0") {
|
||||
const parent = await findFeeType(client, corpId, parentTarget, { all: true });
|
||||
if (!parent) {
|
||||
throw new BusinessError(
|
||||
`目标父级费用类型 "${parentTarget}" 不存在`,
|
||||
"PARENT_FEETYPE_NOT_FOUND"
|
||||
);
|
||||
}
|
||||
if (parent.id === found.id) {
|
||||
throw new BusinessError("不能将费用类型移动到其自身之下", "INVALID_MOVE_TARGET");
|
||||
}
|
||||
newParentId = parent.id;
|
||||
newParentName = parent.name;
|
||||
}
|
||||
|
||||
const ok = await moveFeeTypes(client, corpId, [found.id], newParentId);
|
||||
const fresh = await getFeeTypeDetail(client, corpId, found.id);
|
||||
return { success: ok, item: fresh.feeType, parentName: newParentName };
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取费用类型的表单字段明细清单 (报账与申请字段)
|
||||
*/
|
||||
export async function getFeeTypeFieldsList(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string
|
||||
): Promise<{
|
||||
feeType: FlatFeeTypeItem;
|
||||
expenseFields: {
|
||||
field: string;
|
||||
label: string;
|
||||
type: string;
|
||||
required: boolean;
|
||||
editable: boolean;
|
||||
hidden: boolean;
|
||||
}[];
|
||||
requisitionFields: {
|
||||
field: string;
|
||||
label: string;
|
||||
type: string;
|
||||
required: boolean;
|
||||
editable: boolean;
|
||||
hidden: boolean;
|
||||
}[];
|
||||
}> {
|
||||
const detail = await getFeeTypeDetail(client, corpId, target, { includeSpecs: true });
|
||||
|
||||
const mapComponent = (c: FeeTypeComponent) => ({
|
||||
field: c.field || "-",
|
||||
label: c.cnLabel || c.label || "-",
|
||||
type: c.type || "text",
|
||||
required: !c.optional,
|
||||
editable: c.editable !== false,
|
||||
hidden: Boolean(c.hide),
|
||||
});
|
||||
|
||||
return {
|
||||
feeType: detail.feeType,
|
||||
expenseFields: (detail.specifications?.expenseComponents ?? []).map(mapComponent),
|
||||
requisitionFields: (detail.specifications?.requisitionComponents ?? []).map(mapComponent),
|
||||
};
|
||||
}
|
||||
|
||||
// ── MCP Tool Definitions ─────────────────────────────────────────────────────
|
||||
|
||||
export const feetypeTools = [
|
||||
{
|
||||
name: "feetype_list",
|
||||
description: "查询企业费用类型树或平铺列表 (可按关键词筛选、包含已停用)",
|
||||
parameters: z.object({
|
||||
corpId: z.string().describe("企业 ID"),
|
||||
keyword: z.string().optional().describe("搜索关键词 (名称/编码/全路径)"),
|
||||
all: z.boolean().optional().default(false).describe("是否包含已停用的费用类型"),
|
||||
flat: z.boolean().optional().default(false).describe("是否以平铺列表格式返回"),
|
||||
}),
|
||||
handler: async (client: KyInstance, args: any) => {
|
||||
return listFeeTypes(client, args.corpId, {
|
||||
keyword: args.keyword,
|
||||
all: args.all,
|
||||
flat: args.flat,
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "feetype_get",
|
||||
description: "获取单个费用类型的详细配置与字段规格",
|
||||
parameters: z.object({
|
||||
corpId: z.string().describe("企业 ID"),
|
||||
target: z.string().describe("费用类型 ID、编码或名称"),
|
||||
includeSpecs: z.boolean().optional().default(false).describe("是否包含报账与申请字段规格定义"),
|
||||
}),
|
||||
handler: async (client: KyInstance, args: any) => {
|
||||
return getFeeTypeDetail(client, args.corpId, args.target, {
|
||||
includeSpecs: args.includeSpecs,
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "feetype_create",
|
||||
description: "新建费用类型 (支持指定父级节点、编码自增与继承字段规则)",
|
||||
parameters: z.object({
|
||||
corpId: z.string().describe("企业 ID"),
|
||||
name: z.string().describe("费用类型名称"),
|
||||
code: z.string().optional().describe("费用编码 (不提供则系统自增生成)"),
|
||||
parentId: z.string().optional().describe("父级费用类型 ID、编码或名称 (不提供则建为顶级)"),
|
||||
enName: z.string().optional().describe("英文名称"),
|
||||
description: z.string().optional().describe("描述信息"),
|
||||
color: z.string().optional().describe("标识颜色 (如 #90caf9)"),
|
||||
}),
|
||||
handler: async (client: KyInstance, args: any) => {
|
||||
return createFeeType(client, args.corpId, args);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "feetype_update",
|
||||
description: "修改费用类型属性 (名称、编码、英文名、颜色、图标或描述)",
|
||||
parameters: z.object({
|
||||
corpId: z.string().describe("企业 ID"),
|
||||
target: z.string().describe("费用类型 ID、编码或名称"),
|
||||
name: z.string().optional().describe("新名称"),
|
||||
code: z.string().optional().describe("新编码"),
|
||||
enName: z.string().optional().describe("新英文名"),
|
||||
description: z.string().optional().describe("新描述"),
|
||||
color: z.string().optional().describe("新颜色"),
|
||||
}),
|
||||
handler: async (client: KyInstance, args: any) => {
|
||||
return updateFeeTypeInfo(client, args.corpId, args.target, args);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "feetype_toggle",
|
||||
description: "停用或启用费用类型",
|
||||
parameters: z.object({
|
||||
corpId: z.string().describe("企业 ID"),
|
||||
target: z.string().describe("费用类型 ID、编码或名称"),
|
||||
action: z.enum(["disable", "enable"]).describe("执行动作: disable 停用, enable 启用"),
|
||||
recursive: z.boolean().optional().default(true).describe("启用时是否递归启用子节点"),
|
||||
}),
|
||||
handler: async (client: KyInstance, args: any) => {
|
||||
if (args.action === "disable") {
|
||||
return disableFeeTypeItem(client, args.corpId, args.target);
|
||||
} else {
|
||||
return enableFeeTypeItem(client, args.corpId, args.target, {
|
||||
recursive: args.recursive,
|
||||
});
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "feetype_move",
|
||||
description: "移动费用类型至新的父级节点 (传入 root 移至根目录)",
|
||||
parameters: z.object({
|
||||
corpId: z.string().describe("企业 ID"),
|
||||
target: z.string().describe("待移动的费用类型 ID、编码或名称"),
|
||||
parent: z.string().describe("目标父级费用类型 ID、编码或名称 (传入 'root' 为移至顶级)"),
|
||||
}),
|
||||
handler: async (client: KyInstance, args: any) => {
|
||||
return moveFeeTypeItem(client, args.corpId, args.target, args.parent);
|
||||
},
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,169 @@
|
||||
import { z } from "zod";
|
||||
|
||||
// ── 费用类型基础实体 ─────────────────────────────────────────────────────────
|
||||
|
||||
export const FeeTypeItemSchema = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
code: z.string(),
|
||||
enName: z.string().nullish().default(""),
|
||||
parentId: z.string().nullish().default(""),
|
||||
active: z.boolean().default(true),
|
||||
order: z.number().nullish().default(1000000),
|
||||
color: z.string().nullish().default("#90caf9"),
|
||||
icon: z.string().nullish().default(""),
|
||||
description: z.string().nullish().default(""),
|
||||
corporationId: z.string().optional(),
|
||||
expenseSpecificationId: z.string().nullish(),
|
||||
requisitionSpecificationId: z.string().nullish(),
|
||||
receiptSpecificationId: z.string().nullish(),
|
||||
showPoint: z.boolean().nullish().default(false),
|
||||
createTime: z.number().nullish(),
|
||||
updateTime: z.number().nullish(),
|
||||
permissions: z
|
||||
.array(
|
||||
z.object({
|
||||
name: z.string(),
|
||||
auth: z.boolean(),
|
||||
})
|
||||
)
|
||||
.nullish()
|
||||
.default([]),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export type FeeTypeItem = z.infer<typeof FeeTypeItemSchema>;
|
||||
|
||||
// ── 树节点模型 ─────────────────────────────────────────────────────────────
|
||||
|
||||
export interface FeeTypeNode {
|
||||
feeType: FeeTypeItem;
|
||||
children: FeeTypeNode[];
|
||||
}
|
||||
|
||||
export const FeeTypeNodeSchema: z.ZodType<FeeTypeNode> = z.lazy(() =>
|
||||
z.object({
|
||||
feeType: FeeTypeItemSchema,
|
||||
children: z.array(FeeTypeNodeSchema).default([]),
|
||||
})
|
||||
);
|
||||
|
||||
export const FeeTypeTreeResponseSchema = z.object({
|
||||
items: z.array(FeeTypeNodeSchema).default([]),
|
||||
});
|
||||
|
||||
export type FeeTypeTreeResponse = z.infer<typeof FeeTypeTreeResponseSchema>;
|
||||
|
||||
export const FeeTypeDetailResponseSchema = z.object({
|
||||
value: FeeTypeItemSchema,
|
||||
});
|
||||
|
||||
export type FeeTypeDetailResponse = z.infer<typeof FeeTypeDetailResponseSchema>;
|
||||
|
||||
export const FeeTypeCreateResultSchema = z.object({
|
||||
value: z
|
||||
.object({
|
||||
ids: z.array(z.string()).default([]),
|
||||
names: z.record(z.string(), z.string()).optional(),
|
||||
errorMsgs: z.array(z.string()).nullish().default([]),
|
||||
})
|
||||
.default({ ids: [], errorMsgs: [] }),
|
||||
});
|
||||
|
||||
export type FeeTypeCreateResult = z.infer<typeof FeeTypeCreateResultSchema>;
|
||||
|
||||
// ── 字段配置与规格模型 ───────────────────────────────────────────────────────
|
||||
|
||||
export const FeeTypeComponentSchema = z
|
||||
.object({
|
||||
field: z.string().optional(),
|
||||
label: z.string().optional(),
|
||||
cnLabel: z.string().nullish(),
|
||||
enLabel: z.string().nullish(),
|
||||
type: z.string().optional(),
|
||||
placeholder: z.string().nullish(),
|
||||
readonly: z.boolean().nullish().default(false),
|
||||
editable: z.boolean().nullish().default(true),
|
||||
optional: z.boolean().nullish().default(true),
|
||||
hide: z.boolean().nullish().default(false),
|
||||
showInDetails: z.boolean().nullish().default(false),
|
||||
defaultField: z.boolean().nullish().default(false),
|
||||
defaultValue: z.record(z.string(), z.any()).nullish(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export type FeeTypeComponent = z.infer<typeof FeeTypeComponentSchema>;
|
||||
|
||||
export const FeeTypeSpecificationItemSchema = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
expenseComponents: z.array(FeeTypeComponentSchema).nullish().default([]),
|
||||
requisitionComponents: z.array(FeeTypeComponentSchema).nullish().default([]),
|
||||
receiptComponents: z.array(FeeTypeComponentSchema).nullish().default([]),
|
||||
expenseRules: z.array(z.any()).nullish().default([]),
|
||||
requisitionRules: z.array(z.any()).nullish().default([]),
|
||||
receiptRules: z.array(z.any()).nullish().default([]),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export type FeeTypeSpecificationItem = z.infer<typeof FeeTypeSpecificationItemSchema>;
|
||||
|
||||
export const FeeTypeSpecificationResponseSchema = z.object({
|
||||
items: z.array(FeeTypeSpecificationItemSchema).default([]),
|
||||
});
|
||||
|
||||
export type FeeTypeSpecificationResponse = z.infer<typeof FeeTypeSpecificationResponseSchema>;
|
||||
|
||||
export const DefaultSpecResponseSchema = z
|
||||
.object({
|
||||
components: z.array(FeeTypeComponentSchema).nullish().default([]),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export type DefaultSpecResponse = z.infer<typeof DefaultSpecResponseSchema>;
|
||||
|
||||
// ── 业务输入参数 ────────────────────────────────────────────────────────────
|
||||
|
||||
export interface FeeTypeCreateInput {
|
||||
name: string;
|
||||
code?: string;
|
||||
enName?: string;
|
||||
parentId?: string;
|
||||
description?: string;
|
||||
color?: string;
|
||||
icon?: string;
|
||||
expenseComponents?: Record<string, unknown>[];
|
||||
requisitionComponents?: Record<string, unknown>[];
|
||||
}
|
||||
|
||||
export interface FeeTypeUpdateInput {
|
||||
name?: string;
|
||||
code?: string;
|
||||
enName?: string;
|
||||
description?: string;
|
||||
color?: string;
|
||||
icon?: string;
|
||||
order?: number;
|
||||
}
|
||||
|
||||
export interface FeeTypeQueryOptions {
|
||||
all?: boolean;
|
||||
keyword?: string;
|
||||
flat?: boolean;
|
||||
}
|
||||
|
||||
export interface FeeTypeView {
|
||||
id: string;
|
||||
name: string;
|
||||
code: string;
|
||||
enName: string;
|
||||
active: boolean;
|
||||
parentId: string;
|
||||
parentName?: string;
|
||||
path: string;
|
||||
description: string;
|
||||
color: string;
|
||||
icon: string;
|
||||
childrenCount: number;
|
||||
}
|
||||
@@ -6,6 +6,8 @@ import {
|
||||
WorkflowStatsSchema,
|
||||
WorkflowChargeSchema,
|
||||
WorkflowDetailSchema,
|
||||
WorkflowSnapshotPageSchema,
|
||||
WorkflowLogPageSchema,
|
||||
WorkflowJobSchema,
|
||||
WorkflowDslSchema,
|
||||
StaffSchema,
|
||||
@@ -84,6 +86,53 @@ export async function getWorkflowDetail(
|
||||
return unwrap(response, WorkflowDetailSchema);
|
||||
}
|
||||
|
||||
// ── 工作流草稿保存(Piper)───────────────────────────────────────────────────
|
||||
// Web 端“保存更新”会把完整 pipeline 原样 PUT 回服务端;节点不是独立资源。
|
||||
export async function updateWorkflow(
|
||||
client: KyInstance,
|
||||
workflow: import("./types.js").WorkflowDetail
|
||||
): Promise<import("./types.js").WorkflowDetail> {
|
||||
const response = await client.put(`api/easo/pipelines/${workflow.id}`, {
|
||||
json: workflow,
|
||||
});
|
||||
return unwrap(response, WorkflowDetailSchema);
|
||||
}
|
||||
|
||||
export async function listWorkflowSnapshots(
|
||||
client: KyInstance,
|
||||
pipelineId: string,
|
||||
page: number = 1,
|
||||
pageSize: number = 10
|
||||
): Promise<import("./types.js").WorkflowSnapshotPage> {
|
||||
const response = await client.get(`api/easo/pipelines/${pipelineId}/snapshots`, {
|
||||
searchParams: { number: String(page), pageSize: String(pageSize) },
|
||||
});
|
||||
return unwrap(response, WorkflowSnapshotPageSchema);
|
||||
}
|
||||
|
||||
export async function listWorkflowLogs(
|
||||
client: KyInstance,
|
||||
pipelineId: string,
|
||||
options: {
|
||||
state?: string;
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
startTime?: string;
|
||||
endTime?: string;
|
||||
} = {},
|
||||
): Promise<import("./types.js").WorkflowLogPage> {
|
||||
const response = await client.get(`api/easo/pipelines/${pipelineId}/log`, {
|
||||
searchParams: {
|
||||
state: options.state ?? "",
|
||||
number: String(options.page ?? 1),
|
||||
pageSize: String(options.pageSize ?? 10),
|
||||
...(options.startTime ? { startTime: options.startTime } : {}),
|
||||
...(options.endTime ? { endTime: options.endTime } : {}),
|
||||
},
|
||||
});
|
||||
return unwrap(response, WorkflowLogPageSchema);
|
||||
}
|
||||
|
||||
// ── 工作流启停(Piper)────────────────────────────────────────────────────────
|
||||
|
||||
export async function toggleWorkflow(
|
||||
|
||||
@@ -283,8 +283,52 @@ export const WorkflowDetailSchema = z.object({
|
||||
tasksVersion: z.number().default(0),
|
||||
tasks: z.array(WorkflowTaskSchema).default([]),
|
||||
alarm: WorkflowAlarmSchema.optional(),
|
||||
inputs: z.array(z.object({ key: z.string(), value: z.any() })).optional(),
|
||||
"$snapshot": z.array(z.object({ key: z.string(), value: z.string() })).optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const WorkflowSnapshotSchema = z.object({
|
||||
id: z.string(),
|
||||
pipelineId: z.string(),
|
||||
corporationId: z.string().default(""),
|
||||
platformId: z.string().default(""),
|
||||
triggerKey: z.string().default(""),
|
||||
label: z.string().default(""),
|
||||
tasks: z.array(WorkflowTaskSchema).nullable().optional(),
|
||||
inputs: z.union([z.string(), z.array(z.any())]).default("[]"),
|
||||
outputs: z.union([z.string(), z.array(z.any())]).default("[]"),
|
||||
retry: z.number().default(0),
|
||||
state: z.number().default(0),
|
||||
debugState: z.number().default(0),
|
||||
staffId: z.string().nullable().optional(),
|
||||
staffName: z.string().nullable().optional(),
|
||||
createTime: z.string().default(""),
|
||||
updateTime: z.string().default(""),
|
||||
version: z.string().default(""),
|
||||
}).passthrough();
|
||||
|
||||
export const WorkflowSnapshotPageSchema = z.object({
|
||||
number: z.number().default(1),
|
||||
size: z.number().default(10),
|
||||
totalPages: z.number().default(0),
|
||||
totalItems: z.number().default(0),
|
||||
items: z.array(WorkflowSnapshotSchema).default([]),
|
||||
});
|
||||
|
||||
export const WorkflowLogItemSchema = z.record(z.string(), z.any());
|
||||
|
||||
export const WorkflowLogPageSchema = z.object({
|
||||
number: z.number().default(1),
|
||||
size: z.number().default(10),
|
||||
totalPages: z.number().default(0),
|
||||
totalItems: z.number().default(0),
|
||||
items: z.array(WorkflowLogItemSchema).default([]),
|
||||
executeCount: z.number().default(0),
|
||||
successCount: z.number().default(0),
|
||||
errorCount: z.number().default(0),
|
||||
jobList: z.array(WorkflowLogItemSchema).default([]),
|
||||
}).passthrough();
|
||||
|
||||
export const WorkflowChargeSchema = z.object({
|
||||
corporationId: z.string().default(""),
|
||||
status: z.string().default(""),
|
||||
@@ -373,6 +417,10 @@ export type WorkflowPage = z.infer<typeof WorkflowPageSchema>;
|
||||
export type WorkflowStats = z.infer<typeof WorkflowStatsSchema>;
|
||||
export type WorkflowAlarm = z.infer<typeof WorkflowAlarmSchema>;
|
||||
export type WorkflowDetail = z.infer<typeof WorkflowDetailSchema>;
|
||||
export type WorkflowSnapshot = z.infer<typeof WorkflowSnapshotSchema>;
|
||||
export type WorkflowSnapshotPage = z.infer<typeof WorkflowSnapshotPageSchema>;
|
||||
export type WorkflowLogItem = z.infer<typeof WorkflowLogItemSchema>;
|
||||
export type WorkflowLogPage = z.infer<typeof WorkflowLogPageSchema>;
|
||||
export type WorkflowCharge = z.infer<typeof WorkflowChargeSchema>;
|
||||
export type WorkflowJob = z.infer<typeof WorkflowJobSchema>;
|
||||
export type WorkflowDsl = z.infer<typeof WorkflowDslSchema>;
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { dirname } from "node:path";
|
||||
|
||||
export interface WorkflowErrorAlert {
|
||||
id: string;
|
||||
pipelineId: string;
|
||||
platformId: string;
|
||||
pipelineName: string;
|
||||
errorCount: number;
|
||||
state: number;
|
||||
observedAt: number;
|
||||
}
|
||||
|
||||
interface PersistedAlerts {
|
||||
version: 1;
|
||||
alerts: Record<string, { errorCount: number; lastSeen: number }>;
|
||||
}
|
||||
|
||||
export interface WorkflowAlertCheckResult {
|
||||
activeAlerts: WorkflowErrorAlert[];
|
||||
newAlerts: WorkflowErrorAlert[];
|
||||
}
|
||||
|
||||
/** 本地持久化工作流错误指纹,避免定时检查时重复提醒同一错误计数。 */
|
||||
export class WorkflowAlertStore {
|
||||
constructor(private readonly filePath: string) {}
|
||||
|
||||
private read(): PersistedAlerts {
|
||||
if (!existsSync(this.filePath)) return { version: 1, alerts: {} };
|
||||
try {
|
||||
const value = JSON.parse(readFileSync(this.filePath, "utf8")) as Partial<PersistedAlerts>;
|
||||
return { version: 1, alerts: value.alerts && typeof value.alerts === "object" ? value.alerts : {} };
|
||||
} catch {
|
||||
return { version: 1, alerts: {} };
|
||||
}
|
||||
}
|
||||
|
||||
observe(alerts: WorkflowErrorAlert[]): WorkflowAlertCheckResult {
|
||||
const data = this.read();
|
||||
const activeIds = new Set(alerts.map((alert) => alert.id));
|
||||
const newAlerts = alerts.filter((alert) => data.alerts[alert.id]?.errorCount !== alert.errorCount);
|
||||
const updated = { ...data.alerts };
|
||||
for (const id of Object.keys(updated)) {
|
||||
if (!activeIds.has(id)) delete updated[id];
|
||||
}
|
||||
for (const alert of alerts) updated[alert.id] = { errorCount: alert.errorCount, lastSeen: alert.observedAt };
|
||||
mkdirSync(dirname(this.filePath), { recursive: true, mode: 0o700 });
|
||||
writeFileSync(this.filePath, `${JSON.stringify({ version: 1, alerts: updated }, null, 2)}\n`, { mode: 0o600 });
|
||||
return { activeAlerts: alerts, newAlerts };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import {
|
||||
beginWorkflowSave,
|
||||
applyWorkflowPathPatch,
|
||||
commitWorkflowSave,
|
||||
createWorkflowDraft,
|
||||
failWorkflowSave,
|
||||
hasWorkflowVersionConflict,
|
||||
patchWorkflowDraft,
|
||||
} from "./workflow-state.js";
|
||||
import { WorkflowDetailSchema } from "./types.js";
|
||||
import type { WorkflowDetail } from "./types.js";
|
||||
import { listWorkflowSnapshots, listWorkflowLogs, toggleWorkflow, updateWorkflow } from "./api.js";
|
||||
import { WorkflowAlertStore } from "./workflow-alert-store.js";
|
||||
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
const workflow = (overrides: Partial<WorkflowDetail> = {}): WorkflowDetail => WorkflowDetailSchema.parse({
|
||||
id: "wf-1",
|
||||
label: "测试流程",
|
||||
state: 0,
|
||||
debugState: 0,
|
||||
runTimes: 0,
|
||||
errorTimes: 0,
|
||||
updateTime: "",
|
||||
version: "1",
|
||||
dataLimit: 20,
|
||||
source: 1,
|
||||
queueJobs: false,
|
||||
tasksVersion: 3,
|
||||
tasks: [],
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe("workflow draft state machine", () => {
|
||||
it("patches a nested node field without mutating the source snapshot", () => {
|
||||
const source = workflow({ tasks: [{ name: "task-1", type: "code", label: "旧值", groupName: "", orderIndex: 0, levelIndex: [0], status: "ok", code: "return 1;" }] });
|
||||
const patched = applyWorkflowPathPatch(source, "tasks[0].code", "return 2;");
|
||||
expect(patched.tasks[0]?.code).toBe("return 2;");
|
||||
expect(source.tasks[0]?.code).toBe("return 1;");
|
||||
});
|
||||
|
||||
it("rejects a path whose parent does not exist", () => {
|
||||
expect(() => applyWorkflowPathPatch(workflow(), "tasks.0.form.title", "x")).toThrow("路径不存在");
|
||||
});
|
||||
|
||||
it("sends the complete workflow snapshot to the Piper update endpoint", async () => {
|
||||
let request: { url: string; json: WorkflowDetail } | undefined;
|
||||
const client = {
|
||||
put: async (url: string, options: { json: WorkflowDetail }) => {
|
||||
request = { url, json: options.json };
|
||||
return { json: async () => ({ data: options.json }) };
|
||||
},
|
||||
} as any;
|
||||
const input = workflow({ inputs: [{ key: "$platformId", value: "platform-1" }], "$snapshot": [{ key: "tasks.0", value: "{}" }] });
|
||||
const result = await updateWorkflow(client, input);
|
||||
expect(request?.url).toBe("api/easo/pipelines/wf-1");
|
||||
expect(request?.json.inputs).toEqual([{ key: "$platformId", value: "platform-1" }]);
|
||||
expect(result["$snapshot"]).toEqual([{ key: "tasks.0", value: "{}" }]);
|
||||
});
|
||||
|
||||
it("reads snapshot history and accepts the web API's serialized inputs", async () => {
|
||||
let request: { url: string; options: any } | undefined;
|
||||
const client = {
|
||||
get: async (url: string, options: any) => {
|
||||
request = { url, options };
|
||||
return new Response(JSON.stringify({ data: {
|
||||
number: 1,
|
||||
size: 10,
|
||||
totalPages: 1,
|
||||
totalItems: 1,
|
||||
items: [{
|
||||
id: "snapshot-1",
|
||||
pipelineId: "wf-1",
|
||||
platformId: "platform-1",
|
||||
inputs: '[{"key":"$platformId","value":"platform-1"}]',
|
||||
outputs: "[]",
|
||||
version: "26.2.38",
|
||||
}],
|
||||
} }));
|
||||
},
|
||||
} as any;
|
||||
const result = await listWorkflowSnapshots(client, "wf-1", 2, 5);
|
||||
expect(request?.url).toBe("api/easo/pipelines/wf-1/snapshots");
|
||||
expect(request?.options.searchParams).toEqual({ number: "2", pageSize: "5" });
|
||||
expect(result.items[0]?.inputs).toContain("$platformId");
|
||||
expect(result.items[0]?.version).toBe("26.2.38");
|
||||
});
|
||||
|
||||
it("reads workflow logs with the web query contract", async () => {
|
||||
let request: { url: string; options: any } | undefined;
|
||||
const client = {
|
||||
get: async (url: string, options: any) => {
|
||||
request = { url, options };
|
||||
return new Response(JSON.stringify({ data: { number: 1, size: 10, totalItems: 1, items: [{ id: "run-1", state: "FAILED", message: "测试错误" }] } }));
|
||||
},
|
||||
} as any;
|
||||
const result = await listWorkflowLogs(client, "wf-1", { state: "FAILED", startTime: "2026-09-01", endTime: "2026-09-09" });
|
||||
expect(request?.url).toBe("api/easo/pipelines/wf-1/log");
|
||||
expect(request?.options.searchParams).toEqual({ state: "FAILED", number: "1", pageSize: "10", startTime: "2026-09-01", endTime: "2026-09-09" });
|
||||
expect(result.items[0]?.message).toBe("测试错误");
|
||||
});
|
||||
|
||||
it("uses the state endpoint for publishing a workflow", async () => {
|
||||
let request: { url: string; options: any } | undefined;
|
||||
const client = {
|
||||
put: async (url: string, options: any) => {
|
||||
request = { url, options };
|
||||
return new Response(JSON.stringify({ code: 200, msg: "更新成功", data: null }), { status: 200 });
|
||||
},
|
||||
} as any;
|
||||
const result = await toggleWorkflow(client, "wf-1", 1);
|
||||
expect(result.success).toBe(true);
|
||||
expect(request?.url).toBe("api/easo/pipelines/state/wf-1");
|
||||
expect(request?.options.searchParams).toEqual({ state: "1" });
|
||||
});
|
||||
|
||||
it("persists workflow alert fingerprints and only reports new counts", () => {
|
||||
const dir = mkdtempSync("hose-workflow-alert-");
|
||||
const file = join(dir, "alerts.json");
|
||||
const store = new WorkflowAlertStore(file);
|
||||
const alert = { id: "corp:platform:wf-1", pipelineId: "wf-1", platformId: "platform-1", pipelineName: "测试流程", errorCount: 1, state: 0, observedAt: 1 };
|
||||
expect(store.observe([alert]).newAlerts).toHaveLength(1);
|
||||
expect(store.observe([{ ...alert, observedAt: 2 }]).newAlerts).toHaveLength(0);
|
||||
expect(store.observe([{ ...alert, errorCount: 2, observedAt: 3 }]).newAlerts).toHaveLength(1);
|
||||
expect(store.observe([]).newAlerts).toHaveLength(0);
|
||||
expect(store.observe([{ ...alert, observedAt: 4 }]).newAlerts).toHaveLength(1);
|
||||
expect(JSON.parse(readFileSync(file, "utf8")).version).toBe(1);
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("tracks dirty revisions and commits the server snapshot", () => {
|
||||
let state = createWorkflowDraft(workflow());
|
||||
state = patchWorkflowDraft(state, (current) => ({ ...current, label: "已修改" }), ["label"]);
|
||||
expect(state.status).toBe("dirty");
|
||||
expect(state.revision).toBe(1);
|
||||
expect(state.dirtyPaths).toEqual(["label"]);
|
||||
state = beginWorkflowSave(state);
|
||||
expect(state.status).toBe("saving");
|
||||
state = commitWorkflowSave(state, workflow({ label: "已修改", tasksVersion: 4 }));
|
||||
expect(state.status).toBe("saved");
|
||||
expect(state.dirtyPaths).toEqual([]);
|
||||
expect(state.baseTasksVersion).toBe(4);
|
||||
});
|
||||
|
||||
it("detects optimistic concurrency conflicts and preserves failures", () => {
|
||||
const state = createWorkflowDraft(workflow());
|
||||
expect(hasWorkflowVersionConflict(state, workflow({ tasksVersion: 4 }))).toBe(true);
|
||||
const failed = failWorkflowSave(beginWorkflowSave(patchWorkflowDraft(state, (current) => current)), "网络错误");
|
||||
expect(failed.status).toBe("failed");
|
||||
expect(failed.error).toBe("网络错误");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,117 @@
|
||||
import type { WorkflowDetail } from "./types.js";
|
||||
|
||||
export type WorkflowDraftStatus = "clean" | "dirty" | "saving" | "saved" | "failed";
|
||||
|
||||
export interface WorkflowDraftState {
|
||||
workflow: WorkflowDetail;
|
||||
baseVersion: string;
|
||||
baseTasksVersion: number;
|
||||
revision: number;
|
||||
status: WorkflowDraftStatus;
|
||||
dirtyPaths: string[];
|
||||
lastSavedAt?: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
function pathParts(path: string): string[] {
|
||||
const parts = path
|
||||
.replace(/\[(\d+)\]/g, ".$1")
|
||||
.split(".")
|
||||
.map((part) => part.trim())
|
||||
.filter(Boolean);
|
||||
if (!parts.length) throw new Error("工作流配置路径不能为空");
|
||||
if (parts.some((part) => !/^[A-Za-z_$][\w$-]*$/.test(part) && !/^\d+$/.test(part))) {
|
||||
throw new Error(`工作流配置路径非法: ${path}`);
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
|
||||
/**
|
||||
* 在完整 pipeline 草稿上做局部修改。这里只改本地对象,不触发网络请求;
|
||||
* 远端持久化统一交给 workflow save,避免绕过版本保护直接写服务端。
|
||||
*/
|
||||
export function applyWorkflowPathPatch(
|
||||
workflow: WorkflowDetail,
|
||||
path: string,
|
||||
value: unknown,
|
||||
): WorkflowDetail {
|
||||
const parts = pathParts(path);
|
||||
const patched = structuredClone(workflow) as Record<string, any>;
|
||||
let cursor: any = patched;
|
||||
for (const part of parts.slice(0, -1)) {
|
||||
if (cursor === null || typeof cursor !== "object" || !(part in cursor)) {
|
||||
throw new Error(`工作流配置路径不存在: ${path}`);
|
||||
}
|
||||
cursor = cursor[part];
|
||||
}
|
||||
if (cursor === null || typeof cursor !== "object") {
|
||||
throw new Error(`工作流配置路径不可写: ${path}`);
|
||||
}
|
||||
cursor[parts.at(-1)!] = value;
|
||||
return patched as WorkflowDetail;
|
||||
}
|
||||
|
||||
export function createWorkflowDraft(workflow: WorkflowDetail): WorkflowDraftState {
|
||||
return {
|
||||
workflow,
|
||||
baseVersion: workflow.version,
|
||||
baseTasksVersion: workflow.tasksVersion,
|
||||
revision: 0,
|
||||
status: "clean",
|
||||
dirtyPaths: [],
|
||||
};
|
||||
}
|
||||
|
||||
export function patchWorkflowDraft(
|
||||
state: WorkflowDraftState,
|
||||
update: (workflow: WorkflowDetail) => WorkflowDetail,
|
||||
dirtyPaths: string[] = ["*"]
|
||||
): WorkflowDraftState {
|
||||
return {
|
||||
...state,
|
||||
workflow: update(state.workflow),
|
||||
revision: state.revision + 1,
|
||||
status: "dirty",
|
||||
dirtyPaths: [...new Set([...state.dirtyPaths, ...dirtyPaths])],
|
||||
error: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export function beginWorkflowSave(state: WorkflowDraftState): WorkflowDraftState {
|
||||
if (state.status !== "dirty" && state.status !== "failed") return state;
|
||||
return { ...state, status: "saving", error: undefined };
|
||||
}
|
||||
|
||||
export function commitWorkflowSave(
|
||||
state: WorkflowDraftState,
|
||||
savedWorkflow: WorkflowDetail
|
||||
): WorkflowDraftState {
|
||||
return {
|
||||
...state,
|
||||
workflow: savedWorkflow,
|
||||
baseVersion: savedWorkflow.version,
|
||||
baseTasksVersion: savedWorkflow.tasksVersion,
|
||||
status: "saved",
|
||||
dirtyPaths: [],
|
||||
lastSavedAt: new Date().toISOString(),
|
||||
error: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export function failWorkflowSave(
|
||||
state: WorkflowDraftState,
|
||||
error: unknown
|
||||
): WorkflowDraftState {
|
||||
return {
|
||||
...state,
|
||||
status: "failed",
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
};
|
||||
}
|
||||
|
||||
export function hasWorkflowVersionConflict(
|
||||
draft: WorkflowDraftState,
|
||||
remote: WorkflowDetail
|
||||
): boolean {
|
||||
return draft.baseTasksVersion !== remote.tasksVersion || draft.baseVersion !== remote.version;
|
||||
}
|
||||
+4
-3
@@ -12,6 +12,7 @@ import { authTools } from "./core/auth/tools.js";
|
||||
import { platformTools } from "./domains/platform/tools.js";
|
||||
import { datalinkTools } from "./domains/datalink/tools.js";
|
||||
import { billTools } from "./domains/bill/tools.js";
|
||||
import { feetypeTools } from "./domains/feetype/tools.js";
|
||||
import { runCli } from "./cli/runner.js";
|
||||
import { redactSensitiveText } from "./cli/printer.js";
|
||||
import { VERSION } from "./version.js";
|
||||
@@ -186,7 +187,7 @@ export function createServer(options: { mode?: HoseMcpMode; enabled?: boolean }
|
||||
}
|
||||
);
|
||||
|
||||
const fineGrainedTools = [...authTools, ...platformTools, ...datalinkTools, ...billTools];
|
||||
const fineGrainedTools = [...authTools, ...platformTools, ...datalinkTools, ...billTools, ...feetypeTools];
|
||||
|
||||
// 注册工具列表
|
||||
server.setRequestHandler("tools/list", async () => {
|
||||
@@ -200,14 +201,14 @@ export function createServer(options: { mode?: HoseMcpMode; enabled?: boolean }
|
||||
tools.push({
|
||||
name: HOSE_CLI_TOOL_NAME,
|
||||
description:
|
||||
"Run hose-use CLI commands (e.g. 'bill query', 'corps list', 'workflow search'). See the hose-use skill for command reference.",
|
||||
"Run hose-use CLI commands, including workflow get/patch/save/publish/history/logs/check. See the hose-use skill for command reference.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
command: {
|
||||
type: "string",
|
||||
description:
|
||||
"A hose-use CLI command string, with or without the leading 'hose-use' or 'hose'. Example: 'corps list' or 'bill query --code BX20260901001'.",
|
||||
"A hose-use CLI command string, with or without the leading 'hose-use' or 'hose'. Example: 'workflow check --json', 'workflow publish <pipelineId>', or 'workflow get <pipelineId> --json -o workflow.json'.",
|
||||
},
|
||||
},
|
||||
required: ["command"],
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
export const VERSION = "0.8.4";
|
||||
export const VERSION = "0.8.5";
|
||||
Reference in new issue
Block a user