Compare commits

..
39 Commits
Author SHA1 Message Date
yunyingk 0554f41d12 Merge pull request #73 from yunyingk/codex/release-v0.8.6
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
chore(release): v0.8.6
2026-09-13 13:43:51 +08:00
gitea 8e4535a812 chore(release): bump version to v0.8.6 2026-09-13 13:42:56 +08:00
yunyingk 68c7541cf6 Merge pull request #72 from yunyingk/fix/dev-check-symlink-awareness
fix: recognize canonical Skill symlinks
2026-09-12 23:36:00 +08:00
gitea 134ebf0d2e fix: treat canonical skill symlinks as healthy 2026-09-12 23:34:50 +08:00
yunyingk 5d441d9e90 Merge pull request #71 from yunyingk/feat/dev-hygiene-check
feat: 增加开发环境卫生检查与安全清理
2026-09-12 23:29:20 +08:00
gitea 3db5907357 feat: add development hygiene checks and cleanup 2026-09-12 23:26:08 +08:00
yunyingk b6551497d7 Merge pull request #70 from yunyingk/fix/canonical-skill-install
fix: 统一 Agent Skill 全局安装目录
2026-09-12 23:13:02 +08:00
gitea 33db72f863 fix: install skill only in canonical global directory 2026-09-12 23:02:25 +08:00
gitea f26eae7b08 fix: make dry-run next steps executable 2026-09-11 17:41:58 +08:00
gitea 1571c524c1 feat: protect all CLI state mutations 2026-09-11 17:40:47 +08:00
gitea 3e072b490e feat: install development build globally 2026-09-11 17:35:29 +08:00
gitea 7cfb68e434 feat: migrate legacy hose configuration paths 2026-09-11 17:24:08 +08:00
gitea d15fa65517 feat: sync release version plugin and OpenAPI artifacts 2026-09-11 17:21:41 +08:00
gitea 34983e1c07 feat: add layered CLI help registry 2026-09-11 17:18:39 +08:00
gitea a5c0146c8d feat: add semantic CLI exit codes 2026-09-11 17:11:51 +08:00
gitea 45eb83a609 feat: unify CLI dry-run and write confirmation 2026-09-11 16:53:14 +08:00
gitea 639aaa9271 feat: embed keys and store skill guidance 2026-09-11 16:35:21 +08:00
yunyingk cd7bb44f04 Merge pull request #69 from yunyingk/codex/release-v0.8.5
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
release: v0.8.5 workflow lifecycle and monitoring
2026-09-09 18:43:03 +08:00
gitea 0cdd62161f feat: add workflow lifecycle controls and monitoring 2026-09-09 18:41:36 +08:00
yunyingk 9f9f3abe22 Merge pull request #68 from yunyingk/feat/feetype-domain
feat(feetype): add fee type domain CRUD CLI commands and specifications
2026-09-09 16:25:24 +08:00
gitea fb700a4c86 feat(feetype): add fee type domain CRUD CLI commands and specifications 2026-09-09 16:25:03 +08:00
yunyingk 0be629778f Merge pull request #67 from yunyingk/fix/clean-platform-test-spies
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
fix(test): clean up mock spies in platform.test.ts after each test
2026-09-09 16:03:08 +08:00
gitea a415bf38c3 fix(test): clean up mock spies in platform.test.ts after each test 2026-09-09 16:02:55 +08:00
yunyingk d447426d48 Merge pull request #66 from yunyingk/release/v0.8.4
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
chore(release): bump version to v0.8.4
2026-09-09 16:00:43 +08:00
gitea 03d2337e13 chore(release): bump version to v0.8.4 2026-09-09 16:00:26 +08:00
yunyingk 6f49bfc8a4 Merge pull request #65 from yunyingk/feat/datalink-record-actions
feat(datalink): record actions (get, toggle, edit, recompute) and active display fix
2026-09-09 15:55:34 +08:00
gitea 97b67c71da feat(datalink): add record get, toggle, edit, and recompute actions and fix active display 2026-09-09 15:55:12 +08:00
yunyingk 09c4e7df4a Merge pull request #64 from yunyingk/fix/align-app-platform-terminology-and-skill-version
fix(skill): 对齐应用管理与自建应用术语规范并同步 skill 至 v0.8.3
2026-09-09 15:21:44 +08:00
gitea 69c6396d38 fix(skill): align app and platform terminology and sync skill to v0.8.3 2026-09-09 15:21:18 +08:00
yunyingk 3c680d0ed3 Merge pull request #63 from yunyingk/feat/workbench-apps-and-menu
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
feat: add workbench apps, desktop menu domain, and bump to v0.8.3
2026-09-09 15:07:03 +08:00
gitea 215bc5e2a1 feat(app): add workbench apps, desktop menu domain and bump to v0.8.3 2026-09-09 15:06:34 +08:00
yunyingk 3d0bc2ebff Merge pull request #62 from yunyingk/feat/corps-search-and-aliases
feat(cli): add corps search command and intuitive aliases
2026-09-09 15:01:03 +08:00
gitea 1cd8901f7a feat(cli): add corps search command and intuitive aliases
- Implement hose-use corps search <keyword> with case-insensitive fuzzy matching across id, name, corpId, staffId, staffName, and accountId
- Format terminal table output with matched cell brackets, hit labels, active corp markers, and friendly no-match fallback
- Support --json structured output conforming to CliResult specification
- Add intuitive aliases for frequently guessed commands: auth list -> auth accounts, corps find -> corps search, config show -> config paths
- Enhance CorpSummary and CorpContext with corpId, staffName, and getAllCorps
- Add comprehensive unit tests in corps.test.ts, auth.test.ts, and config.test.ts
2026-09-09 14:42:58 +08:00
yunyingk 8efce4342a Merge pull request #61 from yunyingk/feat/datalink-business-object-query
feat: 通用 DataLink 应用对象与记录查询
2026-09-09 14:05:24 +08:00
gitea 893fc47ac6 feat(datalink): add generic app object and record queries 2026-09-09 13:57:45 +08:00
yunyingk 2502a49fb9 Merge pull request #60 from yunyingk/release/v0.8.1
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
chore(release): bump version to v0.8.1
2026-09-09 09:24:54 +08:00
gitea 212371eb03 chore(release): bump version to v0.8.1 2026-09-09 09:23:47 +08:00
yunyingk e852dbfd47 Merge pull request #59 from yunyingk/feat/store-and-openapi-keys
feat(store): 新增企业 OpenAPI 密钥一键提取(keys)与应用中心探查(store)能力
2026-09-09 09:23:02 +08:00
gitea 0c953df30e feat(store): 新增企业 OpenAPI 密钥一键提取(keys)与应用中心探查(store)能力 2026-09-08 16:59:57 +08:00
94 changed files with 9724 additions and 673 deletions

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "hose-use",
"version": "0.8.0",
"version": "0.8.6",
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
"author": {
"name": "yingqing"
+28 -4
View File
@@ -1,4 +1,4 @@
# hose-use (v0.8.0)
# hose-use (v0.8.6)
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
@@ -17,6 +17,19 @@ bun install
bun run cli <command>
```
### 方式三:将当前工作区安装为全局开发版
开发过程中需要让 PATH 中的 `hose-use` 立即使用当前源码时:
```bash
bun run dev:override
hose-use version
```
该命令会构建本机二进制、原子替换全局 `hose-use`,同步 `~/.agents/skills/hose-use`,并保留 `hose-aipro` 别名;后台服务若正在运行会自动重启。只预览动作可运行 `bun run dev:override -- --dry-run`。
> 开发版安装会覆盖当前 PATH 中的 `hose-use`,适合本机测试;发布环境请使用正式 Release 安装脚本。不要用 `npm install -g .` 代替,它会留下不会随源码更新的旧副本。
---
### CLI 常用命令速查 (`hose-use`)
@@ -29,6 +42,7 @@ hose-use auth refresh # 批量刷新账号名下全部
# 2. 多企业租户管理
hose-use corps list # 列出名下所有已配置企业
hose-use corps search <关键词> # 模糊搜索已保存的企业与员工 (别名: corps find)
hose-use corps switch <corpId> # 切换工作企业
hose-use corps current # 查看当前激活企业
@@ -38,11 +52,20 @@ hose-use config paths # 查看多级企业目录发现
hose-use config mode stateless # 切换为无状态模式 (防止 Agent 误操作)
hose-use config mode stateful # 切换为有状态模式 (记忆默认企业)
# 4. 平台与工作流管理 (跨自建应用聚合)
# 4. 工作台应用、菜单与工作流管理 (跨自建应用聚合)
hose-use app list # 查看工作台应用管理列表 (含套件/制度/模板/自建)
hose-use app get <应用ID|名称> # 查看具体应用详情与 Web 直达路由
hose-use menu list # 查看桌面端全站一级主导航与模块列表
hose-use workflow list # 汇总查看全部工作流列表
hose-use workflow get <pipelineId> # 获取工作流详情与节点结构
hose-use workflow find --task=code-js2 # 搜索包含特定节点类型的工作流
hose-use workflow toggle <pipelineId> --state=1 # 启用/停用工作流
hose-use workflow toggle <pipelineId> --state=1 --yes # 启用/停用工作流
hose-use workflow save <pipelineId> --file=workflow.json --yes # 按完整快照保存草稿
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> --yes # 保存后的发布/启用
hose-use platform list # 查看企业下所有启用的自建应用
# 5. 单据与费用明细管理 (DataLink 字典自动还原 & 200KB 防爆拦截)
@@ -84,7 +107,8 @@ hose-use mcp # 启动 MCP Server (默认暴露
### 模块化 Agent Skill 与 IDE 插件规范
- **多文件 Skill 模块体系**:知识体系划分至 `references/auth.md`、`references/bill.md`、`references/workflow.md`、`references/service.md`,执行 `hose-use skill install` 自动递归安装并支持环境自愈;
- **多文件 Skill 模块体系**:知识体系划分至 `references/auth.md`、`references/bill.md`、`references/workflow.md`、`references/service.md`,执行 `hose-use skill install` 自动递归安装到统一的 `~/.agents/skills/hose-use`;如需安装到其他位置,必须显式使用 `--dir`;
- **开发环境检查**:Git 工作树、分支、无引用提交、canonical Skill 与全局开发版可通过 `bun run dev:status`、`bun run dev:check` 检查;清理必须先 `bun run dev:clean --dry-run`,再追加 `--yes`;
- **原生 IDE 插件规范支持**:内嵌 `.zcode-plugin/plugin.json` 与 `.mcp.json` 清单,支持标准 IDE 插件市场/本地插件直接载入,并在设置界面支持可视化切换 MCP 开关;
- **MCP 单文件产物**:支持通过 `bun run build:plugin` 快速编译 Node.js 兼容的轻量单文件 `dist/mcp/server.js`。
+868 -482
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -2,7 +2,7 @@
"openapi": "3.1.0",
"info": {
"title": "hose-use API & MCP Tools Specification",
"version": "0.8.0",
"version": "0.8.6",
"description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."
},
"servers": [
+24
View File
@@ -10,6 +10,12 @@ src/domains/platform/
├── api.ts # HTTP 传输层(EKB / EASO / Piper 接口封装)
└── tools.ts # MCP tool 注册 + 服务层聚合函数
src/domains/datalink/
├── types.ts # 应用、业务对象、字段、记录与权限模型
├── api.ts # DataLink HTTP 接口封装
├── services.ts # 应用/对象解析与过滤辅助
└── tools.ts # DataLink MCP tools
src/server.ts # MCP Server 入口,负责 tool 注册与客户端派发
```
@@ -40,6 +46,18 @@ src/server.ts # MCP Server 入口,负责 tool 注册与客户端派发
## MCP Tools
### DataLink 应用与业务对象
| Tool | 说明 | 后端 |
|---|---|---|
| `datalink_platform_list` | 列出当前企业账号可见的启用自建应用 | EKB |
| `datalink_platform_get` | 获取应用详情及管理员、人员、角色、部门权限 | EKB |
| `datalink_entity_list` | 获取应用下业务对象、字段、操作和可见性配置 | EKB |
| `datalink_record_search` | 分页检索业务对象记录,支持 `filterBy` | EKB |
| `datalink_import_jobs` | 查看对象导入任务及最近导入结果 | EKB |
CLI 入口保持在 `platform` 命令域,支持 `list`、`get`、`entities`、`schema`、`records`、`permissions` 和 `imports`。
| Tool | 说明 | 后端 |
|---|---|---|
| `platform_list` | 列出企业下所有启用的自建应用 | EKB |
@@ -48,6 +66,12 @@ src/server.ts # MCP Server 入口,负责 tool 注册与客户端派发
| `platform_workflow_charge` | 查询企业工作流用量配额 | EASO |
| `platform_workflow_detail` | 获取工作流详情(含节点配置) | EASO / Piper |
| `platform_workflow_toggle` | 启用/停用工作流 | EASO / Piper |
| `workflow save` (CLI) | 按完整快照保存工作流草稿并校验版本 | Piper |
| `workflow history` (CLI) | 读取工作流服务端版本快照历史 | Piper |
| `workflow patch` (CLI) | 在本地完整快照上修改节点路径,生成新草稿文件 | 本地 |
| `workflow logs` (CLI) | 查询指定工作流运行日志 | Piper |
| `workflow check` (CLI) | 扫描错误管道并持久化去重提醒 | 本地 + EASO |
| `workflow publish` (CLI) | 将已保存的工作流状态切换为启用 | Piper |
| `platform_workflow_jobs` | 查询工作流运行中的任务 | EASO / Piper |
| `platform_workflow_dsl` | 获取工作流 DSL 配置列表 | EASO / Piper |
| `platform_workflow_staffs` | 获取企业员工列表 | EASO / Piper |
+1 -1
View File
@@ -1,7 +1,7 @@
openapi: 3.1.0
info:
title: hose-use API & MCP Tools Specification
version: 0.8.0
version: 0.8.6
description: >-
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
servers:
+8 -1
View File
@@ -1,6 +1,6 @@
{
"name": "hose-use",
"version": "0.8.0",
"version": "0.8.6",
"module": "src/server.ts",
"type": "module",
"bin": {
@@ -15,11 +15,18 @@
"typecheck": "tsc --noEmit",
"test": "bun test",
"bump": "bun run scripts/bump-version.ts",
"sync:release": "bun run scripts/bump-version.ts",
"check:version": "bun run scripts/check-version-sync.ts",
"openapi:bundle": "bun run scripts/bundle-openapi.ts",
"openapi:generate-raw": "bun run scripts/generate-raw-openapi.ts",
"openapi:all": "bun run scripts/generate-raw-openapi.ts && bun run scripts/bundle-openapi.ts",
"build:binary": "node scripts/build-binary.mjs",
"build:plugin": "node scripts/build-plugin.mjs",
"dev:override": "bun run scripts/dev-override.ts",
"dev:link": "bun run scripts/dev-override.ts",
"dev:status": "bun run scripts/dev-hygiene.ts status",
"dev:check": "bun run scripts/dev-hygiene.ts check",
"dev:clean": "bun run scripts/dev-hygiene.ts clean",
"dev": "bun run --watch src/server.ts",
"start": "bun run src/server.ts",
"export:workflow-schema": "bun run scripts/export-workflow-schema.ts"
+9 -5
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env bun
import { readFileSync, writeFileSync, existsSync, cpSync } from "node:fs";
import { readFileSync, writeFileSync, existsSync, cpSync, readdirSync } from "node:fs";
import { join } from "node:path";
import { execSync } from "node:child_process";
@@ -78,17 +78,21 @@ if (existsSync(pluginJsonPath)) {
// 6. Sync to global ~/.agents/skills/hose-use/ if present
const globalSkillDir = join(process.env.HOME || "", ".agents", "skills", "hose-use");
if (existsSync(globalSkillDir)) {
cpSync(join(ROOT, "skills", "hose-use"), globalSkillDir, { recursive: true });
const srcDir = join(ROOT, "skills", "hose-use");
for (const item of readdirSync(srcDir)) {
cpSync(join(srcDir, item), join(globalSkillDir, item), { recursive: true, force: true });
}
console.log("✓ Synchronized ~/.agents/skills/hose-use/");
}
// 7. Rebuild OpenAPI bundles
console.log("==> Rebuilding OpenAPI bundles...");
// 7. Rebuild OpenAPI and plugin bundles so generated artifacts stay in lockstep.
console.log("==> Rebuilding OpenAPI and plugin bundles...");
execSync("bun run openapi:all", { cwd: ROOT, stdio: "inherit" });
execSync("bun run build:plugin", { cwd: ROOT, stdio: "inherit" });
console.log("\n🎉 Successfully bumped version to " + nextVersion + "!");
console.log("\nNext steps to publish:");
console.log(` 1. Update CHANGELOG.md (if exists)`);
console.log(` 2. git commit -am "chore(release): bump version to v${nextVersion}"`);
console.log(` 3. git tag -a v${nextVersion} -m "🚀 Release v${nextVersion}"`);
console.log(` 4. git push origin main --tags\n`);
console.log(` 4. git push origin <feature-branch>\n`);
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env bun
import { readFileSync, existsSync } from "node:fs";
import { join } from "node:path";
const root = join(import.meta.dirname, "..");
const packageVersion = (JSON.parse(readFileSync(join(root, "package.json"), "utf8")) as { version: string }).version;
const expected: Array<[string, string | undefined]> = [
["package.json", packageVersion],
["src/version.ts", readFileSync(join(root, "src/version.ts"), "utf8").match(/VERSION\s*=\s*[\"']([^\"']+)/)?.[1]],
[".zcode-plugin/plugin.json", readJsonVersion(".zcode-plugin/plugin.json")],
["openapi/openapi.yaml", readFileSync(join(root, "openapi/openapi.yaml"), "utf8").match(/^\s+version:\s+([^\s]+)\s*$/m)?.[1]],
["dist/openapi.json", readJsonVersion("dist/openapi.json", ["info", "version"])],
];
const mismatches = expected.filter(([, value]) => value !== packageVersion);
if (mismatches.length) {
console.error(`Version drift detected; expected ${packageVersion}:`);
for (const [file, value] of mismatches) console.error(` ${file}: ${value ?? "missing"}`);
process.exit(1);
}
console.log(`Version synchronized: ${packageVersion}`);
function readJsonVersion(file: string, path: string[] = ["version"]): string | undefined {
const fullPath = join(root, file);
if (!existsSync(fullPath)) return undefined;
let value: unknown = JSON.parse(readFileSync(fullPath, "utf8"));
for (const key of path) {
if (!value || typeof value !== "object") return undefined;
value = (value as Record<string, unknown>)[key];
}
return typeof value === "string" ? value : undefined;
}
+42
View File
@@ -0,0 +1,42 @@
import { describe, expect, test } from "bun:test";
import { buildCleanupPlan, classifyExitCode, parseDevHygieneArgs, type Finding } from "./dev-hygiene.ts";
describe("dev hygiene tooling", () => {
test("only accepts development-scoped modes and confirmation flags", () => {
expect(parseDevHygieneArgs(["status"])).toEqual({ mode: "status", dryRun: false, yes: false, pruneUnreachable: false, help: false });
expect(parseDevHygieneArgs(["clean", "--dry-run"])).toEqual({ mode: "clean", dryRun: true, yes: false, pruneUnreachable: false, help: false });
expect(parseDevHygieneArgs(["clean", "--yes", "--prune-unreachable"])).toEqual({ mode: "clean", dryRun: false, yes: true, pruneUnreachable: true, help: false });
});
test("uses semantic exit codes for clean, warning, and blocked states", () => {
const finding = (level: Finding["level"]): Finding => ({ id: level, level, message: level });
expect(classifyExitCode([])).toBe(0);
expect(classifyExitCode([finding("info")])).toBe(0);
expect(classifyExitCode([finding("warning")])).toBe(2);
expect(classifyExitCode([finding("blocked")])).toBe(3);
});
test("only plans deletion for clean merged worktrees and local branches", () => {
const snapshot = {
repository: {} as any,
worktrees: [
{ path: "/tmp/merged", head: "a", branch: "feat/merged", current: false, exists: true, clean: true },
{ path: "/tmp/dirty", head: "b", branch: "feat/dirty", current: false, exists: true, clean: false },
],
branches: [
{ name: "main", sha: "m", merged: true, gone: false },
{ name: "feat/merged", sha: "a", merged: true, gone: false },
{ name: "feat/dirty", sha: "b", merged: true, gone: false },
{ name: "feat/live", sha: "c", merged: false, gone: false },
],
unreachableCommits: ["deadbeef"],
skill: {} as any,
binaries: [],
legacyConfig: {} as any,
};
const plan = buildCleanupPlan(snapshot, false);
expect(plan.map((action) => action.target)).toEqual(["/tmp/merged", "feat/merged"]);
expect(plan[1]?.kind).toBe("branch-delete");
expect(plan.some((action) => action.kind === "git-prune")).toBe(false);
});
});
+517
View File
@@ -0,0 +1,517 @@
#!/usr/bin/env bun
import { createHash } from "node:crypto";
import { execFileSync, spawnSync } from "node:child_process";
import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join, relative, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const PACKAGE = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")) as { version: string };
const CANONICAL_SKILL_DIR = join(homedir(), ".agents", "skills", "hose-use");
const NON_CANONICAL_SKILL_DIRS = [
join(homedir(), ".gemini", "antigravity", "skills", "hose-use"),
join(homedir(), ".codex", "skills", "hose-use"),
];
export type FindingLevel = "info" | "warning" | "blocked";
export type HygieneMode = "status" | "check" | "clean";
export interface Finding {
id: string;
level: FindingLevel;
message: string;
details?: Record<string, unknown>;
nextAction?: string;
}
export interface HygieneArgs {
mode: HygieneMode;
dryRun: boolean;
yes: boolean;
pruneUnreachable: boolean;
help: boolean;
}
export interface CleanupAction {
kind: "worktree-remove" | "worktree-prune" | "branch-delete" | "git-prune";
target: string;
command: string;
reason: string;
}
interface GitBranch {
name: string;
sha: string;
upstream?: string;
gone: boolean;
merged: boolean;
}
interface GitWorktree {
path: string;
head: string;
branch?: string;
current: boolean;
exists: boolean;
clean?: boolean;
}
interface HygieneSnapshot {
repository: {
root: string;
branch: string;
head: string;
upstream?: string;
ahead: number;
behind: number;
clean: boolean;
stagedChanges: number;
unstagedChanges: number;
untrackedFiles: number;
};
worktrees: GitWorktree[];
branches: GitBranch[];
unreachableCommits: string[];
skill: {
canonicalDir: string;
canonicalExists: boolean;
canonicalIsSymlink: boolean;
missingFiles: string[];
mismatchedFiles: string[];
nonCanonicalCopies: Array<{ dir: string; exists: boolean; isSymlink: boolean; pointsToCanonical: boolean }>;
};
binaries: Array<{
name: string;
path?: string;
version?: string;
expectedVersion: string;
matches: boolean;
error?: string;
}>;
legacyConfig: {
enterprisesDir: string;
configFile: string;
enterprisesDirExists: boolean;
configFileExists: boolean;
};
}
export interface HygieneReport {
schemaVersion: 1;
mode: HygieneMode;
generatedAt: string;
repository: string;
snapshot: HygieneSnapshot;
findings: Finding[];
counts: Record<FindingLevel, number>;
nextActions: string[];
exitCode: number;
}
export function parseDevHygieneArgs(argv: string[]): HygieneArgs {
const requestedMode = argv.find((arg) => !arg.startsWith("--")) || "check";
const mode: HygieneMode = requestedMode === "status" || requestedMode === "clean" ? requestedMode : "check";
return {
mode,
dryRun: argv.includes("--dry-run") || argv.includes("--dryRun"),
yes: argv.includes("--yes") || argv.includes("--confirm"),
pruneUnreachable: argv.includes("--prune-unreachable"),
help: argv.includes("--help") || argv.includes("-h"),
};
}
export function classifyExitCode(findings: Finding[]): number {
if (findings.some((finding) => finding.level === "blocked")) return 3;
if (findings.some((finding) => finding.level === "warning")) return 2;
return 0;
}
function git(args: string[], cwd = ROOT): string {
try {
return execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
} catch (error) {
const detail = error instanceof Error ? error.message : String(error);
throw new Error(`git ${args.join(" ")} 失败: ${detail}`);
}
}
function gitMaybe(args: string[], cwd = ROOT): string | undefined {
try {
return git(args, cwd).trim() || undefined;
} catch {
return undefined;
}
}
function parseRepository(): HygieneSnapshot["repository"] {
const status = git(["status", "--porcelain=v1", "-b"]);
const lines = status.split("\n").filter(Boolean);
const branchLine = lines.shift() || "## HEAD";
const branch = branchLine.replace(/^##\s+/, "").split("...")[0] || "HEAD";
const changes = lines.filter((line) => !line.startsWith("##"));
const stagedChanges = changes.filter((line) => line !== "??" && line[0] !== " " && line[0] !== "?").length;
const unstagedChanges = changes.filter((line) => line !== "??" && line[1] !== " " && line.slice(0, 2) !== "??").length;
const untrackedFiles = changes.filter((line) => line.startsWith("??")).length;
const upstream = gitMaybe(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"]);
const divergence = upstream ? gitMaybe(["rev-list", "--left-right", "--count", "HEAD...@{upstream}"]) : undefined;
const [ahead, behind] = (divergence || "0 0").split(/\s+/).map((value) => Number(value) || 0);
return {
root: ROOT,
branch,
head: git(["rev-parse", "--short", "HEAD"]).trim(),
...(upstream ? { upstream } : {}),
ahead,
behind,
clean: changes.length === 0,
stagedChanges,
unstagedChanges,
untrackedFiles,
};
}
function parseWorktrees(): GitWorktree[] {
const records: GitWorktree[] = [];
let current: Partial<GitWorktree> = {};
const flush = () => {
if (!current.path) return;
const path = resolve(current.path);
const exists = existsSync(path);
let clean: boolean | undefined;
if (exists) {
try {
clean = git(["status", "--porcelain=v1"], path).trim() === "";
} catch {
clean = undefined;
}
}
records.push({
path,
head: current.head || "",
...(current.branch ? { branch: current.branch } : {}),
current: path === ROOT,
exists,
...(clean === undefined ? {} : { clean }),
});
current = {};
};
for (const line of git(["worktree", "list", "--porcelain"]).split("\n")) {
if (!line) {
flush();
continue;
}
const [key, ...rest] = line.split(" ");
const value = rest.join(" ");
if (key === "worktree") current.path = value;
if (key === "HEAD") current.head = value;
if (key === "branch") current.branch = value.replace(/^refs\/heads\//, "");
}
flush();
return records;
}
function parseBranches(): GitBranch[] {
const merged = new Set(git(["branch", "--merged", "main", "--format=%(refname:short)"]).split("\n").filter(Boolean));
return git(["for-each-ref", "--format=%(refname:short)%09%(objectname:short)%09%(upstream:short)%09%(upstream:track)", "refs/heads"])
.split("\n")
.filter(Boolean)
.map((line) => {
const [name, sha, upstream, track] = line.split("\t");
return { name, sha, ...(upstream ? { upstream } : {}), gone: track === "[gone]", merged: merged.has(name) };
});
}
function parseUnreachableCommits(): string[] {
return git(["fsck", "--full", "--no-reflogs", "--unreachable"])
.split("\n")
.filter((line) => line.includes(" commit "))
.map((line) => line.trim().split(/\s+/)[2])
.filter(Boolean);
}
function listFiles(dir: string, base = dir): string[] {
if (!existsSync(dir)) return [];
const files: string[] = [];
for (const entry of readdirSync(dir, { withFileTypes: true })) {
const fullPath = join(dir, entry.name);
if (entry.isDirectory() && !entry.isSymbolicLink()) files.push(...listFiles(fullPath, base));
else files.push(relative(base, fullPath));
}
return files.sort();
}
function fileHash(path: string): string | undefined {
try {
return createHash("sha256").update(readFileSync(path)).digest("hex");
} catch {
return undefined;
}
}
function parseSkill(): HygieneSnapshot["skill"] {
const expectedFiles = git(["ls-files", "skills/hose-use"]).split("\n").filter(Boolean).map((path) => path.slice("skills/hose-use/".length));
const missingFiles = expectedFiles.filter((file) => !existsSync(join(CANONICAL_SKILL_DIR, file)));
const mismatchedFiles = expectedFiles.filter((file) => {
const sourceHash = fileHash(join(ROOT, "skills", "hose-use", file));
const targetHash = fileHash(join(CANONICAL_SKILL_DIR, file));
return sourceHash !== undefined && targetHash !== undefined && sourceHash !== targetHash;
});
return {
canonicalDir: CANONICAL_SKILL_DIR,
canonicalExists: existsSync(CANONICAL_SKILL_DIR),
canonicalIsSymlink: existsSync(CANONICAL_SKILL_DIR) && lstatSync(CANONICAL_SKILL_DIR).isSymbolicLink(),
missingFiles,
mismatchedFiles,
nonCanonicalCopies: NON_CANONICAL_SKILL_DIRS.map((dir) => ({
dir,
exists: existsSync(dir),
isSymlink: existsSync(dir) && lstatSync(dir).isSymbolicLink(),
pointsToCanonical: (() => {
try {
return lstatSync(dir).isSymbolicLink() && realpathSync(dir) === CANONICAL_SKILL_DIR;
} catch {
return false;
}
})(),
})),
};
}
function resolveCommand(name: string): string | undefined {
const result = spawnSync("which", [name], { encoding: "utf8" });
if (result.status === 0 && result.stdout?.trim()) return result.stdout.trim();
return undefined;
}
function inspectBinary(name: string): HygieneSnapshot["binaries"][number] {
const path = resolveCommand(name);
if (!path) return { name, expectedVersion: PACKAGE.version, matches: false, error: "PATH 中未找到" };
const result = spawnSync(path, ["version", "--json"], { cwd: ROOT, encoding: "utf8", timeout: 5000 });
if (result.status !== 0) {
return { name, path, expectedVersion: PACKAGE.version, matches: false, error: result.stderr?.trim() || `退出码 ${result.status ?? 1}` };
}
try {
const version = (JSON.parse(result.stdout) as { version?: string }).version;
return { name, path, version, expectedVersion: PACKAGE.version, matches: version === PACKAGE.version };
} catch {
return { name, path, expectedVersion: PACKAGE.version, matches: false, error: "版本输出不是 JSON" };
}
}
function parseLegacyConfig(): HygieneSnapshot["legacyConfig"] {
const home = homedir();
const enterprisesDir = join(home, ".cache", "ekb-mcp", "enterprises");
const configFile = join(home, ".cache", "ekb-mcp", "config.json");
return { enterprisesDir, configFile, enterprisesDirExists: existsSync(enterprisesDir), configFileExists: existsSync(configFile) };
}
function collectSnapshot(): HygieneSnapshot {
return {
repository: parseRepository(),
worktrees: parseWorktrees(),
branches: parseBranches(),
unreachableCommits: parseUnreachableCommits(),
skill: parseSkill(),
binaries: [inspectBinary("hose-use"), inspectBinary("hose-aipro")],
legacyConfig: parseLegacyConfig(),
};
}
function buildFindings(snapshot: HygieneSnapshot): Finding[] {
const findings: Finding[] = [];
const repo = snapshot.repository;
if (!repo.clean) {
findings.push({ id: "repo.dirty", level: "warning", message: "当前开发工作树存在未提交修改", details: { stagedChanges: repo.stagedChanges, unstagedChanges: repo.unstagedChanges, untrackedFiles: repo.untrackedFiles }, nextAction: "先确认这些修改属于当前工作,必要时提交或单独保存" });
}
if (repo.branch === "HEAD") findings.push({ id: "repo.detached", level: "blocked", message: "当前处于 detached HEAD", nextAction: "切换到明确的开发分支后再进行清理" });
if (repo.behind > 0) findings.push({ id: "repo.behind", level: "warning", message: "当前分支落后于上游分支", details: { upstream: repo.upstream, behind: repo.behind }, nextAction: "确认远程变化后再执行开发清理" });
for (const worktree of snapshot.worktrees) {
if (!worktree.exists) {
findings.push({ id: "worktree.missing", level: "blocked", message: "Git 记录了不存在的工作树路径", details: { path: worktree.path, branch: worktree.branch }, nextAction: "先用 git worktree prune 清理失效记录" });
} else if (!worktree.current && worktree.clean === false) {
findings.push({ id: "worktree.dirty", level: "warning", message: "额外工作树存在未提交修改", details: { path: worktree.path, branch: worktree.branch }, nextAction: "不要自动删除;先进入该工作树确认修改归属" });
} else if (!worktree.current) {
findings.push({ id: "worktree.extra", level: "info", message: "存在额外工作树,需人工确认是否仍有用途", details: { path: worktree.path, branch: worktree.branch } });
}
}
for (const branch of snapshot.branches) {
if (branch.name === snapshot.repository.branch) continue;
if (branch.name !== "main" && branch.merged) {
const linked = snapshot.worktrees.some((worktree) => worktree.branch === branch.name);
findings.push({ id: "branch.merged", level: linked ? "warning" : "info", message: linked ? "已合并分支仍被工作树占用" : "发现已合并的本地分支", details: { branch: branch.name, sha: branch.sha, linkedWorktree: linked } });
} else if (branch.gone) {
findings.push({ id: "branch.gone", level: "warning", message: "本地分支的上游远程分支已不存在", details: { branch: branch.name, upstream: branch.upstream }, nextAction: "确认本地分支不再需要后再删除" });
}
}
if (snapshot.unreachableCommits.length) {
findings.push({ id: "git.unreachable", level: "warning", message: "发现无分支或标签引用的 Git commit", details: { count: snapshot.unreachableCommits.length, commits: snapshot.unreachableCommits }, nextAction: "先检查内容,确认后使用 dev:clean --yes --prune-unreachable" });
}
const skill = snapshot.skill;
if (!skill.canonicalExists || skill.missingFiles.length || skill.mismatchedFiles.length) {
findings.push({ id: "skill.canonical-drift", level: "warning", message: "canonical Skill 缺失或与当前源码不一致", details: { dir: skill.canonicalDir, missingFiles: skill.missingFiles, mismatchedFiles: skill.mismatchedFiles }, nextAction: "运行 bun run dev:override 同步开发版 Skill" });
}
for (const copy of skill.nonCanonicalCopies.filter((item) => item.exists && !item.pointsToCanonical)) {
findings.push({ id: "skill.noncanonical-copy", level: "warning", message: "发现非 canonical Skill 副本;检查不会删除它", details: copy, nextAction: "确认外部工具不再使用后,再单独设计迁移或软链接" });
}
for (const binary of snapshot.binaries) {
if (!binary.path) {
findings.push({ id: "binary.missing", level: "info", message: `${binary.name} 未安装到 PATH`, details: binary, nextAction: "如需全局开发版,运行 bun run dev:override" });
} else if (!binary.matches) {
findings.push({ id: "binary.drift", level: "warning", message: `${binary.name} 全局版本与当前源码不一致`, details: binary, nextAction: "运行 bun run dev:override 同步全局开发版" });
}
}
const legacy = snapshot.legacyConfig;
if (legacy.enterprisesDirExists || legacy.configFileExists) {
findings.push({ id: "config.legacy", level: "warning", message: "发现旧版 ekb-mcp 配置路径;检查不会删除配置", details: legacy, nextAction: "先确认迁移结果,再按配置迁移策略清理" });
}
return findings;
}
export function buildCleanupPlan(snapshot: HygieneSnapshot, pruneUnreachable: boolean): CleanupAction[] {
const actions: CleanupAction[] = [];
if (snapshot.worktrees.some((worktree) => !worktree.exists)) {
actions.push({ kind: "worktree-prune", target: "stale-worktree-records", command: "git worktree prune", reason: "移除 Git 记录中已经不存在的工作树" });
}
const removableWorktreeBranches = new Set(
snapshot.worktrees
.filter((worktree) => !worktree.current && worktree.exists && worktree.clean && worktree.branch && snapshot.branches.some((branch) => branch.name === worktree.branch && branch.merged))
.map((worktree) => worktree.branch)
.filter((branch): branch is string => Boolean(branch))
);
const linkedPaths = new Set(
snapshot.worktrees
.filter((worktree) => !removableWorktreeBranches.has(worktree.branch || ""))
.map((worktree) => worktree.branch)
.filter((branch): branch is string => Boolean(branch))
);
for (const worktree of snapshot.worktrees) {
if (!worktree.current && worktree.exists && worktree.clean && worktree.branch && snapshot.branches.some((branch) => branch.name === worktree.branch && branch.merged)) {
actions.push({ kind: "worktree-remove", target: worktree.path, command: `git worktree remove ${JSON.stringify(worktree.path)}`, reason: `工作树干净且分支 ${worktree.branch} 已合并` });
}
}
for (const branch of snapshot.branches) {
if (branch.name !== "main" && branch.merged && !linkedPaths.has(branch.name)) {
actions.push({ kind: "branch-delete", target: branch.name, command: `git branch -d ${branch.name}`, reason: "本地分支已合并且没有关联工作树" });
}
}
if (pruneUnreachable && snapshot.unreachableCommits.length) {
actions.push({ kind: "git-prune", target: "unreachable-objects", command: "git reflog expire --expire=now --all && git gc --prune=now", reason: "明确启用 unreachable 对象清理" });
}
return actions;
}
function applyCleanup(actions: CleanupAction[]): Array<{ action: CleanupAction; ok: boolean; error?: string }> {
return actions.map((action) => {
try {
if (action.kind === "worktree-remove") git(["worktree", "remove", action.target]);
else if (action.kind === "worktree-prune") git(["worktree", "prune"]);
else if (action.kind === "branch-delete") git(["branch", "-d", action.target]);
else {
git(["reflog", "expire", "--expire=now", "--all"]);
git(["gc", "--prune=now"]);
}
return { action, ok: true };
} catch (error) {
return { action, ok: false, error: error instanceof Error ? error.message : String(error) };
}
});
}
function createReport(mode: HygieneMode): HygieneReport {
const snapshot = collectSnapshot();
const findings = buildFindings(snapshot);
const counts = {
info: findings.filter((finding) => finding.level === "info").length,
warning: findings.filter((finding) => finding.level === "warning").length,
blocked: findings.filter((finding) => finding.level === "blocked").length,
};
const exitCode = classifyExitCode(findings);
return {
schemaVersion: 1,
mode,
generatedAt: new Date().toISOString(),
repository: ROOT,
snapshot,
findings,
counts,
nextActions: findings.map((finding) => finding.nextAction).filter((action): action is string => Boolean(action)),
exitCode,
};
}
function emit(value: unknown): void {
process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
}
function emitSummary(report: HygieneReport): void {
console.error(`[dev:${report.mode}] ${report.repository}`);
console.error(`发现 ${report.counts.info} 条提示、${report.counts.warning} 条警告、${report.counts.blocked} 条阻塞项;退出码 ${report.exitCode}`);
for (const finding of report.findings) console.error(`- [${finding.level}] ${finding.message}`);
}
function usage(): string {
return [
"开发环境检查(不会进入 hose-use 用户命令):",
" bun run dev:status 输出当前开发环境快照",
" bun run dev:check 只读检查并返回语义化退出码",
" bun run dev:clean --dry-run 预览安全清理动作",
" bun run dev:clean --yes 执行干净且已合并的本地清理",
" bun run dev:clean --yes --prune-unreachable 额外清理无引用 Git 对象",
"",
"stdout 始终为 JSON;人类提示和进度写入 stderr。远程分支和非 canonical Skill 目录不会被自动删除。",
].join("\n");
}
export async function main(argv = process.argv.slice(2)): Promise<number> {
const args = parseDevHygieneArgs(argv);
if (args.help) {
emit({ ok: true, usage: usage().split("\n") });
console.error(usage());
return 0;
}
try {
if (args.mode !== "clean") {
const report = createReport(args.mode);
emit(report);
emitSummary(report);
return args.mode === "status" ? 0 : report.exitCode;
}
const report = createReport("clean");
const plan = buildCleanupPlan(report.snapshot, args.pruneUnreachable);
if (args.dryRun || !args.yes) {
emit({ ...report, plan, dryRun: true, nextAction: "bun run dev:clean --yes" });
emitSummary(report);
console.error(plan.length ? "[dev:clean] 当前仅预览,追加 --yes 才会执行。" : "[dev:clean] 没有满足安全条件的本地清理动作。");
return report.exitCode;
}
if (report.snapshot.repository.branch === "HEAD") {
emit({ ...report, plan, applied: false, error: "detached HEAD 下拒绝清理" });
return 3;
}
const results = applyCleanup(plan);
const failed = results.filter((result) => !result.ok);
emit({ ...report, plan, applied: true, results, failed: failed.length });
console.error(`[dev:clean] 已执行 ${results.length - failed.length} 项,失败 ${failed.length} 项。`);
return failed.length ? 4 : 0;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
emit({ ok: false, error: message });
console.error(`[dev:hygiene] ${message}`);
return 4;
}
}
if (import.meta.main) {
main().then((exitCode) => {
process.exitCode = exitCode;
});
}
+17
View File
@@ -0,0 +1,17 @@
import { describe, expect, test } from "bun:test";
import { globalBinCandidates, parseDevOverrideArgs } from "./dev-override.js";
describe("dev:override", () => {
test("parses dry-run and explicit target path without touching the host", () => {
expect(parseDevOverrideArgs(["--dry-run", "--target-path=/tmp/hose-use-test"])).toEqual({
dryRun: true,
targetPath: "/tmp/hose-use-test",
});
});
test("uses stable global binary locations", () => {
const candidates = globalBinCandidates("hose-use-test");
expect(candidates.some((candidate) => candidate.endsWith("/hose-use-test"))).toBe(true);
expect(candidates).toHaveLength(4);
});
});
+159
View File
@@ -0,0 +1,159 @@
#!/usr/bin/env bun
import { chmodSync, copyFileSync, cpSync, existsSync, mkdirSync, rmSync, symlinkSync } from "node:fs";
import { spawnSync } from "node:child_process";
import { homedir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
export interface DevOverrideOptions {
dryRun: boolean;
targetPath?: string;
}
export function parseDevOverrideArgs(argv: string[]): DevOverrideOptions {
return {
dryRun: argv.includes("--dry-run") || argv.includes("--dryRun"),
targetPath: argv.find((arg) => arg.startsWith("--target-path="))?.slice("--target-path=".length),
};
}
export function globalBinCandidates(commandName = "hose-use"): string[] {
return [
"/opt/homebrew/bin",
"/usr/local/bin",
join(homedir(), ".local", "bin"),
join(homedir(), "bin"),
].map((dir) => join(dir, commandName));
}
export function resolveTargetBinaryPath(commandName = "hose-use"): string {
try {
const whichRes = spawnSync("which", [commandName], { encoding: "utf8" });
if (whichRes.status === 0 && whichRes.stdout) {
const path = whichRes.stdout.trim();
if (path && existsSync(path)) return path;
}
} catch {
// Fall back to conventional user-level locations.
}
for (const candidate of globalBinCandidates(commandName)) {
if (existsSync(dirname(candidate))) return candidate;
}
const defaultDir = join(homedir(), ".local", "bin");
mkdirSync(defaultDir, { recursive: true });
return join(defaultDir, commandName);
}
function runBuild(): string {
const result = spawnSync("node", ["scripts/build-binary.mjs"], {
cwd: ROOT,
stdio: ["ignore", "inherit", "inherit"],
});
if (result.error) throw result.error;
if (result.status !== 0) throw new Error(`构建开发版二进制失败,退出码: ${result.status ?? 1}`);
const localBinary = join(ROOT, "dist", "bin", "hose-use");
if (!existsSync(localBinary)) throw new Error(`未找到构建产物: ${localBinary}`);
return localBinary;
}
function stopRunningService(targetPath: string): boolean {
try {
const statusRes = spawnSync(targetPath, ["service", "status", "--json"], { encoding: "utf8" });
if (statusRes.status !== 0 || !statusRes.stdout) return false;
const status = JSON.parse(statusRes.stdout) as { running?: boolean };
if (!status.running) return false;
console.error("==> [dev:override] 停止正在运行的后台服务...");
const stopRes = spawnSync(targetPath, ["service", "stop"], { stdio: "ignore" });
if (stopRes.status !== 0) throw new Error("无法停止后台服务,已中止替换操作");
return true;
} catch (error) {
if (error instanceof Error && error.message.includes("无法停止")) throw error;
return false;
}
}
function installBinary(localBinary: string, targetPath: string): void {
const targetDir = dirname(targetPath);
mkdirSync(targetDir, { recursive: true });
const temporaryPath = `${targetPath}.tmp.${process.pid}.${Date.now()}`;
try {
copyFileSync(localBinary, temporaryPath);
chmodSync(temporaryPath, 0o755);
if (process.platform === "darwin") {
spawnSync("/usr/bin/codesign", ["--remove-signature", temporaryPath], { stdio: "ignore" });
spawnSync("/usr/bin/codesign", ["--force", "--sign", "-", temporaryPath], { stdio: "ignore" });
}
// copyFileSync follows an existing symlink, so a package-manager shim is not
// accidentally replaced by a regular file.
copyFileSync(temporaryPath, targetPath);
chmodSync(targetPath, 0o755);
} finally {
rmSync(temporaryPath, { force: true });
}
}
function syncAgentSkill(): string | undefined {
const source = join(ROOT, "skills", "hose-use");
const target = join(homedir(), ".agents", "skills", "hose-use");
if (!existsSync(source)) return undefined;
mkdirSync(dirname(target), { recursive: true });
cpSync(source, target, { recursive: true, force: true });
return target;
}
export async function main(argv = process.argv.slice(2)): Promise<number> {
const options = parseDevOverrideArgs(argv);
const targetPath = options.targetPath || resolveTargetBinaryPath();
console.error("==> [dev:override] 将当前工作区安装为全局开发版 hose-use");
console.error(` 工作区: ${ROOT}`);
console.error(` 目标: ${targetPath}`);
if (options.dryRun) {
console.error("[DRY-RUN] 将执行: 构建 dist/bin/hose-use、替换全局二进制、同步 ~/.agents/skills/hose-use");
return 0;
}
const builtBinary = runBuild();
const serviceWasRunning = stopRunningService(targetPath);
installBinary(builtBinary, targetPath);
const aiproPath = join(dirname(targetPath), "hose-aipro");
if (aiproPath !== targetPath) {
rmSync(aiproPath, { force: true });
symlinkSync(targetPath, aiproPath);
}
try {
const skillTarget = syncAgentSkill();
if (skillTarget) console.error(`✓ [dev:override] 已同步 Agent Skill: ${skillTarget}`);
} catch (error) {
console.error(`⚠️ [dev:override] Agent Skill 同步失败: ${error}`);
}
if (serviceWasRunning) {
console.error("==> [dev:override] 使用新二进制重启后台服务...");
const startRes = spawnSync(targetPath, ["service", "start"], { stdio: "ignore" });
if (startRes.status !== 0) console.error("⚠️ [dev:override] 后台服务重启失败,请手动运行 hose-use service start");
}
const versionRes = spawnSync(targetPath, ["version"], { encoding: "utf8" });
if (versionRes.status !== 0) throw new Error(versionRes.stderr || "开发版安装后校验失败");
console.error("✨ [dev:override] 全局开发版安装完成");
process.stdout.write(versionRes.stdout || "");
return 0;
}
if (import.meta.main) {
main().catch((error) => {
console.error(`❌ [dev:override] ${error instanceof Error ? error.message : String(error)}`);
process.exitCode = 1;
});
}
+56 -13
View File
@@ -1,12 +1,12 @@
---
name: hose-use
description: "v0.8.0: 合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号 API 登录、租户切换、单据检索与审批动作、工作流跨域扫描、内置 HTTP 交互文档与常驻守护进程。"
description: "v0.8.6: 合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号 API 登录、租户切换、单据检索与审批动作、工作流跨域扫描、内置 HTTP 交互文档与常驻守护进程。"
metadata:
version: 0.8.0
short-description: 合思/易快报企业级 CLI 工具与底层 SDK (v0.8.0)
version: 0.8.6
short-description: 合思/易快报企业级 CLI 工具与底层 SDK (v0.8.6)
---
# hose-use (v0.8.0)
# hose-use (v0.8.6)
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
@@ -22,7 +22,10 @@ metadata:
- 面对单据明细、实体字典、工作流等大数据量查询,优先使用 `--json -o <path>` 本地转储或使用 `--limit` 限制分页;
- 严禁盲目使用 `--full` 将上万行原始报文一次性塞入上下文;
- 永远解析 JSON stdout,不要从格式化表格的终端字符中正则刮取数据。
4. **无状态与并发安全**:Agent 在自动化批处理或会话中,建议使用无状态模式(添加 `--stateless` 或显式指定 `--corp=<id>`),避免多任务并发切换全局状态发生冲突。
4. **密钥安全**:`keys` 默认在表格和 JSON 中脱敏 `appSecurity`;只有用户明确需要完整凭证时才使用 `--reveal`/`-r`。不要把明文密钥写入日志、共享文件、提示词或聊天回复;尤其不要组合 `--reveal -o <path>`。
5. **无状态与并发安全**:Agent 在自动化批处理或会话中,建议使用无状态模式(添加 `--stateless` 或显式指定 `--corp=<id>`),避免多任务并发切换全局状态发生冲突。
6. **写操作两阶段确认**:所有 CLI 写操作先使用 `--dry-run` 查看目标和变更,再使用同一命令追加 `--yes` 或 `--confirm` 执行;未确认时不会发起写请求或写入本地状态。
7. **开发版全局安装**:需要让 PATH 中的命令立即跟随当前工作区时,运行 `bun run dev:override`;它会构建本机二进制、同步 Agent Skill,并更新全局 `hose-use` / `hose-aipro`。可先用 `bun run dev:override -- --dry-run` 查看计划;不要使用 `npm install -g .` 留下静态旧副本。
---
@@ -34,7 +37,7 @@ metadata:
| AI PRO 审批仲裁网关状态与当前连接企业 | `hose-aipro status [--json]`, `hose-use aipro status` | [references/approval.md](references/approval.md) |
| AI PRO 规则场景库与审核要点清单 | `hose-aipro scopes`, `hose-aipro points <索引>` | [references/approval.md](references/approval.md) |
| AI PRO 确定性审批仲裁全流程 (核验/仲裁) | `hose-aipro bind`, `hose-aipro review`, `hose-aipro decide` | [references/approval.md](references/approval.md) |
| 本地 AI 审批规约与规则增删改查 | `hose-use rule scopes`, `hose-use rule add`, `hose-use rule list` | [references/approval.md](references/approval.md) |
| 本地 AI 审批规约与规则增删改查 | `hose-use rule scopes`, `hose-use rule add --dry-run/--yes`, `hose-use rule list` | [references/approval.md](references/approval.md) |
| 首次登录 / 账密认证 / Token过期 / 多账号 | `hose-use auth login`, `hose-use auth status`, `hose-use auth refresh` | [references/auth.md](references/auth.md) |
| 第三方免密/协助链接一键秒级导入 | `hose-use corps add-link <url>`, `hose-use auth add-link <url>` | [references/auth.md](references/auth.md) |
| 代客协助凭证导入 / 探针连通性诊断 | `hose-use auth import`, `hose-use probe` | [references/auth.md](references/auth.md) |
@@ -49,17 +52,25 @@ metadata:
| 单据附件 / 发票原件标准列表 | `hose-use bill attachments <单号|ID>` | [references/bill.md](references/bill.md) |
| 单据附件下载 | `hose-use bill download <单号|ID> --output-dir <目录>` | [references/bill.md](references/bill.md) |
| 系统/自定义档案维度与档案项 | `hose-use dimension list`, `hose-use dimension items <维度>` | [references/dimension.md](references/dimension.md) |
| 费用类型全生命周期与表单规格 (增删查改/停启用/移动/字段) | `hose-use feetype list`, `hose-use feetype create`, `hose-use feetype get <ID>` | [references/feetype.md](references/feetype.md) |
| 企业角色、角色组与角色成员 | `hose-use role list`, `hose-use role groups`, `hose-use role members <角色>` | [references/role.md](references/role.md) |
| 角色权限只读快照 | `hose-use permission get` | [references/role.md](references/role.md) |
| 单据 Web 详情直达链接生成 | `hose-use bill link <单号|ID>` | [references/bill.md](references/bill.md) |
| 单据实体模型与字段元数据查询 | `hose-use bill schema` | [references/bill.md](references/bill.md) |
| 企业通讯录检索 / 员工档案 / 防爆保护 | `hose-use contact search`, `hose-use contact list`, `hose-use contact get` | [references/contact.md](references/contact.md) |
| 待办中心 / 已审批 / 我发起的 / 审批记录 / 抄送 | `hose-use task todo`, `hose-use task submitted`, `hose-use task records`, `hose-use task cc` | [references/task.md](references/task.md) |
| 消息中心 / 未读统计 / 标记已读 / 类型过滤 | `hose-use message list [--all]`, `hose-use message count`, `hose-use message read` | [references/message.md](references/message.md) |
| 跨自建应用工作流聚合检索 | `hose-use workflow list`, `hose-use platform list` | [references/workflow.md](references/workflow.md) |
| 应用管理 (桌面端工作台开通的用车/套件/制度/自建前台应用) | `hose-use app list [--keyword]`, `hose-use app get <应用>` | [references/workflow.md](references/workflow.md) |
| 自建应用与数据模型 (开放平台业务对象/字段定义/底层记录) | `hose-use platform list`, `hose-use platform entities <应用>` | [references/workflow.md](references/workflow.md) |
| 自建应用单条记录操作 (详情/停启用/字段编辑/台账重算) | `hose-use platform record <get|toggle|edit|recompute>` | [references/workflow.md](references/workflow.md) |
| 跨自建应用工作流聚合检索与节点扫描 | `hose-use workflow list`, `hose-use workflow find --task=code-js2` | [references/workflow.md](references/workflow.md) |
| 桌面端全站主导航与一级模块树 | `hose-use menu list`, `hose-use menu tree` | [references/workflow.md](references/workflow.md) |
| 模糊搜索已保存的企业与员工信息 | `hose-use corps search <关键词>` | [references/auth.md](references/auth.md) |
| 特定任务节点扫描 (如脚本/Webhook) | `hose-use workflow find --task=code-js2` | [references/workflow.md](references/workflow.md) |
| 工作流详情与开通切换 | `hose-use workflow get`, `hose-use workflow toggle` | [references/workflow.md](references/workflow.md) |
| 工作流详情、节点草稿修改、草稿保存、版本历史、运行日志、发布与开通切换 | `hose-use workflow get`, `hose-use workflow patch`, `hose-use workflow save`, `hose-use workflow publish`, `hose-use workflow history`, `hose-use workflow logs`, `hose-use workflow toggle` | [references/workflow.md](references/workflow.md) |
| 工作流节点树、代码依赖与静态诊断 | `hose-use workflow analyze <pipelineId>` | [references/workflow.md](references/workflow.md) |
| 工作流错误管道扫描与本地去重提醒 | `hose-use workflow check [--fail-on-alert]` | [references/workflow.md](references/workflow.md) |
| 企业 OpenAPI 接入密钥(默认脱敏) | `hose-use keys [--json]`, `hose-use openapi keys`, `hose-use store keys` | [references/store.md](references/store.md) |
| 企业已购应用 / 应用商店探查 | `hose-use store list / search / get` | [references/store.md](references/store.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) |
@@ -109,6 +120,14 @@ 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="交通费" --dry-run # 先预览新建
hose-use feetype create --name="市内打车" --parent="交通费" --yes # 确认新建
hose-use feetype update 市内打车 --desc="滴滴企业版" --yes # 修改费用类型属性
hose-use feetype disable 市内打车 --yes # 停用费用类型 (软删除)
hose-use feetype enable 市内打车 --yes # 重新启用费用类型
hose-use feetype move 市内打车 --parent="差旅费用" --yes # 移动费用类型到新父级
hose-use role list # 查看企业角色定义
hose-use role groups # 查看角色组及其角色
hose-use role members 财务主管 # 查看指定角色成员
@@ -122,14 +141,36 @@ hose-use message list --all # 合并查看已读和
hose-use message count # 查看未读数量
hose-use message read <messageId> # 标记单条消息已读
# 5. 自建应用与工作流
hose-use platform list # 查看自建应用列表
hose-use workflow list # 聚合扫描全部应用下的工作流
# 5. 应用管理、自建应用与工作流
hose-use app list # 查看应用管理列表(桌面端工作台业务应用集成)
hose-use app get 用车补贴 # 查看指定应用管理的配置与 Web 路由
hose-use platform list # 列出企业可见的自建应用平台
hose-use platform entities 新转转集团 # 查看自建应用下的业务对象与字段
hose-use platform records 新转转集团 合同 # 查看业务对象的底层数据记录
hose-use platform record get 新转转集团 合同 <记录ID> # 获取单条记录完整字段与属性详情
hose-use platform record toggle 新转转集团 合同 <记录ID> --dry-run # 预览状态切换
hose-use platform record edit 新转转集团 合同 <记录ID> --data='{"name":"新名称"}' --yes # 编辑记录字段
hose-use platform record recompute 新转转集团 合同 <记录ID> --yes # 重新计算记录关联的全部台账
hose-use menu list # 查看桌面端主框架一级导航树
hose-use workflow list # 聚合扫描全部自建应用下的工作流
hose-use workflow find --task=code-js2 # 查找部署了代码节点的工作流
hose-use workflow get wf_01k83y... # 查看指定工作流节点拓扑
hose-use workflow analyze wf_01k83y... --json # 输出节点树、引用依赖与静态诊断
hose-use workflow save wf_01k83y... --file=workflow.json --yes # 按完整快照保存草稿并做版本保护
hose-use workflow patch wf_01k83y... --file=workflow.json --path=tasks.0.code --value='return 2;' --output=patched.json --yes
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... --yes # 将保存后的工作流发布/启用
# 6. 服务与守护进程
# 6. OpenAPI 密钥与应用中心
hose-use keys --json # 查询当前企业密钥,appSecurity 默认脱敏
hose-use keys --reveal # 仅在用户明确授权时查看完整 appSecurity
hose-use store list --all # 查看当前企业已购/已开通应用
hose-use store search "开放接口" # 搜索应用商店
hose-use store get <应用ID> # 查看应用详情(ID 可带或不带前导 $)
# 7. 服务与守护进程
hose-use http --port=8888 # 启动前台 HTTP 服务与交互式文档
hose-use service start # 后台启动常驻守护进程服务
hose-use service status # 查看常驻守护进程运行状态与端点
@@ -148,4 +189,6 @@ hose-use service stop # 停止后台常驻守
- `--full`:全量输出大报文(绕过 200KB 体积防爆拦截)
- `--stateless`:单次命令强制以无状态模式执行
- `--stateful`:单次命令强制以有状态模式执行
- `--dry-run`:预览写操作,不发起写请求或落盘
- `--yes`, `--confirm`:显式确认执行写操作
- `--help, -h`:查看命令帮助与参数说明
+2 -2
View File
@@ -5,12 +5,12 @@ auth:
type: "none"
tools:
- name: "hose_cli"
description: "执行合思/易快报 hose-use CLI 命令。详细命令语法请参考 hose-use skill 文档。"
description: "执行合思/易快报 hose-use CLI 命令,包括 keys 凭证查询与 store 应用探查。详细命令语法请参考 hose-use skill 文档。"
parameters:
type: "object"
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"
+8
View File
@@ -87,6 +87,14 @@ hose-use corps list
hose-use corps list --json
```
### 模糊搜索企业 (`corps search` / `corps find`)
```bash
# 支持根据企业名称、企业 ID、员工工号、员工姓名或所属账号模糊搜索
hose-use corps search 某企业
hose-use corps search 17718556446
hose-use corps search 周某某 --json
```
### 切换当前活跃企业
```bash
hose-use corps switch uzU7pcWfScck00
+33
View File
@@ -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 # 移至企业顶级根节点
```
+36
View File
@@ -0,0 +1,36 @@
# OpenAPI 密钥与应用中心
本专卷覆盖 v0.8.1 引入的企业 OpenAPI 接入密钥查询,以及企业已购应用和合思应用商店探查。执行前先确认目标企业;可用 `hose-use context --json` 或 `hose-use corps list`,跨企业任务优先显式传入 `--corp=<id>`。
## 密钥查询 (`keys`)
```bash
hose-use keys # 当前企业的密钥列表,appSecurity 默认脱敏
hose-use keys --json # 结构化结果,appSecurity 仍默认脱敏
hose-use openapi keys # 同一能力的 OpenAPI 别名
hose-use store keys # 同一能力的 store 别名
hose-use keys --reveal # 用户明确要求时才显示完整 appSecurity
```
`keys` 返回密钥备注、`appKey`、状态和创建时间。`appSecurity` 是接入密码:默认输出会遮罩;`--reveal`/`-r`/`--plain` 才请求完整值。
安全边界:
- 没有用户明确授权时,不要使用 `--reveal`,也不要从结果中推断或复述明文密钥。
- 不要把明文密钥放进聊天、日志、命令历史、提交内容或共享目录;不要使用 `--reveal -o <path>`。
- 只需判断密钥是否存在、状态或匹配某个 `appKey` 时,使用默认脱敏输出即可。
- 需要交给脚本处理时优先使用不带 `--reveal` 的 `--json`;若确实必须取得明文,先确认接收方和落盘位置,再尽量短暂使用并及时清理。
## 应用中心与应用商店 (`store`)
```bash
hose-use store list # 当前企业已购/已开通应用
hose-use store list --all # 请求完整已购应用列表
hose-use store list <关键词> # 按名称或简介筛选已购应用
hose-use store search <关键词> # 搜索应用商店商品
hose-use store get <应用ID> # 查看商品详情;ID 可带或不带前导 $
```
`store list` 展示应用 ID、名称、开通状态、有效期限、配置支持和绑定能力;`store search` 返回商店结果总数及当前结果;`store get` 用于查看指定应用的详情。上述命令均支持 `--json`,适合 Agent 解析。
若用户说“查 OpenAPI 密钥”,路由到 `keys`;若用户说“看企业买了什么应用/查应用市场”,路由到 `store list` 或 `store search`;若已有应用 ID,再用 `store get` 下钻。`openapi keys` 与 `store keys` 只作为 `keys` 的兼容别名。
+129 -18
View File
@@ -1,28 +1,78 @@
# 工作流与自建应用指南 (Workflow & Platform Guide)
# 应用管理、自建应用与工作流指南 (App, Platform & Workflow Guide)
本参考专卷详细说明合思自建应用(EASO 开放平台)的工作流跨域扫描、任务节点聚合检索与自动化开通。
本参考专卷详细说明合思桌面端【应用管理】、企业后台【自建应用】(DataLink 数据建模与底层记录)以及任务节点工作流(Workflow)的查询与使用。
> **核心概念辨析(严禁混淆)**:
> - **【应用管理】(唯一命令:`hose-use app`)**:对应合思桌面端顶层一级导航【应用管理】。聚合了企业为员工开通的**全部前台业务落地应用**,既包括用车补贴、用车制度、E商卡等官方套件与制度,也包括新转转集团、差旅申请等挂载了视图的自建应用前台入口。
> - **【自建应用】(唯一命令:`hose-use platform` / `datalink`)**:对应企业后台【应用中心 -> 自建应用】(开放平台/PaaS)。负责业务对象建模(entities)、字段定义(schema)、权限快照与底层业务记录(records)。**切勿将自建应用称为“应用管理”**。
> - **【工作流】(唯一命令:`hose-use workflow`)**:自建应用下的任务流水线、拓扑节点(如自定义 JS 脚本 `code-js2`、Webhook 通知等)。
---
## 1. 自建应用管理 (`platform`)
## 1. 应用管理 (`app`)
合思企业支持创建多个自建应用,每个应用承载独立的业务流程与工作流。
查看员工工作台开通的业务应用列表与详情:
```bash
# 列出当前企业下全部已开通的自建应用
hose-use platform list
hose-use platform list --json
```
# 列出工作台开通的全部业务应用(用车、制度、模板、自建前台等)
hose-use app list
hose-use app list --keyword="差旅"
hose-use app list --json
**输出关键字段**:
- `appId`:应用全局唯一标识
- `appName`:应用中文名称
- `status`:应用运行状态(ENABLE / DISABLE)
- `createdAt` / `updatedAt`:创建与最后更新时间
# 查看某个应用的详情与配置
hose-use app get 用车补贴
hose-use app get ID01RKbEvQsWbd
```
---
## 2. 跨应用工作流聚合检索 (`workflow list`)
## 2. 自建应用与数据模型 (`platform` / `datalink`)
合思企业支持创建多个自建应用,每个自建应用可承载多个业务对象、字段模型与业务数据记录:
```bash
# 列出当前企业下全部已开通的自建应用平台
hose-use platform list
hose-use platform list --json
# 查看指定自建应用包含的业务对象清单
hose-use platform entities 新转转集团
# 查看业务对象的完整字段定义(schema)
hose-use platform schema 新转转集团 合同
hose-use platform schema 新转转集团 合同 --keyword="金额"
# 检索业务对象的底层真实数据记录
hose-use platform records 新转转集团 合同 --limit=5
hose-use platform records 新转转集团 合同 --keyword="技术服务" --fields "合同编号,金额,经办人" --json
```
### 2.1 业务对象记录操作 (`platform record`)
支持对业务对象单条记录进行精准详情查看、停用/启用状态翻转、表单字段更新以及台账重新计算:
```bash
# 1. 查看单条记录详情 (包含基本信息、实体字段、关联台账与可见范围)
hose-use platform record get 新转转集团 合同 ID01TqE4yUG6hF
hose-use platform record get 新转转集团 合同 ID01TqE4yUG6hF --json
# 2. 切换记录停用/启用状态 (默认自动翻转,支持 --state 显式指定)
hose-use platform record toggle 新转转集团 合同 ID01TqE4yUG6hF
hose-use platform record toggle 新转转集团 合同 ID01TqE4yUG6hF --state=false # 停用
hose-use platform record toggle 新转转集团 合同 ID01TqE4yUG6hF --state=true # 启用
# 3. 编辑更新记录字段 (传入 JSON 字典或 --data)
hose-use platform record edit 新转转集团 合同 ID01TqE4yUG6hF --data='{"name":"新名称","项目内容":"技术支持"}'
hose-use platform record edit 新转转集团 合同 ID01TqE4yUG6hF '{"name":"新名称"}'
# 4. 重新计算记录关联的全部台账
hose-use platform record recompute 新转转集团 合同 ID01TqE4yUG6hF
```
---
## 3. 跨应用工作流聚合检索 (`workflow list`)
合思官方后台一次只能查看单个自建应用的工作流。`hose-use` 实现了跨应用并发聚合扫描:
@@ -36,7 +86,7 @@ hose-use workflow list --app-id=app_01j72x...
---
## 3. 工作流任务节点精准扫描 (`workflow find`)
## 4. 工作流任务节点精准扫描 (`workflow find`)
用于快速定位企业中部署了特定逻辑节点(如自定义 JS 脚本、飞书推送、钉钉同步等)的工作流:
@@ -53,7 +103,7 @@ hose-use workflow find --keyword="自动审批"
---
## 4. 工作流详情查询 (`workflow get`)
## 5. 工作流详情查询 (`workflow get`)
获取工作流的完整节点拓扑、参数配置与表达式定义:
@@ -64,7 +114,7 @@ hose-use workflow get wf_01k83y... --json -o /tmp/workflow_detail.json
---
## 5. 工作流启用与关闭 (`workflow toggle`)
## 6. 工作流启用与关闭 (`workflow toggle`)
```bash
# 激活/启用指定工作流
@@ -74,10 +124,71 @@ hose-use workflow toggle wf_01k83y... --enable
hose-use workflow toggle wf_01k83y... --disable
```
## 6. 工作流静态分析 (`workflow analyze`)
## 7. 工作流静态分析 (`workflow analyze`)
从应用中心的具体自建应用进入工作流详情后,CLI 可以读取同一份详情并生成递归节点树、代码表达式引用依赖和明显配置诊断;该命令只读,不执行工作流:
```bash
hose-use workflow analyze wf_01k83y... --json
```
## 8. 工作流草稿保存 (`workflow save`)
Web 端“保存更新”是对完整 pipeline 的 PUT,而不是单节点 PATCH。推荐先导出详情,再修改 JSON,最后按版本保护保存:
```bash
hose-use workflow get <pipelineId> --json -o workflow.json
# 修改 workflow.json 中的 tasks / inputs / $snapshot 等字段
hose-use workflow save <pipelineId> --file=workflow.json
```
命令会先重新读取远端版本;若 `version` 或 `tasksVersion` 已变化会拒绝覆盖。确认需要强制覆盖时显式使用 `--force-write`。
## 9. 本地节点草稿修改 (`workflow patch`)
网页编辑器最终提交的是完整 pipeline,因此节点修改先在完整 JSON 草稿上完成,再交给 `workflow save` 做版本保护和服务端持久化:
```bash
hose-use workflow patch <pipelineId> \\
--file=workflow.json \\
--path=tasks.1.form.title \\
--value="新的标题" \\
--output=workflow.patched.json
```
数组也可以使用 `tasks[1].form.title`。需要写入数字、布尔值或对象时加 `--value-json`;使用 `--in-place` 才会覆盖输入文件。该命令只修改本地草稿,不直接触发远端写入。
## 10. 工作流版本历史 (`workflow history`)
服务端每次完整保存都会生成一个版本快照,可用以下命令读取审计历史:
```bash
hose-use workflow history <pipelineId> --json
```
## 11. 运行日志与错误管道提醒
查询单个工作流的运行日志:
```bash
hose-use workflow logs <pipelineId> --state=FAILED --json
```
扫描企业内工作流列表中的 `errorCount`,并把已提醒的错误计数保存在本地状态文件;同一错误计数不会重复提醒,错误计数增加时才产生新提醒:
```bash
hose-use workflow check --json
hose-use workflow check --json --fail-on-alert
```
默认状态文件为 `~/.config/hose-use/workflow-alerts-<corp>.json`,可用 `--state-file` 指定。`--fail-on-alert` 适合被常驻服务或外部调度器检测;它只改变退出码,不自动向外部人员发送消息。
## 12. 发布工作流 (`workflow publish`)
网页端发布动作对应 Piper 的状态接口:`PUT /api/easo/pipelines/state/{pipelineId}?state=1`。CLI 提供同等入口:
```bash
hose-use workflow publish <pipelineId>
```
建议先执行 `workflow save`,确认保存成功后再执行 `workflow publish`;发布只切换启用状态,不替代完整配置保存。
+10
View File
@@ -25,6 +25,16 @@ describe("CLI - hose-aipro 审批流与网关阻拦全链路测试", () => {
delete process.env.HOSE_APPROVAL_DB;
});
test("version/help --json only emit machine-readable stdout", async () => {
const version = await runAiProCli(["version", "--json"]);
const help = await runAiProCli(["help", "--json"]);
expect(JSON.parse(version.stdout)).toEqual({ name: "hose-aipro", version: expect.any(String) });
expect(JSON.parse(help.stdout).help).toContain("hose-aipro");
expect(version.stderr).toBe("");
expect(help.stderr).toBe("");
});
test("完整闭环:bind 挂载 ➔ review 证据核验 ➔ decide 网关阻拦与裁决 ➔ logs 审计追溯", async () => {
const db = getApprovalDatabase(":memory:");
const repo = new ApprovalRepository(db);
+22 -5
View File
@@ -53,6 +53,7 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string;
}
const command = (positional[0] || "help").toLowerCase();
const jsonMode = booleanOption(parsed.options, ["json", "j"]);
const targetSn = positional[1] || stringOption(parsed.options, ["code", "sn", "id", "target"]);
const args = positional.slice(1);
const corpId = corp?.corpId || corp?.id;
@@ -73,6 +74,16 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string;
};
try {
if (command === "version" || command === "v" || booleanOption(parsed.options, ["version", "v"])) {
return {
stdout: jsonMode
? printJson({ name: "hose-aipro", version: VERSION }) + "\n"
: `hose-aipro v${VERSION}\n`,
stderr: "",
exitCode: 0,
};
}
switch (command) {
// ── 0. 运行时上下文与身份诊断 (status / whoami / context / info) ────────
case "status":
@@ -1136,7 +1147,11 @@ ${corpBanner}
7. 全流程监控日志流水查看:
hose-aipro logs [单号] # 追溯所有 AI PRO 操作流水
`;
return { stdout: helpText.trim() + "\n", stderr: "", exitCode: 0 };
return {
stdout: jsonMode ? printJson({ help: helpText.trim() }) + "\n" : helpText.trim() + "\n",
stderr: "",
exitCode: 0,
};
}
}
} catch (err: any) {
@@ -1151,8 +1166,8 @@ ${corpBanner}
summary: err.message.replace(/\n+/g, " "),
});
return {
stdout: "",
stderr: `\n${err.message}\n`,
stdout: jsonMode ? printJson({ error: true, message: err.message, exitCode: 1 }) + "\n" : "",
stderr: jsonMode ? "" : `\n${err.message}\n`,
exitCode: 1,
};
}
@@ -1167,8 +1182,10 @@ ${corpBanner}
});
return {
stdout: "",
stderr: `[AI PRO 错误] ${err?.message || err}\n`,
stdout: jsonMode
? printJson({ error: true, message: String(err?.message || err), exitCode: 1 }) + "\n"
: "",
stderr: jsonMode ? "" : `[AI PRO 错误] ${err?.message || err}\n`,
exitCode: 1,
};
}
+183
View File
@@ -0,0 +1,183 @@
import { describe, it, expect, spyOn } from "bun:test";
import { handleAppCommand } from "./app.js";
import * as menuTools from "../../domains/menu/tools.js";
import type { CliRuntime } from "../types.js";
import type { CorpConfig } from "../../core/config/types.js";
describe("cli/commands/app > handleAppCommand", () => {
const dummyRuntimeNoCorp: CliRuntime = {
corpContext: {
listCorps: () => [],
getCurrent: () => null,
switchCorp: () => false,
resolve: () => null,
} as any,
selectedCorp: null,
jsonMode: false,
};
const mockCorp: CorpConfig = {
id: "corp123",
name: "转转二手交易网",
source: "account",
baseUrl: "https://app.ekuaibao.com",
credentials: {
accessToken: "mock-token",
corpId: "corp123",
staffId: "mock-staff",
},
};
const dummyRuntimeWithCorp: CliRuntime = {
corpContext: {
listCorps: () => [mockCorp],
getCurrent: () => mockCorp,
switchCorp: () => true,
resolve: () => mockCorp,
} as any,
selectedCorp: mockCorp,
jsonMode: false,
};
it("fails with exitCode 1 when no corp is selected", async () => {
const res = await handleAppCommand(
{
area: "app",
action: "list",
args: [],
options: {},
raw: ["app", "list"],
},
dummyRuntimeNoCorp
);
expect(res.exitCode).toBe(1);
expect(res.stderr).toContain("未选中企业");
});
it("lists workbench apps in table format", async () => {
const mockApps = [
{
id: "SCGY:corp123",
name: "用车补贴",
code: "dataLinkItem",
href: "/third-party-item/SCGY:corp123",
type: "MENU",
},
{
id: "ID01PIqCA1Di0v",
name: "用车制度",
code: "dataLinkItem",
href: "/third-party-item/ID01PIqCA1Di0v",
type: "REGULATION",
},
];
const spy = spyOn(menuTools, "fetchWorkbenchAppsList").mockResolvedValue(mockApps as any);
const res = await handleAppCommand(
{
area: "app",
action: "list",
args: [],
options: {},
raw: ["app", "list"],
},
dummyRuntimeWithCorp
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("工作台应用管理列表");
expect(res.stdout).toContain("用车补贴");
expect(res.stdout).toContain("用车制度");
expect(res.stdout).toContain("用车/商旅套件");
expect(res.stdout).toContain("制度与规约");
spy.mockRestore();
});
it("filters workbench apps with --keyword", async () => {
const mockApps = [
{
id: "SCGY:corp123",
name: "用车补贴",
code: "dataLinkItem",
href: "/third-party-item/SCGY:corp123",
},
{
id: "ID01PIqCA1Di0v",
name: "差旅申请",
code: "dataLinkItem",
href: "/third-party-item/ID01PIqCA1Di0v",
},
];
const spy = spyOn(menuTools, "fetchWorkbenchAppsList").mockResolvedValue(mockApps as any);
const res = await handleAppCommand(
{
area: "app",
action: "list",
args: [],
options: { keyword: "补贴" },
raw: ["app", "list", "--keyword", "补贴"],
},
dummyRuntimeWithCorp
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("用车补贴");
expect(res.stdout).not.toContain("差旅申请");
spy.mockRestore();
});
it("supports --json output for app list", async () => {
const mockApps = [
{
id: "SCGY:corp123",
name: "用车补贴",
code: "dataLinkItem",
href: "/third-party-item/SCGY:corp123",
},
];
const spy = spyOn(menuTools, "fetchWorkbenchAppsList").mockResolvedValue(mockApps as any);
const jsonRuntime = { ...dummyRuntimeWithCorp, jsonMode: true };
const res = await handleAppCommand(
{
area: "app",
action: "list",
args: [],
options: { json: true },
raw: ["app", "list", "--json"],
},
jsonRuntime
);
expect(res.exitCode).toBe(0);
const parsed = JSON.parse(res.stdout);
expect(parsed.total).toBe(1);
expect(parsed.apps[0].id).toBe("SCGY:corp123");
expect(parsed.apps[0].name).toBe("用车补贴");
spy.mockRestore();
});
it("returns error for unknown subcommand", async () => {
const res = await handleAppCommand(
{
area: "app",
action: "unknownAction",
args: [],
options: {},
raw: ["app", "unknownAction"],
},
dummyRuntimeWithCorp
);
expect(res.exitCode).toBe(1);
expect(res.stderr).toContain("未知 app 子命令");
});
});
+149
View File
@@ -0,0 +1,149 @@
import { fetchWorkbenchAppsList } from "../../domains/menu/tools.js";
import { getPlatform } from "../../domains/datalink/api.js";
import { createClientsForCorp } from "../helpers.js";
import { stringOption, booleanOption } from "../parser.js";
import { printJson, printTable } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
function inferCategory(app: { id: string; name: string; type?: string | null }): string {
if (app.id.startsWith("SCGY:") || app.type === "PRIVATE_CAR") return "用车/商旅套件";
if (app.type === "REGULATION") return "制度与规约";
if (app.type === "VCM") return "商旅卡与金融";
if (app.name.includes("[模板]") || app.name.includes("模板")) return "预置模板";
return "自建业务应用";
}
export async function handleAppCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
if (!runtime.selectedCorp) {
return {
stdout: "",
stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n",
exitCode: 1,
};
}
const action = parsed.action || "list";
switch (action) {
case "list":
case "ls":
case "apps":
case "workbench": {
const keyword = stringOption(parsed.options, ["keyword", "k", "q", "query"])?.toLowerCase();
const apps = await fetchWorkbenchAppsList(runtime.selectedCorp);
const filtered = keyword
? apps.filter((app) =>
[app.id, app.name, app.code, app.href]
.filter((val): val is string => Boolean(val))
.some((val) => val.toLowerCase().includes(keyword))
)
: apps;
if (runtime.jsonMode) {
return {
stdout: printJson(
{
corpId: runtime.selectedCorp.credentials.corpId,
corpName: runtime.selectedCorp.name,
total: apps.length,
count: filtered.length,
keyword: keyword ?? null,
apps: filtered,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
if (filtered.length === 0) {
const msg = keyword
? `企业 [${runtime.selectedCorp.name}] 下未找到匹配 "${keyword}" 的工作台应用\n`
: `企业 [${runtime.selectedCorp.name}] 下暂无工作台应用配置\n`;
return { stdout: msg, stderr: "", exitCode: 0 };
}
const headers = ["#", "应用 ID", "应用名称", "应用分类", "功能代码", "Web 直达路由"];
const rows = filtered.map((app, i) => [
i + 1,
app.id,
app.name,
inferCategory(app),
app.code || "dataLinkItem",
app.href,
]);
const title = `====== [${runtime.selectedCorp.name}] 工作台应用管理列表 (${filtered.length} 个应用) ======\n`;
return {
stdout: title + printTable(headers, rows) + "\n",
stderr: "",
exitCode: 0,
};
}
case "get":
case "show": {
const target = parsed.args[0] || stringOption(parsed.options, ["id", "name", "app"]);
if (!target) {
return {
stdout: "",
stderr: "请提供应用 ID 或名称: hose-use app get <应用 ID|名称>\n",
exitCode: 1,
};
}
const apps = await fetchWorkbenchAppsList(runtime.selectedCorp);
const matched = apps.find(
(a) =>
a.id.toLowerCase() === target.toLowerCase() ||
a.name.toLowerCase().includes(target.toLowerCase())
);
const appId = matched ? matched.id : target;
const appName = matched ? matched.name : target;
const clients = await createClientsForCorp(runtime.selectedCorp);
const corpId = runtime.selectedCorp.credentials.corpId;
try {
const detail = await getPlatform(clients.ekbClient, corpId, appId);
if (runtime.jsonMode) {
return { stdout: printJson(detail, runtime.outputOptions), stderr: "", exitCode: 0 };
}
const infoRows = [
["应用 ID", detail.id],
["应用名称", detail.name],
["应用分类", inferCategory(detail)],
["启用状态", detail.active ? "🟢 已启用" : "⚪ 未启用"],
["Web 路由", matched?.href || `/third-party-item/${detail.id}`],
["管理员数", detail.adminIds.length],
["可见人员数", detail.staffIds.length],
["可见角色数", detail.roleIds.length],
["可见部门数", detail.departmentIds.length],
];
const text = `====== 工作台应用详情: ${appName} ======\n${printTable(["属性", "信息"], infoRows)}\n`;
return { stdout: text, stderr: "", exitCode: 0 };
} catch (err) {
return {
stdout: "",
stderr: `获取应用详情失败: ${err instanceof Error ? err.message : String(err)}\n`,
exitCode: 1,
};
}
}
default:
return {
stdout: "",
stderr: `未知 app 子命令: ${action}。支持: list, get\n用法: hose-use app list [--keyword <关键词>]\n`,
exitCode: 1,
};
}
}
+67
View File
@@ -0,0 +1,67 @@
import { describe, it, expect } from "bun:test";
import { handleAuthCommand } from "./auth.js";
import type { CliRuntime } from "../types.js";
describe("cli/commands/auth > aliases and subcommands", () => {
const dummyRuntime: CliRuntime = {
corpContext: {
listCorps: () => [],
getCurrent: () => null,
switchCorp: () => false,
resolve: () => null,
} as any,
selectedCorp: null,
jsonMode: false,
};
it("maps auth list to handleAccounts smoothly", async () => {
const res = await handleAuthCommand(
{
area: "auth",
action: "list",
args: [],
options: {},
raw: ["auth", "list"],
},
dummyRuntime
);
expect(res.exitCode).toBe(0);
// 应该输出已保存账号表格或无账号提示
expect(res.stdout).toMatch(/(已保存账号列表|暂无保存的账号)/);
});
it("supports auth accounts with --json mode", async () => {
const jsonRuntime = { ...dummyRuntime, jsonMode: true };
const res = await handleAuthCommand(
{
area: "auth",
action: "list",
args: [],
options: { json: true },
raw: ["auth", "list", "--json"],
},
jsonRuntime
);
expect(res.exitCode).toBe(0);
const data = JSON.parse(res.stdout);
expect(data).toHaveProperty("accounts");
});
it("handles auth status / current aliases without crash", async () => {
const res = await handleAuthCommand(
{
area: "auth",
action: "current",
args: [],
options: {},
raw: ["auth", "current"],
},
dummyRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("当前登录与企业状态");
});
});
+38
View File
@@ -18,6 +18,7 @@ import { createEkbClient } from "../../core/auth/ekb.js";
import { stringOption, booleanOption } from "../parser.js";
import { printJson, printKeyValue, printTable, formatSourceLabel, formatExpiresAt } from "../printer.js";
import { prompt } from "../helpers.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
export async function handleAuthCommand(
@@ -31,16 +32,26 @@ export async function handleAuthCommand(
return handleLogin(parsed, runtime);
case "status":
case "whoami":
case "current":
return handleStatus(parsed, runtime);
case "refresh":
case "renew":
return handleRefresh(parsed, runtime);
case "import":
case "add":
return handleImport(parsed, runtime);
case "add-link":
case "link":
case "import-link":
return handleAddLink(parsed, runtime);
case "accounts":
case "list":
case "account":
case "accs":
return handleAccounts(parsed, runtime);
case "switch-account":
case "switch":
case "use-account":
return handleSwitchAccount(parsed, runtime);
default:
return {
@@ -58,6 +69,14 @@ async function handleLogin(parsed: CliParsedArgs, runtime: CliRuntime): Promise<
const isSync = booleanOption(parsed.options, ["sync"]);
const isInteractive = booleanOption(parsed.options, ["interactive", "i"]) || (!phone && !password && !isSms && !isSync);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "登录并保存企业凭证", phone || (isSync ? "浏览器会话" : "交互式登录"), {
mode: isSync ? "browser-sync" : isSms ? "sms" : "password",
saveAll: true,
});
}
requireMutationConfirmation(parsed, runtime, "登录并保存企业凭证", `hose-use auth login${phone ? ` --phone=${phone}` : ""} --yes`);
// 1. 浏览器同步
if (isSync) {
const res = await fullBrowserSyncLogin({ saveAll: true });
@@ -220,6 +239,10 @@ async function handleStatus(parsed: CliParsedArgs, runtime: CliRuntime): Promise
async function handleRefresh(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const accountId = stringOption(parsed.options, ["account", "a"]);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "刷新账号下企业凭证", accountId || "当前账号", { saveAll: true });
}
requireMutationConfirmation(parsed, runtime, "刷新账号下企业凭证", `hose-use auth refresh${accountId ? ` --account=${accountId}` : ""} --yes`);
const res = await refreshAccountCorporations(accountId, { saveAll: true });
if (runtime.jsonMode) {
@@ -243,6 +266,16 @@ async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise
const ttl = stringOption(parsed.options, ["ttl"]);
const expires = stringOption(parsed.options, ["expires", "days"]);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "导入并保存企业凭证", corpId || "待解析企业", {
source: raw ? "captured-input" : "manual-input",
overwrite,
ttl: ttl || null,
expires: expires || null,
});
}
requireMutationConfirmation(parsed, runtime, "导入并保存企业凭证", `hose-use auth ${parsed.action || "import"} --yes`);
if (!raw && !accessToken && process.stdin.isTTY) {
raw = await prompt("请粘贴抓包文本 / cURL 命令行 / 协助免密 URL (直接回车则手动逐项输入): ");
}
@@ -360,6 +393,11 @@ async function handleSwitchAccount(parsed: CliParsedArgs, runtime: CliRuntime):
return { stdout: "", stderr: "用法: hose-use auth switch-account <accountId>\n", exitCode: 1 };
}
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "切换当前活跃账号", target, { activeAccountId: target });
}
requireMutationConfirmation(parsed, runtime, "切换当前活跃账号", `hose-use auth switch-account ${target} --yes`);
const success = setActiveAccount(target);
if (!success) {
return { stdout: "", stderr: `未找到账号: ${target}\n`, exitCode: 1 };
+41 -23
View File
@@ -20,6 +20,7 @@ import {
commentBill,
resolveBillStaffIds,
} from "../../domains/bill/tools.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
export async function handleBillCommand(
parsed: CliParsedArgs,
@@ -32,15 +33,24 @@ export async function handleBillCommand(
);
}
const client = await createEkbClient(corp);
const action = parsed.action?.toLowerCase();
const corpId = corp.corpId || corp.id;
let client: Awaited<ReturnType<typeof createEkbClient>> | undefined;
const getClient = async () => {
client ??= await createEkbClient(corp);
return client;
};
const actionTarget = () => parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
const requireWriteConfirmation = async () => {
if (booleanOption(parsed.options, ["yes", "y", "confirm", "force-write"])) return;
if (isDryRun(parsed, runtime) || booleanOption(parsed.options, ["yes", "y", "confirm", "force-write"])) return;
if (!process.stdin.isTTY || !process.stdout.isTTY) {
throw new Error("审批动作会改变单据状态。请显式添加 --yes(或 --confirm)后重试。");
requireMutationConfirmation(
parsed,
runtime,
"单据审批动作",
`hose-use bill ${action || "approve"} ${actionTarget() || "<单号|ID>"} --yes`
);
}
const { prompt } = await import("../helpers.js");
const answer = await prompt("该操作会改变单据状态,确认继续?输入 yes 继续: ");
@@ -68,7 +78,7 @@ export async function handleBillCommand(
});
const resolveApproverIds = async (values: string[] | undefined): Promise<string[]> => {
if (!values?.length) throw new Error("请通过 --approver-id、--staff 或 --to 指定员工 ID、工号或姓名");
return resolveBillStaffIds(client, corpId, values);
return resolveBillStaffIds(await getClient(), corpId, values);
};
switch (action) {
@@ -77,7 +87,8 @@ export async function handleBillCommand(
await requireWriteConfirmation();
const target = actionTarget();
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill approve <单号|ID> --yes");
const result = await approveBill(client, corpId, target, actionOptions());
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "同意单据审批", target, actionOptions());
const result = await approveBill(await getClient(), corpId, target, actionOptions());
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
return { stdout: `审批同意成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 };
}
@@ -89,7 +100,8 @@ export async function handleBillCommand(
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill reject <单号|ID> --comment <原因> --yes");
const options = actionOptions();
if (!options.comment?.trim()) throw new Error("驳回原因不能为空,请通过 --comment 提供原因");
const result = await rejectBill(client, corpId, target, options);
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "驳回单据审批", target, options);
const result = await rejectBill(await getClient(), corpId, target, options);
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
return { stdout: `驳回成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 };
}
@@ -99,8 +111,10 @@ export async function handleBillCommand(
await requireWriteConfirmation();
const target = actionTarget();
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill transfer <单号|ID> --approver-id <员工ID> --yes");
const options = { ...actionOptions(), approverIds: await resolveApproverIds(actionOptions().approverIds) };
const result = await transferBill(client, corpId, target, options);
const rawOptions = actionOptions();
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "转交单据审批", target, rawOptions);
const options = { ...rawOptions, approverIds: await resolveApproverIds(rawOptions.approverIds) };
const result = await transferBill(await getClient(), corpId, target, options);
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
return { stdout: `转交审批成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 };
}
@@ -112,8 +126,10 @@ export async function handleBillCommand(
await requireWriteConfirmation();
const target = actionTarget();
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill add-node <单号|ID> --approver-id <员工ID> --yes");
const options = { ...actionOptions(), approverIds: await resolveApproverIds(actionOptions().approverIds) };
const result = await addNodeBill(client, corpId, target, options);
const rawOptions = actionOptions();
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "单据加签", target, rawOptions);
const options = { ...rawOptions, approverIds: await resolveApproverIds(rawOptions.approverIds) };
const result = await addNodeBill(await getClient(), corpId, target, options);
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
return { stdout: `加签审批成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 };
}
@@ -123,7 +139,9 @@ export async function handleBillCommand(
await requireWriteConfirmation();
const target = actionTarget();
if (!target) throw new Error("请提供单号或单据 ID: hose-use bill comment <单号|ID> --comment <内容> --yes");
const result = await commentBill(client, corpId, target, actionOptions());
const options = actionOptions();
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "添加单据评论", target, options);
const result = await commentBill(await getClient(), corpId, target, options);
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
return { stdout: `单据评论成功\n单号: ${result.billCode || target}\n流程 ID: ${result.flowId}\n`, stderr: "", exitCode: 0 };
}
@@ -137,7 +155,7 @@ export async function handleBillCommand(
const state = stringOption(parsed.options, ["state", "s"]);
const count = numberOption(parsed.options, ["count", "limit", "n"], 20);
const result = await searchAndFormatBills(client, corpId, {
const result = await searchAndFormatBills(await getClient(), corpId, {
code,
keyword,
stage,
@@ -192,7 +210,7 @@ export async function handleBillCommand(
throw new Error("请提供要查询的单号或单据 ID: hose-use bill get <单号|ID>");
}
const bills = await getBillByCodeOrId(client, corpId, target);
const bills = await getBillByCodeOrId(await getClient(), corpId, target);
if (bills.length === 0) {
if (runtime.jsonMode) {
@@ -211,7 +229,7 @@ export async function handleBillCommand(
const withRisk = booleanOption(parsed.options, ["risk", "with-risk", "audit"]);
const riskReports = withRisk
? await Promise.all(bills.map((bill) => getBillRisk(client, corpId, bill.billId || bill.billCode)))
? await Promise.all(bills.map(async (bill) => getBillRisk(await getClient(), corpId, bill.billId || bill.billCode)))
: [];
if (runtime.jsonMode) {
@@ -287,7 +305,7 @@ export async function handleBillCommand(
case "schema":
case "schemas":
case "entities": {
const { entities } = await getFieldDictionary(client, corpId, true);
const { entities } = await getFieldDictionary(await getClient(), corpId, true);
if (runtime.jsonMode) {
return {
@@ -328,7 +346,7 @@ export async function handleBillCommand(
case "timeline": {
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) throw new Error("请提供要查询流程的单号或单据 ID: hose-use bill flow <单号|ID>");
const flow = await getBillFlow(client, corpId, target);
const flow = await getBillFlow(await getClient(), corpId, target);
if (!flow) {
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
return { stdout: "", stderr: `[NOT FOUND] 未找到单据流程: ${target}\n`, exitCode: 1 };
@@ -370,7 +388,7 @@ export async function handleBillCommand(
case "warnings": {
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) throw new Error("请提供要查询风控结果的单号或单据 ID: hose-use bill risk <单号|ID>");
const report = await getBillRisk(client, corpId, target);
const report = await getBillRisk(await getClient(), corpId, target);
if (!report) {
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
return { stdout: "", stderr: `[NOT FOUND] 未找到单据风控结果: ${target}\n`, exitCode: 1 };
@@ -400,7 +418,7 @@ export async function handleBillCommand(
case "budgets": {
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) throw new Error("请提供要查询预算状态的单号或单据 ID: hose-use bill budget <单号|ID>");
const report = await getBillRisk(client, corpId, target);
const report = await getBillRisk(await getClient(), corpId, target);
if (!report) {
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
return { stdout: "", stderr: `[NOT FOUND] 未找到单据预算状态: ${target}\n`, exitCode: 1 };
@@ -426,7 +444,7 @@ export async function handleBillCommand(
case "resolve": {
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) throw new Error("请提供要解析引用的单号或单据 ID: hose-use bill refs <单号|ID>");
const report = await getBillReferences(client, corpId, target);
const report = await getBillReferences(await getClient(), corpId, target);
if (!report) {
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
return { stdout: "", stderr: `[NOT FOUND] 未找到单据引用: ${target}\n`, exitCode: 1 };
@@ -455,7 +473,7 @@ export async function handleBillCommand(
case "links": {
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) throw new Error("请提供要查询关联关系的单号或单据 ID: hose-use bill relations <单号|ID>");
const report = await getBillRelations(client, corpId, target);
const report = await getBillRelations(await getClient(), corpId, target);
if (!report) {
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
return { stdout: "", stderr: `[NOT FOUND] 未找到单据关联关系: ${target}\n`, exitCode: 1 };
@@ -488,7 +506,7 @@ export async function handleBillCommand(
case "files": {
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) throw new Error("请提供要查询附件的单号或单据 ID: hose-use bill attachments <单号|ID>");
const report = await getBillAttachments(client, corpId, target);
const report = await getBillAttachments(await getClient(), corpId, target);
if (!report) {
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
return { stdout: "", stderr: `[NOT FOUND] 未找到单据附件: ${target}\n`, exitCode: 1 };
@@ -511,7 +529,7 @@ export async function handleBillCommand(
if (!target) throw new Error("请提供要下载附件的单号或单据 ID: hose-use bill download <单号|ID>");
const outputDir = stringOption(parsed.options, ["output-dir", "dir"]) || `${process.cwd()}/downloads`;
const fileId = stringOption(parsed.options, ["file-id", "file"]);
const result = await downloadBillAttachments(client, corpId, target, outputDir, fileId);
const result = await downloadBillAttachments(await getClient(), corpId, target, outputDir, fileId);
const summary = {
corpId,
corpName: corp.name,
@@ -546,7 +564,7 @@ export async function handleBillCommand(
};
}
const items = await getBillByCodeOrId(client, corpId, target);
const items = await getBillByCodeOrId(await getClient(), corpId, target);
if (!items || items.length === 0) {
return {
stdout: "",
+87
View File
@@ -0,0 +1,87 @@
import { describe, it, expect } from "bun:test";
import { handleConfigCommand } from "./config.js";
import type { CliRuntime } from "../types.js";
describe("cli/commands/config > aliases and path mapping", () => {
const dummyRuntime: CliRuntime = {
corpContext: {
listCorps: () => [],
getCurrent: () => null,
switchCorp: () => false,
resolve: () => null,
} as any,
selectedCorp: null,
jsonMode: false,
};
it("maps config show to config paths diagnosis", async () => {
const res = await handleConfigCommand(
{
area: "config",
action: "show",
args: [],
options: {},
raw: ["config", "show"],
},
dummyRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("配置路径诊断 (Config Paths)");
expect(res.stdout).toContain("当前生效配置文件");
expect(res.stdout).toContain("运行模式 (Mode)");
});
it("supports config paths directly", async () => {
const res = await handleConfigCommand(
{
area: "config",
action: "paths",
args: [],
options: {},
raw: ["config", "paths"],
},
dummyRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("配置路径诊断 (Config Paths)");
});
it("supports config show --json structured output", async () => {
const jsonRuntime = { ...dummyRuntime, jsonMode: true };
const res = await handleConfigCommand(
{
area: "config",
action: "show",
args: [],
options: { json: true },
raw: ["config", "show", "--json"],
},
jsonRuntime
);
expect(res.exitCode).toBe(0);
const data = JSON.parse(res.stdout);
expect(data).toHaveProperty("configFile");
expect(data).toHaveProperty("writableDir");
expect(data).toHaveProperty("mode");
});
it("supports config get for inspecting global stateful configuration", async () => {
const res = await handleConfigCommand(
{
area: "config",
action: "get",
args: [],
options: {},
raw: ["config", "get"],
},
dummyRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("全局运行配置");
expect(res.stdout).toContain("运行模式 (Mode)");
});
});
+35 -7
View File
@@ -9,23 +9,26 @@ import {
} from "../../core/config/loader.js";
import { booleanOption } from "../parser.js";
import { printJson, printKeyValue } from "../printer.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
export async function handleConfigCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const action = parsed.action || "show";
const action = parsed.action || "paths";
switch (action) {
case "show":
case "get":
case "list":
return handleShow(parsed, runtime);
case "paths":
case "path":
case "dirs":
case "show":
case "list":
return handlePaths(parsed, runtime);
case "get":
case "status":
case "info":
return handleShow(parsed, runtime);
case "mode":
return handleMode(parsed, runtime);
case "test-dir":
@@ -36,7 +39,7 @@ export async function handleConfigCommand(
default:
return {
stdout: "",
stderr: `未知 config 子命令: ${action}。支持: show, paths, mode <stateful|stateless>, test-dir <path|--clear>, set <key> <val>\n`,
stderr: `未知 config 子命令: ${action}。支持: paths, show, get, mode <stateful|stateless>, test-dir <path|--clear>, set <key> <val>\n`,
exitCode: 1,
};
}
@@ -92,6 +95,10 @@ async function handleMode(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
}
const isStateful = targetMode === "stateful";
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "切换全局运行模式", targetMode, { stateful: isStateful });
}
requireMutationConfirmation(parsed, runtime, "切换全局运行模式", `hose-use config mode ${targetMode} --yes`);
const updated = saveGlobalConfig({ stateful: isStateful });
if (runtime.jsonMode) {
@@ -110,6 +117,10 @@ async function handleTestDir(parsed: CliParsedArgs, runtime: CliRuntime): Promis
const globalConfig = loadGlobalConfig();
if (isClear) {
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "清除测试企业目录配置", globalConfig.testEnterprisesDir || "当前未设置", { testEnterprisesDir: null });
}
requireMutationConfirmation(parsed, runtime, "清除测试企业目录配置", "hose-use config test-dir --clear --yes");
const updated = saveGlobalConfig({ testEnterprisesDir: undefined });
if (runtime.jsonMode) {
return { stdout: printJson(updated), stderr: "", exitCode: 0 };
@@ -142,6 +153,10 @@ async function handleTestDir(parsed: CliParsedArgs, runtime: CliRuntime): Promis
}
const resolved = resolve(dirArg);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "设置测试企业目录", resolved, { testEnterprisesDir: resolved });
}
requireMutationConfirmation(parsed, runtime, "设置测试企业目录", `hose-use config test-dir ${dirArg} --yes`);
const updated = saveGlobalConfig({ testEnterprisesDir: resolved });
if (runtime.jsonMode) {
return { stdout: printJson(updated), stderr: "", exitCode: 0 };
@@ -207,6 +222,10 @@ async function handleSet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<Cl
};
}
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "更新全局配置", resolvedKey, partial);
}
requireMutationConfirmation(parsed, runtime, "更新全局配置", `hose-use config set ${rawKey} ${val} --yes`);
const updated = saveGlobalConfig(partial);
if (runtime.jsonMode) {
return { stdout: printJson(updated), stderr: "", exitCode: 0 };
@@ -227,11 +246,17 @@ async function handlePaths(parsed: CliParsedArgs, runtime: CliRuntime): Promise<
const writableDir = resolveWritableEnterprisesDir();
const configFile = resolveGlobalConfigFile();
const candidates = getEnterprisesDirCandidates();
const globalConfig = loadGlobalConfig();
const currentCorp = runtime.selectedCorp;
const data = {
configFile,
writableDir,
existingDirs,
mode: globalConfig.stateful ? "stateful" : "stateless",
stateful: globalConfig.stateful,
defaultCorpId: globalConfig.defaultCorpId || null,
activeCorp: currentCorp ? { id: currentCorp.id, name: currentCorp.name } : null,
env: {
HOSE_ENTERPRISES_DIR: envDir || null,
HOSE_USER_ENTERPRISES_DIR: envUserDir || null,
@@ -241,13 +266,16 @@ async function handlePaths(parsed: CliParsedArgs, runtime: CliRuntime): Promise<
};
if (runtime.jsonMode) {
return { stdout: printJson(data), stderr: "", exitCode: 0 };
return { stdout: printJson(data, runtime.outputOptions), stderr: "", exitCode: 0 };
}
const output = printKeyValue({
"当前生效配置文件": configFile,
"凭证保存写入目录": writableDir,
"已发现企业目录": existingDirs.length ? existingDirs.join("\n ") : "无 (未发现任何有效企业目录)",
"运行模式 (Mode)": globalConfig.stateful ? "有状态模式 (Stateful - 自动记忆默认企业)" : "无状态模式 (Stateless - 每次需显式传 --corp)",
"默认工作企业": globalConfig.defaultCorpId || "未设置 (使用首个可用企业)",
"当前解析企业": currentCorp ? `${currentCorp.name} (${currentCorp.id})` : "无",
"环境变量指定目录": envDir || "未设置 (HOSE_ENTERPRISES_DIR)",
"全部目录候选链": candidates.join("\n "),
});
+237
View File
@@ -79,3 +79,240 @@ describe("cli/commands/corps > handleCorpsCommand add-link", () => {
expect(res.stderr).toContain("必须提供协助/免密链接 URL");
});
});
describe("cli/commands/corps > handleCorpsCommand search & aliases", () => {
const mockCorps = [
{
id: "corpAlpha",
name: "阿尔法网络科技有限公司",
corpId: "alphaPhysicalId",
staffId: "STAFF_001",
staffName: "张三",
accountId: "13800000001",
source: "account",
baseUrl: "https://app.ekuaibao.com",
credentials: {
accessToken: "token-alpha",
corpId: "alphaPhysicalId",
staffId: "STAFF_001",
},
},
{
id: "corpBeta@13900000002",
name: "贝塔云端信息系统",
corpId: "corpBeta",
staffId: "STAFF_002",
staffName: "李四",
accountId: "13900000002",
source: "link",
baseUrl: "https://wx2.ekuaibao.com",
credentials: {
accessToken: "token-beta",
corpId: "corpBeta",
staffId: "STAFF_002",
},
session: {
staffName: "李四",
cellphone: "13900000002",
},
},
];
const searchRuntime: CliRuntime = {
corpContext: {
getAllCorps: () => mockCorps,
listCorps: () => mockCorps.map((c) => ({
id: c.id,
name: c.name,
corpId: c.corpId,
staffId: c.staffId,
staffName: c.staffName,
accountId: c.accountId,
source: c.source,
current: c.id === "corpAlpha",
})),
getCurrent: () => mockCorps[0],
switchCorp: (id: string) => mockCorps.some((c) => c.id === id),
resolve: () => mockCorps[0],
} as any,
selectedCorp: mockCorps[0] as any,
jsonMode: false,
};
it("returns error exit code when search keyword is empty", async () => {
const res = await handleCorpsCommand(
{
area: "corps",
action: "search",
args: [],
options: {},
raw: ["corps", "search"],
},
searchRuntime
);
expect(res.exitCode).toBe(1);
expect(res.stderr).toContain("用法: hose-use corps search <关键词>");
});
it("searches by name with case-insensitive substring match", async () => {
const res = await handleCorpsCommand(
{
area: "corps",
action: "search",
args: ["阿尔法"],
options: {},
raw: ["corps", "search", "阿尔法"],
},
searchRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("[阿尔法网络科技有限公司]");
expect(res.stdout).toContain("命中企业名称");
expect(res.stdout).toContain("* 1"); // 当前激活标记
});
it("searches by staffName and highlights the matched cell", async () => {
const res = await handleCorpsCommand(
{
area: "corps",
action: "search",
args: ["李四"],
options: {},
raw: ["corps", "search", "李四"],
},
searchRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("[李四]");
expect(res.stdout).toContain("命中员工姓名");
expect(res.stdout).toContain("corpBeta");
});
it("searches by staffId case-insensitively", async () => {
const res = await handleCorpsCommand(
{
area: "corps",
action: "search",
args: ["staff_001"],
options: {},
raw: ["corps", "search", "staff_001"],
},
searchRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("[STAFF_001]");
expect(res.stdout).toContain("命中员工工号");
});
it("searches by physical corpId", async () => {
const res = await handleCorpsCommand(
{
area: "corps",
action: "search",
args: ["alphaPhysicalId"],
options: {},
raw: ["corps", "search", "alphaPhysicalId"],
},
searchRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("阿尔法网络科技有限公司");
expect(res.stdout).toContain("命中企业ID");
});
it("searches by accountId", async () => {
const res = await handleCorpsCommand(
{
area: "corps",
action: "search",
args: ["13900000002"],
options: {},
raw: ["corps", "search", "13900000002"],
},
searchRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("[13900000002]");
expect(res.stdout).toContain("命中所属账号");
});
it("supports find alias for search", async () => {
const res = await handleCorpsCommand(
{
area: "corps",
action: "find",
args: ["阿尔法"],
options: {},
raw: ["corps", "find", "阿尔法"],
},
searchRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("[阿尔法网络科技有限公司]");
});
it("outputs friendly message when no corps match", async () => {
const res = await handleCorpsCommand(
{
area: "corps",
action: "search",
args: ["nonexistent_keyword"],
options: {},
raw: ["corps", "search", "nonexistent_keyword"],
},
searchRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toBe("未找到匹配 \"nonexistent_keyword\" 的企业配置\n");
});
it("supports --json mode with structured output", async () => {
const jsonRuntime = { ...searchRuntime, jsonMode: true };
const res = await handleCorpsCommand(
{
area: "corps",
action: "search",
args: ["阿尔法"],
options: { json: true },
raw: ["corps", "search", "阿尔法", "--json"],
},
jsonRuntime
);
expect(res.exitCode).toBe(0);
const data = JSON.parse(res.stdout);
expect(data.keyword).toBe("阿尔法");
expect(data.count).toBe(1);
expect(data.activeCorpId).toBe("corpAlpha");
expect(data.corporations).toHaveLength(1);
expect(data.corporations[0].id).toBe("corpAlpha");
expect(data.corporations[0].name).toBe("阿尔法网络科技有限公司");
expect(data.corporations[0].matchedFields).toContain("name");
});
it("outputs help message via corps help", async () => {
const res = await handleCorpsCommand(
{
area: "corps",
action: "help",
args: [],
options: {},
raw: ["corps", "help"],
},
searchRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("hose-use corps <子命令>");
expect(res.stdout).toContain("search <关键词>");
expect(res.stdout).toContain("find");
});
});
+206 -1
View File
@@ -4,8 +4,18 @@ import { resolveWritableEnterprisesDir } from "../../core/config/loader.js";
import { stringOption, booleanOption } from "../parser.js";
import { prompt } from "../helpers.js";
import { printJson, printKeyValue, printTable, formatSourceLabel, formatExpiresAt } from "../printer.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
const FIELD_LABEL_MAP: Record<string, string> = {
id: "配置ID",
name: "企业名称",
corpId: "企业ID",
staffId: "员工工号",
staffName: "员工姓名",
accountId: "所属账号",
};
export async function handleCorpsCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
@@ -14,23 +24,203 @@ export async function handleCorpsCommand(
switch (action) {
case "list":
case "ls":
return handleList(parsed, runtime);
case "search":
case "find":
case "query":
case "filter":
return handleSearch(parsed, runtime);
case "switch":
case "use":
return handleSwitch(parsed, runtime);
case "current":
case "whoami":
case "status":
case "active":
return handleCurrent(parsed, runtime);
case "add-link":
case "link":
case "import-link":
return handleAddLink(parsed, runtime);
case "help":
return handleCorpsHelp();
default:
return {
stdout: "",
stderr: `未知 corps 子命令: ${action}。支持: list, switch, current, add-link\n`,
stderr: `未知 corps 子命令: ${action}。支持: list, search, switch, current, add-link\n`,
exitCode: 1,
};
}
}
export function printCorpsHelp(): string {
return `
用法:
hose-use corps <子命令> [参数] [选项]
子命令:
list 列出本地已保存的所有企业配置 (别名: ls)
search <关键词> 根据关键词模糊搜索企业(支持 id, name, corpId, staffId, staffName, accountId,别名: find)
switch <企业ID> 切换当前激活的工作企业 (别名: use)
current 查看当前激活的企业配置与凭证详情
add-link <URL> 从第三方协助/免密链接导入企业凭证
选项:
--json, -j 以 JSON 格式输出
--help, -h 查看帮助信息
示例:
hose-use corps list
hose-use corps search 某企业
hose-use corps search 17718556446
hose-use corps switch ID01MCcOgJl1td
`.trim();
}
function handleCorpsHelp(): CliResult {
return {
stdout: printCorpsHelp() + "\n",
stderr: "",
exitCode: 0,
};
}
async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const keyword = parsed.args[0] || stringOption(parsed.options, ["keyword", "query", "k", "q", "name", "id"]);
if (!keyword || !keyword.trim()) {
return {
stdout: "",
stderr: "用法: hose-use corps search <关键词>\n",
exitCode: 1,
};
}
const kw = keyword.trim().toLowerCase();
// 从 CorpContext 中获取企业列表
const rawCorps = typeof runtime.corpContext.getAllCorps === "function"
? runtime.corpContext.getAllCorps()
: null;
const normalizedCorps = rawCorps
? rawCorps.map((c) => ({
id: c.id,
name: c.name,
corpId: c.corpId || c.credentials?.corpId || c.id,
staffId: c.staffId || c.credentials?.staffId || "",
staffName: c.staffName || c.session?.staffName || "",
accountId: c.accountId || "",
source: c.source || "manual",
baseUrl: c.baseUrl,
current: c.id === runtime.selectedCorp?.id,
expiresAt: c.auth?.expiresAt || (c.session?.expTime ?? undefined),
}))
: runtime.corpContext.listCorps().map((c) => ({
id: c.id,
name: c.name,
corpId: c.corpId || c.id,
staffId: c.staffId || "",
staffName: c.staffName || "",
accountId: c.accountId || "",
source: c.source || "manual",
baseUrl: c.baseUrl,
current: c.current || c.id === runtime.selectedCorp?.id,
expiresAt: c.expiresAt,
}));
const matches: Array<typeof normalizedCorps[number] & { matchedFields: string[] }> = [];
for (const corp of normalizedCorps) {
const matchedFields: string[] = [];
if (corp.id && corp.id.toLowerCase().includes(kw)) {
matchedFields.push("id");
}
if (corp.name && corp.name.toLowerCase().includes(kw)) {
matchedFields.push("name");
}
if (corp.corpId && corp.corpId.toLowerCase().includes(kw) && !matchedFields.includes("corpId") && corp.corpId !== corp.id) {
matchedFields.push("corpId");
}
if (corp.staffId && corp.staffId.toLowerCase().includes(kw)) {
matchedFields.push("staffId");
}
if (corp.staffName && corp.staffName.toLowerCase().includes(kw)) {
matchedFields.push("staffName");
}
if (corp.accountId && corp.accountId.toLowerCase().includes(kw)) {
matchedFields.push("accountId");
}
if (matchedFields.length > 0) {
matches.push({ ...corp, matchedFields });
}
}
if (runtime.jsonMode) {
return {
stdout: printJson(
{
keyword: keyword.trim(),
count: matches.length,
activeCorpId: runtime.selectedCorp?.id,
corporations: matches.map((m) => ({
id: m.id,
name: m.name,
corpId: m.corpId,
staffId: m.staffId,
staffName: m.staffName || undefined,
accountId: m.accountId || undefined,
source: m.source,
baseUrl: m.baseUrl,
current: m.current,
expiresAt: m.expiresAt,
matchedFields: m.matchedFields,
})),
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
if (matches.length === 0) {
return {
stdout: `未找到匹配 "${keyword.trim()}" 的企业配置\n`,
stderr: "",
exitCode: 0,
};
}
const rows = matches.map((m, i) => {
const isCurrent = m.current;
const matchLabels = m.matchedFields.map((f) => FIELD_LABEL_MAP[f] || f);
return [
isCurrent ? `* ${i + 1}` : ` ${i + 1}`,
m.matchedFields.includes("id") || m.matchedFields.includes("corpId") ? `[${m.id}]` : m.id,
m.matchedFields.includes("name") ? `[${m.name}]` : m.name,
m.matchedFields.includes("staffId") ? `[${m.staffId}]` : m.staffId,
m.staffName ? (m.matchedFields.includes("staffName") ? `[${m.staffName}]` : m.staffName) : "-",
m.accountId ? (m.matchedFields.includes("accountId") ? `[${m.accountId}]` : m.accountId) : "-",
matchLabels.map((l) => `命中${l}`).join(", "),
formatExpiresAt(m.expiresAt),
];
});
const table = printTable(
["#", "企业 ID", "企业名称", "员工工号", "员工姓名", "所属账号", "匹配项", "Token 过期时间"],
rows
);
return {
stdout: `====== 企业搜索结果 (关键词: "${keyword.trim()}", 找到 ${matches.length} 家) ======\n${table}\n\n提示:\n - 标记 * 为当前激活企业\n - 标记 [...] 为命中关键词的字段\n - 使用 hose-use corps switch <企业ID> 切换工作企业\n`,
stderr: "",
exitCode: 0,
};
}
async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const corps = runtime.corpContext.listCorps();
@@ -80,6 +270,11 @@ async function handleSwitch(parsed: CliParsedArgs, runtime: CliRuntime): Promise
return { stdout: "", stderr: "用法: hose-use corps switch <企业ID>\n", exitCode: 1 };
}
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "切换当前工作企业", corpId, { defaultCorpId: corpId });
}
requireMutationConfirmation(parsed, runtime, "切换当前工作企业", `hose-use corps switch ${corpId} --yes`);
const success = runtime.corpContext.switchCorp(corpId);
if (!success) {
return {
@@ -175,6 +370,16 @@ async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promis
};
}
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "从协助链接导入企业凭证", name || "待解析企业", {
source: "assistance-link",
overwrite,
ttl: ttl || null,
expires: expires || null,
});
}
requireMutationConfirmation(parsed, runtime, "从协助链接导入企业凭证", `hose-use corps add-link <url> --yes`);
try {
const corp = await importFromLink(linkUrl, {
name,
+448
View File
@@ -0,0 +1,448 @@
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: "差旅费用",
yes: true,
},
raw: ["feetype", "create", "--name=酒店住宿", "--parent=差旅费用", "--yes"],
},
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: "新说明", yes: true },
raw: ["feetype", "update", "酒店住宿", "--desc=新说明", "--yes"],
},
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: { yes: true },
raw: ["feetype", "enable", "酒店住宿", "--yes"],
},
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: "办公费", yes: true },
raw: ["feetype", "move", "酒店住宿", "--parent=办公费", "--yes"],
},
dummyRuntimeWithCorp
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("费用类型移动成功");
expect(res.stdout).toContain("新所属父级 : 办公费");
spy.mockRestore();
});
it("feetype create --dry-run 不创建费用类型", async () => {
const spy = spyOn(feetypeTools, "createFeeType").mockResolvedValue({} as any);
const res = await handleFeeTypeCommand(
{
area: "feetype",
action: "create",
args: [],
options: { name: "酒店住宿", parent: "差旅费用", "dry-run": true },
raw: ["feetype", "create", "--name=酒店住宿", "--parent=差旅费用", "--dry-run"],
},
dummyRuntimeWithCorp
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("DRY-RUN");
expect(res.stdout).toContain("新建费用类型");
expect(spy).not.toHaveBeenCalled();
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 子命令");
});
});
+595
View File
@@ -0,0 +1,595 @@
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";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.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 corpId = corp.corpId || corp.id;
const action = (parsed.action?.toLowerCase() || "list").trim();
let client: Awaited<ReturnType<typeof createEkbClient>> | undefined;
const getClient = async () => {
client ??= await createEkbClient(corp);
return client;
};
// ── 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(await getClient(), 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(await getClient(), 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"]);
requireMutationConfirmation(
parsed,
runtime,
"新建费用类型",
`hose-use feetype create --name="${name.trim()}" --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "新建费用类型", name.trim(), {
corpId,
name: name.trim(),
code: code || null,
parentId: parent || null,
enName: enName || null,
description: description || null,
color: color || null,
icon: icon || null,
});
}
const created = await createFeeType(await getClient(), 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)");
}
requireMutationConfirmation(
parsed,
runtime,
"修改费用类型",
`hose-use feetype update ${target} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "修改费用类型", target, {
corpId,
name: name ?? null,
code: code ?? null,
enName: enName ?? null,
description: description ?? null,
color: color ?? null,
icon: icon ?? null,
});
}
const updated = await updateFeeTypeInfo(await getClient(), 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|编码|名称>");
}
requireMutationConfirmation(
parsed,
runtime,
"停用费用类型",
`hose-use feetype disable ${target} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "停用费用类型", target, { corpId, active: false });
}
const res = await disableFeeTypeItem(await getClient(), 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;
requireMutationConfirmation(
parsed,
runtime,
"启用费用类型",
`hose-use feetype enable ${target} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "启用费用类型", target, {
corpId,
active: true,
recursive,
});
}
const res = await enableFeeTypeItem(await getClient(), 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 (移至顶级)");
}
requireMutationConfirmation(
parsed,
runtime,
"移动费用类型",
`hose-use feetype move ${target} --parent=${parentTarget} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "移动费用类型", target, {
corpId,
parent: parentTarget,
});
}
const res = await moveFeeTypeItem(await getClient(), 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(await getClient(), 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|编码|名称> (查看报账与申请字段清单)`
);
}
+144
View File
@@ -0,0 +1,144 @@
import { describe, expect, test, spyOn } from "bun:test";
import { handleKeysCommand } from "./keys.js";
import { handleOpenApiCommand } from "./openapi.js";
import type { CliRuntime, CliParsedArgs } from "../types.js";
import * as storeTools from "../../domains/store/tools.js";
describe("CLI - keys 顶级命令与凭证提取", () => {
const dummyCorp: any = {
id: "test-corp-id",
name: "测试企业A",
corpId: "test-corp-id",
credentials: { corpId: "test-corp-id", accessToken: "token123" },
};
const createRuntime = (corp: any = dummyCorp, jsonMode = false): CliRuntime => ({
corpContext: {} as any,
selectedCorp: corp,
jsonMode,
});
test("未选中企业时返回提示并报错", async () => {
const runtime = createRuntime(null);
const parsed: CliParsedArgs = { area: "keys", options: {}, args: [], raw: ["keys"] };
const res = await handleKeysCommand(parsed, runtime);
expect(res.exitCode).toBe(1);
expect(res.stderr).toContain("未选中企业");
});
test("keys 默认脱敏显示 appSecurity 接入密码", async () => {
const spy = spyOn(storeTools, "fetchOpenApiKeys").mockImplementation(() =>
Promise.resolve([
{
id: "k-1",
name: "开发测试密钥",
appKey: "545f8b6a-75a7-4f99-86e1-bca747c985e7",
appSecurity: "9bc91727-e96e-4924-abcb-d8ed77557f58",
active: true,
createTime: 1751357077503,
updateTime: 1769063905460,
},
])
);
const runtime = createRuntime(dummyCorp);
const parsed: CliParsedArgs = { area: "keys", options: {}, args: [], raw: ["keys"] };
const res = await handleKeysCommand(parsed, runtime);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("开发测试密钥");
expect(res.stdout).toContain("545f8b6a-75a7-4f99-86e1-bca747c985e7");
// 默认脱敏
expect(res.stdout).toContain("9bc91727...7f58");
expect(res.stdout).not.toContain("9bc91727-e96e-4924-abcb-d8ed77557f58");
spy.mockRestore();
});
test("keys --reveal 显式输出完整接入密码明文", async () => {
const spy = spyOn(storeTools, "fetchOpenApiKeys").mockImplementation(() =>
Promise.resolve([
{
id: "k-1",
name: "生产密钥",
appKey: "key-full-123",
appSecurity: "secret-super-long-plain-text",
active: true,
createTime: 1751357077503,
updateTime: 1769063905460,
},
])
);
const runtime = createRuntime(dummyCorp);
const parsed: CliParsedArgs = {
area: "keys",
options: { reveal: true },
args: [],
raw: ["keys", "--reveal"],
};
const res = await handleKeysCommand(parsed, runtime);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("secret-super-long-plain-text");
spy.mockRestore();
});
test("keys --json 模式正常序列化", async () => {
const spy = spyOn(storeTools, "fetchOpenApiKeys").mockImplementation(() =>
Promise.resolve([
{
id: "k-1",
name: "JSON密钥",
appKey: "json-app-key",
appSecurity: "secret-for-json-test",
active: true,
createTime: 1751357077503,
updateTime: 1769063905460,
},
])
);
const runtime = createRuntime(dummyCorp, true);
const parsed: CliParsedArgs = { area: "keys", options: { json: true }, args: [], raw: ["keys", "--json"] };
const res = await handleKeysCommand(parsed, runtime);
expect(res.exitCode).toBe(0);
const data = JSON.parse(res.stdout);
expect(Array.isArray(data)).toBe(true);
expect(data[0].appKey).toBe("json-app-key");
// 默认 json 脱敏
expect(data[0].appSecurity).toContain("...");
spy.mockRestore();
});
test("openapi keys 子命令平滑转发至同一执行器", async () => {
const spy = spyOn(storeTools, "fetchOpenApiKeys").mockImplementation(() =>
Promise.resolve([
{
id: "k-1",
name: "OpenAPI子命令测试",
appKey: "sub-app-key",
appSecurity: "sub-app-security-123456",
active: true,
createTime: 1751357077503,
updateTime: 1769063905460,
},
])
);
const runtime = createRuntime(dummyCorp);
const parsed: CliParsedArgs = {
area: "openapi",
action: "keys",
options: {},
args: [],
raw: ["openapi", "keys"],
};
const res = await handleOpenApiCommand(parsed, runtime);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("OpenAPI子命令测试");
expect(res.stdout).toContain("sub-app-key");
spy.mockRestore();
});
});
+98
View File
@@ -0,0 +1,98 @@
import { fetchOpenApiKeys } from "../../domains/store/tools.js";
import { booleanOption } from "../parser.js";
import { printJson, printTable } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
function formatDate(ts: number): string {
if (!ts) return "-";
const d = new Date(ts);
if (isNaN(d.getTime())) return "-";
const Y = d.getFullYear();
const M = String(d.getMonth() + 1).padStart(2, "0");
const D = String(d.getDate()).padStart(2, "0");
const h = String(d.getHours()).padStart(2, "0");
const m = String(d.getMinutes()).padStart(2, "0");
return `${Y}/${M}/${D} ${h}:${m}`;
}
function maskSecret(secret: string): string {
if (!secret) return "-";
if (secret.length <= 12) return "******";
return `${secret.slice(0, 8)}...${secret.slice(-4)}`;
}
export async function handleKeysCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const currentCorp = runtime.selectedCorp;
if (!currentCorp) {
return {
stdout: "",
stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n",
exitCode: 1,
};
}
const reveal =
booleanOption(parsed.options, ["reveal", "r", "plain"]) ||
parsed.action === "reveal" ||
parsed.args[0] === "reveal";
try {
const keys = await fetchOpenApiKeys(currentCorp);
if (runtime.jsonMode) {
const outputData = reveal
? keys
: keys.map((k) => ({
...k,
appSecurity: maskSecret(k.appSecurity),
}));
return {
stdout: printJson(outputData, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
if (keys.length === 0) {
return {
stdout: `企业 [${currentCorp.name}] 暂未创建 OpenAPI 密钥凭证\n`,
stderr: "",
exitCode: 0,
};
}
const rows = keys.map((k, i) => [
i + 1,
k.name || "-",
k.appKey,
reveal ? k.appSecurity : maskSecret(k.appSecurity),
k.active ? "🟢 启用" : "⚪ 停用",
formatDate(k.createTime),
]);
const table = printTable(
["#", "密钥备注", "接入账号 (appKey)", "接入密码 (appSecurity)", "状态", "创建时间"],
rows
);
const title = `====== [${currentCorp.name}] 企业 OpenAPI 接入密钥列表 (共 ${keys.length} 个) ======`;
const hint = reveal
? ""
: "\n提示: 接入密码默认脱敏,附加 --reveal (或 -r) 可查看完整明文;使用 --json 可输出完整结构。\n";
return {
stdout: `${title}\n\n${table}\n${hint}`,
stderr: "",
exitCode: 0,
};
} catch (err: any) {
return {
stdout: "",
stderr: `获取企业 OpenAPI 密钥失败: ${err?.message || err}\n`,
exitCode: 1,
};
}
}
+178
View File
@@ -0,0 +1,178 @@
import { describe, it, expect, spyOn } from "bun:test";
import { handleMenuCommand } from "./menu.js";
import * as menuTools from "../../domains/menu/tools.js";
import type { CliRuntime } from "../types.js";
import type { CorpConfig } from "../../core/config/types.js";
describe("cli/commands/menu > handleMenuCommand", () => {
const dummyRuntimeNoCorp: CliRuntime = {
corpContext: {
listCorps: () => [],
getCurrent: () => null,
switchCorp: () => false,
resolve: () => null,
} as any,
selectedCorp: null,
jsonMode: false,
};
const mockCorp: CorpConfig = {
id: "corp123",
name: "转转二手交易网",
source: "account",
baseUrl: "https://app.ekuaibao.com",
credentials: {
accessToken: "mock-token",
corpId: "corp123",
staffId: "mock-staff",
},
};
const dummyRuntimeWithCorp: CliRuntime = {
corpContext: {
listCorps: () => [mockCorp],
getCurrent: () => mockCorp,
switchCorp: () => true,
resolve: () => mockCorp,
} as any,
selectedCorp: mockCorp,
jsonMode: false,
};
it("fails with exitCode 1 when no corp is selected", async () => {
const res = await handleMenuCommand(
{
area: "menu",
action: "list",
args: [],
options: {},
raw: ["menu", "list"],
},
dummyRuntimeNoCorp
);
expect(res.exitCode).toBe(1);
expect(res.stderr).toContain("未选中企业");
});
it("lists desktop menus in table format", async () => {
const mockMenus = [
{
id: "newHomePage",
label: "首页",
appId: "100-home",
href: "/home",
children: [],
},
{
id: "dataLink",
label: "应用管理",
appId: "160-datalink-platform",
href: "/datalink",
children: [
{ id: "sub1", label: "用车补贴" },
{ id: "sub2", label: "用车制度" },
],
},
];
const spy = spyOn(menuTools, "fetchDesktopMenus").mockResolvedValue(mockMenus as any);
const res = await handleMenuCommand(
{
area: "menu",
action: "list",
args: [],
options: {},
raw: ["menu", "list"],
},
dummyRuntimeWithCorp
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("桌面端主框架导航与模块列表");
expect(res.stdout).toContain("首页");
expect(res.stdout).toContain("应用管理");
expect(res.stdout).toContain("160-datalink-platform");
spy.mockRestore();
});
it("supports --json output for menu list", async () => {
const mockMenus = [
{
id: "newHomePage",
label: "首页",
appId: "100-home",
href: "/home",
},
];
const spy = spyOn(menuTools, "fetchDesktopMenus").mockResolvedValue(mockMenus as any);
const jsonRuntime = { ...dummyRuntimeWithCorp, jsonMode: true };
const res = await handleMenuCommand(
{
area: "menu",
action: "list",
args: [],
options: { json: true },
raw: ["menu", "list", "--json"],
},
jsonRuntime
);
expect(res.exitCode).toBe(0);
const parsed = JSON.parse(res.stdout);
expect(parsed.count).toBe(1);
expect(parsed.menus[0].id).toBe("newHomePage");
spy.mockRestore();
});
it("delegates menu apps to handleAppCommand", async () => {
const mockApps = [
{
id: "SCGY:corp123",
name: "用车补贴",
code: "dataLinkItem",
href: "/third-party-item/SCGY:corp123",
},
];
const spy = spyOn(menuTools, "fetchWorkbenchAppsList").mockResolvedValue(mockApps as any);
const res = await handleMenuCommand(
{
area: "menu",
action: "apps",
args: [],
options: {},
raw: ["menu", "apps"],
},
dummyRuntimeWithCorp
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("工作台应用管理列表");
expect(res.stdout).toContain("用车补贴");
spy.mockRestore();
});
it("returns error for unknown menu subcommand", async () => {
const res = await handleMenuCommand(
{
area: "menu",
action: "badsub",
args: [],
options: {},
raw: ["menu", "badsub"],
},
dummyRuntimeWithCorp
);
expect(res.exitCode).toBe(1);
expect(res.stderr).toContain("未知 menu 子命令");
});
});
+71
View File
@@ -0,0 +1,71 @@
import { fetchDesktopMenus } from "../../domains/menu/tools.js";
import { handleAppCommand } from "./app.js";
import { printJson, printTable } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
export async function handleMenuCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
if (!runtime.selectedCorp) {
return {
stdout: "",
stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n",
exitCode: 1,
};
}
const action = parsed.action || "list";
switch (action) {
case "apps":
case "workbench":
return handleAppCommand(parsed, runtime);
case "list":
case "ls":
case "tree": {
const items = await fetchDesktopMenus(runtime.selectedCorp);
if (runtime.jsonMode) {
return {
stdout: printJson(
{
corpId: runtime.selectedCorp.credentials.corpId,
corpName: runtime.selectedCorp.name,
count: items.length,
menus: items,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
const headers = ["#", "模块 ID", "导航名称", "模块标识 (appId)", "子菜单数", "默认路由"];
const rows = items.map((m, i) => [
i + 1,
m.id,
m.label,
m.appId || "-",
m.children?.length || 0,
m.href || "-",
]);
const title = `====== [${runtime.selectedCorp.name}] 桌面端主框架导航与模块列表 (共 ${items.length} 个一级导航) ======\n`;
return {
stdout: title + printTable(headers, rows) + "\n",
stderr: "",
exitCode: 0,
};
}
default:
return {
stdout: "",
stderr: `未知 menu 子命令: ${action}。支持: list, tree, apps\n用法: hose-use menu list\n`,
exitCode: 1,
};
}
}
+14 -1
View File
@@ -4,6 +4,7 @@ import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
import { createEkbClient } from "../../core/auth/ekb.js";
import { filterMessages, listMessages, mergeMessages, readMessage } from "../../domains/message/tools.js";
import type { MessageItem } from "../../domains/message/types.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
function formatTime(value: number | undefined): string {
return value === undefined ? "-" : new Date(value).toISOString().replace("T", " ").slice(0, 16);
@@ -26,10 +27,10 @@ export async function handleMessageCommand(parsed: CliParsedArgs, runtime: CliRu
const corp = runtime.selectedCorp;
if (!corp) throw new Error("未指定或未找到有效企业。请运行 hose-use corps list 或指定 --corp=<id>");
const action = parsed.action || parsed.args[0] || "list";
const client = await createEkbClient(corp);
const corpId = corp.corpId || corp.id;
if (action === "count" || action === "unread") {
const client = await createEkbClient(corp);
const result = await listMessages(client, corpId, { start: 0, count: 1, read: false });
if (runtime.jsonMode) return { stdout: printJson({ corpId, unread: result.total }, runtime.outputOptions), stderr: "", exitCode: 0 };
return { stdout: `未读消息: ${result.total}\n`, stderr: "", exitCode: 0 };
@@ -38,12 +39,22 @@ export async function handleMessageCommand(parsed: CliParsedArgs, runtime: CliRu
if (action === "read" || action === "mark-read") {
const messageId = parsed.args[0] || stringOption(parsed.options, ["id", "message-id"]);
if (!messageId) return { stdout: "", stderr: "用法: hose-use message read <messageId>\n", exitCode: 1 };
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "标记消息为已读", messageId, { read: true });
}
requireMutationConfirmation(parsed, runtime, "标记消息为已读", `hose-use message read ${messageId} --yes`);
const client = await createEkbClient(corp);
await readMessage(client, corpId, messageId);
if (runtime.jsonMode) return { stdout: printJson({ corpId, id: messageId, read: true }, runtime.outputOptions), stderr: "", exitCode: 0 };
return { stdout: `已标记消息为已读: ${messageId}\n`, stderr: "", exitCode: 0 };
}
if (action === "read-all" || action === "mark-all-read") {
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "批量标记未读消息为已读", `corp:${corpId}`, { read: true, allUnread: true });
}
requireMutationConfirmation(parsed, runtime, "批量标记未读消息为已读", "hose-use message read-all --yes");
const client = await createEkbClient(corp);
const ids: string[] = [];
let start = 0;
let total = 0;
@@ -63,6 +74,8 @@ export async function handleMessageCommand(parsed: CliParsedArgs, runtime: CliRu
return { stdout: "", stderr: `未知消息子命令: ${action}。支持: list, count, read <messageId>, read-all\n`, exitCode: 1 };
}
const client = await createEkbClient(corp);
const read = booleanOption(parsed.options, ["read"]);
const unread = booleanOption(parsed.options, ["unread"]);
const all = booleanOption(parsed.options, ["all"]);
+7 -1
View File
@@ -2,18 +2,24 @@ import { getOpenApiSchema, listOpenApiPaths, type OpenApiType } from "../../core
import { booleanOption, stringOption } from "../parser.js";
import { printJson, printKeyValue, printTable } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
import { handleKeysCommand } from "./keys.js";
export async function handleOpenApiCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const action = parsed.action?.toLowerCase();
if (action === "keys" || action === "key") {
return handleKeysCommand(parsed, runtime);
}
const isRaw =
booleanOption(parsed.options, ["raw"]) ||
parsed.action === "raw" ||
parsed.args[0] === "raw";
const type: OpenApiType = isRaw ? "raw" : "wrapped";
const action = parsed.action?.toLowerCase();
switch (action) {
case "paths":
+199
View File
@@ -0,0 +1,199 @@
import { describe, expect, it, spyOn, afterEach } from "bun:test";
import { handlePlatformCommand } from "./platform.js";
import * as api from "../../domains/datalink/api.js";
import * as services from "../../domains/datalink/services.js";
import * as helpers from "../helpers.js";
import type { CliRuntime } from "../types.js";
import type { CorpConfig } from "../../core/config/types.js";
describe("CLI - platform 命令与 record 动作", () => {
let spies: ReturnType<typeof spyOn>[] = [];
afterEach(() => {
for (const spy of spies) {
spy.mockRestore();
}
spies = [];
});
const mockCorp: CorpConfig = {
id: "corp-1",
name: "测试企业",
source: "account",
baseUrl: "https://app.ekuaibao.com",
credentials: {
accessToken: "mock-token",
corpId: "corp-1",
staffId: "staff-1",
},
};
const dummyRuntime: CliRuntime = {
corpContext: {
listCorps: () => [mockCorp],
getCurrent: () => mockCorp,
switchCorp: () => true,
resolve: () => mockCorp,
} as any,
selectedCorp: mockCorp,
jsonMode: false,
};
const mockPlatform = {
id: "platform-1",
name: "项目台账",
code: "PJ",
active: true,
adminIds: ["staff-1"],
staffIds: [],
roleIds: [],
departmentIds: [],
departmentsIncludeChildren: false,
};
const mockEntity = {
id: "entity-1",
name: "项目",
code: "PROJECT",
type: "DIMENSION",
active: true,
fields: [
{ name: "code", label: "编码", type: "text" },
{ name: "name", label: "名称", type: "text" },
{ name: "customField", label: "自定义字段", type: "text" },
],
actions: [],
importMethod: [],
};
it("未选中企业时报错并返回 exitCode 1", async () => {
const res = await handlePlatformCommand(
{ area: "platform", action: "list", args: [], options: {}, raw: [] },
{ ...dummyRuntime, selectedCorp: null }
);
expect(res.exitCode).toBe(1);
expect(res.stderr).toContain("未选中企业");
});
it("records 正确解析嵌套 dataLink 的停启用状态和更新时间", async () => {
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any));
spies.push(spyOn(api, "searchEntityRecords").mockResolvedValue({
total: 2,
data: [
{
id: "r-1",
dataLink: { id: "r-1", name: "项目1", code: "P1", active: false, updateTime: "2026-09-09" },
},
{
id: "r-2",
dataLink: { id: "r-2", name: "项目2", code: "P2", active: true, updateTime: "2026-09-09" },
},
],
actions: [],
components: [],
path: null,
template: null,
}));
const res = await handlePlatformCommand(
{ area: "platform", action: "records", args: ["platform-1", "entity-1"], options: {}, raw: [] },
dummyRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("停用");
expect(res.stdout).toContain("启用");
});
it("record get 获取记录详情", async () => {
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any));
spies.push(spyOn(api, "getRecordDetail").mockResolvedValue({
dataLink: {
id: "r-1",
name: "测试项目",
code: "P-100",
active: true,
createTime: 12345678,
updateTime: 12345679,
form: { customField: "测试值" },
},
}));
const res = await handlePlatformCommand(
{ area: "platform", action: "record", args: ["get", "platform-1", "entity-1", "r-1"], options: {}, raw: [] },
dummyRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("测试项目");
expect(res.stdout).toContain("P-100");
expect(res.stdout).toContain("测试值");
});
it("record toggle 切换停启用状态", async () => {
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any));
const toggleSpy = spyOn(api, "toggleRecordState").mockResolvedValue({ recordId: "r-1", active: true });
spies.push(toggleSpy);
const res = await handlePlatformCommand(
{ area: "platform", action: "record", args: ["toggle", "platform-1", "entity-1", "r-1"], options: { yes: true }, raw: ["platform", "record", "toggle", "platform-1", "entity-1", "r-1", "--yes"] },
dummyRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("状态已成功切换为");
expect(toggleSpy).toHaveBeenCalledWith(expect.anything(), "corp-1", "r-1", undefined);
});
it("record edit 编辑字段", async () => {
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any));
const editSpy = spyOn(api, "editRecord").mockResolvedValue({ id: "r-1" } as any);
spies.push(editSpy);
const res = await handlePlatformCommand(
{
area: "platform",
action: "record",
args: ["edit", "platform-1", "entity-1", "r-1"],
options: { data: '{"name":"更新后的名称"}', yes: true },
raw: ["platform", "record", "edit", "platform-1", "entity-1", "r-1", "--yes"],
},
dummyRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("字段更新成功");
expect(editSpy).toHaveBeenCalledWith(
expect.anything(),
"corp-1",
expect.objectContaining({
dataLinkEntityId: "entity-1",
dataLinkId: "r-1",
form: { name: "更新后的名称" },
})
);
});
it("record recompute 触发台账重算", async () => {
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any));
const recomputeSpy = spyOn(api, "recomputeRecordLedger").mockResolvedValue({ id: "ok" });
spies.push(recomputeSpy);
const res = await handlePlatformCommand(
{ area: "platform", action: "record", args: ["recompute", "platform-1", "entity-1", "r-1"], options: { yes: true }, raw: ["platform", "record", "recompute", "platform-1", "entity-1", "r-1", "--yes"] },
dummyRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("台账重算任务已成功触发");
expect(recomputeSpy).toHaveBeenCalledWith(expect.anything(), "corp-1", "r-1");
});
});
+326 -40
View File
@@ -1,64 +1,350 @@
import * as api from "../../domains/platform/api.js";
import * as api from "../../domains/datalink/api.js";
import { buildKeywordFilter, resolveEntity, resolvePlatform, selectRecordFields } from "../../domains/datalink/services.js";
import { createClientsForCorp } from "../helpers.js";
import { booleanOption, numberOption, stringOption } from "../parser.js";
import { printJson, printTable } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
export async function handlePlatformCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const currentCorp = runtime.selectedCorp;
if (!currentCorp) {
return {
stdout: "",
stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n",
exitCode: 1,
};
function requiredTarget(parsed: CliParsedArgs, index: number, usage: string): string {
const target = parsed.args[index]?.trim();
if (!target) throw new Error(`请提供目标参数: ${usage}`);
return target;
}
function splitFields(value?: string): string[] {
return value ? value.split(",").map((field) => field.trim()).filter(Boolean) : [];
}
function cell(value: unknown): string {
if (value === undefined || value === null) return "";
if (typeof value === "object") return JSON.stringify(value);
return String(value);
}
async function resolveAppAndEntity(parsed: CliParsedArgs, runtime: CliRuntime, appIndex = 0, entityIndex = 1) {
const appTarget = requiredTarget(parsed, appIndex, "hose-use platform <子命令> <应用 ID|名称>");
const clients = await createClientsForCorp(runtime.selectedCorp!);
const corpId = runtime.selectedCorp!.credentials.corpId;
const platform = await resolvePlatform(clients.ekbClient, corpId, appTarget);
if (!platform) throw new Error(`[NOT FOUND] 当前企业下未找到自建应用: ${appTarget}`);
const entityTarget = parsed.args[entityIndex]?.trim();
if (!entityTarget) return { clients, corpId, platform, entity: undefined };
const entity = await resolveEntity(clients.ekbClient, corpId, platform, entityTarget);
if (!entity) throw new Error(`[NOT FOUND] 应用 [${platform.name}] 下未找到业务对象: ${entityTarget}`);
return { clients, corpId, platform, entity };
}
export async function handlePlatformCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
if (!runtime.selectedCorp) {
return { stdout: "", stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n", exitCode: 1 };
}
const action = parsed.action || "list";
const isWorkbench = action === "workbench" || booleanOption(parsed.options, ["workbench", "w"], false);
if (isWorkbench) {
const { handleAppCommand } = await import("./app.js");
return handleAppCommand(parsed, runtime);
}
switch (action) {
case "list":
case "ls":
return handleList(parsed, runtime);
case "apps": return handleList(parsed, runtime);
case "get":
case "show": return handleGet(parsed, runtime);
case "entities":
case "objects": return handleEntities(parsed, runtime);
case "schema":
case "fields": return handleSchema(parsed, runtime);
case "records":
case "data":
case "search": return handleRecords(parsed, runtime);
case "record":
case "record-get":
case "record-toggle":
case "record-edit":
case "record-recompute": return handleRecordAction(parsed, runtime);
case "permissions":
case "permission":
case "auth": return handlePermissions(parsed, runtime);
case "imports":
case "import-jobs": return handleImports(parsed, runtime);
default:
return {
stdout: "",
stderr: `未知 platform 子命令: ${action}。支持: list\n`,
exitCode: 1,
};
return { stdout: "", stderr: `未知 platform 子命令: ${action}。支持: list, get, entities, schema, records, record, permissions, imports\n`, exitCode: 1 };
}
}
async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const clients = await createClientsForCorp(runtime.selectedCorp!);
const platforms = await api.listPlatforms(clients.ekbClient, runtime.selectedCorp!.credentials.corpId);
const isAll = booleanOption(parsed.options, ["all", "a"], false);
const platforms = isAll
? await api.listAllPlatforms(clients.ekbClient, runtime.selectedCorp!.credentials.corpId)
: await api.listPlatforms(clients.ekbClient, runtime.selectedCorp!.credentials.corpId);
if (runtime.jsonMode) {
return { stdout: printJson(platforms, runtime.outputOptions), stderr: "", exitCode: 0 };
if (runtime.jsonMode) return { stdout: printJson({ count: platforms.length, all: isAll, platforms }, runtime.outputOptions), stderr: "", exitCode: 0 };
if (platforms.length === 0) return { stdout: `企业 [${runtime.selectedCorp!.name}] 下暂无自建应用\n`, stderr: "", exitCode: 0 };
const rows = platforms.map((p, i) => [i + 1, p.id, p.name, p.code, p.active ? "🟢 已启用" : "⚪ 未启用"]);
const label = isAll ? "自建应用与模板全量列表" : "自建应用列表";
return { stdout: `====== [${runtime.selectedCorp!.name}] ${label} (共 ${platforms.length} 个) ======\n${printTable(["#", "自建应用 ID", "应用名称", "编码", "状态"], rows)}\n`, stderr: "", exitCode: 0 };
}
async function handleGet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const { platform } = await resolveAppAndEntity(parsed, runtime);
if (runtime.jsonMode) return { stdout: printJson(platform, runtime.outputOptions), stderr: "", exitCode: 0 };
return { stdout: `====== 自建应用详情: ${platform.name} ======\n${printTable(["字段", "值"], [
["ID", platform.id], ["编码", platform.code], ["状态", platform.active ? "已启用" : "未启用"],
["管理员数量", platform.adminIds.length], ["可见人员数量", platform.staffIds.length],
["可见角色数量", platform.roleIds.length], ["可见部门数量", platform.departmentIds.length],
["包含子部门", platform.departmentsIncludeChildren ? "是" : "否"],
])}\n`, stderr: "", exitCode: 0 };
}
async function handleEntities(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const { clients, corpId, platform } = await resolveAppAndEntity(parsed, runtime);
const entities = await api.listPlatformEntities(clients.ekbClient, corpId, platform.id);
const keyword = stringOption(parsed.options, ["keyword", "q"])?.toLowerCase();
const filtered = keyword ? entities.filter((entity) => [entity.id, entity.name, entity.code].some((value) => value.toLowerCase().includes(keyword))) : entities;
if (runtime.jsonMode) return { stdout: printJson({ platform, keyword, total: entities.length, count: filtered.length, entities: filtered }, runtime.outputOptions), stderr: "", exitCode: 0 };
const rows = filtered.map((entity, i) => [i + 1, entity.id, entity.name, entity.code, entity.fields.length, entity.active ? "🟢 已启用" : "⚪ 未启用"]);
return { stdout: `====== 应用 [${platform.name}] 业务对象 (匹配 ${filtered.length} / 共 ${entities.length} 个) ======\n${printTable(["#", "对象 ID", "对象名称", "编码", "字段数", "状态"], rows)}\n`, stderr: "", exitCode: 0 };
}
async function handleSchema(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const resolved = await resolveAppAndEntity(parsed, runtime);
const entities = resolved.entity ? [resolved.entity] : await api.listPlatformEntities(resolved.clients.ekbClient, resolved.corpId, resolved.platform.id);
const fieldKeyword = stringOption(parsed.options, ["keyword", "field", "name"])?.toLowerCase();
const output = entities.map((entity) => ({ ...entity, fields: fieldKeyword ? entity.fields.filter((field) => [field.name, field.label, field.type].some((value) => value.toLowerCase().includes(fieldKeyword))) : entity.fields }));
if (runtime.jsonMode) return { stdout: printJson({ platform: resolved.platform, count: output.length, entities: output }, runtime.outputOptions), stderr: "", exitCode: 0 };
const rows = output.flatMap((entity) => entity.fields.map((field): Array<string | number | boolean | null | undefined> => [entity.name, field.name, field.label, field.type, field.optional === false ? "必填" : "可选", cell(field.entity)]));
return { stdout: `====== 应用 [${resolved.platform.name}] 字段定义 ======\n${printTable(["业务对象", "字段名", "显示名", "类型", "必填性", "引用对象"], rows)}\n`, stderr: "", exitCode: 0 };
}
async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const resolved = await resolveAppAndEntity(parsed, runtime);
if (!resolved.entity) throw new Error("请提供业务对象 ID、编码或名称: hose-use platform records <应用> <业务对象>");
const keyword = stringOption(parsed.options, ["keyword", "q", "query"]);
const filterBy = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]) || (keyword ? buildKeywordFilter(keyword) : undefined);
const start = numberOption(parsed.options, ["start", "offset"], 0);
const count = numberOption(parsed.options, ["count", "limit"], 20);
const fields = splitFields(stringOption(parsed.options, ["fields", "select"]));
const page = await api.searchEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { start, count, filterBy });
const data = fields.length ? page.data.map((item) => selectRecordFields(item, fields, resolved.entity!.fields)) : page.data;
const result = { platform: resolved.platform, entity: resolved.entity, query: { start, count, filterBy, fields }, total: page.total, returned: data.length, data };
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
const nameField = resolved.entity.fields.find((f) => f.label === "名称" || f.label.includes("名称") || f.name.endsWith("_name"));
const codeField = resolved.entity.fields.find((f) => f.label === "编码" || f.label.includes("编码") || f.name.endsWith("_code"));
const rows = data.map((item, i): Array<string | number | boolean | null | undefined> => {
const source = item.dataLink && typeof item.dataLink === "object" && !Array.isArray(item.dataLink) ? (item.dataLink as Record<string, unknown>) : item;
const id = source.id ?? item.id;
const active = source.active ?? item.active;
const updateTime = source.updateTime ?? item.updateTime;
const nameVal = source.name ?? source["名称"] ?? (nameField ? source[nameField.name] : undefined) ?? source[`E_${resolved.entity!.id}_name`];
const codeVal = source.code ?? source["编码"] ?? (codeField ? source[codeField.name] : undefined) ?? source[`E_${resolved.entity!.id}_code`];
const formattedTime = typeof updateTime === "number" ? new Date(updateTime).toLocaleString("zh-CN", { hour12: false }) : cell(updateTime);
return [i + 1, cell(id), cell(nameVal), cell(codeVal), active === false ? "停用" : "启用", formattedTime];
});
return { stdout: `====== [${resolved.platform.name}] ${resolved.entity.name} 记录 (总数: ${page.total}, 当前: ${data.length}) ======\n${printTable(["#", "记录 ID", "名称", "编码", "状态", "更新时间"], rows)}\n`, stderr: "", exitCode: 0 };
}
async function handlePermissions(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const resolved = await resolveAppAndEntity(parsed, runtime);
const appPermission = { adminIds: resolved.platform.adminIds, staffIds: resolved.platform.staffIds, roleIds: resolved.platform.roleIds, departmentIds: resolved.platform.departmentIds, departmentsIncludeChildren: resolved.platform.departmentsIncludeChildren };
const result = resolved.entity ? { platform: resolved.platform, entity: resolved.entity, appPermission } : { platform: resolved.platform, appPermission };
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
const rows: Array<Array<string | number | boolean | null | undefined>> = [["应用管理员", resolved.platform.adminIds.length], ["应用可见人员", resolved.platform.staffIds.length], ["应用可见角色", resolved.platform.roleIds.length], ["应用可见部门", resolved.platform.departmentIds.length]];
if (resolved.entity) rows.push(["对象可见性", cell(resolved.entity.visibility)], ["首页可见性", cell(resolved.entity.homeVisibility)], ["导出权限", cell(resolved.entity.exportVisibility)], ["数据过滤", cell(resolved.entity.dataFilter)]);
return { stdout: `====== 权限信息: ${resolved.platform.name}${resolved.entity ? ` / ${resolved.entity.name}` : ""} ======\n${printTable(["权限项", "值"], rows)}\n`, stderr: "", exitCode: 0 };
}
async function handleImports(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const resolved = await resolveAppAndEntity(parsed, runtime);
if (!resolved.entity) throw new Error("请提供业务对象 ID、编码或名称: hose-use platform imports <应用> <业务对象>");
const [jobs, latestResult] = await Promise.all([
api.listImportJobs(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id),
api.getImportResult(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id),
]);
const result = { platform: resolved.platform, entity: resolved.entity, jobs, latestResult };
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
return { stdout: `====== 导入任务: ${resolved.platform.name} / ${resolved.entity.name} ======\n${printTable(["#", "任务"], jobs.map((job, i) => [i + 1, cell(job)]))}\n`, stderr: "", exitCode: 0 };
}
async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const action = parsed.action?.toLowerCase() || "record";
let subAction: string;
let appIndex: number;
let entityIndex: number;
let recordIdIndex: number;
if (action.startsWith("record-")) {
subAction = action.replace("record-", "");
appIndex = 0;
entityIndex = 1;
recordIdIndex = 2;
} else {
const firstArg = parsed.args[0]?.toLowerCase();
if (["get", "show", "detail", "toggle", "state", "edit", "update", "recompute", "recalc"].includes(firstArg)) {
subAction = firstArg;
appIndex = 1;
entityIndex = 2;
recordIdIndex = 3;
} else {
subAction = "get";
appIndex = 0;
entityIndex = 1;
recordIdIndex = 2;
}
}
const resolved = await resolveAppAndEntity(parsed, runtime, appIndex, entityIndex);
if (!resolved.entity) throw new Error("请提供业务对象 ID、编码或名称: hose-use platform record <动作> <应用> <业务对象> <记录ID>");
const recordId = requiredTarget(parsed, recordIdIndex, "hose-use platform record <动作> <应用> <业务对象> <记录ID>");
switch (subAction) {
case "get":
case "show":
case "detail": {
const detail = await api.getRecordDetail(resolved.clients.ekbClient, resolved.corpId, recordId);
if (runtime.jsonMode) return { stdout: printJson(detail, runtime.outputOptions), stderr: "", exitCode: 0 };
const record = ((detail.dataLink ?? (detail as any).data?.dataLink ?? detail) as Record<string, unknown>);
const nameField = resolved.entity.fields.find((f) => f.label === "名称" || f.label.includes("名称") || f.name.endsWith("_name"));
const codeField = resolved.entity.fields.find((f) => f.label === "编码" || f.label.includes("编码") || f.name.endsWith("_code"));
const nameVal = record.name ?? record["名称"] ?? (nameField ? record[nameField.name] : undefined) ?? record[`E_${resolved.entity.id}_name`];
const codeVal = record.code ?? record["编码"] ?? (codeField ? record[codeField.name] : undefined) ?? record[`E_${resolved.entity.id}_code`];
if (platforms.length === 0) {
return {
stdout: `企业 [${runtime.selectedCorp!.name}] 下暂无自建应用\n`,
stderr: "",
exitCode: 0,
};
}
const formatTime = (time: unknown) => typeof time === "number" ? new Date(time).toLocaleString("zh-CN", { hour12: false }) : cell(time);
const rows = platforms.map((p, i) => [
i + 1,
p.id,
p.name,
p.active ? "🟢 已启用" : "⚪ 未启用",
]);
const rows: Array<Array<string | number | boolean | null | undefined>> = [
["记录 ID", cell(record.id ?? recordId)],
["业务对象", `${resolved.entity.name} (${resolved.entity.id})`],
["名称", cell(nameVal)],
["编码", cell(codeVal)],
["状态", record.active === false ? "🔴 停用" : "🟢 启用"],
["创建时间", formatTime(record.createTime)],
["更新时间", formatTime(record.updateTime)],
];
const table = printTable(["#", "自建应用 ID", "应用名称", "状态"], rows);
for (const field of resolved.entity.fields) {
if (field.name === nameField?.name || field.name === codeField?.name) continue;
const val = record[field.name] ?? record[`E_${resolved.entity.id}_${field.name}`] ?? (record.form as Record<string, unknown> | undefined)?.[field.name] ?? record[field.label];
if (val !== undefined && val !== null && val !== "") {
let displayVal = val;
if (field.type === "date" && typeof val === "number") {
displayVal = new Date(val).toLocaleDateString("zh-CN");
} else if (field.type === "money" && typeof val === "object" && val !== null && "standard" in (val as any)) {
displayVal = `${(val as any).standard} ${(val as any).standardStrCode || "CNY"}`;
}
rows.push([`${field.label} (${field.name})`, cell(displayVal)]);
}
}
return {
stdout: `====== [${runtime.selectedCorp!.name}] 自建应用列表 (共 ${platforms.length} 个) ======\n${table}\n`,
stderr: "",
exitCode: 0,
};
return {
stdout: `====== 记录详情: [${resolved.platform.name}] ${resolved.entity.name} (${recordId}) ======\n${printTable(["字段/属性", "值"], rows)}\n`,
stderr: "",
exitCode: 0,
};
}
case "toggle":
case "state": {
const explicitState = parsed.options.state !== undefined
? booleanOption(parsed.options, ["state"], true)
: parsed.options.active !== undefined
? booleanOption(parsed.options, ["active"], true)
: undefined;
requireMutationConfirmation(
parsed,
runtime,
"切换业务对象记录状态",
`hose-use platform record toggle ${resolved.platform.id} ${resolved.entity.id} ${recordId} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "切换业务对象记录状态", recordId, {
corpId: resolved.corpId,
platformId: resolved.platform.id,
entityId: resolved.entity.id,
active: explicitState ?? "toggle",
});
}
const res = await api.toggleRecordState(resolved.clients.ekbClient, resolved.corpId, recordId, explicitState);
if (runtime.jsonMode) {
return {
stdout: printJson({ success: true, recordId: res.recordId, active: res.active, app: resolved.platform.name, entity: resolved.entity.name }, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
const label = res.active ? "🟢 启用" : "🔴 停用";
return {
stdout: `✅ 应用 [${resolved.platform.name}] 业务对象 [${resolved.entity.name}] 记录 [${recordId}] 状态已成功切换为 [${label}]。\n`,
stderr: "",
exitCode: 0,
};
}
case "edit":
case "update": {
const dataStr = stringOption(parsed.options, ["data", "form", "d", "f"]);
let form: Record<string, unknown> = {};
if (dataStr) {
try {
form = JSON.parse(dataStr);
} catch {
throw new Error("提供的 --data 参数不是合法的 JSON 字符串");
}
}
const activeOpt = parsed.options.active !== undefined ? booleanOption(parsed.options, ["active"], true) : undefined;
const changes = {
dataLinkEntityId: resolved.entity.id,
dataLinkId: recordId,
form,
active: activeOpt ?? null,
};
requireMutationConfirmation(
parsed,
runtime,
"编辑业务对象记录",
`hose-use platform record edit ${resolved.platform.id} ${resolved.entity.id} ${recordId} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "编辑业务对象记录", recordId, changes);
}
const result = await api.editRecord(resolved.clients.ekbClient, resolved.corpId, {
dataLinkEntityId: resolved.entity.id,
dataLinkId: recordId,
form,
active: activeOpt,
});
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
return {
stdout: `✅ 应用 [${resolved.platform.name}] 业务对象 [${resolved.entity.name}] 记录 [${recordId}] 字段更新成功。\n`,
stderr: "",
exitCode: 0,
};
}
case "recompute":
case "recalc": {
requireMutationConfirmation(
parsed,
runtime,
"触发业务对象记录台账重算",
`hose-use platform record recompute ${resolved.platform.id} ${resolved.entity.id} ${recordId} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "触发业务对象记录台账重算", recordId, {
corpId: resolved.corpId,
platformId: resolved.platform.id,
entityId: resolved.entity.id,
});
}
const result = await api.recomputeRecordLedger(resolved.clients.ekbClient, resolved.corpId, recordId);
if (runtime.jsonMode) return { stdout: printJson({ success: true, recordId, result }, runtime.outputOptions), stderr: "", exitCode: 0 };
return {
stdout: `✅ 应用 [${resolved.platform.name}] 业务对象 [${resolved.entity.name}] 记录 [${recordId}] 台账重算任务已成功触发。\n`,
stderr: "",
exitCode: 0,
};
}
default:
throw new Error(`未知 record 动作: ${subAction}。支持: get, toggle, edit, recompute`);
}
}
+37 -1
View File
@@ -87,7 +87,8 @@ describe("CLI - hose-use rule 规则与场景索引命令", () => {
"add",
"办公采购",
"单笔采购大于1万,[必须附采购合同]{硬性};[建议由采购员集中办理]{建议}。",
"--json"
"--json",
"--yes"
]);
expect(addRes.exitCode).toBe(0);
const addData = JSON.parse(addRes.stdout);
@@ -102,6 +103,41 @@ describe("CLI - hose-use rule 规则与场景索引命令", () => {
expect(scopesData.scopes[2].scope).toBe("办公采购");
});
test("hose-use rule add --dry-run 只预览且不写入数据库", async () => {
const res = await runCli([
"rule",
"add",
"办公采购",
"单笔采购大于1万,[必须附采购合同]{硬性}。",
"--json",
"--dry-run",
]);
expect(res.exitCode).toBe(0);
const data = JSON.parse(res.stdout);
expect(data.dryRun).toBe(true);
expect(data.operation).toBe("新增审批规则");
expect(data.changes.scope).toBe("办公采购");
const scopes = await runCli(["rule", "scopes", "--json"]);
expect(JSON.parse(scopes.stdout).count).toBe(2);
});
test("hose-use rule add 未确认时拒绝写入并给出下一步", async () => {
const res = await runCli([
"rule",
"add",
"办公采购",
"单笔采购大于1万,[必须附采购合同]{硬性}。",
]);
expect(res.exitCode).not.toBe(0);
expect(res.stderr).toContain("--dry-run");
expect(res.stderr).toContain("--yes");
const scopes = await runCli(["rule", "scopes", "--json"]);
expect(JSON.parse(scopes.stdout).count).toBe(2);
});
test("hose-use rule add 语法错误拦截并阻止入库", async () => {
const failRes = await runCli([
"rule",
+30
View File
@@ -2,6 +2,7 @@ import { ApprovalRepository, parseRuleBody } from "../../domains/approval/index.
import { booleanOption, stringOption } from "../parser.js";
import { printJson, printTable } from "../printer.js";
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
export async function handleRuleCommand(
parsed: CliParsedArgs,
@@ -205,6 +206,22 @@ export async function handleRuleCommand(
if (!scope) throw new Error("缺少适用场景/索引参数:请输入索引名称或使用 --scope 指定");
if (!body) throw new Error("缺少规约正文参数:请输入正文或使用 --body 指定,须包含 [动作句式]{硬性|弹性|建议|特殊}");
// 先做纯函数校验,让调用方在确认前就能修正格式错误。
parseRuleBody(body);
requireMutationConfirmation(
parsed,
runtime,
"新增审批规则",
`hose-use rule add --scope=${scope} --body='${body}' --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "新增审批规则", scope, {
scope,
body,
status: "active",
});
}
const rule = repo.createRule({
scope,
@@ -240,6 +257,19 @@ export async function handleRuleCommand(
ruleId = found.id;
}
requireMutationConfirmation(
parsed,
runtime,
"删除审批规则",
`hose-use rule delete ${ruleId} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "删除审批规则", ruleId, {
id: ruleId,
irreversible: true,
});
}
const deleted = repo.deleteRule(ruleId);
if (runtime.jsonMode) {
return {
+11 -18
View File
@@ -1,13 +1,14 @@
import { existsSync } from "node:fs";
import { join } from "node:path";
import {
EMBEDDED_SKILL_FILES,
getDefaultGlobalSkillDir,
getAgentSkillCandidates,
getSkillContent,
installSkillFiles,
} from "../../core/embedded-skill.js";
import { booleanOption, stringOption } from "../parser.js";
import { printJson, printKeyValue } from "../printer.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
export async function handleSkillCommand(
@@ -41,19 +42,16 @@ export async function handleSkillCommand(
? join(process.cwd(), ".agents", "skills", "hose-use")
: getDefaultGlobalSkillDir();
const result = installSkillFiles(targetDir);
// 也同时尝试安装到其它检测到的候选目录
const candidates = getAgentSkillCandidates();
for (const dir of candidates) {
if (dir !== targetDir) {
try {
installSkillFiles(dir);
} catch {
// ignore
}
}
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "安装 Agent Skill 文件", targetDir, {
fileCount: Object.keys(EMBEDDED_SKILL_FILES).length,
local: isLocal,
targetPolicy: customDir ? "explicit" : isLocal ? "workspace" : "global-canonical",
});
}
requireMutationConfirmation(parsed, runtime, "安装 Agent Skill 文件", `hose-use skill install${customDir ? ` --dir=${customDir}` : ""} --yes`);
const result = installSkillFiles(targetDir);
if (runtime.jsonMode) {
return {
@@ -79,7 +77,6 @@ export async function handleSkillCommand(
case "get": {
const globalDir = getDefaultGlobalSkillDir();
const localDir = join(process.cwd(), ".agents", "skills", "hose-use");
const candidates = getAgentSkillCandidates();
const statusObj = {
global: {
@@ -90,10 +87,6 @@ export async function handleSkillCommand(
dir: localDir,
installed: existsSync(join(localDir, "SKILL.md")),
},
candidates: candidates.map((dir) => ({
dir,
installed: existsSync(join(dir, "SKILL.md")),
})),
};
if (runtime.jsonMode) {
+150
View File
@@ -0,0 +1,150 @@
import { describe, expect, test, spyOn } from "bun:test";
import { handleStoreCommand } from "./store.js";
import type { CliRuntime, CliParsedArgs } from "../types.js";
import * as storeTools from "../../domains/store/tools.js";
describe("CLI - store 应用中心与应用商店探查", () => {
const dummyCorp: any = {
id: "test-corp-id",
name: "测试企业A",
corpId: "test-corp-id",
credentials: { corpId: "test-corp-id", accessToken: "token123" },
};
const createRuntime = (corp: any = dummyCorp, jsonMode = false): CliRuntime => ({
corpContext: {} as any,
selectedCorp: corp,
jsonMode,
});
test("未选中企业时返回提示并报错", async () => {
const runtime = createRuntime(null);
const parsed: CliParsedArgs = { area: "store", options: {}, args: [], raw: ["store"] };
const res = await handleStoreCommand(parsed, runtime);
expect(res.exitCode).toBe(1);
expect(res.stderr).toContain("未选中企业");
});
test("store list 展示企业已购应用列表", async () => {
const spy = spyOn(storeTools, "fetchClientGoods").mockImplementation(() =>
Promise.resolve([
{
id: "g-1",
name: "开放接口(新)",
status: "OPENED",
expireTime: 1914422399000,
hasConfig: true,
powers: [{ powerCode: "219904", powerName: "开放接口(新)" }],
},
] as any)
);
const runtime = createRuntime(dummyCorp);
const parsed: CliParsedArgs = {
area: "store",
action: "list",
options: {},
args: [],
raw: ["store", "list"],
};
const res = await handleStoreCommand(parsed, runtime);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("开放接口(新)");
expect(res.stdout).toContain("已开通");
expect(res.stdout).toContain("支持配置");
spy.mockRestore();
});
test("store search 检索应用市场商品", async () => {
const spy = spyOn(storeTools, "searchGoods").mockImplementation(() =>
Promise.resolve({
total: 1,
items: [
{
id: "g-2",
name: "纷享销客基础互联应用",
status: "OPENED",
summary: "连接纷享销客",
},
],
} as any)
);
const runtime = createRuntime(dummyCorp);
const parsed: CliParsedArgs = {
area: "store",
action: "search",
options: {},
args: ["纷享"],
raw: ["store", "search", "纷享"],
};
const res = await handleStoreCommand(parsed, runtime);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("纷享销客基础互联应用");
expect(res.stdout).toContain("连接纷享销客");
spy.mockRestore();
});
test("store get 查看应用详情", async () => {
const spy = spyOn(storeTools, "fetchGoodsDetail").mockImplementation(() =>
Promise.resolve({
id: "g-1",
name: "开放接口(新)",
status: "OPENED",
hasConfig: true,
configStyle: "SIDESLIP",
powers: [{ powerCode: "219904", powerName: "开放接口(新)" }],
summary: "OpenAPI提供标准化接口",
} as any)
);
const runtime = createRuntime(dummyCorp);
const parsed: CliParsedArgs = {
area: "store",
action: "get",
options: {},
args: ["g-1"],
raw: ["store", "get", "g-1"],
};
const res = await handleStoreCommand(parsed, runtime);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("开放接口(新)");
expect(res.stdout).toContain("219904");
expect(res.stdout).toContain("SIDESLIP");
spy.mockRestore();
});
test("store keys 转发至 keys 执行器", async () => {
const spy = spyOn(storeTools, "fetchOpenApiKeys").mockImplementation(() =>
Promise.resolve([
{
id: "k-1",
name: "Store转发密钥",
appKey: "store-key-123",
appSecurity: "store-secret-456",
active: true,
createTime: 1751357077503,
updateTime: 1769063905460,
},
])
);
const runtime = createRuntime(dummyCorp);
const parsed: CliParsedArgs = {
area: "store",
action: "keys",
options: {},
args: [],
raw: ["store", "keys"],
};
const res = await handleStoreCommand(parsed, runtime);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("Store转发密钥");
expect(res.stdout).toContain("store-key-123");
spy.mockRestore();
});
});
+239
View File
@@ -0,0 +1,239 @@
import {
fetchClientGoods,
searchGoods,
fetchGoodsDetail,
} from "../../domains/store/tools.js";
import { booleanOption, stringOption } from "../parser.js";
import { printJson, printKeyValue, printTable } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
import { handleKeysCommand } from "./keys.js";
function formatDate(ts: number | null | undefined): string {
if (!ts) return "长期有效";
const d = new Date(ts);
if (isNaN(d.getTime())) return "-";
const Y = d.getFullYear();
const M = String(d.getMonth() + 1).padStart(2, "0");
const D = String(d.getDate()).padStart(2, "0");
return `${Y}/${M}/${D}`;
}
function formatStatus(status: string | null | undefined): string {
if (!status) return "-";
switch (status.toUpperCase()) {
case "OPENED":
return "🟢 已开通";
case "EXPIRE":
return "🔴 已过期";
case "APPLYING":
return "🟡 申请中";
case "CLOSED":
return "⚪ 已关闭";
default:
return status;
}
}
export async function handleStoreCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const currentCorp = runtime.selectedCorp;
if (!currentCorp) {
return {
stdout: "",
stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n",
exitCode: 1,
};
}
const action = (parsed.action || "list").toLowerCase();
switch (action) {
case "keys":
case "key":
return handleKeysCommand(parsed, runtime);
case "list":
case "ls":
return handleList(parsed, runtime);
case "search":
case "find":
return handleSearch(parsed, runtime);
case "get":
case "info":
case "detail":
return handleGet(parsed, runtime);
default:
return {
stdout: "",
stderr: `未知 store 子命令: ${action}。支持: list, search, get, keys\n`,
exitCode: 1,
};
}
}
async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const currentCorp = runtime.selectedCorp!;
const keyword = parsed.args[0] || stringOption(parsed.options, ["name", "keyword", "k"]);
const isAll = booleanOption(parsed.options, ["all", "a"]);
try {
const items = await fetchClientGoods(currentCorp, { keyword, isAll });
if (runtime.jsonMode) {
return {
stdout: printJson(items, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
if (items.length === 0) {
return {
stdout: `企业 [${currentCorp.name}] 暂无匹配的已购应用${keyword ? ` (搜索: ${keyword})` : ""}\n`,
stderr: "",
exitCode: 0,
};
}
const rows = items.map((item, i) => {
const powersStr = (item.powers || [])
.map((p) => (typeof p === "string" ? p : p.powerName || p.powerCode || ""))
.filter(Boolean)
.join(", ");
return [
i + 1,
item.id,
item.name,
formatStatus(item.status),
formatDate(item.expireTime),
item.hasConfig ? "支持配置" : "-",
powersStr || "-",
];
});
const table = printTable(
["#", "应用 ID", "应用名称", "开通状态", "有效期限", "配置支持", "绑定能力 (Powers)"],
rows
);
const title = `====== [${currentCorp.name}] 企业已开通/已购应用列表 (共 ${items.length} 个) ======`;
return {
stdout: `${title}\n\n${table}\n`,
stderr: "",
exitCode: 0,
};
} catch (err: any) {
return {
stdout: "",
stderr: `查询企业已购应用失败: ${err?.message || err}\n`,
exitCode: 1,
};
}
}
async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const currentCorp = runtime.selectedCorp!;
const keyword = parsed.args[0] || stringOption(parsed.options, ["name", "keyword", "k"]) || "";
try {
const result = await searchGoods(currentCorp, { keyword, count: 20 });
if (runtime.jsonMode) {
return {
stdout: printJson(result, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
if (result.items.length === 0) {
return {
stdout: `应用商店未搜索到匹配应用${keyword ? ` (关键词: ${keyword})` : ""}\n`,
stderr: "",
exitCode: 0,
};
}
const rows = result.items.map((item, i) => [
i + 1,
item.id,
item.name,
formatStatus(item.status),
item.summary || "-",
]);
const table = printTable(["#", "商品 ID", "应用名称", "企业状态", "应用简介"], rows);
const title = `====== 合思应用商店搜索结果 (共 ${result.total} 条,当前展示 ${result.items.length} 条) ======`;
return {
stdout: `${title}\n\n${table}\n`,
stderr: "",
exitCode: 0,
};
} catch (err: any) {
return {
stdout: "",
stderr: `搜索应用商店失败: ${err?.message || err}\n`,
exitCode: 1,
};
}
}
async function handleGet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const currentCorp = runtime.selectedCorp!;
const goodsId = parsed.args[0] || stringOption(parsed.options, ["id"]);
if (!goodsId) {
return {
stdout: "",
stderr: "请提供应用/商品 ID,例如: hose-use store get O1w2Hg000000qw\n",
exitCode: 1,
};
}
try {
const detail = await fetchGoodsDetail(currentCorp, goodsId);
if (runtime.jsonMode) {
return {
stdout: printJson(detail, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
const powersStr = (detail.powers || [])
.map((p) => `${p.powerName || p.powerCode || ""} (${p.powerCode || ""})`)
.join(", ");
const out = printKeyValue({
"应用 ID": detail.id,
"应用名称": detail.name,
"应用编码": detail.code || "-",
"开通状态": formatStatus(detail.status),
"有效期限": formatDate(detail.expireTime),
"支持配置": detail.hasConfig ? `是 (${detail.configStyle || "默认"})` : "否",
"绑定能力": powersStr || "-",
"应用摘要": detail.summary || "-",
});
return {
stdout: `====== 应用详情: ${detail.name} ======\n${out}\n`,
stderr: "",
exitCode: 0,
};
} catch (err: any) {
return {
stdout: "",
stderr: `获取应用详情失败: ${err?.message || err}\n`,
exitCode: 1,
};
}
}
+310 -8
View File
@@ -4,10 +4,26 @@ 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";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
const WORKFLOW_STATE_DIR = process.env.HOSE_STATE_DIR || join(homedir(), ".config", "hose-use");
export async function handleWorkflowCommand(
parsed: CliParsedArgs,
@@ -38,23 +54,193 @@ 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!;
requireMutationConfirmation(
parsed,
runtime,
"写入工作流草稿文件",
`hose-use workflow patch ${pipelineId} --file=${file} --path=${path} --value='${rawValue}' ${inPlace ? "--in-place" : `--output=${target}`} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "写入工作流草稿文件", target, {
pipelineId,
path,
value,
tasksVersion: patched.tasksVersion,
});
}
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 forceWrite = booleanOption(parsed.options, ["force-write", "forceWrite"]);
requireMutationConfirmation(
parsed,
runtime,
"保存工作流草稿到远端",
`hose-use workflow save ${pipelineId} --file=${file} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "保存工作流草稿到远端", pipelineId, {
file,
tasksVersion: parsedWorkflow.tasksVersion,
forceWrite,
});
}
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: ["*"],
};
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 +253,98 @@ 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 };
requireMutationConfirmation(
parsed,
runtime,
"发布并启用工作流",
`hose-use workflow publish ${pipelineId} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "发布并启用工作流", pipelineId, { state: 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 +391,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 +425,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 +506,17 @@ 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);
requireMutationConfirmation(
parsed,
runtime,
"切换工作流状态",
`hose-use workflow toggle ${pipelineId} --state=${state} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "切换工作流状态", 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 };
+58
View File
@@ -0,0 +1,58 @@
export type CliExitCode = 1 | 2 | 10 | 11 | 12;
export class CliError extends Error {
readonly exitCode: CliExitCode;
readonly nextAction?: string;
constructor(message: string, exitCode: CliExitCode, nextAction?: string) {
super(message);
this.name = "CliError";
this.exitCode = exitCode;
this.nextAction = nextAction;
}
}
export class PayloadTooLargeError extends CliError {
constructor(message: string, nextAction?: string) {
super(message, 12, nextAction);
this.name = "PayloadTooLargeError";
}
}
export function usageError(message: string, nextAction?: string): CliError {
return new CliError(message, 2, nextAction);
}
export function confirmationRequired(message: string, nextAction: string): CliError {
return new CliError(message, 10, nextAction);
}
export function classifyCliError(error: unknown): {
exitCode: CliExitCode;
nextAction?: string;
} {
if (error instanceof CliError) {
return { exitCode: error.exitCode, nextAction: error.nextAction };
}
const value = error instanceof Error ? error.message : String(error);
const status = responseStatus(error);
if (status === 401 || status === 403 || /(?:^|\s)(?:token|bearer|session) (?:expired|missing|invalid)/i.test(value)) {
return { exitCode: 11, nextAction: "hose-use auth login" };
}
if (/^(?:Usage:|用法:|未知(?:命令|.*子命令)|缺少|请提供|请指定|Invalid|Missing|required)/i.test(value)) {
return { exitCode: 2 };
}
if (/without --(?:yes|confirm)|请显式添加 --yes|需要 --(?:yes|confirm)/i.test(value)) {
return { exitCode: 10 };
}
return { exitCode: 1 };
}
function responseStatus(error: unknown): number | undefined {
if (!error || typeof error !== "object") return undefined;
const response = (error as { response?: unknown }).response;
if (!response || typeof response !== "object") return undefined;
const status = (response as { status?: unknown }).status;
return typeof status === "number" ? status : undefined;
}
+51
View File
@@ -0,0 +1,51 @@
export interface HelpTopic {
summary: string;
usage: string;
commands: Record<string, string>;
options?: string[];
}
export const HELP_REGISTRY: Record<string, HelpTopic> = {
context: { summary: "全局运行上下文与身份诊断", usage: "hose-use context [--json]", commands: { context: "输出当前企业、账号、运行模式与认证状态" } },
auth: { summary: "认证与凭证管理", usage: "hose-use auth <子命令>", commands: { login: "登录并保存企业凭证", status: "查看当前认证状态", accounts: "列出已保存账号", "switch-account": "切换默认账号" } },
corps: { summary: "多企业租户管理", usage: "hose-use corps <子命令>", commands: { list: "列出本地企业配置", search: "搜索企业与员工", switch: "切换当前工作企业", current: "查看当前企业", "add-link": "从链接导入企业凭证" } },
config: { summary: "全局运行模式与路径配置", usage: "hose-use config <子命令>", commands: { paths: "诊断配置目录链", get: "查看全局配置", mode: "切换 stateful/stateless", set: "更新指定配置项" } },
workflow: { summary: "工作流查询、草稿与生命周期管理", usage: "hose-use workflow <子命令> [参数] [选项]", commands: { list: "列出工作流", get: "查看工作流详情", find: "按节点类型搜索", analyze: "静态分析工作流", patch: "生成草稿字段补丁", save: "保存草稿到远端", toggle: "切换启停状态", publish: "发布并启用工作流", history: "查看版本历史", logs: "查看运行日志", check: "检查错误管道" }, options: ["--dry-run 只预览写操作", "--yes/--confirm 确认写操作", "--file=<workflow.json> 指定工作流快照"] },
bill: { summary: "单据检索与审批动作", usage: "hose-use bill <子命令> [单号|ID] [选项]", commands: { list: "查询单据", get: "查看单据详情", flow: "查看审批流程", approve: "同意审批", reject: "驳回审批", transfer: "转交审批", "add-node": "加签审批", comment: "添加评论" }, options: ["--dry-run 只预览审批动作", "--yes/--confirm 确认执行审批动作", "--comment=<原因> 驳回或评论内容"] },
platform: { summary: "自建应用、业务对象与底层记录", usage: "hose-use platform <子命令> [参数]", commands: { list: "列出自建应用", entities: "列出业务对象", schema: "查看字段定义", records: "查询记录", record: "查看或修改单条记录", permissions: "查看权限", imports: "查看导入任务" }, options: ["--dry-run 只预览记录写操作", "--yes/--confirm 确认记录写操作"] },
feetype: { summary: "费用类型全生命周期管理", usage: "hose-use feetype <子命令> [参数]", commands: { list: "查看费用类型树", get: "查看详情与字段", create: "新建费用类型", update: "修改属性", disable: "停用", enable: "启用", move: "移动层级", fields: "查看字段配置" }, options: ["--dry-run 只预览写操作", "--yes/--confirm 确认写操作"] },
rule: { summary: "本地审批规约管理", usage: "hose-use rule <子命令> [参数]", commands: { scopes: "列出适用场景", scope: "查看场景明细", list: "列出规则", get: "查看规则详情", add: "新增规则", delete: "删除规则" }, options: ["--dry-run 只预览增删", "--yes/--confirm 确认增删"] },
approval: { summary: "确定性审批网关与要点仲裁", usage: "hose-use approval audit <子命令> [单号]", commands: { points: "查看审核要点", checklist: "查看核验清单", review: "核验事实", decide: "生成或执行仲裁决定" }, options: ["--apply --yes 执行真实审批流转"] },
message: { summary: "消息中心与通知管理", usage: "hose-use message <子命令>", commands: { list: "查询消息", count: "查看未读数", read: "标记消息已读", "read-all": "全部标记已读" } },
task: { summary: "待办中心与审批任务", usage: "hose-use task <子命令>", commands: { todo: "待我审批", approved: "我已审批", submitted: "我发起的", records: "审批记录", cc: "抄送任务" } },
contact: { summary: "企业通讯录与人员检索", usage: "hose-use contact <子命令>", commands: { list: "列出员工", search: "搜索员工", get: "查看员工详情" } },
dimension: { summary: "系统与自定义档案维度", usage: "hose-use dimension <子命令>", commands: { list: "列出维度", items: "列出维度项" } },
role: { summary: "企业角色定义与成员", usage: "hose-use role <子命令>", commands: { list: "列出角色", groups: "列出角色组", members: "查看角色成员" } },
permission: { summary: "权限模型快照", usage: "hose-use permission get", commands: { get: "查看角色权限开关" } },
app: { summary: "桌面端工作台应用管理", usage: "hose-use app <子命令>", commands: { list: "列出应用", get: "查看应用详情" } },
menu: { summary: "桌面端主导航菜单树", usage: "hose-use menu list", commands: { list: "查看主导航", apps: "查看应用入口" } },
openapi: { summary: "OpenAPI 规范导出与路径查询", usage: "hose-use openapi [paths|info|--raw|keys]", commands: { paths: "列出路径概要", info: "查看规范元数据", keys: "查看企业接入密钥" } },
keys: { summary: "企业 OpenAPI 接入凭证", usage: "hose-use keys [--json] [--reveal]", commands: { keys: "读取当前企业密钥(默认脱敏)" }, options: ["--reveal 仅在明确授权后查看明文"] },
store: { summary: "已购应用与应用商店探查", usage: "hose-use store <list|search|get>", commands: { list: "列出已购应用", search: "搜索应用商店", get: "查看应用详情" } },
update: { summary: "版本自更新与发布记录", usage: "hose-use update [check|--changelog]", commands: { update: "检查并升级版本", check: "只检查可用版本", changelog: "查看发布记录" } },
skill: { summary: "Agent Skill 管理", usage: "hose-use skill <install|status|dump>", commands: { install: "安装内嵌 Skill", status: "查看安装状态", dump: "导出 Skill 文件" } },
service: { summary: "常驻守护进程管理", usage: "hose-use service <start|stop|restart|status|logs|poll>", commands: { start: "启动服务", stop: "停止服务", restart: "重启服务", status: "查看服务状态", logs: "查看服务日志", poll: "轮询事件" } },
probe: { summary: "企业连通性诊断", usage: "hose-use probe [corpId]", commands: { probe: "检查认证与 API 连通性" } },
http: { summary: "轻量 HTTP Server 与交互文档", usage: "hose-use http [--port=<port>]", commands: { http: "启动 HTTP 服务" } },
mcp: { summary: "MCP Server", usage: "hose-use mcp serve", commands: { serve: "启动 MCP 服务" } },
aipro: { summary: "AI PRO 确定性审批仲裁", usage: "hose-use aipro <子命令>", commands: { status: "查看网关状态", bind: "绑定单据", review: "核验要点", decide: "执行仲裁" } },
};
export function renderScopedHelp(target: string[]): string {
const area = target[0]?.toLowerCase();
const topic = area ? HELP_REGISTRY[area] : undefined;
if (!topic) return `未找到命令域帮助: ${target.join(" ") || "<empty>"}\n运行 hose-use --help 查看全部命令域。`;
const action = target[1]?.toLowerCase();
const lines = [`${area} - ${topic.summary}`, "", `用法: ${topic.usage}`, "", "子命令:"];
if (action && topic.commands[action]) lines.push(` ${action.padEnd(14)} ${topic.commands[action]}`);
else for (const [name, description] of Object.entries(topic.commands)) lines.push(` ${name.padEnd(14)} ${description}`);
if (topic.options?.length) lines.push("", "常用选项:", ...topic.options.map((option) => ` ${option}`));
lines.push("", "提示: 追加 --json 获取机器可解析结果;写操作先用 --dry-run,再用 --yes 或 --confirm 执行。", "更多: hose-use --help");
return lines.join("\n");
}
+9
View File
@@ -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(
@@ -12,6 +13,8 @@ export function initCorpRuntime(
stateless?: boolean;
stateful?: boolean;
jsonMode?: boolean;
dryRun?: boolean;
confirmed?: boolean;
outputOptions?: OutputOptions;
appRoot?: string;
entryFile?: string;
@@ -47,6 +50,8 @@ export function initCorpRuntime(
corpContext,
selectedCorp,
jsonMode: options.jsonMode ?? false,
dryRun: options.dryRun ?? false,
confirmed: options.confirmed ?? false,
outputOptions: options.outputOptions,
appRoot: options.appRoot,
entryFile: options.entryFile,
@@ -64,6 +69,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,
+45
View File
@@ -0,0 +1,45 @@
import { describe, expect, test } from "bun:test";
import { handleAuthCommand } from "./commands/auth.js";
import { handleConfigCommand } from "./commands/config.js";
import { handleCorpsCommand } from "./commands/corps.js";
import { handleMessageCommand } from "./commands/message.js";
import { handleSkillCommand } from "./commands/skill.js";
import type { CliRuntime } from "./types.js";
const runtime: CliRuntime = {
corpContext: {
listCorps: () => [],
getCurrent: () => null,
switchCorp: () => true,
resolve: () => null,
} as any,
selectedCorp: {
id: "corp-test",
name: "测试企业",
corpId: "corp-test",
credentials: { accessToken: "token", corpId: "corp-test", staffId: "staff-test" },
} as any,
jsonMode: true,
};
describe("CLI mutation boundaries", () => {
test("auth login dry-run does not prompt or call the login API", async () => {
const result = await handleAuthCommand({ area: "auth", action: "login", args: [], options: { "dry-run": true }, raw: ["auth", "login", "--dry-run"] }, runtime);
expect(result.exitCode).toBe(0);
expect(JSON.parse(result.stdout).dryRun).toBe(true);
});
test("corps/config state changes share the dry-run protocol", async () => {
const corp = await handleCorpsCommand({ area: "corps", action: "switch", args: ["corp-next"], options: { "dry-run": true }, raw: ["corps", "switch", "corp-next", "--dry-run"] }, runtime);
const config = await handleConfigCommand({ area: "config", action: "mode", args: ["stateless"], options: { "dry-run": true }, raw: ["config", "mode", "stateless", "--dry-run"] }, runtime);
expect(JSON.parse(corp.stdout).operation).toContain("工作企业");
expect(JSON.parse(config.stdout).changes.stateful).toBe(false);
});
test("skill installation and message read never write during dry-run", async () => {
const skill = await handleSkillCommand({ area: "skill", action: "install", args: [], options: { "dry-run": true }, raw: ["skill", "install", "--dry-run"] }, runtime);
const message = await handleMessageCommand({ area: "message", action: "read", args: ["message-1"], options: { "dry-run": true }, raw: ["message", "read", "message-1", "--dry-run"] }, runtime);
expect(JSON.parse(skill.stdout).dryRun).toBe(true);
expect(JSON.parse(message.stdout).changes.read).toBe(true);
});
});
+57
View File
@@ -0,0 +1,57 @@
import { describe, expect, test } from "bun:test";
import { handleBillCommand } from "./commands/bill.js";
import type { CliRuntime } from "./types.js";
const runtime: CliRuntime = {
corpContext: {} as any,
selectedCorp: {
id: "corp-test",
name: "测试企业",
source: "account",
baseUrl: "https://app.ekuaibao.com",
credentials: {
corpId: "corp-test",
staffId: "staff-test",
accessToken: "token-test",
},
},
jsonMode: true,
};
describe("CLI mutation protocol", () => {
test("bill --dry-run returns a preview without creating an API client", async () => {
const result = await handleBillCommand(
{
area: "bill",
action: "approve",
args: ["S26000001"],
options: { "dry-run": true },
raw: ["bill", "approve", "S26000001", "--dry-run"],
},
runtime
);
expect(result.exitCode).toBe(0);
const preview = JSON.parse(result.stdout);
expect(preview.dryRun).toBe(true);
expect(preview.operation).toBe("同意单据审批");
expect(preview.target).toBe("S26000001");
expect(preview.nextAction).not.toContain("--dry-run");
expect(preview.nextAction).toContain("--yes");
});
test("bill write without confirmation is rejected before the API call", async () => {
await expect(
handleBillCommand(
{
area: "bill",
action: "approve",
args: ["S26000001"],
options: {},
raw: ["bill", "approve", "S26000001"],
},
runtime
)
).rejects.toThrow("--yes");
});
});
+87
View File
@@ -0,0 +1,87 @@
import { booleanOption } from "./parser.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "./types.js";
import { CliError } from "./errors.js";
/**
* All mutating CLI commands use the same two-step contract:
* 1. --dry-run only describes the intended change;
* 2. --yes/--confirm is required before the real operation runs.
*
* The parsed-argument fallback keeps command handlers easy to unit-test without
* requiring every hand-built CliRuntime to include the newer fields.
*/
export class MutationConfirmationRequired extends CliError {
readonly operation: string;
constructor(operation: string, nextAction: string) {
super(
`拒绝执行${operation}:该操作会改变数据。请先使用 --dry-run 预览,确认后追加 --yes(或 --confirm)。`,
10,
nextAction
);
this.name = "MutationConfirmationRequired";
this.operation = operation;
}
}
export function isDryRun(parsed: CliParsedArgs, runtime: CliRuntime): boolean {
return runtime.dryRun === true || booleanOption(parsed.options, ["dry-run", "dryRun", "dryrun"]);
}
export function isConfirmed(parsed: CliParsedArgs, runtime: CliRuntime): boolean {
return (
runtime.confirmed === true ||
booleanOption(parsed.options, ["yes", "y", "confirm", "force-write"])
);
}
export function requireMutationConfirmation(
parsed: CliParsedArgs,
runtime: CliRuntime,
operation: string,
nextAction: string
): void {
if (isDryRun(parsed, runtime) || isConfirmed(parsed, runtime)) return;
throw new MutationConfirmationRequired(operation, nextAction);
}
export function mutationPreview(
parsed: CliParsedArgs,
runtime: CliRuntime,
operation: string,
target: string,
changes: Record<string, unknown>
): CliResult {
const confirmedArgs = parsed.raw.filter((arg) => !["--dry-run", "--dryRun", "--dryrun"].includes(arg));
const nextAction = `hose-use ${confirmedArgs.join(" ")} --yes`;
const payload = {
dryRun: true,
operation,
target,
changes,
nextAction,
};
if (runtime.jsonMode) {
return {
stdout: `${JSON.stringify(payload, null, 2)}\n`,
stderr: "",
exitCode: 0,
};
}
const lines = [
"[DRY-RUN] 未执行任何写操作。",
`操作: ${operation}`,
`目标: ${target}`,
"变更:",
...Object.entries(changes).map(([key, value]) => ` ${key}: ${formatPreviewValue(value)}`),
`下一步: ${nextAction}`,
];
return { stdout: `${lines.join("\n")}\n`, stderr: "", exitCode: 0 };
}
function formatPreviewValue(value: unknown): string {
if (typeof value === "string") return value;
return JSON.stringify(value);
}
+3
View File
@@ -27,6 +27,9 @@ const KNOWN_BOOLEAN_FLAGS = new Set([
"yes",
"confirm",
"force-write",
"dry-run",
"dryRun",
"dryrun",
]);
export function parseArgs(rawArgs: string[]): CliParsedArgs {
+38 -9
View File
@@ -1,6 +1,8 @@
import { writeFileSync } from "node:fs";
import { VERSION } from "../version.js";
import type { OutputOptions } from "./types.js";
import { PayloadTooLargeError } from "./errors.js";
import { renderScopedHelp } from "./help.js";
export const DEFAULT_OUTPUT_BYTES_LIMIT = 200_000;
@@ -15,8 +17,9 @@ export function protectLargeOutput(result: unknown, options: OutputOptions = {})
if (options.allowFull || options.outputFile) return;
const bodyBytes = Buffer.byteLength(JSON.stringify(result), "utf-8");
if (bodyBytes > DEFAULT_OUTPUT_BYTES_LIMIT) {
throw new Error(
`输出体积过大 (${bodyBytes} 字节,超过安全阈值 ${DEFAULT_OUTPUT_BYTES_LIMIT} 字节)。请使用 --output-file <路径> (或 -o <路径>) 转储到本地文件;若确需完整大报文请附加 --full 参数。`
throw new PayloadTooLargeError(
`输出体积过大 (${bodyBytes} 字节,超过安全阈值 ${DEFAULT_OUTPUT_BYTES_LIMIT} 字节)。请使用 --output-file <路径> (或 -o <路径>) 转储到本地文件;若确需完整大报文请附加 --full 参数。`,
"hose-use <command> --json --output-file <path>"
);
}
}
@@ -109,7 +112,8 @@ export function printTable(
return [headerLine, separatorLine, ...dataLines].map((l) => ` ${l}`).join("\n");
}
export function printHelp(): string {
export function printHelp(target: string[] = []): string {
if (target.length) return renderScopedHelp(target);
return `
合思/易快报企业级 CLI 工具 (hose-use) v${VERSION}
@@ -118,17 +122,21 @@ export function printHelp(): string {
核心命令域:
context 查看全局运行上下文与身份诊断 (context, status, whoami, env)
auth 认证与凭证管理 (login, status, refresh, import, accounts)
corps 多企业租户管理 (list, switch, current)
auth 认证与凭证管理 (login, status, refresh, import, accounts, switch-account)
corps 多企业租户管理 (list, search <关键词>, switch, current, add-link)
aipro 合思 AI PRO 确定性审批仲裁网关入口 (status, scopes, bind, checklist, review, decide, logs)
config 全局运行模式与路径诊断 (show, paths, mode <stateful|stateless>, set)
workflow 工作流管理 (list, get, find, analyze, toggle)
workflow 工作流管理 (list, get, find, analyze, toggle, publish, patch, save, history, logs, check)
bill 单据检索与审批动作 (list, get <单号|ID> [--risk], approve|reject|transfer|add-node|comment <单号|ID> [选项], refs, relations, attachments, download, flow, risk, budget, schema, link)
contact 企业通讯录与人员检索 (list, search <关键词>, get <staffId>)
task 待办中心与审批任务 (todo, approved, records, submitted, cc)
message 消息中心与通知管理 (list, count, read, read-all)
platform 自建应用管理 (list)
app 应用管理 (桌面端工作台业务应用: list [--keyword], get <应用ID|名称>)
menu 桌面端主导航菜单树与模块 (list, tree, apps)
platform 自建应用与数据模型 (开放平台业务对象、字段与底层记录: list, get, entities, schema, records, permissions, imports)
datalink platform 的同义入口,面向 DataLink 业务对象查询
dimension 系统/自定义档案维度 (list, items <维度>)
feetype 费用类型管理与字段规格配置 (list, get, create, update, disable, enable, move, fields)
role 角色定义与成员 (list, groups, members <角色>)
permission 权限模型快照 (get)
rule 本地 AI 审批规约管理 (scopes, scope <索引号|场景>, list, get, add, delete)
@@ -136,7 +144,9 @@ export function printHelp(): string {
skill Agent Skill 管理 (install, status, dump)
probe 连通性诊断 (probe [corpId])
update 版本自更新与发布记录 (update, update check, update --changelog, --github, --gitea, --repo=<owner/repo>)
openapi OpenAPI 3.1.0 规范导出 (openapi, openapi --raw, openapi paths, openapi info)
openapi OpenAPI 3.1.0 规范导出与凭证查看 (openapi, openapi --raw, openapi paths, openapi info, openapi keys)
keys 企业 OpenAPI 接入凭证一键获取 (keys [--reveal|-r])
store 应用中心已购应用与应用商店探查 (list, search <关键词>, get <ID>)
http 启动轻量 HTTP Server 与交互式文档 (http [--port=8888] [--host=127.0.0.1])
service 常驻守护进程管理 (service start|stop|restart|status|logs|poll)
mcp MCP Server 运行 (serve)
@@ -149,7 +159,9 @@ export function printHelp(): string {
--full 允许全量输出大体积 JSON (绕过 200KB 防爆拦截)
--stateless 单次强制以无状态模式执行
--stateful 单次强制以有状态模式执行
--yes, -y 确认执行会改变单据状态的审批动作
--dry-run 只预览写操作,不发起写请求或落盘
--yes, -y 确认执行会改变数据的写操作
--confirm --yes 的可读别名;写操作必须显式确认
--help, -h 查看帮助信息
常用示例:
@@ -160,6 +172,7 @@ export function printHelp(): string {
hose-use config paths # 查看多级企业配置目录链
hose-use config mode stateless # 切换为无状态模式 (防止 Agent 误操作)
hose-use corps list # 列出名下所有企业
hose-use corps search 某企业 # 模糊搜索已保存的企业与员工信息
hose-use corps switch ID01MCcOgJl1td # 切换工作企业
hose-use contact search 张三 # 模糊搜索员工工号、邮箱与电话
hose-use contact list --limit=20 # 采样查看企业通讯录(带防爆截断保护)
@@ -172,6 +185,15 @@ export function printHelp(): string {
hose-use message count # 查看未读消息数
hose-use workflow list # 汇总查看全部工作流
hose-use workflow find --task=code-js2 # 搜索包含自定义脚本的工作流
hose-use app list # 查看应用管理列表(桌面端工作台开通的业务应用)
hose-use app get 用车补贴 # 查看指定应用管理的详情与元数据配置
hose-use menu list # 查看桌面端主框架一级导航树与功能模块
hose-use platform list # 列出企业可见的自建应用平台
hose-use platform entities <应用> # 查看应用下的业务对象
hose-use platform schema <应用> <对象> # 查看对象字段(--keyword 可筛选字段)
hose-use platform records <应用> <对象> --keyword 关键词 --fields 名称,编码 --json
# 查询记录并只输出指定字段
hose-use platform permissions <应用> [对象] # 查看应用/对象权限快照
hose-use bill list # 查看当前企业单据与报销列表
hose-use bill flow S26000001 # 查看单据审批历史与后续节点
hose-use bill risk S26000001 # 查看风控预警、预算与发票风险
@@ -182,6 +204,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 财务主管 # 查看指定角色成员
+38
View File
@@ -60,4 +60,42 @@ describe("CLI runner - version and help aliases", () => {
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain("未知命令域: unknown-command-xyz");
});
it("returns semantic confirmation exit code and nextAction", async () => {
const result = await runCli([
"rule",
"add",
"办公采购",
"采购时,[必须附采购合同]{硬性}。",
"--json",
]);
expect(result.exitCode).toBe(10);
const data = JSON.parse(result.stdout);
expect(data.exitCode).toBe(10);
expect(data.nextAction).toContain("--yes");
});
it("supports layered help by command domain and subcommand", async () => {
const domain = await runCli(["help", "workflow"]);
expect(domain.exitCode).toBe(0);
expect(domain.stdout).toContain("workflow -");
expect(domain.stdout).toContain("patch");
expect(domain.stdout).toContain("--dry-run");
const command = await runCli(["workflow", "publish", "--help"]);
expect(command.exitCode).toBe(0);
expect(command.stdout).toContain("publish");
expect(command.stdout).toContain("发布并启用工作流");
});
it("keeps help and version machine-readable when --json is requested", async () => {
const help = await runCli(["help", "workflow", "--json"]);
const version = await runCli(["version", "--json"]);
expect(JSON.parse(help.stdout).help).toContain("workflow -");
expect(JSON.parse(version.stdout)).toEqual({ name: "hose-use", version: VERSION });
expect(help.stderr).toBe("");
expect(version.stderr).toBe("");
});
});
+67 -10
View File
@@ -1,12 +1,15 @@
import { VERSION } from "../version.js";
import { parseArgs, stringOption, booleanOption, outputOptions } from "./parser.js";
import { printHelp, printJson, redactSensitiveText } from "./printer.js";
import { classifyCliError } from "./errors.js";
import { initCorpRuntime } from "./helpers.js";
import { handleAuthCommand } from "./commands/auth.js";
import { handleCorpsCommand } from "./commands/corps.js";
import { handleConfigCommand } from "./commands/config.js";
import { handleWorkflowCommand } from "./commands/workflow.js";
import { handlePlatformCommand } from "./commands/platform.js";
import { handleAppCommand } from "./commands/app.js";
import { handleMenuCommand } from "./commands/menu.js";
import { handleSkillCommand } from "./commands/skill.js";
import { handleProbeCommand } from "./commands/probe.js";
import { handleMcpCommand } from "./commands/mcp.js";
@@ -24,6 +27,9 @@ import { handlePermissionCommand } from "./commands/permission.js";
import { handleRuleCommand } from "./commands/rule.js";
import { handleApprovalCommand } from "./commands/approval.js";
import { handleContextCommand } from "./commands/context.js";
import { handleKeysCommand } from "./commands/keys.js";
import { handleStoreCommand } from "./commands/store.js";
import { handleFeeTypeCommand } from "./commands/feetype.js";
import type { CliParsedArgs, CliResult, CliRunOptions } from "./types.js";
const STANDING_COMMANDS = new Set(["http", "server", "web", "mcp"]);
@@ -60,11 +66,13 @@ async function runCliOnce(
): Promise<CliResult> {
const stdoutChunks: string[] = [];
const stderrChunks: string[] = [];
const machineJson = booleanOption(parseArgs(rawArgs).options, ["json", "j"]);
const originalLog = console.log;
const originalError = console.error;
console.log = (...values: unknown[]) => {
stdoutChunks.push(values.map((v) => (typeof v === "string" ? v : String(v))).join(" "));
const line = values.map((v) => (typeof v === "string" ? v : String(v))).join(" ");
(machineJson ? stderrChunks : stdoutChunks).push(line);
};
console.error = (...values: unknown[]) => {
stderrChunks.push(values.map((v) => (typeof v === "string" ? v : String(v))).join(" "));
@@ -111,31 +119,51 @@ function isVersionRequested(parsed: CliParsedArgs): boolean {
return false;
}
function resolveHelpTarget(parsed: CliParsedArgs): string[] {
if (["help", "h", "?"].includes((parsed.area || "").toLowerCase())) {
return [parsed.action, parsed.args[0]].filter((value): value is string => Boolean(value));
}
return [parsed.area, parsed.action].filter((value): value is string => Boolean(value));
}
async function dispatchCli(
rawArgs: string[],
options: CliRunOptions = {}
): Promise<CliResult> {
const parsed = parseArgs(rawArgs);
const jsonMode = booleanOption(parsed.options, ["json", "j"]);
if (isHelpRequested(parsed)) {
return { stdout: printHelp() + "\n", stderr: "", exitCode: 0 };
const help = printHelp(resolveHelpTarget(parsed));
return {
stdout: jsonMode ? printJson({ help }) : `${help}\n`,
stderr: "",
exitCode: 0,
};
}
if (isVersionRequested(parsed)) {
return { stdout: `hose-use v${VERSION}\n`, stderr: "", exitCode: 0 };
return {
stdout: jsonMode ? printJson({ name: "hose-use", version: VERSION }) : `hose-use v${VERSION}\n`,
stderr: "",
exitCode: 0,
};
}
const jsonMode = booleanOption(parsed.options, ["json", "j"]);
const corpIdOption = stringOption(parsed.options, ["corp", "c"]);
const statelessOption = booleanOption(parsed.options, ["stateless"]);
const statefulOption = booleanOption(parsed.options, ["stateful"]);
const outputOpts = outputOptions(parsed.options);
const dryRun = booleanOption(parsed.options, ["dry-run", "dryRun", "dryrun"]);
const confirmed = booleanOption(parsed.options, ["yes", "y", "confirm", "force-write"]);
const runtime = initCorpRuntime({
corpId: corpIdOption,
stateless: statelessOption,
stateful: statefulOption,
jsonMode,
dryRun,
confirmed,
outputOptions: outputOpts,
appRoot: options.appRoot,
entryFile: options.entryFile,
@@ -189,6 +217,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);
@@ -209,9 +245,16 @@ async function dispatchCli(
return await handleMessageCommand(parsed, runtime);
case "platform":
case "platforms":
case "datalink":
case "data-link":
return await handlePlatformCommand(parsed, runtime);
case "app":
case "apps":
return await handlePlatformCommand(parsed, runtime);
case "workbench":
return await handleAppCommand(parsed, runtime);
case "menu":
case "menus":
return await handleMenuCommand(parsed, runtime);
case "skill":
case "skills":
return await handleSkillCommand(parsed, runtime);
@@ -227,6 +270,14 @@ async function dispatchCli(
case "schema":
case "spec":
return await handleOpenApiCommand(parsed, runtime);
case "keys":
case "key":
case "secret":
case "secrets":
return await handleKeysCommand(parsed, runtime);
case "store":
case "market":
return await handleStoreCommand(parsed, runtime);
case "http":
case "server":
case "web":
@@ -237,7 +288,7 @@ async function dispatchCli(
case "mcp":
return await handleMcpCommand(parsed, options);
case undefined:
return { stdout: printHelp() + "\n", stderr: "", exitCode: 0 };
return { stdout: printHelp(resolveHelpTarget(parsed)) + "\n", stderr: "", exitCode: 0 };
default:
return {
stdout: "",
@@ -247,17 +298,23 @@ async function dispatchCli(
}
} catch (error) {
const errorMsg = redactSensitiveText(error instanceof Error ? error.message : String(error));
const classification = classifyCliError(error);
if (jsonMode) {
return {
stdout: printJson({ error: true, message: errorMsg }),
stdout: JSON.stringify({
error: true,
message: errorMsg,
exitCode: classification.exitCode,
...(classification.nextAction ? { nextAction: classification.nextAction } : {}),
}, null, 2),
stderr: "",
exitCode: 1,
exitCode: classification.exitCode,
};
}
return {
stdout: "",
stderr: `[ERROR] ${errorMsg}\n`,
exitCode: 1,
stderr: `[ERROR] ${errorMsg}${classification.nextAction ? `\n下一步: ${classification.nextAction}` : ""}\n`,
exitCode: classification.exitCode,
};
}
}
+2
View File
@@ -34,6 +34,8 @@ export interface CliRuntime {
corpContext: CorpContext;
selectedCorp: CorpConfig | null;
jsonMode: boolean;
dryRun?: boolean;
confirmed?: boolean;
outputOptions?: OutputOptions;
appRoot?: string;
entryFile?: string;
+61 -1
View File
@@ -29,6 +29,11 @@ const easoMemoryCache = new Map<
{ token: string; hoseToken: string; expiresAt: number }
>();
const unityMemoryCache = new Map<
string,
{ token: string; expiresAt: number }
>();
function isExpired(entry: { expiresAt: number }, refreshTtl: number): boolean {
return Date.now() >= entry.expiresAt - refreshTtl * 1000;
}
@@ -53,7 +58,7 @@ async function fetchHoseToken(
return response.data;
}
async function fetchUnityJwt(
export async function fetchUnityJwt(
accessToken: string,
corpId: string,
staffId: string,
@@ -168,3 +173,58 @@ export async function getEasoClient(corp: CorpConfig): Promise<{
}),
};
}
export async function getUnityClient(corp: CorpConfig): Promise<{
client: ReturnType<typeof createAuthClient>;
unityJwt: string;
}> {
const refreshTtl = corp.auth?.refreshTtl ?? 300;
const cacheKey = `${corp.id}:unity`;
const mem = unityMemoryCache.get(cacheKey);
if (mem && !isExpired(mem, refreshTtl)) {
return {
unityJwt: mem.token,
client: createAuthClient({
prefixUrl: EASO_BASE_URL,
getHeaders: () => ({
Authorization: `Bearer ${mem.token}`,
}),
onUnauthorized: () => {
unityMemoryCache.delete(cacheKey);
},
}),
};
}
const corpId = corp.corpId || corp.credentials.corpId;
const staffId = corp.staffId || corp.credentials.staffId;
const baseUrl = corp.baseUrl || EKB_BASE_URL;
const unityJwt = await fetchUnityJwt(
corp.credentials.accessToken,
corpId,
staffId,
baseUrl
);
const entry = {
token: unityJwt,
expiresAt: Date.now() + 2 * 60 * 60 * 1000,
};
unityMemoryCache.set(cacheKey, entry);
return {
unityJwt,
client: createAuthClient({
prefixUrl: EASO_BASE_URL,
getHeaders: () => ({
Authorization: `Bearer ${unityJwt}`,
}),
onUnauthorized: () => {
unityMemoryCache.delete(cacheKey);
},
}),
};
}
+44 -1
View File
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync, readFileSync } from "node:fs";
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync, readFileSync, utimesSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
@@ -11,6 +11,8 @@ import {
loadGlobalConfig,
saveGlobalConfig,
resolveGlobalConfigFile,
syncLegacyEnterprisesDir,
syncLegacyGlobalConfig,
} from "./loader.js";
import type { CorpConfig } from "./types.js";
@@ -170,4 +172,45 @@ describe("core/config/loader", () => {
expect(updated.stateful).toBe(false);
expect(updated.defaultCorpId).toBe("test-corp-123");
});
test("syncLegacyEnterprisesDir copies legacy credentials and removes stale legacy directory", () => {
const primary = join(tempDir, "primary");
const legacy = join(tempDir, "legacy");
mkdirSync(legacy, { recursive: true });
writeFileSync(join(legacy, "corp-old.json"), JSON.stringify(createMockCorp("corp-old", "旧企业")));
const old = new Date(Date.now() - 10 * 24 * 60 * 60 * 1000);
utimesSync(join(legacy, "corp-old.json"), old, old);
utimesSync(legacy, old, old);
const result = syncLegacyEnterprisesDir(primary, legacy);
expect(result.copied).toEqual(["corp-old.json"]);
expect(result.deletedLegacyDir).toBe(true);
expect(existsSync(join(primary, "corp-old.json"))).toBe(true);
expect(existsSync(legacy)).toBe(false);
});
test("syncLegacyEnterprisesDir preserves a recently modified legacy directory", () => {
const primary = join(tempDir, "primary-recent");
const legacy = join(tempDir, "legacy-recent");
mkdirSync(legacy, { recursive: true });
writeFileSync(join(legacy, "corp-recent.json"), JSON.stringify(createMockCorp("corp-recent", "近期企业")));
const result = syncLegacyEnterprisesDir(primary, legacy);
expect(result.deletedLegacyDir).toBe(false);
expect(existsSync(legacy)).toBe(true);
});
test("syncLegacyGlobalConfig migrates and removes a stale legacy config", () => {
const primary = join(tempDir, "config", "config.json");
const legacy = join(tempDir, "legacy-config.json");
writeFileSync(legacy, JSON.stringify({ stateful: false }));
const old = new Date(Date.now() - 10 * 24 * 60 * 60 * 1000);
utimesSync(legacy, old, old);
const result = syncLegacyGlobalConfig(primary, legacy);
expect(result.copied).toBe(true);
expect(result.deletedLegacyFile).toBe(true);
expect(JSON.parse(readFileSync(primary, "utf8")).stateful).toBe(false);
expect(existsSync(legacy)).toBe(false);
});
});
+70 -2
View File
@@ -1,4 +1,4 @@
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigSchema } from "./types.js";
@@ -14,6 +14,8 @@ export const USER_ENTERPRISES_DIR = PRIMARY_USER_ENTERPRISES_DIR;
export const PRIMARY_GLOBAL_CONFIG_FILE = join(homedir(), ".config", "hose-use", "config.json");
export const LEGACY_GLOBAL_CONFIG_FILE = join(homedir(), ".cache", "ekb-mcp", "config.json");
const LEGACY_CLEANUP_GRACE_MS = 7 * 24 * 60 * 60 * 1000;
function ensureDir(dir: string): void {
mkdirSync(dir, { recursive: true });
}
@@ -27,7 +29,14 @@ export function resolveEnterprisesDirs(): string[] {
const configuredUserDir = process.env[USER_DIR_ENV]?.trim();
const userDirs = configuredUserDir
? (existsSync(configuredUserDir) ? [configuredUserDir] : [])
: [PRIMARY_USER_ENTERPRISES_DIR, LEGACY_USER_ENTERPRISES_DIR];
: (() => {
try {
syncLegacyEnterprisesDir();
} catch {
// Legacy migration must never prevent normal CLI startup.
}
return [PRIMARY_USER_ENTERPRISES_DIR, LEGACY_USER_ENTERPRISES_DIR];
})();
const globalConfig = loadGlobalConfig();
const testDir = globalConfig.testEnterprisesDir?.trim();
@@ -69,11 +78,70 @@ export function getEnterprisesDirCandidates(): string[] {
export function resolveGlobalConfigFile(): string {
const configured = process.env[GLOBAL_CONFIG_ENV]?.trim();
if (configured) return configured;
try {
syncLegacyGlobalConfig();
} catch {
// Legacy migration must never prevent normal CLI startup.
}
if (existsSync(PRIMARY_GLOBAL_CONFIG_FILE)) return PRIMARY_GLOBAL_CONFIG_FILE;
if (existsSync(LEGACY_GLOBAL_CONFIG_FILE)) return LEGACY_GLOBAL_CONFIG_FILE;
return PRIMARY_GLOBAL_CONFIG_FILE;
}
export function syncLegacyEnterprisesDir(
primaryDir: string = PRIMARY_USER_ENTERPRISES_DIR,
legacyDir: string = LEGACY_USER_ENTERPRISES_DIR
): { copied: string[]; deletedLegacyDir: boolean } {
if (!existsSync(legacyDir)) return { copied: [], deletedLegacyDir: false };
mkdirSync(primaryDir, { recursive: true, mode: 0o700 });
const copied: string[] = [];
const files = readdirSync(legacyDir).filter((file) => file.endsWith(".json"));
for (const file of files) {
const legacyPath = join(legacyDir, file);
const primaryPath = join(primaryDir, file);
if (!existsSync(primaryPath) || statSync(legacyPath).mtimeMs > statSync(primaryPath).mtimeMs) {
copyFileSync(legacyPath, primaryPath);
copied.push(file);
}
}
const now = Date.now();
const hasRecentEntry = readdirSync(legacyDir).some((file) => now - statSync(join(legacyDir, file)).mtimeMs < LEGACY_CLEANUP_GRACE_MS);
const hasNewerLegacyFile = files.some((file) => {
const legacyPath = join(legacyDir, file);
const primaryPath = join(primaryDir, file);
return existsSync(primaryPath) && statSync(legacyPath).mtimeMs > statSync(primaryPath).mtimeMs;
});
const directoryIsRecent = now - statSync(legacyDir).mtimeMs < LEGACY_CLEANUP_GRACE_MS;
const deletedLegacyDir = !hasRecentEntry && !hasNewerLegacyFile && !directoryIsRecent;
if (deletedLegacyDir) rmSync(legacyDir, { recursive: true, force: true });
return { copied, deletedLegacyDir };
}
export function syncLegacyGlobalConfig(
primaryFile: string = PRIMARY_GLOBAL_CONFIG_FILE,
legacyFile: string = LEGACY_GLOBAL_CONFIG_FILE
): { copied: boolean; deletedLegacyFile: boolean } {
if (!existsSync(legacyFile)) return { copied: false, deletedLegacyFile: false };
mkdirSync(dirname(primaryFile), { recursive: true, mode: 0o700 });
let copied = false;
if (!existsSync(primaryFile) || statSync(legacyFile).mtimeMs > statSync(primaryFile).mtimeMs) {
copyFileSync(legacyFile, primaryFile);
copied = true;
}
const oldEnough = Date.now() - statSync(legacyFile).mtimeMs >= LEGACY_CLEANUP_GRACE_MS;
const safeToDelete = existsSync(primaryFile) && statSync(legacyFile).mtimeMs <= statSync(primaryFile).mtimeMs && oldEnough;
if (safeToDelete) {
rmSync(legacyFile, { force: true });
return { copied, deletedLegacyFile: true };
}
return { copied, deletedLegacyFile: false };
}
export function loadGlobalConfig(): GlobalConfig {
const file = resolveGlobalConfigFile();
try {
+9 -1
View File
@@ -4,6 +4,8 @@ import { saveGlobalConfig } from "./loader.js";
export interface CorpSummary {
id: string;
name: string;
corpId?: string;
staffName?: string;
source?: string;
accountId?: string;
staffId: string;
@@ -143,13 +145,19 @@ export class CorpContext {
return true;
}
getAllCorps(): CorpConfig[] {
return Array.from(this.corps.values());
}
listCorps(): CorpSummary[] {
return Array.from(this.corps.values()).map((corp) => ({
id: corp.id,
name: corp.name,
corpId: corp.corpId || corp.credentials.corpId,
staffId: corp.credentials.staffId,
staffName: corp.staffName || corp.session?.staffName || undefined,
source: corp.source || "manual",
accountId: corp.accountId,
staffId: corp.credentials.staffId,
baseUrl: corp.baseUrl,
current: corp.id === this.current?.id,
expiresAt: corp.auth?.expiresAt || (corp.session?.expTime ?? undefined),
+15 -3
View File
@@ -1,10 +1,14 @@
import { describe, expect, test } from "bun:test";
import { mkdtempSync, rmSync, existsSync } from "node:fs";
import { tmpdir } from "node:os";
import { homedir, tmpdir } from "node:os";
import { join } from "node:path";
import { EMBEDDED_SKILL_FILES, getSkillContent, installSkillFiles } from "./embedded-skill.js";
import { EMBEDDED_SKILL_FILES, getDefaultGlobalSkillDir, getSkillContent, installSkillFiles } from "./embedded-skill.js";
describe("embedded-skill - 多文件内嵌 Skill 体系", () => {
test("全局 Skill 目录固定为 ~/.agents/skills/hose-use", () => {
expect(getDefaultGlobalSkillDir()).toBe(join(homedir(), ".agents", "skills", "hose-use"));
});
test("正确内嵌 SKILL.md、agents/openai.yaml 及各领域参考专卷", () => {
expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toBeDefined();
expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toContain("name: hose-use");
@@ -30,6 +34,12 @@ 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");
expect(EMBEDDED_SKILL_FILES["references/store.md"]).toBeDefined();
expect(EMBEDDED_SKILL_FILES["references/store.md"]).toContain("hose-use keys");
expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toContain("--reveal -o <path>");
expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toContain("references/store.md");
});
test("installSkillFiles 递归保留层级结构并落盘到目标目录", () => {
@@ -37,16 +47,18 @@ 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(14);
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);
expect(existsSync(join(tmp, "references", "store.md"))).toBe(true);
} finally {
rmSync(tmp, { recursive: true, force: true });
}
+4 -8
View File
@@ -14,6 +14,8 @@ 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" };
import refStore from "../../skills/hose-use/references/store.md" with { type: "text" };
export const EMBEDDED_SKILL_FILES: Record<string, string> = {
"SKILL.md": skillMain,
@@ -21,6 +23,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,
@@ -28,6 +31,7 @@ export const EMBEDDED_SKILL_FILES: Record<string, string> = {
"references/role.md": refRole,
"references/workflow.md": refWorkflow,
"references/service.md": refService,
"references/store.md": refStore,
};
export function getSkillContent(): string {
@@ -38,14 +42,6 @@ export function getDefaultGlobalSkillDir(): string {
return join(homedir(), ".agents", "skills", "hose-use");
}
export function getAgentSkillCandidates(): string[] {
return [
join(homedir(), ".agents", "skills", "hose-use"),
join(homedir(), ".gemini", "antigravity", "skills", "hose-use"),
join(homedir(), ".codex", "skills", "hose-use"),
];
}
export function installSkillFiles(targetDir: string = getDefaultGlobalSkillDir()): {
targetDir: string;
files: string[];
+7
View File
@@ -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";
}
}
+3
View File
@@ -7,7 +7,10 @@
| 域 | 说明 | 详细文档 |
|---|---|---|
| `platform/` | 自建应用(DataLink Platform)与工作流(EASO/Piper) | [README.platform.md](./platform/README.platform.md) |
| `datalink/` | 自建应用下的业务对象、字段、记录、权限与导入状态 | [README.datalink.md](./datalink/README.datalink.md) |
| `bill/` | 费控单据、报销单、发票与 DataLink 实体字典 | [README.bill.md](./bill/README.bill.md) |
| `store/` | 企业应用中心/应用商店与 OpenAPI 密钥凭证 | [README.store.md](./store/README.store.md) |
| `feetype/` | 企业费用类型全生命周期管理与字段规格配置 | [README.feetype.md](./feetype/README.feetype.md) |
## 分层规则
+44
View File
@@ -0,0 +1,44 @@
# DataLink 域说明
DataLink 域负责跨企业查询当前账号可见的自建应用、业务对象、字段定义、业务记录、权限快照和导入状态。
## 代码结构
```text
src/domains/datalink/
├── types.ts # 应用详情、对象字段、记录分页与权限模型
├── api.ts # DataLink HTTP 传输层
├── services.ts # 应用/对象名称解析与查询表达式辅助
└── tools.ts # MCP tool 注册
```
## 查询链路
```text
platform/search
└─ platform/{platformId} 应用详情与管理权限
└─ entity/platformId/{platformId} 业务对象与字段定义
└─ searchPlatformDataLinkWithChild/{entityId} 业务记录
```
应用列表和应用详情使用 EKB client。记录查询的 `filterBy` 原样支持 DataLink 过滤表达式;CLI 另提供 `--keyword`,自动生成名称/编码模糊查询。
## CLI
```bash
hose-use platform list
hose-use platform get <应用 ID|名称>
hose-use platform entities <应用 ID|名称>
hose-use platform schema <应用 ID|名称> [对象 ID|名称] [--keyword <字段关键词>]
hose-use platform records <应用 ID|名称> <对象 ID|名称> [--keyword <关键词>] [--filter <表达式>] [--fields <字段列表>]
hose-use platform record get <应用> <业务对象> <记录ID>
hose-use platform record toggle <应用> <业务对象> <记录ID> [--state=true|false] [--dry-run|--yes]
hose-use platform record edit <应用> <业务对象> <记录ID> --data='{"field": "val"}' [--dry-run|--yes]
hose-use platform record recompute <应用> <业务对象> <记录ID> [--dry-run|--yes]
hose-use platform permissions <应用 ID|名称> [对象 ID|名称]
hose-use platform imports <应用 ID|名称> <对象 ID|名称>
```
也可以使用 `datalink` / `data-link` 作为同义命令域。
单条业务对象记录支持通过 `record get`(详情)、`record toggle`(启停用)、`record edit`(字段编辑更新)以及 `record recompute`(台账重算)进行维护。Excel 批量上传与流程引擎触发暂不在本域开放。
+280
View File
@@ -0,0 +1,280 @@
import { z } from "zod";
import type { KyInstance } from "ky";
import {
DatalinkEntitySchema,
DatalinkPlatformDetailSchema,
type DatalinkEntity,
type DatalinkImportJob,
type DatalinkPlatformDetail,
type DatalinkRecord,
type DatalinkRecordDetail,
type DatalinkRecordEditPayload,
type DatalinkRecordPage,
type DatalinkRecordQuery,
} from "./types.js";
function asRecord(value: unknown): Record<string, any> {
return value !== null && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, any>)
: {};
}
function numberOr(value: unknown, fallback: number): number {
const parsed = typeof value === "number" ? value : Number(value);
return Number.isFinite(parsed) ? parsed : fallback;
}
function parseEntity(value: unknown): DatalinkEntity {
return DatalinkEntitySchema.parse(asRecord(value));
}
function sanitizePlatformDetail(value: unknown): Record<string, unknown> {
const platform = asRecord(value);
const admin = Array.isArray(platform.admin)
? platform.admin.map((item) => {
const staff = asRecord(item);
return {
id: staff.id,
name: staff.name,
code: staff.code,
active: staff.active,
};
})
: platform.admin;
return { ...platform, admin };
}
/** 列出当前企业可见的启用自建应用。 */
export async function listPlatforms(client: KyInstance, corpId: string) {
const response = await client.get("api/v2/datalink/platform/search", {
searchParams: { scope: "enable", corpId },
});
const json = asRecord(await response.json());
const items = Array.isArray(json.items) ? json.items.map(sanitizePlatformDetail) : [];
return z.array(DatalinkPlatformDetailSchema).parse(items);
}
/** 列出当前企业全量自建应用与模板平台(包含 HAB 模板与全部自建应用)。 */
export async function listAllPlatforms(client: KyInstance, corpId: string) {
const response = await client.get("api/v2/datalink/platform", {
searchParams: { corpId },
});
const json = asRecord(await response.json());
const rawList = Array.isArray(json) ? json : Array.isArray(json.items) ? json.items : [];
const items = rawList.map(sanitizePlatformDetail);
return z.array(DatalinkPlatformDetailSchema).parse(items);
}
/** 获取单个应用详情以及应用级人员/角色/部门权限。 */
export async function getPlatform(
client: KyInstance,
corpId: string,
platformId: string
): Promise<DatalinkPlatformDetail> {
const normalizedId = platformId.startsWith("$") ? platformId : `$${platformId}`;
const bareId = platformId.startsWith("$") ? platformId.slice(1) : platformId;
const response = await client.get(`api/v2/datalink/platform/${normalizedId}`, {
// 前端实际使用两个 join,并且详情接口要求同时传 id。
searchParams: new URLSearchParams([
["id", bareId],
["join", "icon.fileId,fileId,/v1/attachment/attachments"],
["corpId", corpId],
["join", "adminIds,admin,/v1/organization/staffs"],
]),
});
const json = asRecord(await response.json());
return DatalinkPlatformDetailSchema.parse(sanitizePlatformDetail(json.value ?? json.data ?? json));
}
/** 获取应用下的业务对象目录及完整字段定义。 */
export async function listPlatformEntities(
client: KyInstance,
corpId: string,
platformId: string
): Promise<DatalinkEntity[]> {
const normalizedId = platformId.startsWith("$") ? platformId : `$${platformId}`;
const response = await client.post(`api/v2/datalink/entity/platformId/${normalizedId}`, {
searchParams: { corpId },
// 该 POST 即使没有筛选条件也要求发送空 JSON body;前端会发送 {}。
json: {},
});
const json = asRecord(await response.json());
const rawItems = Array.isArray(json.items)
? json.items
: Array.isArray(asRecord(json.value).items)
? asRecord(json.value).items
: [];
return rawItems.map(parseEntity);
}
/** 分页检索指定业务对象的记录。filterBy 使用 DataLink 原生表达式。 */
export async function searchEntityRecords(
client: KyInstance,
corpId: string,
entityId: string,
query: DatalinkRecordQuery = {}
): Promise<DatalinkRecordPage> {
const normalizedId = entityId.startsWith("$") ? entityId : `$${entityId}`;
const limit = {
start: query.start ?? 0,
count: query.count ?? 20,
};
const nativeQuery: Record<string, unknown> = {
filterBy: query.filterBy?.trim() || "(active.in(true,false))",
limit,
};
if (query.orderBy !== undefined) nativeQuery.orderBy = query.orderBy;
const response = await client.post(
`api/v2/datalink/searchPlatformDataLinkWithChild/${normalizedId}`,
{
searchParams: { corpId },
json: { query: nativeQuery, entityId },
}
);
const json = asRecord(await response.json());
const payload = asRecord(json.items && !Array.isArray(json.items) ? json.items : json.value ?? json);
const rawData = Array.isArray(payload.data)
? payload.data
: Array.isArray(payload.items)
? payload.items
: Array.isArray(json.items)
? json.items
: [];
return {
total: numberOr(payload.total ?? json.total, rawData.length),
data: rawData.filter((item): item is DatalinkRecord => item !== null && typeof item === "object"),
actions: Array.isArray(payload.actions) ? payload.actions : [],
components: Array.isArray(payload.components) ? payload.components : [],
path: payload.path,
template: payload.template,
};
}
/** 查询对象导入任务状态。 */
export async function listImportJobs(
client: KyInstance,
corpId: string,
entityId: string
): Promise<DatalinkImportJob[]> {
const response = await client.get("api/engine/easo/batchJobs", {
searchParams: { entityId, corpId },
});
const json = asRecord(await response.json());
const items = json.items ?? asRecord(json.value).items ?? json.value ?? [];
return Array.isArray(items) ? items.filter((item): item is DatalinkImportJob => item !== null && typeof item === "object") : [];
}
/** 查询对象最近一次 Excel 导入结果。 */
export async function getImportResult(
client: KyInstance,
corpId: string,
entityId: string
): Promise<Record<string, unknown>> {
const normalizedId = entityId.startsWith("$") ? entityId : `$${entityId}`;
const response = await client.get(`api/v1/datalink/excel/import/result/${normalizedId}`, {
searchParams: { entityId, corpId },
});
return asRecord(await response.json());
}
/** 切换业务对象记录的停启用状态 (active: true <-> false)。若未指定 state 则自动反转当前状态。 */
export async function toggleRecordState(
client: KyInstance,
corpId: string,
recordId: string,
state?: boolean
): Promise<{ recordId: string; active: boolean }> {
const normalizedId = recordId.startsWith("$") ? recordId : `$${recordId}`;
const bareId = recordId.startsWith("$") ? recordId.slice(1) : recordId;
let targetState = state;
if (targetState === undefined) {
const detail = await getRecordDetail(client, corpId, recordId);
const record = ((detail.dataLink ?? (detail as any).data?.dataLink ?? detail) as Record<string, unknown>);
targetState = !(record.active ?? true);
}
await client.put(`api/supplier/v3/contract/${normalizedId}/state`, {
searchParams: { corpId },
json: { id: bareId, state: targetState },
});
return { recordId: bareId, active: targetState };
}
/** 获取单条业务对象记录的完整详情(包含展示模板、字段值、可见性及审批历史等)。 */
export async function getRecordDetail(
client: KyInstance,
corpId: string,
recordId: string
): Promise<DatalinkRecordDetail> {
const normalizedId = recordId.startsWith("$") ? recordId : `$${recordId}`;
const bareId = recordId.startsWith("$") ? recordId.slice(1) : recordId;
const response = await client.get(`api/v2/datalink/detail/${normalizedId}/$DETAIL`, {
searchParams: {
dataLinkId: bareId,
type: "DETAIL",
corpId,
},
});
const json = asRecord(await response.json());
return (json.value ?? json.data ?? json) as DatalinkRecordDetail;
}
/** 获取业务对象编辑表单的字段结构定义。 */
export async function getRecordFormSchema(
client: KyInstance,
corpId: string,
entityId: string
): Promise<Record<string, unknown>> {
const normalizedId = entityId.startsWith("$") ? entityId : `$${entityId}`;
const bareId = entityId.startsWith("$") ? entityId.slice(1) : entityId;
const response = await client.get(`api/v2/datalink/entityEdit/entityForm/${normalizedId}/$true`, {
searchParams: {
entityId: bareId,
isInsert: "true",
needFormula: "true",
corpId,
},
});
return asRecord(await response.json());
}
/** 编辑更新业务对象记录字段。 */
export async function editRecord(
client: KyInstance,
corpId: string,
payload: DatalinkRecordEditPayload
): Promise<Record<string, unknown>> {
const bareEntityId = payload.dataLinkEntityId.startsWith("$")
? payload.dataLinkEntityId.slice(1)
: payload.dataLinkEntityId;
const bareRecordId = payload.dataLinkId.startsWith("$")
? payload.dataLinkId.slice(1)
: payload.dataLinkId;
const response = await client.post("api/v2/datalink/entityEdit/edit", {
searchParams: { corpId },
json: {
...payload,
dataLinkEntityId: bareEntityId,
dataLinkId: bareRecordId,
},
});
const json = asRecord(await response.json());
return (json.value ?? json.data ?? json) as Record<string, unknown>;
}
/** 重算业务对象记录下的台账信息。 */
export async function recomputeRecordLedger(
client: KyInstance,
corpId: string,
recordId: string
): Promise<Record<string, unknown>> {
const normalizedId = recordId.startsWith("$") ? recordId : `$${recordId}`;
const response = await client.post(`api/v2/ledger/recompute/${normalizedId}`, {
searchParams: { corpId },
});
return asRecord(await response.json());
}
+171
View File
@@ -0,0 +1,171 @@
import { describe, expect, test } from "bun:test";
import {
editRecord,
getPlatform,
getRecordDetail,
listPlatformEntities,
listPlatforms,
recomputeRecordLedger,
searchEntityRecords,
toggleRecordState,
} from "./api.js";
import { buildKeywordFilter, selectRecordFields } from "./services.js";
const platform = {
id: "platform-1",
name: "业务应用",
corporationId: "corp-1",
active: true,
adminIds: ["staff-1"],
};
describe("DataLink Domain - 应用、业务对象与记录查询", () => {
test("列出应用并为权限数组提供稳定默认值", async () => {
const client = {
get: async (url: string, options: any) => {
expect(url).toBe("api/v2/datalink/platform/search");
expect(options.searchParams).toEqual({ scope: "enable", corpId: "corp-1" });
return { json: async () => ({ items: [platform] }) };
},
} as any;
const result = await listPlatforms(client, "corp-1");
expect(result[0]?.name).toBe("业务应用");
expect(result[0]?.staffIds).toEqual([]);
expect(result[0]?.departmentIds).toEqual([]);
});
test("获取应用详情时请求管理员关联", async () => {
const client = {
get: async (url: string, options: any) => {
expect(url).toBe("api/v2/datalink/platform/$platform-1");
expect(options.searchParams).toBeInstanceOf(URLSearchParams);
expect(options.searchParams.get("id")).toBe("platform-1");
expect(options.searchParams.getAll("join")).toEqual([
"icon.fileId,fileId,/v1/attachment/attachments",
"adminIds,admin,/v1/organization/staffs",
]);
expect(options.searchParams.get("corpId")).toBe("corp-1");
return { json: async () => ({ value: { ...platform, staffIds: ["staff-1"], roleIds: ["role-1"], departmentIds: [], admin: [{ id: "staff-1", name: "管理员", code: "A-1", cellphone: "13800000000" }] } }) };
},
} as any;
const result = await getPlatform(client, "corp-1", "platform-1");
expect(result.adminIds).toEqual(["staff-1"]);
expect(result.roleIds).toEqual(["role-1"]);
expect(result.admin).toEqual([{ id: "staff-1", name: "管理员", code: "A-1", active: undefined }]);
expect(JSON.stringify(result)).not.toContain("13800000000");
});
test("获取对象字段元数据并保留扩展属性", async () => {
const client = {
post: async (url: string, options: any) => {
expect(url).toBe("api/v2/datalink/entity/platformId/$platform-1");
expect(options.searchParams.corpId).toBe("corp-1");
expect(options.json).toEqual({});
return { json: async () => ({ items: [{ id: "entity-1", name: "供应商", fields: [{ name: "code", label: "编码", type: "text", optional: false, customFlag: true }] }] }) };
},
} as any;
const result = await listPlatformEntities(client, "corp-1", "platform-1");
expect(result[0]?.fields[0]?.label).toBe("编码");
expect(result[0]?.fields[0]?.customFlag).toBe(true);
});
test("分页查询记录并生成标准化分页结果", async () => {
const client = {
post: async (url: string, options: any) => {
expect(url).toBe("api/v2/datalink/searchPlatformDataLinkWithChild/$entity-1");
expect(options.searchParams.corpId).toBe("corp-1");
expect(options.json).toEqual({
entityId: "entity-1",
query: { filterBy: 'code == "A-1"', limit: { start: 10, count: 5 } },
});
return { json: async () => ({ items: { total: 1, data: [{ id: "record-1", dataLink: { code: "A-1" } }] } }) };
},
} as any;
const result = await searchEntityRecords(client, "corp-1", "entity-1", { start: 10, count: 5, filterBy: 'code == "A-1"' });
expect(result.total).toBe(1);
expect(result.data[0]?.dataLink?.code).toBe("A-1");
});
test("关键词过滤和字段投影可用于通用 CLI 查询", () => {
expect(buildKeywordFilter('A"1')).toContain('A\\"1');
expect(selectRecordFields({ id: "r-1", dataLink: { code: "A-1" } }, ["编码"], [{ name: "code", label: "编码", type: "text" }])).toEqual({ id: "r-1", dataLink: { 编码: "A-1" } });
});
test("切换记录停启用状态调用 PUT contract state 接口", async () => {
let calledUrl = "";
let calledParams: any = null;
let calledJson: any = null;
const client = {
get: async () => ({
json: async () => ({ value: { id: "record-1", active: true } }),
}),
put: async (url: string, options: any) => {
calledUrl = url;
calledParams = options.searchParams;
calledJson = options.json;
return { status: 204 };
},
} as any;
const res = await toggleRecordState(client, "corp-1", "record-1");
expect(calledUrl).toBe("api/supplier/v3/contract/$record-1/state");
expect(calledParams).toEqual({ corpId: "corp-1" });
expect(calledJson).toEqual({ id: "record-1", state: false });
expect(res).toEqual({ recordId: "record-1", active: false });
});
test("获取记录详情调用 GET datalink detail 接口", async () => {
const client = {
get: async (url: string, options: any) => {
expect(url).toBe("api/v2/datalink/detail/$record-1/$DETAIL");
expect(options.searchParams).toEqual({
dataLinkId: "record-1",
type: "DETAIL",
corpId: "corp-1",
});
return { json: async () => ({ value: { id: "record-1", name: "记录1" } }) };
},
} as any;
const result = await getRecordDetail(client, "corp-1", "record-1");
expect((result as any).name).toBe("记录1");
});
test("编辑业务对象记录调用 POST entityEdit edit 接口", async () => {
const client = {
post: async (url: string, options: any) => {
expect(url).toBe("api/v2/datalink/entityEdit/edit");
expect(options.searchParams).toEqual({ corpId: "corp-1" });
expect(options.json.dataLinkEntityId).toBe("entity-1");
expect(options.json.dataLinkId).toBe("record-1");
expect(options.json.form).toEqual({ name: "新名称" });
return { json: async () => ({ value: { id: "record-1", name: "新名称" } }) };
},
} as any;
const result = await editRecord(client, "corp-1", {
dataLinkEntityId: "$entity-1",
dataLinkId: "$record-1",
form: { name: "新名称" },
});
expect((result as any).name).toBe("新名称");
});
test("重算台账调用 POST ledger recompute 接口", async () => {
const client = {
post: async (url: string, options: any) => {
expect(url).toBe("api/v2/ledger/recompute/$record-1");
expect(options.searchParams).toEqual({ corpId: "corp-1" });
return { json: async () => ({ id: "ok" }) };
},
} as any;
const result = await recomputeRecordLedger(client, "corp-1", "record-1");
expect(result.id).toBe("ok");
});
});
+52
View File
@@ -0,0 +1,52 @@
import type { KyInstance } from "ky";
import * as api from "./api.js";
import type { DatalinkEntity, DatalinkField, DatalinkPlatformDetail } from "./types.js";
function matches(value: unknown, target: string): boolean {
return typeof value === "string" && value.toLowerCase() === target.toLowerCase();
}
export async function resolvePlatform(
client: KyInstance,
corpId: string,
target: string
): Promise<DatalinkPlatformDetail | undefined> {
const platforms = await api.listPlatforms(client, corpId);
const found = platforms.find((platform) =>
[platform.id, platform.name, platform.code].some((value) => matches(value, target))
);
return found ? api.getPlatform(client, corpId, found.id) : undefined;
}
export async function resolveEntity(
client: KyInstance,
corpId: string,
platform: DatalinkPlatformDetail,
target: string
): Promise<DatalinkEntity | undefined> {
const entities = await api.listPlatformEntities(client, corpId, platform.id);
return entities.find((entity) =>
[entity.id, entity.name, entity.code].some((value) => matches(value, target))
);
}
export function buildKeywordFilter(keyword: string): string {
const escaped = keyword.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
return `(name.containsIgnoreCase("${escaped}")||code.containsIgnoreCase("${escaped}"))&&(active.in(true,false))`;
}
export function selectRecordFields(record: Record<string, unknown>, fields: string[], definitions: DatalinkField[] = []): Record<string, unknown> {
if (fields.length === 0) return record;
const dataLink = record.dataLink && typeof record.dataLink === "object" && !Array.isArray(record.dataLink)
? (record.dataLink as Record<string, unknown>)
: record;
const selected: Record<string, unknown> = {};
for (const selector of fields) {
const definition = definitions.find((field) => field.name === selector || field.label === selector);
const sourceName = definition?.name ?? selector;
if (sourceName in dataLink) selected[definition?.label || selector] = dataLink[sourceName];
}
return record.dataLink && typeof record.dataLink === "object"
? { ...record, dataLink: selected }
: selected;
}
+136
View File
@@ -0,0 +1,136 @@
import { z } from "zod";
import * as api from "./api.js";
const clientSchema = z.object({
corp: z.object({ credentials: z.object({ corpId: z.string() }) }).passthrough(),
ekbClient: z.any(),
});
export const datalinkTools = [
{
name: "datalink_platform_list",
description: "列出当前企业账号可见的启用自建应用(可传入 all=true 查看包含模板平台的完整列表)",
parameters: z.object({
all: z.boolean().optional().describe("是否拉取包含 HAB 模板与全量平台列表"),
}),
handler: async (clients: unknown, params: { all?: boolean } = {}) => {
const { corp, ekbClient } = clientSchema.parse(clients);
const platforms = params.all
? await api.listAllPlatforms(ekbClient, corp.credentials.corpId)
: await api.listPlatforms(ekbClient, corp.credentials.corpId);
return { platforms };
},
},
{
name: "datalink_platform_get",
description: "获取自建应用详情以及应用管理员、人员、角色和部门可见权限",
parameters: z.object({ platformId: z.string().describe("自建应用 ID") }),
handler: async (clients: unknown, params: { platformId: string }) => {
const { corp, ekbClient } = clientSchema.parse(clients);
return api.getPlatform(ekbClient, corp.credentials.corpId, params.platformId);
},
},
{
name: "datalink_entity_list",
description: "获取一个自建应用下的业务对象目录、字段、操作和可见性配置",
parameters: z.object({ platformId: z.string().describe("自建应用 ID") }),
handler: async (clients: unknown, params: { platformId: string }) => {
const { corp, ekbClient } = clientSchema.parse(clients);
return { entities: await api.listPlatformEntities(ekbClient, corp.credentials.corpId, params.platformId) };
},
},
{
name: "datalink_record_search",
description: "分页检索业务对象记录,支持 DataLink filterBy 表达式",
parameters: z.object({
entityId: z.string().describe("业务对象 ID"),
start: z.number().int().min(0).optional(),
count: z.number().int().min(1).max(1000).optional(),
filterBy: z.string().optional().describe("DataLink 原生过滤表达式"),
}),
handler: async (clients: unknown, params: { entityId: string; start?: number; count?: number; filterBy?: string }) => {
const { corp, ekbClient } = clientSchema.parse(clients);
return api.searchEntityRecords(ekbClient, corp.credentials.corpId, params.entityId, params);
},
},
{
name: "datalink_import_jobs",
description: "查看业务对象的导入任务和最近导入结果",
parameters: z.object({ entityId: z.string().describe("业务对象 ID") }),
handler: async (clients: unknown, params: { entityId: string }) => {
const { corp, ekbClient } = clientSchema.parse(clients);
const [jobs, result] = await Promise.all([
api.listImportJobs(ekbClient, corp.credentials.corpId, params.entityId),
api.getImportResult(ekbClient, corp.credentials.corpId, params.entityId),
]);
return { jobs, latestResult: result };
},
},
{
name: "datalink_record_get",
description: "获取单条业务对象记录的完整详情(模板、字段值、可见性及历史等)",
parameters: z.object({
recordId: z.string().describe("业务对象记录 ID (dataLinkId)"),
}),
handler: async (clients: unknown, params: { recordId: string }) => {
const { corp, ekbClient } = clientSchema.parse(clients);
return api.getRecordDetail(ekbClient, corp.credentials.corpId, params.recordId);
},
},
{
name: "datalink_record_toggle",
description: "切换业务对象记录的停启用状态 (active: true <-> false)",
parameters: z.object({
recordId: z.string().describe("业务对象记录 ID (dataLinkId)"),
state: z.boolean().optional().describe("目标状态 (true 为启用,false 为停用,不传则自动翻转)"),
}),
handler: async (clients: unknown, params: { recordId: string; state?: boolean }) => {
const { corp, ekbClient } = clientSchema.parse(clients);
const result = await api.toggleRecordState(ekbClient, corp.credentials.corpId, params.recordId, params.state);
return { success: true, ...result };
},
},
{
name: "datalink_record_edit",
description: "编辑更新业务对象记录的字段值",
parameters: z.object({
entityId: z.string().describe("业务对象 ID"),
recordId: z.string().describe("业务对象记录 ID (dataLinkId)"),
form: z.record(z.string(), z.unknown()).describe("待更新的表单字段键值对"),
active: z.boolean().optional().describe("停启用状态"),
visibility: z.record(z.string(), z.unknown()).optional().describe("可见性配置"),
}),
handler: async (
clients: unknown,
params: {
entityId: string;
recordId: string;
form: Record<string, unknown>;
active?: boolean;
visibility?: Record<string, unknown>;
}
) => {
const { corp, ekbClient } = clientSchema.parse(clients);
return api.editRecord(ekbClient, corp.credentials.corpId, {
dataLinkEntityId: params.entityId,
dataLinkId: params.recordId,
form: params.form,
active: params.active,
visibility: params.visibility,
});
},
},
{
name: "datalink_record_recompute",
description: "重新计算指定业务对象记录下的全部台账信息",
parameters: z.object({
recordId: z.string().describe("业务对象记录 ID (dataLinkId)"),
}),
handler: async (clients: unknown, params: { recordId: string }) => {
const { corp, ekbClient } = clientSchema.parse(clients);
return api.recomputeRecordLedger(ekbClient, corp.credentials.corpId, params.recordId);
},
},
];
export type DatalinkTool = (typeof datalinkTools)[number];
+121
View File
@@ -0,0 +1,121 @@
import { z } from "zod";
import { PlatformSchema } from "../platform/types.js";
const NullableBoolean = z.boolean().nullable().optional();
/** DataLink 字段元数据。保留服务端未建模的扩展字段,避免丢失配置。 */
export const DatalinkFieldSchema = z
.object({
name: z.string().default(""),
label: z.string().default(""),
type: z.string().default("text"),
optional: NullableBoolean,
regex: z.string().nullable().optional(),
source: z.string().nullable().optional(),
formula: z.boolean().nullable().optional(),
calculation: z.record(z.string(), z.unknown()).nullable().optional(),
entity: z.string().nullable().optional(),
withTime: z.boolean().nullable().optional(),
scale: z.number().nullable().optional(),
unit: z.string().nullable().optional(),
index: z.boolean().nullable().optional(),
systemField: z.boolean().nullable().optional(),
})
.passthrough();
export const DatalinkEntitySchema = z
.object({
id: z.string(),
code: z.string().default(""),
name: z.string().default(""),
type: z.string().default(""),
active: z.boolean().default(true),
fields: z.array(DatalinkFieldSchema).default([]),
actions: z.array(z.unknown()).default([]),
importMethod: z.array(z.string()).default([]),
visibility: z.unknown().optional(),
homeVisibility: z.unknown().optional(),
exportVisibility: z.unknown().optional(),
dataFilter: z.unknown().optional(),
})
.passthrough();
export const DatalinkPlatformDetailSchema = PlatformSchema.passthrough().extend({
staffIds: z.array(z.string()).nullish().transform((value) => value ?? []),
roleIds: z.array(z.string()).nullish().transform((value) => value ?? []),
departmentIds: z.array(z.string()).nullish().transform((value) => value ?? []),
departmentsIncludeChildren: z.boolean().nullish().transform((value) => value ?? false),
});
export interface DatalinkRecordQuery {
start?: number;
count?: number;
filterBy?: string;
/** 服务端支持的排序表达式,原样透传。 */
orderBy?: unknown;
}
export interface DatalinkRecord {
id?: string;
entityId?: string;
dataLink?: Record<string, unknown>;
fieldAuth?: Record<string, unknown>;
visibility?: unknown;
active?: boolean;
ownerId?: string;
createTime?: number | string;
updateTime?: number | string;
actions?: unknown[];
source?: unknown;
sourceId?: unknown;
[key: string]: unknown;
}
export interface DatalinkRecordPage {
total: number;
data: DatalinkRecord[];
actions: unknown[];
components: unknown[];
path: unknown;
template: unknown;
}
export interface DatalinkImportJob {
[key: string]: unknown;
}
export type DatalinkField = z.infer<typeof DatalinkFieldSchema>;
export type DatalinkEntity = z.infer<typeof DatalinkEntitySchema>;
export type DatalinkPlatformDetail = z.infer<typeof DatalinkPlatformDetailSchema>;
export interface DatalinkPermissionSnapshot {
platform: DatalinkPlatformDetail;
entity?: DatalinkEntity;
}
export interface DatalinkRecordDetail {
dataLink?: DatalinkRecord;
template?: unknown;
entity?: unknown;
actions?: unknown[];
flowCounts?: Record<string, unknown>;
ledger?: Record<string, unknown>;
ledgers?: unknown[];
[key: string]: unknown;
}
export interface DatalinkRecordEditPayload {
dataLinkEntityId: string;
dataLinkId: string;
active?: boolean;
form: Record<string, unknown>;
visibility?: {
fullVisible?: boolean;
staffs?: string[];
roles?: string[];
departments?: string[];
departmentsIncludeChildren?: boolean;
[key: string]: unknown;
};
[key: string]: unknown;
}
+69
View File
@@ -0,0 +1,69 @@
# 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="办公杂费" --dry-run
hose-use feetype create --name="办公杂费" --yes
hose-use feetype create --name="市内打车" --parent="交通费" --yes
# 修改费用类型
hose-use feetype update 市内打车 --desc="滴滴企业版" --yes
# 停用与启用
hose-use feetype disable 市内打车 --yes
hose-use feetype enable 市内打车 --yes
# 移动层级
hose-use feetype move 市内打车 --parent="差旅费用" --yes
hose-use feetype move 市内打车 --parent=root --yes
# 查看表单字段配置
hose-use feetype fields 交通费
```
+294
View File
@@ -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"
);
}
}
+74
View File
@@ -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);
});
});
+548
View File
@@ -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);
},
},
];
+169
View File
@@ -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;
}
+34
View File
@@ -0,0 +1,34 @@
# Menu 域说明(桌面端主框架菜单与工作台业务应用)
Menu 域负责获取合思桌面端全站主框架导航菜单树(`MAIN_FRAME_DESKTOP`)以及业务工作台【应用管理】下的业务应用集成列表。
## 业务背景
在合思产品体系中:
1. **应用中心 -> 自建应用**(由 `platform` / `datalink` 域负责):属于开发者与 PaaS 容器层(`groupType: NORMAL`),主要用于自定义实体建模和脚本工作流;
2. **顶层一级导航【应用管理】**(由本 `menu` 域负责):属于用户业务工作台层,聚合了租户开通的**全部前台业务落地应用**,既包括挂载了对象视图的自建应用(如新转转集团、差旅申请、项目预算),也包含官方业务套件(如用车补贴 `SCGY:...`、用车制度)与金融扩展(如 E商卡管理)。
## 核心接口
| 接口 | 方法 | 说明 |
|---|---|---|
| `api/menu/v2/menus/byDeviceTypeAndAppId/$MAIN_FRAME_DESKTOP` | `GET` | 获取桌面端全站主框架导航菜单树 |
## 代码结构
```text
src/domains/menu/
├── types.ts # 菜单树节点与 WorkbenchApp 视图模型
├── api.ts # HTTP 传输层
└── tools.ts # 服务层聚合函数与导出
```
## CLI 对应命令
```bash
# 查看顶层【应用管理】下的业务应用列表
hose-use app list [--corp=<id>]
# 查看桌面端主框架菜单树
hose-use menu tree [--corp=<id>]
```
+125
View File
@@ -0,0 +1,125 @@
import { describe, expect, test } from "bun:test";
import {
fetchDesktopMenuTree,
fetchWorkbenchApps,
fetchAppCenterMenus,
} from "./api.js";
const mockMenuPayload = {
items: [
{
id: "newHomePage",
label: "首页",
appId: "100-home",
href: "/home",
children: [],
},
{
id: "dataLink",
label: "应用管理",
appId: "160-datalink-platform",
children: [
{
id: "SCGY:corp-test",
label: "用车补贴",
code: "dataLinkItem",
href: "/third-party-item/SCGY:corp-test",
appId: "160-datalink-platform",
type: "MENU",
fromWay: "SYSTEM",
},
{
id: "ID01PIqCA1Di0v",
label: "用车制度",
code: "dataLinkItem",
href: "/third-party-item/ID01PIqCA1Di0v",
appId: "160-datalink-platform",
type: "MENU",
fromWay: "SYSTEM",
},
{
id: "ID01RKbEvQsWbd",
label: "新转转集团",
code: "dataLinkItem",
href: "/third-party-item/ID01RKbEvQsWbd",
appId: "160-datalink-platform",
type: "MENU",
fromWay: "SYSTEM",
},
],
},
{
id: "appcenter",
label: "应用中心",
appId: "150-appcenter",
children: [
{
id: "selfBuiltApplication",
label: "自建应用",
code: "selfBuiltApplication",
href: "/expense-center-new/self_built_app",
},
],
},
],
};
describe("Domains/Menu - API 单元测试", () => {
test("fetchDesktopMenuTree 成功解析全站桌面端菜单响应", async () => {
const mockClient = {
get: async (url: string, opts: any) => {
expect(url).toBe("api/menu/v2/menus/byDeviceTypeAndAppId/$MAIN_FRAME_DESKTOP");
expect(opts.searchParams.corpId).toBe("corp-test");
return {
json: async () => mockMenuPayload,
};
},
} as any;
const items = await fetchDesktopMenuTree(mockClient, "corp-test");
expect(items.length).toBe(3);
expect(items[0].label).toBe("首页");
expect(items[1].label).toBe("应用管理");
expect(items[2].label).toBe("应用中心");
});
test("fetchWorkbenchApps 成功提取应用管理下的 7/N 个业务应用", async () => {
const mockClient = {
get: async () => ({
json: async () => mockMenuPayload,
}),
} as any;
const apps = await fetchWorkbenchApps(mockClient, "corp-test");
expect(apps.length).toBe(3);
expect(apps[0].id).toBe("SCGY:corp-test");
expect(apps[0].name).toBe("用车补贴");
expect(apps[0].href).toBe("/third-party-item/SCGY:corp-test");
expect(apps[1].name).toBe("用车制度");
expect(apps[2].name).toBe("新转转集团");
});
test("fetchAppCenterMenus 成功提取应用中心子栏目", async () => {
const mockClient = {
get: async () => ({
json: async () => mockMenuPayload,
}),
} as any;
const menus = await fetchAppCenterMenus(mockClient, "corp-test");
expect(menus.length).toBe(1);
expect(menus[0].id).toBe("selfBuiltApplication");
expect(menus[0].label).toBe("自建应用");
});
test("当菜单树无 dataLink 节点时安全返回空数组", async () => {
const mockClient = {
get: async () => ({
json: async () => ({ items: [] }),
}),
} as any;
const apps = await fetchWorkbenchApps(mockClient, "corp-test");
expect(apps).toEqual([]);
});
});
+62
View File
@@ -0,0 +1,62 @@
import type { KyInstance } from "ky";
import { DesktopMenuResponseSchema, type MenuItem, type WorkbenchApp } from "./types.js";
/** 获取桌面端全站主框架导航菜单树 */
export async function fetchDesktopMenuTree(
client: KyInstance,
corpId: string
): Promise<MenuItem[]> {
const response = await client.get(
"api/menu/v2/menus/byDeviceTypeAndAppId/$MAIN_FRAME_DESKTOP",
{
searchParams: { corpId },
}
);
const json = await response.json();
const parsed = DesktopMenuResponseSchema.parse(json);
return parsed.items;
}
/** 获取工作台【应用管理】下的业务应用列表(包括套件、模板与自建应用) */
export async function fetchWorkbenchApps(
client: KyInstance,
corpId: string
): Promise<WorkbenchApp[]> {
const items = await fetchDesktopMenuTree(client, corpId);
const dataLinkNode = items.find(
(i) =>
i.id === "dataLink" ||
i.appId === "160-datalink-platform" ||
i.label === "应用管理"
);
if (!dataLinkNode || !Array.isArray(dataLinkNode.children)) {
return [];
}
return dataLinkNode.children.map((child) => ({
id: child.id,
name: child.label,
code: child.code || "dataLinkItem",
href: child.href || `/third-party-item/${child.id}`,
appId: child.appId || "160-datalink-platform",
type: child.type || "MENU",
fromWay: child.fromWay || "SYSTEM",
}));
}
/** 获取【应用中心】下的子栏目菜单列表(如应用商店、已购应用、自建应用等) */
export async function fetchAppCenterMenus(
client: KyInstance,
corpId: string
): Promise<MenuItem[]> {
const items = await fetchDesktopMenuTree(client, corpId);
const appCenterNode = items.find(
(i) =>
i.id === "appcenter" ||
i.appId === "150-appcenter" ||
i.label === "应用中心"
);
return appCenterNode?.children || [];
}
+35
View File
@@ -0,0 +1,35 @@
import { createEkbClient } from "../../core/auth/ekb.js";
import type { CorpConfig } from "../../core/config/types.js";
import {
fetchDesktopMenuTree,
fetchWorkbenchApps,
fetchAppCenterMenus,
} from "./api.js";
import type { MenuItem, WorkbenchApp } from "./types.js";
/** 获取桌面端工作台【应用管理】下的业务应用列表 */
export async function fetchWorkbenchAppsList(
corp: CorpConfig
): Promise<WorkbenchApp[]> {
const client = await createEkbClient(corp);
const corpId = corp.corpId || corp.credentials.corpId;
return fetchWorkbenchApps(client, corpId);
}
/** 获取桌面端全站主框架导航菜单树 */
export async function fetchDesktopMenus(
corp: CorpConfig
): Promise<MenuItem[]> {
const client = await createEkbClient(corp);
const corpId = corp.corpId || corp.credentials.corpId;
return fetchDesktopMenuTree(client, corpId);
}
/** 获取【应用中心】下的子栏目 */
export async function fetchAppCenterSubMenus(
corp: CorpConfig
): Promise<MenuItem[]> {
const client = await createEkbClient(corp);
const corpId = corp.corpId || corp.credentials.corpId;
return fetchAppCenterMenus(client, corpId);
}
+47
View File
@@ -0,0 +1,47 @@
import { z } from "zod";
export interface MenuItem {
id: string;
label: string;
code?: string | null;
href?: string | null;
appId?: string | null;
type?: string | null;
fromWay?: string | null;
icon?: string | null;
iconFill?: string | null;
selected?: boolean | null;
children?: MenuItem[];
}
export const MenuItemSchema: z.ZodType<MenuItem> = z.lazy(() =>
z.object({
id: z.string(),
label: z.string().default(""),
code: z.string().nullable().optional(),
href: z.string().nullable().optional(),
appId: z.string().nullable().optional(),
type: z.string().nullable().optional(),
fromWay: z.string().nullable().optional(),
icon: z.string().nullable().optional(),
iconFill: z.string().nullable().optional(),
selected: z.boolean().nullable().optional(),
children: z.array(MenuItemSchema).optional().default([]),
})
);
export const DesktopMenuResponseSchema = z.object({
items: z.array(MenuItemSchema).default([]),
});
export type DesktopMenuResponse = z.infer<typeof DesktopMenuResponseSchema>;
export const WorkbenchAppSchema = z.object({
id: z.string().describe("业务应用 ID (如 SCGY:corpId 或 自建应用物理ID)"),
name: z.string().describe("应用名称"),
code: z.string().optional().describe("功能代码 (如 dataLinkItem)"),
href: z.string().describe("Web 端直达路由路径"),
appId: z.string().default("160-datalink-platform").describe("所属主框架模块"),
type: z.string().optional().describe("菜单或应用类型"),
fromWay: z.string().optional().describe("来源方式 (如 SYSTEM, MANUAL)"),
});
export type WorkbenchApp = z.infer<typeof WorkbenchAppSchema>;
+1 -1
View File
@@ -1,6 +1,6 @@
# Platform 域说明
Platform 域负责自建应用(DataLink Platform)和工作流(EASO/Piper)相关能力。
Platform 域负责工作流(EASO/Piper)以及自建应用容器的兼容能力。自建应用下的业务对象、字段、记录和权限查询统一放在 [DataLink 域](../datalink/README.datalink.md)。
## 代码结构
+49
View File
@@ -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(
+48
View File
@@ -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 };
}
}
+153
View File
@@ -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("网络错误");
});
});
+117
View File
@@ -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;
}
+17
View File
@@ -0,0 +1,17 @@
# Store / OpenAPI Keys 域说明
本域负责企业 OpenAPI 接入凭证提取以及应用商店(Unity Store)/ 企业已购应用探查能力。
## 架构
- `api.ts`:传输层,负责与 `app.ekuaibao.com/api/innerapi` 以及 `unity.ekuaibao.com/api/store` 的 HTTP 交互。
- `tools.ts`:业务层,负责换票与参数组装,供 CLI 与外部调用。
- `types.ts`:Zod 模式与 TypeScript 类型定义。
## 关键接口
- `listOpenApiKeys`: 查询企业 OpenAPI 密钥列表(appKey / appSecurity / 备注 / 状态)
- `getOpenConfig`: 查询企业免登重定向配置
- `listClientGoods`: 查询当前租户已购/已开通的应用清单(状态、到期时间、绑定能力)
- `searchStoreGoods`: 检索合思应用商店全部上架应用
- `getGoodsDetail`: 获取指定应用的详细信息、套餐与规格
+145
View File
@@ -0,0 +1,145 @@
import { describe, expect, test } from "bun:test";
import {
listOpenApiKeys,
getOpenConfig,
listClientGoods,
searchStoreGoods,
getGoodsDetail,
} from "./api.js";
describe("Domains/Store - API 单元测试", () => {
test("listOpenApiKeys 解析规范的企业 OpenAPI 密钥响应", async () => {
const mockClient = {
get: async (url: string, opts: any) => {
expect(url).toBe("api/innerapi/v1/key");
expect(opts.searchParams.corpId).toBe("corp-123");
return {
json: async () => ({
count: 1,
items: [
{
id: "key-1",
name: "测试密钥",
appKey: "test-app-key",
appSecurity: "test-app-security",
active: true,
createTime: 1700000000000,
updateTime: 1700000000000,
},
],
}),
};
},
} as any;
const keys = await listOpenApiKeys(mockClient, "corp-123");
expect(keys.length).toBe(1);
expect(keys[0].id).toBe("key-1");
expect(keys[0].name).toBe("测试密钥");
expect(keys[0].appKey).toBe("test-app-key");
expect(keys[0].appSecurity).toBe("test-app-security");
expect(keys[0].active).toBe(true);
});
test("getOpenConfig 解析免登重定向配置响应", async () => {
const mockClient = {
get: async (url: string, opts: any) => {
expect(url).toBe("api/innerapi/v1/openConfig");
expect(opts.searchParams.corpId).toBe("corp-123");
return {
json: async () => ({
items: [{ id: "cfg-1", url: "https://example.com/oauth" }],
}),
};
},
} as any;
const config = await getOpenConfig(mockClient, "corp-123");
expect(config.items.length).toBe(1);
expect(config.items[0].url).toBe("https://example.com/oauth");
});
test("listClientGoods 解析企业已购应用响应", async () => {
const mockClient = {
get: async (url: string, opts: any) => {
expect(url).toBe("api/store/client/goods");
expect(opts.searchParams.corpId).toBe("corp-123");
return {
json: async () => ({
value: {
items: [
{
id: "goods-1",
name: "开放接口(新)",
status: "OPENED",
hasConfig: true,
powers: [{ powerCode: "219904", powerName: "开放接口(新)" }],
},
],
},
}),
};
},
} as any;
const goods = await listClientGoods(mockClient, "corp-123");
expect(goods.length).toBe(1);
expect(goods[0].name).toBe("开放接口(新)");
expect(goods[0].status).toBe("OPENED");
expect(goods[0].hasConfig).toBe(true);
});
test("searchStoreGoods 解析全量应用搜索响应", async () => {
const mockClient = {
post: async (url: string, opts: any) => {
expect(url).toBe("api/store/goods");
expect(opts.searchParams.corpId).toBe("corp-123");
expect(opts.json.name).toBe("接口");
return {
json: async () => ({
value: {
total: 2,
items: [
{ id: "g-1", name: "通讯录接口", status: null },
{ id: "g-2", name: "开放接口(新)", status: "OPENED" },
],
},
}),
};
},
} as any;
const result = await searchStoreGoods(mockClient, "corp-123", { name: "接口" });
expect(result.total).toBe(2);
expect(result.items.length).toBe(2);
expect(result.items[0].name).toBe("通讯录接口");
expect(result.items[1].name).toBe("开放接口(新)");
});
test("getGoodsDetail 解析指定应用规格与详情", async () => {
const mockClient = {
get: async (url: string, opts: any) => {
expect(url).toBe("api/store/client/goods/detail/$goods-99");
expect(opts.searchParams.corpId).toBe("corp-123");
return {
json: async () => ({
value: {
id: "goods-99",
name: "合思商城",
status: "EXPIRE",
hasConfig: true,
configStyle: "SIDESLIP",
powers: [{ powerCode: "120209", powerName: "合思商城订购管理" }],
},
}),
};
},
} as any;
const detail = await getGoodsDetail(mockClient, "corp-123", "goods-99");
expect(detail.id).toBe("goods-99");
expect(detail.name).toBe("合思商城");
expect(detail.hasConfig).toBe(true);
expect(detail.configStyle).toBe("SIDESLIP");
});
});
+98
View File
@@ -0,0 +1,98 @@
import { z } from "zod";
import type { KyInstance } from "ky";
import {
OpenApiKeySchema,
OpenConfigSchema,
ClientGoodsSchema,
StoreGoodsItemSchema,
GoodsDetailSchema,
type OpenApiKey,
type OpenConfig,
type ClientGoods,
type StoreGoodsItem,
type GoodsDetail,
} from "./types.js";
// ── OpenAPI 密钥与配置接口 ───────────────────────────────────────────────────
export async function listOpenApiKeys(
ekbClient: KyInstance,
corpId: string
): Promise<OpenApiKey[]> {
const response = await ekbClient.get("api/innerapi/v1/key", {
searchParams: { corpId },
});
const json = (await response.json()) as { items?: unknown[]; count?: number };
const rawItems = json.items ?? [];
return z.array(OpenApiKeySchema).parse(rawItems);
}
export async function getOpenConfig(
ekbClient: KyInstance,
corpId: string
): Promise<OpenConfig> {
const response = await ekbClient.get("api/innerapi/v1/openConfig", {
searchParams: { corpId },
});
const json = await response.json();
return OpenConfigSchema.parse(json);
}
// ── 应用商店与已购应用接口 ───────────────────────────────────────────────────
export async function listClientGoods(
unityClient: KyInstance,
corpId: string,
options: { name?: string; isAll?: boolean } = {}
): Promise<ClientGoods[]> {
const response = await unityClient.get("api/store/client/goods", {
searchParams: {
corpId,
name: options.name ?? "",
isAll: String(options.isAll ?? false),
},
});
const json = (await response.json()) as any;
const items = json?.value?.items ?? json?.items ?? json?.value ?? [];
return z.array(ClientGoodsSchema).parse(items);
}
export async function searchStoreGoods(
unityClient: KyInstance,
corpId: string,
params: { name?: string; menuId?: string; start?: number; count?: number } = {}
): Promise<{ total: number; items: StoreGoodsItem[] }> {
const response = await unityClient.post("api/store/goods", {
searchParams: { corpId },
json: {
menuId: params.menuId ?? "",
start: params.start ?? 0,
count: params.count ?? 20,
orderType: "recommend",
name: params.name ?? "",
goodsId: "all",
labelId: [],
},
});
const json = (await response.json()) as any;
const value = json?.value ?? {};
const total = Number(value.total ?? 0);
const items = z.array(StoreGoodsItemSchema).parse(value.items ?? []);
return { total, items };
}
export async function getGoodsDetail(
unityClient: KyInstance,
corpId: string,
goodsId: string
): Promise<GoodsDetail> {
const normalizedId = goodsId.startsWith("$") ? goodsId : `$${goodsId}`;
const response = await unityClient.get(
`api/store/client/goods/detail/${normalizedId}`,
{
searchParams: { corpId },
}
);
const json = (await response.json()) as any;
return GoodsDetailSchema.parse(json?.value ?? {});
}
+74
View File
@@ -0,0 +1,74 @@
import { createEkbClient } from "../../core/auth/ekb.js";
import { getUnityClient } from "../../core/auth/easo.js";
import type { CorpConfig } from "../../core/config/types.js";
import {
listOpenApiKeys,
getOpenConfig,
listClientGoods,
searchStoreGoods,
getGoodsDetail,
} from "./api.js";
import type {
OpenApiKey,
OpenConfig,
ClientGoods,
StoreGoodsItem,
GoodsDetail,
} from "./types.js";
export async function fetchOpenApiKeys(corp: CorpConfig): Promise<OpenApiKey[]> {
const ekbClient = await createEkbClient(corp);
const corpId = corp.corpId || corp.credentials.corpId;
return listOpenApiKeys(ekbClient, corpId);
}
export async function fetchOpenConfig(corp: CorpConfig): Promise<OpenConfig> {
const ekbClient = await createEkbClient(corp);
const corpId = corp.corpId || corp.credentials.corpId;
return getOpenConfig(ekbClient, corpId);
}
export async function fetchClientGoods(
corp: CorpConfig,
options: { keyword?: string; isAll?: boolean } = {}
): Promise<ClientGoods[]> {
const { client: unityClient } = await getUnityClient(corp);
const corpId = corp.corpId || corp.credentials.corpId;
const items = await listClientGoods(unityClient, corpId, {
name: options.keyword,
isAll: options.isAll,
});
if (options.keyword && options.keyword.trim()) {
const kw = options.keyword.trim().toLowerCase();
return items.filter(
(item) =>
item.name.toLowerCase().includes(kw) ||
(item.summary && item.summary.toLowerCase().includes(kw))
);
}
return items;
}
export async function searchGoods(
corp: CorpConfig,
options: { keyword?: string; start?: number; count?: number } = {}
): Promise<{ total: number; items: StoreGoodsItem[] }> {
const { client: unityClient } = await getUnityClient(corp);
const corpId = corp.corpId || corp.credentials.corpId;
return searchStoreGoods(unityClient, corpId, {
name: options.keyword,
start: options.start,
count: options.count,
});
}
export async function fetchGoodsDetail(
corp: CorpConfig,
goodsId: string
): Promise<GoodsDetail> {
const { client: unityClient } = await getUnityClient(corp);
const corpId = corp.corpId || corp.credentials.corpId;
return getGoodsDetail(unityClient, corpId, goodsId);
}
+112
View File
@@ -0,0 +1,112 @@
import { z } from "zod";
// ── OpenAPI 密钥模型 ─────────────────────────────────────────────────────────
export const OpenApiKeySchema = z.object({
id: z.string(),
name: z.string().nullish().default(""),
appKey: z.string(),
appSecurity: z.string(),
active: z.boolean().default(true),
corporationId: z.string().optional(),
createTime: z.number().default(0),
updateTime: z.number().default(0),
authorities: z.any().nullish(),
});
export type OpenApiKey = z.infer<typeof OpenApiKeySchema>;
// ── 免登重定向配置模型 ───────────────────────────────────────────────────────
export const OpenConfigItemSchema = z
.object({
id: z.string().optional(),
url: z.string().optional(),
})
.passthrough();
export const OpenConfigSchema = z.object({
items: z.array(OpenConfigItemSchema).default([]),
});
export type OpenConfig = z.infer<typeof OpenConfigSchema>;
// ── 商店与应用模型 ───────────────────────────────────────────────────────────
export const GoodsPowerSchema = z
.object({
id: z.string().optional(),
powerCode: z.string().optional(),
powerName: z.string().optional(),
paymentStatus: z.string().optional(),
chargeType: z.string().optional(),
authorizeType: z.string().optional(),
summary: z.string().nullish().default(""),
expireTime: z.any().optional(),
})
.passthrough();
export type GoodsPower = z.infer<typeof GoodsPowerSchema>;
export const ClientGoodsSchema = z
.object({
id: z.string(),
name: z.string(),
code: z.string().optional(),
summary: z.string().nullish().default(""),
menuId: z.string().optional(),
type: z.string().optional(),
logo: z.string().nullish().default(""),
status: z.string().nullish().default(""),
onLineStatus: z.string().nullish().default(""),
expireTime: z.number().nullish(),
powers: z.array(z.union([z.string(), GoodsPowerSchema])).nullish().default([]),
hasConfig: z.boolean().optional().default(false),
configStyle: z.string().optional(),
paymentMode: z.record(z.string(), z.any()).nullish(),
})
.passthrough();
export type ClientGoods = z.infer<typeof ClientGoodsSchema>;
export const StoreGoodsItemSchema = z
.object({
id: z.string(),
name: z.string(),
code: z.string().optional(),
summary: z.string().nullish().default(""),
menuId: z.string().optional(),
type: z.string().optional(),
logo: z.string().nullish().default(""),
status: z.string().nullish().default(""),
onLineStatus: z.string().nullish().default(""),
expireTime: z.number().nullish(),
powers: z.array(z.union([z.string(), GoodsPowerSchema])).nullish().default([]),
hasConfig: z.boolean().optional().default(false),
configStyle: z.string().optional(),
paymentMode: z.record(z.string(), z.any()).nullish(),
})
.passthrough();
export type StoreGoodsItem = z.infer<typeof StoreGoodsItemSchema>;
export const GoodsDetailSchema = z
.object({
id: z.string(),
name: z.string(),
code: z.string().optional(),
summary: z.string().nullish().default(""),
menuId: z.string().optional(),
type: z.string().optional(),
logo: z.string().nullish().default(""),
status: z.string().nullish().default(""),
powers: z.array(GoodsPowerSchema).nullish().default([]),
hasConfig: z.boolean().optional().default(false),
configStyle: z.string().optional(),
detailDesc: z.string().nullish().default(""),
paymentMode: z.record(z.string(), z.any()).nullish(),
expireTime: z.number().nullish(),
})
.passthrough();
export type GoodsDetail = z.infer<typeof GoodsDetailSchema>;
+25 -3
View File
@@ -10,7 +10,9 @@ import { getEasoClient } from "./core/auth/easo.js";
import { AuthenticationError, EkbError, NotLoggedInError } from "./core/errors.js";
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";
@@ -185,7 +187,7 @@ export function createServer(options: { mode?: HoseMcpMode; enabled?: boolean }
}
);
const fineGrainedTools = [...authTools, ...platformTools, ...billTools];
const fineGrainedTools = [...authTools, ...platformTools, ...datalinkTools, ...billTools, ...feetypeTools];
// 注册工具列表
server.setRequestHandler("tools/list", async () => {
@@ -199,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"],
@@ -358,6 +360,26 @@ export function createServer(options: { mode?: HoseMcpMode; enabled?: boolean }
};
}
// DataLink 应用/业务对象/记录工具
const datalinkTool = datalinkTools.find((t) => t.name === name);
if (datalinkTool) {
const parsed = datalinkTool.parameters.safeParse(args || {});
if (!parsed.success) {
return {
content: [{ type: "text", text: `参数错误: ${parsed.error.message}` }],
isError: true,
};
}
const ekbClient = await createEkbClient(currentCorp);
const result = await datalinkTool.handler(
{ corp: currentCorp, ekbClient },
parsed.data as never
);
return {
content: [{ type: "text", text: typeof result === "string" ? result : JSON.stringify(result, null, 2) }],
};
}
return {
content: [
{
+1 -1
View File
@@ -1 +1 @@
export const VERSION = "0.8.0";
export const VERSION = "0.8.6";