Compare commits
39
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
038aca10fb | ||
|
|
9b780c345d | ||
|
|
d38eaecc12 | ||
|
|
4b4a7049a0 | ||
|
|
baec8be6d3 | ||
|
|
833cdf8573 | ||
|
|
d6d5d2d732 | ||
|
|
8b0346221f | ||
|
|
235e4b806d | ||
|
|
4ea73ef322 | ||
|
|
edafe8d086 | ||
|
|
b787130880 | ||
|
|
54382ae7ce | ||
|
|
950e97eacc | ||
|
|
85992e29ce | ||
|
|
42bf0bfb0b | ||
|
|
62b47f5ad7 | ||
|
|
83dacf90c4 | ||
|
|
1c5d6153a2 | ||
|
|
6ba748e531 | ||
|
|
9cf247fe45 | ||
|
|
4f572ad9c1 | ||
|
|
448dd438ff | ||
|
|
cfd0c48a8b | ||
|
|
b7fda124fd | ||
|
|
e00adbe5a8 | ||
|
|
75a0611f0e | ||
|
|
75740c4ec3 | ||
|
|
22215eb317 | ||
|
|
0c9eb27f85 | ||
|
|
ea5eb22c51 | ||
|
|
e588416a5f | ||
|
|
de88e218e7 | ||
|
|
020e4a2761 | ||
|
|
e7e856bbb0 | ||
|
|
bfbf6cf55f | ||
|
|
f3caebfd8a | ||
|
|
1eeb288143 | ||
|
|
4272dd8e60 |
No files matched your search
@@ -10,7 +10,9 @@
|
|||||||
| [production-safety.md](./production-safety.md) | 操作真实企业前;确认只读/写入范围、预演、凭证脱敏要求 |
|
| [production-safety.md](./production-safety.md) | 操作真实企业前;确认只读/写入范围、预演、凭证脱敏要求 |
|
||||||
| [tenant-and-credential.md](./tenant-and-credential.md) | 多租户身份、协助链接和凭证导入,以及个人单据查询 |
|
| [tenant-and-credential.md](./tenant-and-credential.md) | 多租户身份、协助链接和凭证导入,以及个人单据查询 |
|
||||||
| [testing-and-dev-hygiene.md](./testing-and-dev-hygiene.md) | 编写测试、隔离环境、处理非交互输入与提交验证 |
|
| [testing-and-dev-hygiene.md](./testing-and-dev-hygiene.md) | 编写测试、隔离环境、处理非交互输入与提交验证 |
|
||||||
|
| [troubleshooting-and-investigation.md](./troubleshooting-and-investigation.md) | 业务排障诊断、探针环境隔离,以及沉淀优先原则 |
|
||||||
| [typescript-style.md](./typescript-style.md) | TypeScript、ESM 导入和运行时模型修改 |
|
| [typescript-style.md](./typescript-style.md) | TypeScript、ESM 导入和运行时模型修改 |
|
||||||
|
|
||||||
| [windows-development.md](./windows-development.md) | 跨平台路径、分支命名、换行及文件名兼容 |
|
| [windows-development.md](./windows-development.md) | 跨平台路径、分支命名、换行及文件名兼容 |
|
||||||
|
|
||||||
## 维护边界
|
## 维护边界
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
---
|
||||||
|
description: "排障诊断、探针环境与正式环境隔离,以及沉淀优先原则"
|
||||||
|
globs: "src/**/*.{ts,md}"
|
||||||
|
trigger: "manual"
|
||||||
|
---
|
||||||
|
|
||||||
|
# 业务排障与系统探查铁律(Troubleshooting & Investigation Rules)
|
||||||
|
|
||||||
|
本规则总结自多租户、工作流与审批流联动真实排障过程中的典型教训,面向所有在此仓库进行业务排查与功能迭代的 AI Agent。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 探针环境与业务目标企业严格隔离(Probe vs. Target Boundary)
|
||||||
|
|
||||||
|
在面对未知系统接口、未逆向的页面交互或存在破坏性风险的操作时,用户常会引导 Agent「先去测试企业(如沈玥妍测试企业)摸一下/探查一下」:
|
||||||
|
|
||||||
|
1. **明确行为性质是“探针(Probe)”而非“诊断结论”**:
|
||||||
|
- 访问测试企业的**唯一目的**是:安全抓包、获取底层 API 路径、探明请求/响应 JSON Schema 或验证逆向结论。
|
||||||
|
- **绝对禁止将探针环境的现状当作业务问题的根因**:例如测试企业的出站规则停用,绝不代表目标正式企业的单据卡住是因为规则停用。
|
||||||
|
2. **探针完毕后必须立即主动切回业务企业**:
|
||||||
|
- 一旦在测试企业摸清 API 契约与数据结构,必须**自动、毫不犹豫地切换回用户最初声明的问题主体(目标正式企业与员工身份)**执行只读验证;
|
||||||
|
- 绝不能等用户反问“你在说什么、为什么不看某某所在的正式企业”才被动纠正。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 沉淀优先于临时脚本(Productization First)
|
||||||
|
|
||||||
|
在排障过程中,当发现需要调用尚未被 CLI 封装的系统内部接口(如系统出站消息规则 `GET api/outbound/v1/message`、投递日志 `POST api/outbound/v1/message/messageLog` 等)时:
|
||||||
|
|
||||||
|
1. **严禁随手编写 ad-hoc 一次性脚本(`scratch_*.ts`)解决眼前问题**:
|
||||||
|
- 一次性脚本容易陷入路径引用、未导出函数、临时编译报错等低价值泥潭;
|
||||||
|
- 一次性脚本无法给用户留下可复现、可交付的资产。
|
||||||
|
2. **标准研发流:边排障边沉淀到工程体系**:
|
||||||
|
- 按照分层架构规范,第一时间将接口接入:
|
||||||
|
$$\text{transport/ (API 校验)} \rightarrow \text{services.ts (业务门面)} \rightarrow \text{cli/commands/ (用户命令)} \rightarrow \text{command-metadata.ts (参数契约)}$$
|
||||||
|
- 补齐最小单元测试,保证 `bun test` 与 `bun run check` 通过;
|
||||||
|
- **直接使用自身编译/运行的官方 CLI 命令(例如 `hose-use workflow outbound logs ...`)为用户输出排查结果**。
|
||||||
|
3. **闭环 PR 与本地重载**:
|
||||||
|
- 查完问题后,主动通过标准 PR 流程将能力合入主分支;
|
||||||
|
- 执行 `bun run dev:override` 重新编译安装本地开发二进制与 Skill,保持环境资产最新。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 合思审批流与工作流联动排障心智模型(Mental Model)
|
||||||
|
|
||||||
|
当遇到“新提交的单据卡在工作流计算节点,且工作流运行日志没有任何记录”时,必须建立**全链路事件下发**的全局排查视角:
|
||||||
|
|
||||||
|
$$\text{单据提交审批} \xrightarrow{\text{审批流出站节点}} \text{系统出站规则 (Outbound)} \xrightarrow{\text{HTTP Webhook}} \text{工作流触发器 (Piper)} \xrightarrow{\text{OpenAPI}} \text{回写/推进节点}$$
|
||||||
|
|
||||||
|
排查漏斗四步法:
|
||||||
|
1. **看出站规则列表(`workflow outbound list`)**:
|
||||||
|
- 检查企业内是否存在类型为 `flow` 的出站规则;
|
||||||
|
- 检查规则是否启用(`enable: true`),且其 `callbackUrl` 是否指向目标工作流的 Webhook 路径。
|
||||||
|
2. **看出站投递日志(`workflow outbound logs <单号>`)**:
|
||||||
|
- 若**完全无记录**:说明单据流转时未匹配上任何出站规则(常见原因:审批流中的出站节点未关联出站规则,或单据模板类型不在出站规则适用范围);
|
||||||
|
- 若**有记录但状态为 FAILED**:查看日志中的 `request` 与目标服务器返回的 `response`(错误码、超时或 404 等)。
|
||||||
|
3. **看工作流日志(`workflow logs <workflowId>`)**:
|
||||||
|
- 若出站日志记录为 SUCCESS,但工作流日志为 0,排查 Webhook 载荷格式与工作流触发器入参映射是否脱节。
|
||||||
|
4. **看单据类型契约(`formSpecification`)**:
|
||||||
|
- 检查历史成功单据与卡住单据的表单规范(如「商机费用报销」vs「差旅费报销单」),核对工作流内代码节点或查询节点是否写死了特定单据模板 ID。
|
||||||
@@ -27,7 +27,7 @@ jobs:
|
|||||||
build-and-publish:
|
build-and-publish:
|
||||||
name: 🚀 Build & Publish Multi-Platform Binaries
|
name: 🚀 Build & Publish Multi-Platform Binaries
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
timeout-minutes: 30
|
timeout-minutes: 60
|
||||||
permissions:
|
permissions:
|
||||||
contents: write
|
contents: write
|
||||||
env:
|
env:
|
||||||
@@ -183,9 +183,9 @@ jobs:
|
|||||||
local file="$1" filename expected_hash attempt info existing remote_hash asset_id response delete_failed
|
local file="$1" filename expected_hash attempt info existing remote_hash asset_id response delete_failed
|
||||||
filename=$(basename "$file")
|
filename=$(basename "$file")
|
||||||
expected_hash=$(sha256sum "$file" | awk '{ print $1 }')
|
expected_hash=$(sha256sum "$file" | awk '{ print $1 }')
|
||||||
for attempt in 1 2 3; do
|
for attempt in 1 2 3 4 5; do
|
||||||
if [ "$attempt" -gt 1 ]; then sleep "${GITEA_RETRY_DELAY:-3}"; fi
|
if [ "$attempt" -gt 1 ]; then sleep "${GITEA_RETRY_DELAY:-3}"; fi
|
||||||
echo " [start] Uploading ${filename} to Gitea (attempt ${attempt}/3)..."
|
echo " [start] Uploading ${filename} to Gitea (attempt ${attempt}/5)..."
|
||||||
if ! info=$(curl -fsS --connect-timeout 15 --max-time 60 -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}"); then
|
if ! info=$(curl -fsS --connect-timeout 15 --max-time 60 -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}"); then
|
||||||
continue
|
continue
|
||||||
fi
|
fi
|
||||||
@@ -212,24 +212,16 @@ jobs:
|
|||||||
return 0
|
return 0
|
||||||
fi
|
fi
|
||||||
done
|
done
|
||||||
echo "::error::Failed to upload ${filename} after 3 attempts."
|
echo "::error::Failed to upload ${filename} after 5 attempts."
|
||||||
return 1
|
return 1
|
||||||
}
|
}
|
||||||
|
|
||||||
# Bound outbound traffic: large raw binaries must not compete with all archives.
|
# 串行上传:Gitea 维护期并发推大文件容易把重试窗口耗光,宁可慢也不要丢资产。
|
||||||
pids=()
|
# 配合 job 超时 60 分钟与单资产 5 次重试,给服务端抖动留出余量。
|
||||||
failed=0
|
failed=0
|
||||||
for file in dist/bin/hose-use-* dist/bin/checksums.txt; do
|
for file in dist/bin/hose-use-* dist/bin/checksums.txt; do
|
||||||
upload_asset "$file" &
|
upload_asset "$file" || failed=1
|
||||||
pids+=($!)
|
|
||||||
if [ "${#pids[@]}" -eq 2 ]; then
|
|
||||||
for pid in "${pids[@]}"; do wait "$pid" || failed=1; done
|
|
||||||
pids=()
|
|
||||||
fi
|
|
||||||
done
|
done
|
||||||
if [ "${#pids[@]}" -gt 0 ]; then
|
|
||||||
for pid in "${pids[@]}"; do wait "$pid" || failed=1; done
|
|
||||||
fi
|
|
||||||
if [ "$failed" -ne 0 ]; then
|
if [ "$failed" -ne 0 ]; then
|
||||||
echo "::error::One or more Gitea assets failed to upload."
|
echo "::error::One or more Gitea assets failed to upload."
|
||||||
exit 1
|
exit 1
|
||||||
|
|||||||
@@ -28,7 +28,7 @@
|
|||||||
## 已知基础设施
|
## 已知基础设施
|
||||||
|
|
||||||
- New API(LLM 代理)端点为 `api.ying-qing.cn`;原 Sealos 实例 `sealosgzg.site` 已回收,属用户本地基础设施,与本仓库代码无关。
|
- New API(LLM 代理)端点为 `api.ying-qing.cn`;原 Sealos 实例 `sealosgzg.site` 已回收,属用户本地基础设施,与本仓库代码无关。
|
||||||
- workflow 灰度节点开通曾用的 `*.sealosgzg.site` 第三方网关已在 commit `e562ae9` 移除,改为本地 EASO 换票后直连 Piper。**当前源码/产物中已无任何 `sealosgzg.site` 残留,也不存在「迁移到 api.ying-qing.cn」这个端点**(`api.ying-qing.cn` 是 LLM 代理,不是工作流网关)。不要再派后续 Agent 做这项无效清理。Piper 域名常量见 `src/core/http/script-engine-client.ts:19` 与 `transport/catalog/api.ts:84,87`,均为硬编码且无环境变量覆盖口(旧 `HOSE_GRAY_GATEWAY_URL` 逃生口随 e562ae9 一并删除)。
|
- workflow 灰度节点开通曾用的 `*.sealosgzg.site` 第三方网关已在 commit `e562ae9` 移除,改为本地 EASO 换票后直连 Piper。**当前源码/产物中已无任何 `sealosgzg.site` 残留,也不存在「迁移到 api.ying-qing.cn」这个端点**(`api.ying-qing.cn` 是 LLM 代理,不是工作流网关)。不要再派后续 Agent 做这项无效清理。Piper 域名常量见 `src/core/http/piper-workflow-client.ts`(收口于 `piper-endpoints.ts`)与 `transport/catalog/api.ts:84,87`,均为硬编码且无环境变量覆盖口(旧 `HOSE_GRAY_GATEWAY_URL` 逃生口随 e562ae9 一并删除)。
|
||||||
|
|
||||||
## 工作流与 Piper 核心契约(2026-11-02 固化)
|
## 工作流与 Piper 核心契约(2026-11-02 固化)
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "hose-use",
|
"name": "hose-use",
|
||||||
"version": "0.9.4",
|
"version": "0.9.8",
|
||||||
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
|
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
|
||||||
"author": {
|
"author": {
|
||||||
"name": "yingqing"
|
"name": "yingqing"
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ CLI (src/cli.ts) / AI PRO (src/aipro-cli.ts) / MCP (src/server.ts) / HTTP (src/h
|
|||||||
- `server.ts` 只做单工具 MCP 协议适配(`hose_cli` 委托 `src/cli/runner.ts`)
|
- `server.ts` 只做单工具 MCP 协议适配(`hose_cli` 委托 `src/cli/runner.ts`)
|
||||||
- `src/cli/registry.ts` 作为顶层命令、别名与常驻属性的唯一声明式注册表
|
- `src/cli/registry.ts` 作为顶层命令、别名与常驻属性的唯一声明式注册表
|
||||||
- 业务编排统一放在 `domains/*/tools.ts` 或 `domains/*/services.ts`
|
- 业务编排统一放在 `domains/*/tools.ts` 或 `domains/*/services.ts`
|
||||||
|
- 开放平台官方接口/规范/参数规格检索统一使用 `hose-use docs search/show`,严禁 Agent 或上层代码绕过 CLI 直接解析 specs 目录下的底层 JSON 数据
|
||||||
- 自建应用平台统一位于 `domains/platform/`,applications、datalink、workflow 分别拥有自己的模型、传输与服务出口;applications 不反向依赖另外两者,DataLink 不依赖 workflow,跨子模块不得直接调用 api。
|
- 自建应用平台统一位于 `domains/platform/`,applications、datalink、workflow 分别拥有自己的模型、传输与服务出口;applications 不反向依赖另外两者,DataLink 不依赖 workflow,跨子模块不得直接调用 api。
|
||||||
- `domains/**/api.ts` 只负责 HTTP 请求和响应校验,严禁被入口层直接导入
|
- `domains/**/api.ts` 只负责 HTTP 请求和响应校验,严禁被入口层直接导入
|
||||||
- `core/` 严格保持基础设施窄白名单(`auth/`, `cache/`, `config/`, `db/`, `errors.ts`, `http/`),构建产物与 Skill 分发统一置于 `src/packaging/`
|
- `core/` 严格保持基础设施窄白名单(`auth/`, `cache/`, `config/`, `db/`, `errors.ts`, `http/`),构建产物与 Skill 分发统一置于 `src/packaging/`
|
||||||
@@ -54,6 +55,7 @@ CLI (src/cli.ts) / AI PRO (src/aipro-cli.ts) / MCP (src/server.ts) / HTTP (src/h
|
|||||||
常用子域入口:
|
常用子域入口:
|
||||||
|
|
||||||
- Platform 说明:[src/domains/platform/README.platform.md](./src/domains/platform/README.platform.md)
|
- Platform 说明:[src/domains/platform/README.platform.md](./src/domains/platform/README.platform.md)
|
||||||
|
- Docs 说明:[src/domains/docs/README.docs.md](./src/domains/docs/README.docs.md)
|
||||||
|
|
||||||
## 开发与修改规则
|
## 开发与修改规则
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# hose-use (v0.9.4)
|
# hose-use (v0.9.8)
|
||||||
|
|
||||||
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
|
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
|
||||||
|
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ src/http/ # HTTP -> runCli
|
|||||||
| `EasoClient` | `unity.ekuaibao.com` | 统一认证与 EASO 资源 |
|
| `EasoClient` | `unity.ekuaibao.com` | 统一认证与 EASO 资源 |
|
||||||
| `PiperClient` | `piper.ekuaibao.com` | 工作流列表、详情、配置保存与 Job 执行 |
|
| `PiperClient` | `piper.ekuaibao.com` | 工作流列表、详情、配置保存与 Job 执行 |
|
||||||
|
|
||||||
客户端装配统一位于 `src/core/http/`:主站使用 `session-client.ts`,Unity/EASO 使用 `unity-client.ts`,Piper 使用 `script-engine-client.ts`。工作流 CLI 按应用 ID 创建 Piper 客户端;不在 MCP Server 内单独分派业务。
|
客户端装配统一位于 `src/core/http/`:主站使用 `hose-web-session-client.ts`,Unity/EASO 使用 `unity-easo-client.ts`,Piper 使用 `piper-workflow-client.ts`。工作流 CLI 按应用 ID 创建 Piper 客户端;不在 MCP Server 内单独分派业务。
|
||||||
|
|
||||||
## 认证链路
|
## 认证链路
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "hose-use",
|
"name": "hose-use",
|
||||||
"version": "0.9.4",
|
"version": "0.9.8",
|
||||||
"module": "src/server.ts",
|
"module": "src/server.ts",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"exports": {
|
"exports": {
|
||||||
|
|||||||
@@ -162,7 +162,7 @@ for arg in "$@"; do
|
|||||||
done
|
done
|
||||||
exit 22
|
exit 22
|
||||||
`, { mode: 0o755 });
|
`, { mode: 0o755 });
|
||||||
const result = spawnSync("bash", ["-eo", "pipefail", "-c", step.run], { cwd: f.root, env: { ...process.env, PATH: `${join(f.root, "tools")}:${process.env.PATH}`, GITEA_TOKEN: "fixture", GITEA_RETRY_DELAY: "0", GITEA_HOST: "https://example.test", GITEA_REPO: "test/repo", RELEASE_TAG: "v1.0.0" }, encoding: "utf8", timeout: 30_000 });
|
const result = spawnSync("bash", ["-eo", "pipefail", "-c", step.run], { cwd: f.root, env: { ...process.env, PATH: `${join(f.root, "tools")}:${process.env.PATH}`, GITEA_TOKEN: "fixture", GITEA_RETRY_DELAY: "0", GITEA_HOST: "https://example.test", GITEA_REPO: "test/repo", RELEASE_TAG: "v1.0.0" }, encoding: "utf8", timeout: 40_000 });
|
||||||
expect(result.status).toBe(1);
|
expect(result.status).toBe(1);
|
||||||
expect(result.stdout).toContain("assets failed to upload");
|
expect(result.stdout).toContain("assets failed to upload");
|
||||||
expect(result.stdout).not.toContain("Successfully published");
|
expect(result.stdout).not.toContain("Successfully published");
|
||||||
@@ -173,7 +173,7 @@ exit 22
|
|||||||
const result = f.run();
|
const result = f.run();
|
||||||
expect(result.status).toBe(0);
|
expect(result.status).toBe(0);
|
||||||
for (const name of f.files) expect(readFileSync(join(f.root, `count-${name}`), "utf8")).toBe("2");
|
for (const name of f.files) expect(readFileSync(join(f.root, `count-${name}`), "utf8")).toBe("2");
|
||||||
expect(result.stdout).toContain("attempt 2/3");
|
expect(result.stdout).toContain("attempt 2/5");
|
||||||
}, 60_000);
|
}, 60_000);
|
||||||
|
|
||||||
test("correct mirror assets are verified and retained without uploading replacements", () => {
|
test("correct mirror assets are verified and retained without uploading replacements", () => {
|
||||||
@@ -189,7 +189,7 @@ exit 22
|
|||||||
expect(readFileSync(join(f.root, "gh.log"), "utf8")).toContain("release download v1.0.0");
|
expect(readFileSync(join(f.root, "gh.log"), "utf8")).toContain("release download v1.0.0");
|
||||||
}, 60_000);
|
}, 60_000);
|
||||||
|
|
||||||
test("asset transfers never exceed two concurrent workers", () => {
|
test("asset transfers are serialized to a single worker", () => {
|
||||||
const f = mirrorFixture("concurrency");
|
const f = mirrorFixture("concurrency");
|
||||||
expect(f.run().status).toBe(0);
|
expect(f.run().status).toBe(0);
|
||||||
let active = 0, peak = 0;
|
let active = 0, peak = 0;
|
||||||
@@ -198,6 +198,6 @@ exit 22
|
|||||||
peak = Math.max(peak, active);
|
peak = Math.max(peak, active);
|
||||||
}
|
}
|
||||||
expect(active).toBe(0);
|
expect(active).toBe(0);
|
||||||
expect(peak).toBeLessThanOrEqual(2);
|
expect(peak).toBe(1);
|
||||||
}, 60_000);
|
}, 60_000);
|
||||||
});
|
});
|
||||||
@@ -2,11 +2,11 @@
|
|||||||
name: hose-aipro
|
name: hose-aipro
|
||||||
description: "合思 AI PRO(EASO AI PRO)确定性审批仲裁网关 CLI 与技能套件:单据挂载绑定、事实证据核验与打标 (PASS/FAIL/SKIP)、审核要点/规则场景库检索、确定性审批仲裁(同意/驳回/转人工硬阻断)、审计轨迹日志查询与常驻服务管理。用于一切合思 AI PRO 确定性审批仲裁与要点核验请求。"
|
description: "合思 AI PRO(EASO AI PRO)确定性审批仲裁网关 CLI 与技能套件:单据挂载绑定、事实证据核验与打标 (PASS/FAIL/SKIP)、审核要点/规则场景库检索、确定性审批仲裁(同意/驳回/转人工硬阻断)、审计轨迹日志查询与常驻服务管理。用于一切合思 AI PRO 确定性审批仲裁与要点核验请求。"
|
||||||
metadata:
|
metadata:
|
||||||
version: 0.9.4
|
version: 0.9.8
|
||||||
short-description: 合思 AI PRO 确定性审批仲裁网关与审核要点核验 skill
|
short-description: 合思 AI PRO 确定性审批仲裁网关与审核要点核验 skill
|
||||||
---
|
---
|
||||||
|
|
||||||
# hose-aipro (v0.9.4)
|
# hose-aipro (v0.9.8)
|
||||||
|
|
||||||
合思 AI PRO 确定性审批仲裁网关是专门面向企业财务核算、单据审核与自动化合规风控的确定性仲裁命令行与 SDK。
|
合思 AI PRO 确定性审批仲裁网关是专门面向企业财务核算、单据审核与自动化合规风控的确定性仲裁命令行与 SDK。
|
||||||
|
|
||||||
|
|||||||
@@ -2,11 +2,11 @@
|
|||||||
name: hose-use
|
name: hose-use
|
||||||
description: "合思/易快报(Ekuaibao)企业级 SaaS 一站式能力:hose-use CLI/SDK 多账号登录、租户切换、单据检索与审批动作、自建应用与工作流扫描、密钥与应用中心、常驻守护进程与 HTTP 文档/OpenAPI,以及工作流 MVEL 代码节点脚本生成调试、节点批量开通。用于一切合思/易快报相关请求。"
|
description: "合思/易快报(Ekuaibao)企业级 SaaS 一站式能力:hose-use CLI/SDK 多账号登录、租户切换、单据检索与审批动作、自建应用与工作流扫描、密钥与应用中心、常驻守护进程与 HTTP 文档/OpenAPI,以及工作流 MVEL 代码节点脚本生成调试、节点批量开通。用于一切合思/易快报相关请求。"
|
||||||
metadata:
|
metadata:
|
||||||
version: 0.9.4
|
version: 0.9.8
|
||||||
short-description: 合思/易快报 企业级 CLI 与工作流 skill 套件(含 MVEL 代码节点)
|
short-description: 合思/易快报 企业级 CLI 与工作流 skill 套件(含 MVEL 代码节点)
|
||||||
---
|
---
|
||||||
|
|
||||||
# hose-use (v0.9.4)
|
# hose-use (v0.9.8)
|
||||||
|
|
||||||
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
|
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
|
||||||
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
|
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
|
||||||
@@ -89,6 +89,14 @@ metadata:
|
|||||||
- 原生 `every` 的筛选字段物理键与右值选择器是两种结构:左侧保留 `feeTypeId`,右侧固定费用类型需保留前端 `value()` 描述符的真实 `key` 和 `label`;裸 ID 运行成功不代表设计器正常显示;
|
- 原生 `every` 的筛选字段物理键与右值选择器是两种结构:左侧保留 `feeTypeId`,右侧固定费用类型需保留前端 `value()` 描述符的真实 `key` 和 `label`;裸 ID 运行成功不代表设计器正常显示;
|
||||||
- 金额来源、费用类型与明细对应关系须按用户确认的业务规则和实际字段元数据确定;创单引用循环聚合结果,空明细不得继续创单或回写成功;
|
- 金额来源、费用类型与明细对应关系须按用户确认的业务规则和实际字段元数据确定;创单引用循环聚合结果,空明细不得继续创单或回写成功;
|
||||||
- 回读用户手工保存的 JSON 时,同时检查 `batch` / `batchSize`;并行配置会改变执行方式,不得当作显示修复自动覆盖。完整结构、金额类型与空列表兼容方案见 [references/workflow.md §20](./references/workflow.md#20-原生循环筛选选择器与费用明细)。
|
- 回读用户手工保存的 JSON 时,同时检查 `batch` / `batchSize`;并行配置会改变执行方式,不得当作显示修复自动覆盖。完整结构、金额类型与空列表兼容方案见 [references/workflow.md §20](./references/workflow.md#20-原生循环筛选选择器与费用明细)。
|
||||||
|
18. **合思开放平台接口自省铁律(Docs & OpenAPI Self-Reflection First & Zero-JSON-Digging)**:
|
||||||
|
- 当需要调研或回答“合思有哪些接口、支持哪些字段、具体参数/返回值规范是什么、如何设计第三方系统对接方案”时,**唯一正规、第一优先级的入口是 `hose-use docs search <关键词>` 与 `hose-use docs show <Path>`**;
|
||||||
|
- **严禁翻找源码或 specs 目录下的 `docs-catalog.json` / `openapi*.json`**,严禁使用 `bun -e '...'` 或系统临时脚本暴力解析底层 JSON 文件;
|
||||||
|
- 检索三步法:
|
||||||
|
1. 查看模块大类:`hose-use docs categories`(了解合思 26+ 个业务分类及端点分布);
|
||||||
|
2. 关键词检索:`hose-use docs search <关键词> [--category=<分类>] [--json]`(毫秒级获取接口清单与废弃标记);
|
||||||
|
3. 单篇精细查阅:`hose-use docs show <Path|URL|名称> [--json]`(获取官方完整参数规格、类型约束与 CURL 示例);
|
||||||
|
- 细节查阅专属参考文档:[references/docs.md](./references/docs.md)。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -97,6 +105,7 @@ metadata:
|
|||||||
| 用户意图 / 场景 | 推荐命令 | 深入参考文档 |
|
| 用户意图 / 场景 | 推荐命令 | 深入参考文档 |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| 全局运行上下文 / 身份诊断 / 免读源码自省 | `hose-use context [--json]`, `hose-use status` | [references/auth.md](./references/auth.md) |
|
| 全局运行上下文 / 身份诊断 / 免读源码自省 | `hose-use context [--json]`, `hose-use status` | [references/auth.md](./references/auth.md) |
|
||||||
|
| 合思开放平台官方接口/文档规范/售前能力调研/端点规格与CURL检索 | `hose-use docs search <关键词>`, `hose-use docs show <Path>`, `hose-use docs categories` | [references/docs.md](./references/docs.md) |
|
||||||
| AI PRO 确定性审批仲裁全流程 / 事实证据核验 | `hose-aipro bind`, `hose-aipro review`, `hose-aipro decide` | [独立技能 hose-aipro](../hose-aipro/SKILL.md) |
|
| AI PRO 确定性审批仲裁全流程 / 事实证据核验 | `hose-aipro bind`, `hose-aipro review`, `hose-aipro decide` | [独立技能 hose-aipro](../hose-aipro/SKILL.md) |
|
||||||
| 本机 AI PRO 审批网关常驻服务启停与管理 | `hose-use aipro <start\|stop\|restart\|status>` | [references/service.md](./references/service.md) |
|
| 本机 AI PRO 审批网关常驻服务启停与管理 | `hose-use aipro <start\|stop\|restart\|status>` | [references/service.md](./references/service.md) |
|
||||||
| 本地审批规约场景与规则管理 | `hose-use rule scopes`, `hose-use rule add --dry-run/--yes`, `hose-use rule list` | [references/service.md](./references/service.md) |
|
| 本地审批规约场景与规则管理 | `hose-use rule scopes`, `hose-use rule add --dry-run/--yes`, `hose-use rule list` | [references/service.md](./references/service.md) |
|
||||||
@@ -107,7 +116,7 @@ metadata:
|
|||||||
| OpenAPI 密钥持久化接入 / 从链接提取密钥 | `hose-use corps add-persistent`, `hose-use corps extract-keys <url>` | [references/auth.md](./references/auth.md) |
|
| OpenAPI 密钥持久化接入 / 从链接提取密钥 | `hose-use corps add-persistent`, `hose-use corps extract-keys <url>` | [references/auth.md](./references/auth.md) |
|
||||||
| 代客协助凭证导入 / 探针连通性诊断 | `hose-use auth import`, `hose-use probe` | [references/auth.md](./references/auth.md) |
|
| 代客协助凭证导入 / 探针连通性诊断 | `hose-use auth import`, `hose-use probe` | [references/auth.md](./references/auth.md) |
|
||||||
| 企业租户切换 / 查看当前企业 | `hose-use corps list`, `hose-use corps switch <id>` | [references/auth.md](./references/auth.md) |
|
| 企业租户切换 / 查看当前企业 | `hose-use corps list`, `hose-use corps switch <id>` | [references/auth.md](./references/auth.md) |
|
||||||
| 报销单据检索 / 费用明细下钻 / 中文字典 | `hose-use bill list [--since=7d] [--code=<单号>]`, `hose-use bill get <单号|ID> [--risk]` | [references/bill.md](./references/bill.md) |
|
| 报销单据检索 / 费用明细下钻 / 中文字典 | `hose-use bill list [--since=7d] [--code=<单号>] [--state=draft]`, `hose-use bill get <单号|ID> [--risk]` | [references/bill.md](./references/bill.md) |
|
||||||
| 单据审批动作(同意/驳回/转交/加签/评论) | `hose-use bill approve|reject|transfer|add-node|comment <单号|ID> --yes` | [references/bill.md](./references/bill.md) |
|
| 单据审批动作(同意/驳回/转交/加签/评论) | `hose-use bill approve|reject|transfer|add-node|comment <单号|ID> --yes` | [references/bill.md](./references/bill.md) |
|
||||||
| 单据审批历史 / 当前节点 / 后续流程 | `hose-use bill flow <单号|ID>` | [references/bill.md](./references/bill.md) |
|
| 单据审批历史 / 当前节点 / 后续流程 | `hose-use bill flow <单号|ID>` | [references/bill.md](./references/bill.md) |
|
||||||
| 单据风控预警 / 预算状态 / 发票风险 | `hose-use bill risk <单号|ID>` | [references/bill.md](./references/bill.md) |
|
| 单据风控预警 / 预算状态 / 发票风险 | `hose-use bill risk <单号|ID>` | [references/bill.md](./references/bill.md) |
|
||||||
@@ -131,7 +140,7 @@ metadata:
|
|||||||
| 企业通讯录检索 / 员工档案 / 防爆保护 | `hose-use contact search`, `hose-use contact list`, `hose-use contact get` | [references/contact.md](./references/contact.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 task todo`, `hose-use task submitted`, `hose-use task records`, `hose-use task cc` | [references/task.md](./references/task.md) |
|
||||||
| 应用管理 (桌面端工作台开通的用车/套件/制度/自建前台应用) | `hose-use app list [--keyword]`, `hose-use app get <应用>` | [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 <应用>`, `hose-use platform records <应用> <对象> --all`, `hose-use platform audit <应用> <对象>` | [references/workflow.md](./references/workflow.md) |
|
| 自建应用与数据模型 (开放平台业务对象/字段定义/全量记录/健康度体检) | `hose-use platform list`, `hose-use platform entities <应用>`, `hose-use platform records <应用> <对象> --all --ndjson -o <path>`, `hose-use platform audit <应用> <对象>` | [references/workflow.md](./references/workflow.md) |
|
||||||
| 自建应用单条/批量记录安全操作 (详情/停启用/安全合并编辑/批量补丁/台账重算) | `hose-use platform record <get|toggle|edit|batch-edit|recompute>` | [references/workflow.md](./references/workflow.md) |
|
| 自建应用单条/批量记录安全操作 (详情/停启用/安全合并编辑/批量补丁/台账重算) | `hose-use platform record <get|toggle|edit|batch-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 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 menu list`, `hose-use menu tree` | [references/workflow.md](./references/workflow.md) |
|
||||||
@@ -139,7 +148,7 @@ metadata:
|
|||||||
| 特定任务节点扫描 (如脚本/Webhook) | `hose-use workflow find --task=code-js2` | [references/workflow.md](./references/workflow.md) |
|
| 特定任务节点扫描 (如脚本/Webhook) | `hose-use workflow find --task=code-js2` | [references/workflow.md](./references/workflow.md) |
|
||||||
| 工作流详情、节点草稿修改、草稿保存、版本历史、运行日志、单次运行排障、发布与开通切换 | `hose-use workflow get`, `hose-use workflow job <jobId>`, `hose-use workflow patch`, `hose-use workflow save`, `hose-use workflow publish`, `hose-use workflow history`, `hose-use workflow logs`, `hose-use workflow toggle` | [references/workflow.md](./references/workflow.md) |
|
| 工作流详情、节点草稿修改、草稿保存、版本历史、运行日志、单次运行排障、发布与开通切换 | `hose-use workflow get`, `hose-use workflow job <jobId>`, `hose-use workflow patch`, `hose-use workflow save`, `hose-use workflow publish`, `hose-use workflow history`, `hose-use workflow logs`, `hose-use workflow toggle` | [references/workflow.md](./references/workflow.md) |
|
||||||
| 工作流节点树、代码依赖与静态门禁诊断(硬门禁/软建议/权限/DataLink公式) | `hose-use workflow analyze <pipelineId> [--fail]` | [references/workflow.md](./references/workflow.md) |
|
| 工作流节点树、代码依赖与静态门禁诊断(硬门禁/软建议/权限/DataLink公式) | `hose-use workflow analyze <pipelineId> [--fail]` | [references/workflow.md](./references/workflow.md) |
|
||||||
| 企业已开通工作流节点字典探针与灰度开通 | `hose-use workflow nodes [--all]`, `hose-use workflow nodes grant <type...>` | [references/workflow.md](./references/workflow.md) |
|
| 企业已开通工作流节点字典探针与灰度开通 | `hose-use workflow nodes [--all]`, `hose-use workflow nodes grant <type...> [--allow-prod]` | [references/workflow.md](./references/workflow.md) |
|
||||||
| 工作流错误管道扫描与本地去重提醒 | `hose-use workflow check [--fail-on-alert]` | [references/workflow.md](./references/workflow.md) |
|
| 工作流错误管道扫描与本地去重提醒 | `hose-use workflow check [--fail-on-alert]` | [references/workflow.md](./references/workflow.md) |
|
||||||
| 企业 OpenAPI 接入密钥(默认脱敏) | `hose-use keys [--json]`, `hose-use openapi keys`, `hose-use store keys` | [references/store.md](./references/store.md) |
|
| 企业 OpenAPI 接入密钥(默认脱敏) | `hose-use keys [--json]`, `hose-use openapi keys`, `hose-use store keys` | [references/store.md](./references/store.md) |
|
||||||
| 企业已购应用 / 应用商店探查 | `hose-use store list / search / get` | [references/store.md](./references/store.md) |
|
| 企业已购应用 / 应用商店探查 | `hose-use store list / search / get` | [references/store.md](./references/store.md) |
|
||||||
@@ -182,7 +191,10 @@ hose-use bill list --keyword=打车 # 单据关键字跨
|
|||||||
hose-use bill list --keyword=打车 --search-fields=name,form # 自定义匹配字段 (支持 name,code,form 等)
|
hose-use bill list --keyword=打车 --search-fields=name,form # 自定义匹配字段 (支持 name,code,form 等)
|
||||||
hose-use bill link CL20260901001 # 生成官方 Web 详情直达免密跳转链接
|
hose-use bill link CL20260901001 # 生成官方 Web 详情直达免密跳转链接
|
||||||
hose-use bill list --json -o /tmp/bills.json # 导出全量单据报文至本地磁盘
|
hose-use bill list --json -o /tmp/bills.json # 导出全量单据报文至本地磁盘
|
||||||
|
hose-use bill list --state=draft --json # 查询我发起的未提交草稿(flows/my 数据源)
|
||||||
|
hose-use bill list --state=draft --template=<模板ID> --title=付款 --staff=张三 --page=1 # 草稿模板/标题/提交人过滤
|
||||||
hose-use bill get n0GMIM0dkQmKbS # 精准查询单据详情 (中文字段映射)
|
hose-use bill get n0GMIM0dkQmKbS # 精准查询单据详情 (中文字段映射)
|
||||||
|
hose-use bill get <单号|flowId> # 草稿也支持按 flowId 直读(工作流 Job 输出)
|
||||||
hose-use bill get S26000001 --risk # 在详情中附加费控风控与发票风险快照
|
hose-use bill get S26000001 --risk # 在详情中附加费控风控与发票风险快照
|
||||||
hose-use bill approve S26000001 --yes # 同意当前待办
|
hose-use bill approve S26000001 --yes # 同意当前待办
|
||||||
hose-use bill reject S26000001 --comment "金额不符" --yes # 驳回并写明原因
|
hose-use bill reject S26000001 --comment "金额不符" --yes # 驳回并写明原因
|
||||||
@@ -233,7 +245,7 @@ hose-use platform list # 列出企业可见的
|
|||||||
hose-use platform entities 新转转集团 # 查看自建应用下的业务对象与字段
|
hose-use platform entities 新转转集团 # 查看自建应用下的业务对象与字段
|
||||||
hose-use platform records 新转转集团 合同 --stats # 宏观结构画像(总数/启停比率/重名数/编码规则聚类)
|
hose-use platform records 新转转集团 合同 --stats # 宏观结构画像(总数/启停比率/重名数/编码规则聚类)
|
||||||
hose-use platform records 新转转集团 合同 --ndjson --flat # 万级海量数据 $O(1)$ 内存逐行流式输出 JSON Lines
|
hose-use platform records 新转转集团 合同 --ndjson --flat # 万级海量数据 $O(1)$ 内存逐行流式输出 JSON Lines
|
||||||
hose-use platform records 新转转集团 合同 --all -o /tmp/records.json # 自动翻页导出全量业务对象记录
|
hose-use platform records 新转转集团 合同 --all --ndjson -o /tmp/records.json # 自动翻页并流式导出全量业务对象记录
|
||||||
hose-use platform audit 新转转集团 合同 --check-fields="我方签约主体" # 一键巡检必填缺失、停用引用与跨表同步差异
|
hose-use platform audit 新转转集团 合同 --check-fields="我方签约主体" # 一键巡检必填缺失、停用引用与跨表同步差异
|
||||||
hose-use platform record get <记录ID> # 免传应用/对象,直接按记录 ID 获取完整详情
|
hose-use platform record get <记录ID> # 免传应用/对象,直接按记录 ID 获取完整详情
|
||||||
hose-use platform record toggle 新转转集团 合同 <记录ID> --dry-run # 预览状态切换
|
hose-use platform record toggle 新转转集团 合同 <记录ID> --dry-run # 预览状态切换
|
||||||
@@ -257,7 +269,7 @@ hose-use workflow publish wf_01k83y... --yes # 将保存后的工
|
|||||||
hose-use workflow nodes # 探查当前企业已开通的工作流节点字典(动作/控制/触发器)
|
hose-use workflow nodes # 探查当前企业已开通的工作流节点字典(动作/控制/触发器)
|
||||||
hose-use workflow nodes --all # 对照官方 108 个灰度节点清单查看全量开通状态
|
hose-use workflow nodes --all # 对照官方 108 个灰度节点清单查看全量开通状态
|
||||||
hose-use workflow nodes grant code-js2 --dry-run # 预览灰度开通变更(含固定附带开关)
|
hose-use workflow nodes grant code-js2 --dry-run # 预览灰度开通变更(含固定附带开关)
|
||||||
hose-use workflow nodes grant code-js2 --yes # 确认执行;生产企业硬拦截,可选 --password 管理员保护
|
hose-use workflow nodes grant code-js2 --yes # 确认执行;生产企业默认硬拦截,需 --allow-prod
|
||||||
hose-use workflow create --name="风险推送" --trigger=webhook --yes # 从零新建工作流 (支持 new, add, 自动分配 Webhook UUID, 强制草稿 state=0)
|
hose-use workflow create --name="风险推送" --trigger=webhook --yes # 从零新建工作流 (支持 new, add, 自动分配 Webhook UUID, 强制草稿 state=0)
|
||||||
hose-use workflow copy wf_01k83y... --name="监控克隆版" --yes # 复制工作流为新草稿 (支持 cp, clone, 自动重置 Webhook urlPath)
|
hose-use workflow copy wf_01k83y... --name="监控克隆版" --yes # 复制工作流为新草稿 (支持 cp, clone, 自动重置 Webhook urlPath)
|
||||||
hose-use workflow webhook send wf_01k83y... --bill=<单号> --yes # 向 Webhook 发送测试载荷(解决【获取更多数据样本】无事件问题)
|
hose-use workflow webhook send wf_01k83y... --bill=<单号> --yes # 向 Webhook 发送测试载荷(解决【获取更多数据样本】无事件问题)
|
||||||
@@ -288,6 +300,16 @@ hose-use service status # 查看常驻守护进
|
|||||||
hose-use service poll --corp=ID01ofWoOC1wiX --json # 轮询待办/消息并去重落盘
|
hose-use service poll --corp=ID01ofWoOC1wiX --json # 轮询待办/消息并去重落盘
|
||||||
hose-use service logs # 查看常驻守护进程日志
|
hose-use service logs # 查看常驻守护进程日志
|
||||||
hose-use service stop # 停止后台常驻守护进程
|
hose-use service stop # 停止后台常驻守护进程
|
||||||
|
|
||||||
|
# 8. 合思开放平台官方接口文档与端点规范 (docs)
|
||||||
|
hose-use docs categories # 查看 26+ 个业务分类及 HTTP 端点分布
|
||||||
|
hose-use docs categories --json # 结构化查看业务模块清单
|
||||||
|
hose-use docs search 预算 # 智能加权检索包含“预算”的全部接口与指南
|
||||||
|
hose-use docs search 批量更新 --category=预算 # 在指定业务分类内精准检索
|
||||||
|
hose-use docs search 角色组 --json # 结构化输出匹配端点列表
|
||||||
|
hose-use docs show /api/openapi/v2.1/budgets/\$budgetId/batchUpdate # 查看指定端点完整参数规格、约束与 CURL 示例
|
||||||
|
hose-use docs show /api/openapi/v2.1/budgets/\$budgetId/batchUpdate --json # 结构化输出端点定义模型
|
||||||
|
hose-use docs sync # 强制与 docs.ekuaibao.com 线上文档全量同步
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
@@ -27,6 +27,10 @@ CLI 使用本地企业配置中的 `accessToken`、员工 ID 和 `baseUrl` 完
|
|||||||
```bash
|
```bash
|
||||||
hose-use workflow nodes grant code risk --corp=<corpId> --dry-run
|
hose-use workflow nodes grant code risk --corp=<corpId> --dry-run
|
||||||
hose-use workflow nodes grant code risk --corp=<corpId> --yes
|
hose-use workflow nodes grant code risk --corp=<corpId> --yes
|
||||||
|
|
||||||
|
# 正式生产企业:默认被硬拦截,需显式追加 --allow-prod
|
||||||
|
hose-use workflow nodes grant code risk --corp=<corpId> --allow-prod --dry-run
|
||||||
|
hose-use workflow nodes grant code risk --corp=<corpId> --allow-prod --yes
|
||||||
```
|
```
|
||||||
|
|
||||||
工作流节点开通的默认 CLI 命令保持不变。先用 `--dry-run` 预览目标和节点,再对同一命令使用 `--yes` 执行。
|
工作流节点开通的默认 CLI 命令保持不变。先用 `--dry-run` 预览目标和节点,再对同一命令使用 `--yes` 执行。
|
||||||
@@ -35,7 +39,7 @@ hose-use workflow nodes grant code risk --corp=<corpId> --yes
|
|||||||
|
|
||||||
`--dry-run` 只预览操作,不会探测企业对应的 Piper 环境。成功开通可以确认所选环境;请求失败本身不能单独证明环境选错,还应检查认证错误和 Piper 返回的业务错误。确认目标使用测试 Piper 后,才在原命令上加 `--is-test`;该选项不会根据企业信息自动开启。
|
`--dry-run` 只预览操作,不会探测企业对应的 Piper 环境。成功开通可以确认所选环境;请求失败本身不能单独证明环境选错,还应检查认证错误和 Piper 返回的业务错误。确认目标使用测试 Piper 后,才在原命令上加 `--is-test`;该选项不会根据企业信息自动开启。
|
||||||
|
|
||||||
**生产企业硬拦截**:CLI 用 `isCorpProd` 判定企业,正式生产环境(含未标记、按名称保守推断为 prod 的企业)直接拒绝,且**没有 `--force` 逃生口**。灰度节点开通是不可逆的企业级写操作,只能切换到测试企业执行。`--is-test` 仅切换 Piper 域名,不构成对生产企业的授权。`--dry-run` 预览会展示 Piper 固定附带开关(`recalculate-the-approval-flow`、`ui-notification`、`start`),与实际 payload 一致。
|
**生产企业默认硬拦截**:CLI 用 `isCorpProd` 判定企业,正式生产环境(含未标记、按名称保守推断为 prod 的企业)默认拒绝。灰度节点开通是不可逆的企业级写操作;确需在生产环境执行时,必须显式追加 `--allow-prod` 承担风险,并继续遵守 `--dry-run` 预览 → `--yes` 执行的两阶段确认。`--is-test` 仅切换 Piper 域名,不构成对生产企业的授权。`--dry-run` 预览会展示 Piper 固定附带开关(`recalculate-the-approval-flow`、`ui-notification`、`start`),与实际 payload 一致。
|
||||||
|
|
||||||
## 结果处理
|
## 结果处理
|
||||||
|
|
||||||
|
|||||||
@@ -22,9 +22,10 @@ hose-use bill list --corp=uzU7pcWfScck00 --json
|
|||||||
- `--since=<duration>` / `-d`: 相对时间范围(如 `7d`、`30d`、`90d`、`1y`),大租户海量单据下强烈推荐以避免全量超时;
|
- `--since=<duration>` / `-d`: 相对时间范围(如 `7d`、`30d`、`90d`、`1y`),大租户海量单据下强烈推荐以避免全量超时;
|
||||||
- `--start-date=<date>` / `--end-date=<date>`: 起止日期过滤(支持 `YYYY-MM-DD` 或毫秒时间戳);
|
- `--start-date=<date>` / `--end-date=<date>`: 起止日期过滤(支持 `YYYY-MM-DD` 或毫秒时间戳);
|
||||||
- `--stage=<stage>`: 业务阶段过滤(如 `expense` 报销, `loan` 借款, `payment` 付款);
|
- `--stage=<stage>`: 业务阶段过滤(如 `expense` 报销, `loan` 借款, `payment` 付款);
|
||||||
- `--state=<state>` / `-s`: 审批与支付状态过滤(如 `paid` 已支付, `approving` 审批中, `draft` 草稿);
|
- `--state=<state>` / `-s`: 审批与支付状态过滤(如 `paid` 已支付, `approving` 审批中)。`--state=draft`(或 `草稿`)使用专用草稿列表:草稿尚未进入台账索引,数据源为「我发起」的 `flows/my`;
|
||||||
|
- 草稿专用过滤:`--template=<模板ID>`、`--title=<标题关键字>`、`--staff=<姓名|工号|员工ID>`、`--page=<页码>`(与 `--count` 配合分页);
|
||||||
- `--count=<number>` / `--limit` / `-n`: 单页拉取数量(默认 20);
|
- `--count=<number>` / `--limit` / `-n`: 单页拉取数量(默认 20);
|
||||||
- `--mine`: 快捷查询当前登录人提交的单据(自动桥接至 `task submitted`);
|
- `--mine`: 快捷查询当前登录人提交的单据(自动桥接至 `task submitted`;`--state=draft` 时仍走草稿列表);
|
||||||
- `--select=<fields>`: 按需指定返回字段(逗号分隔,如 `id,code,name,createTime,form`);
|
- `--select=<fields>`: 按需指定返回字段(逗号分隔,如 `id,code,name,createTime,form`);
|
||||||
- `--distinct`: 是否对单据记录去重。
|
- `--distinct`: 是否对单据记录去重。
|
||||||
|
|
||||||
@@ -40,8 +41,18 @@ hose-use bill list --code=CL20260901001
|
|||||||
|
|
||||||
# 查询近 30 天已支付的报销单
|
# 查询近 30 天已支付的报销单
|
||||||
hose-use bill list --since=30d --stage=expense --state=paid --limit=50
|
hose-use bill list --since=30d --stage=expense --state=paid --limit=50
|
||||||
|
|
||||||
|
# 查询我发起的未提交草稿(支持模板、标题、提交人与分页过滤)
|
||||||
|
hose-use bill list --state=draft
|
||||||
|
hose-use bill list --state=draft --template=<模板ID> --title=付款 --staff=张三 --page=1 --count=20
|
||||||
|
|
||||||
|
# 草稿详情:支持单号或 flowId(工作流创建的草稿可用 Job 输出里的 flowId 查询)
|
||||||
|
hose-use bill get <单号|flowId>
|
||||||
```
|
```
|
||||||
|
|
||||||
|
> 草稿列表只覆盖当前身份可见的「我发起」流程。他人或系统创建的草稿可能不在 `flows/my` 中;
|
||||||
|
> 已知单号时用 `bill get <单号>`,已知 flowId 时用 `bill get <flowId>` 直读详情。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 2. 单据详情精准下钻 (`bill get`)
|
## 2. 单据详情精准下钻 (`bill get`)
|
||||||
|
|||||||
@@ -0,0 +1,109 @@
|
|||||||
|
# 合思开放平台官方接口文档与端点规范 (docs)
|
||||||
|
|
||||||
|
合思/易快报拥有 26+ 个业务分类、330+ 篇官方文档与 270+ 个 HTTP OpenAPI 端点。
|
||||||
|
`hose-use docs` 命令域提供了**完全离线、毫秒级响应、带加权打分与完整 CURL/参数表格**的结构化自省能力。
|
||||||
|
|
||||||
|
> [!IMPORTANT]
|
||||||
|
> **Agent 与实施首选铁律**:
|
||||||
|
> 凡涉及“合思有哪些接口、特定业务(如预算/发票/报销/自建应用)支持哪些 API、请求参数与返回结构是什么、如何设计第三方系统集成方案”等场景,**唯一正规、第一优先级的入口是 `hose-use docs search` 与 `hose-use docs show`**。
|
||||||
|
> **严禁**翻找源码目录或直接用临时脚本(如 `bun -e`)硬扒 `specs/docs-catalog.json`!
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 常用子命令与速查
|
||||||
|
|
||||||
|
### 1. 业务分类全览 (`hose-use docs categories`)
|
||||||
|
查看合思开放平台包含的所有业务大类以及每个分类下的端点数量:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
hose-use docs categories
|
||||||
|
hose-use docs categories --json
|
||||||
|
```
|
||||||
|
|
||||||
|
输出示例:
|
||||||
|
```text
|
||||||
|
====== 合思开放平台业务模块分类 (共 26 个) ======
|
||||||
|
|
||||||
|
# 业务分类 文档篇数 HTTP 端点数
|
||||||
|
-- ------------ -------- -----------
|
||||||
|
1 单据 50 篇 42 个
|
||||||
|
2 自建应用 45 篇 38 个
|
||||||
|
3 预算 13 篇 9 个
|
||||||
|
4 费用类型 12 篇 10 个
|
||||||
|
5 员工档案 15 篇 12 个
|
||||||
|
...
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 关键词加权智能检索 (`hose-use docs search`)
|
||||||
|
按接口标题、请求路径、URL、参数规格、正文段落综合加权搜索。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 基础检索
|
||||||
|
hose-use docs search 预算
|
||||||
|
hose-use docs search roleDefGroups
|
||||||
|
hose-use docs search "发票查重"
|
||||||
|
|
||||||
|
# 限定业务大类检索 (通过 --category)
|
||||||
|
hose-use docs search 批量更新 --category=预算
|
||||||
|
hose-use docs search 审批 --category=单据
|
||||||
|
|
||||||
|
# 限制返回条数与 JSON 结构化输出 (最适合 Agent 解析)
|
||||||
|
hose-use docs search 预算 --limit=10 --json
|
||||||
|
```
|
||||||
|
|
||||||
|
**JSON 模式返回字段说明**:
|
||||||
|
- `total`: 命中总数
|
||||||
|
- `results`: 匹配条目数组,包含:
|
||||||
|
- `id`: 文档 ID
|
||||||
|
- `title`: 中文标题(如“批量更新(新增/修改/删除)预算节点”)
|
||||||
|
- `category`: 业务分类(如“预算”)
|
||||||
|
- `path`: HTTP 路由(如 `/api/openapi/v2.1/budgets/$budgetId/batchUpdate`)
|
||||||
|
- `method`: HTTP 方法(`GET`, `POST`, `PUT`, `DELETE` 等)
|
||||||
|
- `permalink`: 官方在线文档链接
|
||||||
|
- `matchReason`: 匹配依据与高亮摘要
|
||||||
|
|
||||||
|
### 3. 单篇接口详细规格查询 (`hose-use docs show`)
|
||||||
|
精准调阅指定端点的全量参数规格表、Query/Path/Body 定义、完整 CURL 示例以及成功/失败响应报文。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 按接口 Path 查看 (推荐)
|
||||||
|
hose-use docs show /api/openapi/v2.1/budgets/\$budgetId/batchUpdate
|
||||||
|
|
||||||
|
# 按文档 URL 查看
|
||||||
|
hose-use docs show /docs/open-api/budget/batch-pdate-budget-node
|
||||||
|
|
||||||
|
# 按中文标题模糊查看
|
||||||
|
hose-use docs show "批量更新(新增/修改/删除)预算节点"
|
||||||
|
|
||||||
|
# JSON 模式输出完整原始模型
|
||||||
|
hose-use docs show /api/openapi/v2.1/budgets/\$budgetId/batchUpdate --json
|
||||||
|
```
|
||||||
|
|
||||||
|
输出包含以下结构:
|
||||||
|
- **基本信息**:标题、分类、方法、路径、在线链接;
|
||||||
|
- **参数规格与定义**:Path Parameters、Query Parameters、Body Parameters(含层级嵌套、字段类型、必填性、默认值、枚举值和业务语义备注);
|
||||||
|
- **CURL / 调用示例**:包含实际请求头、典型 Payload JSON 模板;
|
||||||
|
- **响应示例**:成功响应 JSON 与失败状态码说明。
|
||||||
|
|
||||||
|
### 4. 强制全量同步更新 (`hose-use docs sync`)
|
||||||
|
当合思官方开放平台上线新接口或调整文档时,运行同步命令:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
hose-use docs sync
|
||||||
|
```
|
||||||
|
该命令会自动从 `https://docs.ekuaibao.com/search-index.json` 拉取最新全量索引,并自动更新本地 SQLite 缓存与静态存储。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 接口调研与售前方案编写标准 SOP (Agent Playbook)
|
||||||
|
|
||||||
|
当客户提出“我们需要做一个第三方系统(如预算系统、HRM、CRM、ERP)与合思的集成方案”时,Agent 必须遵循以下工作流:
|
||||||
|
|
||||||
|
1. **第一步:摸底业务分类**
|
||||||
|
执行 `hose-use docs categories`,识别目标业务在合思体系中的归属分类(例如预算归属于“预算”,部门人员归属于“企业组织架构/员工档案”,单据归属于“单据”)。
|
||||||
|
2. **第二步:拉取端点清单**
|
||||||
|
执行 `hose-use docs search <核心词> --category=<分类> --json`,获取该业务领域全量推荐端点,并注意过滤掉标注为 `历史版本(不推荐)` 的废弃接口。
|
||||||
|
3. **第三步:获取主力端点规格**
|
||||||
|
对筛选出的 2~3 个主力接口(如主数据批量更新、单据提交、状态回调),执行 `hose-use docs show <Path> --json` 获取精确的字段层级、类型与约束。
|
||||||
|
4. **第四步:产出方案**
|
||||||
|
基于官方规范提炼出系统对接模式(定时下发 vs 实时回调)、字段映射表、版本控制机制与并发防踩坑建议。整个过程完全通过 CLI 命令自闭环,高效且精确。
|
||||||
@@ -44,12 +44,14 @@ hose-use platform entities 新转转集团
|
|||||||
hose-use platform schema 新转转集团 合同
|
hose-use platform schema 新转转集团 合同
|
||||||
hose-use platform schema 新转转集团 合同 --keyword="金额"
|
hose-use platform schema 新转转集团 合同 --keyword="金额"
|
||||||
|
|
||||||
# 检索业务对象的底层真实数据记录(支持 --all 自动翻页拉取全量记录)
|
# 检索业务对象的底层真实数据记录(--all 自动翻页拉取全量记录)
|
||||||
hose-use platform records 新转转集团 合同 --limit=5
|
hose-use platform records 新转转集团 合同 --limit=5
|
||||||
hose-use platform records 新转转集团 合同 --keyword="技术服务" --fields "合同编号,金额,经办人" --json
|
hose-use platform records 新转转集团 合同 --keyword="技术服务" --fields "合同编号,金额,经办人" --json
|
||||||
hose-use platform records 新转转集团 支付计划表 --all --json -o /tmp/payment_plans.json
|
hose-use platform records 新转转集团 支付计划表 --all --ndjson -o /tmp/payment_plans.json
|
||||||
```
|
```
|
||||||
|
|
||||||
|
> `--all` 必须与 `--ndjson --output-file <path>` 一起使用;缺少流式导出时会返回 `DATASET_TOO_LARGE`(exitCode 2),并给出分页与流式导出的恢复建议。
|
||||||
|
|
||||||
### 2.1 业务对象记录操作 (`platform record`) 与安全全量合并 (Read-Modify-Write)
|
### 2.1 业务对象记录操作 (`platform record`) 与安全全量合并 (Read-Modify-Write)
|
||||||
|
|
||||||
> **关键防坑说明**:合思 DataLink `PUT /api/v2.2/datalink/platformDataLink/$id` 是**整单覆盖接口**,而非局部 PATCH。若只传修改的 1 个字段,未传字段会被清空、对象引用若未提取 `.id` 会报 417、`visibility` 漏传会导致全员不可见。`hose-use platform record edit` 与 `batch-edit` 默认内置 **Read-Modify-Write 安全合并引擎**,自动拉取原记录与 Schema、归一化嵌套引用 ID、保留全部存量字段与 `visibility` 权限,并支持字段中英文短名自动解析。
|
> **关键防坑说明**:合思 DataLink `PUT /api/v2.2/datalink/platformDataLink/$id` 是**整单覆盖接口**,而非局部 PATCH。若只传修改的 1 个字段,未传字段会被清空、对象引用若未提取 `.id` 会报 417、`visibility` 漏传会导致全员不可见。`hose-use platform record edit` 与 `batch-edit` 默认内置 **Read-Modify-Write 安全合并引擎**,自动拉取原记录与 Schema、归一化嵌套引用 ID、保留全部存量字段与 `visibility` 权限,并支持字段中英文短名自动解析。
|
||||||
@@ -186,7 +188,9 @@ hose-use workflow nodes --all
|
|||||||
|
|
||||||
# 3. 申请开通灰度节点(支持中文名归一化;同名节点需改用明确的 type)
|
# 3. 申请开通灰度节点(支持中文名归一化;同名节点需改用明确的 type)
|
||||||
hose-use workflow nodes grant code-js2 --dry-run # 预览变更,含 Piper 固定附带开关
|
hose-use workflow nodes grant code-js2 --dry-run # 预览变更,含 Piper 固定附带开关
|
||||||
hose-use workflow nodes grant code-js2 --yes # 确认执行;生产企业一律被硬拦截
|
hose-use workflow nodes grant code-js2 --yes # 确认执行;生产企业默认被硬拦截
|
||||||
|
hose-use workflow nodes grant code-js2 --allow-prod --dry-run # 生产企业:显式承担风险后预览
|
||||||
|
hose-use workflow nodes grant code-js2 --allow-prod --yes # 生产企业:确认执行
|
||||||
```
|
```
|
||||||
|
|
||||||
## 8. 工作流单次运行实例排障 (`workflow job`)
|
## 8. 工作流单次运行实例排障 (`workflow job`)
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# 规范与生成物(specs)
|
||||||
|
|
||||||
|
本目录集中存放随仓库分发的接口规范、结构快照与生成物,供 CLI 内嵌分发(`hose-use openapi`、本地 HTTP 文档页)、docs 域离线检索与发布校验读取。除 `hose-open-api/` 的源 YAML 和 `hose-close-api/` 的契约文档外,其余 JSON 都是生成物,不要手工编辑。
|
||||||
|
|
||||||
|
## 目录与文件
|
||||||
|
|
||||||
|
| 路径 | 类型 | 说明 | 维护方式 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| [hose-open-api/](./hose-open-api/openapi.yaml) | 源 YAML | hose-use 包装层 OpenAPI 3.1 源规范,入口文件通过相对 `$ref` 组装 `paths/` 与 `components/` | 手工维护,拆分说明见 [README.paths.md](./hose-open-api/paths/README.paths.md) |
|
||||||
|
| [hose-close-api/](./hose-close-api/README.md) | 文档 | 合思内部/网页接口契约清单(method、path、参数、响应结构与 JSON Schema) | 手工维护,约定见目录 README |
|
||||||
|
| [openapi.json](./openapi.json) | 生成物 | 包装层 OpenAPI 打包结果,供 `hose-use openapi` 与 HTTP 文档页内嵌 | `bun run openapi:bundle` |
|
||||||
|
| [openapi.raw.json](./openapi.raw.json) | 生成物 | 原生下游接口规范(`data` / `code` / `message` 响应包装) | `bun run openapi:generate-raw` |
|
||||||
|
| [workflow-schema.json](./workflow-schema.json) | 生成物 | 由 Zod 导出的工作流归一化结构 | `bun run export:workflow-schema` |
|
||||||
|
| [docs-catalog.json](./docs-catalog.json) | 快照 | 开放平台文档索引静态快照,作为 docs 域离线检索保底 | 随 docs 域更新重新生成并提交;运行时 `hose-use docs sync` 只刷新本地缓存,不改写本文件 |
|
||||||
|
|
||||||
|
## 修改约定
|
||||||
|
|
||||||
|
- 改包装层 API 一律先改 `hose-open-api/` 源 YAML,再执行 `bun run openapi:all` 重新生成两份 JSON;不要直接编辑生成物。
|
||||||
|
- `workflow-schema.json` 由 `src/domains/platform/workflow/types.ts` 的 Zod 模式推导;`export-workflow-schema.test.ts` 会校验仓库文件与重新导出的结果一致,改模式后必须重新导出。
|
||||||
|
- 生成物必须随 Git 提交:编译二进制与 CI 无需额外构建步骤即可携带完整规范(见 [Packaging 说明](../src/packaging/README.packaging.md))。
|
||||||
|
- 发布前 `scripts/release/check-version-sync.ts` 会核对 `hose-open-api/openapi.yaml` 与 `openapi.json` 的 `info.version` 是否和 `package.json` 一致。
|
||||||
|
- 本地抓包、租户模板等含业务 ID 的资料只放在已 Git 忽略的 `hose-close-api/_tmp-captured/`,不得提交。
|
||||||
|
|
||||||
|
## 消费方
|
||||||
|
|
||||||
|
| 消费方 | 读取内容 |
|
||||||
|
|---|---|
|
||||||
|
| `src/packaging/embedded-openapi.ts` | `openapi.json`、`openapi.raw.json`(构建期内嵌) |
|
||||||
|
| `src/domains/docs/tools.ts` | `docs-catalog.json`(离线检索保底) |
|
||||||
|
| `scripts/release/check-version-sync.ts` | `hose-open-api/openapi.yaml`、`openapi.json`(版本一致性) |
|
||||||
|
|
||||||
|
检索开放平台官方接口的正式入口是 `hose-use docs search/show`;上层代码与 Agent 不应绕过 CLI 直接解析本目录的 JSON 文件。
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{"version":"1.0.0","updatedAt":"2026-11-16T08:08:21.159Z","sourceUrl":"https://docs.ekuaibao.com/search-index.json","totalDocs":330,"totalEndpoints":279,"items":[{"id":3788,"title":"下载附件","category":"附件","url":"/docs/open-api/attachment/attachment-download","permalink":"https://docs.ekuaibao.com/docs/open-api/attachment/attachment-download","method":"POST","path":"/api/openapi/v2/attachment/downloadurls","breadcrumbs":["Open API","附件"],"headings":["Query Parameters","Body Parameters","CURL","成功响应","失败响应","钉盘附件下载","阿里云OSS CURL"],"sections":[{"title":"下载附件","content":"通过附件的 id、key 去获取附件的下载链接。 POST/api/openapi/v2/attachment/downloadurls 更新日志 2.3.1 🚀 优化了接口,支持ISV应用钉盘附件下载。 1.6.3 🐞 优化了接口 HTTP 500 错误,输出报错信息。"},{"title":"Query Parameters","content":"名称 类型 描述 是否必填 默认值 备注 accessToken String 认证token 必填 - 通过 获取授权 获取 accessToken"},{"title":"Body Parameters","content":"名称 类型 描述 是否必填 默认值 备注 -- Array 数组参数 必填 - 数组参数,最大支持 100 个参数 ∟ id String 文件fileId 必填 - 上传附件 接口返回的 fileId 字段 接口下载单据上的附件时,可通过 获取单据详情 获取 attachments 字段的 fileId 值 ∟ key String 文件key 必填 - 上传附件 接口返回的 key 字段 接口下载单据上的附件时,可通过 获取单据详情 获取 attachments 字段的 key 值,注意: key 值前缀是 DP:时,表示该附件是钉盘附件 。 ∟ expiration Number 下载链接有效时间 必填 - 下载链接在多长时间内有效,单位:秒,最大 1800 秒 ,钉盘附件该值无效"},{"title":"CURL","content":"curl --location --request POST 'https://app.ekuaibao.com/api/openapi/v2/attachment/downloadurls?accessToken=UvsbtOEHTsk000' \\ --header 'Content-Type: application/json' \\ --data-raw '[ { \"id\": \"61sbwX3DEAgk00\", \"key\": \"openapi0306c2d1-7a5b-4e96-8172-60c5ee0f971e-kotlin简介.docx\", \"expiration\": 1000 }, { \"id\": \"136634573449\", \"key\": \"DP:{\\\"fileId\\\":\\\"136634437985\\\",\\\"fileName\\\":\\\"128163bbba83.jpg\\\",\\\"fileSize\\\":2985928,\\\"fileType\\\":\\\"jpg\\\",\\\"spaceId\\\":\\\"7215288789\\\"}\", \"expiration\": 1000 } ]'"},{"title":"成功响应","content":"tip url 是文件下载路径,thumbUrl 是指缩略图的下载路径。 thumbUrl 只针对图片有效,PDF文件生成的链接是不可用的。 key 下载钉盘附件时,url 和 thumbUrl 都是 阿里OSS 文件链接,保存文件时需要根据key值内的 fileType 值来判断文件类型。 headers 只针对钉盘附件有效,下载文件时需要将 headers传入,否则会下载失败。 [ { \"id\": \"61sbwX3DEAgk00\", \"key\": \"openapi0306c2d1-7a5b-4e96-8172-60c5ee0f971e-kotlin简介.docx\", \"url\": \"https://ekuaibao.oss-cn-hangzhou.aliyuncs.com/openapi0306c2d1-7a5b-4e96-8172-60c5ee0f971e-kotlin%E7%AE%80%E4%BB%8B.docx?Expires=1599099810&OSSAccessKeyId=STS.NUTdxysMYQXwZApA734jgqnJb&Signature=wTRfcimdrHhXbL3efe8MftOSOmo%3D&security-token=CAIS8AF1q6Ft5B2yfSjIr5bhL8LNnpJ45pqcWGfBpTdmOOVLnqvhgDz2IHlPdHZhBekYtPszmW9Z6%2FsdlqF%2BSIJETEbNapPbRkWwXEXzDbDasumZsJYm6vT8a0XxZjf%2F2MjNGZabKPrWZvaqbX3diyZ32sGUXD6%2BXlujQ%2Fbr4NwdGbZxZASjaidcD9p7PxZrrNRgVUHcLvGwKBXn8AGyZQhKwlMk1zojtf7lmpTMtUuE0ALAp7VL99irEP%2BNdNJxOZpzadCx0dFte7DJuCwqsEERpPgn0PUao2ib447MXgQO%2BXScOu%2FT6cZ0MBRpwUXA2EKANZEagAFRCqgjZY6QvIiWMtTWb7UIfba4ebfujIHa7cn7sA3r0vGyNUnObhl5H5zW4cc%2FM%2FiHehACg83wRu189TUg4Qt5MRZ0KuYre7mpa4NWPJpcILHkRjLBR2YoL6Z27iqhNbtcZoezq%2B4ky3N60IIaXhUoYJcteXtru12W%2BiLzfiB%2FuA%3D%3D\", \"thumbUrl\": \"https://ekuaibao.oss-cn-hangzhou.aliyuncs.com/openapi0306c2d1-7a5b-4e96-8172-60c5ee0f971e-kotlin%E7%AE%80%E4%BB%8B.docx?Expires=1599099810&OSSAccessKeyId=STS.NUTdxysMYQXwZApA734jgqnJb&Signature=evQnFfd4YhL5zkFMovDl9ZfVdlw%3D&x-oss-process=image%2Fresize%2Cw_120%2Ch_120&security-token=CAIS8AF1q6Ft5B2yfSjIr5bhL8LNnpJ45pqcWGfBpTdmOOVLnqvhgDz2IHlPdHZhBekYtPszmW9Z6%2FsdlqF%2BSIJETEbNapPbRkWwXEXzDbDasumZsJYm6vT8a0XxZjf%2F2MjNGZabKPrWZvaqbX3diyZ32sGUXD6%2BXlujQ%2Fbr4NwdGbZxZASjaidcD9p7PxZrrNRgVUHcLvGwKBXn8AGyZQhKwlMk1zojtf7lmpTMtUuE0ALAp7VL99irEP%2BNdNJxOZpzadCx0dFte7DJuCwqsEERpPgn0PUao2ib447MXgQO%2BXScOu%2FT6cZ0MBRpwUXA2EKANZEagAFRCqgjZY6QvIiWMtTWb7UIfba4ebfujIHa7cn7sA3r0vGyNUnObhl5H5zW4cc%2FM%2FiHehACg83wRu189TUg4Qt5MRZ0KuYre7mpa4NWPJpcILHkRjLBR2YoL6Z27iqhNbtcZoezq%2B4ky3N60IIaXhUoYJcteXtru12W%2BiLzfiB%2FuA%3D%3D\" }, { \"id\": \"136634573449\", \"key\": \"DP:{\\\"fileId\\\":\\\"136634437985\\\",\\\"fileName\\\":\\\"128163bbba83.jpg\\\",\\\"fileSize\\\":2985928,\\\"fileType\\\":\\\"jpg\\\",\\\"spaceId\\\":\\\"7215288789\\\"}\", \"url\": \"https://sh-dualstack.trans.dingtalk.com/yundisk0/iAEIAqRmaWxlA6h5dW5kaXNrMATOITK4JgXNEKcGzTyBB85mF5ENCM24VQ.file\", \"thumbUrl\": \"https://sh-dualstack.trans.dingtalk.com/yundisk0/iAEIAqRmaWxlA6h5dW5kaXLine truncated
|
||||||
@@ -45,7 +45,7 @@ specs/hose-close-api/
|
|||||||
- `src/domains/feetype/api.ts`
|
- `src/domains/feetype/api.ts`
|
||||||
- `src/domains/assist-platform/api.ts`
|
- `src/domains/assist-platform/api.ts`
|
||||||
- `src/core/auth/login.ts`、`src/core/auth/openapi-v1.ts`、`src/core/auth/link-import.ts`
|
- `src/core/auth/login.ts`、`src/core/auth/openapi-v1.ts`、`src/core/auth/link-import.ts`
|
||||||
- `src/core/http/openapi-client.ts`、`unity-client.ts`、`script-engine-client.ts`、`assist-platform-client.ts`、`session-client.ts`
|
- `src/core/http/hose-web-session-client.ts`、`openapi-client.ts`、`piper-workflow-client.ts`、`hose-docs-client.ts`、`unity-easo-client.ts`、`assist-platform-client.ts`、`sso-auth-client.ts`
|
||||||
- 历史参考:`specs/openapi.raw.json`
|
- 历史参考:`specs/openapi.raw.json`
|
||||||
|
|
||||||
## 域名约定
|
## 域名约定
|
||||||
|
|||||||
@@ -17,10 +17,10 @@
|
|||||||
| A05 | GET | `BC /cloud-auth/public/auth/list-corporations` | Header `cloud-auth-token` | `{data:{items:[CorporationItem],externalItems:[]},errorCode?,errorMessage?}`;Item 字段见下 | `src/core/auth/login.ts:242` | 否 |
|
| A05 | GET | `BC /cloud-auth/public/auth/list-corporations` | Header `cloud-auth-token` | `{data:{items:[CorporationItem],externalItems:[]},errorCode?,errorMessage?}`;Item 字段见下 | `src/core/auth/login.ts:242` | 否 |
|
||||||
| A06 | POST | `BC /cloud-auth/public/auth/switch-corporation` | Header `cloud-auth-token`;body `{corporationId,userId,cluster}` | `{data:{accessToken:<authCode>},errorCode?,errorMessage?}` | `src/core/auth/login.ts:269` | 否 |
|
| A06 | POST | `BC /cloud-auth/public/auth/switch-corporation` | Header `cloud-auth-token`;body `{corporationId,userId,cluster}` | `{data:{accessToken:<authCode>},errorCode?,errorMessage?}` | `src/core/auth/login.ts:269` | 否 |
|
||||||
| A07 | POST | `IDP /api/idp/public/oauth2/token` | `{clientId:"whispered-app",grantType:"authorization_code",code:<authCode>,withIdToken:false}` | `{access_token,token_type,expires_in,refresh_token?,id_token?}` | `src/core/auth/login.ts:288` | 否 |
|
| A07 | POST | `IDP /api/idp/public/oauth2/token` | `{clientId:"whispered-app",grantType:"authorization_code",code:<authCode>,withIdToken:false}` | `{access_token,token_type,expires_in,refresh_token?,id_token?}` | `src/core/auth/login.ts:288` | 否 |
|
||||||
| A08 | GET | `BC /auth/oauth2/grant/ekb/accessToken` | Query `{corpId,ekbAccessToken,environment}` | `{data:<hose-access-token>}` | `src/core/http/unity-client.ts:70` | 否 |
|
| A08 | GET | `BC /auth/oauth2/grant/ekb/accessToken` | Query `{corpId,ekbAccessToken,environment}` | `{data:<hose-access-token>}` | `src/core/http/unity-easo-client.ts:70` | 否 |
|
||||||
| A09 | GET | `EKB /api/engine/realm/$UNITY/actions/jwt` | Query `{corpId}`;Headers `accesstoken`、`corpid`、`staffid` | `{id?,value?}`,取 `id` 或 `value` 作为 UNITY JWT | `src/core/http/unity-client.ts:91`、`src/core/auth/link-import.ts:262` | 否 |
|
| A09 | GET | `EKB /api/engine/realm/$UNITY/actions/jwt` | Query `{corpId}`;Headers `accesstoken`、`corpid`、`staffid` | `{id?,value?}`,取 `id` 或 `value` 作为 UNITY JWT | `src/core/http/unity-easo-client.ts:91`、`src/core/auth/link-import.ts:262` | 否 |
|
||||||
| A10 | GET | `EKB /api/engine/realm/$EASO/actions/jwt` | 同 A09 | `{id?,value?}`,取 `id` 或 `value` 作为 EASO JWT | `src/core/http/script-engine-client.ts:68` | 否 |
|
| A10 | GET | `EKB /api/engine/realm/$EASO/actions/jwt` | 同 A09 | `{id?,value?}`,取 `id` 或 `value` 作为 EASO JWT | `src/core/http/piper-workflow-client.ts:68` | 否 |
|
||||||
| A11 | GET | `EASO /api/realms/EASO` | Query `{corpId}`;Headers `Authorization: Bearer <unityJwt>`、可选 `hoseaccesstoken` | `{value:{accessToken}}` | `src/core/http/unity-client.ts:119` | 否 |
|
| A11 | GET | `EASO /api/realms/EASO` | Query `{corpId}`;Headers `Authorization: Bearer <unityJwt>`、可选 `hoseaccesstoken` | `{value:{accessToken}}` | `src/core/http/unity-easo-client.ts:119` | 否 |
|
||||||
| A12 | GET | `EKB /api/account/v2/session` | Headers `accesstoken`、`corpid`、可选 `staffid` | `{value:{id,userId,loginStaffId,corporationId,platform,isAssistPlatform,isShortTermToken,assistId,operationUserId,operationUserName,privilege,deviceType,loginAccountType,loginTime,expTime}}` | `src/core/auth/link-import.ts:329` | 否 |
|
| A12 | GET | `EKB /api/account/v2/session` | Headers `accesstoken`、`corpid`、可选 `staffid` | `{value:{id,userId,loginStaffId,corporationId,platform,isAssistPlatform,isShortTermToken,assistId,operationUserId,operationUserName,privilege,deviceType,loginAccountType,loginTime,expTime}}` | `src/core/auth/link-import.ts:329` | 否 |
|
||||||
| A13 | POST | `EKB /api/openapi/v1/auth/getAccessToken` | `{appKey,appSecurity}` | `{value:{accessToken,corporationId,expireTime,errorCode?,errorMessage?}}`;也兼容顶层 `accessToken`/`token` | `src/core/auth/openapi-v1.ts:133` | 否 |
|
| A13 | POST | `EKB /api/openapi/v1/auth/getAccessToken` | `{appKey,appSecurity}` | `{value:{accessToken,corporationId,expireTime,errorCode?,errorMessage?}}`;也兼容顶层 `accessToken`/`token` | `src/core/auth/openapi-v1.ts:133` | 否 |
|
||||||
| A14 | POST | `EKB /api/openapi/v1.1/provisional/getProvisionalAuth` | Query `{accessToken}`;body `{uid,pageType:"home",expireDate}` | `{value:{message:<loginUrl>}}`,从 URL 的 `accessToken` 参数取临时会话 token | `src/core/auth/openapi-v1.ts:199` | 否 |
|
| A14 | POST | `EKB /api/openapi/v1.1/provisional/getProvisionalAuth` | Query `{accessToken}`;body `{uid,pageType:"home",expireDate}` | `{value:{message:<loginUrl>}}`,从 URL 的 `accessToken` 参数取临时会话 token | `src/core/auth/openapi-v1.ts:199` | 否 |
|
||||||
@@ -39,7 +39,7 @@ staffId, userId, sourceChannel?, baseUrl?, external?, needAuth?
|
|||||||
|
|
||||||
## 2. platform / workflow(30)
|
## 2. platform / workflow(30)
|
||||||
|
|
||||||
工作流接口通过 Piper 客户端调用(`src/core/http/script-engine-client.ts`):
|
工作流接口通过 Piper 客户端调用(`src/core/http/piper-workflow-client.ts`):
|
||||||
`Authorization: Bearer <EASO JWT>`、`platformid: <platformId>`、可选 `hoseaccesstoken`。
|
`Authorization: Bearer <EASO JWT>`、`platformid: <platformId>`、可选 `hoseaccesstoken`。
|
||||||
`listPlatforms` 例外,它走主站 `ekbClient`。
|
`listPlatforms` 例外,它走主站 `ekbClient`。
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
openapi: 3.1.0
|
openapi: 3.1.0
|
||||||
info:
|
info:
|
||||||
title: hose-use API & MCP Tools Specification
|
title: hose-use API & MCP Tools Specification
|
||||||
version: 0.9.4
|
version: 0.9.8
|
||||||
description: >-
|
description: >-
|
||||||
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
|
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
|
||||||
servers:
|
servers:
|
||||||
|
|||||||
@@ -27,9 +27,36 @@ list:
|
|||||||
- name: state
|
- name: state
|
||||||
in: query
|
in: query
|
||||||
required: false
|
required: false
|
||||||
description: 按审批/支付状态过滤(paid 已支付, approving 审批中, draft 草稿)
|
description: >-
|
||||||
|
按审批/支付状态过滤(paid 已支付, approving 审批中)。传 draft/草稿 时改用
|
||||||
|
「我发起」的 flows/my 草稿列表,因为草稿尚未进入台账索引。
|
||||||
schema:
|
schema:
|
||||||
type: string
|
type: string
|
||||||
|
- name: template
|
||||||
|
in: query
|
||||||
|
required: false
|
||||||
|
description: 草稿模式下按模板(表单规格)ID 过滤;版本化 ID 会剥离末尾哈希
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
- name: title
|
||||||
|
in: query
|
||||||
|
required: false
|
||||||
|
description: 草稿模式下按标题关键字过滤
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
- name: staff
|
||||||
|
in: query
|
||||||
|
required: false
|
||||||
|
description: 草稿模式下按提交人(员工 ID、工号或唯一姓名)过滤
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
- name: page
|
||||||
|
in: query
|
||||||
|
required: false
|
||||||
|
description: 页码,与 count 配合分页(从 1 开始)
|
||||||
|
schema:
|
||||||
|
type: integer
|
||||||
|
default: 1
|
||||||
- name: count
|
- name: count
|
||||||
in: query
|
in: query
|
||||||
required: false
|
required: false
|
||||||
|
|||||||
+39
-2
@@ -2,7 +2,7 @@
|
|||||||
"openapi": "3.1.0",
|
"openapi": "3.1.0",
|
||||||
"info": {
|
"info": {
|
||||||
"title": "hose-use API & MCP Tools Specification",
|
"title": "hose-use API & MCP Tools Specification",
|
||||||
"version": "0.9.4",
|
"version": "0.9.8",
|
||||||
"description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."
|
"description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."
|
||||||
},
|
},
|
||||||
"servers": [
|
"servers": [
|
||||||
@@ -662,11 +662,48 @@
|
|||||||
"name": "state",
|
"name": "state",
|
||||||
"in": "query",
|
"in": "query",
|
||||||
"required": false,
|
"required": false,
|
||||||
"description": "按审批/支付状态过滤(paid 已支付, approving 审批中, draft 草稿)",
|
"description": "按审批/支付状态过滤(paid 已支付, approving 审批中)。传 draft/草稿 时改用 「我发起」的 flows/my 草稿列表,因为草稿尚未进入台账索引。",
|
||||||
"schema": {
|
"schema": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"name": "template",
|
||||||
|
"in": "query",
|
||||||
|
"required": false,
|
||||||
|
"description": "草稿模式下按模板(表单规格)ID 过滤;版本化 ID 会剥离末尾哈希",
|
||||||
|
"schema": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "title",
|
||||||
|
"in": "query",
|
||||||
|
"required": false,
|
||||||
|
"description": "草稿模式下按标题关键字过滤",
|
||||||
|
"schema": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "staff",
|
||||||
|
"in": "query",
|
||||||
|
"required": false,
|
||||||
|
"description": "草稿模式下按提交人(员工 ID、工号或唯一姓名)过滤",
|
||||||
|
"schema": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "page",
|
||||||
|
"in": "query",
|
||||||
|
"required": false,
|
||||||
|
"description": "页码,与 count 配合分页(从 1 开始)",
|
||||||
|
"schema": {
|
||||||
|
"type": "integer",
|
||||||
|
"default": 1
|
||||||
|
}
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"name": "count",
|
"name": "count",
|
||||||
"in": "query",
|
"in": "query",
|
||||||
|
|||||||
@@ -14,7 +14,7 @@
|
|||||||
- `errors.ts`:`classifyCliError` 按 `EkbError` 子类与状态码映射退出码与恢复建议。
|
- `errors.ts`:`classifyCliError` 按 `EkbError` 子类与状态码映射退出码与恢复建议。
|
||||||
带结构化元数据的 `EkbError.details` 会保留在 JSON 错误中,例如工作流主保存已完成但元数据刷新失败时的 `remoteSaved` 和服务端版本;普通错误输出不变。
|
带结构化元数据的 `EkbError.details` 会保留在 JSON 错误中,例如工作流主保存已完成但元数据刷新失败时的 `remoteSaved` 和服务端版本;普通错误输出不变。
|
||||||
- `mutation.ts`:写操作统一防护(确认/dry-run 语义),边界由 `mutation-boundaries.test.ts` 强制。
|
- `mutation.ts`:写操作统一防护(确认/dry-run 语义),边界由 `mutation-boundaries.test.ts` 强制。
|
||||||
- `生产环境安全阻断 (Production Safeguard)`:对带副作用的敏感调试命令(如 `workflow test`),在正式生产企业 (`env === "prod"`) 执行时触发硬阻断,要求必须显式带上 `--force` 确认生产风险;自省命令(`corps list`、`corps current`、`context`、`probe`)显式输出环境标识,并提供 `corps tag` 标记与 `corps list --test/--prod` 筛选。
|
- `生产环境安全阻断 (Production Safeguard)`:对带副作用的敏感命令,在正式生产企业 (`env === "prod"`) 执行时触发硬阻断。`workflow test` 需显式带 `--force` 确认生产风险;`workflow nodes grant` 需显式带 `--allow-prod`,并继续遵守 `--dry-run`/`--yes` 两阶段确认。自省命令(`corps list`、`corps current`、`context`、`probe`)显式输出环境标识,并提供 `corps tag` 标记与 `corps list --test/--prod` 筛选。
|
||||||
- `helpers.ts`:横切运行时助手(`initCorpRuntime` / `requireSelectedCorp` / `getSessionClientForRuntime`)。
|
- `helpers.ts`:横切运行时助手(`initCorpRuntime` / `requireSelectedCorp` / `getSessionClientForRuntime`)。
|
||||||
- `service.ts`:常驻守护进程管理(安装/启停/状态)。
|
- `service.ts`:常驻守护进程管理(安装/启停/状态)。
|
||||||
- `help.ts`:帮助文本组织。
|
- `help.ts`:帮助文本组织。
|
||||||
|
|||||||
@@ -277,8 +277,10 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
|||||||
"lint-script": "静态检查 JavaScript / MVEL 脚本",
|
"lint-script": "静态检查 JavaScript / MVEL 脚本",
|
||||||
"eval-script": "在本地沙箱中模拟执行脚本",
|
"eval-script": "在本地沙箱中模拟执行脚本",
|
||||||
"webhook": "向工作流 Webhook 触发器发送测试数据 (别名: webhook-send)",
|
"webhook": "向工作流 Webhook 触发器发送测试数据 (别名: webhook-send)",
|
||||||
"link": "生成工作流设计器 (Piper) 免密直达链接 (包含特权警告)"
|
"link": "生成工作流设计器 (Piper) 免密直达链接 (包含特权警告)",
|
||||||
|
"outbound": "查询合思系统出站消息规则与投递日志 (list|logs)"
|
||||||
},
|
},
|
||||||
|
|
||||||
"options": [
|
"options": [
|
||||||
"--flow=<单号> 指定测试单据",
|
"--flow=<单号> 指定测试单据",
|
||||||
"--file=<workflow.json> 指定工作流快照",
|
"--file=<workflow.json> 指定工作流快照",
|
||||||
@@ -333,9 +335,13 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
|||||||
"webhook-send": "webhook",
|
"webhook-send": "webhook",
|
||||||
"webhooks": "webhook",
|
"webhooks": "webhook",
|
||||||
"url": "link",
|
"url": "link",
|
||||||
"web": "link"
|
"web": "link",
|
||||||
|
"outbounds": "outbound",
|
||||||
|
"outbound-message": "outbound"
|
||||||
},
|
},
|
||||||
flags: { ...flagList("all allow-prod allow-production auto-publish autoPublish compare detail diff empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite full has-error hasError in-place inPlace includeDetail is-test json none once publish snapshot v value-json valueJson verbose with-tasks withTasks timeline progress steps", "boolean"), ...flagList("a admin-key adminKey after app app-id appId b bill body c choose-serialization code code-file container count d data desc description display display-name displayName end-time endTime entity execution-logs field file filter flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId json-file keyword l label limit log logs mapping mapping-file max-jobs maxJobs n name node node-id nodeId nodes output output-file outputFile p page page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform platform-id platformId pwd q query record s sample sample-id sampleId seconds set size sleep-time sleepTime snapshot1 snapshot2 snapshotA snapshotB source start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type types value workflowId", "value") }
|
|
||||||
|
flags: { ...flagList("all allow-prod allow-production auto-publish autoPublish compare detail diff empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite full has-error hasError in-place inPlace includeDetail is-test json none once publish snapshot v value-json valueJson verbose with-tasks withTasks timeline progress steps", "boolean"), ...flagList("a admin-key adminKey after app app-id appId b bill body c choose-serialization code code-file container count d data desc description display display-name displayName end-time endTime entity execution-logs field file filter flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId json-file keyword l label limit log logs mapping mapping-file max-jobs maxJobs max-pages maxPages message-type n name node node-id nodeId nodes offset output output-file outputFile p page page-limit page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform platform-id platformId pwd q query record s sample sample-id sampleId seconds set size sleep-time sleepTime sn snapshot1 snapshot2 snapshotA snapshotB source start start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type types value workflowId", "value") }
|
||||||
|
|
||||||
},
|
},
|
||||||
"bill": {
|
"bill": {
|
||||||
"summary": "单据检索、表单规格诊断与审批动作",
|
"summary": "单据检索、表单规格诊断与审批动作",
|
||||||
@@ -370,6 +376,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
|||||||
"--dry-run 只预览审批动作",
|
"--dry-run 只预览审批动作",
|
||||||
"--yes/--confirm 确认执行审批动作",
|
"--yes/--confirm 确认执行审批动作",
|
||||||
"--comment=<原因> 驳回或评论内容",
|
"--comment=<原因> 驳回或评论内容",
|
||||||
|
"--state=draft/草稿 查询未提交草稿(数据源为 flows/my),支持 --template/--title/--staff/--page 过滤",
|
||||||
"trace 的 --no-invoice/--noInvoice/--basic 为兼容空操作;穿透诊断本身不补充加载发票详情"
|
"trace 的 --no-invoice/--noInvoice/--basic 为兼容空操作;穿透诊断本身不补充加载发票详情"
|
||||||
],
|
],
|
||||||
"aliases": [
|
"aliases": [
|
||||||
@@ -409,7 +416,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
|||||||
"url": "link",
|
"url": "link",
|
||||||
"specification": "spec"
|
"specification": "spec"
|
||||||
},
|
},
|
||||||
flags: { ...flagList("all audit basic confirm distinct drop-attachments dropAttachments force-write keep-it-secret mine my no-invoice noInvoice private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target template title to amount reason fee-type feeType", "value") }
|
flags: { ...flagList("all audit basic confirm distinct drop-attachments dropAttachments force-write keep-it-secret mine my no-invoice noInvoice private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir page participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target template title to amount reason fee-type feeType", "value") }
|
||||||
},
|
},
|
||||||
"flow": {
|
"flow": {
|
||||||
"summary": "审批流全域透视与穿透诊断",
|
"summary": "审批流全域透视与穿透诊断",
|
||||||
@@ -441,7 +448,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
|||||||
"show": "get",
|
"show": "get",
|
||||||
"find": "get"
|
"find": "get"
|
||||||
},
|
},
|
||||||
flags: { ...flagList("audit basic confirm distinct force-write keep-it-secret mine my no-invoice noInvoice private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target to", "value") }
|
flags: { ...flagList("audit basic confirm distinct force-write keep-it-secret mine my no-invoice noInvoice private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir page participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target to", "value") }
|
||||||
},
|
},
|
||||||
"contact": {
|
"contact": {
|
||||||
"summary": "企业通讯录与人员检索",
|
"summary": "企业通讯录与人员检索",
|
||||||
@@ -898,6 +905,41 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
|||||||
...flagList("all a logout admin save import persist switch current overwrite candidates list-candidates qr check", "boolean"),
|
...flagList("all a logout admin save import persist switch current overwrite candidates list-candidates qr check", "boolean"),
|
||||||
...flagList("status", "boolean-or-value")
|
...flagList("status", "boolean-or-value")
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"docs": {
|
||||||
|
"summary": "合思开放平台官方接口文档与端点规范检索",
|
||||||
|
"usage": "hose-use docs <search|show|categories|sync> [关键词|路径] [--json]",
|
||||||
|
"commands": {
|
||||||
|
"search": "按关键词、分类或方法检索开放平台 HTTP 接口",
|
||||||
|
"show": "查看指定接口的完整规范、参数定义、CURL 与响应示例",
|
||||||
|
"categories": "查看开放平台所有业务模块分类与端点统计",
|
||||||
|
"sync": "强制与线上文档中心全量同步最新索引"
|
||||||
|
},
|
||||||
|
"aliases": [
|
||||||
|
"doc",
|
||||||
|
"api-doc",
|
||||||
|
"api-docs"
|
||||||
|
],
|
||||||
|
"commandAliases": {
|
||||||
|
"find": "search",
|
||||||
|
"list": "search",
|
||||||
|
"ls": "search",
|
||||||
|
"get": "show",
|
||||||
|
"info": "show",
|
||||||
|
"cat": "show",
|
||||||
|
"read": "show",
|
||||||
|
"detail": "show",
|
||||||
|
"category": "categories",
|
||||||
|
"cats": "categories",
|
||||||
|
"modules": "categories",
|
||||||
|
"groups": "categories",
|
||||||
|
"update": "sync",
|
||||||
|
"refresh": "sync"
|
||||||
|
},
|
||||||
|
flags: {
|
||||||
|
...flagList("keyword query q category cat module method m path p target id name url limit count n", "value"),
|
||||||
|
...flagList("refresh sync force", "boolean")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { createSessionClient } from "../../../core/http/session-client.js";
|
import { createSessionClient } from "../../../core/http/hose-web-session-client.js";
|
||||||
import {
|
import {
|
||||||
approveAssistTicket,
|
approveAssistTicket,
|
||||||
listAssistTickets,
|
listAssistTickets,
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ import {
|
|||||||
getActiveAccount,
|
getActiveAccount,
|
||||||
setActiveAccount,
|
setActiveAccount,
|
||||||
} from "../../core/auth/account-store.js";
|
} from "../../core/auth/account-store.js";
|
||||||
import { createSessionClient } from "../../core/http/session-client.js";
|
import { createSessionClient } from "../../core/http/hose-web-session-client.js";
|
||||||
import { stringOption, booleanOption } from "../parser.js";
|
import { stringOption, booleanOption } from "../parser.js";
|
||||||
import { printJson, printKeyValue, printTable, formatSourceLabel, formatExpiresAt } from "../printer.js";
|
import { printJson, printKeyValue, printTable, formatSourceLabel, formatExpiresAt } from "../printer.js";
|
||||||
import { prompt } from "../helpers.js";
|
import { prompt } from "../helpers.js";
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { createSessionClient } from "../../../core/http/session-client.js";
|
import { createSessionClient } from "../../../core/http/hose-web-session-client.js";
|
||||||
import { resolveBillStaffIds } from "../../../domains/bill/tools.js";
|
import { resolveBillStaffIds } from "../../../domains/bill/tools.js";
|
||||||
import { booleanOption, stringOption } from "../../parser.js";
|
import { booleanOption, stringOption } from "../../parser.js";
|
||||||
import { isDryRun, requireMutationConfirmation } from "../../mutation.js";
|
import { isDryRun, requireMutationConfirmation } from "../../mutation.js";
|
||||||
|
|||||||
@@ -0,0 +1,106 @@
|
|||||||
|
import { afterEach, describe, expect, it, spyOn } from "bun:test";
|
||||||
|
import * as session from "../../../core/http/hose-web-session-client.js";
|
||||||
|
import { parseArgs } from "../../parser.js";
|
||||||
|
import { createBillActionContext } from "./context.js";
|
||||||
|
import { handleList } from "./search.js";
|
||||||
|
|
||||||
|
const spies: Array<{ mockRestore(): void }> = [];
|
||||||
|
afterEach(() => {
|
||||||
|
for (const spy of spies.splice(0).reverse()) spy.mockRestore();
|
||||||
|
});
|
||||||
|
|
||||||
|
function json(value: unknown): Response {
|
||||||
|
return new Response(JSON.stringify(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
function draftClient(corpId: string) {
|
||||||
|
const flowsPosts: any[] = [];
|
||||||
|
const client = {
|
||||||
|
get: async (url: string) => {
|
||||||
|
if (url.includes("staffs/actives")) {
|
||||||
|
return json({ items: [{ id: "staff-1", name: "张三", code: "1001" }] });
|
||||||
|
}
|
||||||
|
return json({});
|
||||||
|
},
|
||||||
|
post: async (url: string, payload: any) => {
|
||||||
|
if (url.includes("datalink/entity/search")) return json({ items: [] });
|
||||||
|
if (url.endsWith("/flows/my")) {
|
||||||
|
flowsPosts.push({ url, payload, corpId });
|
||||||
|
return json({
|
||||||
|
count: 1,
|
||||||
|
items: [{
|
||||||
|
flow: {
|
||||||
|
id: "flow-cli-draft",
|
||||||
|
state: "draft",
|
||||||
|
formType: "payment",
|
||||||
|
createTime: 1781682826000,
|
||||||
|
updateTime: 1781682870000,
|
||||||
|
},
|
||||||
|
form: {
|
||||||
|
code: "FK26000009",
|
||||||
|
title: "付款草稿CLI",
|
||||||
|
specificationId: { id: "spec-pay", name: "对公付款单" },
|
||||||
|
submitterId: { id: "staff-1", name: "张三", code: "1001" },
|
||||||
|
payMoney: { standard: "10.00", standardSymbol: "¥", standardStrCode: "CNY" },
|
||||||
|
},
|
||||||
|
}],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return json({});
|
||||||
|
},
|
||||||
|
};
|
||||||
|
return { client, flowsPosts };
|
||||||
|
}
|
||||||
|
|
||||||
|
function context(args: string[], corpId: string, jsonMode: boolean) {
|
||||||
|
const corp = { id: corpId, name: "测试企业", credentials: { corpId } };
|
||||||
|
return createBillActionContext(parseArgs(args), { jsonMode, selectedCorp: corp } as any);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("bill list draft mode", () => {
|
||||||
|
it("routes --state=draft to flows/my with template, title, submitter and page filters", async () => {
|
||||||
|
const { client, flowsPosts } = draftClient("cli-draft-corp-json");
|
||||||
|
spies.push(spyOn(session, "createSessionClient").mockResolvedValue(client as any));
|
||||||
|
|
||||||
|
const args = [
|
||||||
|
"bill", "list", "--state=draft", "--mine",
|
||||||
|
`--template=spec-pay:${"a".repeat(32)}`,
|
||||||
|
"--title=付款", "--staff=张三",
|
||||||
|
"--page=2", "--count=10", "--json",
|
||||||
|
];
|
||||||
|
const result = await handleList(context(args, "cli-draft-corp-json", true));
|
||||||
|
|
||||||
|
expect(result.exitCode).toBe(0);
|
||||||
|
const output = JSON.parse(result.stdout);
|
||||||
|
expect(output.total).toBe(1);
|
||||||
|
expect(output.items[0]).toMatchObject({
|
||||||
|
billId: "flow-cli-draft",
|
||||||
|
billCode: "FK26000009",
|
||||||
|
billName: "付款草稿CLI",
|
||||||
|
state: "draft",
|
||||||
|
});
|
||||||
|
expect(output.items[0].amount).toContain("10.00");
|
||||||
|
|
||||||
|
expect(flowsPosts).toHaveLength(1);
|
||||||
|
const filterBy = flowsPosts[0].payload.json.filterBy as string;
|
||||||
|
expect(filterBy).toContain('(state.in("draft"))');
|
||||||
|
expect(filterBy).toContain('INSTR(form.title, "付款")');
|
||||||
|
expect(filterBy).toContain('INSTR(form.specificationId, "spec-pay")');
|
||||||
|
expect(filterBy).not.toContain("a".repeat(32));
|
||||||
|
expect(filterBy).toContain('INSTR(form.submitterId, "staff-1")');
|
||||||
|
expect(flowsPosts[0].payload.json.limit).toEqual({ start: 10, count: 10 });
|
||||||
|
expect(flowsPosts[0].payload.json.orderBy).toEqual([{ value: "createTime", order: "DESC" }]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("renders a draft-specific text header for --state=草稿", async () => {
|
||||||
|
const { client } = draftClient("cli-draft-corp-text");
|
||||||
|
spies.push(spyOn(session, "createSessionClient").mockResolvedValue(client as any));
|
||||||
|
|
||||||
|
const result = await handleList(context(["bill", "list", "--state=草稿"], "cli-draft-corp-text", false));
|
||||||
|
|
||||||
|
expect(result.exitCode).toBe(0);
|
||||||
|
expect(result.stdout).toContain("单据草稿列表");
|
||||||
|
expect(result.stdout).toContain("FK26000009");
|
||||||
|
expect(result.stdout).toContain("bill submit");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,4 +1,10 @@
|
|||||||
import { getBillByCodeOrId, getBillRisk, searchAndFormatBills, traceBillFlowDetail } from "../../../domains/bill/tools.js";
|
import {
|
||||||
|
getBillByCodeOrId,
|
||||||
|
getBillRisk,
|
||||||
|
searchAndFormatBills,
|
||||||
|
searchAndFormatDraftBills,
|
||||||
|
traceBillFlowDetail,
|
||||||
|
} from "../../../domains/bill/tools.js";
|
||||||
import { booleanOption, numberOption, stringOption } from "../../parser.js";
|
import { booleanOption, numberOption, stringOption } from "../../parser.js";
|
||||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||||
import type { CliResult } from "../../types.js";
|
import type { CliResult } from "../../types.js";
|
||||||
@@ -6,8 +12,10 @@ import type { BillActionContext } from "./context.js";
|
|||||||
|
|
||||||
export async function handleList(ctx: BillActionContext): Promise<CliResult> {
|
export async function handleList(ctx: BillActionContext): Promise<CliResult> {
|
||||||
const { parsed, runtime, corp, corpId } = ctx;
|
const { parsed, runtime, corp, corpId } = ctx;
|
||||||
|
const state = stringOption(parsed.options, ["state", "s"]);
|
||||||
|
const isDraft = state ? /^(draft|草稿)$/i.test(state.trim()) : false;
|
||||||
const mine = booleanOption(parsed.options, ["mine", "my", "self"]);
|
const mine = booleanOption(parsed.options, ["mine", "my", "self"]);
|
||||||
if (mine) {
|
if (mine && !isDraft) {
|
||||||
const { handleTaskCommand } = await import("./../task.js");
|
const { handleTaskCommand } = await import("./../task.js");
|
||||||
return handleTaskCommand(
|
return handleTaskCommand(
|
||||||
{
|
{
|
||||||
@@ -23,8 +31,9 @@ export async function handleList(ctx: BillActionContext): Promise<CliResult> {
|
|||||||
const keyword = stringOption(parsed.options, ["keyword", "k", "q", "query"]);
|
const keyword = stringOption(parsed.options, ["keyword", "k", "q", "query"]);
|
||||||
const searchFields = stringOption(parsed.options, ["search-fields", "searchFields", "search-field", "sf"]);
|
const searchFields = stringOption(parsed.options, ["search-fields", "searchFields", "search-field", "sf"]);
|
||||||
const stage = stringOption(parsed.options, ["stage"]);
|
const stage = stringOption(parsed.options, ["stage"]);
|
||||||
const state = stringOption(parsed.options, ["state", "s"]);
|
const count = numberOption(parsed.options, ["count", "limit", "n"], 20) ?? 20;
|
||||||
const count = numberOption(parsed.options, ["count", "limit", "n"], 20);
|
const page = Math.max(1, numberOption(parsed.options, ["page"], 1) ?? 1);
|
||||||
|
const start = (page - 1) * count;
|
||||||
const since = stringOption(parsed.options, ["since", "days", "d"]);
|
const since = stringOption(parsed.options, ["since", "days", "d"]);
|
||||||
const startDate = stringOption(parsed.options, ["start-date", "startDate", "from", "start"]);
|
const startDate = stringOption(parsed.options, ["start-date", "startDate", "from", "start"]);
|
||||||
const endDate = stringOption(parsed.options, ["end-date", "endDate", "to", "end"]);
|
const endDate = stringOption(parsed.options, ["end-date", "endDate", "to", "end"]);
|
||||||
@@ -34,21 +43,54 @@ export async function handleList(ctx: BillActionContext): Promise<CliResult> {
|
|||||||
const select = stringOption(parsed.options, ["select", "fields"]);
|
const select = stringOption(parsed.options, ["select", "fields"]);
|
||||||
const distinct = booleanOption(parsed.options, ["distinct"]);
|
const distinct = booleanOption(parsed.options, ["distinct"]);
|
||||||
|
|
||||||
const result = await searchAndFormatBills(await ctx.getClient(), corpId, {
|
const title = stringOption(parsed.options, ["title"]);
|
||||||
code,
|
const rawTemplate = stringOption(parsed.options, [
|
||||||
keyword,
|
"template",
|
||||||
searchFields,
|
"spec",
|
||||||
stage,
|
"specification",
|
||||||
state,
|
"specification-id",
|
||||||
count,
|
"specificationId",
|
||||||
since,
|
]);
|
||||||
startDate,
|
const templateId = rawTemplate
|
||||||
endDate,
|
? rawTemplate
|
||||||
order,
|
.trim()
|
||||||
filterBy,
|
.replace(/^\[|\]$/g, "")
|
||||||
select,
|
.replace(/:[0-9a-f]{32,64}$/i, "")
|
||||||
distinct,
|
: undefined;
|
||||||
});
|
const staffValues = ctx.listOption(["staff", "staff-id"]);
|
||||||
|
const submitterIds =
|
||||||
|
isDraft && staffValues?.length ? await ctx.resolveApproverIds(staffValues) : undefined;
|
||||||
|
|
||||||
|
const result = isDraft
|
||||||
|
? await searchAndFormatDraftBills(await ctx.getClient(), corpId, {
|
||||||
|
code,
|
||||||
|
keyword,
|
||||||
|
title,
|
||||||
|
templateId,
|
||||||
|
submitterIds,
|
||||||
|
start,
|
||||||
|
count,
|
||||||
|
since,
|
||||||
|
startDate,
|
||||||
|
endDate,
|
||||||
|
order,
|
||||||
|
})
|
||||||
|
: await searchAndFormatBills(await ctx.getClient(), corpId, {
|
||||||
|
code,
|
||||||
|
keyword,
|
||||||
|
searchFields,
|
||||||
|
stage,
|
||||||
|
state,
|
||||||
|
start,
|
||||||
|
count,
|
||||||
|
since,
|
||||||
|
startDate,
|
||||||
|
endDate,
|
||||||
|
order,
|
||||||
|
filterBy,
|
||||||
|
select,
|
||||||
|
distinct,
|
||||||
|
});
|
||||||
|
|
||||||
if (runtime.jsonMode) {
|
if (runtime.jsonMode) {
|
||||||
return {
|
return {
|
||||||
@@ -67,7 +109,7 @@ export async function handleList(ctx: BillActionContext): Promise<CliResult> {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const headers = ["#", "单据编号 (单号)", "单据名称", "阶段", "状态", "金额", "提交时间"];
|
const headers = ["#", "单据编号 (单号)", "单据名称", "阶段", "状态", "金额", isDraft ? "创建时间" : "提交时间"];
|
||||||
const rows = result.items.map((b, idx) => [
|
const rows = result.items.map((b, idx) => [
|
||||||
idx + 1,
|
idx + 1,
|
||||||
b.billCode,
|
b.billCode,
|
||||||
@@ -75,7 +117,7 @@ export async function handleList(ctx: BillActionContext): Promise<CliResult> {
|
|||||||
b.stage || "-",
|
b.stage || "-",
|
||||||
b.state || "-",
|
b.state || "-",
|
||||||
b.amount || "-",
|
b.amount || "-",
|
||||||
b.submitDate || b.createTime || "-",
|
isDraft ? b.createTime || b.submitDate || "-" : b.submitDate || b.createTime || "-",
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const filterSummary: string[] = [];
|
const filterSummary: string[] = [];
|
||||||
@@ -87,14 +129,23 @@ export async function handleList(ctx: BillActionContext): Promise<CliResult> {
|
|||||||
}
|
}
|
||||||
if (stage) filterSummary.push(`阶段: ${stage}`);
|
if (stage) filterSummary.push(`阶段: ${stage}`);
|
||||||
if (state) filterSummary.push(`状态: ${state}`);
|
if (state) filterSummary.push(`状态: ${state}`);
|
||||||
|
if (isDraft) {
|
||||||
|
if (templateId) filterSummary.push(`模板: ${templateId}`);
|
||||||
|
if (title) filterSummary.push(`标题: ${title}`);
|
||||||
|
if (staffValues?.length) filterSummary.push(`提交人: ${staffValues.join(", ")}`);
|
||||||
|
if (page > 1) filterSummary.push(`第 ${page} 页`);
|
||||||
|
}
|
||||||
const filterTag = filterSummary.length > 0 ? ` | 筛选: ${filterSummary.join(", ")}` : "";
|
const filterTag = filterSummary.length > 0 ? ` | 筛选: ${filterSummary.join(", ")}` : "";
|
||||||
|
|
||||||
const tableOutput = printTable(headers, rows);
|
const tableOutput = printTable(headers, rows);
|
||||||
const title = `====== 单据与费用明细列表 (企业: ${corp.name}${filterTag} | 匹配总数: ${result.total} | 本次返回: ${result.returned}) ======\n`;
|
const listLabel = isDraft ? "单据草稿列表" : "单据与费用明细列表";
|
||||||
const tip = `\n提示: 运行 hose-use bill get <单号> 查看表单结构化详情与发票明细\n`;
|
const titleLine = `====== ${listLabel} (企业: ${corp.name}${filterTag} | 匹配总数: ${result.total} | 本次返回: ${result.returned}) ======\n`;
|
||||||
|
const tip = isDraft
|
||||||
|
? `\n提示: 运行 hose-use bill get <单号|flowId> 查看草稿详情;提交使用 hose-use bill submit <单号|flowId> --yes\n`
|
||||||
|
: `\n提示: 运行 hose-use bill get <单号> 查看表单结构化详情与发票明细\n`;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
stdout: title + tableOutput + tip,
|
stdout: titleLine + tableOutput + tip,
|
||||||
stderr: "",
|
stderr: "",
|
||||||
exitCode: 0,
|
exitCode: 0,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import {
|
|||||||
getEnterprisesDirCandidates,
|
getEnterprisesDirCandidates,
|
||||||
} from "../../core/config/loader.js";
|
} from "../../core/config/loader.js";
|
||||||
import { ApprovalRepository } from "../../domains/approval/index.js";
|
import { ApprovalRepository } from "../../domains/approval/index.js";
|
||||||
|
import { getDocsCatalog } from "../../domains/docs/tools.js";
|
||||||
import { VERSION } from "../../version.js";
|
import { VERSION } from "../../version.js";
|
||||||
import { formatExpiresAt, formatSourceLabel, formatCorpEnvLabel, printJson } from "../printer.js";
|
import { formatExpiresAt, formatSourceLabel, formatCorpEnvLabel, printJson } from "../printer.js";
|
||||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||||
@@ -53,6 +54,18 @@ export async function handleContextCommand(
|
|||||||
// 容错处理(如 SQLite 尚未初始化等场景)
|
// 容错处理(如 SQLite 尚未初始化等场景)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let docsStats = { totalDocs: 0, totalEndpoints: 0, ready: false };
|
||||||
|
try {
|
||||||
|
const catalog = await getDocsCatalog();
|
||||||
|
docsStats = {
|
||||||
|
totalDocs: catalog.totalDocs,
|
||||||
|
totalEndpoints: catalog.totalEndpoints,
|
||||||
|
ready: true,
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
// 容错处理
|
||||||
|
}
|
||||||
|
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
const validCorps = allCorps.filter((c) => c.persistent || !c.expiresAt || c.expiresAt > now);
|
const validCorps = allCorps.filter((c) => c.persistent || !c.expiresAt || c.expiresAt > now);
|
||||||
const expiredCorps = allCorps.filter((c) => !c.persistent && c.expiresAt && c.expiresAt <= now);
|
const expiredCorps = allCorps.filter((c) => !c.persistent && c.expiresAt && c.expiresAt <= now);
|
||||||
@@ -114,6 +127,7 @@ export async function handleContextCommand(
|
|||||||
pendingRunsCount,
|
pendingRunsCount,
|
||||||
totalRunsCount,
|
totalRunsCount,
|
||||||
},
|
},
|
||||||
|
docsCatalog: docsStats,
|
||||||
runtime: {
|
runtime: {
|
||||||
mode: isStateful ? "stateful" : "stateless",
|
mode: isStateful ? "stateful" : "stateless",
|
||||||
configFile,
|
configFile,
|
||||||
@@ -152,6 +166,7 @@ export async function handleContextCommand(
|
|||||||
` 凭证有效状态 : ${currentCorp ? formatExpiresAt(corpExpiresAt, currentPersistent, hasOpenApiPersistentCredentials(currentCorp) ? "openapi" : currentCorp.source) : "-"}`,
|
` 凭证有效状态 : ${currentCorp ? formatExpiresAt(corpExpiresAt, currentPersistent, hasOpenApiPersistentCredentials(currentCorp) ? "openapi" : currentCorp.source) : "-"}`,
|
||||||
` 主站 BaseURL : ${currentCorp?.baseUrl || "-"}`,
|
` 主站 BaseURL : ${currentCorp?.baseUrl || "-"}`,
|
||||||
` 已配置企业总数: ${allCorps.length} 家 (🏭 正式: ${prodCount} 家, 🧪 测试: ${testCount} 家, 🎪 演示: ${demoCount} 家)`,
|
` 已配置企业总数: ${allCorps.length} 家 (🏭 正式: ${prodCount} 家, 🧪 测试: ${testCount} 家, 🎪 演示: ${demoCount} 家)`,
|
||||||
|
` 开放平台接口库: ${docsStats.ready ? `已就绪 (${docsStats.totalDocs} 篇文档 / ${docsStats.totalEndpoints} 个端点,可用 hose-use docs search 检索)` : "未就绪"}`,
|
||||||
` AI PRO 规约库 : ${scopesStr}`,
|
` AI PRO 规约库 : ${scopesStr}`,
|
||||||
` AI PRO 待决断 : ${pendingRunsCount} 个待决断会话 (当前企业历史总会话: ${totalRunsCount} 个)`,
|
` AI PRO 待决断 : ${pendingRunsCount} 个待决断会话 (当前企业历史总会话: ${totalRunsCount} 个)`,
|
||||||
` 运行模式设置 : ${isStateful ? "有状态模式 (Stateful - 自动记忆当前企业)" : "无状态模式 (Stateless)"}`,
|
` 运行模式设置 : ${isStateful ? "有状态模式 (Stateful - 自动记忆当前企业)" : "无状态模式 (Stateless)"}`,
|
||||||
@@ -160,6 +175,7 @@ export async function handleContextCommand(
|
|||||||
"",
|
"",
|
||||||
"提示:",
|
"提示:",
|
||||||
" - hose-use 与 hose-aipro 默认共享同一套企业与身份凭证上下文,无须重复配置。",
|
" - hose-use 与 hose-aipro 默认共享同一套企业与身份凭证上下文,无须重复配置。",
|
||||||
|
" - 调研合思开放接口与参数规范: hose-use docs search <关键词> 或 hose-use docs show <Path>",
|
||||||
" - 切换全局默认企业: hose-use corps switch <企业ID>",
|
" - 切换全局默认企业: hose-use corps switch <企业ID>",
|
||||||
" - 单次临时指定企业: hose-use --corp=<企业ID> <命令> 或 hose-aipro --corp=<企业ID> <子命令>",
|
" - 单次临时指定企业: hose-use --corp=<企业ID> <命令> 或 hose-aipro --corp=<企业ID> <子命令>",
|
||||||
" - AI PRO 专属上下文: hose-aipro status",
|
" - AI PRO 专属上下文: hose-aipro status",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { describe, it, expect } from "bun:test";
|
import { describe, it, expect } from "bun:test";
|
||||||
import { parseHeadersOrCurl } from "../../core/auth/login.js";
|
import { parseHeadersOrCurl } from "../../core/auth/login.js";
|
||||||
import { resolveCorpCluster } from "../../core/http/unity-client.js";
|
import { resolveCorpCluster } from "../../core/http/unity-easo-client.js";
|
||||||
import { handleCorpsCommand } from "./corps/index.js";
|
import { handleCorpsCommand } from "./corps/index.js";
|
||||||
import type { CliRuntime } from "../types.js";
|
import type { CliRuntime } from "../types.js";
|
||||||
import type { CorpConfig } from "../../core/config/types.js";
|
import type { CorpConfig } from "../../core/config/types.js";
|
||||||
@@ -35,7 +35,7 @@ describe("core/auth/login > parseHeadersOrCurl & URL link parsing", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("core/http/unity-client > resolveCorpCluster", () => {
|
describe("core/http/unity-easo-client > resolveCorpCluster", () => {
|
||||||
it("prioritizes explicit cluster config", () => {
|
it("prioritizes explicit cluster config", () => {
|
||||||
expect(resolveCorpCluster({ cluster: "wx2", baseUrl: "https://app.ekuaibao.com" })).toBe("wx2");
|
expect(resolveCorpCluster({ cluster: "wx2", baseUrl: "https://app.ekuaibao.com" })).toBe("wx2");
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { loadCorpConfigs } from "../../../core/config/loader.js";
|
import { loadCorpConfigs } from "../../../core/config/loader.js";
|
||||||
import { createSessionClient } from "../../../core/http/session-client.js";
|
import { createSessionClient } from "../../../core/http/hose-web-session-client.js";
|
||||||
import { booleanOption, stringOption } from "../../parser.js";
|
import { booleanOption, stringOption } from "../../parser.js";
|
||||||
import { NotFoundError } from "../../../core/errors.js";
|
import { NotFoundError } from "../../../core/errors.js";
|
||||||
import { formatSourceLabel, printJson, printTable } from "../../printer.js";
|
import { formatSourceLabel, printJson, printTable } from "../../printer.js";
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||||
import { printJson, printTable } from "../printer.js";
|
import { printJson, printTable } from "../printer.js";
|
||||||
import { numberOption, stringOption } from "../parser.js";
|
import { numberOption, stringOption } from "../parser.js";
|
||||||
import { createSessionClient } from "../../core/http/session-client.js";
|
import { createSessionClient } from "../../core/http/hose-web-session-client.js";
|
||||||
import { searchDimensions, resolveDimension } from "../../domains/dimension/tools.js";
|
import { searchDimensions, resolveDimension } from "../../domains/dimension/tools.js";
|
||||||
|
|
||||||
export async function handleDimensionCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
export async function handleDimensionCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||||
|
|||||||
@@ -0,0 +1,80 @@
|
|||||||
|
import { describe, expect, test } from "bun:test";
|
||||||
|
import { runCli } from "../runner.js";
|
||||||
|
|
||||||
|
describe("CLI - 开放平台官方接口文档域 (docs / openapi-docs)", () => {
|
||||||
|
test("hose-use docs 输出开放平台文档概览与端点总数", async () => {
|
||||||
|
const res = await runCli(["docs"]);
|
||||||
|
expect(res.exitCode).toBe(0);
|
||||||
|
expect(res.stdout).toContain("合思开放平台官方文档中心");
|
||||||
|
expect(res.stdout).toContain("文档总数:");
|
||||||
|
expect(res.stdout).toContain("端点总数:");
|
||||||
|
expect(res.stdout).toContain("hose-use docs search");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("hose-use docs --json 输出概览结构化元数据", async () => {
|
||||||
|
const res = await runCli(["docs", "--json"]);
|
||||||
|
expect(res.exitCode).toBe(0);
|
||||||
|
const data = JSON.parse(res.stdout);
|
||||||
|
expect(data.totalDocs).toBeGreaterThan(100);
|
||||||
|
expect(data.totalEndpoints).toBeGreaterThan(100);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("hose-use docs search roleDefGroups 能检索出角色组接口", async () => {
|
||||||
|
const res = await runCli(["docs", "search", "roleDefGroups"]);
|
||||||
|
expect(res.exitCode).toBe(0);
|
||||||
|
expect(res.stdout).toContain("GET");
|
||||||
|
expect(res.stdout).toContain("/api/openapi/v1/roleDefGroups");
|
||||||
|
expect(res.stdout).toContain("查询角色组和角色");
|
||||||
|
expect(res.stdout).toContain("企业通讯录");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("hose-use docs search 角色组 --json 输出精准结构化搜索结果", async () => {
|
||||||
|
const res = await runCli(["docs", "search", "角色组", "--json"]);
|
||||||
|
expect(res.exitCode).toBe(0);
|
||||||
|
const data = JSON.parse(res.stdout);
|
||||||
|
expect(data.total).toBeGreaterThanOrEqual(1);
|
||||||
|
expect(data.items.some((i: any) => i.path === "/api/openapi/v1/roleDefGroups")).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("hose-use docs show /api/openapi/v1/roleDefGroups 展示完整接口规格与 CURL 示范", async () => {
|
||||||
|
const res = await runCli(["docs", "show", "/api/openapi/v1/roleDefGroups"]);
|
||||||
|
expect(res.exitCode).toBe(0);
|
||||||
|
expect(res.stdout).toContain("查询角色组和角色");
|
||||||
|
expect(res.stdout).toContain("GET");
|
||||||
|
expect(res.stdout).toContain("/api/openapi/v1/roleDefGroups");
|
||||||
|
expect(res.stdout).toContain("CURL 请求示范");
|
||||||
|
expect(res.stdout).toContain("成功响应示例");
|
||||||
|
expect(res.stdout).toContain("accessToken");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("hose-use docs show /api/openapi/v1/roleDefGroups --json 返回全量结构化文档项", async () => {
|
||||||
|
const res = await runCli(["docs", "show", "/api/openapi/v1/roleDefGroups", "--json"]);
|
||||||
|
expect(res.exitCode).toBe(0);
|
||||||
|
const doc = JSON.parse(res.stdout);
|
||||||
|
expect(doc.path).toBe("/api/openapi/v1/roleDefGroups");
|
||||||
|
expect(doc.method).toBe("GET");
|
||||||
|
expect(doc.category).toBe("企业通讯录");
|
||||||
|
expect(doc.permalink).toContain("get-roles-group");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("hose-use docs show 未知目标时返回友好错误", async () => {
|
||||||
|
const res = await runCli(["docs", "show", "non_existing_api_path_xyz"]);
|
||||||
|
expect(res.exitCode).toBe(1);
|
||||||
|
expect(res.stderr).toContain("NOT FOUND");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("hose-use docs categories 输出所有业务分类与端点分布", async () => {
|
||||||
|
const res = await runCli(["docs", "categories"]);
|
||||||
|
expect(res.exitCode).toBe(0);
|
||||||
|
expect(res.stdout).toContain("合思开放平台业务模块分类");
|
||||||
|
expect(res.stdout).toContain("企业通讯录");
|
||||||
|
expect(res.stdout).toContain("预算");
|
||||||
|
expect(res.stdout).toContain("单据");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("hose-use doc 别名也能正常调用", async () => {
|
||||||
|
const res = await runCli(["doc", "search", "roleDefGroups"]);
|
||||||
|
expect(res.exitCode).toBe(0);
|
||||||
|
expect(res.stdout).toContain("/api/openapi/v1/roleDefGroups");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,249 @@
|
|||||||
|
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||||
|
import { printJson, printKeyValue, printTable } from "../printer.js";
|
||||||
|
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||||
|
import {
|
||||||
|
getDocDetail,
|
||||||
|
getDocsCatalog,
|
||||||
|
listCategories,
|
||||||
|
searchDocs,
|
||||||
|
syncDocsCatalog,
|
||||||
|
} from "../../domains/docs/tools.js";
|
||||||
|
|
||||||
|
export async function handleDocsCommand(
|
||||||
|
parsed: CliParsedArgs,
|
||||||
|
runtime: CliRuntime
|
||||||
|
): Promise<CliResult> {
|
||||||
|
const action = parsed.action?.toLowerCase() || "";
|
||||||
|
const forceRefresh =
|
||||||
|
booleanOption(parsed.options, ["refresh", "force", "sync"]) ||
|
||||||
|
action === "sync";
|
||||||
|
|
||||||
|
// 1. 同步命令: hose-use docs sync
|
||||||
|
if (action === "sync") {
|
||||||
|
const res = await syncDocsCatalog();
|
||||||
|
if (runtime.jsonMode) {
|
||||||
|
return {
|
||||||
|
stdout: printJson(res, runtime.outputOptions),
|
||||||
|
stderr: "",
|
||||||
|
exitCode: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
stdout: `====== 开放平台文档同步完成 ======\n文档总数: ${res.totalDocs}\n接口端点: ${res.totalEndpoints}\n数据源: ${res.source}\n更新时间: ${res.updatedAt}\n`,
|
||||||
|
stderr: "",
|
||||||
|
exitCode: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 分类列表: hose-use docs categories
|
||||||
|
if (["categories", "category", "cats", "modules"].includes(action)) {
|
||||||
|
const cats = await listCategories({ forceRefresh });
|
||||||
|
if (runtime.jsonMode) {
|
||||||
|
return {
|
||||||
|
stdout: printJson({ count: cats.length, categories: cats }, runtime.outputOptions),
|
||||||
|
stderr: "",
|
||||||
|
exitCode: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const rows = cats.map((c, i) => [
|
||||||
|
i + 1,
|
||||||
|
c.name,
|
||||||
|
`${c.count} 篇`,
|
||||||
|
`${c.endpointsCount} 个`,
|
||||||
|
]);
|
||||||
|
const table = printTable(["#", "业务分类", "文档篇数", "HTTP 端点数"], rows);
|
||||||
|
return {
|
||||||
|
stdout: `====== 合思开放平台业务模块分类 (共 ${cats.length} 个) ======\n\n${table}\n\n提示: 运行 hose-use docs search --category=<模块名> 可查看该模块下的所有接口\n`,
|
||||||
|
stderr: "",
|
||||||
|
exitCode: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 详情命令: hose-use docs show <target>
|
||||||
|
if (["show", "get", "info", "cat", "read"].includes(action)) {
|
||||||
|
const target = parsed.args[0] || stringOption(parsed.options, ["path", "url", "id", "name", "target"]);
|
||||||
|
if (!target) {
|
||||||
|
throw new Error("请指定要查看的接口路径、文档 URL 或名称: hose-use docs show <接口或URL>");
|
||||||
|
}
|
||||||
|
|
||||||
|
const doc = await getDocDetail(target, { forceRefresh });
|
||||||
|
if (!doc) {
|
||||||
|
if (runtime.jsonMode) {
|
||||||
|
return {
|
||||||
|
stdout: printJson({ found: false, target }, runtime.outputOptions),
|
||||||
|
stderr: "",
|
||||||
|
exitCode: 1,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
stdout: "",
|
||||||
|
stderr: `[NOT FOUND] 未找到匹配的文档或接口: ${target}\n提示: 可以先运行 hose-use docs search ${target} 检索相近接口。\n`,
|
||||||
|
exitCode: 1,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (runtime.jsonMode) {
|
||||||
|
return {
|
||||||
|
stdout: printJson(doc, runtime.outputOptions),
|
||||||
|
stderr: "",
|
||||||
|
exitCode: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
let out = `====== ${doc.title} ======\n`;
|
||||||
|
out += printKeyValue({
|
||||||
|
"业务模块": doc.category,
|
||||||
|
"HTTP 方法": doc.method || "非端点/指南页面",
|
||||||
|
"接口路径": doc.path || "-",
|
||||||
|
"在线文档": doc.permalink,
|
||||||
|
"文档标识": `#${doc.id}`,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (doc.parameters) {
|
||||||
|
out += `\n\n### 参数规格与定义\n${doc.parameters}\n`;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (doc.curl) {
|
||||||
|
out += `\n### CURL 请求示范\n\`\`\`bash\n${doc.curl}\n\`\`\`\n`;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (doc.responseSample) {
|
||||||
|
out += `\n### 成功响应示例\n\`\`\`json\n${doc.responseSample}\n\`\`\`\n`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return { stdout: `${out}\n`, stderr: "", exitCode: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. 搜索命令 (默认行为): hose-use docs search <keyword> 或 hose-use docs <keyword>
|
||||||
|
const isSearchAction = ["search", "find", "list", "ls", ""].includes(action);
|
||||||
|
if (isSearchAction) {
|
||||||
|
const keyword =
|
||||||
|
(action === "search" || action === "find" ? parsed.args[0] : action || parsed.args[0]) ||
|
||||||
|
stringOption(parsed.options, ["keyword", "q", "query"]);
|
||||||
|
|
||||||
|
const category = stringOption(parsed.options, ["category", "cat", "module"]);
|
||||||
|
const method = stringOption(parsed.options, ["method", "m"]);
|
||||||
|
const path = stringOption(parsed.options, ["path", "p"]);
|
||||||
|
const limit = numberOption(parsed.options, ["limit", "n", "count"], 25);
|
||||||
|
|
||||||
|
// 如果没有任何搜索条件且没有关键词,展示全局概览
|
||||||
|
if (!keyword && !category && !method && !path && !action) {
|
||||||
|
const catalog = await getDocsCatalog({ forceRefresh });
|
||||||
|
if (runtime.jsonMode) {
|
||||||
|
return {
|
||||||
|
stdout: printJson(
|
||||||
|
{
|
||||||
|
totalDocs: catalog.totalDocs,
|
||||||
|
totalEndpoints: catalog.totalEndpoints,
|
||||||
|
sourceUrl: catalog.sourceUrl,
|
||||||
|
updatedAt: catalog.updatedAt,
|
||||||
|
},
|
||||||
|
runtime.outputOptions
|
||||||
|
),
|
||||||
|
stderr: "",
|
||||||
|
exitCode: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
stdout: `====== 合思开放平台官方文档中心 ======
|
||||||
|
文档总数: ${catalog.totalDocs} 篇
|
||||||
|
端点总数: ${catalog.totalEndpoints} 个
|
||||||
|
数据来源: ${catalog.sourceUrl}
|
||||||
|
更新时间: ${catalog.updatedAt}
|
||||||
|
|
||||||
|
常用子命令:
|
||||||
|
hose-use docs search <关键词> 检索开放平台 HTTP 接口与文档
|
||||||
|
hose-use docs show <路径|名称|URL> 查看单篇接口规格、参数表格与 CURL 响应
|
||||||
|
hose-use docs categories 查看 26+ 个业务分类及其端点数
|
||||||
|
hose-use docs sync 强制与线上最新文档中心全量同步
|
||||||
|
`,
|
||||||
|
stderr: "",
|
||||||
|
exitCode: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const searchRes = await searchDocs(
|
||||||
|
{
|
||||||
|
keyword,
|
||||||
|
category,
|
||||||
|
method,
|
||||||
|
path,
|
||||||
|
limit,
|
||||||
|
},
|
||||||
|
{ forceRefresh }
|
||||||
|
);
|
||||||
|
|
||||||
|
if (runtime.jsonMode) {
|
||||||
|
const summaryItems = searchRes.items.map((item) => ({
|
||||||
|
id: item.id,
|
||||||
|
title: item.title,
|
||||||
|
category: item.category,
|
||||||
|
method: item.method,
|
||||||
|
path: item.path,
|
||||||
|
url: item.url,
|
||||||
|
permalink: item.permalink,
|
||||||
|
matchReason: item.matchReason || undefined,
|
||||||
|
}));
|
||||||
|
return {
|
||||||
|
stdout: printJson(
|
||||||
|
{
|
||||||
|
total: searchRes.total,
|
||||||
|
count: summaryItems.length,
|
||||||
|
keyword: searchRes.keyword,
|
||||||
|
category: searchRes.category,
|
||||||
|
method: searchRes.method,
|
||||||
|
items: summaryItems,
|
||||||
|
},
|
||||||
|
runtime.outputOptions
|
||||||
|
),
|
||||||
|
stderr: "",
|
||||||
|
exitCode: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (searchRes.items.length === 0) {
|
||||||
|
return {
|
||||||
|
stdout: `未找到匹配的文档或接口 (关键词: ${keyword || "-"}, 分类: ${category || "-"}, 方法: ${method || "-"})\n`,
|
||||||
|
stderr: "",
|
||||||
|
exitCode: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const hasKeyword = Boolean(keyword);
|
||||||
|
const headers = hasKeyword
|
||||||
|
? ["Method", "Path / URL", "标题", "分类", "匹配依据"]
|
||||||
|
: ["Method", "Path / URL", "标题", "分类"];
|
||||||
|
|
||||||
|
const rows = searchRes.items.map((item) => {
|
||||||
|
const base = [
|
||||||
|
item.method || "DOC",
|
||||||
|
item.path || item.url,
|
||||||
|
item.title,
|
||||||
|
item.category,
|
||||||
|
];
|
||||||
|
if (hasKeyword) {
|
||||||
|
base.push(item.matchReason || "-");
|
||||||
|
}
|
||||||
|
return base;
|
||||||
|
});
|
||||||
|
|
||||||
|
const table = printTable(headers, rows);
|
||||||
|
const filterDesc = [
|
||||||
|
keyword ? `关键词: '${keyword}'` : "",
|
||||||
|
category ? `分类: '${category}'` : "",
|
||||||
|
method ? `方法: '${method}'` : "",
|
||||||
|
]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(", ");
|
||||||
|
|
||||||
|
return {
|
||||||
|
stdout: `====== 开放平台接口搜索结果 (找到 ${searchRes.total} 条${filterDesc ? ` | ${filterDesc}` : ""}) ======\n\n${table}\n\n提示: 运行 hose-use docs show <Path> 可查看对应接口的完整参数和 CURL 示范\n`,
|
||||||
|
stderr: "",
|
||||||
|
exitCode: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(
|
||||||
|
`未知的 docs 子命令: ${action}。支持: search <关键词>, show <路径|URL>, categories, sync`
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||||
import { printJson, printTable } from "../printer.js";
|
import { printJson, printTable } from "../printer.js";
|
||||||
import { booleanOption, stringOption } from "../parser.js";
|
import { booleanOption, stringOption } from "../parser.js";
|
||||||
import { createSessionClient } from "../../core/http/session-client.js";
|
import { createSessionClient } from "../../core/http/hose-web-session-client.js";
|
||||||
import {
|
import {
|
||||||
createFeeType,
|
createFeeType,
|
||||||
disableFeeTypeItem,
|
disableFeeTypeItem,
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { describe, expect, it, spyOn, afterEach } from "bun:test";
|
|||||||
import { handleFlowCommand } from "./flow.js";
|
import { handleFlowCommand } from "./flow.js";
|
||||||
import { handleBillCommand } from "./bill/index.js";
|
import { handleBillCommand } from "./bill/index.js";
|
||||||
import { findCommandByArea } from "../registry.js";
|
import { findCommandByArea } from "../registry.js";
|
||||||
import * as sessionModule from "../../core/http/session-client.js";
|
import * as sessionModule from "../../core/http/hose-web-session-client.js";
|
||||||
import type { CliRuntime } from "../types.js";
|
import type { CliRuntime } from "../types.js";
|
||||||
import type { CorpConfig } from "../../core/config/types.js";
|
import type { CorpConfig } from "../../core/config/types.js";
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||||
import { printJson, printTable } from "../printer.js";
|
import { printJson, printTable } from "../printer.js";
|
||||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||||
import { createSessionClient } from "../../core/http/session-client.js";
|
import { createSessionClient } from "../../core/http/hose-web-session-client.js";
|
||||||
import { filterMessages, listMessages, mergeMessages, readMessage } from "../../domains/message/tools.js";
|
import { filterMessages, listMessages, mergeMessages, readMessage } from "../../domains/message/tools.js";
|
||||||
import type { MessageItem } from "../../domains/message/types.js";
|
import type { MessageItem } from "../../domains/message/types.js";
|
||||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
|
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { printJson, printTable } from "../printer.js";
|
import { printJson, printTable } from "../printer.js";
|
||||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||||
import { createSessionClient } from "../../core/http/session-client.js";
|
import { createSessionClient } from "../../core/http/hose-web-session-client.js";
|
||||||
import { getPermissions } from "../../domains/permission/tools.js";
|
import { getPermissions } from "../../domains/permission/tools.js";
|
||||||
|
|
||||||
export async function handlePermissionCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
export async function handlePermissionCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||||
|
|||||||
@@ -528,6 +528,33 @@ describe("CLI - platform 命令与 record 动作", () => {
|
|||||||
).rejects.toThrow("--all 不再直接返回全量");
|
).rejects.toThrow("--all 不再直接返回全量");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("platform records --all --json 返回 DATASET_TOO_LARGE 结构化错误", async () => {
|
||||||
|
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||||
|
spies.push(spyOn(servicesApplications, "resolvePlatform").mockResolvedValue(mockPlatform as any));
|
||||||
|
spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any));
|
||||||
|
const result = await handlePlatformCommand(
|
||||||
|
{
|
||||||
|
area: "platform",
|
||||||
|
action: "records",
|
||||||
|
args: ["platform-1", "entity-1"],
|
||||||
|
options: { all: true, json: true },
|
||||||
|
raw: ["platform", "records", "platform-1", "entity-1", "--all", "--json"],
|
||||||
|
},
|
||||||
|
{ ...dummyRuntime, jsonMode: true }
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(result.exitCode).toBe(2);
|
||||||
|
const parsed = JSON.parse(result.stdout);
|
||||||
|
expect(parsed.error).toBe(true);
|
||||||
|
expect(parsed.code).toBe("DATASET_TOO_LARGE");
|
||||||
|
expect(parsed.exitCode).toBe(2);
|
||||||
|
expect(parsed.nextAction).toContain("--ndjson");
|
||||||
|
expect(parsed.suggestions).toEqual([
|
||||||
|
{ type: "paginate", command: "--page=1 --pageSize=500" },
|
||||||
|
{ type: "stream_export", command: "--ndjson --output-file=<path>" },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
it("rejects malformed batch predicates before fetching all records or calling the writer", async () => {
|
it("rejects malformed batch predicates before fetching all records or calling the writer", async () => {
|
||||||
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||||
spies.push(spyOn(servicesApplications, "resolvePlatform").mockResolvedValue(mockPlatform as any));
|
spies.push(spyOn(servicesApplications, "resolvePlatform").mockResolvedValue(mockPlatform as any));
|
||||||
@@ -572,5 +599,85 @@ describe("CLI - platform 命令与 record 动作", () => {
|
|||||||
expect(jsRes.stdout).toContain('const ENTITY_ID = "E_contract";');
|
expect(jsRes.stdout).toContain('const ENTITY_ID = "E_contract";');
|
||||||
expect(jsRes.stdout).toContain('"合同名称": FIELD_PREFIX + "name"');
|
expect(jsRes.stdout).toContain('"合同名称": FIELD_PREFIX + "name"');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("platform records 支持仅传单参数业务对象名称,全局反查其所属应用", async () => {
|
||||||
|
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||||
|
// 按应用名称查未找到
|
||||||
|
spies.push(spyOn(servicesApplications, "resolvePlatform").mockResolvedValue(undefined));
|
||||||
|
// 列出所有平台
|
||||||
|
spies.push(spyOn(servicesApplications, "listPlatforms").mockResolvedValue([
|
||||||
|
{ id: "platform-lease", name: "租赁摊销业务" } as any,
|
||||||
|
{ id: "platform-other", name: "其他应用" } as any,
|
||||||
|
]));
|
||||||
|
// 模拟应用详情与对象列表
|
||||||
|
spies.push(spyOn(servicesApplications, "getPlatform").mockResolvedValue({
|
||||||
|
id: "platform-lease",
|
||||||
|
name: "租赁摊销业务",
|
||||||
|
} as any));
|
||||||
|
spies.push(spyOn(services, "listPlatformEntities").mockImplementation(async (_, __, platformId) => {
|
||||||
|
if (platformId === "platform-lease") {
|
||||||
|
return [
|
||||||
|
{ id: "ent-track", name: "付款发票跟踪", code: "TRACK", fields: [{ name: "name", label: "名称", type: "text" }] } as any,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
return [];
|
||||||
|
}));
|
||||||
|
spies.push(spyOn(api, "searchEntityRecords").mockResolvedValue({
|
||||||
|
total: 1,
|
||||||
|
data: [
|
||||||
|
{
|
||||||
|
id: "rec-1",
|
||||||
|
dataLink: { id: "rec-1", name: "记录1", code: "R1", active: true, updateTime: "2026-10-22" },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
actions: [],
|
||||||
|
components: [],
|
||||||
|
path: null,
|
||||||
|
template: null,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const res = await handlePlatformCommand(
|
||||||
|
{ area: "platform", action: "records", args: ["付款发票跟踪"], options: { count: 1 }, raw: [] },
|
||||||
|
dummyRuntime
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(res.exitCode).toBe(0);
|
||||||
|
expect(res.stdout).toContain("记录1");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("platform records 单参数业务对象在多个应用重名时抛出明确指导错误", async () => {
|
||||||
|
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||||
|
spies.push(spyOn(servicesApplications, "resolvePlatform").mockResolvedValue(undefined));
|
||||||
|
spies.push(spyOn(servicesApplications, "listPlatforms").mockResolvedValue([
|
||||||
|
{ id: "app-1", name: "应用一" } as any,
|
||||||
|
{ id: "app-2", name: "应用二" } as any,
|
||||||
|
]));
|
||||||
|
spies.push(spyOn(services, "listPlatformEntities").mockImplementation(async (_, __, platformId) => {
|
||||||
|
return [{ id: `ent-${platformId}`, name: "重名对象", code: "DUP" } as any];
|
||||||
|
}));
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
handlePlatformCommand(
|
||||||
|
{ area: "platform", action: "records", args: ["重名对象"], options: {}, raw: [] },
|
||||||
|
dummyRuntime
|
||||||
|
)
|
||||||
|
).rejects.toThrow("在多个自建应用中找到同名业务对象 [重名对象],请显式指定应用名称");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("platform records 单参数既不是应用也不是业务对象时返回明确 NOT FOUND 错误", async () => {
|
||||||
|
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||||
|
spies.push(spyOn(servicesApplications, "resolvePlatform").mockResolvedValue(undefined));
|
||||||
|
spies.push(spyOn(servicesApplications, "listPlatforms").mockResolvedValue([
|
||||||
|
{ id: "app-1", name: "应用一" } as any,
|
||||||
|
]));
|
||||||
|
spies.push(spyOn(services, "listPlatformEntities").mockResolvedValue([]));
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
handlePlatformCommand(
|
||||||
|
{ area: "platform", action: "records", args: ["未知目标"], options: {}, raw: [] },
|
||||||
|
dummyRuntime
|
||||||
|
)
|
||||||
|
).rejects.toThrow("[NOT FOUND] 当前企业下未找到名为 [未知目标] 的自建应用或业务对象");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -63,9 +63,27 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
|
|||||||
// 全量 JSON/表格很容易把几十万条记录倒进 stdout 或内存;全量导出必须显式走文件流。
|
// 全量 JSON/表格很容易把几十万条记录倒进 stdout 或内存;全量导出必须显式走文件流。
|
||||||
if (isAll && !isProfileStats && !sumOption) {
|
if (isAll && !isProfileStats && !sumOption) {
|
||||||
if (!isStream || !runtime.outputOptions?.outputFile) {
|
if (!isStream || !runtime.outputOptions?.outputFile) {
|
||||||
throw usageError(
|
const message =
|
||||||
"--all 不再直接返回全量 JSON/表格。请使用 --page/--count 分页查询,或使用 --ndjson --output-file <path> 流式导出;大范围检索建议交给脚本处理。"
|
"--all 不再直接返回全量 JSON/表格。请使用 --page/--count 分页查询,或使用 --ndjson --output-file <path> 流式导出;大范围检索建议交给脚本处理。";
|
||||||
);
|
const nextAction = "hose-use platform records <应用> <业务对象> --ndjson --output-file <path>";
|
||||||
|
if (runtime.jsonMode) {
|
||||||
|
return {
|
||||||
|
stdout: JSON.stringify({
|
||||||
|
error: true,
|
||||||
|
code: "DATASET_TOO_LARGE",
|
||||||
|
message,
|
||||||
|
exitCode: 2,
|
||||||
|
nextAction,
|
||||||
|
suggestions: [
|
||||||
|
{ type: "paginate", command: "--page=1 --pageSize=500" },
|
||||||
|
{ type: "stream_export", command: "--ndjson --output-file=<path>" },
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
stderr: "",
|
||||||
|
exitCode: 2,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
throw usageError(message, nextAction);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -243,8 +261,8 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
|
|||||||
};
|
};
|
||||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
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 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 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 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 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 id = source.id ?? item.id;
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
import { resolveEntity } from "../../../domains/platform/datalink/services.js";
|
import type { KyInstance } from "ky";
|
||||||
import { resolvePlatform } from "../../../domains/platform/applications/services.js";
|
import { listPlatformEntities, resolveEntity } from "../../../domains/platform/datalink/services.js";
|
||||||
|
import { getPlatform, listPlatforms, resolvePlatform } from "../../../domains/platform/applications/services.js";
|
||||||
|
import type { DatalinkEntity } from "../../../domains/platform/datalink/types.js";
|
||||||
|
import type { DatalinkPlatformDetail } from "../../../domains/platform/applications/types.js";
|
||||||
import { createClientsForCorp } from "../../helpers.js";
|
import { createClientsForCorp } from "../../helpers.js";
|
||||||
import type { CliParsedArgs, CliRuntime } from "../../types.js";
|
import type { CliParsedArgs, CliRuntime } from "../../types.js";
|
||||||
|
|
||||||
@@ -19,16 +22,81 @@ export function cell(value: unknown): string {
|
|||||||
return String(value);
|
return String(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 在企业全量自建应用中智能反查指定业务对象,避免强制用户/Agent 手动查询并记忆 platformId
|
||||||
|
*/
|
||||||
|
async function resolveEntityGlobally(
|
||||||
|
client: KyInstance,
|
||||||
|
corpId: string,
|
||||||
|
target: string
|
||||||
|
): Promise<{ platform: DatalinkPlatformDetail; entity: DatalinkEntity } | undefined> {
|
||||||
|
const platforms = await listPlatforms(client, corpId);
|
||||||
|
const matches: Array<{ platform: any; entity: DatalinkEntity }> = [];
|
||||||
|
|
||||||
|
const results = await Promise.allSettled(
|
||||||
|
platforms.map(async (p) => {
|
||||||
|
const entities = await listPlatformEntities(client, corpId, p.id);
|
||||||
|
const found = entities.find((e) =>
|
||||||
|
[e.id, e.name, e.code].some((val) => typeof val === "string" && val.toLowerCase() === target.toLowerCase())
|
||||||
|
);
|
||||||
|
if (found) {
|
||||||
|
return { platform: p, entity: found };
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
for (const r of results) {
|
||||||
|
if (r.status === "fulfilled" && r.value) {
|
||||||
|
matches.push(r.value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (matches.length === 1) {
|
||||||
|
const fullPlatform = await getPlatform(client, corpId, matches[0].platform.id);
|
||||||
|
return { platform: fullPlatform || matches[0].platform, entity: matches[0].entity };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (matches.length > 1) {
|
||||||
|
const names = matches.map((m) => `[${m.platform.name}] (${m.platform.id})`).join(", ");
|
||||||
|
throw new Error(`在多个自建应用中找到同名业务对象 [${target}],请显式指定应用名称: ${names}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
export async function resolveAppAndEntity(parsed: CliParsedArgs, runtime: CliRuntime, appIndex = 0, entityIndex = 1) {
|
export async function resolveAppAndEntity(parsed: CliParsedArgs, runtime: CliRuntime, appIndex = 0, entityIndex = 1) {
|
||||||
const appTarget = requiredTarget(parsed, appIndex, "hose-use platform <子命令> <应用 ID|名称>");
|
const targetA = parsed.args[appIndex]?.trim();
|
||||||
|
const targetB = parsed.args[entityIndex]?.trim();
|
||||||
|
|
||||||
|
if (!targetA) {
|
||||||
|
throw new Error("请提供自建应用或业务对象参数: hose-use platform <子命令> [应用] <业务对象>");
|
||||||
|
}
|
||||||
|
|
||||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||||
const corpId = runtime.selectedCorp!.credentials.corpId;
|
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();
|
// 1. 若提供了两个位置参数,严格按「应用 ➔ 对象」标准两级解析
|
||||||
if (!entityTarget) return { clients, corpId, platform, entity: undefined };
|
if (targetB) {
|
||||||
const entity = await resolveEntity(clients.ekbClient, corpId, platform, entityTarget);
|
const platform = await resolvePlatform(clients.ekbClient, corpId, targetA);
|
||||||
if (!entity) throw new Error(`[NOT FOUND] 应用 [${platform.name}] 下未找到业务对象: ${entityTarget}`);
|
if (!platform) throw new Error(`[NOT FOUND] 当前企业下未找到自建应用: ${targetA}`);
|
||||||
return { clients, corpId, platform, entity };
|
const entity = await resolveEntity(clients.ekbClient, corpId, platform, targetB);
|
||||||
|
if (!entity) throw new Error(`[NOT FOUND] 应用 [${platform.name}] 下未找到业务对象: ${targetB}`);
|
||||||
|
return { clients, corpId, platform, entity };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 若仅提供了一个位置参数:优先尝试按「应用」解析(兼容查看应用级信息,如 entities/audit 等)
|
||||||
|
const platform = await resolvePlatform(clients.ekbClient, corpId, targetA);
|
||||||
|
if (platform) {
|
||||||
|
return { clients, corpId, platform, entity: undefined };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 若按应用未找到,自动降维为「业务对象」在企业全量自建应用中智能反查 (Zero-Config Search)
|
||||||
|
const globalMatch = await resolveEntityGlobally(clients.ekbClient, corpId, targetA);
|
||||||
|
if (globalMatch) {
|
||||||
|
return { clients, corpId, platform: globalMatch.platform, entity: globalMatch.entity };
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(`[NOT FOUND] 当前企业下未找到名为 [${targetA}] 的自建应用或业务对象`);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -5,7 +5,7 @@ import { join } from "node:path";
|
|||||||
import * as services from "../../domains/platform/workflow/services.js";
|
import * as services from "../../domains/platform/workflow/services.js";
|
||||||
import * as billApi from "../../domains/bill/api.js";
|
import * as billApi from "../../domains/bill/api.js";
|
||||||
import * as cache from "../../core/cache/index.js";
|
import * as cache from "../../core/cache/index.js";
|
||||||
import * as session from "../../core/http/session-client.js";
|
import * as session from "../../core/http/hose-web-session-client.js";
|
||||||
import * as helpers from "../helpers.js";
|
import * as helpers from "../helpers.js";
|
||||||
import * as workflowShared from "./workflow/shared.js";
|
import * as workflowShared from "./workflow/shared.js";
|
||||||
import * as platformShared from "./platform/shared.js";
|
import * as platformShared from "./platform/shared.js";
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { numberOption, stringOption } from "../parser.js";
|
import { numberOption, stringOption } from "../parser.js";
|
||||||
import { printJson, printTable } from "../printer.js";
|
import { printJson, printTable } from "../printer.js";
|
||||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||||
import { createSessionClient } from "../../core/http/session-client.js";
|
import { createSessionClient } from "../../core/http/hose-web-session-client.js";
|
||||||
import { getRoleGroups, getRoleMembers, searchRoles } from "../../domains/role/tools.js";
|
import { getRoleGroups, getRoleMembers, searchRoles } from "../../domains/role/tools.js";
|
||||||
|
|
||||||
export async function handleRoleCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
export async function handleRoleCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ import {
|
|||||||
import { printJson, printKeyValue } from "../printer.js";
|
import { printJson, printKeyValue } from "../printer.js";
|
||||||
import { numberOption, stringOption } from "../parser.js";
|
import { numberOption, stringOption } from "../parser.js";
|
||||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||||
import { createSessionClient } from "../../core/http/session-client.js";
|
import { createSessionClient } from "../../core/http/hose-web-session-client.js";
|
||||||
import { EventStore } from "../../domains/events/store.js";
|
import { EventStore } from "../../domains/events/store.js";
|
||||||
import { pollEvents } from "../../domains/events/poller.js";
|
import { pollEvents } from "../../domains/events/poller.js";
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||||
import { printJson, printTable } from "../printer.js";
|
import { printJson, printTable } from "../printer.js";
|
||||||
import { createSessionClient } from "../../core/http/session-client.js";
|
import { createSessionClient } from "../../core/http/hose-web-session-client.js";
|
||||||
import { listTasks } from "../../domains/task/tools.js";
|
import { listTasks } from "../../domains/task/tools.js";
|
||||||
import type { TaskView } from "../../domains/task/types.js";
|
import type { TaskView } from "../../domains/task/types.js";
|
||||||
|
|
||||||
|
|||||||
@@ -3,29 +3,31 @@ import { handleWorkflowCommand } from "./workflow/index.js";
|
|||||||
import { parseArgs } from "../parser.js";
|
import { parseArgs } from "../parser.js";
|
||||||
import * as services from "../../domains/platform/workflow/services.js";
|
import * as services from "../../domains/platform/workflow/services.js";
|
||||||
|
|
||||||
|
function prodRuntime(jsonMode = false) {
|
||||||
|
return {
|
||||||
|
selectedCorp: {
|
||||||
|
id: "prod-corp",
|
||||||
|
name: "正式生产企业",
|
||||||
|
env: "prod",
|
||||||
|
credentials: { corpId: "prod-corp", accessToken: "token" },
|
||||||
|
},
|
||||||
|
jsonMode,
|
||||||
|
} as any;
|
||||||
|
}
|
||||||
|
|
||||||
test("production corp is blocked before any grant request or confirmation", async () => {
|
test("production corp is blocked before any grant request or confirmation", async () => {
|
||||||
const grant = spyOn(services, "grantWorkflowNodes").mockResolvedValue({
|
const grant = spyOn(services, "grantWorkflowNodes").mockResolvedValue({
|
||||||
success: true, saved: ["code"], skipped: [], rawMessage: "ok", isTest: false,
|
success: true, saved: ["code"], skipped: [], rawMessage: "ok", isTest: false,
|
||||||
});
|
});
|
||||||
try {
|
try {
|
||||||
const runtime = {
|
|
||||||
selectedCorp: {
|
|
||||||
id: "prod-corp",
|
|
||||||
name: "正式生产企业",
|
|
||||||
env: "prod",
|
|
||||||
credentials: { corpId: "prod-corp", accessToken: "token" },
|
|
||||||
},
|
|
||||||
jsonMode: false,
|
|
||||||
} as any;
|
|
||||||
|
|
||||||
const result = await handleWorkflowCommand(
|
const result = await handleWorkflowCommand(
|
||||||
parseArgs(["workflow", "nodes", "grant", "code", "--yes"]),
|
parseArgs(["workflow", "nodes", "grant", "code", "--yes"]),
|
||||||
runtime
|
prodRuntime()
|
||||||
);
|
);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(1);
|
expect(result.exitCode).toBe(1);
|
||||||
expect(result.stderr).toContain("生产环境安全阻断");
|
expect(result.stderr).toContain("生产环境安全阻断");
|
||||||
expect(result.stderr).toContain("未提供 --force 逃生口");
|
expect(result.stderr).toContain("--allow-prod");
|
||||||
expect(grant).not.toHaveBeenCalled();
|
expect(grant).not.toHaveBeenCalled();
|
||||||
} finally {
|
} finally {
|
||||||
grant.mockRestore();
|
grant.mockRestore();
|
||||||
@@ -42,9 +44,85 @@ test("env-unmarked corp is conservatively treated as production", async () => {
|
|||||||
{ selectedCorp: { id: "corp", name: "浙江麦瑞克科技有限公司" }, jsonMode: true } as any
|
{ selectedCorp: { id: "corp", name: "浙江麦瑞克科技有限公司" }, jsonMode: true } as any
|
||||||
);
|
);
|
||||||
expect(result.exitCode).toBe(1);
|
expect(result.exitCode).toBe(1);
|
||||||
expect(JSON.parse(result.stdout).code).toBe("PROD_GRANT_BLOCKED");
|
const parsed = JSON.parse(result.stdout);
|
||||||
|
expect(parsed.code).toBe("PROD_GRANT_BLOCKED");
|
||||||
|
expect(parsed.nextAction).toContain("--allow-prod");
|
||||||
expect(grant).not.toHaveBeenCalled();
|
expect(grant).not.toHaveBeenCalled();
|
||||||
} finally {
|
} finally {
|
||||||
grant.mockRestore();
|
grant.mockRestore();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("--allow-prod dry-run previews the production grant without writing", async () => {
|
||||||
|
const grant = spyOn(services, "grantWorkflowNodes").mockResolvedValue({
|
||||||
|
success: true, saved: ["code"], skipped: [], rawMessage: "ok", isTest: false,
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
const result = await handleWorkflowCommand(
|
||||||
|
parseArgs(["workflow", "nodes", "grant", "code", "--allow-prod", "--dry-run"]),
|
||||||
|
prodRuntime()
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(result.exitCode).toBe(0);
|
||||||
|
expect(result.stdout).toContain("productionOverride: true");
|
||||||
|
expect(result.stdout).toContain("生产环境逃生口已启用");
|
||||||
|
expect(result.stdout).toContain("--allow-prod --yes");
|
||||||
|
expect(grant).not.toHaveBeenCalled();
|
||||||
|
} finally {
|
||||||
|
grant.mockRestore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("--allow-prod still requires --yes before the production grant runs", async () => {
|
||||||
|
const grant = spyOn(services, "grantWorkflowNodes").mockResolvedValue({
|
||||||
|
success: true, saved: ["code"], skipped: [], rawMessage: "ok", isTest: false,
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
await expect(
|
||||||
|
handleWorkflowCommand(
|
||||||
|
parseArgs(["workflow", "nodes", "grant", "code", "--allow-prod"]),
|
||||||
|
prodRuntime()
|
||||||
|
)
|
||||||
|
).rejects.toThrow("拒绝执行开通企业工作流灰度节点");
|
||||||
|
expect(grant).not.toHaveBeenCalled();
|
||||||
|
} finally {
|
||||||
|
grant.mockRestore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("--allow-prod --yes executes the production grant and marks the result", async () => {
|
||||||
|
const grant = spyOn(services, "grantWorkflowNodes").mockResolvedValue({
|
||||||
|
success: true, saved: ["code"], skipped: [], rawMessage: "新开通的节点:code", isTest: false,
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
const result = await handleWorkflowCommand(
|
||||||
|
parseArgs(["workflow", "nodes", "grant", "code", "--allow-prod", "--yes"]),
|
||||||
|
prodRuntime()
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(result.exitCode).toBe(0);
|
||||||
|
expect(result.stdout).toContain("生产环境逃生口已启用");
|
||||||
|
expect(result.stdout).toContain("灰度节点开通结果");
|
||||||
|
expect(grant).toHaveBeenCalledTimes(1);
|
||||||
|
} finally {
|
||||||
|
grant.mockRestore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("--allow-prod --yes JSON result exposes productionOverride", async () => {
|
||||||
|
const grant = spyOn(services, "grantWorkflowNodes").mockResolvedValue({
|
||||||
|
success: true, saved: ["code"], skipped: [], rawMessage: "新开通的节点:code", isTest: false,
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
const result = await handleWorkflowCommand(
|
||||||
|
parseArgs(["workflow", "nodes", "grant", "code", "--allow-prod", "--yes", "--json"]),
|
||||||
|
prodRuntime(true)
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(result.exitCode).toBe(0);
|
||||||
|
expect(JSON.parse(result.stdout).productionOverride).toBe(true);
|
||||||
|
expect(grant).toHaveBeenCalledTimes(1);
|
||||||
|
} finally {
|
||||||
|
grant.mockRestore();
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { readFileSync, writeFileSync } from "node:fs";
|
import { readFileSync, writeFileSync } from "node:fs";
|
||||||
import { EkbError } from "../../../core/errors.js";
|
import { EkbError } from "../../../core/errors.js";
|
||||||
import { getWorkflowDetail, listAllWorkflows, refreshWorkflowChooses, updateWorkflow } from "../../../domains/platform/workflow/services.js";
|
import { getWorkflowDetail, listAllWorkflows, refreshWorkflowChooses, updateWorkflow, lintWorkflowScripts } from "../../../domains/platform/workflow/services.js";
|
||||||
import { WorkflowSavePartialError } from "../../../domains/platform/workflow/management/save-error.js";
|
import { WorkflowSavePartialError } from "../../../domains/platform/workflow/management/save-error.js";
|
||||||
import { WorkflowDetailSchema } from "../../../domains/platform/workflow/types.js";
|
import { WorkflowDetailSchema } from "../../../domains/platform/workflow/types.js";
|
||||||
import {
|
import {
|
||||||
@@ -99,6 +99,22 @@ export async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Pr
|
|||||||
|
|
||||||
const forceWrite = booleanOption(parsed.options, ["force-write", "forceWrite"]);
|
const forceWrite = booleanOption(parsed.options, ["force-write", "forceWrite"]);
|
||||||
const syncFile = booleanOption(parsed.options, ["in-place", "inPlace"]);
|
const syncFile = booleanOption(parsed.options, ["in-place", "inPlace"]);
|
||||||
|
|
||||||
|
// 保存前静态代码健康度检查
|
||||||
|
const scriptLintReport = lintWorkflowScripts(parsedWorkflow as any);
|
||||||
|
const scriptWarnings: string[] = [];
|
||||||
|
if (scriptLintReport.totalCodeNodes > 0) {
|
||||||
|
for (const node of scriptLintReport.reports) {
|
||||||
|
if (node.issues.length > 0) {
|
||||||
|
for (const iss of node.issues) {
|
||||||
|
const icon = iss.level === "error" ? "❌" : "⚠️";
|
||||||
|
const loc = iss.line ? `(L${iss.line})` : "";
|
||||||
|
scriptWarnings.push(`${icon} 节点 [${node.nodeName}] ${loc}: [${iss.rule}] ${iss.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
requireMutationConfirmation(
|
requireMutationConfirmation(
|
||||||
parsed,
|
parsed,
|
||||||
runtime,
|
runtime,
|
||||||
@@ -112,6 +128,7 @@ export async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Pr
|
|||||||
tasksVersion: parsedWorkflow.tasksVersion,
|
tasksVersion: parsedWorkflow.tasksVersion,
|
||||||
forceWrite,
|
forceWrite,
|
||||||
syncFile,
|
syncFile,
|
||||||
|
...(scriptWarnings.length > 0 ? { scriptWarnings } : {}),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { getWorkflowDetail, listWorkflowLogs, listWorkflowSnapshots } from "../../../domains/platform/workflow/services.js";
|
import { getWorkflowDetail, listWorkflowLogs, listWorkflowSnapshots, searchWorkflowJobByFlowCode } from "../../../domains/platform/workflow/services.js";
|
||||||
import { stringOption, numberOption, booleanOption } from "../../parser.js";
|
import { stringOption, numberOption, booleanOption } from "../../parser.js";
|
||||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||||
@@ -28,8 +28,52 @@ export async function handleHistory(parsed: CliParsedArgs, runtime: CliRuntime):
|
|||||||
|
|
||||||
export async function handleLogs(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
export async function handleLogs(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||||
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow logs <pipelineId> [--state=FAILED] [--has-error] [--start-time=YYYY-MM-DD] [--end-time=YYYY-MM-DD]\n", exitCode: 1 };
|
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow logs <pipelineId> [--flow=<单号>] [--state=FAILED] [--has-error] [--start-time=YYYY-MM-DD] [--end-time=YYYY-MM-DD]\n", exitCode: 1 };
|
||||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||||
|
|
||||||
|
// 优先支持按单号精准定位 Job(本地 SQLite 缓存秒级直达 + 流式熔断探查)
|
||||||
|
const flowFilter = stringOption(parsed.options, ["flow", "flowCode", "code"]);
|
||||||
|
if (flowFilter) {
|
||||||
|
const corpId = runtime.selectedCorp?.credentials.corpId || "";
|
||||||
|
const searchResult = await searchWorkflowJobByFlowCode(client, corpId, pipelineId, flowFilter, {
|
||||||
|
maxScanPages: numberOption(parsed.options, ["max-pages", "maxPages", "page-limit"]) ?? 10,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (runtime.jsonMode) {
|
||||||
|
return {
|
||||||
|
stdout: printJson(searchResult, runtime.outputOptions),
|
||||||
|
stderr: "",
|
||||||
|
exitCode: searchResult.found ? 0 : 1,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!searchResult.found) {
|
||||||
|
return {
|
||||||
|
stdout: `未找到单号 [${flowFilter}] 对应的工作流执行记录 (已探查 ${searchResult.totalScanned || 0} 笔 Job)\n`,
|
||||||
|
stderr: "",
|
||||||
|
exitCode: 1,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const job = searchResult.job!;
|
||||||
|
const hitInfo = searchResult.source === "cache" ? "⚡ 本地 SQLite 缓存秒级命中" : "🔍 远端流式探查并自动建立本地缓存";
|
||||||
|
const out = [
|
||||||
|
`====== 工作流单据定位成功 [${pipelineId}] ======`,
|
||||||
|
printKeyValue({
|
||||||
|
"定位来源": hitInfo,
|
||||||
|
"触发单号": searchResult.flowCode || "-",
|
||||||
|
"实例 ID (jobId)": job.id,
|
||||||
|
"运行状态 (status)": job.status || "-",
|
||||||
|
"提交人": job.inputs?.userInfo?.name || "-",
|
||||||
|
"创建时间": job.createTime ? new Date(job.createTime).toLocaleString() : "-",
|
||||||
|
}),
|
||||||
|
"",
|
||||||
|
`提示: 可执行 hose-use workflow job ${job.id} 查看该单据的完整节点执行树与代码运算日志。`,
|
||||||
|
].join("\n");
|
||||||
|
|
||||||
|
return { stdout: `${out}\n`, stderr: "", exitCode: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
const rawResult = await listWorkflowLogs(client, pipelineId, {
|
const rawResult = await listWorkflowLogs(client, pipelineId, {
|
||||||
state: stringOption(parsed.options, ["state"]),
|
state: stringOption(parsed.options, ["state"]),
|
||||||
page: numberOption(parsed.options, ["page"]),
|
page: numberOption(parsed.options, ["page"]),
|
||||||
|
|||||||
@@ -17,6 +17,8 @@ import { handleWorkflowLintScript, handleWorkflowEvalScript } from "./script.js"
|
|||||||
import { handleWorkflowEnum } from "./enum.js";
|
import { handleWorkflowEnum } from "./enum.js";
|
||||||
import { handleWebhookCommand } from "./webhook.js";
|
import { handleWebhookCommand } from "./webhook.js";
|
||||||
import { handleWorkflowLink } from "./link.js";
|
import { handleWorkflowLink } from "./link.js";
|
||||||
|
import { handleOutboundCommand } from "./outbound.js";
|
||||||
|
|
||||||
|
|
||||||
export async function handleWorkflowCommand(
|
export async function handleWorkflowCommand(
|
||||||
parsed: CliParsedArgs,
|
parsed: CliParsedArgs,
|
||||||
@@ -126,11 +128,16 @@ export async function handleWorkflowCommand(
|
|||||||
case "url":
|
case "url":
|
||||||
case "web":
|
case "web":
|
||||||
return handleWorkflowLink(parsed, runtime);
|
return handleWorkflowLink(parsed, runtime);
|
||||||
|
case "outbound":
|
||||||
|
case "outbounds":
|
||||||
|
case "outbound-message":
|
||||||
|
return handleOutboundCommand(parsed, runtime);
|
||||||
default:
|
default:
|
||||||
return {
|
return {
|
||||||
stdout: "",
|
stdout: "",
|
||||||
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, refresh-chooses, history, logs, job, diff, diff-job, check, test, copy, create, delete, node, tail, lint-script, eval-script, enum, webhook, link\n`,
|
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, refresh-chooses, history, logs, job, diff, diff-job, check, test, copy, create, delete, node, tail, lint-script, eval-script, enum, webhook, link, outbound\n`,
|
||||||
exitCode: 1,
|
exitCode: 1,
|
||||||
};
|
};
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -113,23 +113,34 @@ export async function handleGrantNodes(
|
|||||||
runtime: CliRuntime
|
runtime: CliRuntime
|
||||||
): Promise<CliResult> {
|
): Promise<CliResult> {
|
||||||
const corp = runtime.selectedCorp!;
|
const corp = runtime.selectedCorp!;
|
||||||
|
const isProd = isCorpProd(corp);
|
||||||
|
const allowProd = booleanOption(parsed.options, ["allow-prod", "allow-production"]);
|
||||||
|
const prodNextAction = "hose-use workflow nodes grant <type...> --allow-prod --yes";
|
||||||
|
|
||||||
// 生产环境硬拦截:灰度节点开通属于不可逆企业级写操作,本项目禁止对生产企业执行。
|
// 生产环境默认硬拦截:灰度节点开通属于不可逆企业级写操作。
|
||||||
// 与 workflow/test.ts 的调试阻断不同,这里不提供 --force 逃生口。
|
// 逃生口必须显式追加 --allow-prod,且仍受 --dry-run / --yes 两阶段确认约束。
|
||||||
if (isCorpProd(corp)) {
|
if (isProd && !allowProd) {
|
||||||
return {
|
return {
|
||||||
stdout: runtime.jsonMode
|
stdout: runtime.jsonMode
|
||||||
? printJson({ error: true, code: "PROD_GRANT_BLOCKED", message: "禁止对正式生产企业开通灰度节点" }) + "\n"
|
? printJson({
|
||||||
|
error: true,
|
||||||
|
code: "PROD_GRANT_BLOCKED",
|
||||||
|
message: "对正式生产企业开通灰度节点需显式追加 --allow-prod",
|
||||||
|
exitCode: 1,
|
||||||
|
nextAction: prodNextAction,
|
||||||
|
}) + "\n"
|
||||||
: "",
|
: "",
|
||||||
stderr: runtime.jsonMode
|
stderr: runtime.jsonMode
|
||||||
? ""
|
? ""
|
||||||
: [
|
: [
|
||||||
"🛑 生产环境安全阻断 (Production Safeguard):",
|
"🛑 生产环境安全阻断 (Production Safeguard):",
|
||||||
`当前工作企业 [${corp.name || corp.id}] 被判定为【正式生产环境】。`,
|
`当前工作企业 [${corp.name || corp.id}] 被判定为【正式生产环境】。`,
|
||||||
"灰度节点开通是不可逆的企业级写操作,本项目禁止对生产企业执行,且未提供 --force 逃生口。",
|
"灰度节点开通是不可逆的企业级写操作,默认禁止对生产企业执行。",
|
||||||
|
"",
|
||||||
|
"如确需在生产环境开通,必须显式追加 --allow-prod 承担风险,并先预览再执行:",
|
||||||
|
" hose-use workflow nodes grant <type...> --allow-prod --dry-run",
|
||||||
|
` ${prodNextAction}`,
|
||||||
"",
|
"",
|
||||||
"请切换到测试企业后重试:",
|
|
||||||
" hose-use corps switch <测试企业ID>",
|
|
||||||
"若企业环境标记有误,请检查 ~/.config/hose-use/enterprises/ 下的 env / isTest 字段。",
|
"若企业环境标记有误,请检查 ~/.config/hose-use/enterprises/ 下的 env / isTest 字段。",
|
||||||
].join("\n") + "\n",
|
].join("\n") + "\n",
|
||||||
exitCode: 1,
|
exitCode: 1,
|
||||||
@@ -159,7 +170,12 @@ export async function handleGrantNodes(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
requireMutationConfirmation(parsed, runtime, "开通企业工作流灰度节点", "hose-use workflow nodes grant <type...> --yes");
|
requireMutationConfirmation(
|
||||||
|
parsed,
|
||||||
|
runtime,
|
||||||
|
"开通企业工作流灰度节点",
|
||||||
|
isProd ? prodNextAction : "hose-use workflow nodes grant <type...> --yes"
|
||||||
|
);
|
||||||
const isTest = booleanOption(parsed.options, ["is-test"]);
|
const isTest = booleanOption(parsed.options, ["is-test"]);
|
||||||
if (isDryRun(parsed, runtime)) {
|
if (isDryRun(parsed, runtime)) {
|
||||||
return mutationPreview(parsed, runtime, "开通企业工作流灰度节点", corp.corpId || corp.credentials.corpId || corp.id, {
|
return mutationPreview(parsed, runtime, "开通企业工作流灰度节点", corp.corpId || corp.credentials.corpId || corp.id, {
|
||||||
@@ -167,6 +183,12 @@ export async function handleGrantNodes(
|
|||||||
isTest,
|
isTest,
|
||||||
attachedOptions: GRANT_ATTACHED_OPTIONS,
|
attachedOptions: GRANT_ATTACHED_OPTIONS,
|
||||||
adminPasswordRequired: Boolean(process.env.HOSE_ADMIN_PASSWORD),
|
adminPasswordRequired: Boolean(process.env.HOSE_ADMIN_PASSWORD),
|
||||||
|
...(isProd
|
||||||
|
? {
|
||||||
|
productionOverride: true,
|
||||||
|
productionWarning: "生产环境逃生口已启用:实际执行会变更正式生产企业,请再次核对企业与节点类型。",
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -180,7 +202,7 @@ export async function handleGrantNodes(
|
|||||||
|
|
||||||
if (runtime.jsonMode) {
|
if (runtime.jsonMode) {
|
||||||
return {
|
return {
|
||||||
stdout: printJson(result, runtime.outputOptions),
|
stdout: printJson(isProd ? { ...result, productionOverride: true } : result, runtime.outputOptions),
|
||||||
stderr: "",
|
stderr: "",
|
||||||
exitCode: result.success ? 0 : 1,
|
exitCode: result.success ? 0 : 1,
|
||||||
};
|
};
|
||||||
@@ -190,6 +212,9 @@ export async function handleGrantNodes(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const lines = [
|
const lines = [
|
||||||
|
...(isProd
|
||||||
|
? ["⚠️ 生产环境逃生口已启用 (--allow-prod):本次对正式生产企业执行了灰度节点开通。", ""]
|
||||||
|
: []),
|
||||||
`====== 灰度节点开通结果 [${corp.name}] ======`,
|
`====== 灰度节点开通结果 [${corp.name}] ======`,
|
||||||
printKeyValue({
|
printKeyValue({
|
||||||
"申请开通节点": targetNodes.join(", "),
|
"申请开通节点": targetNodes.join(", "),
|
||||||
|
|||||||
@@ -88,13 +88,15 @@ export async function handleNodeCommand(
|
|||||||
"",
|
"",
|
||||||
"子命令 (企业灰度节点级别):",
|
"子命令 (企业灰度节点级别):",
|
||||||
" nodes [list] [--all] 列出当前企业已开通的节点字典 (别名: probe, catalog)",
|
" nodes [list] [--all] 列出当前企业已开通的节点字典 (别名: probe, catalog)",
|
||||||
" nodes grant <type...> [--is-test] 为当前企业开通灰度节点(标准/测试 Piper 二选一)",
|
" nodes grant <type...> [--is-test] [--allow-prod] 为当前企业开通灰度节点(生产环境需显式 --allow-prod)",
|
||||||
"",
|
"",
|
||||||
"示例:",
|
"示例:",
|
||||||
" hose-use workflow nodes",
|
" hose-use workflow nodes",
|
||||||
" hose-use workflow nodes --all",
|
" hose-use workflow nodes --all",
|
||||||
" hose-use workflow nodes grant code-js2",
|
" hose-use workflow nodes grant code-js2",
|
||||||
" hose-use workflow nodes grant code-js2 --is-test # 仅用于工作流位于测试 Piper 的企业",
|
" hose-use workflow nodes grant code-js2 --is-test # 仅用于工作流位于测试 Piper 的企业",
|
||||||
|
" hose-use workflow nodes grant code-js2 --allow-prod --dry-run # 生产企业:先预览",
|
||||||
|
" hose-use workflow nodes grant code-js2 --allow-prod --yes # 生产企业:确认执行",
|
||||||
" hose-use workflow node list 896398895352487950",
|
" hose-use workflow node list 896398895352487950",
|
||||||
].join("\n") + "\n",
|
].join("\n") + "\n",
|
||||||
exitCode: 1,
|
exitCode: 1,
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { describe, expect, it } from "bun:test";
|
||||||
|
import { handleOutboundCommand } from "./outbound.js";
|
||||||
|
import type { CliParsedArgs, CliRuntime } from "../../types.js";
|
||||||
|
|
||||||
|
describe("handleOutboundCommand", () => {
|
||||||
|
it("rejects when no corp selected", async () => {
|
||||||
|
const result = await handleOutboundCommand(
|
||||||
|
{ args: ["list"], options: {}, raw: [] },
|
||||||
|
{ selectedCorp: null, jsonMode: false } as unknown as CliRuntime
|
||||||
|
);
|
||||||
|
expect(result.exitCode).toBe(1);
|
||||||
|
expect(result.stderr).toContain("未选中企业");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
import { stringOption, numberOption } from "../../parser.js";
|
||||||
|
import { printJson, printTable } from "../../printer.js";
|
||||||
|
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||||
|
import { createSessionClient } from "../../../core/http/hose-web-session-client.js";
|
||||||
|
import { getOutboundMessages, queryOutboundMessageLogs } from "../../../domains/platform/workflow/services.js";
|
||||||
|
|
||||||
|
function formatTime(timestamp: number | undefined): string {
|
||||||
|
if (!timestamp) return "-";
|
||||||
|
const date = new Date(timestamp);
|
||||||
|
return date.toLocaleString("zh-CN", { hour12: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function handleOutboundCommand(
|
||||||
|
parsed: CliParsedArgs,
|
||||||
|
runtime: CliRuntime
|
||||||
|
): Promise<CliResult> {
|
||||||
|
const corp = runtime.selectedCorp;
|
||||||
|
if (!corp) {
|
||||||
|
return {
|
||||||
|
stdout: "",
|
||||||
|
stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n",
|
||||||
|
exitCode: 1,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const sub = parsed.args[0] || "list";
|
||||||
|
const corpId = corp.corpId || corp.id;
|
||||||
|
const client = await createSessionClient(corp);
|
||||||
|
|
||||||
|
if (sub === "list" || sub === "rules") {
|
||||||
|
const rules = await getOutboundMessages(client, corpId);
|
||||||
|
|
||||||
|
if (runtime.jsonMode) {
|
||||||
|
return {
|
||||||
|
stdout: printJson({ corpId, total: rules.length, items: rules }, runtime.outputOptions),
|
||||||
|
stderr: "",
|
||||||
|
exitCode: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const headers = ["#", "规则名称", "类型", "状态", "目标回调 URL", "监听事件"];
|
||||||
|
const rows = rules.map((r, i) => [
|
||||||
|
String(i + 1),
|
||||||
|
r.messageName || "-",
|
||||||
|
r.messageType || "-",
|
||||||
|
r.enable ? "🟢 启用" : "⚪ 停用",
|
||||||
|
r.callbackUrl || "-",
|
||||||
|
r.actionEvent && r.actionEvent.length ? r.actionEvent.join(", ") : "全部/默认",
|
||||||
|
]);
|
||||||
|
|
||||||
|
const title = `====== [${corp.name}] 出站消息规则列表 (共 ${rules.length} 条) ======\n`;
|
||||||
|
return {
|
||||||
|
stdout: title + (rules.length ? printTable(headers, rows) : " (暂无配置)\n"),
|
||||||
|
stderr: "",
|
||||||
|
exitCode: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sub === "logs" || sub === "log") {
|
||||||
|
const code = stringOption(parsed.options, ["code", "sn", "flow", "bill"]) || (parsed.args[1] && !parsed.args[1].startsWith("-") ? parsed.args[1] : undefined);
|
||||||
|
const messageType = stringOption(parsed.options, ["type", "message-type"]) || "flow";
|
||||||
|
const start = numberOption(parsed.options, ["start", "offset"], 0) ?? 0;
|
||||||
|
const count = numberOption(parsed.options, ["count", "limit", "n"], 20) ?? 20;
|
||||||
|
|
||||||
|
const result = await queryOutboundMessageLogs(client, corpId, {
|
||||||
|
messageType,
|
||||||
|
code,
|
||||||
|
start,
|
||||||
|
count,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (runtime.jsonMode) {
|
||||||
|
return {
|
||||||
|
stdout: printJson({ corpId, code, total: result.count, items: result.items }, runtime.outputOptions),
|
||||||
|
stderr: "",
|
||||||
|
exitCode: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const headers = ["#", "单号", "规则名", "动作/阶段", "状态", "投递时间", "目标 URL / 响应详情"];
|
||||||
|
const rows = result.items.map((item, i) => {
|
||||||
|
const sn = item.flowId?.form?.code || item.request?.code || "-";
|
||||||
|
const statusIcon = item.state === "SUCCESS" ? "✅ 成功" : item.state === "FAILED" ? "❌ 失败" : item.state;
|
||||||
|
const respPreview = typeof item.response === "object" && item.response !== null
|
||||||
|
? JSON.stringify(item.response).slice(0, 60)
|
||||||
|
: String(item.response ?? "-").slice(0, 60);
|
||||||
|
|
||||||
|
return [
|
||||||
|
String(i + 1),
|
||||||
|
sn,
|
||||||
|
item.name || "-",
|
||||||
|
`${item.type} (${item.nodeName || "-"})`,
|
||||||
|
statusIcon,
|
||||||
|
formatTime(item.createTime),
|
||||||
|
respPreview,
|
||||||
|
];
|
||||||
|
});
|
||||||
|
|
||||||
|
const filterDesc = code ? ` | 单号筛选: ${code}` : "";
|
||||||
|
const title = `====== [${corp.name}] 出站消息投递日志 (类型: ${messageType}${filterDesc} | 匹配: ${result.count} | 返回: ${result.items.length}) ======\n`;
|
||||||
|
return {
|
||||||
|
stdout: title + (result.items.length ? printTable(headers, rows) : " (暂无匹配日志)\n"),
|
||||||
|
stderr: "",
|
||||||
|
exitCode: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
stdout: "",
|
||||||
|
stderr: `未知 outbound 子命令: ${sub}。支持: list (别名: rules), logs [单号] [--type=flow|message]\n`,
|
||||||
|
exitCode: 1,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -89,6 +89,7 @@ export async function createScriptEngineClientForCorp(corp: CorpConfig, platform
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const createPiperClientForCorp = createScriptEngineClientForCorp;
|
export const createPiperClientForCorp = createScriptEngineClientForCorp;
|
||||||
|
export const createPiperWorkflowClientForCorp = createPiperClientForCorp;
|
||||||
|
|
||||||
export function requireSelectedCorp(
|
export function requireSelectedCorp(
|
||||||
runtime: CliRuntime,
|
runtime: CliRuntime,
|
||||||
@@ -107,6 +108,9 @@ export async function getSessionClientForRuntime(runtime: CliRuntime) {
|
|||||||
return { corp, corpId, client };
|
return { corp, corpId, client };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const getHoseWebSessionClientForRuntime = getSessionClientForRuntime;
|
||||||
|
|
||||||
|
|
||||||
export function prompt(question: string): Promise<string> {
|
export function prompt(question: string): Promise<string> {
|
||||||
const rl = readline.createInterface({
|
const rl = readline.createInterface({
|
||||||
input: process.stdin,
|
input: process.stdin,
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ import { handleKeysCommand } from "./commands/keys.js";
|
|||||||
import { handleStoreCommand } from "./commands/store.js";
|
import { handleStoreCommand } from "./commands/store.js";
|
||||||
import { handleFeeTypeCommand } from "./commands/feetype.js";
|
import { handleFeeTypeCommand } from "./commands/feetype.js";
|
||||||
import { handleAssistPlatformCommand } from "./commands/assist-platform/index.js";
|
import { handleAssistPlatformCommand } from "./commands/assist-platform/index.js";
|
||||||
|
import { handleDocsCommand } from "./commands/docs.js";
|
||||||
import { COMMAND_METADATA, type CliCommandMetadata } from "./command-metadata.js";
|
import { COMMAND_METADATA, type CliCommandMetadata } from "./command-metadata.js";
|
||||||
import type { CliParsedArgs, CliResult, CliRunOptions, CliRuntime } from "./types.js";
|
import type { CliParsedArgs, CliResult, CliRunOptions, CliRuntime } from "./types.js";
|
||||||
|
|
||||||
@@ -206,6 +207,11 @@ export const CLI_COMMAND_REGISTRY: readonly CliCommandDefinition[] = [
|
|||||||
...COMMAND_METADATA["assist-platform"],
|
...COMMAND_METADATA["assist-platform"],
|
||||||
handler: (parsed, runtime) => handleAssistPlatformCommand(parsed, runtime),
|
handler: (parsed, runtime) => handleAssistPlatformCommand(parsed, runtime),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
area: "docs",
|
||||||
|
...COMMAND_METADATA.docs,
|
||||||
|
handler: (parsed, runtime) => handleDocsCommand(parsed, runtime),
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
const COMMAND_LOOKUP = new Map<string, CliCommandDefinition>();
|
const COMMAND_LOOKUP = new Map<string, CliCommandDefinition>();
|
||||||
|
|||||||
+15
-11
@@ -14,22 +14,26 @@ src/core/
|
|||||||
│ ├── account-store.ts # 多账号持久化存储 (~/.config/hose-use/accounts.json, 0o600 权限保护)
|
│ ├── account-store.ts # 多账号持久化存储 (~/.config/hose-use/accounts.json, 0o600 权限保护)
|
||||||
│ ├── token-store.ts # 子域动态 Token 跨进程 L2 持久化缓存 (~/.config/hose-use/tokens.json, 0o600)
|
│ ├── token-store.ts # 子域动态 Token 跨进程 L2 持久化缓存 (~/.config/hose-use/tokens.json, 0o600)
|
||||||
│ └── types.ts
|
│ └── types.ts
|
||||||
├── http/ # 统一 HTTP 客户端装配与网络传输(语义化客户端)
|
├── http/ # 统一 HTTP 客户端装配与网络传输(7 大语义化标准客户端)
|
||||||
│ ├── factory.ts # Ky 底层客户端工厂(超时、重试、错误钩子)
|
│ ├── factory.ts # Ky 底层客户端工厂(超时、重试、错误钩子)
|
||||||
│ ├── fingerprint.ts # 统一浏览器指纹、User-Agent、Cookie 与 WAF 策略头
|
│ ├── fingerprint.ts # 统一浏览器指纹、User-Agent、Cookie 与 WAF 策略头
|
||||||
│ ├── session-client.ts # 闭合用户会话客户端(三 Header + 指纹 + 账号/OpenAPI 双通道自动续杯)
|
│ ├── hose-web-session-client.ts # 合思 Web 主站会话客户端(三 Header + 指纹 + 账号/OpenAPI 双通道自动续杯)
|
||||||
│ ├── openapi-client.ts # 开放平台应用客户端(appKey 换票与签名机制)
|
│ ├── openapi-client.ts # 开放平台应用客户端(appKey 换票与签名机制)
|
||||||
│ ├── unity-client.ts # 应用中心与动态集群寻址客户端(L1 内存 + L2 token-store 跨进程复用)
|
│ ├── piper-workflow-client.ts # Piper 工作流引擎客户端(工作流生命周期、108 类节点编排与 Job 流转)
|
||||||
│ ├── script-engine-client.ts # 工作流 MVEL/Python 脚本调试引擎客户端(L1 + L2 token-store 缓存)
|
│ ├── hose-docs-client.ts # 合思开放文档客户端(docs.ekuaibao.com 8.4MB 索引与 270+ OpenAPI 自省)
|
||||||
│ └── index.ts # 统一导出入口
|
│ ├── unity-easo-client.ts # Unity / EASO 运营中台与动态集群寻址客户端(L1 + L2 跨进程复用)
|
||||||
|
│ ├── assist-platform-client.ts # 合思协助运维平台客户端(代客工单无密直通)
|
||||||
|
│ ├── sso-auth-client.ts # SSO 与扫码鉴权客户端(单点登录与二维码轮询)
|
||||||
|
│ └── index.ts # 统一导出入口
|
||||||
├── cache/ # 统一多级协同缓存
|
├── cache/ # 统一多级协同缓存
|
||||||
│ ├── memory.ts # L1 内存缓存(严格 LRU、TTL、容量限制、按命名空间清理)
|
│ ├── memory.ts # L1 内存缓存(严格 LRU、TTL、容量限制、按命名空间清理)
|
||||||
│ ├── sqlite.ts # L2 SQLite 持久化缓存(跨 CLI 进程复用)
|
│ ├── sqlite.ts # L2 SQLite 持久化缓存(跨 CLI 进程复用)
|
||||||
│ ├── multi-level.ts # 多级联动门面与 in-flight 并发防击穿包装器
|
│ ├── multi-level.ts # 多级联动门面与 in-flight 并发防击穿包装器
|
||||||
│ └── types.ts
|
│ └── types.ts
|
||||||
├── db/ # 统一 SQLite 数据库与结构化版本迁移
|
├── db/ # 统一 SQLite 数据库与结构化版本迁移
|
||||||
│ ├── connection.ts # SQLite 单例、WAL 模式、文件权限 0o600 保护
|
│ ├── connection.ts # SQLite 单例、WAL 模式、文件权限 0o600 保护
|
||||||
│ ├── migrations.ts # 结构化增量迁移运行器(_schema_migrations)
|
│ ├── migrations.ts # 结构化增量迁移运行器(_schema_migrations)
|
||||||
|
│ ├── workflow-job-cache.ts # 工作流 Job 索引缓存与单据触发单号秒级检索
|
||||||
│ └── types.ts
|
│ └── types.ts
|
||||||
├── config/ # 企业配置管理
|
├── config/ # 企业配置管理
|
||||||
│ ├── loader.ts # 全局与多企业配置读写(强制 0o600 权限与字段归一化)
|
│ ├── loader.ts # 全局与多企业配置读写(强制 0o600 权限与字段归一化)
|
||||||
@@ -46,7 +50,7 @@ src/core/
|
|||||||
|
|
||||||
## 分层约束
|
## 分层约束
|
||||||
|
|
||||||
- `domains/*` 优先通过 `core/http/` 获取语义化客户端(`createSessionClient`, `createOpenApiClient`, `getUnityClient`, `getScriptEngineClient`),保持底层网络与指纹统一
|
- `domains/*` 优先通过 `core/http/` 获取语义化客户端(`createHoseWebSessionClient`, `createOpenApiClient`, `getPiperWorkflowClient`, `createHoseDocsClient`, `getUnityEasoClient` 等),保持底层网络与指纹统一
|
||||||
- `domains/*` 层只抛 `EkbError` 子类(由 `cli/errors.ts` 统一按结构化 `code` / `status` 映射退出码)
|
- `domains/*` 层只抛 `EkbError` 子类(由 `cli/errors.ts` 统一按结构化 `code` / `status` 映射退出码)
|
||||||
- `server.ts` 作为极简 MCP 单工具网关(`hose_cli`)直接委托 `cli/runner.ts` 执行
|
- `server.ts` 作为极简 MCP 单工具网关(`hose_cli`)直接委托 `cli/runner.ts` 执行
|
||||||
- 业务域如果需要缓存,统一使用 `core/cache/` 提供的多级缓存门面
|
- 业务域如果需要缓存,统一使用 `core/cache/` 提供的多级缓存门面
|
||||||
|
|||||||
@@ -4,8 +4,8 @@ import { join } from "node:path";
|
|||||||
import { AuthenticationError } from "../errors.js";
|
import { AuthenticationError } from "../errors.js";
|
||||||
import { CorpConfig, CredentialSource } from "../config/types.js";
|
import { CorpConfig, CredentialSource } from "../config/types.js";
|
||||||
import { saveCorpConfig, resolveWritableEnterprisesDir } from "../config/loader.js";
|
import { saveCorpConfig, resolveWritableEnterprisesDir } from "../config/loader.js";
|
||||||
import { resolveCorpCluster, clearUnityClientCache } from "../http/unity-client.js";
|
import { resolveCorpCluster, clearUnityClientCache } from "../http/unity-easo-client.js";
|
||||||
import { clearScriptEngineClientCache } from "../http/script-engine-client.js";
|
import { clearScriptEngineClientCache } from "../http/piper-workflow-client.js";
|
||||||
import { clearCorpTokens } from "./token-store.js";
|
import { clearCorpTokens } from "./token-store.js";
|
||||||
import {
|
import {
|
||||||
DEFAULT_EKB_BASE_URL,
|
DEFAULT_EKB_BASE_URL,
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { join } from "node:path";
|
|||||||
import { AuthenticationError } from "../errors.js";
|
import { AuthenticationError } from "../errors.js";
|
||||||
import { CorpConfig, CorpConfigSchema } from "../config/types.js";
|
import { CorpConfig, CorpConfigSchema } from "../config/types.js";
|
||||||
import { saveCorpConfig, resolveWritableEnterprisesDir } from "../config/loader.js";
|
import { saveCorpConfig, resolveWritableEnterprisesDir } from "../config/loader.js";
|
||||||
import { resolveCorpCluster } from "../http/unity-client.js";
|
import { resolveCorpCluster } from "../http/unity-easo-client.js";
|
||||||
import {
|
import {
|
||||||
DEFAULT_EKB_BASE_URL,
|
DEFAULT_EKB_BASE_URL,
|
||||||
HoseOpenApiKeyItem,
|
HoseOpenApiKeyItem,
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
# 统一 SQLite 数据库(db)
|
||||||
|
|
||||||
|
本目录是全部本地持久化的唯一入口:单例连接、PRAGMA 调优、文件权限保护与结构化版本迁移都在这里。业务域不自行创建数据库或私有表,需要持久化时接入本目录并注册迁移。上级职责见 [Core 说明](../README.core.md)。
|
||||||
|
|
||||||
|
## 文件职责
|
||||||
|
|
||||||
|
| 文件 | 职责 |
|
||||||
|
|---|---|
|
||||||
|
| [connection.ts](./connection.ts) | 路径解析、单例连接、PRAGMA 与权限设置、迁移入口 |
|
||||||
|
| [migrations.ts](./migrations.ts) | 迁移列表与 `runMigrations` 原子执行器 |
|
||||||
|
| [workflow-job-cache.ts](./workflow-job-cache.ts) | `workflow_job_index` 的批量 upsert 与按企业/工作流/单号检索 |
|
||||||
|
| [types.ts](./types.ts) | `DatabaseMigration`、`DatabaseConnectionOptions` |
|
||||||
|
| [index.ts](./index.ts) | 统一导出 |
|
||||||
|
|
||||||
|
## 连接与路径
|
||||||
|
|
||||||
|
- 默认路径 `~/.config/hose-use/approval.db`,可用环境变量 `HOSE_APPROVAL_DB` 覆盖;`:memory:` 供测试使用。
|
||||||
|
- 目录创建为 `0o700`,数据库文件 `chmod 0o600`,与配置、Token 文件的权限基线一致。
|
||||||
|
- 连接启用 `journal_mode = WAL`、`foreign_keys = ON`、`busy_timeout = 5000`、`synchronous = NORMAL`。
|
||||||
|
- 目标路径变化时先关闭旧连接再建新连接;`closeDatabase()` 用于显式释放句柄(测试隔离也会用到)。
|
||||||
|
- 迁移失败时关闭句柄、不激活单例缓存并向上抛出,避免半初始化连接被后续调用复用。
|
||||||
|
|
||||||
|
## 迁移机制
|
||||||
|
|
||||||
|
- 迁移历史记录在 `_schema_migrations(version, name, applied_at)`,`runMigrations` 按 `version` 升序只执行未应用项。
|
||||||
|
- 每个迁移由 `BEGIN IMMEDIATE` / `COMMIT` 独立事务包裹,失败 `ROLLBACK` 并抛出,不留半应用状态。
|
||||||
|
- 当前迁移版本:
|
||||||
|
|
||||||
|
| 版本 | 名称 | 主要内容 |
|
||||||
|
|---:|---|---|
|
||||||
|
| 1 | `001_core_schema_and_approval_tables` | `rules`、`preferences`、`approval_runs`、`approval_findings`、`aipro_logs`、`cache_entries` |
|
||||||
|
| 2 | `002_cache_entries_composite_primary_key` | 重建 `cache_entries` 为复合主键 |
|
||||||
|
| 3 | `003_events_and_workflow_alerts_tables` | `observed_events`、`workflow_error_alerts` |
|
||||||
|
| 4 | `004_approval_runs_unique_short_id` | 存量短 ID 纠偏并建立大小写不敏感唯一索引 |
|
||||||
|
| 5 | `005_workflow_job_cache` | `workflow_job_index` 及其检索索引 |
|
||||||
|
|
||||||
|
## 表与消费方
|
||||||
|
|
||||||
|
| 表 | 用途 | 主要消费方 |
|
||||||
|
|---|---|---|
|
||||||
|
| `rules` / `preferences` / `approval_runs` / `approval_findings` | 审批规则、风格偏好、运行记录与命中明细 | `src/domains/approval/repository.ts` |
|
||||||
|
| `aipro_logs` | AI PRO 操作审计日志 | `src/domains/approval/repository.ts` |
|
||||||
|
| `cache_entries` | L2 跨进程持久化缓存 | [core/cache/sqlite.ts](../cache/sqlite.ts) |
|
||||||
|
| `observed_events` | 事件轮询去重 | `src/domains/events/store.ts` |
|
||||||
|
| `workflow_error_alerts` | 工作流错误指纹与告警频次 | `src/domains/platform/workflow/alert/index.ts` |
|
||||||
|
| `workflow_job_index` | Job 单号索引,免全量扫描 | [workflow-job-cache.ts](./workflow-job-cache.ts)、`src/domains/platform/workflow/execution/search-by-flow.ts` |
|
||||||
|
|
||||||
|
## 新增迁移
|
||||||
|
|
||||||
|
- 版本号取当前最大值 + 1;已发布迁移禁止修改,只能追加新版本。
|
||||||
|
- DDL 保持幂等:建表/建索引使用 `IF NOT EXISTS`;老库补列先用 `PRAGMA table_info` 探测(参考 `hasColumn`)再 `ALTER TABLE`。
|
||||||
|
- 迁移只做结构与必要回填,不发起网络请求,也不依赖上层业务域。
|
||||||
|
- 新表或新列的行为在 [db.test.ts](./db.test.ts) 覆盖;测试使用临时库或 `:memory:`,并在结束时 `closeDatabase()` 隔离。
|
||||||
@@ -39,6 +39,7 @@ describe("Core DB - 数据库连接与结构化迁移机制 (加固测试)", ()
|
|||||||
expect(tableNames.has("cache_entries")).toBe(true);
|
expect(tableNames.has("cache_entries")).toBe(true);
|
||||||
expect(tableNames.has("observed_events")).toBe(true);
|
expect(tableNames.has("observed_events")).toBe(true);
|
||||||
expect(tableNames.has("workflow_error_alerts")).toBe(true);
|
expect(tableNames.has("workflow_error_alerts")).toBe(true);
|
||||||
|
expect(tableNames.has("workflow_job_index")).toBe(true);
|
||||||
|
|
||||||
// 检查加固索引:UPPER(short_id)、findings(rule_id)
|
// 检查加固索引:UPPER(short_id)、findings(rule_id)
|
||||||
const indices = db
|
const indices = db
|
||||||
@@ -55,6 +56,8 @@ describe("Core DB - 数据库连接与结构化迁移机制 (加固测试)", ()
|
|||||||
expect(indexNames.has("idx_cache_expires_at")).toBe(true);
|
expect(indexNames.has("idx_cache_expires_at")).toBe(true);
|
||||||
expect(indexNames.has("idx_observed_events_scope")).toBe(true);
|
expect(indexNames.has("idx_observed_events_scope")).toBe(true);
|
||||||
expect(indexNames.has("idx_workflow_alerts_scope")).toBe(true);
|
expect(indexNames.has("idx_workflow_alerts_scope")).toBe(true);
|
||||||
|
expect(indexNames.has("idx_wf_jobs_corp_pipeline_code")).toBe(true);
|
||||||
|
expect(indexNames.has("idx_wf_jobs_code_upper")).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("cache_entries 具备复合主键 (namespace, key) 约束", () => {
|
test("cache_entries 具备复合主键 (namespace, key) 约束", () => {
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
export * from "./types.js";
|
export * from "./types.js";
|
||||||
export * from "./connection.js";
|
export * from "./connection.js";
|
||||||
export * from "./migrations.js";
|
export * from "./migrations.js";
|
||||||
|
export * from "./workflow-job-cache.js";
|
||||||
@@ -242,6 +242,30 @@ export const migrations: DatabaseMigration[] = [
|
|||||||
);
|
);
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
version: 5,
|
||||||
|
name: "005_workflow_job_cache",
|
||||||
|
up(db: Database): void {
|
||||||
|
db.run(`
|
||||||
|
CREATE TABLE IF NOT EXISTS workflow_job_index (
|
||||||
|
corp_id TEXT NOT NULL,
|
||||||
|
pipeline_id TEXT NOT NULL,
|
||||||
|
job_id TEXT NOT NULL,
|
||||||
|
flow_code TEXT,
|
||||||
|
flow_id TEXT,
|
||||||
|
execute_time INTEGER,
|
||||||
|
status TEXT,
|
||||||
|
user_name TEXT,
|
||||||
|
updated_at INTEGER NOT NULL,
|
||||||
|
PRIMARY KEY (corp_id, pipeline_id, job_id)
|
||||||
|
);
|
||||||
|
`);
|
||||||
|
db.run("CREATE INDEX IF NOT EXISTS idx_wf_jobs_code ON workflow_job_index(corp_id, flow_code);");
|
||||||
|
db.run("CREATE INDEX IF NOT EXISTS idx_wf_jobs_pipeline ON workflow_job_index(corp_id, pipeline_id);");
|
||||||
|
db.run("CREATE INDEX IF NOT EXISTS idx_wf_jobs_corp_pipeline_code ON workflow_job_index(corp_id, pipeline_id, flow_code);");
|
||||||
|
db.run("CREATE INDEX IF NOT EXISTS idx_wf_jobs_code_upper ON workflow_job_index(corp_id, pipeline_id, UPPER(flow_code));");
|
||||||
|
},
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
function seedDefaultPreference(db: Database): void {
|
function seedDefaultPreference(db: Database): void {
|
||||||
|
|||||||
@@ -0,0 +1,130 @@
|
|||||||
|
import { Database } from "bun:sqlite";
|
||||||
|
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||||
|
import { closeDatabase, getDatabase } from "./connection.js";
|
||||||
|
import {
|
||||||
|
getCachedWorkflowJobByCode,
|
||||||
|
upsertWorkflowJobIndex,
|
||||||
|
type WorkflowJobCacheRecord,
|
||||||
|
} from "./workflow-job-cache.js";
|
||||||
|
|
||||||
|
describe("Core DB - Workflow Job 本地缓存与索引检索 (workflow_job_index)", () => {
|
||||||
|
let db: Database;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
db = getDatabase(":memory:");
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
closeDatabase();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("批量插入 Job 缓存并支持单号精准与大小写不敏感检索", () => {
|
||||||
|
const records: WorkflowJobCacheRecord[] = [
|
||||||
|
{
|
||||||
|
corpId: "corp_winner",
|
||||||
|
pipelineId: "pipe_101",
|
||||||
|
jobId: "job_001",
|
||||||
|
flowCode: "XZ2610474",
|
||||||
|
flowId: "flow_abc",
|
||||||
|
executeTime: 1700000000000,
|
||||||
|
status: "COMPLETED",
|
||||||
|
userName: "欧阳亚玲",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
corpId: "corp_winner",
|
||||||
|
pipelineId: "pipe_101",
|
||||||
|
jobId: "job_002",
|
||||||
|
flowCode: "XZ2610475",
|
||||||
|
status: "RUNNING",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
upsertWorkflowJobIndex(records, ":memory:");
|
||||||
|
|
||||||
|
// 精确匹配
|
||||||
|
const hitExact = getCachedWorkflowJobByCode("corp_winner", "pipe_101", "XZ2610474", ":memory:");
|
||||||
|
expect(hitExact).not.toBeNull();
|
||||||
|
expect(hitExact?.jobId).toBe("job_001");
|
||||||
|
expect(hitExact?.userName).toBe("欧阳亚玲");
|
||||||
|
expect(hitExact?.status).toBe("COMPLETED");
|
||||||
|
|
||||||
|
// 小写模糊匹配
|
||||||
|
const hitLower = getCachedWorkflowJobByCode("corp_winner", "pipe_101", "xz2610474", ":memory:");
|
||||||
|
expect(hitLower).not.toBeNull();
|
||||||
|
expect(hitLower?.jobId).toBe("job_001");
|
||||||
|
|
||||||
|
// 不存在的单号或不同企业/工作流应返回 null
|
||||||
|
expect(getCachedWorkflowJobByCode("corp_winner", "pipe_101", "NON_EXISTENT", ":memory:")).toBeNull();
|
||||||
|
expect(getCachedWorkflowJobByCode("other_corp", "pipe_101", "XZ2610474", ":memory:")).toBeNull();
|
||||||
|
expect(getCachedWorkflowJobByCode("corp_winner", "other_pipe", "XZ2610474", ":memory:")).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("同单号存在多笔记录时,按 execute_time DESC 优先返回最新执行的一笔", () => {
|
||||||
|
const records: WorkflowJobCacheRecord[] = [
|
||||||
|
{
|
||||||
|
corpId: "corp_winner",
|
||||||
|
pipelineId: "pipe_101",
|
||||||
|
jobId: "job_old",
|
||||||
|
flowCode: "XZ2610474",
|
||||||
|
executeTime: 1000,
|
||||||
|
status: "FAILED",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
corpId: "corp_winner",
|
||||||
|
pipelineId: "pipe_101",
|
||||||
|
jobId: "job_new",
|
||||||
|
flowCode: "XZ2610474",
|
||||||
|
executeTime: 2000,
|
||||||
|
status: "COMPLETED",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
upsertWorkflowJobIndex(records, ":memory:");
|
||||||
|
|
||||||
|
const hit = getCachedWorkflowJobByCode("corp_winner", "pipe_101", "XZ2610474", ":memory:");
|
||||||
|
expect(hit).not.toBeNull();
|
||||||
|
expect(hit?.jobId).toBe("job_new");
|
||||||
|
expect(hit?.status).toBe("COMPLETED");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("相同主键冲突时,执行增量更新并保持已有非空字段 (COALESCE)", () => {
|
||||||
|
upsertWorkflowJobIndex(
|
||||||
|
[
|
||||||
|
{
|
||||||
|
corpId: "corp_winner",
|
||||||
|
pipelineId: "pipe_101",
|
||||||
|
jobId: "job_001",
|
||||||
|
flowCode: "XZ2610474",
|
||||||
|
userName: "欧阳亚玲",
|
||||||
|
status: "RUNNING",
|
||||||
|
executeTime: 1000,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
":memory:"
|
||||||
|
);
|
||||||
|
|
||||||
|
// 再次写入,只更新 status,未传 userName
|
||||||
|
upsertWorkflowJobIndex(
|
||||||
|
[
|
||||||
|
{
|
||||||
|
corpId: "corp_winner",
|
||||||
|
pipelineId: "pipe_101",
|
||||||
|
jobId: "job_001",
|
||||||
|
status: "COMPLETED",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
":memory:"
|
||||||
|
);
|
||||||
|
|
||||||
|
const hit = getCachedWorkflowJobByCode("corp_winner", "pipe_101", "XZ2610474", ":memory:");
|
||||||
|
expect(hit).not.toBeNull();
|
||||||
|
expect(hit?.jobId).toBe("job_001");
|
||||||
|
expect(hit?.status).toBe("COMPLETED");
|
||||||
|
// userName 依然保留
|
||||||
|
expect(hit?.userName).toBe("欧阳亚玲");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("空数组调用 upsert 不抛异常", () => {
|
||||||
|
expect(() => upsertWorkflowJobIndex([], ":memory:")).not.toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
import { getDatabase } from "./connection.js";
|
||||||
|
|
||||||
|
export interface WorkflowJobCacheRecord {
|
||||||
|
corpId: string;
|
||||||
|
pipelineId: string;
|
||||||
|
jobId: string;
|
||||||
|
flowCode?: string;
|
||||||
|
flowId?: string;
|
||||||
|
executeTime?: number;
|
||||||
|
status?: string;
|
||||||
|
userName?: string;
|
||||||
|
updatedAt?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按企业 + 工作流 + 单号快速从本地 SQLite 缓存中检索匹配的 Job 记录
|
||||||
|
*/
|
||||||
|
export function getCachedWorkflowJobByCode(
|
||||||
|
corpId: string,
|
||||||
|
pipelineId: string,
|
||||||
|
flowCode: string,
|
||||||
|
dbPath?: string
|
||||||
|
): WorkflowJobCacheRecord | null {
|
||||||
|
const db = getDatabase(dbPath);
|
||||||
|
const normalizedCode = flowCode.trim();
|
||||||
|
const row = db
|
||||||
|
.query(
|
||||||
|
`SELECT corp_id AS corpId, pipeline_id AS pipelineId, job_id AS jobId,
|
||||||
|
flow_code AS flowCode, flow_id AS flowId, execute_time AS executeTime,
|
||||||
|
status, user_name AS userName, updated_at AS updatedAt
|
||||||
|
FROM workflow_job_index
|
||||||
|
WHERE corp_id = ? AND pipeline_id = ? AND (flow_code = ? OR UPPER(flow_code) = UPPER(?))
|
||||||
|
ORDER BY execute_time DESC, updated_at DESC
|
||||||
|
LIMIT 1`
|
||||||
|
)
|
||||||
|
.get(corpId, pipelineId, normalizedCode, normalizedCode) as WorkflowJobCacheRecord | null;
|
||||||
|
|
||||||
|
return row ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 批量插入或更新 Job 缓存索引
|
||||||
|
*/
|
||||||
|
export function upsertWorkflowJobIndex(
|
||||||
|
records: WorkflowJobCacheRecord[],
|
||||||
|
dbPath?: string
|
||||||
|
): void {
|
||||||
|
if (!records.length) return;
|
||||||
|
const db = getDatabase(dbPath);
|
||||||
|
const now = Date.now();
|
||||||
|
|
||||||
|
const insertStmt = db.prepare(`
|
||||||
|
INSERT INTO workflow_job_index (
|
||||||
|
corp_id, pipeline_id, job_id, flow_code, flow_id, execute_time, status, user_name, updated_at
|
||||||
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
ON CONFLICT(corp_id, pipeline_id, job_id) DO UPDATE SET
|
||||||
|
flow_code = COALESCE(excluded.flow_code, workflow_job_index.flow_code),
|
||||||
|
flow_id = COALESCE(excluded.flow_id, workflow_job_index.flow_id),
|
||||||
|
execute_time = COALESCE(excluded.execute_time, workflow_job_index.execute_time),
|
||||||
|
status = COALESCE(excluded.status, workflow_job_index.status),
|
||||||
|
user_name = COALESCE(excluded.user_name, workflow_job_index.user_name),
|
||||||
|
updated_at = excluded.updated_at
|
||||||
|
`);
|
||||||
|
|
||||||
|
db.transaction(() => {
|
||||||
|
for (const r of records) {
|
||||||
|
insertStmt.run(
|
||||||
|
r.corpId,
|
||||||
|
r.pipelineId,
|
||||||
|
r.jobId,
|
||||||
|
r.flowCode || null,
|
||||||
|
r.flowId || null,
|
||||||
|
r.executeTime || null,
|
||||||
|
r.status || null,
|
||||||
|
r.userName || null,
|
||||||
|
now
|
||||||
|
);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
}
|
||||||
@@ -1,25 +1,32 @@
|
|||||||
# HTTP 客户端与认证衔接(http)
|
# HTTP 客户端与通信底座(core/http)
|
||||||
|
|
||||||
本目录封装语义化 HTTP 客户端、指纹、换票和鉴权续期,是 [Core](../README.core.md) 的传输基础设施。业务 URL、响应模型与业务错误校验由各域 `api.ts` 管理,不放进通用工厂。
|
本目录封装语义化 HTTP 客户端、浏览器指纹伪装、多协议动态换票和自动续期重放,是 [Core](../README.core.md) 的底层网络通信基础设施。业务 URL、响应校验与领域模型由各业务域 `api.ts` 管理,不混入底层通用工厂。
|
||||||
|
|
||||||
## 客户端选择
|
## 7 大核心通信客户端矩阵
|
||||||
|
|
||||||
| 文件 | 使用场景 |
|
全仓统一收敛为对齐外部网络拓扑与独立服务协议的 **7 大标准客户端**(全部规范使用 `-client.ts` 命名):
|
||||||
|
|
||||||
|
| 标准文件名 | 导出的标准工厂 / 方法 | 核心域名端点 | 业务场景与控制范围 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| [hose-web-session-client.ts](./hose-web-session-client.ts) | `createHoseWebSessionClient` | `app.ekuaibao.com` | **合思 Web 主站会话客户端**:承载单据台账、报销审批流、费用科目、员工通讯录等闭环操作,带 Cookie / Token 双通道自动无感续杯与 401 防抖重试。 |
|
||||||
|
| [openapi-client.ts](./openapi-client.ts) | `createOpenApiClient` | `app.ekuaibao.com/api/openapi` | **开放平台官方 OpenAPI 客户端**:基于企业自建应用凭据(`appKey` + `appSecurity`)换取 `accessToken`,调用官方开放标准接口。 |
|
||||||
|
| [piper-workflow-client.ts](./piper-workflow-client.ts) | `getPiperWorkflowClient` | `piper.ekuaibao.com` | **Piper 工作流引擎客户端**:**自建应用工作流完整控制面与执行引擎**。全面管理工作流创建/命名/全量节点保存/发布/快照历史,编排 108 类节点能力与灰度开通,以及流转实例(Job/Tasks)跟踪排查与代码沙箱调试。 |
|
||||||
|
| [hose-docs-client.ts](./hose-docs-client.ts) | `createHoseDocsClient` | `docs.ekuaibao.com` | **合思开放文档客户端**:直连官方文档中心,在线拉取 8.4MB 全量富文本索引,自省 330 篇文档与 270+ OpenAPI 规范与参数定义。 |
|
||||||
|
| [unity-easo-client.ts](./unity-easo-client.ts) | `getUnityEasoClient` / `getEasoClient` | `unity.ekuaibao.com` | **Unity / EASO 运营中台客户端**:负责合思企业部署集群动态寻址(如北京、上海、专有集群)与跨租户全局 JWT / HoseToken 换票。 |
|
||||||
|
| [assist-platform-client.ts](./assist-platform-client.ts) | `createAssistPlatformClient` | `unity.ekuaibao.com/api`<br>*(Web: `/platform-charge/`)* | **合思协助平台客户端**:技术支持人员的代客运维工单匹配、无密直通换票与租户提权。 |
|
||||||
|
| [sso-auth-client.ts](./sso-auth-client.ts) | `createSsoAuthClient` | `sso.hosecloud.com` | **SSO 与扫码鉴权客户端**:企业单点登录、微信/钉钉二维码轮询状态与会话建立。 |
|
||||||
|
|
||||||
|
## 辅助基础设施
|
||||||
|
|
||||||
|
| 文件 | 说明 |
|
||||||
|---|---|
|
|---|---|
|
||||||
| [factory.ts](./factory.ts) | Ky 底层客户端和带鉴权恢复的工厂 |
|
| [factory.ts](./factory.ts) | Ky 底层客户端工厂与 401 自动鉴权恢复机制 |
|
||||||
| [session-client.ts](./session-client.ts) | 合思用户 Session 请求与续期 |
|
| [fingerprint.ts](./fingerprint.ts) | 统一浏览器指纹(User-Agent、sec-ch-ua、Origin、Referer)伪装 |
|
||||||
| [openapi-client.ts](./openapi-client.ts) | 应用凭证换取 OpenAPI Token 并构造请求 |
|
| [piper-endpoints.ts](./piper-endpoints.ts) | Piper / ScriptEngine 生产与测试集群域名动态解析收口 |
|
||||||
| [unity-client.ts](./unity-client.ts) | 应用中心、Unity/EASO 换票及企业集群寻址 |
|
| [index.ts](./index.ts) | HTTP 客户端基础设施全量规范导出入口 |
|
||||||
| [script-engine-client.ts](./script-engine-client.ts) | Piper 脚本引擎客户端与认证缓存 |
|
|
||||||
| [assist-platform-client.ts](./assist-platform-client.ts) | 协助平台客户端 |
|
|
||||||
| [sso-client.ts](./sso-client.ts) | SSO 登录请求与二维码状态查询 |
|
|
||||||
| [fingerprint.ts](./fingerprint.ts) | 统一浏览器指纹和请求头配置 |
|
|
||||||
| [index.ts](./index.ts) | 对外导出入口 |
|
|
||||||
|
|
||||||
## 重放与错误边界
|
## 重放与错误边界
|
||||||
|
|
||||||
鉴权失效时按工厂配置续期并重放一次,重放响应仍检查 HTTP 状态与鉴权错误头,包括 HTTP 200 携带鉴权错误标记的情况。持续鉴权失败应抛认证异常,不递归换票;普通 HTTP 失败保留客户端原有错误语义。
|
1. **自动续期与单次重放**:当鉴权失效时(HTTP 401),客户端按工厂配置续期并最多重放一次。重放响应仍严格检查 HTTP 状态与业务鉴权错误标记(包括 HTTP 200 返回体中带有鉴权失败 code 的情况);
|
||||||
|
2. **凭据隔离**:客户端依据目标企业与业务协议创建,禁止跨企业复用带身份的客户端实例或 Token;
|
||||||
客户端依据目标企业与协议创建,不能跨企业复用带身份的实例或 Token。缓存失效与凭证存储衔接见 [auth/](../auth/README.auth.md)。日志不得输出认证头或完整会话链接。
|
3. **安全日志**:请求日志严禁输出用户 Token、Cookie、Authorization 头或完整私密会话参数。
|
||||||
|
|
||||||
[replay-contract.test.ts](./replay-contract.test.ts)、[clients.test.ts](./clients.test.ts)、Session 与续期测试共同验证客户端协议。变更恢复逻辑时同时检查重放次数、请求体保留和最终响应,避免把传输成功误当作业务成功。
|
|
||||||
@@ -10,6 +10,9 @@ export interface AssistPlatformClientOptions {
|
|||||||
timeout?: number;
|
timeout?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type CreateAssistPlatformClientOptions = AssistPlatformClientOptions;
|
||||||
|
|
||||||
|
|
||||||
export function createAssistPlatformClient(options: AssistPlatformClientOptions): KyInstance {
|
export function createAssistPlatformClient(options: AssistPlatformClientOptions): KyInstance {
|
||||||
if (!options.token || !options.token.trim()) {
|
if (!options.token || !options.token.trim()) {
|
||||||
throw new AuthenticationError("缺少协助平台凭证 Token,请先登录协助平台");
|
throw new AuthenticationError("缺少协助平台凭证 Token,请先登录协助平台");
|
||||||
|
|||||||
@@ -0,0 +1,87 @@
|
|||||||
|
import { describe, expect, it } from "bun:test";
|
||||||
|
import {
|
||||||
|
// 1. hose-web-session-client
|
||||||
|
createHoseWebSessionClient,
|
||||||
|
createSessionClient,
|
||||||
|
getHoseWebSessionHeaders,
|
||||||
|
getSessionHeaders,
|
||||||
|
|
||||||
|
// 2. openapi-client
|
||||||
|
createOpenApiClient,
|
||||||
|
getOpenApiHeaders,
|
||||||
|
|
||||||
|
// 3. piper-workflow-client
|
||||||
|
getPiperWorkflowClient,
|
||||||
|
getScriptEngineClient,
|
||||||
|
clearPiperWorkflowClientCache,
|
||||||
|
clearScriptEngineClientCache,
|
||||||
|
PIPER_BASE_URL,
|
||||||
|
SCRIPT_ENGINE_BASE_URL,
|
||||||
|
|
||||||
|
// 4. hose-docs-client
|
||||||
|
createHoseDocsClient,
|
||||||
|
DEFAULT_HOSE_DOCS_BASE_URL,
|
||||||
|
|
||||||
|
// 5. unity-easo-client
|
||||||
|
getUnityEasoClient,
|
||||||
|
getUnityClient,
|
||||||
|
getEasoClient,
|
||||||
|
clearUnityEasoClientCache,
|
||||||
|
clearUnityClientCache,
|
||||||
|
resolveCorpCluster,
|
||||||
|
|
||||||
|
// 6. assist-platform-client
|
||||||
|
createAssistPlatformClient,
|
||||||
|
|
||||||
|
// 7. sso-auth-client
|
||||||
|
createSsoAuthClient,
|
||||||
|
createSsoClient,
|
||||||
|
DEFAULT_SSO_BASE_URL,
|
||||||
|
} from "./index.js";
|
||||||
|
|
||||||
|
describe("core/http/clients-semantics - 7 大标准通信客户端语义规范验证", () => {
|
||||||
|
it("1. hose-web-session-client: 正确导出标准客户端工厂与请求头提取器", () => {
|
||||||
|
expect(createHoseWebSessionClient).toBeDefined();
|
||||||
|
expect(createSessionClient).toBe(createHoseWebSessionClient);
|
||||||
|
expect(getHoseWebSessionHeaders).toBeDefined();
|
||||||
|
expect(getSessionHeaders).toBe(getHoseWebSessionHeaders);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("2. openapi-client: 正确导出官方 OpenAPI 客户端工厂与请求头工具", () => {
|
||||||
|
expect(createOpenApiClient).toBeDefined();
|
||||||
|
expect(getOpenApiHeaders).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("3. piper-workflow-client: 正确导出工作流控制面与执行引擎客户端及缓存工具", () => {
|
||||||
|
expect(getPiperWorkflowClient).toBeDefined();
|
||||||
|
expect(getScriptEngineClient).toBe(getPiperWorkflowClient);
|
||||||
|
expect(clearPiperWorkflowClientCache).toBeDefined();
|
||||||
|
expect(clearScriptEngineClientCache).toBe(clearPiperWorkflowClientCache);
|
||||||
|
expect(PIPER_BASE_URL).toBe(SCRIPT_ENGINE_BASE_URL);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("4. hose-docs-client: 正确导出合思开放文档客户端", () => {
|
||||||
|
expect(createHoseDocsClient).toBeDefined();
|
||||||
|
expect(DEFAULT_HOSE_DOCS_BASE_URL).toBe("https://docs.ekuaibao.com");
|
||||||
|
const docsClient = createHoseDocsClient();
|
||||||
|
expect(docsClient).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("5. unity-easo-client: 正确导出运营中台与企业集群客户端", () => {
|
||||||
|
expect(getUnityEasoClient).toBeDefined();
|
||||||
|
expect(getUnityEasoClient).toBe(getUnityClient);
|
||||||
|
expect(getEasoClient).toBeDefined();
|
||||||
|
expect(clearUnityEasoClientCache).toBe(clearUnityClientCache);
|
||||||
|
expect(resolveCorpCluster).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("6. assist-platform-client: 正确导出协助运维平台客户端", () => {
|
||||||
|
expect(createAssistPlatformClient).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("7. sso-auth-client: 正确导出 SSO 与扫码鉴权客户端", () => {
|
||||||
|
expect(createSsoAuthClient).toBeDefined();
|
||||||
|
expect(createSsoAuthClient).toBe(createSsoClient);
|
||||||
|
expect(DEFAULT_SSO_BASE_URL).toBe("https://sso.hosecloud.com");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -8,14 +8,33 @@ import {
|
|||||||
import {
|
import {
|
||||||
getSessionHeaders,
|
getSessionHeaders,
|
||||||
createSessionClient,
|
createSessionClient,
|
||||||
} from "./session-client.js";
|
getHoseWebSessionHeaders,
|
||||||
|
createHoseWebSessionClient,
|
||||||
|
} from "./hose-web-session-client.js";
|
||||||
import {
|
import {
|
||||||
createOpenApiClient,
|
createOpenApiClient,
|
||||||
getOpenApiHeaders,
|
getOpenApiHeaders,
|
||||||
} from "./openapi-client.js";
|
} from "./openapi-client.js";
|
||||||
import { resolveCorpCluster, getEasoClient, getUnityClient, clearUnityClientCache } from "./unity-client.js";
|
import {
|
||||||
|
resolveCorpCluster,
|
||||||
|
getEasoClient,
|
||||||
|
getUnityClient,
|
||||||
|
getUnityEasoClient,
|
||||||
|
clearUnityClientCache,
|
||||||
|
} from "./unity-easo-client.js";
|
||||||
import { createAssistPlatformClient } from "./assist-platform-client.js";
|
import { createAssistPlatformClient } from "./assist-platform-client.js";
|
||||||
import { getScriptEngineClient } from "./script-engine-client.js";
|
import {
|
||||||
|
getScriptEngineClient,
|
||||||
|
getPiperWorkflowClient,
|
||||||
|
} from "./piper-workflow-client.js";
|
||||||
|
import {
|
||||||
|
createHoseDocsClient,
|
||||||
|
DEFAULT_HOSE_DOCS_BASE_URL,
|
||||||
|
} from "./hose-docs-client.js";
|
||||||
|
import {
|
||||||
|
createSsoAuthClient,
|
||||||
|
createSsoClient,
|
||||||
|
} from "./sso-auth-client.js";
|
||||||
import { setCorpTokens, resetTokenStoreMemory } from "../auth/token-store.js";
|
import { setCorpTokens, resetTokenStoreMemory } from "../auth/token-store.js";
|
||||||
import { mkdtempSync, rmSync } from "node:fs";
|
import { mkdtempSync, rmSync } from "node:fs";
|
||||||
import { tmpdir } from "node:os";
|
import { tmpdir } from "node:os";
|
||||||
@@ -47,63 +66,44 @@ describe("core/http/fingerprint", () => {
|
|||||||
expect(headers["sec-ch-ua"]).toContain("Chrome");
|
expect(headers["sec-ch-ua"]).toContain("Chrome");
|
||||||
expect(headers["Cookie"]).toBeUndefined();
|
expect(headers["Cookie"]).toBeUndefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("supports custom cookie and referer", () => {
|
|
||||||
const headers = getBrowserFingerprintHeaders({
|
|
||||||
cookie: "SESSION=abc123xyz; cloud_waf=token456",
|
|
||||||
referer: "https://custom.ekuaibao.com/flow",
|
|
||||||
});
|
|
||||||
expect(headers["Cookie"]).toBe("SESSION=abc123xyz; cloud_waf=token456");
|
|
||||||
expect(headers["Referer"]).toBe("https://custom.ekuaibao.com/flow");
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("core/http/session-client", () => {
|
describe("core/http/hose-web-session-client", () => {
|
||||||
it("merges closed session headers with browser fingerprint", () => {
|
it("injects valid session headers and preserves caller custom options", () => {
|
||||||
const corp = mockCorp();
|
const corp = mockCorp();
|
||||||
const headers = getSessionHeaders(corp);
|
const headers = getHoseWebSessionHeaders(corp, {
|
||||||
|
referer: "https://custom.ekuaibao.com",
|
||||||
|
});
|
||||||
|
|
||||||
// 核心三 Header 校验
|
expect(headers["accesstoken"]).toBe("mock-access-token");
|
||||||
expect(headers.accesstoken).toBe("mock-access-token");
|
expect(headers["corpid"]).toBe("mock-corp-id");
|
||||||
expect(headers.corpid).toBe("mock-corp-id");
|
expect(headers["staffid"]).toBe("mock-staff-id");
|
||||||
expect(headers.staffid).toBe("mock-staff-id");
|
expect(headers["Referer"]).toBe("https://custom.ekuaibao.com");
|
||||||
|
|
||||||
// 统一防爬指纹校验
|
|
||||||
expect(headers["User-Agent"]).toBe(DEFAULT_USER_AGENT);
|
|
||||||
expect(headers["Origin"]).toBe(DEFAULT_ORIGIN);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("createSessionClient produces valid client", async () => {
|
it("createHoseWebSessionClient is callable and aliased to createSessionClient", async () => {
|
||||||
const corp = mockCorp();
|
const corp = mockCorp();
|
||||||
const client = await createSessionClient(corp);
|
const client = await createHoseWebSessionClient(corp);
|
||||||
expect(client).toBeDefined();
|
expect(client).toBeDefined();
|
||||||
|
expect(createSessionClient).toBe(createHoseWebSessionClient);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("core/http/openapi-client", () => {
|
describe("core/http/openapi-client", () => {
|
||||||
it("builds correct OpenAPI request headers", () => {
|
it("formats standard Bearer authorization header", () => {
|
||||||
const headers = getOpenApiHeaders("test-app-token-123");
|
const headers = getOpenApiHeaders("valid-mock-token");
|
||||||
expect(headers["app-token"]).toBe("test-app-token-123");
|
expect(headers["Authorization"]).toBe("Bearer valid-mock-token");
|
||||||
expect(headers["Authorization"]).toBe("Bearer test-app-token-123");
|
expect(headers["app-token"]).toBe("valid-mock-token");
|
||||||
expect(headers["User-Agent"]).toBe(DEFAULT_USER_AGENT);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("creates OpenAPI client with static appToken", async () => {
|
it("throws ValidationError when both auth and appToken are missing", async () => {
|
||||||
const client = await createOpenApiClient({
|
|
||||||
appToken: "static-token",
|
|
||||||
baseUrl: "https://app.ekuaibao.com",
|
|
||||||
});
|
|
||||||
expect(client).toBeDefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("fails to create OpenAPI client when neither auth nor appToken is provided", async () => {
|
|
||||||
await expect(createOpenApiClient({})).rejects.toThrow(
|
await expect(createOpenApiClient({})).rejects.toThrow(
|
||||||
"创建 OpenAPI 客户端失败: 必须提供 auth 凭据或 appToken"
|
"创建 OpenAPI 客户端失败: 必须提供 auth 凭据或 appToken"
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("core/http/unity-client & script-engine-client", () => {
|
describe("core/http/unity-easo-client & piper-workflow-client", () => {
|
||||||
it("resolves corp cluster from cluster property or baseUrl", () => {
|
it("resolves corp cluster from cluster property or baseUrl", () => {
|
||||||
expect(resolveCorpCluster({ cluster: "shanghai" })).toBe("shanghai");
|
expect(resolveCorpCluster({ cluster: "shanghai" })).toBe("shanghai");
|
||||||
expect(resolveCorpCluster({ baseUrl: "https://wx2.ekuaibao.com" })).toBe("wx2");
|
expect(resolveCorpCluster({ baseUrl: "https://wx2.ekuaibao.com" })).toBe("wx2");
|
||||||
@@ -111,8 +111,14 @@ describe("core/http/unity-client & script-engine-client", () => {
|
|||||||
expect(resolveCorpCluster({})).toBe("app");
|
expect(resolveCorpCluster({})).toBe("app");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("getScriptEngineClient is defined and callable", () => {
|
it("getPiperWorkflowClient is defined and callable (aliased to getScriptEngineClient)", () => {
|
||||||
expect(getScriptEngineClient).toBeDefined();
|
expect(getPiperWorkflowClient).toBeDefined();
|
||||||
|
expect(getScriptEngineClient).toBe(getPiperWorkflowClient);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("getUnityEasoClient is defined and aliased to getUnityClient", () => {
|
||||||
|
expect(getUnityEasoClient).toBeDefined();
|
||||||
|
expect(getUnityEasoClient).toBe(getUnityClient);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("reuses persisted EASO and Unity tokens from token-store across CLI runs without network calls", async () => {
|
it("reuses persisted EASO and Unity tokens from token-store across CLI runs without network calls", async () => {
|
||||||
@@ -171,3 +177,17 @@ describe("core/http/unity-client & script-engine-client", () => {
|
|||||||
}).toThrow("协助平台凭证已过期或无效,请运行: hose-use assist-platform login 重新扫码登录");
|
}).toThrow("协助平台凭证已过期或无效,请运行: hose-use assist-platform login 重新扫码登录");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("core/http/hose-docs-client & sso-auth-client", () => {
|
||||||
|
it("createHoseDocsClient constructs with default base URL and docs user-agent", () => {
|
||||||
|
const client = createHoseDocsClient();
|
||||||
|
expect(client).toBeDefined();
|
||||||
|
expect(DEFAULT_HOSE_DOCS_BASE_URL).toBe("https://docs.ekuaibao.com");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("createSsoAuthClient is aliased to createSsoClient and instantiates correctly", () => {
|
||||||
|
expect(createSsoAuthClient).toBe(createSsoClient);
|
||||||
|
const ssoClient = createSsoAuthClient();
|
||||||
|
expect(ssoClient).toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import ky, { type KyInstance } from "ky";
|
||||||
|
|
||||||
|
export const DEFAULT_HOSE_DOCS_BASE_URL = "https://docs.ekuaibao.com";
|
||||||
|
|
||||||
|
export interface CreateHoseDocsClientOptions {
|
||||||
|
/** 文档站点基础地址 (默认 https://docs.ekuaibao.com) */
|
||||||
|
baseUrl?: string;
|
||||||
|
/** 超时毫秒数 (默认 15000) */
|
||||||
|
timeout?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建合思开放文档客户端 (Hose Open Docs Client)
|
||||||
|
* 直连合思官方开放平台接口文档中心 (docs.ekuaibao.com),
|
||||||
|
* 负责在线检索与拉取全量 8.4MB 接口索引,自省 330 篇文档与 270+ HTTP OpenAPI 规范。
|
||||||
|
*/
|
||||||
|
export function createHoseDocsClient(
|
||||||
|
options: CreateHoseDocsClientOptions = {}
|
||||||
|
): KyInstance {
|
||||||
|
const baseUrl = options.baseUrl || DEFAULT_HOSE_DOCS_BASE_URL;
|
||||||
|
return ky.create({
|
||||||
|
prefix: baseUrl.replace(/\/+$/, ""),
|
||||||
|
timeout: options.timeout ?? 15000,
|
||||||
|
headers: {
|
||||||
|
Accept: "application/json",
|
||||||
|
"User-Agent": "hose-use/docs-client",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
+2
-2
@@ -10,7 +10,7 @@ import {
|
|||||||
resolveLinkExpiresAt,
|
resolveLinkExpiresAt,
|
||||||
selectOpenApiKey,
|
selectOpenApiKey,
|
||||||
} from "../auth/login.js";
|
} from "../auth/login.js";
|
||||||
import { createSessionClient } from "./session-client.js";
|
import { createSessionClient } from "./hose-web-session-client.js";
|
||||||
import type { CorpConfig } from "../config/types.js";
|
import type { CorpConfig } from "../config/types.js";
|
||||||
|
|
||||||
function corp(overrides: Partial<CorpConfig> = {}): CorpConfig {
|
function corp(overrides: Partial<CorpConfig> = {}): CorpConfig {
|
||||||
@@ -24,7 +24,7 @@ function corp(overrides: Partial<CorpConfig> = {}): CorpConfig {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
describe("core/http/session-client refresh policy", () => {
|
describe("core/http/hose-web-session-client refresh policy", () => {
|
||||||
it("allows refresh for account credentials or OpenAPI persistent credentials", () => {
|
it("allows refresh for account credentials or OpenAPI persistent credentials", () => {
|
||||||
expect(canRefreshCorpAccessToken(corp())).toBe(false);
|
expect(canRefreshCorpAccessToken(corp())).toBe(false);
|
||||||
expect(canRefreshCorpAccessToken(corp({ source: "browser", accountId: "86-1" }))).toBe(false);
|
expect(canRefreshCorpAccessToken(corp({ source: "browser", accountId: "86-1" }))).toBe(false);
|
||||||
@@ -10,17 +10,19 @@ import {
|
|||||||
refreshSingleCorpAccessToken,
|
refreshSingleCorpAccessToken,
|
||||||
} from "../auth/login.js";
|
} from "../auth/login.js";
|
||||||
|
|
||||||
export interface CreateSessionClientOptions {
|
export interface CreateHoseWebSessionClientOptions {
|
||||||
/** 额外的指纹或请求头配置 */
|
/** 额外的指纹或请求头配置 */
|
||||||
fingerprint?: BrowserFingerprintOptions;
|
fingerprint?: BrowserFingerprintOptions;
|
||||||
/** 超时毫秒数 (默认 30000) */
|
/** 超时毫秒数 (默认 30000) */
|
||||||
timeout?: number | false;
|
timeout?: number | false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type CreateSessionClientOptions = CreateHoseWebSessionClientOptions;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取闭合用户会话所必需的认证请求头与浏览器指纹
|
* 获取合思 Web 主站会话所必需的认证请求头与浏览器指纹
|
||||||
*/
|
*/
|
||||||
export function getSessionHeaders(
|
export function getHoseWebSessionHeaders(
|
||||||
corp: CorpConfig,
|
corp: CorpConfig,
|
||||||
fingerprintOptions?: BrowserFingerprintOptions
|
fingerprintOptions?: BrowserFingerprintOptions
|
||||||
): Record<string, string> {
|
): Record<string, string> {
|
||||||
@@ -34,13 +36,16 @@ export function getSessionHeaders(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const getSessionHeaders = getHoseWebSessionHeaders;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 创建合思闭合用户会话客户端 (Session Client)
|
* 创建合思 Web 主站用户会话客户端 (Hose Web Session Client)
|
||||||
* 适用于内部单据台账、审批流、员工角色、配置等闭环操作
|
* 直连合思主站 (app.ekuaibao.com),承载单据台账、报销审批流、
|
||||||
|
* 费用类型科目、员工通讯录等闭环操作,带 Cookie/Token 双通道自动续期与 401 重试。
|
||||||
*/
|
*/
|
||||||
export async function createSessionClient(
|
export async function createHoseWebSessionClient(
|
||||||
corp: CorpConfig,
|
corp: CorpConfig,
|
||||||
options: CreateSessionClientOptions = {}
|
options: CreateHoseWebSessionClientOptions = {}
|
||||||
) {
|
) {
|
||||||
const canRefresh = canRefreshCorpAccessToken(corp);
|
const canRefresh = canRefreshCorpAccessToken(corp);
|
||||||
|
|
||||||
@@ -56,7 +61,7 @@ export async function createSessionClient(
|
|||||||
// 2. 具备续期能力(主账号或 OpenAPI 持久化密钥)时启用 401 自动重试与换票;临时凭证直接给出可操作错误
|
// 2. 具备续期能力(主账号或 OpenAPI 持久化密钥)时启用 401 自动重试与换票;临时凭证直接给出可操作错误
|
||||||
return createAuthClient({
|
return createAuthClient({
|
||||||
prefixUrl: corp.baseUrl || "https://app.ekuaibao.com",
|
prefixUrl: corp.baseUrl || "https://app.ekuaibao.com",
|
||||||
getHeaders: () => getSessionHeaders(corp, options.fingerprint),
|
getHeaders: () => getHoseWebSessionHeaders(corp, options.fingerprint),
|
||||||
timeout: options.timeout,
|
timeout: options.timeout,
|
||||||
retryUnauthorized: canRefresh,
|
retryUnauthorized: canRefresh,
|
||||||
...(canRefresh
|
...(canRefresh
|
||||||
@@ -71,3 +76,5 @@ export async function createSessionClient(
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const createSessionClient = createHoseWebSessionClient;
|
||||||
+62
-12
@@ -1,9 +1,16 @@
|
|||||||
/**
|
/**
|
||||||
* HTTP 客户端基础设施总入口
|
* HTTP 客户端基础设施总入口
|
||||||
* 包含基础 Ky 客户端工厂、浏览器指纹伪装、闭合用户会话客户端、开放平台客户端、集群客户端及脚本流引擎客户端。
|
* 统一管理 7 大核心通信客户端:
|
||||||
|
* 1. hose-web-session-client (合思 Web 主站会话客户端,打 app.ekuaibao.com)
|
||||||
|
* 2. openapi-client (开放平台官方 OpenAPI 客户端,打开放标准接口)
|
||||||
|
* 3. piper-workflow-client (Piper 工作流引擎客户端,打 piper.ekuaibao.com 工作流全生命周期)
|
||||||
|
* 4. hose-docs-client (合思开放文档客户端,打 docs.ekuaibao.com 接口自省与同步)
|
||||||
|
* 5. unity-easo-client (Unity / EASO 运营中台客户端,企业集群寻址与全局换票)
|
||||||
|
* 6. assist-platform-client (合思协助平台客户端,代客工单免密直通)
|
||||||
|
* 7. sso-auth-client (SSO 与扫码鉴权客户端,单点登录与扫码认证)
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// 1. 底层 Ky 基础工厂
|
// ── 基础工厂与指纹 ─────────────────────────────────────────────────────────────
|
||||||
export {
|
export {
|
||||||
createClient,
|
createClient,
|
||||||
createAuthClient,
|
createAuthClient,
|
||||||
@@ -11,7 +18,6 @@ export {
|
|||||||
type CreateAuthClientOptions,
|
type CreateAuthClientOptions,
|
||||||
} from "./factory.js";
|
} from "./factory.js";
|
||||||
|
|
||||||
// 2. 统一浏览器指纹与防爬请求头
|
|
||||||
export {
|
export {
|
||||||
getBrowserFingerprintHeaders,
|
getBrowserFingerprintHeaders,
|
||||||
DEFAULT_USER_AGENT,
|
DEFAULT_USER_AGENT,
|
||||||
@@ -20,14 +26,17 @@ export {
|
|||||||
type BrowserFingerprintOptions,
|
type BrowserFingerprintOptions,
|
||||||
} from "./fingerprint.js";
|
} from "./fingerprint.js";
|
||||||
|
|
||||||
// 3. 闭合用户会话客户端 (Session Client)
|
// ── 1. 合思 Web 主站会话客户端 (hose-web-session-client) ──────────────────────
|
||||||
export {
|
export {
|
||||||
|
createHoseWebSessionClient,
|
||||||
createSessionClient,
|
createSessionClient,
|
||||||
|
getHoseWebSessionHeaders,
|
||||||
getSessionHeaders,
|
getSessionHeaders,
|
||||||
|
type CreateHoseWebSessionClientOptions,
|
||||||
type CreateSessionClientOptions,
|
type CreateSessionClientOptions,
|
||||||
} from "./session-client.js";
|
} from "./hose-web-session-client.js";
|
||||||
|
|
||||||
// 4. 开放平台 OpenAPI 客户端 (OpenAPI Client)
|
// ── 2. 开放平台官方 OpenAPI 客户端 (openapi-client) ───────────────────────────
|
||||||
export {
|
export {
|
||||||
createOpenApiClient,
|
createOpenApiClient,
|
||||||
fetchOpenApiToken,
|
fetchOpenApiToken,
|
||||||
@@ -36,17 +45,58 @@ export {
|
|||||||
type CreateOpenApiClientOptions,
|
type CreateOpenApiClientOptions,
|
||||||
} from "./openapi-client.js";
|
} from "./openapi-client.js";
|
||||||
|
|
||||||
// 5. 应用中心与集群寻址客户端 (Unity Client)
|
// ── 3. Piper 工作流引擎客户端 (piper-workflow-client) ─────────────────────────
|
||||||
export {
|
export {
|
||||||
|
getPiperWorkflowClient,
|
||||||
|
getScriptEngineClient,
|
||||||
|
clearPiperWorkflowClientCache,
|
||||||
|
clearScriptEngineClientCache,
|
||||||
|
fetchEasoJwt,
|
||||||
|
resolvePiperBaseUrl,
|
||||||
|
PIPER_BASE_URL,
|
||||||
|
SCRIPT_ENGINE_BASE_URL,
|
||||||
|
SCRIPT_ENGINE_TEST_BASE_URL,
|
||||||
|
} from "./piper-workflow-client.js";
|
||||||
|
|
||||||
|
// ── 4. 合思开放文档客户端 (hose-docs-client) ──────────────────────────────────
|
||||||
|
export {
|
||||||
|
createHoseDocsClient,
|
||||||
|
DEFAULT_HOSE_DOCS_BASE_URL,
|
||||||
|
type CreateHoseDocsClientOptions,
|
||||||
|
} from "./hose-docs-client.js";
|
||||||
|
|
||||||
|
// ── 5. Unity / EASO 运营中台客户端 (unity-easo-client) ────────────────────────
|
||||||
|
export {
|
||||||
|
getUnityEasoClient,
|
||||||
getUnityClient,
|
getUnityClient,
|
||||||
getEasoClient,
|
getEasoClient,
|
||||||
resolveCorpCluster,
|
resolveCorpCluster,
|
||||||
fetchUnityJwt,
|
fetchUnityJwt,
|
||||||
fetchHoseToken,
|
fetchHoseToken,
|
||||||
} from "./unity-client.js";
|
clearUnityEasoClientCache,
|
||||||
|
clearUnityClientCache,
|
||||||
|
EASO_BASE_URL,
|
||||||
|
BUSINESS_CENTER_URL,
|
||||||
|
EKB_BASE_URL,
|
||||||
|
} from "./unity-easo-client.js";
|
||||||
|
|
||||||
// 6. 工作流脚本调试引擎客户端 (Script Engine Client)
|
// ── 6. 合思协助平台客户端 (assist-platform-client) ────────────────────────────
|
||||||
export {
|
export {
|
||||||
getScriptEngineClient,
|
createAssistPlatformClient,
|
||||||
fetchEasoJwt,
|
type AssistPlatformClientOptions,
|
||||||
} from "./script-engine-client.js";
|
type CreateAssistPlatformClientOptions,
|
||||||
|
} from "./assist-platform-client.js";
|
||||||
|
|
||||||
|
// ── 7. SSO 与扫码鉴权客户端 (sso-auth-client) ─────────────────────────────────
|
||||||
|
export {
|
||||||
|
createSsoAuthClient,
|
||||||
|
createSsoClient,
|
||||||
|
getSsoQrCode,
|
||||||
|
pollSsoQrCodeStatus,
|
||||||
|
verifySsoTokenOnUnity,
|
||||||
|
DEFAULT_SSO_BASE_URL,
|
||||||
|
type SsoAuthClientOptions,
|
||||||
|
type SsoClientOptions,
|
||||||
|
type SsoQrCodeResult,
|
||||||
|
type QrCodeStatusResponse,
|
||||||
|
} from "./sso-auth-client.js";
|
||||||
@@ -6,7 +6,7 @@ import {
|
|||||||
resolveCorpCluster,
|
resolveCorpCluster,
|
||||||
fetchHoseToken,
|
fetchHoseToken,
|
||||||
EKB_BASE_URL,
|
EKB_BASE_URL,
|
||||||
} from "./unity-client.js";
|
} from "./unity-easo-client.js";
|
||||||
import {
|
import {
|
||||||
canRefreshCorpAccessToken,
|
canRefreshCorpAccessToken,
|
||||||
refreshSingleCorpAccessToken,
|
refreshSingleCorpAccessToken,
|
||||||
@@ -32,19 +32,19 @@ export {
|
|||||||
export const PIPER_BASE_URL = SCRIPT_ENGINE_BASE_URL;
|
export const PIPER_BASE_URL = SCRIPT_ENGINE_BASE_URL;
|
||||||
|
|
||||||
// 内存缓存
|
// 内存缓存
|
||||||
const scriptEngineMemoryCache = new Map<
|
const piperWorkflowMemoryCache = new Map<
|
||||||
string,
|
string,
|
||||||
{ jwt: string; hoseToken: string; expiresAt: number; sourceAccessToken?: string }
|
{ jwt: string; hoseToken: string; expiresAt: number; sourceAccessToken?: string }
|
||||||
>();
|
>();
|
||||||
|
|
||||||
function invalidateScriptEngineCache(corpId: string, cacheKey?: string): void {
|
function invalidatePiperWorkflowCache(corpId: string, cacheKey?: string): void {
|
||||||
if (cacheKey) {
|
if (cacheKey) {
|
||||||
scriptEngineMemoryCache.delete(cacheKey);
|
piperWorkflowMemoryCache.delete(cacheKey);
|
||||||
} else {
|
} else {
|
||||||
const prefix = `${corpId}:`;
|
const prefix = `${corpId}:`;
|
||||||
for (const key of scriptEngineMemoryCache.keys()) {
|
for (const key of piperWorkflowMemoryCache.keys()) {
|
||||||
if (key.startsWith(prefix)) {
|
if (key.startsWith(prefix)) {
|
||||||
scriptEngineMemoryCache.delete(key);
|
piperWorkflowMemoryCache.delete(key);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -56,14 +56,16 @@ function invalidateScriptEngineCache(corpId: string, cacheKey?: string): void {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function clearScriptEngineClientCache(corpId?: string): void {
|
export function clearPiperWorkflowClientCache(corpId?: string): void {
|
||||||
if (!corpId) {
|
if (!corpId) {
|
||||||
scriptEngineMemoryCache.clear();
|
piperWorkflowMemoryCache.clear();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
invalidateScriptEngineCache(corpId);
|
invalidatePiperWorkflowCache(corpId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const clearScriptEngineClientCache = clearPiperWorkflowClientCache;
|
||||||
|
|
||||||
function isExpired(entry: { expiresAt: number }, refreshTtl: number): boolean {
|
function isExpired(entry: { expiresAt: number }, refreshTtl: number): boolean {
|
||||||
return Date.now() >= entry.expiresAt - refreshTtl * 1000;
|
return Date.now() >= entry.expiresAt - refreshTtl * 1000;
|
||||||
}
|
}
|
||||||
@@ -92,18 +94,22 @@ export async function fetchEasoJwt(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取工作流脚本执行引擎客户端 (Workflow Script Engine Client / Piper Client)
|
* 获取 Piper 工作流引擎客户端 (Piper Workflow Engine Client)
|
||||||
* 适用于 MVEL、Python 等工作流代码节点的在线执行与调试
|
* 直连 piper.ekuaibao.com,作为合思自建应用工作流的核心控制面与执行引擎:
|
||||||
|
* - 工作流全生命周期:创建、重命名、全量节点草稿保存、自动生成 chooses 元数据、复制与快照版本历史;
|
||||||
|
* - 全量节点编排调度:触发器、HTTP 出向请求、分支判断、审批流重算、通知与代码节点;
|
||||||
|
* - 节点能力字典与灰度:108 个底层工作流节点能力的声明探查与灰度开通;
|
||||||
|
* - 流转实例与执行监控:Job 运行实例排查、Tasks 任务流链路跟踪与 MVEL/Python 代码沙箱单步调试。
|
||||||
*/
|
*/
|
||||||
export async function getScriptEngineClient(
|
export async function getPiperWorkflowClient(
|
||||||
corp: CorpConfig,
|
corp: CorpConfig,
|
||||||
platformId: string
|
platformId: string
|
||||||
): Promise<ReturnType<typeof createAuthClient>> {
|
): Promise<ReturnType<typeof createAuthClient>> {
|
||||||
const refreshTtl = corp.auth?.refreshTtl ?? 300;
|
const refreshTtl = corp.auth?.refreshTtl ?? 300;
|
||||||
const cacheKey = `${corp.id}:${platformId}:script-engine`;
|
const cacheKey = `${corp.id}:${platformId}:piper-workflow`;
|
||||||
|
|
||||||
// 1. 检查 L1 内存缓存
|
// 1. 检查 L1 内存缓存
|
||||||
let mem = scriptEngineMemoryCache.get(cacheKey);
|
let mem = piperWorkflowMemoryCache.get(cacheKey);
|
||||||
|
|
||||||
// 2. 检查 L2 持久化 TokenStore
|
// 2. 检查 L2 持久化 TokenStore
|
||||||
if (!mem) {
|
if (!mem) {
|
||||||
@@ -119,7 +125,7 @@ export async function getScriptEngineClient(
|
|||||||
expiresAt: persisted.expiresAt,
|
expiresAt: persisted.expiresAt,
|
||||||
sourceAccessToken: persisted.sourceAccessToken,
|
sourceAccessToken: persisted.sourceAccessToken,
|
||||||
};
|
};
|
||||||
scriptEngineMemoryCache.set(cacheKey, mem);
|
piperWorkflowMemoryCache.set(cacheKey, mem);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -130,19 +136,19 @@ export async function getScriptEngineClient(
|
|||||||
prefixUrl: resolvePiperBaseUrl(),
|
prefixUrl: resolvePiperBaseUrl(),
|
||||||
getHeaders: () => {
|
getHeaders: () => {
|
||||||
const headers: Record<string, string> = {
|
const headers: Record<string, string> = {
|
||||||
Authorization: `Bearer ${scriptEngineMemoryCache.get(cacheKey)?.jwt ?? cachedJwt}`,
|
Authorization: `Bearer ${piperWorkflowMemoryCache.get(cacheKey)?.jwt ?? cachedJwt}`,
|
||||||
platformid: platformId,
|
platformid: platformId,
|
||||||
};
|
};
|
||||||
const currentHoseToken = scriptEngineMemoryCache.get(cacheKey)?.hoseToken ?? cachedHoseToken;
|
const currentHoseToken = piperWorkflowMemoryCache.get(cacheKey)?.hoseToken ?? cachedHoseToken;
|
||||||
if (currentHoseToken) {
|
if (currentHoseToken) {
|
||||||
headers.hoseaccesstoken = currentHoseToken;
|
headers.hoseaccesstoken = currentHoseToken;
|
||||||
}
|
}
|
||||||
return headers;
|
return headers;
|
||||||
},
|
},
|
||||||
onUnauthorized: async () => {
|
onUnauthorized: async () => {
|
||||||
invalidateScriptEngineCache(corp.id, cacheKey);
|
invalidatePiperWorkflowCache(corp.id, cacheKey);
|
||||||
if (canRefreshCorpAccessToken(corp)) await refreshSingleCorpAccessToken(corp);
|
if (canRefreshCorpAccessToken(corp)) await refreshSingleCorpAccessToken(corp);
|
||||||
await getScriptEngineClient(corp, platformId);
|
await getPiperWorkflowClient(corp, platformId);
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -169,7 +175,7 @@ export async function getScriptEngineClient(
|
|||||||
);
|
);
|
||||||
} catch {
|
} catch {
|
||||||
// 独立私有化域名或部分仅持 OpenAPI 凭证的租户在 business-center 换取 hose-access-token 可能受限,
|
// 独立私有化域名或部分仅持 OpenAPI 凭证的租户在 business-center 换取 hose-access-token 可能受限,
|
||||||
// 此处优雅降级避免阻塞 Piper / ScriptEngine 客户端构建
|
// 此处优雅降级避免阻塞 Piper / Workflow 客户端构建
|
||||||
}
|
}
|
||||||
const easoJwt = await fetchEasoJwt(
|
const easoJwt = await fetchEasoJwt(
|
||||||
corp.credentials.accessToken,
|
corp.credentials.accessToken,
|
||||||
@@ -186,7 +192,7 @@ export async function getScriptEngineClient(
|
|||||||
sourceAccessToken: corp.credentials.accessToken,
|
sourceAccessToken: corp.credentials.accessToken,
|
||||||
};
|
};
|
||||||
|
|
||||||
scriptEngineMemoryCache.set(cacheKey, entry);
|
piperWorkflowMemoryCache.set(cacheKey, entry);
|
||||||
|
|
||||||
const existingTokens = getCorpTokens(corp.id) ?? {};
|
const existingTokens = getCorpTokens(corp.id) ?? {};
|
||||||
setCorpTokens(corp.id, {
|
setCorpTokens(corp.id, {
|
||||||
@@ -203,19 +209,21 @@ export async function getScriptEngineClient(
|
|||||||
prefixUrl: SCRIPT_ENGINE_BASE_URL,
|
prefixUrl: SCRIPT_ENGINE_BASE_URL,
|
||||||
getHeaders: () => {
|
getHeaders: () => {
|
||||||
const headers: Record<string, string> = {
|
const headers: Record<string, string> = {
|
||||||
Authorization: `Bearer ${scriptEngineMemoryCache.get(cacheKey)?.jwt ?? easoJwt}`,
|
Authorization: `Bearer ${piperWorkflowMemoryCache.get(cacheKey)?.jwt ?? easoJwt}`,
|
||||||
platformid: platformId,
|
platformid: platformId,
|
||||||
};
|
};
|
||||||
const currentHoseToken = scriptEngineMemoryCache.get(cacheKey)?.hoseToken ?? hoseToken;
|
const currentHoseToken = piperWorkflowMemoryCache.get(cacheKey)?.hoseToken ?? hoseToken;
|
||||||
if (currentHoseToken) {
|
if (currentHoseToken) {
|
||||||
headers.hoseaccesstoken = currentHoseToken;
|
headers.hoseaccesstoken = currentHoseToken;
|
||||||
}
|
}
|
||||||
return headers;
|
return headers;
|
||||||
},
|
},
|
||||||
onUnauthorized: async () => {
|
onUnauthorized: async () => {
|
||||||
invalidateScriptEngineCache(corp.id, cacheKey);
|
invalidatePiperWorkflowCache(corp.id, cacheKey);
|
||||||
if (canRefreshCorpAccessToken(corp)) await refreshSingleCorpAccessToken(corp);
|
if (canRefreshCorpAccessToken(corp)) await refreshSingleCorpAccessToken(corp);
|
||||||
await getScriptEngineClient(corp, platformId);
|
await getPiperWorkflowClient(corp, platformId);
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const getScriptEngineClient = getPiperWorkflowClient;
|
||||||
@@ -4,10 +4,10 @@ import {
|
|||||||
getSsoQrCode,
|
getSsoQrCode,
|
||||||
pollSsoQrCodeStatus,
|
pollSsoQrCodeStatus,
|
||||||
verifySsoTokenOnUnity,
|
verifySsoTokenOnUnity,
|
||||||
} from "./sso-client.js";
|
} from "./sso-auth-client.js";
|
||||||
import { AuthenticationError } from "../errors.js";
|
import { AuthenticationError } from "../errors.js";
|
||||||
|
|
||||||
describe("core/http/sso-client", () => {
|
describe("core/http/sso-auth-client", () => {
|
||||||
it("getSsoQrCode 能够正常解析二维码链接与 Session Cookie", async () => {
|
it("getSsoQrCode 能够正常解析二维码链接与 Session Cookie", async () => {
|
||||||
const mockClient = {
|
const mockClient = {
|
||||||
post: async () => ({
|
post: async () => ({
|
||||||
@@ -8,6 +8,8 @@ export interface SsoClientOptions {
|
|||||||
timeout?: number;
|
timeout?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type SsoAuthClientOptions = SsoClientOptions;
|
||||||
|
|
||||||
export function createSsoClient(options: SsoClientOptions = {}): KyInstance {
|
export function createSsoClient(options: SsoClientOptions = {}): KyInstance {
|
||||||
const baseUrl = options.baseUrl || DEFAULT_SSO_BASE_URL;
|
const baseUrl = options.baseUrl || DEFAULT_SSO_BASE_URL;
|
||||||
return ky.create({
|
return ky.create({
|
||||||
@@ -15,12 +17,16 @@ export function createSsoClient(options: SsoClientOptions = {}): KyInstance {
|
|||||||
timeout: options.timeout ?? 15000,
|
timeout: options.timeout ?? 15000,
|
||||||
headers: {
|
headers: {
|
||||||
accept: "application/json, text/plain, */*",
|
accept: "application/json, text/plain, */*",
|
||||||
"user-agent": "hose-use/assist-platform-client",
|
"user-agent": "hose-use/sso-auth-client",
|
||||||
referer: `${baseUrl}/`,
|
referer: `${baseUrl}/`,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 语义化标准别名 (SSO 与扫码鉴权客户端) */
|
||||||
|
export const createSsoAuthClient = createSsoClient;
|
||||||
|
|
||||||
|
|
||||||
export interface QrCodeStatusResponse {
|
export interface QrCodeStatusResponse {
|
||||||
code: number;
|
code: number;
|
||||||
message: string;
|
message: string;
|
||||||
@@ -2,8 +2,8 @@ import { afterEach, expect, test } from "bun:test";
|
|||||||
import { mkdtempSync } from "node:fs";
|
import { mkdtempSync } from "node:fs";
|
||||||
import { tmpdir } from "node:os";
|
import { tmpdir } from "node:os";
|
||||||
import { join } from "node:path";
|
import { join } from "node:path";
|
||||||
import { getEasoClient, getUnityClient, clearUnityClientCache } from "./unity-client.js";
|
import { getEasoClient, getUnityClient, clearUnityClientCache } from "./unity-easo-client.js";
|
||||||
import { getScriptEngineClient, clearScriptEngineClientCache } from "./script-engine-client.js";
|
import { getScriptEngineClient, clearScriptEngineClientCache } from "./piper-workflow-client.js";
|
||||||
import { resetTokenStoreMemory, setCorpTokens } from "../auth/token-store.js";
|
import { resetTokenStoreMemory, setCorpTokens } from "../auth/token-store.js";
|
||||||
const oldFetch = globalThis.fetch, oldFile = process.env.HOSE_TOKENS_FILE;
|
const oldFetch = globalThis.fetch, oldFile = process.env.HOSE_TOKENS_FILE;
|
||||||
afterEach(() => { clearScriptEngineClientCache(); clearUnityClientCache(); resetTokenStoreMemory(); globalThis.fetch = oldFetch; if (oldFile === undefined) delete process.env.HOSE_TOKENS_FILE; else process.env.HOSE_TOKENS_FILE = oldFile; });
|
afterEach(() => { clearScriptEngineClientCache(); clearUnityClientCache(); resetTokenStoreMemory(); globalThis.fetch = oldFetch; if (oldFile === undefined) delete process.env.HOSE_TOKENS_FILE; else process.env.HOSE_TOKENS_FILE = oldFile; });
|
||||||
|
|||||||
@@ -403,3 +403,8 @@ export async function getUnityClient(corp: CorpConfig): Promise<{
|
|||||||
}),
|
}),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 语义化标准别名 (Unity EASO 运营中台客户端) */
|
||||||
|
export const getUnityEasoClient = getUnityClient;
|
||||||
|
export const clearUnityEasoClientCache = clearUnityClientCache;
|
||||||
|
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
本目录按业务域组织代码,每个域独立负责自己的传输层(`api.ts`)、业务编排层(`tools.ts` / `services.ts`)和模型层(`types.ts`)。
|
本目录按业务域组织代码,每个域独立负责自己的传输层(`api.ts`)、业务编排层(`tools.ts` / `services.ts`)和模型层(`types.ts`)。
|
||||||
|
|
||||||
## 当前域(共 14 个)
|
## 当前域(共 15 个)
|
||||||
|
|
||||||
| 域 | 内部形态 | 说明 | 详细文档 |
|
| 域 | 内部形态 | 说明 | 详细文档 |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
@@ -20,10 +20,11 @@
|
|||||||
| `message/` | `api / tools / types` | 系统通知消息分页查询与已读状态标记 | [README.message.md](./message/README.message.md) |
|
| `message/` | `api / tools / types` | 系统通知消息分页查询与已读状态标记 | [README.message.md](./message/README.message.md) |
|
||||||
| `task/` | `api / tools / types` | 待办/已办审批任务流分页查询与汇总 | [README.task.md](./task/README.task.md) |
|
| `task/` | `api / tools / types` | 待办/已办审批任务流分页查询与汇总 | [README.task.md](./task/README.task.md) |
|
||||||
| `events/` | `poller / store / types` | 待办与未读消息增量事件轮询及基于 `core/db` (`observed_events`) 的去重存储 | [README.events.md](./events/README.events.md) |
|
| `events/` | `poller / store / types` | 待办与未读消息增量事件轮询及基于 `core/db` (`observed_events`) 的去重存储 | [README.events.md](./events/README.events.md) |
|
||||||
|
| `docs/` | `api / tools / types` | 合思开放平台官方文档中心(270+ API 端点)在线实时拉取、离线缓存与参数规格检索 | [README.docs.md](./docs/README.docs.md) |
|
||||||
|
|
||||||
## 分层与形态规则
|
## 分层与形态规则
|
||||||
|
|
||||||
1. **标准三件套形态**(`contact`, `dimension`, `feetype`, `menu`, `message`, `permission`, `role`, `store`, `task`):
|
1. **标准三件套形态**(`contact`, `dimension`, `docs`, `feetype`, `menu`, `message`, `permission`, `role`, `store`, `task`):
|
||||||
- `api.ts`:只负责 HTTP 请求和响应校验
|
- `api.ts`:只负责 HTTP 请求和响应校验
|
||||||
- `tools.ts`:纯函数式业务编排,供 CLI 命令(`src/cli/commands/*`)调用
|
- `tools.ts`:纯函数式业务编排,供 CLI 命令(`src/cli/commands/*`)调用
|
||||||
- `types.ts`:Zod schema 与类型定义
|
- `types.ts`:Zod schema 与类型定义
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
## 架构与分工
|
## 架构与分工
|
||||||
|
|
||||||
- **SSO 身份客户端 (`src/core/http/sso-client.ts`)**:
|
- **SSO 身份客户端 (`src/core/http/sso-auth-client.ts`)**:
|
||||||
负责与 `sso.hosecloud.com` 的登录二维码生成、扫码状态轮询以及凭证提取。
|
负责与 `sso.hosecloud.com` 的登录二维码生成、扫码状态轮询以及凭证提取。
|
||||||
- **协助平台网关客户端 (`src/core/http/assist-platform-client.ts`)**:
|
- **协助平台网关客户端 (`src/core/http/assist-platform-client.ts`)**:
|
||||||
负责与 `unity.ekuaibao.com/api` 网关通信,自动挂载 `token: <sessionToken>` 请求头与 Cookie。
|
负责与 `unity.ekuaibao.com/api` 网关通信,自动挂载 `token: <sessionToken>` 请求头与 Cookie。
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import {
|
|||||||
getSsoQrCode,
|
getSsoQrCode,
|
||||||
pollSsoQrCodeStatus,
|
pollSsoQrCodeStatus,
|
||||||
verifySsoTokenOnUnity,
|
verifySsoTokenOnUnity,
|
||||||
} from "../../core/http/sso-client.js";
|
} from "../../core/http/sso-auth-client.js";
|
||||||
import type { CorpConfig } from "../../core/config/types.js";
|
import type { CorpConfig } from "../../core/config/types.js";
|
||||||
import {
|
import {
|
||||||
approveAssistTicketApi,
|
approveAssistTicketApi,
|
||||||
|
|||||||
@@ -86,6 +86,11 @@ src/domains/bill/
|
|||||||
- 先 `POST /api/v1/flow/plans/computed` 计算审批计划;
|
- 先 `POST /api/v1/flow/plans/computed` 计算审批计划;
|
||||||
- 未指派审批人的节点必须由 `--approver` 显式指定,绝不自动编造;
|
- 未指派审批人的节点必须由 `--approver` 显式指定,绝不自动编造;
|
||||||
- 再 `POST /api/flow/v1/flows/$<flowId>`(`name: freeflow.submit`,携带 `nodes`)。
|
- 再 `POST /api/flow/v1/flows/$<flowId>`(`name: freeflow.submit`,携带 `nodes`)。
|
||||||
|
15. **未提交草稿列表 (`searchAndFormatDraftBills`)**:
|
||||||
|
- 草稿未进入 `POST /api/v2/invoice/search` 台账索引,`bill list --state=draft` 改走 `POST /api/flow/v1/flows/my`;
|
||||||
|
- 服务端过滤 `state.in("draft")`,支持 `--template`、`--title`、`--staff`、`--code`、`--keyword`、时间范围与 `--page/--count` 分页,按流程 `createTime` 排序;
|
||||||
|
- 客户端再按模板、标题、提交人做兜底匹配,避免 RQL 对对象字段的差异造成漏筛;
|
||||||
|
- 列表只覆盖当前身份可见的「我发起」草稿。他人/系统或工作流创建的草稿按已知单号查询;`getRawBillFlow` 新增 flowId 直读通道,`bill get <flowId>` 不依赖 `flows/my` 可见性。
|
||||||
|
|
||||||
### 草稿写入前校验
|
### 草稿写入前校验
|
||||||
|
|
||||||
|
|||||||
@@ -120,6 +120,25 @@ export async function getRawBillFlow(
|
|||||||
// 通道 0 失败时继续走既有回溯通道
|
// 通道 0 失败时继续走既有回溯通道
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 通道 0.2: 已知 flowId 时直接读取流程详情。
|
||||||
|
// 工作流或其他身份创建的草稿可能不在当前身份的 flows/my 中,但 Job 输出/页面链接会给出 flowId;
|
||||||
|
// 该通道不依赖列表可见性,也避免回退到「最近 N 条」本地匹配。
|
||||||
|
if (/^ID01/i.test(cleanTarget)) {
|
||||||
|
try {
|
||||||
|
const detail = await client.post(`api/flow/v1/flows/flowId/$${cleanTarget}`, {
|
||||||
|
searchParams: { id: cleanTarget, corpId },
|
||||||
|
json: {
|
||||||
|
filterBy: `(id==${quoted(cleanTarget)})`,
|
||||||
|
select: "id,state,form,logs",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const json = (await detail.json()) as { value?: Record<string, unknown> };
|
||||||
|
if (json.value) return { flowId: json.value };
|
||||||
|
} catch {
|
||||||
|
// 非流程 ID 或不可见时继续走既有回溯通道
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 通道 1: api/flow/v2/backlogs/search 精准单号与 ID 匹配
|
// 通道 1: api/flow/v2/backlogs/search 精准单号与 ID 匹配
|
||||||
const searchFilters = [
|
const searchFilters = [
|
||||||
`(id==${quoted(cleanTarget)})||((flowId.id==${quoted(cleanTarget)})||(flowId.form.code==${quoted(cleanTarget)}))`,
|
`(id==${quoted(cleanTarget)})||((flowId.id==${quoted(cleanTarget)})||(flowId.form.code==${quoted(cleanTarget)}))`,
|
||||||
@@ -496,6 +515,82 @@ export async function searchRawBills(
|
|||||||
return RawBillSearchResponseSchema.parse(json);
|
return RawBillSearchResponseSchema.parse(json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface RawDraftFlowSearchOptions {
|
||||||
|
start?: number;
|
||||||
|
count?: number;
|
||||||
|
code?: string;
|
||||||
|
keyword?: string;
|
||||||
|
title?: string;
|
||||||
|
templateId?: string;
|
||||||
|
submitterIds?: string[];
|
||||||
|
from?: number;
|
||||||
|
to?: number;
|
||||||
|
order?: "ASC" | "DESC";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询「我发起」的未提交草稿流程。
|
||||||
|
*
|
||||||
|
* 草稿尚未进入单据台账索引(`api/v2/invoice/search`),因此列表必须走
|
||||||
|
* `api/flow/v1/flows/my`。服务端过滤字段与 task 域提交列表保持一致:
|
||||||
|
* state 使用小写 `draft`,模板/标题用 `INSTR(form.*, ...)`,时间用流程 `createTime`。
|
||||||
|
*/
|
||||||
|
export async function searchMyDraftFlows(
|
||||||
|
client: KyInstance,
|
||||||
|
corpId: string,
|
||||||
|
options: RawDraftFlowSearchOptions = {}
|
||||||
|
): Promise<{ count: number; items: Record<string, unknown>[] }> {
|
||||||
|
const filters: string[] = [
|
||||||
|
'(state.in("draft"))',
|
||||||
|
// 与 task submitted 一致:对账单流程不是费控单据草稿,避免混入列表。
|
||||||
|
`(INSTR(form.specificationId, ${quoted(`${corpId}:system:对账单`)})==0)`,
|
||||||
|
];
|
||||||
|
|
||||||
|
const code = options.code?.trim();
|
||||||
|
if (code) filters.push(`(form.code.in(${quoted(code)}))`);
|
||||||
|
|
||||||
|
const title = options.title?.trim();
|
||||||
|
if (title) filters.push(`(INSTR(form.title, ${quoted(title)}) > 0)`);
|
||||||
|
|
||||||
|
const templateId = options.templateId?.trim();
|
||||||
|
if (templateId) filters.push(`(INSTR(form.specificationId, ${quoted(templateId)}) > 0)`);
|
||||||
|
|
||||||
|
const submitterIds = (options.submitterIds ?? []).map((id) => id.trim()).filter(Boolean);
|
||||||
|
if (submitterIds.length > 0) {
|
||||||
|
const submitterFilters = submitterIds.map((id) => `(INSTR(form.submitterId, ${quoted(id)}) > 0)`);
|
||||||
|
filters.push(submitterFilters.length === 1 ? submitterFilters[0]! : `(${submitterFilters.join(" || ")})`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const keyword = options.keyword?.trim();
|
||||||
|
if (keyword) {
|
||||||
|
filters.push(
|
||||||
|
`((INSTR(form.title, ${quoted(keyword)}) > 0) || (INSTR(form.code, ${quoted(keyword)}) > 0))`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.from !== undefined) filters.push(`(createTime > ${options.from})`);
|
||||||
|
if (options.to !== undefined) filters.push(`(createTime < ${options.to})`);
|
||||||
|
|
||||||
|
const response = await client.post("api/flow/v1/flows/my", {
|
||||||
|
searchParams: {
|
||||||
|
type: "home5",
|
||||||
|
delegatedFilter: "DELEGATE_TO_ME",
|
||||||
|
corpId,
|
||||||
|
},
|
||||||
|
json: {
|
||||||
|
filterBy: filters.join("&&"),
|
||||||
|
limit: { start: options.start ?? 0, count: options.count ?? 20 },
|
||||||
|
orderBy: [{ value: "createTime", order: options.order ?? "DESC" }],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const json = (await response.json()) as { count?: number; items?: unknown[] };
|
||||||
|
const items = Array.isArray(json.items)
|
||||||
|
? json.items.filter((item): item is Record<string, unknown> => Boolean(item && typeof item === "object"))
|
||||||
|
: [];
|
||||||
|
return { count: json.count ?? items.length, items };
|
||||||
|
}
|
||||||
|
|
||||||
// ── 按 ID 列表精确拉取单据详情 API ─────────────────────────────────────────────
|
// ── 按 ID 列表精确拉取单据详情 API ─────────────────────────────────────────────
|
||||||
|
|
||||||
export async function getRawBillsByIds(
|
export async function getRawBillsByIds(
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
import { describe, it, expect } from "bun:test";
|
import { describe, it, expect } from "bun:test";
|
||||||
import {
|
import {
|
||||||
formatSingleBill,
|
formatSingleBill,
|
||||||
|
formatFlowAsBill,
|
||||||
|
searchAndFormatDraftBills,
|
||||||
|
getBillByCodeOrId,
|
||||||
getBillReferences,
|
getBillReferences,
|
||||||
getBillRelations,
|
getBillRelations,
|
||||||
getBillAttachments,
|
getBillAttachments,
|
||||||
@@ -714,6 +717,183 @@ describe("Bill Domain", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("Bill Draft Listing", () => {
|
||||||
|
const draftItems = [
|
||||||
|
{
|
||||||
|
flow: {
|
||||||
|
id: "flow-draft-1",
|
||||||
|
state: "draft",
|
||||||
|
formType: "payment",
|
||||||
|
createTime: 1781682826000,
|
||||||
|
updateTime: 1781682870000,
|
||||||
|
},
|
||||||
|
form: {
|
||||||
|
code: "FK26000001",
|
||||||
|
title: "付款草稿",
|
||||||
|
specificationId: { id: "spec-pay", name: "对公付款单" },
|
||||||
|
submitterId: { id: "staff-1", name: "张三", code: "1001" },
|
||||||
|
payMoney: { standard: "1200.00", standardSymbol: "¥", standardStrCode: "CNY" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
flow: {
|
||||||
|
id: "flow-draft-2",
|
||||||
|
state: "draft",
|
||||||
|
formType: "expense",
|
||||||
|
createTime: 1781682926000,
|
||||||
|
updateTime: 1781682970000,
|
||||||
|
},
|
||||||
|
form: {
|
||||||
|
code: "BX26000002",
|
||||||
|
title: "报销草稿",
|
||||||
|
specificationId: { id: "spec-exp", name: "报销单" },
|
||||||
|
submitterId: { id: "staff-2", name: "李四", code: "1002" },
|
||||||
|
expenseMoney: { standard: "88.00", standardSymbol: "¥", standardStrCode: "CNY" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
it("formats flows/my items that carry top-level form separately from flow", () => {
|
||||||
|
const bill = formatFlowAsBill(draftItems[0]!, new Map());
|
||||||
|
|
||||||
|
expect(bill.billId).toBe("flow-draft-1");
|
||||||
|
expect(bill.billCode).toBe("FK26000001");
|
||||||
|
expect(bill.billName).toBe("付款草稿");
|
||||||
|
expect(bill.state).toBe("draft");
|
||||||
|
expect(bill.stage).toBe("payment");
|
||||||
|
expect(bill.amount).toContain("1200.00");
|
||||||
|
expect(bill.submitterId).toContain("张三");
|
||||||
|
expect(bill.createTime).not.toBe("");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("queries flows/my for drafts and applies server plus client filters", async () => {
|
||||||
|
const posts: Array<{ url: string; payload: any }> = [];
|
||||||
|
const client = {
|
||||||
|
post: async (url: string, payload: any) => {
|
||||||
|
posts.push({ url, payload });
|
||||||
|
if (url.includes("datalink/entity/search")) {
|
||||||
|
return new Response(JSON.stringify({ items: [] }));
|
||||||
|
}
|
||||||
|
if (url.endsWith("/flows/my")) {
|
||||||
|
return new Response(JSON.stringify({ count: 2, items: draftItems }));
|
||||||
|
}
|
||||||
|
return new Response(JSON.stringify({}));
|
||||||
|
},
|
||||||
|
} as any;
|
||||||
|
|
||||||
|
const result = await searchAndFormatDraftBills(client, "corp-draft-list", {
|
||||||
|
title: "付款",
|
||||||
|
templateId: "spec-pay",
|
||||||
|
submitterIds: ["staff-1"],
|
||||||
|
start: 20,
|
||||||
|
count: 10,
|
||||||
|
since: "7d",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.total).toBe(2);
|
||||||
|
expect(result.returned).toBe(1);
|
||||||
|
expect(result.items[0]?.billId).toBe("flow-draft-1");
|
||||||
|
expect(result.items[0]?.billCode).toBe("FK26000001");
|
||||||
|
|
||||||
|
const draftRequest = posts.find((post) => post.url.endsWith("/flows/my"));
|
||||||
|
expect(draftRequest).toBeDefined();
|
||||||
|
const filterBy = draftRequest!.payload.json.filterBy as string;
|
||||||
|
expect(filterBy).toContain('(state.in("draft"))');
|
||||||
|
expect(filterBy).toContain('INSTR(form.title, "付款")');
|
||||||
|
expect(filterBy).toContain('INSTR(form.specificationId, "spec-pay")');
|
||||||
|
expect(filterBy).toContain('INSTR(form.submitterId, "staff-1")');
|
||||||
|
expect(filterBy).toContain("createTime >");
|
||||||
|
expect(draftRequest!.payload.json.limit).toEqual({ start: 20, count: 10 });
|
||||||
|
expect(draftRequest!.payload.json.orderBy).toEqual([{ value: "createTime", order: "DESC" }]);
|
||||||
|
expect(draftRequest!.payload.searchParams).toMatchObject({
|
||||||
|
corpId: "corp-draft-list",
|
||||||
|
type: "home5",
|
||||||
|
delegatedFilter: "DELEGATE_TO_ME",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("supports the compact flows/my shape: specification field and submitDate as createTime", async () => {
|
||||||
|
const client = {
|
||||||
|
post: async (url: string) => {
|
||||||
|
if (url.includes("datalink/entity/search")) {
|
||||||
|
return new Response(JSON.stringify({ items: [] }));
|
||||||
|
}
|
||||||
|
if (url.endsWith("/flows/my")) {
|
||||||
|
return new Response(JSON.stringify({
|
||||||
|
count: 1,
|
||||||
|
items: [{
|
||||||
|
flow: { id: "flow-compact", state: "draft" },
|
||||||
|
form: {
|
||||||
|
code: "BX26000009",
|
||||||
|
title: "紧凑草稿",
|
||||||
|
type: "expense",
|
||||||
|
specification: { id: "spec-exp:0123456789abcdef0123456789abcdef", name: "报销单" },
|
||||||
|
submitterId: { id: "staff-1", name: "张三", code: "1001" },
|
||||||
|
amount: { standard: "5.00", standardSymbol: "¥", standardStrCode: "CNY" },
|
||||||
|
submitDate: 1794989105307,
|
||||||
|
},
|
||||||
|
}],
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
return new Response(JSON.stringify({}));
|
||||||
|
},
|
||||||
|
} as any;
|
||||||
|
|
||||||
|
const result = await searchAndFormatDraftBills(client, "corp-draft-compact", {
|
||||||
|
templateId: "spec-exp",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.returned).toBe(1);
|
||||||
|
expect(result.items[0]).toMatchObject({
|
||||||
|
billId: "flow-compact",
|
||||||
|
billCode: "BX26000009",
|
||||||
|
stage: "expense",
|
||||||
|
state: "draft",
|
||||||
|
});
|
||||||
|
expect(result.items[0]?.createTime).not.toBe("");
|
||||||
|
expect(result.items[0]?.amount).toContain("5.00");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reads a workflow-created draft by flowId even when flows/my is empty", async () => {
|
||||||
|
const posts: string[] = [];
|
||||||
|
const client = {
|
||||||
|
post: async (url: string) => {
|
||||||
|
posts.push(url);
|
||||||
|
if (url.includes("datalink/entity/search")) {
|
||||||
|
return new Response(JSON.stringify({ items: [] }));
|
||||||
|
}
|
||||||
|
if (url.includes("flows/flowId/")) {
|
||||||
|
return new Response(JSON.stringify({
|
||||||
|
value: {
|
||||||
|
id: "ID01DRAFTFLOW",
|
||||||
|
state: "draft",
|
||||||
|
form: {
|
||||||
|
code: "FD26000001",
|
||||||
|
title: "工作流付款草稿",
|
||||||
|
specificationId: { id: "spec-pay", name: "对公付款单" },
|
||||||
|
payMoney: { standard: "66.00", standardSymbol: "¥", standardStrCode: "CNY" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
if (url.includes("flows/my") || url.includes("flows/approved")) {
|
||||||
|
return new Response(JSON.stringify({ items: [] }));
|
||||||
|
}
|
||||||
|
return new Response(JSON.stringify({ items: [] }));
|
||||||
|
},
|
||||||
|
} as any;
|
||||||
|
|
||||||
|
const bills = await getBillByCodeOrId(client, "corp-draft-flow", "ID01DRAFTFLOW");
|
||||||
|
|
||||||
|
expect(posts.some((url) => url.includes("flows/flowId/$ID01DRAFTFLOW"))).toBe(true);
|
||||||
|
expect(bills).toHaveLength(1);
|
||||||
|
expect(bills[0]?.billId).toBe("ID01DRAFTFLOW");
|
||||||
|
expect(bills[0]?.billCode).toBe("FD26000001");
|
||||||
|
expect(bills[0]?.state).toBe("draft");
|
||||||
|
expect(bills[0]?.amount).toContain("66.00");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe("traceBillFlowDetail 全域穿透诊断与待办根因分析", () => {
|
describe("traceBillFlowDetail 全域穿透诊断与待办根因分析", () => {
|
||||||
it("待审批状态:精准解析提报人、金额、当前节点与待办审批人,判定可审批", async () => {
|
it("待审批状态:精准解析提报人、金额、当前节点与待办审批人,判定可审批", async () => {
|
||||||
const mockRawFlow = {
|
const mockRawFlow = {
|
||||||
|
|||||||
+153
-5
@@ -12,6 +12,7 @@ import {
|
|||||||
} from "../../core/errors.js";
|
} from "../../core/errors.js";
|
||||||
import {
|
import {
|
||||||
searchRawBills,
|
searchRawBills,
|
||||||
|
searchMyDraftFlows,
|
||||||
getRawBillsByIds,
|
getRawBillsByIds,
|
||||||
listEntitySchemas,
|
listEntitySchemas,
|
||||||
getRawBillFlow,
|
getRawBillFlow,
|
||||||
@@ -44,6 +45,7 @@ import {
|
|||||||
type BillPageResult,
|
type BillPageResult,
|
||||||
type EntityMeta,
|
type EntityMeta,
|
||||||
type BillQueryParams,
|
type BillQueryParams,
|
||||||
|
type BillDraftQueryParams,
|
||||||
type BillFlowEntry,
|
type BillFlowEntry,
|
||||||
type BillFlowNode,
|
type BillFlowNode,
|
||||||
type BillFlowTimeline,
|
type BillFlowTimeline,
|
||||||
@@ -678,12 +680,20 @@ export function formatFlowAsBill(
|
|||||||
raw: Record<string, unknown>,
|
raw: Record<string, unknown>,
|
||||||
dictionary: Map<string, { label: string; type: string }>
|
dictionary: Map<string, { label: string; type: string }>
|
||||||
): FormattedBill {
|
): FormattedBill {
|
||||||
const flow = (raw.flowId && typeof raw.flowId === "object" ? raw.flowId : {}) as Record<string, unknown>;
|
const flow = (raw.flowId && typeof raw.flowId === "object"
|
||||||
const form = (flow.form && typeof flow.form === "object" ? flow.form : {}) as Record<string, unknown>;
|
? raw.flowId
|
||||||
|
: raw.flow && typeof raw.flow === "object"
|
||||||
|
? raw.flow
|
||||||
|
: {}) as Record<string, unknown>;
|
||||||
|
const form = (flow.form && typeof flow.form === "object"
|
||||||
|
? flow.form
|
||||||
|
: raw.form && typeof raw.form === "object"
|
||||||
|
? raw.form
|
||||||
|
: {}) as Record<string, unknown>;
|
||||||
const billCode = (typeof form.code === "string" && form.code.trim()) || (typeof flow.id === "string" ? flow.id : String(raw.id || ""));
|
const billCode = (typeof form.code === "string" && form.code.trim()) || (typeof flow.id === "string" ? flow.id : String(raw.id || ""));
|
||||||
const title = (typeof form.title === "string" && form.title.trim()) || (typeof flow.title === "string" ? flow.title : undefined);
|
const title = (typeof form.title === "string" && form.title.trim()) || (typeof flow.title === "string" ? flow.title : undefined);
|
||||||
const billName = title || (flow.formType === "requisition" ? "差旅申请单" : "审批单据");
|
const billName = title || (flow.formType === "requisition" ? "差旅申请单" : "审批单据");
|
||||||
const stage = typeof flow.formType === "string" ? flow.formType : "flow";
|
const stage = typeof flow.formType === "string" ? flow.formType : typeof form.type === "string" ? form.type : "flow";
|
||||||
const state = raw.nodeName
|
const state = raw.nodeName
|
||||||
? `${raw.state || flow.state || "APPROVING"} (${raw.nodeName})`
|
? `${raw.state || flow.state || "APPROVING"} (${raw.nodeName})`
|
||||||
: (typeof raw.state === "string" ? raw.state : typeof flow.state === "string" ? flow.state : "APPROVING");
|
: (typeof raw.state === "string" ? raw.state : typeof flow.state === "string" ? flow.state : "APPROVING");
|
||||||
@@ -714,8 +724,24 @@ export function formatFlowAsBill(
|
|||||||
submitDateStr = new Date(form.submitDate).toLocaleString("zh-CN");
|
submitDateStr = new Date(form.submitDate).toLocaleString("zh-CN");
|
||||||
}
|
}
|
||||||
|
|
||||||
const createTimeNum = typeof flow.createTime === "number" ? flow.createTime : typeof raw.createTime === "number" ? raw.createTime : 0;
|
// flows/my 的精简响应不一定带流程 createTime;草稿没有 submitDate 语义上的提交时间,
|
||||||
const updateTimeNum = typeof flow.updateTime === "number" ? flow.updateTime : typeof raw.updateTime === "number" ? raw.updateTime : 0;
|
// 服务端仍会写入该字段,可作为创建时间兜底,避免列表展示为空。
|
||||||
|
const createTimeNum = typeof flow.createTime === "number"
|
||||||
|
? flow.createTime
|
||||||
|
: typeof raw.createTime === "number"
|
||||||
|
? raw.createTime
|
||||||
|
: typeof form.createTime === "number"
|
||||||
|
? form.createTime
|
||||||
|
: typeof form.submitDate === "number"
|
||||||
|
? form.submitDate
|
||||||
|
: 0;
|
||||||
|
const updateTimeNum = typeof flow.updateTime === "number"
|
||||||
|
? flow.updateTime
|
||||||
|
: typeof raw.updateTime === "number"
|
||||||
|
? raw.updateTime
|
||||||
|
: typeof form.updateTime === "number"
|
||||||
|
? form.updateTime
|
||||||
|
: 0;
|
||||||
const createTimeStr = createTimeNum > 0 ? new Date(createTimeNum).toLocaleString("zh-CN") : "";
|
const createTimeStr = createTimeNum > 0 ? new Date(createTimeNum).toLocaleString("zh-CN") : "";
|
||||||
const updateTimeStr = updateTimeNum > 0 ? new Date(updateTimeNum).toLocaleString("zh-CN") : "";
|
const updateTimeStr = updateTimeNum > 0 ? new Date(updateTimeNum).toLocaleString("zh-CN") : "";
|
||||||
|
|
||||||
@@ -1631,6 +1657,128 @@ export async function searchAndFormatBills(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function draftFlowParts(item: Record<string, unknown>): {
|
||||||
|
flow: Record<string, unknown>;
|
||||||
|
form: Record<string, unknown>;
|
||||||
|
} {
|
||||||
|
const flow = (item.flow && typeof item.flow === "object"
|
||||||
|
? item.flow
|
||||||
|
: item.flowId && typeof item.flowId === "object"
|
||||||
|
? item.flowId
|
||||||
|
: {}) as Record<string, unknown>;
|
||||||
|
const form = (flow.form && typeof flow.form === "object"
|
||||||
|
? flow.form
|
||||||
|
: item.form && typeof item.form === "object"
|
||||||
|
? item.form
|
||||||
|
: {}) as Record<string, unknown>;
|
||||||
|
return { flow, form };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询未提交草稿列表。
|
||||||
|
*
|
||||||
|
* 草稿不在 `api/v2/invoice/search` 台账索引中,数据源改为 `api/flow/v1/flows/my`;
|
||||||
|
* 服务端过滤之外再做一次客户端兜底匹配,避免 RQL 对对象字段的差异造成漏筛。
|
||||||
|
* 该列表只覆盖当前身份可见的「我发起」草稿;他人/系统创建的草稿按已知单号或 flowId
|
||||||
|
* 使用 `bill get` 查询(`getRawBillFlow` 的 flowId 直读通道)。
|
||||||
|
*/
|
||||||
|
export async function searchAndFormatDraftBills(
|
||||||
|
client: KyInstance,
|
||||||
|
corpId: string,
|
||||||
|
params: BillDraftQueryParams = {}
|
||||||
|
): Promise<BillPageResult> {
|
||||||
|
const { dictionary } = await getFieldDictionary(client, corpId);
|
||||||
|
|
||||||
|
let fromTime = params.from ?? parseDateFilter(params.startDate);
|
||||||
|
if (params.since) {
|
||||||
|
const duration = parseSinceDuration(params.since);
|
||||||
|
if (duration !== undefined) fromTime = Math.max(fromTime ?? 0, Date.now() - duration);
|
||||||
|
}
|
||||||
|
const toTime = params.to ?? parseDateFilter(params.endDate, true);
|
||||||
|
|
||||||
|
const page = await searchMyDraftFlows(client, corpId, {
|
||||||
|
start: params.start ?? 0,
|
||||||
|
count: params.count ?? 20,
|
||||||
|
code: params.code,
|
||||||
|
keyword: params.keyword,
|
||||||
|
title: params.title,
|
||||||
|
templateId: params.templateId,
|
||||||
|
submitterIds: params.submitterIds,
|
||||||
|
from: fromTime,
|
||||||
|
to: toTime,
|
||||||
|
order: (params.order ?? "DESC").toUpperCase() as "ASC" | "DESC",
|
||||||
|
});
|
||||||
|
|
||||||
|
let items = page.items;
|
||||||
|
|
||||||
|
const code = params.code?.trim();
|
||||||
|
if (code) {
|
||||||
|
items = items.filter((item) => {
|
||||||
|
const { flow, form } = draftFlowParts(item);
|
||||||
|
return form.code === code || flow.id === code;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const title = params.title?.trim().toLowerCase();
|
||||||
|
if (title) {
|
||||||
|
items = items.filter((item) => {
|
||||||
|
const { form } = draftFlowParts(item);
|
||||||
|
return typeof form.title === "string" && form.title.toLowerCase().includes(title);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const templateId = params.templateId?.trim();
|
||||||
|
if (templateId) {
|
||||||
|
items = items.filter((item) => {
|
||||||
|
const { form } = draftFlowParts(item);
|
||||||
|
// flows/my 返回精简表单时字段名为 specification;创建/详情接口则常用 specificationId。
|
||||||
|
const specification = form.specificationId ?? form.specification;
|
||||||
|
if (typeof specification === "string") return specification.includes(templateId);
|
||||||
|
if (specification && typeof specification === "object") {
|
||||||
|
const record = specification as Record<string, unknown>;
|
||||||
|
return ["id", "originalId", "name"].some((key) => {
|
||||||
|
const value = record[key];
|
||||||
|
return typeof value === "string" && (value === templateId || value.includes(templateId));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const submitterIds = (params.submitterIds ?? []).map((id) => id.trim()).filter(Boolean);
|
||||||
|
if (submitterIds.length > 0) {
|
||||||
|
items = items.filter((item) => {
|
||||||
|
const { form } = draftFlowParts(item);
|
||||||
|
const submitter = form.submitterId;
|
||||||
|
if (typeof submitter === "string") {
|
||||||
|
return submitterIds.some((id) => submitter === id || submitter.includes(id));
|
||||||
|
}
|
||||||
|
if (submitter && typeof submitter === "object") {
|
||||||
|
const record = submitter as Record<string, unknown>;
|
||||||
|
return submitterIds.some((id) =>
|
||||||
|
[record.id, record.userId].some(
|
||||||
|
(value) => typeof value === "string" && (value === id || value.endsWith(`:${id}`))
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const keyword = params.keyword?.trim().toLowerCase();
|
||||||
|
if (keyword) {
|
||||||
|
items = items.filter((item) => {
|
||||||
|
const { form } = draftFlowParts(item);
|
||||||
|
return [form.title, form.code].some(
|
||||||
|
(value) => typeof value === "string" && value.toLowerCase().includes(keyword)
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const formatted = items.map((item) => formatFlowAsBill(item, dictionary));
|
||||||
|
return { total: page.count, returned: formatted.length, items: formatted };
|
||||||
|
}
|
||||||
|
|
||||||
export async function getTranslatorContext(
|
export async function getTranslatorContext(
|
||||||
client: KyInstance,
|
client: KyInstance,
|
||||||
corpId: string,
|
corpId: string,
|
||||||
|
|||||||
@@ -192,6 +192,22 @@ export interface BillQueryParams {
|
|||||||
join?: string | string[];
|
join?: string | string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface BillDraftQueryParams {
|
||||||
|
code?: string;
|
||||||
|
keyword?: string;
|
||||||
|
title?: string;
|
||||||
|
templateId?: string;
|
||||||
|
submitterIds?: string[];
|
||||||
|
start?: number;
|
||||||
|
count?: number;
|
||||||
|
since?: string;
|
||||||
|
from?: number;
|
||||||
|
to?: number;
|
||||||
|
startDate?: string;
|
||||||
|
endDate?: string;
|
||||||
|
order?: "ASC" | "DESC" | "asc" | "desc";
|
||||||
|
}
|
||||||
|
|
||||||
export interface BillFlowEntry {
|
export interface BillFlowEntry {
|
||||||
id?: string;
|
id?: string;
|
||||||
time?: number;
|
time?: number;
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { getEasoClient } from "../../core/http/unity-client.js";
|
import { getEasoClient } from "../../core/http/unity-easo-client.js";
|
||||||
import type { CorpConfig } from "../../core/config/types.js";
|
import type { CorpConfig } from "../../core/config/types.js";
|
||||||
import { fetchStaffs } from "./api.js";
|
import { fetchStaffs } from "./api.js";
|
||||||
import type { ContactListResult, ContactSearchOptions, Staff } from "./types.js";
|
import type { ContactListResult, ContactSearchOptions, Staff } from "./types.js";
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
# Docs 开放平台文档域说明
|
||||||
|
|
||||||
|
本域提供合思/易快报开放平台官方文档中心(`docs.ekuaibao.com`)全量 API 规范、请求方法、URL 路径、参数表格、CURL 示例与响应 JSON 的结构化离线/在线检索与详情提取能力。
|
||||||
|
|
||||||
|
## 架构
|
||||||
|
|
||||||
|
- `api.ts`:传输层,负责实时拉取线上 `https://docs.ekuaibao.com/search-index.json` 并解析出包含 270+ 接口的结构化目录(DocCatalog)。
|
||||||
|
- `tools.ts`:业务层,提供多级缓存(L1 内存 + L2 SQLite + `specs/docs-catalog.json` 静态预编译保底)、关键词评分加权检索、按 URL/Path/标题精确解析文档详情及业务模块分类汇总。
|
||||||
|
- `types.ts`:Zod 模式与 TypeScript 类型定义(`OpenApiDocItem`, `DocCatalog`, `DocSearchQuery`, `DocSearchResult`)。
|
||||||
|
|
||||||
|
## 核心接口
|
||||||
|
|
||||||
|
- `searchDocs(query, options)`: 按关键词、分类(`category`)、HTTP 方法(`method`)与接口路径(`path`)智能打分检索
|
||||||
|
- `getDocDetail(target, options)`: 快速按 ID、Path、URL 或中文标题检索出完整的接口定义
|
||||||
|
- `listCategories(options)`: 汇总开放平台 26+ 个业务分类及对应的文档和端点总数
|
||||||
|
- `syncDocsCatalog(options)`: 强制与线上文档站点执行全量同步并更新本地缓存
|
||||||
@@ -0,0 +1,179 @@
|
|||||||
|
import { EkbApiError } from "../../core/errors.js";
|
||||||
|
import {
|
||||||
|
createHoseDocsClient,
|
||||||
|
DEFAULT_HOSE_DOCS_BASE_URL,
|
||||||
|
} from "../../core/http/hose-docs-client.js";
|
||||||
|
import {
|
||||||
|
DocCatalogSchema,
|
||||||
|
type DocCatalog,
|
||||||
|
type OpenApiDocItem,
|
||||||
|
} from "./types.js";
|
||||||
|
|
||||||
|
export const DEFAULT_DOCS_BASE_URL = DEFAULT_HOSE_DOCS_BASE_URL;
|
||||||
|
|
||||||
|
interface RawSearchDoc {
|
||||||
|
i: number;
|
||||||
|
t: string;
|
||||||
|
u: string;
|
||||||
|
b?: string[];
|
||||||
|
h?: string;
|
||||||
|
p?: number;
|
||||||
|
s?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RawSearchSection {
|
||||||
|
documents?: RawSearchDoc[];
|
||||||
|
index?: Record<string, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseRawSearchIndexToCatalog(
|
||||||
|
rawSections: RawSearchSection[],
|
||||||
|
baseUrl = DEFAULT_DOCS_BASE_URL
|
||||||
|
): DocCatalog {
|
||||||
|
const rawDocs = rawSections[0]?.documents || [];
|
||||||
|
const rawHeadings = rawSections[1]?.documents || [];
|
||||||
|
const rawParagraphs = rawSections[2]?.documents || [];
|
||||||
|
|
||||||
|
const apiDocs = rawDocs.filter((d) => d.u?.startsWith("/docs/open-api/"));
|
||||||
|
const items: OpenApiDocItem[] = [];
|
||||||
|
|
||||||
|
for (const doc of apiDocs) {
|
||||||
|
const headings = rawHeadings
|
||||||
|
.filter((h) => h.p === doc.i)
|
||||||
|
.map((h) => h.t)
|
||||||
|
.filter(Boolean);
|
||||||
|
const paragraphs = rawParagraphs.filter((p) => p.p === doc.i);
|
||||||
|
|
||||||
|
let method: string | undefined;
|
||||||
|
let path: string | undefined;
|
||||||
|
let curl: string | undefined;
|
||||||
|
let responseSample: string | undefined;
|
||||||
|
let parameters: string | undefined;
|
||||||
|
const sections: Array<{ title: string; content: string }> = [];
|
||||||
|
|
||||||
|
for (const p of paragraphs) {
|
||||||
|
const sectionTitle = p.s || "概述";
|
||||||
|
const text = (p.t || "").trim();
|
||||||
|
if (!text) continue;
|
||||||
|
|
||||||
|
// Extract HTTP method and path from paragraph text
|
||||||
|
if (!method || !path) {
|
||||||
|
const methodMatch = text.match(
|
||||||
|
/\b(GET|POST|PUT|DELETE|PATCH)\s*(\/api\/[^\s]+)/i
|
||||||
|
);
|
||||||
|
if (methodMatch) {
|
||||||
|
method = methodMatch[1].toUpperCase();
|
||||||
|
path = methodMatch[2];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract CURL
|
||||||
|
if (
|
||||||
|
sectionTitle === "CURL" ||
|
||||||
|
text.startsWith("curl ") ||
|
||||||
|
text.includes("curl --location")
|
||||||
|
) {
|
||||||
|
curl = text;
|
||||||
|
// Fallback method/path extraction from curl if not found yet
|
||||||
|
if (!method || !path) {
|
||||||
|
const curlMatch = text.match(
|
||||||
|
/--request\s+(GET|POST|PUT|DELETE|PATCH)\s+['"][^'"]*?(\/api\/[^?'"\s]+)/i
|
||||||
|
);
|
||||||
|
if (curlMatch) {
|
||||||
|
method = curlMatch[1].toUpperCase();
|
||||||
|
path = curlMatch[2];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (
|
||||||
|
sectionTitle === "成功响应" ||
|
||||||
|
sectionTitle === "Response" ||
|
||||||
|
(text.startsWith("{") && text.endsWith("}"))
|
||||||
|
) {
|
||||||
|
responseSample = text;
|
||||||
|
} else if (
|
||||||
|
sectionTitle.includes("Parameter") ||
|
||||||
|
sectionTitle.includes("参数") ||
|
||||||
|
sectionTitle.includes("Body")
|
||||||
|
) {
|
||||||
|
parameters = parameters ? `${parameters}\n${text}` : text;
|
||||||
|
}
|
||||||
|
|
||||||
|
sections.push({
|
||||||
|
title: sectionTitle,
|
||||||
|
content: text,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const category = doc.b?.[1] || "未分类";
|
||||||
|
const cleanUrl = doc.u || "";
|
||||||
|
|
||||||
|
items.push({
|
||||||
|
id: doc.i,
|
||||||
|
title: doc.t || "未命名文档",
|
||||||
|
category,
|
||||||
|
url: cleanUrl,
|
||||||
|
permalink: `${baseUrl.replace(/\/+$/, "")}${cleanUrl}`,
|
||||||
|
method,
|
||||||
|
path,
|
||||||
|
breadcrumbs: doc.b || [],
|
||||||
|
headings,
|
||||||
|
sections,
|
||||||
|
parameters,
|
||||||
|
curl,
|
||||||
|
responseSample,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const catalog: DocCatalog = {
|
||||||
|
version: "1.0.0",
|
||||||
|
updatedAt: new Date().toISOString(),
|
||||||
|
sourceUrl: `${baseUrl.replace(/\/+$/, "")}/search-index.json`,
|
||||||
|
totalDocs: items.length,
|
||||||
|
totalEndpoints: items.filter((i) => i.method && i.path).length,
|
||||||
|
items,
|
||||||
|
};
|
||||||
|
|
||||||
|
return DocCatalogSchema.parse(catalog);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 实时从线上文档站点获取最新接口定义索引
|
||||||
|
*/
|
||||||
|
export async function fetchLiveDocsCatalog(options?: {
|
||||||
|
baseUrl?: string;
|
||||||
|
timeoutMs?: number;
|
||||||
|
}): Promise<DocCatalog> {
|
||||||
|
const baseUrl = options?.baseUrl || DEFAULT_DOCS_BASE_URL;
|
||||||
|
const timeoutMs = options?.timeoutMs ?? 15000;
|
||||||
|
const client = createHoseDocsClient({ baseUrl, timeout: timeoutMs });
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await client.get("search-index.json");
|
||||||
|
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new EkbApiError(
|
||||||
|
`获取开放平台文档索引失败: HTTP ${response.status}`,
|
||||||
|
"DOCS_FETCH_FAILED",
|
||||||
|
response.status
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const raw = (await response.json()) as RawSearchSection[];
|
||||||
|
if (!Array.isArray(raw) || raw.length === 0) {
|
||||||
|
throw new EkbApiError(
|
||||||
|
"开放平台文档索引数据异常: 返回格式不是有效的分区数组",
|
||||||
|
"DOCS_INVALID_DATA"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return parseRawSearchIndexToCatalog(raw, baseUrl);
|
||||||
|
} catch (error: any) {
|
||||||
|
if (error instanceof EkbApiError) throw error;
|
||||||
|
throw new EkbApiError(
|
||||||
|
`请求开放平台文档站点 (${baseUrl}/search-index.json) 失败: ${error?.message || String(error)}`,
|
||||||
|
"DOCS_NETWORK_ERROR",
|
||||||
|
502
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
import { describe, expect, it } from "bun:test";
|
||||||
|
import { parseRawSearchIndexToCatalog } from "./api.js";
|
||||||
|
import {
|
||||||
|
getDocDetail,
|
||||||
|
getDocsCatalog,
|
||||||
|
listCategories,
|
||||||
|
searchDocs,
|
||||||
|
} from "./tools.js";
|
||||||
|
|
||||||
|
const mockRawSections = [
|
||||||
|
{
|
||||||
|
documents: [
|
||||||
|
{
|
||||||
|
i: 1001,
|
||||||
|
t: "查询角色组和角色",
|
||||||
|
u: "/docs/open-api/corporation/get-roles-group",
|
||||||
|
b: ["Open API", "企业通讯录"],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
i: 1002,
|
||||||
|
t: "下载附件",
|
||||||
|
u: "/docs/open-api/attachment/attachment-download",
|
||||||
|
b: ["Open API", "附件"],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
i: 1003,
|
||||||
|
t: "其他非 API 页面",
|
||||||
|
u: "/blog/archive",
|
||||||
|
b: [],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
documents: [
|
||||||
|
{
|
||||||
|
i: 2001,
|
||||||
|
t: "Query Parameters",
|
||||||
|
u: "/docs/open-api/corporation/get-roles-group",
|
||||||
|
h: "#query-parameters",
|
||||||
|
p: 1001,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
i: 2002,
|
||||||
|
t: "CURL",
|
||||||
|
u: "/docs/open-api/corporation/get-roles-group",
|
||||||
|
h: "#curl",
|
||||||
|
p: 1001,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
documents: [
|
||||||
|
{
|
||||||
|
i: 3001,
|
||||||
|
t: "GET /api/openapi/v1/roleDefGroups 更新日志 0.7.135 🆕 新增了本接口。",
|
||||||
|
s: "查询角色组和角色",
|
||||||
|
p: 1001,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
i: 3002,
|
||||||
|
t: "accessToken String 认证token 必填 - 通过 获取授权 获取 accessToken",
|
||||||
|
s: "Query Parameters",
|
||||||
|
p: 1001,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
i: 3003,
|
||||||
|
t: "curl --location --request GET 'https://app.ekuaibao.com/api/openapi/v1/roleDefGroups?accessToken=TOKEN'",
|
||||||
|
s: "CURL",
|
||||||
|
p: 1001,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
i: 3004,
|
||||||
|
t: "POST /api/openapi/v2/attachment/downloadurls",
|
||||||
|
s: "下载附件",
|
||||||
|
p: 1002,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
describe("Docs Domain - 开放平台文档域", () => {
|
||||||
|
it("parseRawSearchIndexToCatalog 正确解析原始搜索索引并提取 HTTP 属性", () => {
|
||||||
|
const catalog = parseRawSearchIndexToCatalog(mockRawSections as any);
|
||||||
|
expect(catalog.totalDocs).toBe(2);
|
||||||
|
expect(catalog.totalEndpoints).toBe(2);
|
||||||
|
|
||||||
|
const roleGroupDoc = catalog.items.find((i) => i.id === 1001);
|
||||||
|
expect(roleGroupDoc).toBeDefined();
|
||||||
|
expect(roleGroupDoc?.title).toBe("查询角色组和角色");
|
||||||
|
expect(roleGroupDoc?.category).toBe("企业通讯录");
|
||||||
|
expect(roleGroupDoc?.method).toBe("GET");
|
||||||
|
expect(roleGroupDoc?.path).toBe("/api/openapi/v1/roleDefGroups");
|
||||||
|
expect(roleGroupDoc?.curl).toContain("/api/openapi/v1/roleDefGroups");
|
||||||
|
expect(roleGroupDoc?.parameters).toContain("accessToken");
|
||||||
|
|
||||||
|
const attachmentDoc = catalog.items.find((i) => i.id === 1002);
|
||||||
|
expect(attachmentDoc?.method).toBe("POST");
|
||||||
|
expect(attachmentDoc?.path).toBe("/api/openapi/v2/attachment/downloadurls");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("getDocsCatalog 在测试环境中能安全加载预编译/内嵌规格", async () => {
|
||||||
|
const catalog = await getDocsCatalog();
|
||||||
|
expect(catalog.items.length).toBeGreaterThan(100);
|
||||||
|
expect(catalog.totalEndpoints).toBeGreaterThan(100);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("searchDocs 按关键词检索接口并正确排序", async () => {
|
||||||
|
const res = await searchDocs({ keyword: "roleDefGroups" });
|
||||||
|
expect(res.total).toBeGreaterThanOrEqual(1);
|
||||||
|
expect(res.items[0]?.path).toBe("/api/openapi/v1/roleDefGroups");
|
||||||
|
expect(res.items[0]?.title).toBe("查询角色组和角色");
|
||||||
|
expect(res.items[0]?.matchReason).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("searchDocs 支持多词分词与跨正文/参数模糊检索", async () => {
|
||||||
|
const res = await searchDocs({ keyword: "员工 手机" });
|
||||||
|
expect(res.total).toBeGreaterThanOrEqual(1);
|
||||||
|
expect(res.items.some((i) => i.title.includes("员工"))).toBe(true);
|
||||||
|
expect(res.items[0]?.matchReason).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("searchDocs 支持按分类与 HTTP 方法精确过滤", async () => {
|
||||||
|
const res = await searchDocs({
|
||||||
|
category: "企业通讯录",
|
||||||
|
method: "GET",
|
||||||
|
});
|
||||||
|
expect(res.items.length).toBeGreaterThanOrEqual(1);
|
||||||
|
for (const item of res.items) {
|
||||||
|
expect(item.category).toBe("企业通讯录");
|
||||||
|
expect(item.method).toBe("GET");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("getDocDetail 能按路径、URL、标题或 ID 精准定位文档", async () => {
|
||||||
|
const byPath = await getDocDetail("/api/openapi/v1/roleDefGroups");
|
||||||
|
expect(byPath).toBeDefined();
|
||||||
|
expect(byPath?.title).toBe("查询角色组和角色");
|
||||||
|
|
||||||
|
const byUrl = await getDocDetail("/docs/open-api/corporation/get-roles-group");
|
||||||
|
expect(byUrl).toBeDefined();
|
||||||
|
expect(byUrl?.id).toBe(byPath?.id);
|
||||||
|
|
||||||
|
const byTitle = await getDocDetail("查询角色组和角色");
|
||||||
|
expect(byTitle?.path).toBe("/api/openapi/v1/roleDefGroups");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("listCategories 能够统计分类列表与端点总数", async () => {
|
||||||
|
const cats = await listCategories();
|
||||||
|
expect(cats.length).toBeGreaterThanOrEqual(10);
|
||||||
|
const corpCat = cats.find((c) => c.name === "企业通讯录");
|
||||||
|
expect(corpCat).toBeDefined();
|
||||||
|
expect(corpCat?.count).toBeGreaterThan(0);
|
||||||
|
expect(corpCat?.endpointsCount).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,352 @@
|
|||||||
|
import embeddedCatalog from "../../../specs/docs-catalog.json" with { type: "json" };
|
||||||
|
import { getGlobalCache } from "../../core/cache/index.js";
|
||||||
|
import { fetchLiveDocsCatalog } from "./api.js";
|
||||||
|
import type {
|
||||||
|
DocCatalog,
|
||||||
|
DocCategoryInfo,
|
||||||
|
DocSearchQuery,
|
||||||
|
DocSearchResult,
|
||||||
|
OpenApiDocItem,
|
||||||
|
} from "./types.js";
|
||||||
|
|
||||||
|
const CACHE_KEY = "docs:catalog:v1";
|
||||||
|
const CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24小时缓存
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取接口文档目录(具备实时拉取 + L1/L2 缓存 + 静态内嵌保底能力)
|
||||||
|
*/
|
||||||
|
export async function getDocsCatalog(options?: {
|
||||||
|
forceRefresh?: boolean;
|
||||||
|
baseUrl?: string;
|
||||||
|
}): Promise<DocCatalog> {
|
||||||
|
const cache = getGlobalCache();
|
||||||
|
|
||||||
|
if (!options?.forceRefresh) {
|
||||||
|
const cached = cache.get<DocCatalog>(CACHE_KEY, "docs");
|
||||||
|
if (cached && Array.isArray(cached.items) && cached.items.length > 0) {
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 尝试从线上获取最新规范
|
||||||
|
try {
|
||||||
|
const liveCatalog = await fetchLiveDocsCatalog({ baseUrl: options?.baseUrl });
|
||||||
|
cache.set(CACHE_KEY, liveCatalog, {
|
||||||
|
ttlMs: CACHE_TTL_MS,
|
||||||
|
namespace: "docs",
|
||||||
|
});
|
||||||
|
return liveCatalog;
|
||||||
|
} catch (error) {
|
||||||
|
// 若强制刷新失败且存在历史缓存,则返回历史缓存
|
||||||
|
const cached = cache.get<DocCatalog>(CACHE_KEY, "docs");
|
||||||
|
if (cached && Array.isArray(cached.items) && cached.items.length > 0) {
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 线上无法连通且无历史缓存时,安全降级至本地内嵌预编译规格
|
||||||
|
return embeddedCatalog as unknown as DocCatalog;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 计算文档项与搜索关键词的相关度得分,并生成高亮命中摘要
|
||||||
|
*/
|
||||||
|
function evaluateDocMatch(
|
||||||
|
item: OpenApiDocItem,
|
||||||
|
rawKeyword: string
|
||||||
|
): { item: OpenApiDocItem; score: number } | null {
|
||||||
|
const queryLower = rawKeyword.trim().toLowerCase();
|
||||||
|
if (!queryLower) return null;
|
||||||
|
|
||||||
|
const tokens = queryLower.split(/[\s,+/]+/).filter(Boolean);
|
||||||
|
if (tokens.length === 0) return null;
|
||||||
|
|
||||||
|
let score = 0;
|
||||||
|
const matchReasons: string[] = [];
|
||||||
|
|
||||||
|
const pathLower = (item.path || "").toLowerCase();
|
||||||
|
const titleLower = item.title.toLowerCase();
|
||||||
|
const categoryLower = item.category.toLowerCase();
|
||||||
|
const paramLower = (item.parameters || "").toLowerCase();
|
||||||
|
const curlLower = (item.curl || "").toLowerCase();
|
||||||
|
const respLower = (item.responseSample || "").toLowerCase();
|
||||||
|
const allSectionsText = item.sections.map((s) => s.content).join(" ");
|
||||||
|
const sectionsLower = allSectionsText.toLowerCase();
|
||||||
|
|
||||||
|
// 1. 完整短语匹配加分 (Phrase match)
|
||||||
|
if (queryLower.length > 1) {
|
||||||
|
if (pathLower === queryLower) {
|
||||||
|
score += 120;
|
||||||
|
matchReasons.push("路径完全匹配");
|
||||||
|
} else if (pathLower.includes(queryLower)) {
|
||||||
|
score += 80;
|
||||||
|
matchReasons.push(`路径包含 "${queryLower}"`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (titleLower === queryLower) {
|
||||||
|
score += 100;
|
||||||
|
matchReasons.push("标题完全匹配");
|
||||||
|
} else if (titleLower.includes(queryLower)) {
|
||||||
|
score += 60;
|
||||||
|
matchReasons.push(`标题包含 "${queryLower}"`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (categoryLower.includes(queryLower)) {
|
||||||
|
score += 40;
|
||||||
|
matchReasons.push(`模块: ${item.category}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (paramLower.includes(queryLower)) {
|
||||||
|
score += 45;
|
||||||
|
const idx = paramLower.indexOf(queryLower);
|
||||||
|
const snippet = (item.parameters || "")
|
||||||
|
.substring(Math.max(0, idx - 12), Math.min(item.parameters?.length || 0, idx + 30))
|
||||||
|
.replace(/\s+/g, " ");
|
||||||
|
matchReasons.push(`参数规格: ...${snippet}...`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sectionsLower.includes(queryLower)) {
|
||||||
|
score += 35;
|
||||||
|
const idx = sectionsLower.indexOf(queryLower);
|
||||||
|
const snippet = allSectionsText
|
||||||
|
.substring(Math.max(0, idx - 12), Math.min(allSectionsText.length, idx + 30))
|
||||||
|
.replace(/\s+/g, " ");
|
||||||
|
matchReasons.push(`正文段落: ...${snippet}...`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Token 分词逐项匹配 (Multi-token match)
|
||||||
|
let tokensMatched = 0;
|
||||||
|
for (const token of tokens) {
|
||||||
|
let tokenMatched = false;
|
||||||
|
|
||||||
|
if (pathLower.includes(token)) {
|
||||||
|
score += 30;
|
||||||
|
tokenMatched = true;
|
||||||
|
if (!matchReasons.some((r) => r.includes(token))) {
|
||||||
|
matchReasons.push(`路径含 "${token}"`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (titleLower.includes(token)) {
|
||||||
|
score += 25;
|
||||||
|
tokenMatched = true;
|
||||||
|
if (!matchReasons.some((r) => r.includes(token))) {
|
||||||
|
matchReasons.push(`标题含 "${token}"`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (categoryLower.includes(token)) {
|
||||||
|
score += 20;
|
||||||
|
tokenMatched = true;
|
||||||
|
if (!matchReasons.some((r) => r.includes(token))) {
|
||||||
|
matchReasons.push(`分类含 "${token}"`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (paramLower.includes(token)) {
|
||||||
|
score += 20;
|
||||||
|
tokenMatched = true;
|
||||||
|
if (!matchReasons.some((r) => r.includes(token))) {
|
||||||
|
const idx = paramLower.indexOf(token);
|
||||||
|
const snippet = (item.parameters || "")
|
||||||
|
.substring(Math.max(0, idx - 10), Math.min(item.parameters?.length || 0, idx + 25))
|
||||||
|
.replace(/\s+/g, " ");
|
||||||
|
matchReasons.push(`参数: ...${snippet}...`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (sectionsLower.includes(token)) {
|
||||||
|
score += 15;
|
||||||
|
tokenMatched = true;
|
||||||
|
if (!matchReasons.some((r) => r.includes(token))) {
|
||||||
|
const idx = sectionsLower.indexOf(token);
|
||||||
|
const snippet = allSectionsText
|
||||||
|
.substring(Math.max(0, idx - 10), Math.min(allSectionsText.length, idx + 25))
|
||||||
|
.replace(/\s+/g, " ");
|
||||||
|
matchReasons.push(`正文: ...${snippet}...`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (curlLower.includes(token) || respLower.includes(token)) {
|
||||||
|
score += 15;
|
||||||
|
tokenMatched = true;
|
||||||
|
if (!matchReasons.some((r) => r.includes(token))) {
|
||||||
|
matchReasons.push(`请求/响应含 "${token}"`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (tokenMatched) tokensMatched++;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 多词全部命中奖励 (All-tokens match bonus)
|
||||||
|
if (tokens.length > 1 && tokensMatched === tokens.length) {
|
||||||
|
score += 50;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (score <= 0 || tokensMatched === 0) return null;
|
||||||
|
|
||||||
|
const matchReason = matchReasons.slice(0, 2).join(" | ");
|
||||||
|
return {
|
||||||
|
item: {
|
||||||
|
...item,
|
||||||
|
matchReason,
|
||||||
|
},
|
||||||
|
score,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 搜索开放平台接口与指南文档
|
||||||
|
*/
|
||||||
|
export async function searchDocs(
|
||||||
|
query: DocSearchQuery = {},
|
||||||
|
options?: { forceRefresh?: boolean; baseUrl?: string }
|
||||||
|
): Promise<DocSearchResult> {
|
||||||
|
const catalog = await getDocsCatalog(options);
|
||||||
|
let items = catalog.items;
|
||||||
|
|
||||||
|
// 1. 分类过滤
|
||||||
|
if (query.category) {
|
||||||
|
const catLower = query.category.trim().toLowerCase();
|
||||||
|
items = items.filter((item) =>
|
||||||
|
item.category.toLowerCase().includes(catLower)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. HTTP 方法过滤
|
||||||
|
if (query.method) {
|
||||||
|
const methodUpper = query.method.trim().toUpperCase();
|
||||||
|
items = items.filter((item) => item.method === methodUpper);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 接口路径匹配过滤
|
||||||
|
if (query.path) {
|
||||||
|
const pathLower = query.path.trim().toLowerCase();
|
||||||
|
items = items.filter((item) =>
|
||||||
|
(item.path || "").toLowerCase().includes(pathLower)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. 关键词打分与排序
|
||||||
|
const rawKeyword = query.keyword?.trim();
|
||||||
|
if (rawKeyword) {
|
||||||
|
const scored = items
|
||||||
|
.map((item) => evaluateDocMatch(item, rawKeyword))
|
||||||
|
.filter((entry): entry is { item: OpenApiDocItem; score: number } => entry !== null)
|
||||||
|
.sort((a, b) => b.score - a.score);
|
||||||
|
|
||||||
|
items = scored.map((entry) => entry.item);
|
||||||
|
}
|
||||||
|
|
||||||
|
const total = items.length;
|
||||||
|
const limit = Math.max(1, Math.min(query.limit ?? 20, 100));
|
||||||
|
const pagedItems = items.slice(0, limit);
|
||||||
|
|
||||||
|
return {
|
||||||
|
total,
|
||||||
|
keyword: rawKeyword,
|
||||||
|
category: query.category,
|
||||||
|
method: query.method,
|
||||||
|
items: pagedItems,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按 ID、Path、URL 或文档标题精确解析单篇文档详情
|
||||||
|
*/
|
||||||
|
export async function getDocDetail(
|
||||||
|
target: string,
|
||||||
|
options?: { forceRefresh?: boolean; baseUrl?: string }
|
||||||
|
): Promise<OpenApiDocItem | undefined> {
|
||||||
|
const catalog = await getDocsCatalog(options);
|
||||||
|
const cleanTarget = target.trim();
|
||||||
|
if (!cleanTarget) return undefined;
|
||||||
|
|
||||||
|
const targetLower = cleanTarget.toLowerCase();
|
||||||
|
|
||||||
|
// 1. 按数字 ID 精确查找
|
||||||
|
const idNum = Number(cleanTarget);
|
||||||
|
if (!Number.isNaN(idNum)) {
|
||||||
|
const byId = catalog.items.find((item) => item.id === idNum);
|
||||||
|
if (byId) return byId;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 按接口 Path 精确查找 (如 /api/openapi/v1/roleDefGroups)
|
||||||
|
const byExactPath = catalog.items.find(
|
||||||
|
(item) => (item.path || "").toLowerCase() === targetLower
|
||||||
|
);
|
||||||
|
if (byExactPath) return byExactPath;
|
||||||
|
|
||||||
|
// 3. 按文档 URL 精确查找 (如 /docs/open-api/corporation/get-roles-group)
|
||||||
|
const byExactUrl = catalog.items.find(
|
||||||
|
(item) => item.url.toLowerCase() === targetLower
|
||||||
|
);
|
||||||
|
if (byExactUrl) return byExactUrl;
|
||||||
|
|
||||||
|
// 4. 按标题精确查找
|
||||||
|
const byExactTitle = catalog.items.find(
|
||||||
|
(item) => item.title.toLowerCase() === targetLower
|
||||||
|
);
|
||||||
|
if (byExactTitle) return byExactTitle;
|
||||||
|
|
||||||
|
// 5. 模糊前缀/子串匹配(取最相似的第一个)
|
||||||
|
return (
|
||||||
|
catalog.items.find((item) => (item.path || "").toLowerCase().includes(targetLower)) ||
|
||||||
|
catalog.items.find((item) => item.url.toLowerCase().includes(targetLower)) ||
|
||||||
|
catalog.items.find((item) => item.title.toLowerCase().includes(targetLower))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取开放平台所有业务模块分类与文档数量汇总
|
||||||
|
*/
|
||||||
|
export async function listCategories(options?: {
|
||||||
|
forceRefresh?: boolean;
|
||||||
|
baseUrl?: string;
|
||||||
|
}): Promise<DocCategoryInfo[]> {
|
||||||
|
const catalog = await getDocsCatalog(options);
|
||||||
|
const map = new Map<string, { count: number; endpointsCount: number }>();
|
||||||
|
|
||||||
|
for (const item of catalog.items) {
|
||||||
|
const cat = item.category || "未分类";
|
||||||
|
const current = map.get(cat) || { count: 0, endpointsCount: 0 };
|
||||||
|
current.count += 1;
|
||||||
|
if (item.method && item.path) {
|
||||||
|
current.endpointsCount += 1;
|
||||||
|
}
|
||||||
|
map.set(cat, current);
|
||||||
|
}
|
||||||
|
|
||||||
|
const result: DocCategoryInfo[] = [];
|
||||||
|
for (const [name, stats] of map.entries()) {
|
||||||
|
result.push({
|
||||||
|
name,
|
||||||
|
count: stats.count,
|
||||||
|
endpointsCount: stats.endpointsCount,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return result.sort((a, b) => b.count - a.count);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 手动强制同步线上文档中心索引并重载本地持久化缓存
|
||||||
|
*/
|
||||||
|
export async function syncDocsCatalog(options?: {
|
||||||
|
baseUrl?: string;
|
||||||
|
}): Promise<{
|
||||||
|
success: boolean;
|
||||||
|
totalDocs: number;
|
||||||
|
totalEndpoints: number;
|
||||||
|
source: string;
|
||||||
|
updatedAt: string;
|
||||||
|
}> {
|
||||||
|
const catalog = await getDocsCatalog({
|
||||||
|
forceRefresh: true,
|
||||||
|
baseUrl: options?.baseUrl,
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
totalDocs: catalog.totalDocs,
|
||||||
|
totalEndpoints: catalog.totalEndpoints,
|
||||||
|
source: catalog.sourceUrl,
|
||||||
|
updatedAt: catalog.updatedAt,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
export const DocSectionSchema = z.object({
|
||||||
|
title: z.string().default("概述"),
|
||||||
|
content: z.string().default(""),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const OpenApiDocItemSchema = z.object({
|
||||||
|
id: z.number(),
|
||||||
|
title: z.string().default(""),
|
||||||
|
category: z.string().default("未分类"),
|
||||||
|
url: z.string().default(""),
|
||||||
|
permalink: z.string().default(""),
|
||||||
|
method: z.string().optional(),
|
||||||
|
path: z.string().optional(),
|
||||||
|
breadcrumbs: z.array(z.string()).default([]),
|
||||||
|
headings: z.array(z.string()).default([]),
|
||||||
|
sections: z.array(DocSectionSchema).default([]),
|
||||||
|
parameters: z.string().optional(),
|
||||||
|
curl: z.string().optional(),
|
||||||
|
responseSample: z.string().optional(),
|
||||||
|
matchReason: z.string().optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const DocCatalogSchema = z.object({
|
||||||
|
version: z.string().default("1.0.0"),
|
||||||
|
updatedAt: z.string(),
|
||||||
|
sourceUrl: z.string().default("https://docs.ekuaibao.com/search-index.json"),
|
||||||
|
totalDocs: z.number(),
|
||||||
|
totalEndpoints: z.number(),
|
||||||
|
items: z.array(OpenApiDocItemSchema),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type DocSection = z.infer<typeof DocSectionSchema>;
|
||||||
|
export type OpenApiDocItem = z.infer<typeof OpenApiDocItemSchema>;
|
||||||
|
export type DocCatalog = z.infer<typeof DocCatalogSchema>;
|
||||||
|
|
||||||
|
export interface DocSearchQuery {
|
||||||
|
keyword?: string;
|
||||||
|
category?: string;
|
||||||
|
method?: string;
|
||||||
|
path?: string;
|
||||||
|
limit?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DocSearchResult {
|
||||||
|
total: number;
|
||||||
|
keyword?: string;
|
||||||
|
category?: string;
|
||||||
|
method?: string;
|
||||||
|
items: OpenApiDocItem[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DocCategoryInfo {
|
||||||
|
name: string;
|
||||||
|
count: number;
|
||||||
|
endpointsCount: number;
|
||||||
|
}
|
||||||
@@ -17,7 +17,7 @@ domains/feetype/tools.ts (业务编排:树展开、路径计算、字段规
|
|||||||
domains/feetype/api.ts (HTTP 传输层:直连 /api/v1/form/feeTypes 与 /api/form/v2/specifications)
|
domains/feetype/api.ts (HTTP 传输层:直连 /api/v1/form/feeTypes 与 /api/form/v2/specifications)
|
||||||
│
|
│
|
||||||
▼
|
▼
|
||||||
core/http/session-client.ts (企业会话客户端与凭证注入)
|
core/http/hose-web-session-client.ts (企业会话客户端与凭证注入)
|
||||||
```
|
```
|
||||||
|
|
||||||
## 接口路由映射
|
## 接口路由映射
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { createSessionClient } from "../../core/http/session-client.js";
|
import { createSessionClient } from "../../core/http/hose-web-session-client.js";
|
||||||
import type { CorpConfig } from "../../core/config/types.js";
|
import type { CorpConfig } from "../../core/config/types.js";
|
||||||
import {
|
import {
|
||||||
fetchDesktopMenuTree,
|
fetchDesktopMenuTree,
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ hose-use platform list
|
|||||||
hose-use platform get <应用 ID|名称>
|
hose-use platform get <应用 ID|名称>
|
||||||
hose-use platform entities <应用 ID|名称>
|
hose-use platform entities <应用 ID|名称>
|
||||||
hose-use platform schema <应用 ID|名称> [对象 ID|名称] [--keyword <字段关键词>]
|
hose-use platform schema <应用 ID|名称> [对象 ID|名称] [--keyword <字段关键词>]
|
||||||
hose-use platform records <应用 ID|名称> <对象 ID|名称> [--page <页码>] [--count <每页条数>] [--all] [--keyword <关键词>] [--search-fields <字段列表>] [--filter <表达式>] [--where <条件>] [--sum <字段1,字段2>] [--group-by <字段>] [--fields <字段列表>] [--flat] [--ndjson] [--stats]
|
hose-use platform records [应用 ID|名称] <对象 ID|名称> [--page <页码>] [--count <每页条数>] [--all] [--keyword <关键词>] [--search-fields <字段列表>] [--filter <表达式>] [--where <条件>] [--sum <字段1,字段2>] [--group-by <字段>] [--fields <字段列表>] [--flat] [--ndjson] [--stats]
|
||||||
hose-use platform record get [<应用> <业务对象>] <记录ID>
|
hose-use platform record get [<应用> <业务对象>] <记录ID>
|
||||||
hose-use platform record toggle <应用> <业务对象> <记录ID> [--state=true|false] [--dry-run|--yes]
|
hose-use platform record toggle <应用> <业务对象> <记录ID> [--state=true|false] [--dry-run|--yes]
|
||||||
hose-use platform record edit <应用> <业务对象> <记录ID> [--set="字段=值" | --data='{"field": "val"}'] [--raw] [--dry-run|--yes]
|
hose-use platform record edit <应用> <业务对象> <记录ID> [--set="字段=值" | --data='{"field": "val"}'] [--raw] [--dry-run|--yes]
|
||||||
@@ -47,7 +47,11 @@ hose-use platform imports <应用 ID|名称> <对象 ID|名称>
|
|||||||
|
|
||||||
也可以使用 `datalink` / `data-link` 作为同义命令域。
|
也可以使用 `datalink` / `data-link` 作为同义命令域。
|
||||||
|
|
||||||
|
- `records <业务对象>`(单参数免应用查询):当企业自建应用较多时,无需事先查询 platformId。直接输入业务对象名称或编码,CLI 自动遍历企业全量自建应用进行智能反查与寻址;若跨应用重名则抛出精准候选项提示,避免人工心智负担。
|
||||||
|
|
||||||
- `records --ndjson`(或 `--stream`):针对万级~十万级海量记录,采用 AsyncGenerator 分页流式生成,逐行向 `stdout` 发射 NDJSON。内存恒定为 $O(\text{pageSize})$,严防大报文撑爆内存或终端,无缝对接下游 `jq`、Python 处理流水线。
|
- `records --ndjson`(或 `--stream`):针对万级~十万级海量记录,采用 AsyncGenerator 分页流式生成,逐行向 `stdout` 发射 NDJSON。内存恒定为 $O(\text{pageSize})$,严防大报文撑爆内存或终端,无缝对接下游 `jq`、Python 处理流水线。
|
||||||
|
|
||||||
|
- `records --all`:全量记录不再直接返回 JSON/表格;必须与 `--ndjson --output-file <path>` 一起使用,否则返回 `DATASET_TOO_LARGE`(exitCode 2)并附分页/流式导出建议。`--json` 模式下该错误以 `{ error, code, message, exitCode, nextAction, suggestions }` 结构化输出,Agent 可直接解析。
|
||||||
- 终端入口提供显式输出回调并等待写入完成以响应背压;`--ndjson -o <path>` 写入真正的 NDJSON 文件,返回文件路径、字节数和记录数摘要。
|
- 终端入口提供显式输出回调并等待写入完成以响应背压;`--ndjson -o <path>` 写入真正的 NDJSON 文件,返回文件路径、字节数和记录数摘要。
|
||||||
- MCP / HTTP 默认不提供终端输出通道;未指定文件时拒绝直接流式输出,避免污染协议 stdout 或返回空的成功响应。输出逐行执行统一脱敏。
|
- MCP / HTTP 默认不提供终端输出通道;未指定文件时拒绝直接流式输出,避免污染协议 stdout 或返回空的成功响应。输出逐行执行统一脱敏。
|
||||||
- `records --page=<页码> --count=<每页>`:分页查询,默认 `count=20`;用于替代无边界全量拉取。
|
- `records --page=<页码> --count=<每页>`:分页查询,默认 `count=20`;用于替代无边界全量拉取。
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ hose-use workflow list [--platform-id=<id>|--app-id=<id>] [-q|--keyword=<关键
|
|||||||
hose-use workflow get <pipelineId>
|
hose-use workflow get <pipelineId>
|
||||||
hose-use workflow enum [thirdId] [--third-id=<id>] [--json]
|
hose-use workflow enum [thirdId] [--third-id=<id>] [--json]
|
||||||
hose-use workflow analyze <pipelineId> [--json]
|
hose-use workflow analyze <pipelineId> [--json]
|
||||||
hose-use workflow logs <pipelineId> [--has-error] [--state=FAILED]
|
hose-use workflow logs <pipelineId> [--flow=<单号>] [--has-error] [--state=FAILED]
|
||||||
hose-use workflow job <jobId> [--failed] [--node=<name|id>] [--verbose]
|
hose-use workflow job <jobId> [--failed] [--node=<name|id>] [--verbose]
|
||||||
hose-use workflow diff <snapshotId1> <snapshotId2> [--pipelineId=<id>]
|
hose-use workflow diff <snapshotId1> <snapshotId2> [--pipelineId=<id>]
|
||||||
hose-use workflow diff-job <jobId1> <jobId2> [--json]
|
hose-use workflow diff-job <jobId1> <jobId2> [--json]
|
||||||
@@ -30,7 +30,7 @@ hose-use workflow create [--name=<名称>] [--trigger=webhook|clock|datalink|flo
|
|||||||
hose-use workflow copy <pipelineId> [--name=<名称>] [--platform-id=<应用ID>] [--dry-run|--yes]
|
hose-use workflow copy <pipelineId> [--name=<名称>] [--platform-id=<应用ID>] [--dry-run|--yes]
|
||||||
hose-use workflow delete <pipelineId> [--dry-run|--yes]
|
hose-use workflow delete <pipelineId> [--dry-run|--yes]
|
||||||
hose-use workflow nodes [list] [--all]
|
hose-use workflow nodes [list] [--all]
|
||||||
hose-use workflow nodes grant <type...> [--password=<pwd>] [--is-test] [--dry-run|--yes]
|
hose-use workflow nodes grant <type...> [--password=<pwd>] [--is-test] [--allow-prod] [--dry-run|--yes]
|
||||||
hose-use workflow node list <pipelineId>
|
hose-use workflow node list <pipelineId>
|
||||||
hose-use workflow node get <pipelineId> <节点name或#序号>
|
hose-use workflow node get <pipelineId> <节点name或#序号>
|
||||||
hose-use workflow node add <pipelineId> --type=code-js2 --label="清洗" --display-name="清洗节点" --code="..." [--after=<节点>] [--parent=<容器>] [--dry-run|--yes]
|
hose-use workflow node add <pipelineId> --type=code-js2 --label="清洗" --display-name="清洗节点" --code="..." [--after=<节点>] [--parent=<容器>] [--dry-run|--yes]
|
||||||
@@ -44,6 +44,7 @@ hose-use workflow eval-script --code="return a + b;" --input='{"a":1,"b":2}'
|
|||||||
```
|
```
|
||||||
|
|
||||||
- `workflow list [-q|--keyword=<关键词>] [--full]`:工作流列表。默认采用**轻量化紧凑模式**,自动剥离每个流程内部包含的庞大 `tasks` 节点树与 MVEL/JS 脚本代码(仅保留 `nodeCount` 统计与核心元数据),将输出报文体积削减 97%(从数兆降至几十 KB),彻底解决上下文截断。传入 `--full` 或 `--with-tasks` 时恢复输出完整节点树。支持 `-q / --keyword` 模糊匹配工作流名称、ID 与应用名称。
|
- `workflow list [-q|--keyword=<关键词>] [--full]`:工作流列表。默认采用**轻量化紧凑模式**,自动剥离每个流程内部包含的庞大 `tasks` 节点树与 MVEL/JS 脚本代码(仅保留 `nodeCount` 统计与核心元数据),将输出报文体积削减 97%(从数兆降至几十 KB),彻底解决上下文截断。传入 `--full` 或 `--with-tasks` 时恢复输出完整节点树。支持 `-q / --keyword` 模糊匹配工作流名称、ID 与应用名称。
|
||||||
|
- `workflow logs <pipelineId> --flow=<单号>`:按业务单号(如报销单/销账单号)秒级定位对应的 Job 实例。由于外部 Piper API 原生无单号索引,CLI 引入「本地 SQLite 缓存 + 流式探查早停熔断」机制:首次探查边扫描边建立本地单号索引,后续命中直接 0ms 返回,避免全表盲目拉取。
|
||||||
|
|
||||||
## 触发器分类与调测路径分支 (Path Branching)
|
## 触发器分类与调测路径分支 (Path Branching)
|
||||||
|
|
||||||
@@ -102,6 +103,7 @@ hose-use workflow eval-script --code="return a + b;" --input='{"a":1,"b":2}'
|
|||||||
- 执行 `hose-use workflow nodes` 查看当前租户已开通的节点字典;
|
- 执行 `hose-use workflow nodes` 查看当前租户已开通的节点字典;
|
||||||
- 执行 `hose-use workflow nodes --all` 查看当前企业与官方全量 108 个灰度节点清单的开通状态对照;
|
- 执行 `hose-use workflow nodes --all` 查看当前企业与官方全量 108 个灰度节点清单的开通状态对照;
|
||||||
- 执行 `hose-use workflow nodes grant <type...>` 申请开通灰度节点(内置管理员密码预留设计:未配置环境变量 `HOSE_ADMIN_PASSWORD` 时为免密便捷模式;配置后强制要求 `--password` 授权)。
|
- 执行 `hose-use workflow nodes grant <type...>` 申请开通灰度节点(内置管理员密码预留设计:未配置环境变量 `HOSE_ADMIN_PASSWORD` 时为免密便捷模式;配置后强制要求 `--password` 授权)。
|
||||||
|
- 正式生产企业默认被硬拦截;确需在生产环境开通时,必须显式追加 `--allow-prod`,并继续遵守 `--dry-run` → `--yes` 两阶段确认。`--is-test` 只切换 Piper 域名,不构成生产授权。
|
||||||
|
|
||||||
## 静态分析器:诊断边界显式化(硬门禁 vs 软建议)
|
## 静态分析器:诊断边界显式化(硬门禁 vs 软建议)
|
||||||
|
|
||||||
@@ -159,7 +161,7 @@ MVEL 本地仿真支持的是转译子集:零参 `HashMap` / `ArrayList` 及 `
|
|||||||
|
|
||||||
节点卡片标题保存在 `displayName`,用 `--display-name` 修改;`--label` 是节点类型标题,服务端保存时可能按节点类型重新生成,不能可靠地用于重命名已有节点。设计器前端把节点标题限制为 20 个字符;后端本身不校验该长度(实测 21 字仍可保存),本地 CLI 按前端上限强制校验,超过 20 个 Unicode 字符会在写入前抛出 `ValidationError`。条件/内置节点类型的 `desc` 也由平台按配置重新生成,自定义 `--desc` 可能不会持久化。
|
节点卡片标题保存在 `displayName`,用 `--display-name` 修改;`--label` 是节点类型标题,服务端保存时可能按节点类型重新生成,不能可靠地用于重命名已有节点。设计器前端把节点标题限制为 20 个字符;后端本身不校验该长度(实测 21 字仍可保存),本地 CLI 按前端上限强制校验,超过 20 个 Unicode 字符会在写入前抛出 `ValidationError`。条件/内置节点类型的 `desc` 也由平台按配置重新生成,自定义 `--desc` 可能不会持久化。
|
||||||
|
|
||||||
灰度开通遵循统一写操作门禁:`--dry-run` 仅返回归一化节点清单且不调用网关;实际开通需要 `--yes/--confirm`。管理员密码用于额外授权,不能替代写操作确认。
|
灰度开通遵循统一写操作门禁:`--dry-run` 仅返回归一化节点清单且不调用网关;实际开通需要 `--yes/--confirm`。生产企业额外要求显式 `--allow-prod`。管理员密码用于额外授权,不能替代写操作确认。
|
||||||
|
|
||||||
节点定位约定:CLI 的字符串编号(如 `3`、`2.1`)始终对应列表展示的层级编号;SDK 传入数字 `3` 时表示深度优先遍历的第 3 个节点。节点名称仍可直接用于定位,两个编号体系不再在一次查找中竞争。
|
节点定位约定:CLI 的字符串编号(如 `3`、`2.1`)始终对应列表展示的层级编号;SDK 传入数字 `3` 时表示深度优先遍历的第 3 个节点。节点名称仍可直接用于定位,两个编号体系不再在一次查找中竞争。
|
||||||
|
|
||||||
@@ -349,3 +351,16 @@ hose-use --corp=<企业ID> workflow get <pipelineId> --json \
|
|||||||
已有流程若 `$snapshot` 为空(例如由 CLI 复制/创建产生),需要用全量保存补齐快照条目:读取 `workflow get --json`、在 `$snapshot` 中按 `<taskPath>.url-snapshot` 追加富文本模型,再 `workflow save --file=<json> --yes`。
|
已有流程若 `$snapshot` 为空(例如由 CLI 复制/创建产生),需要用全量保存补齐快照条目:读取 `workflow get --json`、在 `$snapshot` 中按 `<taskPath>.url-snapshot` 追加富文本模型,再 `workflow save --file=<json> --yes`。
|
||||||
|
|
||||||
富文本模型形如:`root → paragraph → [text, context-tag(choose), text]`,三段的拼接结果必须等同于 `url` 字段。
|
富文本模型形如:`root → paragraph → [text, context-tag(choose), text]`,三段的拼接结果必须等同于 `url` 字段。
|
||||||
|
|
||||||
|
## 上游官方规范与参考依据 (Upstream References)
|
||||||
|
|
||||||
|
本域在解析底层数据格式、变量选择树与灰度节点规范时,参考了合思/易快报官方公开的开源仓库定义:
|
||||||
|
|
||||||
|
1. **HoseCloud Hab 任务插件框架**:[`ekuaibao/Hab-Plugin`](https://github.com/ekuaibao/Hab-Plugin)
|
||||||
|
- **底层数据类型**:定义了 39 类官方底层字段数据类型(`com.hosecloud.hab.plugin.DataType`,如 `TEXT`, `MONEY`, `FLOW_FORM`, `DATA_LINK`, `REQUISITION_ITEMS` 等)与 8 种选择项类型(`Choose.ItemType`),收录于 `catalog/enums.ts`(`WORKFLOW_DATA_TYPES` 与 `WORKFLOW_CHOOSE_ITEM_TYPES`);
|
||||||
|
- **动态任务节点机制**:阐明了合思工作流中 `task-dynamic-*`(如官方延迟等待节点 `task-dynamic-delay`)的 PF4J 插件化容器与执行生命周期;
|
||||||
|
- **架构边界说明**:`hose-use` 仅作为合思平台工作流的客户端 CLI、SDK 编排与诊断工具,**不开发或篡改其服务端底层运行时,亦不违规在客户端捏造服务端未支持的自造节点类型**。所有节点类型必须严格对齐服务端或官方灰度清单(`GRAY_NODES_CATALOG`)。
|
||||||
|
|
||||||
|
2. **开放平台接口文档中心**:[`ekuaibao/open-platform-docs`](https://github.com/ekuaibao/open-platform-docs)
|
||||||
|
- 包含开放平台 23 大类、249 篇接口规范,作为工作流 HTTP 节点 (`http`) 与 OpenAPI 任务节点 (`task-openapi`) 的调用路径、参数规格与应用权限映射基准。
|
||||||
|
|
||||||
@@ -5,6 +5,10 @@ import {
|
|||||||
isWorkflowActionCode,
|
isWorkflowActionCode,
|
||||||
matchWorkflowAction,
|
matchWorkflowAction,
|
||||||
resolveWorkflowEnumOptions,
|
resolveWorkflowEnumOptions,
|
||||||
|
WORKFLOW_DATA_TYPES,
|
||||||
|
WORKFLOW_CHOOSE_ITEM_TYPES,
|
||||||
|
isWorkflowDataType,
|
||||||
|
isWorkflowChooseItemType,
|
||||||
} from "../services.js";
|
} from "../services.js";
|
||||||
import { analyzeWorkflow } from "../analysis/index.js";
|
import { analyzeWorkflow } from "../analysis/index.js";
|
||||||
|
|
||||||
@@ -182,4 +186,25 @@ describe("Workflow Action Enums & Diagnostics", () => {
|
|||||||
expect(codes).not.toContain("DEADLOCK_CONDITION_STATE_FILTER");
|
expect(codes).not.toContain("DEADLOCK_CONDITION_STATE_FILTER");
|
||||||
expect(codes).not.toContain("INVALID_ACTION_ENUM_TEXT_VALUE");
|
expect(codes).not.toContain("INVALID_ACTION_ENUM_TEXT_VALUE");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("verifies official workflow DataType definitions from Hab-Plugin", () => {
|
||||||
|
// 官方参考: https://github.com/ekuaibao/Hab-Plugin (com.hosecloud.hab.plugin.DataType)
|
||||||
|
expect(WORKFLOW_DATA_TYPES).toHaveLength(39);
|
||||||
|
expect(isWorkflowDataType("TEXT")).toBe(true);
|
||||||
|
expect(isWorkflowDataType("MONEY")).toBe(true);
|
||||||
|
expect(isWorkflowDataType("FLOW_FORM")).toBe(true);
|
||||||
|
expect(isWorkflowDataType("DATA_LINK")).toBe(true);
|
||||||
|
expect(isWorkflowDataType("REQUISITION_ITEMS")).toBe(true);
|
||||||
|
expect(isWorkflowDataType("NOT_A_REAL_TYPE")).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("verifies official workflow Choose ItemType definitions from Hab-Plugin", () => {
|
||||||
|
// 官方参考: https://github.com/ekuaibao/Hab-Plugin (com.hosecloud.hab.plugin.Choose.ItemType)
|
||||||
|
expect(WORKFLOW_CHOOSE_ITEM_TYPES).toHaveLength(8);
|
||||||
|
expect(isWorkflowChooseItemType("TEXT")).toBe(true);
|
||||||
|
expect(isWorkflowChooseItemType("NUMBER")).toBe(true);
|
||||||
|
expect(isWorkflowChooseItemType("MONEY")).toBe(true);
|
||||||
|
expect(isWorkflowChooseItemType("BOOLEAN")).toBe(true);
|
||||||
|
expect(isWorkflowChooseItemType("UNKNOWN")).toBe(false);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -57,3 +57,86 @@ export function matchWorkflowAction(query: string): WorkflowActionEnumItem | und
|
|||||||
(item) => item.code.toLowerCase() === trimmed.toLowerCase() || item.label === trimmed || item.name === trimmed
|
(item) => item.code.toLowerCase() === trimmed.toLowerCase() || item.label === trimmed || item.name === trimmed
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── 工作流底层官方字段类型与 Choose 类型枚举 ────────────────────────────────────
|
||||||
|
// 来源于 HoseCloud Hab 官方插件框架底层定义 (https://github.com/ekuaibao/Hab-Plugin)
|
||||||
|
// 参考规范:com.hosecloud.hab.plugin.DataType 与 com.hosecloud.hab.plugin.Choose.ItemType
|
||||||
|
// 说明:仅作为客户端变量解析、字段类型断言与 Schema 校验依据,不侵入平台服务端内部插件实现。
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 合思/易快报工作流官方字段底层数据类型枚举(共 39 类)
|
||||||
|
* 对应 HoseCloud Hab 插件框架 com.hosecloud.hab.plugin.DataType (https://github.com/ekuaibao/Hab-Plugin)
|
||||||
|
*/
|
||||||
|
export const WORKFLOW_DATA_TYPES = [
|
||||||
|
"TEXT",
|
||||||
|
"AUTO_NUMBER",
|
||||||
|
"NUMBER",
|
||||||
|
"MONEY",
|
||||||
|
"BOOLEAN",
|
||||||
|
"SWITCH",
|
||||||
|
"DATE",
|
||||||
|
"DATE_RANGE",
|
||||||
|
"DEPARTMENT",
|
||||||
|
"FEISHU_DEPARTMENT",
|
||||||
|
"STAFF",
|
||||||
|
"STAFF_LIST",
|
||||||
|
"DATA_LINK",
|
||||||
|
"DATA_LINK_LIST",
|
||||||
|
"PAYEE_INFO",
|
||||||
|
"DIMENSION",
|
||||||
|
"DIMENSION_LIST",
|
||||||
|
"ENUM",
|
||||||
|
"LIST",
|
||||||
|
"MAP",
|
||||||
|
"FLOW_TEMPLATE",
|
||||||
|
"CITY",
|
||||||
|
"_SELECT_INVOICE_TYPE_",
|
||||||
|
"ATTACHMENT",
|
||||||
|
"REQUISITION_ITEMS",
|
||||||
|
"FEE_DETAIL",
|
||||||
|
"FEE_DETAIL_ITEM",
|
||||||
|
"FLOW_FORM",
|
||||||
|
"FLOW_FORM_ITEM",
|
||||||
|
"RECORD_LINK",
|
||||||
|
"RECORD_LINK_LIST",
|
||||||
|
"VISIBILITY",
|
||||||
|
"ROLE",
|
||||||
|
"ZS_TYPE",
|
||||||
|
"ZS_LIST",
|
||||||
|
"SELECT_INVOICE_CORPORATION",
|
||||||
|
"FREQUENCY",
|
||||||
|
"DATALINK_FILTERS",
|
||||||
|
"UNDEFINED",
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
export type WorkflowDataType = (typeof WORKFLOW_DATA_TYPES)[number];
|
||||||
|
|
||||||
|
const WORKFLOW_DATA_TYPES_SET = new Set<string>(WORKFLOW_DATA_TYPES);
|
||||||
|
|
||||||
|
export function isWorkflowDataType(type: string): type is WorkflowDataType {
|
||||||
|
return WORKFLOW_DATA_TYPES_SET.has(type);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 合思/易快报工作流 Choose 选择项官方基础类型
|
||||||
|
* 对应 HoseCloud Hab 插件框架 com.hosecloud.hab.plugin.Choose.ItemType
|
||||||
|
*/
|
||||||
|
export const WORKFLOW_CHOOSE_ITEM_TYPES = [
|
||||||
|
"TEXT",
|
||||||
|
"NUMBER",
|
||||||
|
"BOOLEAN",
|
||||||
|
"DATE",
|
||||||
|
"DATA_RANGE",
|
||||||
|
"LIST",
|
||||||
|
"MAP",
|
||||||
|
"MONEY",
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
export type WorkflowChooseItemType = (typeof WORKFLOW_CHOOSE_ITEM_TYPES)[number];
|
||||||
|
|
||||||
|
const WORKFLOW_CHOOSE_ITEM_TYPES_SET = new Set<string>(WORKFLOW_CHOOSE_ITEM_TYPES);
|
||||||
|
|
||||||
|
export function isWorkflowChooseItemType(type: string): type is WorkflowChooseItemType {
|
||||||
|
return WORKFLOW_CHOOSE_ITEM_TYPES_SET.has(type);
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||||
|
import { closeDatabase, getDatabase } from "../../../../core/db/connection.js";
|
||||||
|
import {
|
||||||
|
extractJobFlowCode,
|
||||||
|
searchWorkflowJobByFlowCode,
|
||||||
|
} from "./search-by-flow.js";
|
||||||
|
|
||||||
|
describe("Workflow - 按单号查找运行实例 (searchWorkflowJobByFlowCode)", () => {
|
||||||
|
const originalDbEnv = process.env.HOSE_APPROVAL_DB;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
process.env.HOSE_APPROVAL_DB = ":memory:";
|
||||||
|
getDatabase(":memory:");
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
closeDatabase();
|
||||||
|
if (originalDbEnv !== undefined) {
|
||||||
|
process.env.HOSE_APPROVAL_DB = originalDbEnv;
|
||||||
|
} else {
|
||||||
|
delete process.env.HOSE_APPROVAL_DB;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("extractJobFlowCode 能准确从各类 inputs 结构或顶层字段解析出单号", () => {
|
||||||
|
expect(extractJobFlowCode(null)).toBeUndefined();
|
||||||
|
expect(extractJobFlowCode({})).toBeUndefined();
|
||||||
|
expect(extractJobFlowCode({ inputs: { code: " XZ2610474 " } })).toBe("XZ2610474");
|
||||||
|
expect(extractJobFlowCode({ inputs: { flowCode: "BX20261101" } })).toBe("BX20261101");
|
||||||
|
expect(extractJobFlowCode({ code: "JK20260901" })).toBe("JK20260901");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("空单号直接返回未找到", async () => {
|
||||||
|
const dummyClient = {} as any;
|
||||||
|
const res = await searchWorkflowJobByFlowCode(dummyClient, "corp1", "pipe1", " ");
|
||||||
|
expect(res.found).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("流式翻页探查:命中目标单号并自动写入本地 SQLite 缓存,后续查询秒级命中缓存", async () => {
|
||||||
|
const mockJobsDetail: Record<string, any> = {
|
||||||
|
job_001: {
|
||||||
|
id: "job_001",
|
||||||
|
status: "COMPLETED",
|
||||||
|
inputs: {
|
||||||
|
code: "XZ2610474",
|
||||||
|
flowId: "flow_xz_01",
|
||||||
|
userInfo: { name: "欧阳亚玲" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
job_002: {
|
||||||
|
id: "job_002",
|
||||||
|
status: "RUNNING",
|
||||||
|
inputs: {
|
||||||
|
code: "OTHER_999",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
let logCalls = 0;
|
||||||
|
let jobCalls = 0;
|
||||||
|
|
||||||
|
const mockClient = {
|
||||||
|
get: async (path: string, options?: any) => {
|
||||||
|
if (path.includes("/log")) {
|
||||||
|
logCalls++;
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify({
|
||||||
|
code: 200,
|
||||||
|
data: {
|
||||||
|
totalCount: 2,
|
||||||
|
totalPages: 1,
|
||||||
|
jobList: [
|
||||||
|
{ jobId: "job_002", status: "RUNNING", executeTime: 1700000000000 },
|
||||||
|
{ jobId: "job_001", status: "COMPLETED", executeTime: 1700000050000 },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (path.includes("/jobs/")) {
|
||||||
|
jobCalls++;
|
||||||
|
const jobId = path.split("/jobs/")[1]?.split("?")[0];
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify({
|
||||||
|
code: 200,
|
||||||
|
data: mockJobsDetail[jobId] || { id: jobId },
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return new Response(JSON.stringify({ code: 404 }));
|
||||||
|
},
|
||||||
|
} as any;
|
||||||
|
|
||||||
|
// 第一次调用:缓存未命中,执行流式远端嗅探
|
||||||
|
const res1 = await searchWorkflowJobByFlowCode(
|
||||||
|
mockClient,
|
||||||
|
"corp_winner",
|
||||||
|
"pipe_win",
|
||||||
|
"XZ2610474",
|
||||||
|
{ maxScanPages: 5 }
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(res1.found).toBe(true);
|
||||||
|
expect(res1.source).toBe("scan");
|
||||||
|
expect(res1.jobId).toBe("job_001");
|
||||||
|
expect(res1.job?.id).toBe("job_001");
|
||||||
|
expect(logCalls).toBe(1);
|
||||||
|
expect(jobCalls).toBe(2);
|
||||||
|
|
||||||
|
// 第二次调用:应当直接命中本地 SQLite 缓存,不调 /log 接口
|
||||||
|
const prevLogCalls = logCalls;
|
||||||
|
const prevJobCalls = jobCalls;
|
||||||
|
|
||||||
|
const res2 = await searchWorkflowJobByFlowCode(
|
||||||
|
mockClient,
|
||||||
|
"corp_winner",
|
||||||
|
"pipe_win",
|
||||||
|
"xz2610474" // 测试大小写模糊命中
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(res2.found).toBe(true);
|
||||||
|
expect(res2.source).toBe("cache");
|
||||||
|
expect(res2.jobId).toBe("job_001");
|
||||||
|
// 不应再请求 /log
|
||||||
|
expect(logCalls).toBe(prevLogCalls);
|
||||||
|
// 仅通过 getJob 校验最新状态
|
||||||
|
expect(jobCalls).toBe(prevJobCalls + 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("扫描达最大页数仍未找到时安全熔断并返回未找到", async () => {
|
||||||
|
const mockClient = {
|
||||||
|
get: async (path: string) => {
|
||||||
|
if (path.includes("/log")) {
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify({
|
||||||
|
code: 200,
|
||||||
|
data: {
|
||||||
|
totalCount: 10,
|
||||||
|
totalPages: 10,
|
||||||
|
jobList: [
|
||||||
|
{ jobId: "job_x", status: "COMPLETED" },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (path.includes("/jobs/")) {
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify({
|
||||||
|
code: 200,
|
||||||
|
data: { id: "job_x", inputs: { code: "NO_MATCH" } },
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return new Response(JSON.stringify({ code: 404 }));
|
||||||
|
},
|
||||||
|
} as any;
|
||||||
|
|
||||||
|
const res = await searchWorkflowJobByFlowCode(
|
||||||
|
mockClient,
|
||||||
|
"corp1",
|
||||||
|
"pipe1",
|
||||||
|
"WANT_THIS",
|
||||||
|
{ maxScanPages: 2 }
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(res.found).toBe(false);
|
||||||
|
expect(res.scannedPages).toBe(2);
|
||||||
|
expect(res.totalScanned).toBe(2);
|
||||||
|
});
|
||||||
|
});
|
||||||
Loaded 100 of 111 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user