Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0be629778f | ||
|
|
a415bf38c3 | ||
|
|
d447426d48 | ||
|
|
03d2337e13 | ||
|
|
6f49bfc8a4 | ||
|
|
97b67c71da | ||
|
|
09c4e7df4a | ||
|
|
69c6396d38 | ||
|
|
3c680d0ed3 | ||
|
|
215bc5e2a1 | ||
|
|
3d0bc2ebff | ||
|
|
1cd8901f7a | ||
|
|
8efce4342a | ||
|
|
893fc47ac6 | ||
|
|
2502a49fb9 | ||
|
|
212371eb03 | ||
|
|
e852dbfd47 | ||
|
|
0c953df30e |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.8.0",
|
||||
"version": "0.8.4",
|
||||
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
|
||||
"author": {
|
||||
"name": "yingqing"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# hose-use (v0.8.0)
|
||||
# hose-use (v0.8.4)
|
||||
|
||||
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
|
||||
|
||||
@@ -29,6 +29,7 @@ hose-use auth refresh # 批量刷新账号名下全部
|
||||
|
||||
# 2. 多企业租户管理
|
||||
hose-use corps list # 列出名下所有已配置企业
|
||||
hose-use corps search <关键词> # 模糊搜索已保存的企业与员工 (别名: corps find)
|
||||
hose-use corps switch <corpId> # 切换工作企业
|
||||
hose-use corps current # 查看当前激活企业
|
||||
|
||||
@@ -38,7 +39,10 @@ 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 # 搜索包含特定节点类型的工作流
|
||||
|
||||
Vendored
+1
-1
@@ -2,7 +2,7 @@
|
||||
"openapi": "3.1.0",
|
||||
"info": {
|
||||
"title": "hose-use API & MCP Tools Specification",
|
||||
"version": "0.8.0",
|
||||
"version": "0.8.4",
|
||||
"description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."
|
||||
},
|
||||
"servers": [
|
||||
|
||||
@@ -10,6 +10,12 @@ src/domains/platform/
|
||||
├── api.ts # HTTP 传输层(EKB / EASO / Piper 接口封装)
|
||||
└── tools.ts # MCP tool 注册 + 服务层聚合函数
|
||||
|
||||
src/domains/datalink/
|
||||
├── types.ts # 应用、业务对象、字段、记录与权限模型
|
||||
├── api.ts # DataLink HTTP 接口封装
|
||||
├── services.ts # 应用/对象解析与过滤辅助
|
||||
└── tools.ts # DataLink MCP tools
|
||||
|
||||
src/server.ts # MCP Server 入口,负责 tool 注册与客户端派发
|
||||
```
|
||||
|
||||
@@ -40,6 +46,18 @@ src/server.ts # MCP Server 入口,负责 tool 注册与客户端派发
|
||||
|
||||
## MCP Tools
|
||||
|
||||
### DataLink 应用与业务对象
|
||||
|
||||
| Tool | 说明 | 后端 |
|
||||
|---|---|---|
|
||||
| `datalink_platform_list` | 列出当前企业账号可见的启用自建应用 | EKB |
|
||||
| `datalink_platform_get` | 获取应用详情及管理员、人员、角色、部门权限 | EKB |
|
||||
| `datalink_entity_list` | 获取应用下业务对象、字段、操作和可见性配置 | EKB |
|
||||
| `datalink_record_search` | 分页检索业务对象记录,支持 `filterBy` | EKB |
|
||||
| `datalink_import_jobs` | 查看对象导入任务及最近导入结果 | EKB |
|
||||
|
||||
CLI 入口保持在 `platform` 命令域,支持 `list`、`get`、`entities`、`schema`、`records`、`permissions` 和 `imports`。
|
||||
|
||||
| Tool | 说明 | 后端 |
|
||||
|---|---|---|
|
||||
| `platform_list` | 列出企业下所有启用的自建应用 | EKB |
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
openapi: 3.1.0
|
||||
info:
|
||||
title: hose-use API & MCP Tools Specification
|
||||
version: 0.8.0
|
||||
version: 0.8.4
|
||||
description: >-
|
||||
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
|
||||
servers:
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.8.0",
|
||||
"version": "0.8.4",
|
||||
"module": "src/server.ts",
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env bun
|
||||
import { readFileSync, writeFileSync, existsSync, cpSync } from "node:fs";
|
||||
import { readFileSync, writeFileSync, existsSync, cpSync, readdirSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { execSync } from "node:child_process";
|
||||
|
||||
@@ -78,7 +78,10 @@ if (existsSync(pluginJsonPath)) {
|
||||
// 6. Sync to global ~/.agents/skills/hose-use/ if present
|
||||
const globalSkillDir = join(process.env.HOME || "", ".agents", "skills", "hose-use");
|
||||
if (existsSync(globalSkillDir)) {
|
||||
cpSync(join(ROOT, "skills", "hose-use"), globalSkillDir, { recursive: true });
|
||||
const srcDir = join(ROOT, "skills", "hose-use");
|
||||
for (const item of readdirSync(srcDir)) {
|
||||
cpSync(join(srcDir, item), join(globalSkillDir, item), { recursive: true, force: true });
|
||||
}
|
||||
console.log("✓ Synchronized ~/.agents/skills/hose-use/");
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
---
|
||||
name: hose-use
|
||||
description: "v0.8.0: 合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号 API 登录、租户切换、单据检索与审批动作、工作流跨域扫描、内置 HTTP 交互文档与常驻守护进程。"
|
||||
description: "v0.8.4: 合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号 API 登录、租户切换、单据检索与审批动作、工作流跨域扫描、内置 HTTP 交互文档与常驻守护进程。"
|
||||
metadata:
|
||||
version: 0.8.0
|
||||
short-description: 合思/易快报企业级 CLI 工具与底层 SDK (v0.8.0)
|
||||
version: 0.8.4
|
||||
short-description: 合思/易快报企业级 CLI 工具与底层 SDK (v0.8.4)
|
||||
---
|
||||
|
||||
# hose-use (v0.8.0)
|
||||
# hose-use (v0.8.4)
|
||||
|
||||
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
|
||||
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
|
||||
@@ -55,8 +55,12 @@ metadata:
|
||||
| 单据实体模型与字段元数据查询 | `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 analyze <pipelineId>` | [references/workflow.md](references/workflow.md) |
|
||||
@@ -122,9 +126,18 @@ hose-use message list --all # 合并查看已读和
|
||||
hose-use message count # 查看未读数量
|
||||
hose-use message read <messageId> # 标记单条消息已读
|
||||
|
||||
# 5. 自建应用与工作流
|
||||
hose-use platform list # 查看自建应用列表
|
||||
hose-use workflow list # 聚合扫描全部应用下的工作流
|
||||
# 5. 应用管理、自建应用与工作流
|
||||
hose-use app list # 查看应用管理列表(桌面端工作台业务应用集成)
|
||||
hose-use app get 用车补贴 # 查看指定应用管理的配置与 Web 路由
|
||||
hose-use platform list # 列出企业可见的自建应用平台
|
||||
hose-use platform entities 新转转集团 # 查看自建应用下的业务对象与字段
|
||||
hose-use platform records 新转转集团 合同 # 查看业务对象的底层数据记录
|
||||
hose-use platform record get 新转转集团 合同 <记录ID> # 获取单条记录完整字段与属性详情
|
||||
hose-use platform record toggle 新转转集团 合同 <记录ID> # 切换单条记录停启用状态
|
||||
hose-use platform record edit 新转转集团 合同 <记录ID> --data='{"name":"新名称"}' # 编辑记录字段
|
||||
hose-use platform record recompute 新转转集团 合同 <记录ID> # 重新计算记录关联的全部台账
|
||||
hose-use menu list # 查看桌面端主框架一级导航树
|
||||
hose-use workflow list # 聚合扫描全部自建应用下的工作流
|
||||
hose-use workflow find --task=code-js2 # 查找部署了代码节点的工作流
|
||||
hose-use workflow get wf_01k83y... # 查看指定工作流节点拓扑
|
||||
hose-use workflow analyze wf_01k83y... --json # 输出节点树、引用依赖与静态诊断
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,7 +124,7 @@ hose-use workflow toggle wf_01k83y... --enable
|
||||
hose-use workflow toggle wf_01k83y... --disable
|
||||
```
|
||||
|
||||
## 6. 工作流静态分析 (`workflow analyze`)
|
||||
## 7. 工作流静态分析 (`workflow analyze`)
|
||||
|
||||
从应用中心的具体自建应用进入工作流详情后,CLI 可以读取同一份详情并生成递归节点树、代码表达式引用依赖和明显配置诊断;该命令只读,不执行工作流:
|
||||
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
import { describe, it, expect, spyOn } from "bun:test";
|
||||
import { handleAppCommand } from "./app.js";
|
||||
import * as menuTools from "../../domains/menu/tools.js";
|
||||
import type { CliRuntime } from "../types.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
|
||||
describe("cli/commands/app > handleAppCommand", () => {
|
||||
const dummyRuntimeNoCorp: CliRuntime = {
|
||||
corpContext: {
|
||||
listCorps: () => [],
|
||||
getCurrent: () => null,
|
||||
switchCorp: () => false,
|
||||
resolve: () => null,
|
||||
} as any,
|
||||
selectedCorp: null,
|
||||
jsonMode: false,
|
||||
};
|
||||
|
||||
const mockCorp: CorpConfig = {
|
||||
id: "corp123",
|
||||
name: "转转二手交易网",
|
||||
source: "account",
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
credentials: {
|
||||
accessToken: "mock-token",
|
||||
corpId: "corp123",
|
||||
staffId: "mock-staff",
|
||||
},
|
||||
};
|
||||
|
||||
const dummyRuntimeWithCorp: CliRuntime = {
|
||||
corpContext: {
|
||||
listCorps: () => [mockCorp],
|
||||
getCurrent: () => mockCorp,
|
||||
switchCorp: () => true,
|
||||
resolve: () => mockCorp,
|
||||
} as any,
|
||||
selectedCorp: mockCorp,
|
||||
jsonMode: false,
|
||||
};
|
||||
|
||||
it("fails with exitCode 1 when no corp is selected", async () => {
|
||||
const res = await handleAppCommand(
|
||||
{
|
||||
area: "app",
|
||||
action: "list",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["app", "list"],
|
||||
},
|
||||
dummyRuntimeNoCorp
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(1);
|
||||
expect(res.stderr).toContain("未选中企业");
|
||||
});
|
||||
|
||||
it("lists workbench apps in table format", async () => {
|
||||
const mockApps = [
|
||||
{
|
||||
id: "SCGY:corp123",
|
||||
name: "用车补贴",
|
||||
code: "dataLinkItem",
|
||||
href: "/third-party-item/SCGY:corp123",
|
||||
type: "MENU",
|
||||
},
|
||||
{
|
||||
id: "ID01PIqCA1Di0v",
|
||||
name: "用车制度",
|
||||
code: "dataLinkItem",
|
||||
href: "/third-party-item/ID01PIqCA1Di0v",
|
||||
type: "REGULATION",
|
||||
},
|
||||
];
|
||||
|
||||
const spy = spyOn(menuTools, "fetchWorkbenchAppsList").mockResolvedValue(mockApps as any);
|
||||
|
||||
const res = await handleAppCommand(
|
||||
{
|
||||
area: "app",
|
||||
action: "list",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["app", "list"],
|
||||
},
|
||||
dummyRuntimeWithCorp
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("工作台应用管理列表");
|
||||
expect(res.stdout).toContain("用车补贴");
|
||||
expect(res.stdout).toContain("用车制度");
|
||||
expect(res.stdout).toContain("用车/商旅套件");
|
||||
expect(res.stdout).toContain("制度与规约");
|
||||
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it("filters workbench apps with --keyword", async () => {
|
||||
const mockApps = [
|
||||
{
|
||||
id: "SCGY:corp123",
|
||||
name: "用车补贴",
|
||||
code: "dataLinkItem",
|
||||
href: "/third-party-item/SCGY:corp123",
|
||||
},
|
||||
{
|
||||
id: "ID01PIqCA1Di0v",
|
||||
name: "差旅申请",
|
||||
code: "dataLinkItem",
|
||||
href: "/third-party-item/ID01PIqCA1Di0v",
|
||||
},
|
||||
];
|
||||
|
||||
const spy = spyOn(menuTools, "fetchWorkbenchAppsList").mockResolvedValue(mockApps as any);
|
||||
|
||||
const res = await handleAppCommand(
|
||||
{
|
||||
area: "app",
|
||||
action: "list",
|
||||
args: [],
|
||||
options: { keyword: "补贴" },
|
||||
raw: ["app", "list", "--keyword", "补贴"],
|
||||
},
|
||||
dummyRuntimeWithCorp
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("用车补贴");
|
||||
expect(res.stdout).not.toContain("差旅申请");
|
||||
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it("supports --json output for app list", async () => {
|
||||
const mockApps = [
|
||||
{
|
||||
id: "SCGY:corp123",
|
||||
name: "用车补贴",
|
||||
code: "dataLinkItem",
|
||||
href: "/third-party-item/SCGY:corp123",
|
||||
},
|
||||
];
|
||||
|
||||
const spy = spyOn(menuTools, "fetchWorkbenchAppsList").mockResolvedValue(mockApps as any);
|
||||
|
||||
const jsonRuntime = { ...dummyRuntimeWithCorp, jsonMode: true };
|
||||
const res = await handleAppCommand(
|
||||
{
|
||||
area: "app",
|
||||
action: "list",
|
||||
args: [],
|
||||
options: { json: true },
|
||||
raw: ["app", "list", "--json"],
|
||||
},
|
||||
jsonRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
const parsed = JSON.parse(res.stdout);
|
||||
expect(parsed.total).toBe(1);
|
||||
expect(parsed.apps[0].id).toBe("SCGY:corp123");
|
||||
expect(parsed.apps[0].name).toBe("用车补贴");
|
||||
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it("returns error for unknown subcommand", async () => {
|
||||
const res = await handleAppCommand(
|
||||
{
|
||||
area: "app",
|
||||
action: "unknownAction",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["app", "unknownAction"],
|
||||
},
|
||||
dummyRuntimeWithCorp
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(1);
|
||||
expect(res.stderr).toContain("未知 app 子命令");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,149 @@
|
||||
import { fetchWorkbenchAppsList } from "../../domains/menu/tools.js";
|
||||
import { getPlatform } from "../../domains/datalink/api.js";
|
||||
import { createClientsForCorp } from "../helpers.js";
|
||||
import { stringOption, booleanOption } from "../parser.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
|
||||
function inferCategory(app: { id: string; name: string; type?: string | null }): string {
|
||||
if (app.id.startsWith("SCGY:") || app.type === "PRIVATE_CAR") return "用车/商旅套件";
|
||||
if (app.type === "REGULATION") return "制度与规约";
|
||||
if (app.type === "VCM") return "商旅卡与金融";
|
||||
if (app.name.includes("[模板]") || app.name.includes("模板")) return "预置模板";
|
||||
return "自建业务应用";
|
||||
}
|
||||
|
||||
export async function handleAppCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
if (!runtime.selectedCorp) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const action = parsed.action || "list";
|
||||
|
||||
switch (action) {
|
||||
case "list":
|
||||
case "ls":
|
||||
case "apps":
|
||||
case "workbench": {
|
||||
const keyword = stringOption(parsed.options, ["keyword", "k", "q", "query"])?.toLowerCase();
|
||||
const apps = await fetchWorkbenchAppsList(runtime.selectedCorp);
|
||||
|
||||
const filtered = keyword
|
||||
? apps.filter((app) =>
|
||||
[app.id, app.name, app.code, app.href]
|
||||
.filter((val): val is string => Boolean(val))
|
||||
.some((val) => val.toLowerCase().includes(keyword))
|
||||
)
|
||||
: apps;
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId: runtime.selectedCorp.credentials.corpId,
|
||||
corpName: runtime.selectedCorp.name,
|
||||
total: apps.length,
|
||||
count: filtered.length,
|
||||
keyword: keyword ?? null,
|
||||
apps: filtered,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (filtered.length === 0) {
|
||||
const msg = keyword
|
||||
? `企业 [${runtime.selectedCorp.name}] 下未找到匹配 "${keyword}" 的工作台应用\n`
|
||||
: `企业 [${runtime.selectedCorp.name}] 下暂无工作台应用配置\n`;
|
||||
return { stdout: msg, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const headers = ["#", "应用 ID", "应用名称", "应用分类", "功能代码", "Web 直达路由"];
|
||||
const rows = filtered.map((app, i) => [
|
||||
i + 1,
|
||||
app.id,
|
||||
app.name,
|
||||
inferCategory(app),
|
||||
app.code || "dataLinkItem",
|
||||
app.href,
|
||||
]);
|
||||
|
||||
const title = `====== [${runtime.selectedCorp.name}] 工作台应用管理列表 (${filtered.length} 个应用) ======\n`;
|
||||
return {
|
||||
stdout: title + printTable(headers, rows) + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
case "get":
|
||||
case "show": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["id", "name", "app"]);
|
||||
if (!target) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "请提供应用 ID 或名称: hose-use app get <应用 ID|名称>\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const apps = await fetchWorkbenchAppsList(runtime.selectedCorp);
|
||||
const matched = apps.find(
|
||||
(a) =>
|
||||
a.id.toLowerCase() === target.toLowerCase() ||
|
||||
a.name.toLowerCase().includes(target.toLowerCase())
|
||||
);
|
||||
|
||||
const appId = matched ? matched.id : target;
|
||||
const appName = matched ? matched.name : target;
|
||||
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp);
|
||||
const corpId = runtime.selectedCorp.credentials.corpId;
|
||||
|
||||
try {
|
||||
const detail = await getPlatform(clients.ekbClient, corpId, appId);
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(detail, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const infoRows = [
|
||||
["应用 ID", detail.id],
|
||||
["应用名称", detail.name],
|
||||
["应用分类", inferCategory(detail)],
|
||||
["启用状态", detail.active ? "🟢 已启用" : "⚪ 未启用"],
|
||||
["Web 路由", matched?.href || `/third-party-item/${detail.id}`],
|
||||
["管理员数", detail.adminIds.length],
|
||||
["可见人员数", detail.staffIds.length],
|
||||
["可见角色数", detail.roleIds.length],
|
||||
["可见部门数", detail.departmentIds.length],
|
||||
];
|
||||
|
||||
const text = `====== 工作台应用详情: ${appName} ======\n${printTable(["属性", "信息"], infoRows)}\n`;
|
||||
return { stdout: text, stderr: "", exitCode: 0 };
|
||||
} catch (err) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `获取应用详情失败: ${err instanceof Error ? err.message : String(err)}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 app 子命令: ${action}。支持: list, get\n用法: hose-use app list [--keyword <关键词>]\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { describe, it, expect } from "bun:test";
|
||||
import { handleAuthCommand } from "./auth.js";
|
||||
import type { CliRuntime } from "../types.js";
|
||||
|
||||
describe("cli/commands/auth > aliases and subcommands", () => {
|
||||
const dummyRuntime: CliRuntime = {
|
||||
corpContext: {
|
||||
listCorps: () => [],
|
||||
getCurrent: () => null,
|
||||
switchCorp: () => false,
|
||||
resolve: () => null,
|
||||
} as any,
|
||||
selectedCorp: null,
|
||||
jsonMode: false,
|
||||
};
|
||||
|
||||
it("maps auth list to handleAccounts smoothly", async () => {
|
||||
const res = await handleAuthCommand(
|
||||
{
|
||||
area: "auth",
|
||||
action: "list",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["auth", "list"],
|
||||
},
|
||||
dummyRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
// 应该输出已保存账号表格或无账号提示
|
||||
expect(res.stdout).toMatch(/(已保存账号列表|暂无保存的账号)/);
|
||||
});
|
||||
|
||||
it("supports auth accounts with --json mode", async () => {
|
||||
const jsonRuntime = { ...dummyRuntime, jsonMode: true };
|
||||
const res = await handleAuthCommand(
|
||||
{
|
||||
area: "auth",
|
||||
action: "list",
|
||||
args: [],
|
||||
options: { json: true },
|
||||
raw: ["auth", "list", "--json"],
|
||||
},
|
||||
jsonRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
const data = JSON.parse(res.stdout);
|
||||
expect(data).toHaveProperty("accounts");
|
||||
});
|
||||
|
||||
it("handles auth status / current aliases without crash", async () => {
|
||||
const res = await handleAuthCommand(
|
||||
{
|
||||
area: "auth",
|
||||
action: "current",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["auth", "current"],
|
||||
},
|
||||
dummyRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("当前登录与企业状态");
|
||||
});
|
||||
});
|
||||
@@ -31,16 +31,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 {
|
||||
|
||||
@@ -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)");
|
||||
});
|
||||
});
|
||||
@@ -15,17 +15,19 @@ 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 +38,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,
|
||||
};
|
||||
}
|
||||
@@ -227,11 +229,17 @@ async function handlePaths(parsed: CliParsedArgs, runtime: CliRuntime): Promise<
|
||||
const writableDir = resolveWritableEnterprisesDir();
|
||||
const configFile = resolveGlobalConfigFile();
|
||||
const candidates = getEnterprisesDirCandidates();
|
||||
const globalConfig = loadGlobalConfig();
|
||||
const currentCorp = runtime.selectedCorp;
|
||||
|
||||
const data = {
|
||||
configFile,
|
||||
writableDir,
|
||||
existingDirs,
|
||||
mode: globalConfig.stateful ? "stateful" : "stateless",
|
||||
stateful: globalConfig.stateful,
|
||||
defaultCorpId: globalConfig.defaultCorpId || null,
|
||||
activeCorp: currentCorp ? { id: currentCorp.id, name: currentCorp.name } : null,
|
||||
env: {
|
||||
HOSE_ENTERPRISES_DIR: envDir || null,
|
||||
HOSE_USER_ENTERPRISES_DIR: envUserDir || null,
|
||||
@@ -241,13 +249,16 @@ async function handlePaths(parsed: CliParsedArgs, runtime: CliRuntime): Promise<
|
||||
};
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(data), stderr: "", exitCode: 0 };
|
||||
return { stdout: printJson(data, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const output = printKeyValue({
|
||||
"当前生效配置文件": configFile,
|
||||
"凭证保存写入目录": writableDir,
|
||||
"已发现企业目录": existingDirs.length ? existingDirs.join("\n ") : "无 (未发现任何有效企业目录)",
|
||||
"运行模式 (Mode)": globalConfig.stateful ? "有状态模式 (Stateful - 自动记忆默认企业)" : "无状态模式 (Stateless - 每次需显式传 --corp)",
|
||||
"默认工作企业": globalConfig.defaultCorpId || "未设置 (使用首个可用企业)",
|
||||
"当前解析企业": currentCorp ? `${currentCorp.name} (${currentCorp.id})` : "无",
|
||||
"环境变量指定目录": envDir || "未设置 (HOSE_ENTERPRISES_DIR)",
|
||||
"全部目录候选链": candidates.join("\n "),
|
||||
});
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
+190
-1
@@ -6,6 +6,15 @@ import { prompt } from "../helpers.js";
|
||||
import { printJson, printKeyValue, printTable, formatSourceLabel, formatExpiresAt } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
|
||||
const FIELD_LABEL_MAP: Record<string, string> = {
|
||||
id: "配置ID",
|
||||
name: "企业名称",
|
||||
corpId: "企业ID",
|
||||
staffId: "员工工号",
|
||||
staffName: "员工姓名",
|
||||
accountId: "所属账号",
|
||||
};
|
||||
|
||||
export async function handleCorpsCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
@@ -14,23 +23,203 @@ export async function handleCorpsCommand(
|
||||
|
||||
switch (action) {
|
||||
case "list":
|
||||
case "ls":
|
||||
return handleList(parsed, runtime);
|
||||
case "search":
|
||||
case "find":
|
||||
case "query":
|
||||
case "filter":
|
||||
return handleSearch(parsed, runtime);
|
||||
case "switch":
|
||||
case "use":
|
||||
return handleSwitch(parsed, runtime);
|
||||
case "current":
|
||||
case "whoami":
|
||||
case "status":
|
||||
case "active":
|
||||
return handleCurrent(parsed, runtime);
|
||||
case "add-link":
|
||||
case "link":
|
||||
case "import-link":
|
||||
return handleAddLink(parsed, runtime);
|
||||
case "help":
|
||||
return handleCorpsHelp();
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 corps 子命令: ${action}。支持: list, switch, current, 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();
|
||||
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
import { describe, expect, test, spyOn } from "bun:test";
|
||||
import { handleKeysCommand } from "./keys.js";
|
||||
import { handleOpenApiCommand } from "./openapi.js";
|
||||
import type { CliRuntime, CliParsedArgs } from "../types.js";
|
||||
import * as storeTools from "../../domains/store/tools.js";
|
||||
|
||||
describe("CLI - keys 顶级命令与凭证提取", () => {
|
||||
const dummyCorp: any = {
|
||||
id: "test-corp-id",
|
||||
name: "测试企业A",
|
||||
corpId: "test-corp-id",
|
||||
credentials: { corpId: "test-corp-id", accessToken: "token123" },
|
||||
};
|
||||
|
||||
const createRuntime = (corp: any = dummyCorp, jsonMode = false): CliRuntime => ({
|
||||
corpContext: {} as any,
|
||||
selectedCorp: corp,
|
||||
jsonMode,
|
||||
});
|
||||
|
||||
test("未选中企业时返回提示并报错", async () => {
|
||||
const runtime = createRuntime(null);
|
||||
const parsed: CliParsedArgs = { area: "keys", options: {}, args: [], raw: ["keys"] };
|
||||
const res = await handleKeysCommand(parsed, runtime);
|
||||
expect(res.exitCode).toBe(1);
|
||||
expect(res.stderr).toContain("未选中企业");
|
||||
});
|
||||
|
||||
test("keys 默认脱敏显示 appSecurity 接入密码", async () => {
|
||||
const spy = spyOn(storeTools, "fetchOpenApiKeys").mockImplementation(() =>
|
||||
Promise.resolve([
|
||||
{
|
||||
id: "k-1",
|
||||
name: "开发测试密钥",
|
||||
appKey: "545f8b6a-75a7-4f99-86e1-bca747c985e7",
|
||||
appSecurity: "9bc91727-e96e-4924-abcb-d8ed77557f58",
|
||||
active: true,
|
||||
createTime: 1751357077503,
|
||||
updateTime: 1769063905460,
|
||||
},
|
||||
])
|
||||
);
|
||||
|
||||
const runtime = createRuntime(dummyCorp);
|
||||
const parsed: CliParsedArgs = { area: "keys", options: {}, args: [], raw: ["keys"] };
|
||||
const res = await handleKeysCommand(parsed, runtime);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("开发测试密钥");
|
||||
expect(res.stdout).toContain("545f8b6a-75a7-4f99-86e1-bca747c985e7");
|
||||
// 默认脱敏
|
||||
expect(res.stdout).toContain("9bc91727...7f58");
|
||||
expect(res.stdout).not.toContain("9bc91727-e96e-4924-abcb-d8ed77557f58");
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
test("keys --reveal 显式输出完整接入密码明文", async () => {
|
||||
const spy = spyOn(storeTools, "fetchOpenApiKeys").mockImplementation(() =>
|
||||
Promise.resolve([
|
||||
{
|
||||
id: "k-1",
|
||||
name: "生产密钥",
|
||||
appKey: "key-full-123",
|
||||
appSecurity: "secret-super-long-plain-text",
|
||||
active: true,
|
||||
createTime: 1751357077503,
|
||||
updateTime: 1769063905460,
|
||||
},
|
||||
])
|
||||
);
|
||||
|
||||
const runtime = createRuntime(dummyCorp);
|
||||
const parsed: CliParsedArgs = {
|
||||
area: "keys",
|
||||
options: { reveal: true },
|
||||
args: [],
|
||||
raw: ["keys", "--reveal"],
|
||||
};
|
||||
const res = await handleKeysCommand(parsed, runtime);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("secret-super-long-plain-text");
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
test("keys --json 模式正常序列化", async () => {
|
||||
const spy = spyOn(storeTools, "fetchOpenApiKeys").mockImplementation(() =>
|
||||
Promise.resolve([
|
||||
{
|
||||
id: "k-1",
|
||||
name: "JSON密钥",
|
||||
appKey: "json-app-key",
|
||||
appSecurity: "secret-for-json-test",
|
||||
active: true,
|
||||
createTime: 1751357077503,
|
||||
updateTime: 1769063905460,
|
||||
},
|
||||
])
|
||||
);
|
||||
|
||||
const runtime = createRuntime(dummyCorp, true);
|
||||
const parsed: CliParsedArgs = { area: "keys", options: { json: true }, args: [], raw: ["keys", "--json"] };
|
||||
const res = await handleKeysCommand(parsed, runtime);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
const data = JSON.parse(res.stdout);
|
||||
expect(Array.isArray(data)).toBe(true);
|
||||
expect(data[0].appKey).toBe("json-app-key");
|
||||
// 默认 json 脱敏
|
||||
expect(data[0].appSecurity).toContain("...");
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
test("openapi keys 子命令平滑转发至同一执行器", async () => {
|
||||
const spy = spyOn(storeTools, "fetchOpenApiKeys").mockImplementation(() =>
|
||||
Promise.resolve([
|
||||
{
|
||||
id: "k-1",
|
||||
name: "OpenAPI子命令测试",
|
||||
appKey: "sub-app-key",
|
||||
appSecurity: "sub-app-security-123456",
|
||||
active: true,
|
||||
createTime: 1751357077503,
|
||||
updateTime: 1769063905460,
|
||||
},
|
||||
])
|
||||
);
|
||||
|
||||
const runtime = createRuntime(dummyCorp);
|
||||
const parsed: CliParsedArgs = {
|
||||
area: "openapi",
|
||||
action: "keys",
|
||||
options: {},
|
||||
args: [],
|
||||
raw: ["openapi", "keys"],
|
||||
};
|
||||
const res = await handleOpenApiCommand(parsed, runtime);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("OpenAPI子命令测试");
|
||||
expect(res.stdout).toContain("sub-app-key");
|
||||
spy.mockRestore();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
import { fetchOpenApiKeys } from "../../domains/store/tools.js";
|
||||
import { booleanOption } from "../parser.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
|
||||
function formatDate(ts: number): string {
|
||||
if (!ts) return "-";
|
||||
const d = new Date(ts);
|
||||
if (isNaN(d.getTime())) return "-";
|
||||
const Y = d.getFullYear();
|
||||
const M = String(d.getMonth() + 1).padStart(2, "0");
|
||||
const D = String(d.getDate()).padStart(2, "0");
|
||||
const h = String(d.getHours()).padStart(2, "0");
|
||||
const m = String(d.getMinutes()).padStart(2, "0");
|
||||
return `${Y}/${M}/${D} ${h}:${m}`;
|
||||
}
|
||||
|
||||
function maskSecret(secret: string): string {
|
||||
if (!secret) return "-";
|
||||
if (secret.length <= 12) return "******";
|
||||
return `${secret.slice(0, 8)}...${secret.slice(-4)}`;
|
||||
}
|
||||
|
||||
export async function handleKeysCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const currentCorp = runtime.selectedCorp;
|
||||
if (!currentCorp) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const reveal =
|
||||
booleanOption(parsed.options, ["reveal", "r", "plain"]) ||
|
||||
parsed.action === "reveal" ||
|
||||
parsed.args[0] === "reveal";
|
||||
|
||||
try {
|
||||
const keys = await fetchOpenApiKeys(currentCorp);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
const outputData = reveal
|
||||
? keys
|
||||
: keys.map((k) => ({
|
||||
...k,
|
||||
appSecurity: maskSecret(k.appSecurity),
|
||||
}));
|
||||
return {
|
||||
stdout: printJson(outputData, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (keys.length === 0) {
|
||||
return {
|
||||
stdout: `企业 [${currentCorp.name}] 暂未创建 OpenAPI 密钥凭证\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = keys.map((k, i) => [
|
||||
i + 1,
|
||||
k.name || "-",
|
||||
k.appKey,
|
||||
reveal ? k.appSecurity : maskSecret(k.appSecurity),
|
||||
k.active ? "🟢 启用" : "⚪ 停用",
|
||||
formatDate(k.createTime),
|
||||
]);
|
||||
|
||||
const table = printTable(
|
||||
["#", "密钥备注", "接入账号 (appKey)", "接入密码 (appSecurity)", "状态", "创建时间"],
|
||||
rows
|
||||
);
|
||||
|
||||
const title = `====== [${currentCorp.name}] 企业 OpenAPI 接入密钥列表 (共 ${keys.length} 个) ======`;
|
||||
const hint = reveal
|
||||
? ""
|
||||
: "\n提示: 接入密码默认脱敏,附加 --reveal (或 -r) 可查看完整明文;使用 --json 可输出完整结构。\n";
|
||||
|
||||
return {
|
||||
stdout: `${title}\n\n${table}\n${hint}`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
} catch (err: any) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `获取企业 OpenAPI 密钥失败: ${err?.message || err}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
import { describe, it, expect, spyOn } from "bun:test";
|
||||
import { handleMenuCommand } from "./menu.js";
|
||||
import * as menuTools from "../../domains/menu/tools.js";
|
||||
import type { CliRuntime } from "../types.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
|
||||
describe("cli/commands/menu > handleMenuCommand", () => {
|
||||
const dummyRuntimeNoCorp: CliRuntime = {
|
||||
corpContext: {
|
||||
listCorps: () => [],
|
||||
getCurrent: () => null,
|
||||
switchCorp: () => false,
|
||||
resolve: () => null,
|
||||
} as any,
|
||||
selectedCorp: null,
|
||||
jsonMode: false,
|
||||
};
|
||||
|
||||
const mockCorp: CorpConfig = {
|
||||
id: "corp123",
|
||||
name: "转转二手交易网",
|
||||
source: "account",
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
credentials: {
|
||||
accessToken: "mock-token",
|
||||
corpId: "corp123",
|
||||
staffId: "mock-staff",
|
||||
},
|
||||
};
|
||||
|
||||
const dummyRuntimeWithCorp: CliRuntime = {
|
||||
corpContext: {
|
||||
listCorps: () => [mockCorp],
|
||||
getCurrent: () => mockCorp,
|
||||
switchCorp: () => true,
|
||||
resolve: () => mockCorp,
|
||||
} as any,
|
||||
selectedCorp: mockCorp,
|
||||
jsonMode: false,
|
||||
};
|
||||
|
||||
it("fails with exitCode 1 when no corp is selected", async () => {
|
||||
const res = await handleMenuCommand(
|
||||
{
|
||||
area: "menu",
|
||||
action: "list",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["menu", "list"],
|
||||
},
|
||||
dummyRuntimeNoCorp
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(1);
|
||||
expect(res.stderr).toContain("未选中企业");
|
||||
});
|
||||
|
||||
it("lists desktop menus in table format", async () => {
|
||||
const mockMenus = [
|
||||
{
|
||||
id: "newHomePage",
|
||||
label: "首页",
|
||||
appId: "100-home",
|
||||
href: "/home",
|
||||
children: [],
|
||||
},
|
||||
{
|
||||
id: "dataLink",
|
||||
label: "应用管理",
|
||||
appId: "160-datalink-platform",
|
||||
href: "/datalink",
|
||||
children: [
|
||||
{ id: "sub1", label: "用车补贴" },
|
||||
{ id: "sub2", label: "用车制度" },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const spy = spyOn(menuTools, "fetchDesktopMenus").mockResolvedValue(mockMenus as any);
|
||||
|
||||
const res = await handleMenuCommand(
|
||||
{
|
||||
area: "menu",
|
||||
action: "list",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["menu", "list"],
|
||||
},
|
||||
dummyRuntimeWithCorp
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("桌面端主框架导航与模块列表");
|
||||
expect(res.stdout).toContain("首页");
|
||||
expect(res.stdout).toContain("应用管理");
|
||||
expect(res.stdout).toContain("160-datalink-platform");
|
||||
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it("supports --json output for menu list", async () => {
|
||||
const mockMenus = [
|
||||
{
|
||||
id: "newHomePage",
|
||||
label: "首页",
|
||||
appId: "100-home",
|
||||
href: "/home",
|
||||
},
|
||||
];
|
||||
|
||||
const spy = spyOn(menuTools, "fetchDesktopMenus").mockResolvedValue(mockMenus as any);
|
||||
|
||||
const jsonRuntime = { ...dummyRuntimeWithCorp, jsonMode: true };
|
||||
const res = await handleMenuCommand(
|
||||
{
|
||||
area: "menu",
|
||||
action: "list",
|
||||
args: [],
|
||||
options: { json: true },
|
||||
raw: ["menu", "list", "--json"],
|
||||
},
|
||||
jsonRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
const parsed = JSON.parse(res.stdout);
|
||||
expect(parsed.count).toBe(1);
|
||||
expect(parsed.menus[0].id).toBe("newHomePage");
|
||||
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it("delegates menu apps to handleAppCommand", async () => {
|
||||
const mockApps = [
|
||||
{
|
||||
id: "SCGY:corp123",
|
||||
name: "用车补贴",
|
||||
code: "dataLinkItem",
|
||||
href: "/third-party-item/SCGY:corp123",
|
||||
},
|
||||
];
|
||||
|
||||
const spy = spyOn(menuTools, "fetchWorkbenchAppsList").mockResolvedValue(mockApps as any);
|
||||
|
||||
const res = await handleMenuCommand(
|
||||
{
|
||||
area: "menu",
|
||||
action: "apps",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["menu", "apps"],
|
||||
},
|
||||
dummyRuntimeWithCorp
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("工作台应用管理列表");
|
||||
expect(res.stdout).toContain("用车补贴");
|
||||
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it("returns error for unknown menu subcommand", async () => {
|
||||
const res = await handleMenuCommand(
|
||||
{
|
||||
area: "menu",
|
||||
action: "badsub",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["menu", "badsub"],
|
||||
},
|
||||
dummyRuntimeWithCorp
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(1);
|
||||
expect(res.stderr).toContain("未知 menu 子命令");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
import { fetchDesktopMenus } from "../../domains/menu/tools.js";
|
||||
import { handleAppCommand } from "./app.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
|
||||
export async function handleMenuCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
if (!runtime.selectedCorp) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const action = parsed.action || "list";
|
||||
|
||||
switch (action) {
|
||||
case "apps":
|
||||
case "workbench":
|
||||
return handleAppCommand(parsed, runtime);
|
||||
|
||||
case "list":
|
||||
case "ls":
|
||||
case "tree": {
|
||||
const items = await fetchDesktopMenus(runtime.selectedCorp);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId: runtime.selectedCorp.credentials.corpId,
|
||||
corpName: runtime.selectedCorp.name,
|
||||
count: items.length,
|
||||
menus: items,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const headers = ["#", "模块 ID", "导航名称", "模块标识 (appId)", "子菜单数", "默认路由"];
|
||||
const rows = items.map((m, i) => [
|
||||
i + 1,
|
||||
m.id,
|
||||
m.label,
|
||||
m.appId || "-",
|
||||
m.children?.length || 0,
|
||||
m.href || "-",
|
||||
]);
|
||||
|
||||
const title = `====== [${runtime.selectedCorp.name}] 桌面端主框架导航与模块列表 (共 ${items.length} 个一级导航) ======\n`;
|
||||
return {
|
||||
stdout: title + printTable(headers, rows) + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 menu 子命令: ${action}。支持: list, tree, apps\n用法: hose-use menu list\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -2,18 +2,24 @@ import { getOpenApiSchema, listOpenApiPaths, type OpenApiType } from "../../core
|
||||
import { booleanOption, stringOption } from "../parser.js";
|
||||
import { printJson, printKeyValue, printTable } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { handleKeysCommand } from "./keys.js";
|
||||
|
||||
export async function handleOpenApiCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const action = parsed.action?.toLowerCase();
|
||||
|
||||
if (action === "keys" || action === "key") {
|
||||
return handleKeysCommand(parsed, runtime);
|
||||
}
|
||||
|
||||
const isRaw =
|
||||
booleanOption(parsed.options, ["raw"]) ||
|
||||
parsed.action === "raw" ||
|
||||
parsed.args[0] === "raw";
|
||||
|
||||
const type: OpenApiType = isRaw ? "raw" : "wrapped";
|
||||
const action = parsed.action?.toLowerCase();
|
||||
|
||||
switch (action) {
|
||||
case "paths":
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
import { describe, expect, it, spyOn, afterEach } from "bun:test";
|
||||
import { handlePlatformCommand } from "./platform.js";
|
||||
import * as api from "../../domains/datalink/api.js";
|
||||
import * as services from "../../domains/datalink/services.js";
|
||||
import * as helpers from "../helpers.js";
|
||||
import type { CliRuntime } from "../types.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
|
||||
describe("CLI - platform 命令与 record 动作", () => {
|
||||
let spies: ReturnType<typeof spyOn>[] = [];
|
||||
afterEach(() => {
|
||||
for (const spy of spies) {
|
||||
spy.mockRestore();
|
||||
}
|
||||
spies = [];
|
||||
});
|
||||
const mockCorp: CorpConfig = {
|
||||
id: "corp-1",
|
||||
name: "测试企业",
|
||||
source: "account",
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
credentials: {
|
||||
accessToken: "mock-token",
|
||||
corpId: "corp-1",
|
||||
staffId: "staff-1",
|
||||
},
|
||||
};
|
||||
|
||||
const dummyRuntime: CliRuntime = {
|
||||
corpContext: {
|
||||
listCorps: () => [mockCorp],
|
||||
getCurrent: () => mockCorp,
|
||||
switchCorp: () => true,
|
||||
resolve: () => mockCorp,
|
||||
} as any,
|
||||
selectedCorp: mockCorp,
|
||||
jsonMode: false,
|
||||
};
|
||||
|
||||
const mockPlatform = {
|
||||
id: "platform-1",
|
||||
name: "项目台账",
|
||||
code: "PJ",
|
||||
active: true,
|
||||
adminIds: ["staff-1"],
|
||||
staffIds: [],
|
||||
roleIds: [],
|
||||
departmentIds: [],
|
||||
departmentsIncludeChildren: false,
|
||||
};
|
||||
|
||||
const mockEntity = {
|
||||
id: "entity-1",
|
||||
name: "项目",
|
||||
code: "PROJECT",
|
||||
type: "DIMENSION",
|
||||
active: true,
|
||||
fields: [
|
||||
{ name: "code", label: "编码", type: "text" },
|
||||
{ name: "name", label: "名称", type: "text" },
|
||||
{ name: "customField", label: "自定义字段", type: "text" },
|
||||
],
|
||||
actions: [],
|
||||
importMethod: [],
|
||||
};
|
||||
|
||||
it("未选中企业时报错并返回 exitCode 1", async () => {
|
||||
const res = await handlePlatformCommand(
|
||||
{ area: "platform", action: "list", args: [], options: {}, raw: [] },
|
||||
{ ...dummyRuntime, selectedCorp: null }
|
||||
);
|
||||
expect(res.exitCode).toBe(1);
|
||||
expect(res.stderr).toContain("未选中企业");
|
||||
});
|
||||
|
||||
it("records 正确解析嵌套 dataLink 的停启用状态和更新时间", async () => {
|
||||
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
|
||||
spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any));
|
||||
spies.push(spyOn(api, "searchEntityRecords").mockResolvedValue({
|
||||
total: 2,
|
||||
data: [
|
||||
{
|
||||
id: "r-1",
|
||||
dataLink: { id: "r-1", name: "项目1", code: "P1", active: false, updateTime: "2026-09-09" },
|
||||
},
|
||||
{
|
||||
id: "r-2",
|
||||
dataLink: { id: "r-2", name: "项目2", code: "P2", active: true, updateTime: "2026-09-09" },
|
||||
},
|
||||
],
|
||||
actions: [],
|
||||
components: [],
|
||||
path: null,
|
||||
template: null,
|
||||
}));
|
||||
|
||||
const res = await handlePlatformCommand(
|
||||
{ area: "platform", action: "records", args: ["platform-1", "entity-1"], options: {}, raw: [] },
|
||||
dummyRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("停用");
|
||||
expect(res.stdout).toContain("启用");
|
||||
});
|
||||
|
||||
it("record get 获取记录详情", async () => {
|
||||
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
|
||||
spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any));
|
||||
spies.push(spyOn(api, "getRecordDetail").mockResolvedValue({
|
||||
dataLink: {
|
||||
id: "r-1",
|
||||
name: "测试项目",
|
||||
code: "P-100",
|
||||
active: true,
|
||||
createTime: 12345678,
|
||||
updateTime: 12345679,
|
||||
form: { customField: "测试值" },
|
||||
},
|
||||
}));
|
||||
|
||||
const res = await handlePlatformCommand(
|
||||
{ area: "platform", action: "record", args: ["get", "platform-1", "entity-1", "r-1"], options: {}, raw: [] },
|
||||
dummyRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("测试项目");
|
||||
expect(res.stdout).toContain("P-100");
|
||||
expect(res.stdout).toContain("测试值");
|
||||
});
|
||||
|
||||
it("record toggle 切换停启用状态", async () => {
|
||||
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
|
||||
spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any));
|
||||
const toggleSpy = spyOn(api, "toggleRecordState").mockResolvedValue({ recordId: "r-1", active: true });
|
||||
spies.push(toggleSpy);
|
||||
|
||||
const res = await handlePlatformCommand(
|
||||
{ area: "platform", action: "record", args: ["toggle", "platform-1", "entity-1", "r-1"], options: {}, raw: [] },
|
||||
dummyRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("状态已成功切换为");
|
||||
expect(toggleSpy).toHaveBeenCalledWith(expect.anything(), "corp-1", "r-1", undefined);
|
||||
});
|
||||
|
||||
it("record edit 编辑字段", async () => {
|
||||
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
|
||||
spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any));
|
||||
const editSpy = spyOn(api, "editRecord").mockResolvedValue({ id: "r-1" } as any);
|
||||
spies.push(editSpy);
|
||||
|
||||
const res = await handlePlatformCommand(
|
||||
{
|
||||
area: "platform",
|
||||
action: "record",
|
||||
args: ["edit", "platform-1", "entity-1", "r-1"],
|
||||
options: { data: '{"name":"更新后的名称"}' },
|
||||
raw: [],
|
||||
},
|
||||
dummyRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("字段更新成功");
|
||||
expect(editSpy).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
"corp-1",
|
||||
expect.objectContaining({
|
||||
dataLinkEntityId: "entity-1",
|
||||
dataLinkId: "r-1",
|
||||
form: { name: "更新后的名称" },
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("record recompute 触发台账重算", async () => {
|
||||
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
|
||||
spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any));
|
||||
const recomputeSpy = spyOn(api, "recomputeRecordLedger").mockResolvedValue({ id: "ok" });
|
||||
spies.push(recomputeSpy);
|
||||
|
||||
const res = await handlePlatformCommand(
|
||||
{ area: "platform", action: "record", args: ["recompute", "platform-1", "entity-1", "r-1"], options: {}, raw: [] },
|
||||
dummyRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("台账重算任务已成功触发");
|
||||
expect(recomputeSpy).toHaveBeenCalledWith(expect.anything(), "corp-1", "r-1");
|
||||
});
|
||||
});
|
||||
+283
-40
@@ -1,64 +1,307 @@
|
||||
import * as api from "../../domains/platform/api.js";
|
||||
import * as api from "../../domains/datalink/api.js";
|
||||
import { buildKeywordFilter, resolveEntity, resolvePlatform, selectRecordFields } from "../../domains/datalink/services.js";
|
||||
import { createClientsForCorp } from "../helpers.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
|
||||
export async function handlePlatformCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const currentCorp = runtime.selectedCorp;
|
||||
if (!currentCorp) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
function requiredTarget(parsed: CliParsedArgs, index: number, usage: string): string {
|
||||
const target = parsed.args[index]?.trim();
|
||||
if (!target) throw new Error(`请提供目标参数: ${usage}`);
|
||||
return target;
|
||||
}
|
||||
|
||||
function splitFields(value?: string): string[] {
|
||||
return value ? value.split(",").map((field) => field.trim()).filter(Boolean) : [];
|
||||
}
|
||||
|
||||
function cell(value: unknown): string {
|
||||
if (value === undefined || value === null) return "";
|
||||
if (typeof value === "object") return JSON.stringify(value);
|
||||
return String(value);
|
||||
}
|
||||
|
||||
async function resolveAppAndEntity(parsed: CliParsedArgs, runtime: CliRuntime, appIndex = 0, entityIndex = 1) {
|
||||
const appTarget = requiredTarget(parsed, appIndex, "hose-use platform <子命令> <应用 ID|名称>");
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const corpId = runtime.selectedCorp!.credentials.corpId;
|
||||
const platform = await resolvePlatform(clients.ekbClient, corpId, appTarget);
|
||||
if (!platform) throw new Error(`[NOT FOUND] 当前企业下未找到自建应用: ${appTarget}`);
|
||||
|
||||
const entityTarget = parsed.args[entityIndex]?.trim();
|
||||
if (!entityTarget) return { clients, corpId, platform, entity: undefined };
|
||||
const entity = await resolveEntity(clients.ekbClient, corpId, platform, entityTarget);
|
||||
if (!entity) throw new Error(`[NOT FOUND] 应用 [${platform.name}] 下未找到业务对象: ${entityTarget}`);
|
||||
return { clients, corpId, platform, entity };
|
||||
}
|
||||
|
||||
export async function handlePlatformCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
if (!runtime.selectedCorp) {
|
||||
return { stdout: "", stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n", exitCode: 1 };
|
||||
}
|
||||
|
||||
const action = parsed.action || "list";
|
||||
const isWorkbench = action === "workbench" || booleanOption(parsed.options, ["workbench", "w"], false);
|
||||
if (isWorkbench) {
|
||||
const { handleAppCommand } = await import("./app.js");
|
||||
return handleAppCommand(parsed, runtime);
|
||||
}
|
||||
|
||||
switch (action) {
|
||||
case "list":
|
||||
case "ls":
|
||||
return handleList(parsed, runtime);
|
||||
case "apps": return handleList(parsed, runtime);
|
||||
case "get":
|
||||
case "show": return handleGet(parsed, runtime);
|
||||
case "entities":
|
||||
case "objects": return handleEntities(parsed, runtime);
|
||||
case "schema":
|
||||
case "fields": return handleSchema(parsed, runtime);
|
||||
case "records":
|
||||
case "data":
|
||||
case "search": return handleRecords(parsed, runtime);
|
||||
case "record":
|
||||
case "record-get":
|
||||
case "record-toggle":
|
||||
case "record-edit":
|
||||
case "record-recompute": return handleRecordAction(parsed, runtime);
|
||||
case "permissions":
|
||||
case "permission":
|
||||
case "auth": return handlePermissions(parsed, runtime);
|
||||
case "imports":
|
||||
case "import-jobs": return handleImports(parsed, runtime);
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 platform 子命令: ${action}。支持: list\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
return { stdout: "", stderr: `未知 platform 子命令: ${action}。支持: list, get, entities, schema, records, record, permissions, imports\n`, exitCode: 1 };
|
||||
}
|
||||
}
|
||||
|
||||
async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const platforms = await api.listPlatforms(clients.ekbClient, runtime.selectedCorp!.credentials.corpId);
|
||||
const isAll = booleanOption(parsed.options, ["all", "a"], false);
|
||||
const platforms = isAll
|
||||
? await api.listAllPlatforms(clients.ekbClient, runtime.selectedCorp!.credentials.corpId)
|
||||
: await api.listPlatforms(clients.ekbClient, runtime.selectedCorp!.credentials.corpId);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(platforms, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
if (runtime.jsonMode) return { stdout: printJson({ count: platforms.length, all: isAll, platforms }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
if (platforms.length === 0) return { stdout: `企业 [${runtime.selectedCorp!.name}] 下暂无自建应用\n`, stderr: "", exitCode: 0 };
|
||||
const rows = platforms.map((p, i) => [i + 1, p.id, p.name, p.code, p.active ? "🟢 已启用" : "⚪ 未启用"]);
|
||||
const label = isAll ? "自建应用与模板全量列表" : "自建应用列表";
|
||||
return { stdout: `====== [${runtime.selectedCorp!.name}] ${label} (共 ${platforms.length} 个) ======\n${printTable(["#", "自建应用 ID", "应用名称", "编码", "状态"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleGet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const { platform } = await resolveAppAndEntity(parsed, runtime);
|
||||
if (runtime.jsonMode) return { stdout: printJson(platform, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `====== 自建应用详情: ${platform.name} ======\n${printTable(["字段", "值"], [
|
||||
["ID", platform.id], ["编码", platform.code], ["状态", platform.active ? "已启用" : "未启用"],
|
||||
["管理员数量", platform.adminIds.length], ["可见人员数量", platform.staffIds.length],
|
||||
["可见角色数量", platform.roleIds.length], ["可见部门数量", platform.departmentIds.length],
|
||||
["包含子部门", platform.departmentsIncludeChildren ? "是" : "否"],
|
||||
])}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleEntities(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const { clients, corpId, platform } = await resolveAppAndEntity(parsed, runtime);
|
||||
const entities = await api.listPlatformEntities(clients.ekbClient, corpId, platform.id);
|
||||
const keyword = stringOption(parsed.options, ["keyword", "q"])?.toLowerCase();
|
||||
const filtered = keyword ? entities.filter((entity) => [entity.id, entity.name, entity.code].some((value) => value.toLowerCase().includes(keyword))) : entities;
|
||||
if (runtime.jsonMode) return { stdout: printJson({ platform, keyword, total: entities.length, count: filtered.length, entities: filtered }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows = filtered.map((entity, i) => [i + 1, entity.id, entity.name, entity.code, entity.fields.length, entity.active ? "🟢 已启用" : "⚪ 未启用"]);
|
||||
return { stdout: `====== 应用 [${platform.name}] 业务对象 (匹配 ${filtered.length} / 共 ${entities.length} 个) ======\n${printTable(["#", "对象 ID", "对象名称", "编码", "字段数", "状态"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleSchema(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime);
|
||||
const entities = resolved.entity ? [resolved.entity] : await api.listPlatformEntities(resolved.clients.ekbClient, resolved.corpId, resolved.platform.id);
|
||||
const fieldKeyword = stringOption(parsed.options, ["keyword", "field", "name"])?.toLowerCase();
|
||||
const output = entities.map((entity) => ({ ...entity, fields: fieldKeyword ? entity.fields.filter((field) => [field.name, field.label, field.type].some((value) => value.toLowerCase().includes(fieldKeyword))) : entity.fields }));
|
||||
if (runtime.jsonMode) return { stdout: printJson({ platform: resolved.platform, count: output.length, entities: output }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows = output.flatMap((entity) => entity.fields.map((field): Array<string | number | boolean | null | undefined> => [entity.name, field.name, field.label, field.type, field.optional === false ? "必填" : "可选", cell(field.entity)]));
|
||||
return { stdout: `====== 应用 [${resolved.platform.name}] 字段定义 ======\n${printTable(["业务对象", "字段名", "显示名", "类型", "必填性", "引用对象"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime);
|
||||
if (!resolved.entity) throw new Error("请提供业务对象 ID、编码或名称: hose-use platform records <应用> <业务对象>");
|
||||
const keyword = stringOption(parsed.options, ["keyword", "q", "query"]);
|
||||
const filterBy = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]) || (keyword ? buildKeywordFilter(keyword) : undefined);
|
||||
const start = numberOption(parsed.options, ["start", "offset"], 0);
|
||||
const count = numberOption(parsed.options, ["count", "limit"], 20);
|
||||
const fields = splitFields(stringOption(parsed.options, ["fields", "select"]));
|
||||
const page = await api.searchEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { start, count, filterBy });
|
||||
const data = fields.length ? page.data.map((item) => selectRecordFields(item, fields, resolved.entity!.fields)) : page.data;
|
||||
const result = { platform: resolved.platform, entity: resolved.entity, query: { start, count, filterBy, fields }, total: page.total, returned: data.length, data };
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const nameField = resolved.entity.fields.find((f) => f.label === "名称" || f.label.includes("名称") || f.name.endsWith("_name"));
|
||||
const codeField = resolved.entity.fields.find((f) => f.label === "编码" || f.label.includes("编码") || f.name.endsWith("_code"));
|
||||
const rows = data.map((item, i): Array<string | number | boolean | null | undefined> => {
|
||||
const source = item.dataLink && typeof item.dataLink === "object" && !Array.isArray(item.dataLink) ? (item.dataLink as Record<string, unknown>) : item;
|
||||
const id = source.id ?? item.id;
|
||||
const active = source.active ?? item.active;
|
||||
const updateTime = source.updateTime ?? item.updateTime;
|
||||
const nameVal = source.name ?? source["名称"] ?? (nameField ? source[nameField.name] : undefined) ?? source[`E_${resolved.entity!.id}_name`];
|
||||
const codeVal = source.code ?? source["编码"] ?? (codeField ? source[codeField.name] : undefined) ?? source[`E_${resolved.entity!.id}_code`];
|
||||
const formattedTime = typeof updateTime === "number" ? new Date(updateTime).toLocaleString("zh-CN", { hour12: false }) : cell(updateTime);
|
||||
return [i + 1, cell(id), cell(nameVal), cell(codeVal), active === false ? "停用" : "启用", formattedTime];
|
||||
});
|
||||
return { stdout: `====== [${resolved.platform.name}] ${resolved.entity.name} 记录 (总数: ${page.total}, 当前: ${data.length}) ======\n${printTable(["#", "记录 ID", "名称", "编码", "状态", "更新时间"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handlePermissions(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime);
|
||||
const appPermission = { adminIds: resolved.platform.adminIds, staffIds: resolved.platform.staffIds, roleIds: resolved.platform.roleIds, departmentIds: resolved.platform.departmentIds, departmentsIncludeChildren: resolved.platform.departmentsIncludeChildren };
|
||||
const result = resolved.entity ? { platform: resolved.platform, entity: resolved.entity, appPermission } : { platform: resolved.platform, appPermission };
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows: Array<Array<string | number | boolean | null | undefined>> = [["应用管理员", resolved.platform.adminIds.length], ["应用可见人员", resolved.platform.staffIds.length], ["应用可见角色", resolved.platform.roleIds.length], ["应用可见部门", resolved.platform.departmentIds.length]];
|
||||
if (resolved.entity) rows.push(["对象可见性", cell(resolved.entity.visibility)], ["首页可见性", cell(resolved.entity.homeVisibility)], ["导出权限", cell(resolved.entity.exportVisibility)], ["数据过滤", cell(resolved.entity.dataFilter)]);
|
||||
return { stdout: `====== 权限信息: ${resolved.platform.name}${resolved.entity ? ` / ${resolved.entity.name}` : ""} ======\n${printTable(["权限项", "值"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleImports(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime);
|
||||
if (!resolved.entity) throw new Error("请提供业务对象 ID、编码或名称: hose-use platform imports <应用> <业务对象>");
|
||||
const [jobs, latestResult] = await Promise.all([
|
||||
api.listImportJobs(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id),
|
||||
api.getImportResult(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id),
|
||||
]);
|
||||
const result = { platform: resolved.platform, entity: resolved.entity, jobs, latestResult };
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `====== 导入任务: ${resolved.platform.name} / ${resolved.entity.name} ======\n${printTable(["#", "任务"], jobs.map((job, i) => [i + 1, cell(job)]))}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const action = parsed.action?.toLowerCase() || "record";
|
||||
let subAction: string;
|
||||
let appIndex: number;
|
||||
let entityIndex: number;
|
||||
let recordIdIndex: number;
|
||||
|
||||
if (action.startsWith("record-")) {
|
||||
subAction = action.replace("record-", "");
|
||||
appIndex = 0;
|
||||
entityIndex = 1;
|
||||
recordIdIndex = 2;
|
||||
} else {
|
||||
const firstArg = parsed.args[0]?.toLowerCase();
|
||||
if (["get", "show", "detail", "toggle", "state", "edit", "update", "recompute", "recalc"].includes(firstArg)) {
|
||||
subAction = firstArg;
|
||||
appIndex = 1;
|
||||
entityIndex = 2;
|
||||
recordIdIndex = 3;
|
||||
} else {
|
||||
subAction = "get";
|
||||
appIndex = 0;
|
||||
entityIndex = 1;
|
||||
recordIdIndex = 2;
|
||||
}
|
||||
}
|
||||
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime, appIndex, entityIndex);
|
||||
if (!resolved.entity) throw new Error("请提供业务对象 ID、编码或名称: hose-use platform record <动作> <应用> <业务对象> <记录ID>");
|
||||
const recordId = requiredTarget(parsed, recordIdIndex, "hose-use platform record <动作> <应用> <业务对象> <记录ID>");
|
||||
|
||||
switch (subAction) {
|
||||
case "get":
|
||||
case "show":
|
||||
case "detail": {
|
||||
const detail = await api.getRecordDetail(resolved.clients.ekbClient, resolved.corpId, recordId);
|
||||
if (runtime.jsonMode) return { stdout: printJson(detail, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const record = ((detail.dataLink ?? (detail as any).data?.dataLink ?? detail) as Record<string, unknown>);
|
||||
const nameField = resolved.entity.fields.find((f) => f.label === "名称" || f.label.includes("名称") || f.name.endsWith("_name"));
|
||||
const codeField = resolved.entity.fields.find((f) => f.label === "编码" || f.label.includes("编码") || f.name.endsWith("_code"));
|
||||
const nameVal = record.name ?? record["名称"] ?? (nameField ? record[nameField.name] : undefined) ?? record[`E_${resolved.entity.id}_name`];
|
||||
const codeVal = record.code ?? record["编码"] ?? (codeField ? record[codeField.name] : undefined) ?? record[`E_${resolved.entity.id}_code`];
|
||||
|
||||
if (platforms.length === 0) {
|
||||
return {
|
||||
stdout: `企业 [${runtime.selectedCorp!.name}] 下暂无自建应用\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
const formatTime = (time: unknown) => typeof time === "number" ? new Date(time).toLocaleString("zh-CN", { hour12: false }) : cell(time);
|
||||
|
||||
const rows = platforms.map((p, i) => [
|
||||
i + 1,
|
||||
p.id,
|
||||
p.name,
|
||||
p.active ? "🟢 已启用" : "⚪ 未启用",
|
||||
]);
|
||||
const rows: Array<Array<string | number | boolean | null | undefined>> = [
|
||||
["记录 ID", cell(record.id ?? recordId)],
|
||||
["业务对象", `${resolved.entity.name} (${resolved.entity.id})`],
|
||||
["名称", cell(nameVal)],
|
||||
["编码", cell(codeVal)],
|
||||
["状态", record.active === false ? "🔴 停用" : "🟢 启用"],
|
||||
["创建时间", formatTime(record.createTime)],
|
||||
["更新时间", formatTime(record.updateTime)],
|
||||
];
|
||||
|
||||
const table = printTable(["#", "自建应用 ID", "应用名称", "状态"], rows);
|
||||
for (const field of resolved.entity.fields) {
|
||||
if (field.name === nameField?.name || field.name === codeField?.name) continue;
|
||||
const val = record[field.name] ?? record[`E_${resolved.entity.id}_${field.name}`] ?? (record.form as Record<string, unknown> | undefined)?.[field.name] ?? record[field.label];
|
||||
if (val !== undefined && val !== null && val !== "") {
|
||||
let displayVal = val;
|
||||
if (field.type === "date" && typeof val === "number") {
|
||||
displayVal = new Date(val).toLocaleDateString("zh-CN");
|
||||
} else if (field.type === "money" && typeof val === "object" && val !== null && "standard" in (val as any)) {
|
||||
displayVal = `${(val as any).standard} ${(val as any).standardStrCode || "CNY"}`;
|
||||
}
|
||||
rows.push([`${field.label} (${field.name})`, cell(displayVal)]);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `====== [${runtime.selectedCorp!.name}] 自建应用列表 (共 ${platforms.length} 个) ======\n${table}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
return {
|
||||
stdout: `====== 记录详情: [${resolved.platform.name}] ${resolved.entity.name} (${recordId}) ======\n${printTable(["字段/属性", "值"], rows)}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
case "toggle":
|
||||
case "state": {
|
||||
const explicitState = parsed.options.state !== undefined
|
||||
? booleanOption(parsed.options, ["state"], true)
|
||||
: parsed.options.active !== undefined
|
||||
? booleanOption(parsed.options, ["active"], true)
|
||||
: undefined;
|
||||
const res = await api.toggleRecordState(resolved.clients.ekbClient, resolved.corpId, recordId, explicitState);
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ success: true, recordId: res.recordId, active: res.active, app: resolved.platform.name, entity: resolved.entity.name }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
const label = res.active ? "🟢 启用" : "🔴 停用";
|
||||
return {
|
||||
stdout: `✅ 应用 [${resolved.platform.name}] 业务对象 [${resolved.entity.name}] 记录 [${recordId}] 状态已成功切换为 [${label}]。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
case "edit":
|
||||
case "update": {
|
||||
const dataStr = stringOption(parsed.options, ["data", "form", "d", "f"]);
|
||||
let form: Record<string, unknown> = {};
|
||||
if (dataStr) {
|
||||
try {
|
||||
form = JSON.parse(dataStr);
|
||||
} catch {
|
||||
throw new Error("提供的 --data 参数不是合法的 JSON 字符串");
|
||||
}
|
||||
}
|
||||
const activeOpt = parsed.options.active !== undefined ? booleanOption(parsed.options, ["active"], true) : undefined;
|
||||
const result = await api.editRecord(resolved.clients.ekbClient, resolved.corpId, {
|
||||
dataLinkEntityId: resolved.entity.id,
|
||||
dataLinkId: recordId,
|
||||
form,
|
||||
active: activeOpt,
|
||||
});
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return {
|
||||
stdout: `✅ 应用 [${resolved.platform.name}] 业务对象 [${resolved.entity.name}] 记录 [${recordId}] 字段更新成功。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
case "recompute":
|
||||
case "recalc": {
|
||||
const result = await api.recomputeRecordLedger(resolved.clients.ekbClient, resolved.corpId, recordId);
|
||||
if (runtime.jsonMode) return { stdout: printJson({ success: true, recordId, result }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return {
|
||||
stdout: `✅ 应用 [${resolved.platform.name}] 业务对象 [${resolved.entity.name}] 记录 [${recordId}] 台账重算任务已成功触发。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
default:
|
||||
throw new Error(`未知 record 动作: ${subAction}。支持: get, toggle, edit, recompute`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import { describe, expect, test, spyOn } from "bun:test";
|
||||
import { handleStoreCommand } from "./store.js";
|
||||
import type { CliRuntime, CliParsedArgs } from "../types.js";
|
||||
import * as storeTools from "../../domains/store/tools.js";
|
||||
|
||||
describe("CLI - store 应用中心与应用商店探查", () => {
|
||||
const dummyCorp: any = {
|
||||
id: "test-corp-id",
|
||||
name: "测试企业A",
|
||||
corpId: "test-corp-id",
|
||||
credentials: { corpId: "test-corp-id", accessToken: "token123" },
|
||||
};
|
||||
|
||||
const createRuntime = (corp: any = dummyCorp, jsonMode = false): CliRuntime => ({
|
||||
corpContext: {} as any,
|
||||
selectedCorp: corp,
|
||||
jsonMode,
|
||||
});
|
||||
|
||||
test("未选中企业时返回提示并报错", async () => {
|
||||
const runtime = createRuntime(null);
|
||||
const parsed: CliParsedArgs = { area: "store", options: {}, args: [], raw: ["store"] };
|
||||
const res = await handleStoreCommand(parsed, runtime);
|
||||
expect(res.exitCode).toBe(1);
|
||||
expect(res.stderr).toContain("未选中企业");
|
||||
});
|
||||
|
||||
test("store list 展示企业已购应用列表", async () => {
|
||||
const spy = spyOn(storeTools, "fetchClientGoods").mockImplementation(() =>
|
||||
Promise.resolve([
|
||||
{
|
||||
id: "g-1",
|
||||
name: "开放接口(新)",
|
||||
status: "OPENED",
|
||||
expireTime: 1914422399000,
|
||||
hasConfig: true,
|
||||
powers: [{ powerCode: "219904", powerName: "开放接口(新)" }],
|
||||
},
|
||||
] as any)
|
||||
);
|
||||
|
||||
const runtime = createRuntime(dummyCorp);
|
||||
const parsed: CliParsedArgs = {
|
||||
area: "store",
|
||||
action: "list",
|
||||
options: {},
|
||||
args: [],
|
||||
raw: ["store", "list"],
|
||||
};
|
||||
const res = await handleStoreCommand(parsed, runtime);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("开放接口(新)");
|
||||
expect(res.stdout).toContain("已开通");
|
||||
expect(res.stdout).toContain("支持配置");
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
test("store search 检索应用市场商品", async () => {
|
||||
const spy = spyOn(storeTools, "searchGoods").mockImplementation(() =>
|
||||
Promise.resolve({
|
||||
total: 1,
|
||||
items: [
|
||||
{
|
||||
id: "g-2",
|
||||
name: "纷享销客基础互联应用",
|
||||
status: "OPENED",
|
||||
summary: "连接纷享销客",
|
||||
},
|
||||
],
|
||||
} as any)
|
||||
);
|
||||
|
||||
const runtime = createRuntime(dummyCorp);
|
||||
const parsed: CliParsedArgs = {
|
||||
area: "store",
|
||||
action: "search",
|
||||
options: {},
|
||||
args: ["纷享"],
|
||||
raw: ["store", "search", "纷享"],
|
||||
};
|
||||
const res = await handleStoreCommand(parsed, runtime);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("纷享销客基础互联应用");
|
||||
expect(res.stdout).toContain("连接纷享销客");
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
test("store get 查看应用详情", async () => {
|
||||
const spy = spyOn(storeTools, "fetchGoodsDetail").mockImplementation(() =>
|
||||
Promise.resolve({
|
||||
id: "g-1",
|
||||
name: "开放接口(新)",
|
||||
status: "OPENED",
|
||||
hasConfig: true,
|
||||
configStyle: "SIDESLIP",
|
||||
powers: [{ powerCode: "219904", powerName: "开放接口(新)" }],
|
||||
summary: "OpenAPI提供标准化接口",
|
||||
} as any)
|
||||
);
|
||||
|
||||
const runtime = createRuntime(dummyCorp);
|
||||
const parsed: CliParsedArgs = {
|
||||
area: "store",
|
||||
action: "get",
|
||||
options: {},
|
||||
args: ["g-1"],
|
||||
raw: ["store", "get", "g-1"],
|
||||
};
|
||||
const res = await handleStoreCommand(parsed, runtime);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("开放接口(新)");
|
||||
expect(res.stdout).toContain("219904");
|
||||
expect(res.stdout).toContain("SIDESLIP");
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
test("store keys 转发至 keys 执行器", async () => {
|
||||
const spy = spyOn(storeTools, "fetchOpenApiKeys").mockImplementation(() =>
|
||||
Promise.resolve([
|
||||
{
|
||||
id: "k-1",
|
||||
name: "Store转发密钥",
|
||||
appKey: "store-key-123",
|
||||
appSecurity: "store-secret-456",
|
||||
active: true,
|
||||
createTime: 1751357077503,
|
||||
updateTime: 1769063905460,
|
||||
},
|
||||
])
|
||||
);
|
||||
|
||||
const runtime = createRuntime(dummyCorp);
|
||||
const parsed: CliParsedArgs = {
|
||||
area: "store",
|
||||
action: "keys",
|
||||
options: {},
|
||||
args: [],
|
||||
raw: ["store", "keys"],
|
||||
};
|
||||
const res = await handleStoreCommand(parsed, runtime);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("Store转发密钥");
|
||||
expect(res.stdout).toContain("store-key-123");
|
||||
spy.mockRestore();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,239 @@
|
||||
import {
|
||||
fetchClientGoods,
|
||||
searchGoods,
|
||||
fetchGoodsDetail,
|
||||
} from "../../domains/store/tools.js";
|
||||
import { booleanOption, stringOption } from "../parser.js";
|
||||
import { printJson, printKeyValue, printTable } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { handleKeysCommand } from "./keys.js";
|
||||
|
||||
function formatDate(ts: number | null | undefined): string {
|
||||
if (!ts) return "长期有效";
|
||||
const d = new Date(ts);
|
||||
if (isNaN(d.getTime())) return "-";
|
||||
const Y = d.getFullYear();
|
||||
const M = String(d.getMonth() + 1).padStart(2, "0");
|
||||
const D = String(d.getDate()).padStart(2, "0");
|
||||
return `${Y}/${M}/${D}`;
|
||||
}
|
||||
|
||||
function formatStatus(status: string | null | undefined): string {
|
||||
if (!status) return "-";
|
||||
switch (status.toUpperCase()) {
|
||||
case "OPENED":
|
||||
return "🟢 已开通";
|
||||
case "EXPIRE":
|
||||
return "🔴 已过期";
|
||||
case "APPLYING":
|
||||
return "🟡 申请中";
|
||||
case "CLOSED":
|
||||
return "⚪ 已关闭";
|
||||
default:
|
||||
return status;
|
||||
}
|
||||
}
|
||||
|
||||
export async function handleStoreCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const currentCorp = runtime.selectedCorp;
|
||||
if (!currentCorp) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const action = (parsed.action || "list").toLowerCase();
|
||||
|
||||
switch (action) {
|
||||
case "keys":
|
||||
case "key":
|
||||
return handleKeysCommand(parsed, runtime);
|
||||
|
||||
case "list":
|
||||
case "ls":
|
||||
return handleList(parsed, runtime);
|
||||
|
||||
case "search":
|
||||
case "find":
|
||||
return handleSearch(parsed, runtime);
|
||||
|
||||
case "get":
|
||||
case "info":
|
||||
case "detail":
|
||||
return handleGet(parsed, runtime);
|
||||
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 store 子命令: ${action}。支持: list, search, get, keys\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const currentCorp = runtime.selectedCorp!;
|
||||
const keyword = parsed.args[0] || stringOption(parsed.options, ["name", "keyword", "k"]);
|
||||
const isAll = booleanOption(parsed.options, ["all", "a"]);
|
||||
|
||||
try {
|
||||
const items = await fetchClientGoods(currentCorp, { keyword, isAll });
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(items, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (items.length === 0) {
|
||||
return {
|
||||
stdout: `企业 [${currentCorp.name}] 暂无匹配的已购应用${keyword ? ` (搜索: ${keyword})` : ""}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = items.map((item, i) => {
|
||||
const powersStr = (item.powers || [])
|
||||
.map((p) => (typeof p === "string" ? p : p.powerName || p.powerCode || ""))
|
||||
.filter(Boolean)
|
||||
.join(", ");
|
||||
|
||||
return [
|
||||
i + 1,
|
||||
item.id,
|
||||
item.name,
|
||||
formatStatus(item.status),
|
||||
formatDate(item.expireTime),
|
||||
item.hasConfig ? "支持配置" : "-",
|
||||
powersStr || "-",
|
||||
];
|
||||
});
|
||||
|
||||
const table = printTable(
|
||||
["#", "应用 ID", "应用名称", "开通状态", "有效期限", "配置支持", "绑定能力 (Powers)"],
|
||||
rows
|
||||
);
|
||||
|
||||
const title = `====== [${currentCorp.name}] 企业已开通/已购应用列表 (共 ${items.length} 个) ======`;
|
||||
|
||||
return {
|
||||
stdout: `${title}\n\n${table}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
} catch (err: any) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `查询企业已购应用失败: ${err?.message || err}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const currentCorp = runtime.selectedCorp!;
|
||||
const keyword = parsed.args[0] || stringOption(parsed.options, ["name", "keyword", "k"]) || "";
|
||||
|
||||
try {
|
||||
const result = await searchGoods(currentCorp, { keyword, count: 20 });
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(result, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (result.items.length === 0) {
|
||||
return {
|
||||
stdout: `应用商店未搜索到匹配应用${keyword ? ` (关键词: ${keyword})` : ""}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = result.items.map((item, i) => [
|
||||
i + 1,
|
||||
item.id,
|
||||
item.name,
|
||||
formatStatus(item.status),
|
||||
item.summary || "-",
|
||||
]);
|
||||
|
||||
const table = printTable(["#", "商品 ID", "应用名称", "企业状态", "应用简介"], rows);
|
||||
const title = `====== 合思应用商店搜索结果 (共 ${result.total} 条,当前展示 ${result.items.length} 条) ======`;
|
||||
|
||||
return {
|
||||
stdout: `${title}\n\n${table}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
} catch (err: any) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `搜索应用商店失败: ${err?.message || err}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function handleGet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const currentCorp = runtime.selectedCorp!;
|
||||
const goodsId = parsed.args[0] || stringOption(parsed.options, ["id"]);
|
||||
|
||||
if (!goodsId) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "请提供应用/商品 ID,例如: hose-use store get O1w2Hg000000qw\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const detail = await fetchGoodsDetail(currentCorp, goodsId);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(detail, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const powersStr = (detail.powers || [])
|
||||
.map((p) => `${p.powerName || p.powerCode || ""} (${p.powerCode || ""})`)
|
||||
.join(", ");
|
||||
|
||||
const out = printKeyValue({
|
||||
"应用 ID": detail.id,
|
||||
"应用名称": detail.name,
|
||||
"应用编码": detail.code || "-",
|
||||
"开通状态": formatStatus(detail.status),
|
||||
"有效期限": formatDate(detail.expireTime),
|
||||
"支持配置": detail.hasConfig ? `是 (${detail.configStyle || "默认"})` : "否",
|
||||
"绑定能力": powersStr || "-",
|
||||
"应用摘要": detail.summary || "-",
|
||||
});
|
||||
|
||||
return {
|
||||
stdout: `====== 应用详情: ${detail.name} ======\n${out}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
} catch (err: any) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `获取应用详情失败: ${err?.message || err}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
+19
-4
@@ -118,8 +118,8 @@ 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)
|
||||
@@ -127,7 +127,10 @@ export function printHelp(): string {
|
||||
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 <维度>)
|
||||
role 角色定义与成员 (list, groups, members <角色>)
|
||||
permission 权限模型快照 (get)
|
||||
@@ -136,7 +139,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)
|
||||
@@ -160,6 +165,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 +178,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 # 查看风控预警、预算与发票风险
|
||||
|
||||
+20
-1
@@ -7,6 +7,8 @@ import { handleCorpsCommand } from "./commands/corps.js";
|
||||
import { handleConfigCommand } from "./commands/config.js";
|
||||
import { handleWorkflowCommand } from "./commands/workflow.js";
|
||||
import { handlePlatformCommand } from "./commands/platform.js";
|
||||
import { handleAppCommand } from "./commands/app.js";
|
||||
import { handleMenuCommand } from "./commands/menu.js";
|
||||
import { handleSkillCommand } from "./commands/skill.js";
|
||||
import { handleProbeCommand } from "./commands/probe.js";
|
||||
import { handleMcpCommand } from "./commands/mcp.js";
|
||||
@@ -24,6 +26,8 @@ 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 type { CliParsedArgs, CliResult, CliRunOptions } from "./types.js";
|
||||
|
||||
const STANDING_COMMANDS = new Set(["http", "server", "web", "mcp"]);
|
||||
@@ -209,9 +213,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 +238,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":
|
||||
|
||||
+61
-1
@@ -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);
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -7,7 +7,9 @@
|
||||
| 域 | 说明 | 详细文档 |
|
||||
|---|---|---|
|
||||
| `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) |
|
||||
|
||||
## 分层规则
|
||||
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
# DataLink 域说明
|
||||
|
||||
DataLink 域负责跨企业查询当前账号可见的自建应用、业务对象、字段定义、业务记录、权限快照和导入状态。
|
||||
|
||||
## 代码结构
|
||||
|
||||
```text
|
||||
src/domains/datalink/
|
||||
├── types.ts # 应用详情、对象字段、记录分页与权限模型
|
||||
├── api.ts # DataLink HTTP 传输层
|
||||
├── services.ts # 应用/对象名称解析与查询表达式辅助
|
||||
└── tools.ts # MCP tool 注册
|
||||
```
|
||||
|
||||
## 查询链路
|
||||
|
||||
```text
|
||||
platform/search
|
||||
└─ platform/{platformId} 应用详情与管理权限
|
||||
└─ entity/platformId/{platformId} 业务对象与字段定义
|
||||
└─ searchPlatformDataLinkWithChild/{entityId} 业务记录
|
||||
```
|
||||
|
||||
应用列表和应用详情使用 EKB client。记录查询的 `filterBy` 原样支持 DataLink 过滤表达式;CLI 另提供 `--keyword`,自动生成名称/编码模糊查询。
|
||||
|
||||
## CLI
|
||||
|
||||
```bash
|
||||
hose-use platform list
|
||||
hose-use platform get <应用 ID|名称>
|
||||
hose-use platform entities <应用 ID|名称>
|
||||
hose-use platform schema <应用 ID|名称> [对象 ID|名称] [--keyword <字段关键词>]
|
||||
hose-use platform records <应用 ID|名称> <对象 ID|名称> [--keyword <关键词>] [--filter <表达式>] [--fields <字段列表>]
|
||||
hose-use platform record get <应用> <业务对象> <记录ID>
|
||||
hose-use platform record toggle <应用> <业务对象> <记录ID> [--state=true|false]
|
||||
hose-use platform record edit <应用> <业务对象> <记录ID> --data='{"field": "val"}'
|
||||
hose-use platform record recompute <应用> <业务对象> <记录ID>
|
||||
hose-use platform permissions <应用 ID|名称> [对象 ID|名称]
|
||||
hose-use platform imports <应用 ID|名称> <对象 ID|名称>
|
||||
```
|
||||
|
||||
也可以使用 `datalink` / `data-link` 作为同义命令域。
|
||||
|
||||
单条业务对象记录支持通过 `record get`(详情)、`record toggle`(启停用)、`record edit`(字段编辑更新)以及 `record recompute`(台账重算)进行维护。Excel 批量上传与流程引擎触发暂不在本域开放。
|
||||
@@ -0,0 +1,280 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import {
|
||||
DatalinkEntitySchema,
|
||||
DatalinkPlatformDetailSchema,
|
||||
type DatalinkEntity,
|
||||
type DatalinkImportJob,
|
||||
type DatalinkPlatformDetail,
|
||||
type DatalinkRecord,
|
||||
type DatalinkRecordDetail,
|
||||
type DatalinkRecordEditPayload,
|
||||
type DatalinkRecordPage,
|
||||
type DatalinkRecordQuery,
|
||||
} from "./types.js";
|
||||
|
||||
function asRecord(value: unknown): Record<string, any> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as Record<string, any>)
|
||||
: {};
|
||||
}
|
||||
|
||||
function numberOr(value: unknown, fallback: number): number {
|
||||
const parsed = typeof value === "number" ? value : Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : fallback;
|
||||
}
|
||||
|
||||
function parseEntity(value: unknown): DatalinkEntity {
|
||||
return DatalinkEntitySchema.parse(asRecord(value));
|
||||
}
|
||||
|
||||
function sanitizePlatformDetail(value: unknown): Record<string, unknown> {
|
||||
const platform = asRecord(value);
|
||||
const admin = Array.isArray(platform.admin)
|
||||
? platform.admin.map((item) => {
|
||||
const staff = asRecord(item);
|
||||
return {
|
||||
id: staff.id,
|
||||
name: staff.name,
|
||||
code: staff.code,
|
||||
active: staff.active,
|
||||
};
|
||||
})
|
||||
: platform.admin;
|
||||
return { ...platform, admin };
|
||||
}
|
||||
|
||||
/** 列出当前企业可见的启用自建应用。 */
|
||||
export async function listPlatforms(client: KyInstance, corpId: string) {
|
||||
const response = await client.get("api/v2/datalink/platform/search", {
|
||||
searchParams: { scope: "enable", corpId },
|
||||
});
|
||||
const json = asRecord(await response.json());
|
||||
const items = Array.isArray(json.items) ? json.items.map(sanitizePlatformDetail) : [];
|
||||
return z.array(DatalinkPlatformDetailSchema).parse(items);
|
||||
}
|
||||
|
||||
/** 列出当前企业全量自建应用与模板平台(包含 HAB 模板与全部自建应用)。 */
|
||||
export async function listAllPlatforms(client: KyInstance, corpId: string) {
|
||||
const response = await client.get("api/v2/datalink/platform", {
|
||||
searchParams: { corpId },
|
||||
});
|
||||
const json = asRecord(await response.json());
|
||||
const rawList = Array.isArray(json) ? json : Array.isArray(json.items) ? json.items : [];
|
||||
const items = rawList.map(sanitizePlatformDetail);
|
||||
return z.array(DatalinkPlatformDetailSchema).parse(items);
|
||||
}
|
||||
|
||||
/** 获取单个应用详情以及应用级人员/角色/部门权限。 */
|
||||
export async function getPlatform(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
platformId: string
|
||||
): Promise<DatalinkPlatformDetail> {
|
||||
const normalizedId = platformId.startsWith("$") ? platformId : `$${platformId}`;
|
||||
const bareId = platformId.startsWith("$") ? platformId.slice(1) : platformId;
|
||||
const response = await client.get(`api/v2/datalink/platform/${normalizedId}`, {
|
||||
// 前端实际使用两个 join,并且详情接口要求同时传 id。
|
||||
searchParams: new URLSearchParams([
|
||||
["id", bareId],
|
||||
["join", "icon.fileId,fileId,/v1/attachment/attachments"],
|
||||
["corpId", corpId],
|
||||
["join", "adminIds,admin,/v1/organization/staffs"],
|
||||
]),
|
||||
});
|
||||
const json = asRecord(await response.json());
|
||||
return DatalinkPlatformDetailSchema.parse(sanitizePlatformDetail(json.value ?? json.data ?? json));
|
||||
}
|
||||
|
||||
/** 获取应用下的业务对象目录及完整字段定义。 */
|
||||
export async function listPlatformEntities(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
platformId: string
|
||||
): Promise<DatalinkEntity[]> {
|
||||
const normalizedId = platformId.startsWith("$") ? platformId : `$${platformId}`;
|
||||
const response = await client.post(`api/v2/datalink/entity/platformId/${normalizedId}`, {
|
||||
searchParams: { corpId },
|
||||
// 该 POST 即使没有筛选条件也要求发送空 JSON body;前端会发送 {}。
|
||||
json: {},
|
||||
});
|
||||
const json = asRecord(await response.json());
|
||||
const rawItems = Array.isArray(json.items)
|
||||
? json.items
|
||||
: Array.isArray(asRecord(json.value).items)
|
||||
? asRecord(json.value).items
|
||||
: [];
|
||||
return rawItems.map(parseEntity);
|
||||
}
|
||||
|
||||
/** 分页检索指定业务对象的记录。filterBy 使用 DataLink 原生表达式。 */
|
||||
export async function searchEntityRecords(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
entityId: string,
|
||||
query: DatalinkRecordQuery = {}
|
||||
): Promise<DatalinkRecordPage> {
|
||||
const normalizedId = entityId.startsWith("$") ? entityId : `$${entityId}`;
|
||||
const limit = {
|
||||
start: query.start ?? 0,
|
||||
count: query.count ?? 20,
|
||||
};
|
||||
const nativeQuery: Record<string, unknown> = {
|
||||
filterBy: query.filterBy?.trim() || "(active.in(true,false))",
|
||||
limit,
|
||||
};
|
||||
if (query.orderBy !== undefined) nativeQuery.orderBy = query.orderBy;
|
||||
|
||||
const response = await client.post(
|
||||
`api/v2/datalink/searchPlatformDataLinkWithChild/${normalizedId}`,
|
||||
{
|
||||
searchParams: { corpId },
|
||||
json: { query: nativeQuery, entityId },
|
||||
}
|
||||
);
|
||||
const json = asRecord(await response.json());
|
||||
const payload = asRecord(json.items && !Array.isArray(json.items) ? json.items : json.value ?? json);
|
||||
const rawData = Array.isArray(payload.data)
|
||||
? payload.data
|
||||
: Array.isArray(payload.items)
|
||||
? payload.items
|
||||
: Array.isArray(json.items)
|
||||
? json.items
|
||||
: [];
|
||||
|
||||
return {
|
||||
total: numberOr(payload.total ?? json.total, rawData.length),
|
||||
data: rawData.filter((item): item is DatalinkRecord => item !== null && typeof item === "object"),
|
||||
actions: Array.isArray(payload.actions) ? payload.actions : [],
|
||||
components: Array.isArray(payload.components) ? payload.components : [],
|
||||
path: payload.path,
|
||||
template: payload.template,
|
||||
};
|
||||
}
|
||||
|
||||
/** 查询对象导入任务状态。 */
|
||||
export async function listImportJobs(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
entityId: string
|
||||
): Promise<DatalinkImportJob[]> {
|
||||
const response = await client.get("api/engine/easo/batchJobs", {
|
||||
searchParams: { entityId, corpId },
|
||||
});
|
||||
const json = asRecord(await response.json());
|
||||
const items = json.items ?? asRecord(json.value).items ?? json.value ?? [];
|
||||
return Array.isArray(items) ? items.filter((item): item is DatalinkImportJob => item !== null && typeof item === "object") : [];
|
||||
}
|
||||
|
||||
/** 查询对象最近一次 Excel 导入结果。 */
|
||||
export async function getImportResult(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
entityId: string
|
||||
): Promise<Record<string, unknown>> {
|
||||
const normalizedId = entityId.startsWith("$") ? entityId : `$${entityId}`;
|
||||
const response = await client.get(`api/v1/datalink/excel/import/result/${normalizedId}`, {
|
||||
searchParams: { entityId, corpId },
|
||||
});
|
||||
return asRecord(await response.json());
|
||||
}
|
||||
|
||||
/** 切换业务对象记录的停启用状态 (active: true <-> false)。若未指定 state 则自动反转当前状态。 */
|
||||
export async function toggleRecordState(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
recordId: string,
|
||||
state?: boolean
|
||||
): Promise<{ recordId: string; active: boolean }> {
|
||||
const normalizedId = recordId.startsWith("$") ? recordId : `$${recordId}`;
|
||||
const bareId = recordId.startsWith("$") ? recordId.slice(1) : recordId;
|
||||
let targetState = state;
|
||||
if (targetState === undefined) {
|
||||
const detail = await getRecordDetail(client, corpId, recordId);
|
||||
const record = ((detail.dataLink ?? (detail as any).data?.dataLink ?? detail) as Record<string, unknown>);
|
||||
targetState = !(record.active ?? true);
|
||||
}
|
||||
|
||||
await client.put(`api/supplier/v3/contract/${normalizedId}/state`, {
|
||||
searchParams: { corpId },
|
||||
json: { id: bareId, state: targetState },
|
||||
});
|
||||
|
||||
return { recordId: bareId, active: targetState };
|
||||
}
|
||||
|
||||
/** 获取单条业务对象记录的完整详情(包含展示模板、字段值、可见性及审批历史等)。 */
|
||||
export async function getRecordDetail(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
recordId: string
|
||||
): Promise<DatalinkRecordDetail> {
|
||||
const normalizedId = recordId.startsWith("$") ? recordId : `$${recordId}`;
|
||||
const bareId = recordId.startsWith("$") ? recordId.slice(1) : recordId;
|
||||
const response = await client.get(`api/v2/datalink/detail/${normalizedId}/$DETAIL`, {
|
||||
searchParams: {
|
||||
dataLinkId: bareId,
|
||||
type: "DETAIL",
|
||||
corpId,
|
||||
},
|
||||
});
|
||||
const json = asRecord(await response.json());
|
||||
return (json.value ?? json.data ?? json) as DatalinkRecordDetail;
|
||||
}
|
||||
|
||||
/** 获取业务对象编辑表单的字段结构定义。 */
|
||||
export async function getRecordFormSchema(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
entityId: string
|
||||
): Promise<Record<string, unknown>> {
|
||||
const normalizedId = entityId.startsWith("$") ? entityId : `$${entityId}`;
|
||||
const bareId = entityId.startsWith("$") ? entityId.slice(1) : entityId;
|
||||
const response = await client.get(`api/v2/datalink/entityEdit/entityForm/${normalizedId}/$true`, {
|
||||
searchParams: {
|
||||
entityId: bareId,
|
||||
isInsert: "true",
|
||||
needFormula: "true",
|
||||
corpId,
|
||||
},
|
||||
});
|
||||
return asRecord(await response.json());
|
||||
}
|
||||
|
||||
/** 编辑更新业务对象记录字段。 */
|
||||
export async function editRecord(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
payload: DatalinkRecordEditPayload
|
||||
): Promise<Record<string, unknown>> {
|
||||
const bareEntityId = payload.dataLinkEntityId.startsWith("$")
|
||||
? payload.dataLinkEntityId.slice(1)
|
||||
: payload.dataLinkEntityId;
|
||||
const bareRecordId = payload.dataLinkId.startsWith("$")
|
||||
? payload.dataLinkId.slice(1)
|
||||
: payload.dataLinkId;
|
||||
|
||||
const response = await client.post("api/v2/datalink/entityEdit/edit", {
|
||||
searchParams: { corpId },
|
||||
json: {
|
||||
...payload,
|
||||
dataLinkEntityId: bareEntityId,
|
||||
dataLinkId: bareRecordId,
|
||||
},
|
||||
});
|
||||
const json = asRecord(await response.json());
|
||||
return (json.value ?? json.data ?? json) as Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** 重算业务对象记录下的台账信息。 */
|
||||
export async function recomputeRecordLedger(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
recordId: string
|
||||
): Promise<Record<string, unknown>> {
|
||||
const normalizedId = recordId.startsWith("$") ? recordId : `$${recordId}`;
|
||||
const response = await client.post(`api/v2/ledger/recompute/${normalizedId}`, {
|
||||
searchParams: { corpId },
|
||||
});
|
||||
return asRecord(await response.json());
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import {
|
||||
editRecord,
|
||||
getPlatform,
|
||||
getRecordDetail,
|
||||
listPlatformEntities,
|
||||
listPlatforms,
|
||||
recomputeRecordLedger,
|
||||
searchEntityRecords,
|
||||
toggleRecordState,
|
||||
} from "./api.js";
|
||||
import { buildKeywordFilter, selectRecordFields } from "./services.js";
|
||||
|
||||
const platform = {
|
||||
id: "platform-1",
|
||||
name: "业务应用",
|
||||
corporationId: "corp-1",
|
||||
active: true,
|
||||
adminIds: ["staff-1"],
|
||||
};
|
||||
|
||||
describe("DataLink Domain - 应用、业务对象与记录查询", () => {
|
||||
test("列出应用并为权限数组提供稳定默认值", async () => {
|
||||
const client = {
|
||||
get: async (url: string, options: any) => {
|
||||
expect(url).toBe("api/v2/datalink/platform/search");
|
||||
expect(options.searchParams).toEqual({ scope: "enable", corpId: "corp-1" });
|
||||
return { json: async () => ({ items: [platform] }) };
|
||||
},
|
||||
} as any;
|
||||
|
||||
const result = await listPlatforms(client, "corp-1");
|
||||
expect(result[0]?.name).toBe("业务应用");
|
||||
expect(result[0]?.staffIds).toEqual([]);
|
||||
expect(result[0]?.departmentIds).toEqual([]);
|
||||
});
|
||||
|
||||
test("获取应用详情时请求管理员关联", async () => {
|
||||
const client = {
|
||||
get: async (url: string, options: any) => {
|
||||
expect(url).toBe("api/v2/datalink/platform/$platform-1");
|
||||
expect(options.searchParams).toBeInstanceOf(URLSearchParams);
|
||||
expect(options.searchParams.get("id")).toBe("platform-1");
|
||||
expect(options.searchParams.getAll("join")).toEqual([
|
||||
"icon.fileId,fileId,/v1/attachment/attachments",
|
||||
"adminIds,admin,/v1/organization/staffs",
|
||||
]);
|
||||
expect(options.searchParams.get("corpId")).toBe("corp-1");
|
||||
return { json: async () => ({ value: { ...platform, staffIds: ["staff-1"], roleIds: ["role-1"], departmentIds: [], admin: [{ id: "staff-1", name: "管理员", code: "A-1", cellphone: "13800000000" }] } }) };
|
||||
},
|
||||
} as any;
|
||||
|
||||
const result = await getPlatform(client, "corp-1", "platform-1");
|
||||
expect(result.adminIds).toEqual(["staff-1"]);
|
||||
expect(result.roleIds).toEqual(["role-1"]);
|
||||
expect(result.admin).toEqual([{ id: "staff-1", name: "管理员", code: "A-1", active: undefined }]);
|
||||
expect(JSON.stringify(result)).not.toContain("13800000000");
|
||||
});
|
||||
|
||||
test("获取对象字段元数据并保留扩展属性", async () => {
|
||||
const client = {
|
||||
post: async (url: string, options: any) => {
|
||||
expect(url).toBe("api/v2/datalink/entity/platformId/$platform-1");
|
||||
expect(options.searchParams.corpId).toBe("corp-1");
|
||||
expect(options.json).toEqual({});
|
||||
return { json: async () => ({ items: [{ id: "entity-1", name: "供应商", fields: [{ name: "code", label: "编码", type: "text", optional: false, customFlag: true }] }] }) };
|
||||
},
|
||||
} as any;
|
||||
|
||||
const result = await listPlatformEntities(client, "corp-1", "platform-1");
|
||||
expect(result[0]?.fields[0]?.label).toBe("编码");
|
||||
expect(result[0]?.fields[0]?.customFlag).toBe(true);
|
||||
});
|
||||
|
||||
test("分页查询记录并生成标准化分页结果", async () => {
|
||||
const client = {
|
||||
post: async (url: string, options: any) => {
|
||||
expect(url).toBe("api/v2/datalink/searchPlatformDataLinkWithChild/$entity-1");
|
||||
expect(options.searchParams.corpId).toBe("corp-1");
|
||||
expect(options.json).toEqual({
|
||||
entityId: "entity-1",
|
||||
query: { filterBy: 'code == "A-1"', limit: { start: 10, count: 5 } },
|
||||
});
|
||||
return { json: async () => ({ items: { total: 1, data: [{ id: "record-1", dataLink: { code: "A-1" } }] } }) };
|
||||
},
|
||||
} as any;
|
||||
|
||||
const result = await searchEntityRecords(client, "corp-1", "entity-1", { start: 10, count: 5, filterBy: 'code == "A-1"' });
|
||||
expect(result.total).toBe(1);
|
||||
expect(result.data[0]?.dataLink?.code).toBe("A-1");
|
||||
});
|
||||
|
||||
test("关键词过滤和字段投影可用于通用 CLI 查询", () => {
|
||||
expect(buildKeywordFilter('A"1')).toContain('A\\"1');
|
||||
expect(selectRecordFields({ id: "r-1", dataLink: { code: "A-1" } }, ["编码"], [{ name: "code", label: "编码", type: "text" }])).toEqual({ id: "r-1", dataLink: { 编码: "A-1" } });
|
||||
});
|
||||
|
||||
test("切换记录停启用状态调用 PUT contract state 接口", async () => {
|
||||
let calledUrl = "";
|
||||
let calledParams: any = null;
|
||||
let calledJson: any = null;
|
||||
const client = {
|
||||
get: async () => ({
|
||||
json: async () => ({ value: { id: "record-1", active: true } }),
|
||||
}),
|
||||
put: async (url: string, options: any) => {
|
||||
calledUrl = url;
|
||||
calledParams = options.searchParams;
|
||||
calledJson = options.json;
|
||||
return { status: 204 };
|
||||
},
|
||||
} as any;
|
||||
|
||||
const res = await toggleRecordState(client, "corp-1", "record-1");
|
||||
expect(calledUrl).toBe("api/supplier/v3/contract/$record-1/state");
|
||||
expect(calledParams).toEqual({ corpId: "corp-1" });
|
||||
expect(calledJson).toEqual({ id: "record-1", state: false });
|
||||
expect(res).toEqual({ recordId: "record-1", active: false });
|
||||
});
|
||||
|
||||
test("获取记录详情调用 GET datalink detail 接口", async () => {
|
||||
const client = {
|
||||
get: async (url: string, options: any) => {
|
||||
expect(url).toBe("api/v2/datalink/detail/$record-1/$DETAIL");
|
||||
expect(options.searchParams).toEqual({
|
||||
dataLinkId: "record-1",
|
||||
type: "DETAIL",
|
||||
corpId: "corp-1",
|
||||
});
|
||||
return { json: async () => ({ value: { id: "record-1", name: "记录1" } }) };
|
||||
},
|
||||
} as any;
|
||||
|
||||
const result = await getRecordDetail(client, "corp-1", "record-1");
|
||||
expect((result as any).name).toBe("记录1");
|
||||
});
|
||||
|
||||
test("编辑业务对象记录调用 POST entityEdit edit 接口", async () => {
|
||||
const client = {
|
||||
post: async (url: string, options: any) => {
|
||||
expect(url).toBe("api/v2/datalink/entityEdit/edit");
|
||||
expect(options.searchParams).toEqual({ corpId: "corp-1" });
|
||||
expect(options.json.dataLinkEntityId).toBe("entity-1");
|
||||
expect(options.json.dataLinkId).toBe("record-1");
|
||||
expect(options.json.form).toEqual({ name: "新名称" });
|
||||
return { json: async () => ({ value: { id: "record-1", name: "新名称" } }) };
|
||||
},
|
||||
} as any;
|
||||
|
||||
const result = await editRecord(client, "corp-1", {
|
||||
dataLinkEntityId: "$entity-1",
|
||||
dataLinkId: "$record-1",
|
||||
form: { name: "新名称" },
|
||||
});
|
||||
expect((result as any).name).toBe("新名称");
|
||||
});
|
||||
|
||||
test("重算台账调用 POST ledger recompute 接口", async () => {
|
||||
const client = {
|
||||
post: async (url: string, options: any) => {
|
||||
expect(url).toBe("api/v2/ledger/recompute/$record-1");
|
||||
expect(options.searchParams).toEqual({ corpId: "corp-1" });
|
||||
return { json: async () => ({ id: "ok" }) };
|
||||
},
|
||||
} as any;
|
||||
|
||||
const result = await recomputeRecordLedger(client, "corp-1", "record-1");
|
||||
expect(result.id).toBe("ok");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import * as api from "./api.js";
|
||||
import type { DatalinkEntity, DatalinkField, DatalinkPlatformDetail } from "./types.js";
|
||||
|
||||
function matches(value: unknown, target: string): boolean {
|
||||
return typeof value === "string" && value.toLowerCase() === target.toLowerCase();
|
||||
}
|
||||
|
||||
export async function resolvePlatform(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string
|
||||
): Promise<DatalinkPlatformDetail | undefined> {
|
||||
const platforms = await api.listPlatforms(client, corpId);
|
||||
const found = platforms.find((platform) =>
|
||||
[platform.id, platform.name, platform.code].some((value) => matches(value, target))
|
||||
);
|
||||
return found ? api.getPlatform(client, corpId, found.id) : undefined;
|
||||
}
|
||||
|
||||
export async function resolveEntity(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
platform: DatalinkPlatformDetail,
|
||||
target: string
|
||||
): Promise<DatalinkEntity | undefined> {
|
||||
const entities = await api.listPlatformEntities(client, corpId, platform.id);
|
||||
return entities.find((entity) =>
|
||||
[entity.id, entity.name, entity.code].some((value) => matches(value, target))
|
||||
);
|
||||
}
|
||||
|
||||
export function buildKeywordFilter(keyword: string): string {
|
||||
const escaped = keyword.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
|
||||
return `(name.containsIgnoreCase("${escaped}")||code.containsIgnoreCase("${escaped}"))&&(active.in(true,false))`;
|
||||
}
|
||||
|
||||
export function selectRecordFields(record: Record<string, unknown>, fields: string[], definitions: DatalinkField[] = []): Record<string, unknown> {
|
||||
if (fields.length === 0) return record;
|
||||
const dataLink = record.dataLink && typeof record.dataLink === "object" && !Array.isArray(record.dataLink)
|
||||
? (record.dataLink as Record<string, unknown>)
|
||||
: record;
|
||||
const selected: Record<string, unknown> = {};
|
||||
for (const selector of fields) {
|
||||
const definition = definitions.find((field) => field.name === selector || field.label === selector);
|
||||
const sourceName = definition?.name ?? selector;
|
||||
if (sourceName in dataLink) selected[definition?.label || selector] = dataLink[sourceName];
|
||||
}
|
||||
return record.dataLink && typeof record.dataLink === "object"
|
||||
? { ...record, dataLink: selected }
|
||||
: selected;
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import { z } from "zod";
|
||||
import * as api from "./api.js";
|
||||
|
||||
const clientSchema = z.object({
|
||||
corp: z.object({ credentials: z.object({ corpId: z.string() }) }).passthrough(),
|
||||
ekbClient: z.any(),
|
||||
});
|
||||
|
||||
export const datalinkTools = [
|
||||
{
|
||||
name: "datalink_platform_list",
|
||||
description: "列出当前企业账号可见的启用自建应用(可传入 all=true 查看包含模板平台的完整列表)",
|
||||
parameters: z.object({
|
||||
all: z.boolean().optional().describe("是否拉取包含 HAB 模板与全量平台列表"),
|
||||
}),
|
||||
handler: async (clients: unknown, params: { all?: boolean } = {}) => {
|
||||
const { corp, ekbClient } = clientSchema.parse(clients);
|
||||
const platforms = params.all
|
||||
? await api.listAllPlatforms(ekbClient, corp.credentials.corpId)
|
||||
: await api.listPlatforms(ekbClient, corp.credentials.corpId);
|
||||
return { platforms };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "datalink_platform_get",
|
||||
description: "获取自建应用详情以及应用管理员、人员、角色和部门可见权限",
|
||||
parameters: z.object({ platformId: z.string().describe("自建应用 ID") }),
|
||||
handler: async (clients: unknown, params: { platformId: string }) => {
|
||||
const { corp, ekbClient } = clientSchema.parse(clients);
|
||||
return api.getPlatform(ekbClient, corp.credentials.corpId, params.platformId);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "datalink_entity_list",
|
||||
description: "获取一个自建应用下的业务对象目录、字段、操作和可见性配置",
|
||||
parameters: z.object({ platformId: z.string().describe("自建应用 ID") }),
|
||||
handler: async (clients: unknown, params: { platformId: string }) => {
|
||||
const { corp, ekbClient } = clientSchema.parse(clients);
|
||||
return { entities: await api.listPlatformEntities(ekbClient, corp.credentials.corpId, params.platformId) };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "datalink_record_search",
|
||||
description: "分页检索业务对象记录,支持 DataLink filterBy 表达式",
|
||||
parameters: z.object({
|
||||
entityId: z.string().describe("业务对象 ID"),
|
||||
start: z.number().int().min(0).optional(),
|
||||
count: z.number().int().min(1).max(1000).optional(),
|
||||
filterBy: z.string().optional().describe("DataLink 原生过滤表达式"),
|
||||
}),
|
||||
handler: async (clients: unknown, params: { entityId: string; start?: number; count?: number; filterBy?: string }) => {
|
||||
const { corp, ekbClient } = clientSchema.parse(clients);
|
||||
return api.searchEntityRecords(ekbClient, corp.credentials.corpId, params.entityId, params);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "datalink_import_jobs",
|
||||
description: "查看业务对象的导入任务和最近导入结果",
|
||||
parameters: z.object({ entityId: z.string().describe("业务对象 ID") }),
|
||||
handler: async (clients: unknown, params: { entityId: string }) => {
|
||||
const { corp, ekbClient } = clientSchema.parse(clients);
|
||||
const [jobs, result] = await Promise.all([
|
||||
api.listImportJobs(ekbClient, corp.credentials.corpId, params.entityId),
|
||||
api.getImportResult(ekbClient, corp.credentials.corpId, params.entityId),
|
||||
]);
|
||||
return { jobs, latestResult: result };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "datalink_record_get",
|
||||
description: "获取单条业务对象记录的完整详情(模板、字段值、可见性及历史等)",
|
||||
parameters: z.object({
|
||||
recordId: z.string().describe("业务对象记录 ID (dataLinkId)"),
|
||||
}),
|
||||
handler: async (clients: unknown, params: { recordId: string }) => {
|
||||
const { corp, ekbClient } = clientSchema.parse(clients);
|
||||
return api.getRecordDetail(ekbClient, corp.credentials.corpId, params.recordId);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "datalink_record_toggle",
|
||||
description: "切换业务对象记录的停启用状态 (active: true <-> false)",
|
||||
parameters: z.object({
|
||||
recordId: z.string().describe("业务对象记录 ID (dataLinkId)"),
|
||||
state: z.boolean().optional().describe("目标状态 (true 为启用,false 为停用,不传则自动翻转)"),
|
||||
}),
|
||||
handler: async (clients: unknown, params: { recordId: string; state?: boolean }) => {
|
||||
const { corp, ekbClient } = clientSchema.parse(clients);
|
||||
const result = await api.toggleRecordState(ekbClient, corp.credentials.corpId, params.recordId, params.state);
|
||||
return { success: true, ...result };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "datalink_record_edit",
|
||||
description: "编辑更新业务对象记录的字段值",
|
||||
parameters: z.object({
|
||||
entityId: z.string().describe("业务对象 ID"),
|
||||
recordId: z.string().describe("业务对象记录 ID (dataLinkId)"),
|
||||
form: z.record(z.string(), z.unknown()).describe("待更新的表单字段键值对"),
|
||||
active: z.boolean().optional().describe("停启用状态"),
|
||||
visibility: z.record(z.string(), z.unknown()).optional().describe("可见性配置"),
|
||||
}),
|
||||
handler: async (
|
||||
clients: unknown,
|
||||
params: {
|
||||
entityId: string;
|
||||
recordId: string;
|
||||
form: Record<string, unknown>;
|
||||
active?: boolean;
|
||||
visibility?: Record<string, unknown>;
|
||||
}
|
||||
) => {
|
||||
const { corp, ekbClient } = clientSchema.parse(clients);
|
||||
return api.editRecord(ekbClient, corp.credentials.corpId, {
|
||||
dataLinkEntityId: params.entityId,
|
||||
dataLinkId: params.recordId,
|
||||
form: params.form,
|
||||
active: params.active,
|
||||
visibility: params.visibility,
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "datalink_record_recompute",
|
||||
description: "重新计算指定业务对象记录下的全部台账信息",
|
||||
parameters: z.object({
|
||||
recordId: z.string().describe("业务对象记录 ID (dataLinkId)"),
|
||||
}),
|
||||
handler: async (clients: unknown, params: { recordId: string }) => {
|
||||
const { corp, ekbClient } = clientSchema.parse(clients);
|
||||
return api.recomputeRecordLedger(ekbClient, corp.credentials.corpId, params.recordId);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
export type DatalinkTool = (typeof datalinkTools)[number];
|
||||
@@ -0,0 +1,121 @@
|
||||
import { z } from "zod";
|
||||
import { PlatformSchema } from "../platform/types.js";
|
||||
|
||||
const NullableBoolean = z.boolean().nullable().optional();
|
||||
|
||||
/** DataLink 字段元数据。保留服务端未建模的扩展字段,避免丢失配置。 */
|
||||
export const DatalinkFieldSchema = z
|
||||
.object({
|
||||
name: z.string().default(""),
|
||||
label: z.string().default(""),
|
||||
type: z.string().default("text"),
|
||||
optional: NullableBoolean,
|
||||
regex: z.string().nullable().optional(),
|
||||
source: z.string().nullable().optional(),
|
||||
formula: z.boolean().nullable().optional(),
|
||||
calculation: z.record(z.string(), z.unknown()).nullable().optional(),
|
||||
entity: z.string().nullable().optional(),
|
||||
withTime: z.boolean().nullable().optional(),
|
||||
scale: z.number().nullable().optional(),
|
||||
unit: z.string().nullable().optional(),
|
||||
index: z.boolean().nullable().optional(),
|
||||
systemField: z.boolean().nullable().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export const DatalinkEntitySchema = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
code: z.string().default(""),
|
||||
name: z.string().default(""),
|
||||
type: z.string().default(""),
|
||||
active: z.boolean().default(true),
|
||||
fields: z.array(DatalinkFieldSchema).default([]),
|
||||
actions: z.array(z.unknown()).default([]),
|
||||
importMethod: z.array(z.string()).default([]),
|
||||
visibility: z.unknown().optional(),
|
||||
homeVisibility: z.unknown().optional(),
|
||||
exportVisibility: z.unknown().optional(),
|
||||
dataFilter: z.unknown().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export const DatalinkPlatformDetailSchema = PlatformSchema.passthrough().extend({
|
||||
staffIds: z.array(z.string()).nullish().transform((value) => value ?? []),
|
||||
roleIds: z.array(z.string()).nullish().transform((value) => value ?? []),
|
||||
departmentIds: z.array(z.string()).nullish().transform((value) => value ?? []),
|
||||
departmentsIncludeChildren: z.boolean().nullish().transform((value) => value ?? false),
|
||||
});
|
||||
|
||||
export interface DatalinkRecordQuery {
|
||||
start?: number;
|
||||
count?: number;
|
||||
filterBy?: string;
|
||||
/** 服务端支持的排序表达式,原样透传。 */
|
||||
orderBy?: unknown;
|
||||
}
|
||||
|
||||
export interface DatalinkRecord {
|
||||
id?: string;
|
||||
entityId?: string;
|
||||
dataLink?: Record<string, unknown>;
|
||||
fieldAuth?: Record<string, unknown>;
|
||||
visibility?: unknown;
|
||||
active?: boolean;
|
||||
ownerId?: string;
|
||||
createTime?: number | string;
|
||||
updateTime?: number | string;
|
||||
actions?: unknown[];
|
||||
source?: unknown;
|
||||
sourceId?: unknown;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface DatalinkRecordPage {
|
||||
total: number;
|
||||
data: DatalinkRecord[];
|
||||
actions: unknown[];
|
||||
components: unknown[];
|
||||
path: unknown;
|
||||
template: unknown;
|
||||
}
|
||||
|
||||
export interface DatalinkImportJob {
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export type DatalinkField = z.infer<typeof DatalinkFieldSchema>;
|
||||
export type DatalinkEntity = z.infer<typeof DatalinkEntitySchema>;
|
||||
export type DatalinkPlatformDetail = z.infer<typeof DatalinkPlatformDetailSchema>;
|
||||
|
||||
export interface DatalinkPermissionSnapshot {
|
||||
platform: DatalinkPlatformDetail;
|
||||
entity?: DatalinkEntity;
|
||||
}
|
||||
|
||||
export interface DatalinkRecordDetail {
|
||||
dataLink?: DatalinkRecord;
|
||||
template?: unknown;
|
||||
entity?: unknown;
|
||||
actions?: unknown[];
|
||||
flowCounts?: Record<string, unknown>;
|
||||
ledger?: Record<string, unknown>;
|
||||
ledgers?: unknown[];
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface DatalinkRecordEditPayload {
|
||||
dataLinkEntityId: string;
|
||||
dataLinkId: string;
|
||||
active?: boolean;
|
||||
form: Record<string, unknown>;
|
||||
visibility?: {
|
||||
fullVisible?: boolean;
|
||||
staffs?: string[];
|
||||
roles?: string[];
|
||||
departments?: string[];
|
||||
departmentsIncludeChildren?: boolean;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
[key: string]: unknown;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
# Menu 域说明(桌面端主框架菜单与工作台业务应用)
|
||||
|
||||
Menu 域负责获取合思桌面端全站主框架导航菜单树(`MAIN_FRAME_DESKTOP`)以及业务工作台【应用管理】下的业务应用集成列表。
|
||||
|
||||
## 业务背景
|
||||
|
||||
在合思产品体系中:
|
||||
1. **应用中心 -> 自建应用**(由 `platform` / `datalink` 域负责):属于开发者与 PaaS 容器层(`groupType: NORMAL`),主要用于自定义实体建模和脚本工作流;
|
||||
2. **顶层一级导航【应用管理】**(由本 `menu` 域负责):属于用户业务工作台层,聚合了租户开通的**全部前台业务落地应用**,既包括挂载了对象视图的自建应用(如新转转集团、差旅申请、项目预算),也包含官方业务套件(如用车补贴 `SCGY:...`、用车制度)与金融扩展(如 E商卡管理)。
|
||||
|
||||
## 核心接口
|
||||
|
||||
| 接口 | 方法 | 说明 |
|
||||
|---|---|---|
|
||||
| `api/menu/v2/menus/byDeviceTypeAndAppId/$MAIN_FRAME_DESKTOP` | `GET` | 获取桌面端全站主框架导航菜单树 |
|
||||
|
||||
## 代码结构
|
||||
|
||||
```text
|
||||
src/domains/menu/
|
||||
├── types.ts # 菜单树节点与 WorkbenchApp 视图模型
|
||||
├── api.ts # HTTP 传输层
|
||||
└── tools.ts # 服务层聚合函数与导出
|
||||
```
|
||||
|
||||
## CLI 对应命令
|
||||
|
||||
```bash
|
||||
# 查看顶层【应用管理】下的业务应用列表
|
||||
hose-use app list [--corp=<id>]
|
||||
|
||||
# 查看桌面端主框架菜单树
|
||||
hose-use menu tree [--corp=<id>]
|
||||
```
|
||||
@@ -0,0 +1,125 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import {
|
||||
fetchDesktopMenuTree,
|
||||
fetchWorkbenchApps,
|
||||
fetchAppCenterMenus,
|
||||
} from "./api.js";
|
||||
|
||||
const mockMenuPayload = {
|
||||
items: [
|
||||
{
|
||||
id: "newHomePage",
|
||||
label: "首页",
|
||||
appId: "100-home",
|
||||
href: "/home",
|
||||
children: [],
|
||||
},
|
||||
{
|
||||
id: "dataLink",
|
||||
label: "应用管理",
|
||||
appId: "160-datalink-platform",
|
||||
children: [
|
||||
{
|
||||
id: "SCGY:corp-test",
|
||||
label: "用车补贴",
|
||||
code: "dataLinkItem",
|
||||
href: "/third-party-item/SCGY:corp-test",
|
||||
appId: "160-datalink-platform",
|
||||
type: "MENU",
|
||||
fromWay: "SYSTEM",
|
||||
},
|
||||
{
|
||||
id: "ID01PIqCA1Di0v",
|
||||
label: "用车制度",
|
||||
code: "dataLinkItem",
|
||||
href: "/third-party-item/ID01PIqCA1Di0v",
|
||||
appId: "160-datalink-platform",
|
||||
type: "MENU",
|
||||
fromWay: "SYSTEM",
|
||||
},
|
||||
{
|
||||
id: "ID01RKbEvQsWbd",
|
||||
label: "新转转集团",
|
||||
code: "dataLinkItem",
|
||||
href: "/third-party-item/ID01RKbEvQsWbd",
|
||||
appId: "160-datalink-platform",
|
||||
type: "MENU",
|
||||
fromWay: "SYSTEM",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "appcenter",
|
||||
label: "应用中心",
|
||||
appId: "150-appcenter",
|
||||
children: [
|
||||
{
|
||||
id: "selfBuiltApplication",
|
||||
label: "自建应用",
|
||||
code: "selfBuiltApplication",
|
||||
href: "/expense-center-new/self_built_app",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
describe("Domains/Menu - API 单元测试", () => {
|
||||
test("fetchDesktopMenuTree 成功解析全站桌面端菜单响应", async () => {
|
||||
const mockClient = {
|
||||
get: async (url: string, opts: any) => {
|
||||
expect(url).toBe("api/menu/v2/menus/byDeviceTypeAndAppId/$MAIN_FRAME_DESKTOP");
|
||||
expect(opts.searchParams.corpId).toBe("corp-test");
|
||||
return {
|
||||
json: async () => mockMenuPayload,
|
||||
};
|
||||
},
|
||||
} as any;
|
||||
|
||||
const items = await fetchDesktopMenuTree(mockClient, "corp-test");
|
||||
expect(items.length).toBe(3);
|
||||
expect(items[0].label).toBe("首页");
|
||||
expect(items[1].label).toBe("应用管理");
|
||||
expect(items[2].label).toBe("应用中心");
|
||||
});
|
||||
|
||||
test("fetchWorkbenchApps 成功提取应用管理下的 7/N 个业务应用", async () => {
|
||||
const mockClient = {
|
||||
get: async () => ({
|
||||
json: async () => mockMenuPayload,
|
||||
}),
|
||||
} as any;
|
||||
|
||||
const apps = await fetchWorkbenchApps(mockClient, "corp-test");
|
||||
expect(apps.length).toBe(3);
|
||||
expect(apps[0].id).toBe("SCGY:corp-test");
|
||||
expect(apps[0].name).toBe("用车补贴");
|
||||
expect(apps[0].href).toBe("/third-party-item/SCGY:corp-test");
|
||||
expect(apps[1].name).toBe("用车制度");
|
||||
expect(apps[2].name).toBe("新转转集团");
|
||||
});
|
||||
|
||||
test("fetchAppCenterMenus 成功提取应用中心子栏目", async () => {
|
||||
const mockClient = {
|
||||
get: async () => ({
|
||||
json: async () => mockMenuPayload,
|
||||
}),
|
||||
} as any;
|
||||
|
||||
const menus = await fetchAppCenterMenus(mockClient, "corp-test");
|
||||
expect(menus.length).toBe(1);
|
||||
expect(menus[0].id).toBe("selfBuiltApplication");
|
||||
expect(menus[0].label).toBe("自建应用");
|
||||
});
|
||||
|
||||
test("当菜单树无 dataLink 节点时安全返回空数组", async () => {
|
||||
const mockClient = {
|
||||
get: async () => ({
|
||||
json: async () => ({ items: [] }),
|
||||
}),
|
||||
} as any;
|
||||
|
||||
const apps = await fetchWorkbenchApps(mockClient, "corp-test");
|
||||
expect(apps).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { DesktopMenuResponseSchema, type MenuItem, type WorkbenchApp } from "./types.js";
|
||||
|
||||
/** 获取桌面端全站主框架导航菜单树 */
|
||||
export async function fetchDesktopMenuTree(
|
||||
client: KyInstance,
|
||||
corpId: string
|
||||
): Promise<MenuItem[]> {
|
||||
const response = await client.get(
|
||||
"api/menu/v2/menus/byDeviceTypeAndAppId/$MAIN_FRAME_DESKTOP",
|
||||
{
|
||||
searchParams: { corpId },
|
||||
}
|
||||
);
|
||||
const json = await response.json();
|
||||
const parsed = DesktopMenuResponseSchema.parse(json);
|
||||
return parsed.items;
|
||||
}
|
||||
|
||||
/** 获取工作台【应用管理】下的业务应用列表(包括套件、模板与自建应用) */
|
||||
export async function fetchWorkbenchApps(
|
||||
client: KyInstance,
|
||||
corpId: string
|
||||
): Promise<WorkbenchApp[]> {
|
||||
const items = await fetchDesktopMenuTree(client, corpId);
|
||||
const dataLinkNode = items.find(
|
||||
(i) =>
|
||||
i.id === "dataLink" ||
|
||||
i.appId === "160-datalink-platform" ||
|
||||
i.label === "应用管理"
|
||||
);
|
||||
|
||||
if (!dataLinkNode || !Array.isArray(dataLinkNode.children)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return dataLinkNode.children.map((child) => ({
|
||||
id: child.id,
|
||||
name: child.label,
|
||||
code: child.code || "dataLinkItem",
|
||||
href: child.href || `/third-party-item/${child.id}`,
|
||||
appId: child.appId || "160-datalink-platform",
|
||||
type: child.type || "MENU",
|
||||
fromWay: child.fromWay || "SYSTEM",
|
||||
}));
|
||||
}
|
||||
|
||||
/** 获取【应用中心】下的子栏目菜单列表(如应用商店、已购应用、自建应用等) */
|
||||
export async function fetchAppCenterMenus(
|
||||
client: KyInstance,
|
||||
corpId: string
|
||||
): Promise<MenuItem[]> {
|
||||
const items = await fetchDesktopMenuTree(client, corpId);
|
||||
const appCenterNode = items.find(
|
||||
(i) =>
|
||||
i.id === "appcenter" ||
|
||||
i.appId === "150-appcenter" ||
|
||||
i.label === "应用中心"
|
||||
);
|
||||
|
||||
return appCenterNode?.children || [];
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import {
|
||||
fetchDesktopMenuTree,
|
||||
fetchWorkbenchApps,
|
||||
fetchAppCenterMenus,
|
||||
} from "./api.js";
|
||||
import type { MenuItem, WorkbenchApp } from "./types.js";
|
||||
|
||||
/** 获取桌面端工作台【应用管理】下的业务应用列表 */
|
||||
export async function fetchWorkbenchAppsList(
|
||||
corp: CorpConfig
|
||||
): Promise<WorkbenchApp[]> {
|
||||
const client = await createEkbClient(corp);
|
||||
const corpId = corp.corpId || corp.credentials.corpId;
|
||||
return fetchWorkbenchApps(client, corpId);
|
||||
}
|
||||
|
||||
/** 获取桌面端全站主框架导航菜单树 */
|
||||
export async function fetchDesktopMenus(
|
||||
corp: CorpConfig
|
||||
): Promise<MenuItem[]> {
|
||||
const client = await createEkbClient(corp);
|
||||
const corpId = corp.corpId || corp.credentials.corpId;
|
||||
return fetchDesktopMenuTree(client, corpId);
|
||||
}
|
||||
|
||||
/** 获取【应用中心】下的子栏目 */
|
||||
export async function fetchAppCenterSubMenus(
|
||||
corp: CorpConfig
|
||||
): Promise<MenuItem[]> {
|
||||
const client = await createEkbClient(corp);
|
||||
const corpId = corp.corpId || corp.credentials.corpId;
|
||||
return fetchAppCenterMenus(client, corpId);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export interface MenuItem {
|
||||
id: string;
|
||||
label: string;
|
||||
code?: string | null;
|
||||
href?: string | null;
|
||||
appId?: string | null;
|
||||
type?: string | null;
|
||||
fromWay?: string | null;
|
||||
icon?: string | null;
|
||||
iconFill?: string | null;
|
||||
selected?: boolean | null;
|
||||
children?: MenuItem[];
|
||||
}
|
||||
|
||||
export const MenuItemSchema: z.ZodType<MenuItem> = z.lazy(() =>
|
||||
z.object({
|
||||
id: z.string(),
|
||||
label: z.string().default(""),
|
||||
code: z.string().nullable().optional(),
|
||||
href: z.string().nullable().optional(),
|
||||
appId: z.string().nullable().optional(),
|
||||
type: z.string().nullable().optional(),
|
||||
fromWay: z.string().nullable().optional(),
|
||||
icon: z.string().nullable().optional(),
|
||||
iconFill: z.string().nullable().optional(),
|
||||
selected: z.boolean().nullable().optional(),
|
||||
children: z.array(MenuItemSchema).optional().default([]),
|
||||
})
|
||||
);
|
||||
|
||||
export const DesktopMenuResponseSchema = z.object({
|
||||
items: z.array(MenuItemSchema).default([]),
|
||||
});
|
||||
export type DesktopMenuResponse = z.infer<typeof DesktopMenuResponseSchema>;
|
||||
|
||||
export const WorkbenchAppSchema = z.object({
|
||||
id: z.string().describe("业务应用 ID (如 SCGY:corpId 或 自建应用物理ID)"),
|
||||
name: z.string().describe("应用名称"),
|
||||
code: z.string().optional().describe("功能代码 (如 dataLinkItem)"),
|
||||
href: z.string().describe("Web 端直达路由路径"),
|
||||
appId: z.string().default("160-datalink-platform").describe("所属主框架模块"),
|
||||
type: z.string().optional().describe("菜单或应用类型"),
|
||||
fromWay: z.string().optional().describe("来源方式 (如 SYSTEM, MANUAL)"),
|
||||
});
|
||||
export type WorkbenchApp = z.infer<typeof WorkbenchAppSchema>;
|
||||
@@ -1,6 +1,6 @@
|
||||
# Platform 域说明
|
||||
|
||||
Platform 域负责自建应用(DataLink Platform)和工作流(EASO/Piper)相关能力。
|
||||
Platform 域负责工作流(EASO/Piper)以及自建应用容器的兼容能力。自建应用下的业务对象、字段、记录和权限查询统一放在 [DataLink 域](../datalink/README.datalink.md)。
|
||||
|
||||
## 代码结构
|
||||
|
||||
|
||||
@@ -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`: 获取指定应用的详细信息、套餐与规格
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -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 ?? {});
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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>;
|
||||
+22
-1
@@ -10,6 +10,7 @@ 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 { runCli } from "./cli/runner.js";
|
||||
import { redactSensitiveText } from "./cli/printer.js";
|
||||
@@ -185,7 +186,7 @@ export function createServer(options: { mode?: HoseMcpMode; enabled?: boolean }
|
||||
}
|
||||
);
|
||||
|
||||
const fineGrainedTools = [...authTools, ...platformTools, ...billTools];
|
||||
const fineGrainedTools = [...authTools, ...platformTools, ...datalinkTools, ...billTools];
|
||||
|
||||
// 注册工具列表
|
||||
server.setRequestHandler("tools/list", async () => {
|
||||
@@ -358,6 +359,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
@@ -1 +1 @@
|
||||
export const VERSION = "0.8.0";
|
||||
export const VERSION = "0.8.4";
|
||||
Reference in new issue
Block a user