Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bd585db889 | ||
|
|
a0ec7f95a7 | ||
|
|
2ec08033e0 | ||
|
|
96c5a3f242 | ||
|
|
1d825269f4 | ||
|
|
3573ef71aa | ||
|
|
c18ff02386 | ||
|
|
64c0fafcf6 | ||
|
|
db2b256fcd | ||
|
|
aa5ec6b6ce | ||
|
|
8c444efc85 |
No files matched your search
@@ -113,7 +113,7 @@ jobs:
|
||||
local filename
|
||||
filename=$(basename "$file")
|
||||
echo " [start] Uploading ${filename} to Gitea..."
|
||||
RESP=$(curl -s -m 120 -w "\nHTTP_STATUS:%{http_code}" -X POST "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}/assets?name=${filename}" \
|
||||
RESP=$(curl -s -m 600 -w "\nHTTP_STATUS:%{http_code}" -X POST "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}/assets?name=${filename}" \
|
||||
-H "Authorization: token ${GITEA_TOKEN}" \
|
||||
-F "attachment=@${file}")
|
||||
STATUS=$(echo "$RESP" | tail -n 1)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.8.8",
|
||||
"version": "0.8.11",
|
||||
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
|
||||
"author": {
|
||||
"name": "yingqing"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# hose-use (v0.8.8)
|
||||
# hose-use (v0.8.11)
|
||||
|
||||
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
|
||||
|
||||
|
||||
Vendored
+653
-526
File diff suppressed because it is too large.
Load diff
Vendored
+1
-1
@@ -2,7 +2,7 @@
|
||||
"openapi": "3.1.0",
|
||||
"info": {
|
||||
"title": "hose-use API & MCP Tools Specification",
|
||||
"version": "0.8.8",
|
||||
"version": "0.8.11",
|
||||
"description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."
|
||||
},
|
||||
"servers": [
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
openapi: 3.1.0
|
||||
info:
|
||||
title: hose-use API & MCP Tools Specification
|
||||
version: 0.8.8
|
||||
version: 0.8.11
|
||||
description: >-
|
||||
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
|
||||
servers:
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.8.8",
|
||||
"version": "0.8.11",
|
||||
"module": "src/server.ts",
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
+63
-18
@@ -116,30 +116,67 @@ download_candidate() {
|
||||
echo "==> Target install location: ${TARGET_PATH}"
|
||||
TMP_FILE="$(mktemp)"
|
||||
DOWNLOAD_SUCCESS=false
|
||||
DOWNLOADED_FORMAT="archive"
|
||||
|
||||
# Candidate mirrors
|
||||
GITEA_URL="https://git.ying-qing.cn/gitea/hose-use/releases/download/latest/${ASSET_NAME}"
|
||||
GITHUB_URL="https://github.com/${REPO}/releases/latest/download/${ASSET_NAME}"
|
||||
GHPROXY_URL="https://ghfast.top/https://github.com/${REPO}/releases/latest/download/${ASSET_NAME}"
|
||||
# Resolve latest Gitea tag if available
|
||||
GITEA_API_URL="https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases/latest"
|
||||
LATEST_TAG=""
|
||||
if command -v curl >/dev/null 2>&1; then
|
||||
LATEST_TAG="$(curl -sL --connect-timeout 3 "$GITEA_API_URL" | sed -n 's/.*"tag_name":"\([^"]*\)".*/\1/p' || true)"
|
||||
fi
|
||||
[ -z "$LATEST_TAG" ] && LATEST_TAG="v0.8.9"
|
||||
|
||||
# 1. First priority: Compressed Archives (.tar.gz) - fast download & includes aliases
|
||||
GITEA_ARCHIVE_URL="https://git.ying-qing.cn/gitea/hose-use/releases/download/${LATEST_TAG}/${ASSET_NAME}.tar.gz"
|
||||
GITHUB_ARCHIVE_URL="https://github.com/${REPO}/releases/latest/download/${ASSET_NAME}.tar.gz"
|
||||
GHPROXY_ARCHIVE_URL="https://ghfast.top/https://github.com/${REPO}/releases/latest/download/${ASSET_NAME}.tar.gz"
|
||||
|
||||
# 1. Try Gitea mirror
|
||||
if [ "${HOSE_USE_MIRROR:-auto}" = "gitea" ] || [ "${HOSE_USE_MIRROR:-auto}" = "auto" ]; then
|
||||
if download_candidate "$GITEA_URL" "$TMP_FILE" "Gitea High-Speed Mirror"; then
|
||||
if download_candidate "$GITEA_ARCHIVE_URL" "$TMP_FILE" "Gitea High-Speed Mirror (Archive)"; then
|
||||
DOWNLOAD_SUCCESS=true
|
||||
DOWNLOADED_FORMAT="archive"
|
||||
fi
|
||||
fi
|
||||
|
||||
# 2. Try direct GitHub Releases
|
||||
if [ "$DOWNLOAD_SUCCESS" = "false" ]; then
|
||||
if download_candidate "$GITHUB_URL" "$TMP_FILE" "GitHub Releases (Direct)"; then
|
||||
if [ "$DOWNLOAD_SUCCESS" = "false" ] && [ "${HOSE_USE_MIRROR:-auto}" != "gitea" ]; then
|
||||
if download_candidate "$GITHUB_ARCHIVE_URL" "$TMP_FILE" "GitHub Releases (Archive Direct)"; then
|
||||
DOWNLOAD_SUCCESS=true
|
||||
DOWNLOADED_FORMAT="archive"
|
||||
fi
|
||||
fi
|
||||
|
||||
# 3. Try Fast CDN Proxy Fallback
|
||||
if [ "$DOWNLOAD_SUCCESS" = "false" ]; then
|
||||
if download_candidate "$GHPROXY_URL" "$TMP_FILE" "Fast CDN Mirror (Fallback)"; then
|
||||
if [ "$DOWNLOAD_SUCCESS" = "false" ] && [ "${HOSE_USE_MIRROR:-auto}" != "gitea" ]; then
|
||||
if download_candidate "$GHPROXY_ARCHIVE_URL" "$TMP_FILE" "Fast CDN Mirror (Archive Fallback)"; then
|
||||
DOWNLOAD_SUCCESS=true
|
||||
DOWNLOADED_FORMAT="archive"
|
||||
fi
|
||||
fi
|
||||
|
||||
# 2. Second priority: Raw Executable (Fallback)
|
||||
if [ "$DOWNLOAD_SUCCESS" = "false" ]; then
|
||||
GITEA_RAW_URL="https://git.ying-qing.cn/gitea/hose-use/releases/download/${LATEST_TAG}/${ASSET_NAME}"
|
||||
GITHUB_RAW_URL="https://github.com/${REPO}/releases/latest/download/${ASSET_NAME}"
|
||||
GHPROXY_RAW_URL="https://ghfast.top/https://github.com/${REPO}/releases/latest/download/${ASSET_NAME}"
|
||||
|
||||
if [ "${HOSE_USE_MIRROR:-auto}" = "gitea" ] || [ "${HOSE_USE_MIRROR:-auto}" = "auto" ]; then
|
||||
if download_candidate "$GITEA_RAW_URL" "$TMP_FILE" "Gitea High-Speed Mirror (Raw Binary)"; then
|
||||
DOWNLOAD_SUCCESS=true
|
||||
DOWNLOADED_FORMAT="raw"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$DOWNLOAD_SUCCESS" = "false" ] && [ "${HOSE_USE_MIRROR:-auto}" != "gitea" ]; then
|
||||
if download_candidate "$GITHUB_RAW_URL" "$TMP_FILE" "GitHub Releases (Raw Direct)"; then
|
||||
DOWNLOAD_SUCCESS=true
|
||||
DOWNLOADED_FORMAT="raw"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$DOWNLOAD_SUCCESS" = "false" ] && [ "${HOSE_USE_MIRROR:-auto}" != "gitea" ]; then
|
||||
if download_candidate "$GHPROXY_RAW_URL" "$TMP_FILE" "Fast CDN Mirror (Raw Fallback)"; then
|
||||
DOWNLOAD_SUCCESS=true
|
||||
DOWNLOADED_FORMAT="raw"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
@@ -149,18 +186,26 @@ if [ "$DOWNLOAD_SUCCESS" = "false" ]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
chmod +x "$TMP_FILE"
|
||||
mv "$TMP_FILE" "$TARGET_PATH"
|
||||
|
||||
# Create hose-aipro multicall alias pointing at the single binary.
|
||||
if [ -w "$TARGET_DIR" ]; then
|
||||
ln -sf "$TARGET_PATH" "${TARGET_DIR}/hose-aipro" 2>/dev/null || true
|
||||
if [ "$DOWNLOADED_FORMAT" = "archive" ]; then
|
||||
echo "==> Extracting archive to ${TARGET_DIR}..."
|
||||
tar -xzf "$TMP_FILE" -C "$TARGET_DIR"
|
||||
rm -f "$TMP_FILE"
|
||||
chmod +x "$TARGET_PATH"
|
||||
[ -f "${TARGET_DIR}/hose-aipro" ] && chmod +x "${TARGET_DIR}/hose-aipro"
|
||||
else
|
||||
chmod +x "$TMP_FILE"
|
||||
mv "$TMP_FILE" "$TARGET_PATH"
|
||||
# Create hose-aipro multicall alias pointing at the single binary.
|
||||
if [ -w "$TARGET_DIR" ]; then
|
||||
ln -sf "$TARGET_PATH" "${TARGET_DIR}/hose-aipro" 2>/dev/null || true
|
||||
fi
|
||||
fi
|
||||
|
||||
# Ad-hoc sign on macOS
|
||||
if [ "$PLATFORM" = "darwin" ] && command -v codesign >/dev/null 2>&1; then
|
||||
echo "==> Applying macOS code signature..."
|
||||
codesign --force --sign - "$TARGET_PATH" 2>/dev/null || true
|
||||
[ -f "${TARGET_DIR}/hose-aipro" ] && codesign --force --sign - "${TARGET_DIR}/hose-aipro" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
echo "==> Initializing agent skill to ~/.agents/skills/hose-use..."
|
||||
|
||||
+21
-13
@@ -2,11 +2,11 @@
|
||||
name: hose-use
|
||||
description: "合思/易快报(Ekuaibao)企业级 SaaS 一站式能力:hose-use CLI/SDK 多账号登录、租户切换、单据检索与审批动作、自建应用与工作流扫描、密钥与应用中心、常驻守护进程与 HTTP 文档/OpenAPI,以及工作流 MVEL 代码节点脚本生成调试、节点批量开通。用于一切合思/易快报相关请求。"
|
||||
metadata:
|
||||
version: 0.8.8
|
||||
version: 0.8.11
|
||||
short-description: 合思/易快报 企业级 CLI 与工作流 skill 套件(含 MVEL 代码节点)
|
||||
---
|
||||
|
||||
# hose-use (v0.8.8)
|
||||
# hose-use (v0.8.11)
|
||||
|
||||
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
|
||||
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
|
||||
@@ -65,7 +65,9 @@ metadata:
|
||||
| AI PRO 确定性审批仲裁全流程 (核验/仲裁) | `hose-aipro bind`, `hose-aipro review`, `hose-aipro decide` | [references/approval.md](references/approval.md) |
|
||||
| 本地 AI 审批规约与规则增删改查 | `hose-use rule scopes`, `hose-use rule add --dry-run/--yes`, `hose-use rule list` | [references/approval.md](references/approval.md) |
|
||||
| 首次登录 / 账密认证 / Token过期 / 多账号 | `hose-use auth login`, `hose-use auth status`, `hose-use auth refresh` | [references/auth.md](references/auth.md) |
|
||||
| 第三方免密/协助链接一键秒级导入 | `hose-use corps add-link <url>`, `hose-use auth add-link <url>` | [references/auth.md](references/auth.md) |
|
||||
| 生成企业合思 Web 免密登录直达链接 (`thirdparty.html`) | `hose-use corps link [企业ID|名称]`, `hose-use auth hose-link` | [references/auth.md](references/auth.md) |
|
||||
| 第三方免密/协助链接一键导入(自动提取持久化密钥) | `hose-use corps add-link <url> --yes`, `hose-use corps elevate [企业ID] --yes` | [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 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) |
|
||||
@@ -82,18 +84,18 @@ metadata:
|
||||
| 企业角色、角色组与角色成员 | `hose-use role list`, `hose-use role groups`, `hose-use role members <角色>` | [references/role.md](references/role.md) |
|
||||
| 角色权限只读快照 | `hose-use permission get` | [references/role.md](references/role.md) |
|
||||
| 单据 Web 详情直达链接生成 | `hose-use bill link <单号|ID>` | [references/bill.md](references/bill.md) |
|
||||
| 单据实体模型与字段元数据查询 | `hose-use bill schema` | [references/bill.md](references/bill.md) |
|
||||
| 单据实体模型与字段元数据查询 / 单据模板联动规格 | `hose-use bill schema`, `hose-use bill spec <specificationId>` | [references/bill.md](references/bill.md) |
|
||||
| 企业通讯录检索 / 员工档案 / 防爆保护 | `hose-use contact search`, `hose-use contact list`, `hose-use contact get` | [references/contact.md](references/contact.md) |
|
||||
| 待办中心 / 已审批 / 我发起的 / 审批记录 / 抄送 | `hose-use task todo`, `hose-use task submitted`, `hose-use task records`, `hose-use task cc` | [references/task.md](references/task.md) |
|
||||
| 应用管理 (桌面端工作台开通的用车/套件/制度/自建前台应用) | `hose-use app list [--keyword]`, `hose-use app get <应用>` | [references/workflow.md](references/workflow.md) |
|
||||
| 自建应用与数据模型 (开放平台业务对象/字段定义/底层记录) | `hose-use platform list`, `hose-use platform entities <应用>` | [references/workflow.md](references/workflow.md) |
|
||||
| 自建应用单条记录操作 (详情/停启用/字段编辑/台账重算) | `hose-use platform record <get|toggle|edit|recompute>` | [references/workflow.md](references/workflow.md) |
|
||||
| 自建应用与数据模型 (开放平台业务对象/字段定义/全量记录/健康度体检) | `hose-use platform list`, `hose-use platform entities <应用>`, `hose-use platform records <应用> <对象> --all`, `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 workflow list`, `hose-use workflow find --task=code-js2` | [references/workflow.md](references/workflow.md) |
|
||||
| 桌面端全站主导航与一级模块树 | `hose-use menu list`, `hose-use menu tree` | [references/workflow.md](references/workflow.md) |
|
||||
| 模糊搜索已保存的企业与员工信息 | `hose-use corps search <关键词>` | [references/auth.md](references/auth.md) |
|
||||
| 特定任务节点扫描 (如脚本/Webhook) | `hose-use workflow find --task=code-js2` | [references/workflow.md](references/workflow.md) |
|
||||
| 工作流详情、节点草稿修改、草稿保存、版本历史、运行日志、发布与开通切换 | `hose-use workflow get`, `hose-use workflow patch`, `hose-use workflow save`, `hose-use workflow publish`, `hose-use workflow history`, `hose-use workflow logs`, `hose-use workflow toggle` | [references/workflow.md](references/workflow.md) |
|
||||
| 工作流节点树、代码依赖与静态诊断 | `hose-use workflow analyze <pipelineId>` | [references/workflow.md](references/workflow.md) |
|
||||
| 工作流详情、节点草稿修改、草稿保存、版本历史、运行日志、单次运行排障、发布与开通切换 | `hose-use workflow 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) |
|
||||
| 工作流节点树、代码依赖与静态诊断(禁用/SKIP风险/联动覆盖) | `hose-use workflow analyze <pipelineId>` | [references/workflow.md](references/workflow.md) |
|
||||
| 工作流错误管道扫描与本地去重提醒 | `hose-use workflow check [--fail-on-alert]` | [references/workflow.md](references/workflow.md) |
|
||||
| 企业 OpenAPI 接入密钥(默认脱敏) | `hose-use keys [--json]`, `hose-use openapi keys`, `hose-use store keys` | [references/store.md](references/store.md) |
|
||||
| 企业已购应用 / 应用商店探查 | `hose-use store list / search / get` | [references/store.md](references/store.md) |
|
||||
@@ -163,6 +165,7 @@ hose-use role groups # 查看角色组及其
|
||||
hose-use role members 财务主管 # 查看指定角色成员
|
||||
hose-use permission get # 查看角色权限开关(只读)
|
||||
hose-use bill schema # 查询单据实体元数据字典
|
||||
hose-use bill spec ID01TxgE3fhD6n # 查看单据模板字段配置、赋值优先级与联动规则
|
||||
|
||||
# 4. 待办与消息
|
||||
hose-use task submitted # 查看我发起的单据
|
||||
@@ -176,20 +179,25 @@ hose-use app list # 查看应用管理列
|
||||
hose-use app get 用车补贴 # 查看指定应用管理的配置与 Web 路由
|
||||
hose-use platform list # 列出企业可见的自建应用平台
|
||||
hose-use platform entities 新转转集团 # 查看自建应用下的业务对象与字段
|
||||
hose-use platform records 新转转集团 合同 # 查看业务对象的底层数据记录
|
||||
hose-use platform record get 新转转集团 合同 <记录ID> # 获取单条记录完整字段与属性详情
|
||||
hose-use platform records 新转转集团 合同 --all -o /tmp/records.json # 自动翻页导出全量业务对象记录
|
||||
hose-use platform audit 新转转集团 合同 --check-fields="我方签约主体" # 一键巡检必填缺失、停用引用与跨表同步差异
|
||||
hose-use platform record get <记录ID> # 免传应用/对象,直接按记录 ID 获取完整详情
|
||||
hose-use platform record toggle 新转转集团 合同 <记录ID> --dry-run # 预览状态切换
|
||||
hose-use platform record edit 新转转集团 合同 <记录ID> --data='{"name":"新名称"}' --yes # 编辑记录字段
|
||||
hose-use platform record edit 新转转集团 合同 <记录ID> --data='{"我方签约主体":"ID01..."}' --dry-run # Read-Modify-Write 安全合并预览
|
||||
hose-use platform record batch-edit 新转转集团 合同 --ids=id1,id2 --data='{"字段":"值"}' --dry-run # 批量安全更新预览
|
||||
hose-use platform record recompute 新转转集团 合同 <记录ID> --yes # 重新计算记录关联的全部台账
|
||||
hose-use menu list # 查看桌面端主框架一级导航树
|
||||
hose-use workflow list # 聚合扫描全部自建应用下的工作流
|
||||
hose-use workflow find --task=code-js2 # 查找部署了代码节点的工作流
|
||||
hose-use workflow get wf_01k83y... # 查看指定工作流节点拓扑
|
||||
hose-use workflow analyze wf_01k83y... --json # 输出节点树、引用依赖与静态诊断
|
||||
hose-use workflow analyze wf_01k83y... --json # 输出节点树、引用依赖与静态诊断(含联动覆盖/SKIP守卫检查)
|
||||
hose-use workflow logs wf_01k83y... --has-error # 筛选包含报错节点(含被 SKIP 吞掉错误)的运行历史
|
||||
hose-use workflow job 892809886382563347 --failed # 一键定位单次运行失败节点、入参出参与错误原因
|
||||
hose-use workflow job 892809886382563347 --parent=<executionId> # 下钻查看循环/分支容器内子节点执行明细
|
||||
hose-use workflow job 892809886382563347 --logs=<executionId> # 查看指定节点(如 MVEL 脚本)底层执行日志
|
||||
hose-use workflow save wf_01k83y... --file=workflow.json --yes # 按完整快照保存草稿并做版本保护
|
||||
hose-use workflow patch wf_01k83y... --file=workflow.json --path=tasks.0.code --value='return 2;' --output=patched.json --yes
|
||||
hose-use workflow history wf_01k83y... --json # 查看服务端版本快照历史
|
||||
hose-use workflow logs wf_01k83y... --state=FAILED # 查看运行错误日志
|
||||
hose-use workflow check --json --fail-on-alert # 扫描错误管道并只提醒新增错误计数
|
||||
hose-use workflow publish wf_01k83y... --yes # 将保存后的工作流发布/启用
|
||||
|
||||
|
||||
@@ -42,24 +42,47 @@ hose-use auth refresh
|
||||
```
|
||||
- 主动调用主站会话刷新接口,续期当前企业凭据的 AccessToken。
|
||||
|
||||
### 第三方免密/协助链接一键导入 (`corps add-link` / `auth add-link`)
|
||||
### 第三方免密/协助链接一键导入与自动提权持久化 (`corps add-link` / `auth add-link`)
|
||||
```bash
|
||||
# 直接粘贴企业微信免密、合思代客或协助 thirdparty.html 链接
|
||||
hose-use corps add-link "https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=...&ekbCorpId=..."
|
||||
# 直接粘贴企业微信免密、合思代客或协助 thirdparty.html 链接(默认自动探测并持久化保存 OpenAPI appKey + appSecurity)
|
||||
hose-use corps add-link "https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=...&ekbCorpId=..." --yes
|
||||
|
||||
# 可选附加别名与覆盖参数
|
||||
hose-use corps add-link "<url>" --name="客户企业别名" --overwrite
|
||||
# 显式强制要求提取 OpenAPI 持久化密钥(多套密钥时可附加 --app-key 或 --force)
|
||||
hose-use corps add-link "<url>" --elevate --force --overwrite --yes
|
||||
|
||||
# 未提供服务端 expTime 时,可显式指定本地有效期
|
||||
hose-use corps add-link "<url>" --ttl 3d
|
||||
hose-use corps add-link "<url>" --expires 3 # 等价于 3 天;--days 3 也可以
|
||||
hose-use corps add-link "<url>" --ttl 3d --yes
|
||||
```
|
||||
- **全自动识别与身份探测**:
|
||||
- **全自动识别与双通道持久化**:
|
||||
- 自动从 URL 提取服务节点 `baseUrl`、集群环境 `cluster`(如 `wx2`、`app`)、`accessToken` 与 `corpId`;
|
||||
- 自动向 `$UNITY` JWT 与主站 Session 反查员工工号 (`staffId`)、员工姓名、绑定手机、企业全称与是否企业管理员,无需手动寻找工号;
|
||||
- 动态自适应多集群环境换票,确保主站单据审批与 EASO 低代码工作流平台权限全绿连通。
|
||||
- 非账号来源(link/browser/assist/curl/manual)不会触发账号换票;Token 失效时提示重新导入链接。
|
||||
- 服务端返回的 expTime 优先;未返回时不再强制套用 2 小时,可使用 `--ttl` / `--expires` 指定有效期。
|
||||
- 自动向 `$UNITY` JWT 与主站 Session 反查员工工号 (`staffId`)、员工姓名、绑定手机、企业全称与是否企业管理员;
|
||||
- **自动提取 OpenAPI 持久化密钥**:导入链接或账密登录时,自动尝试调用 `/api/innerapi/v1/key` 提取企业启用状态的 `appKey + appSecurity` 并写入 `enterprises/<corpId>.json`;
|
||||
- **双通道无感自动续期**:当会话 `accessToken` 过期时,客户端优先尝试用户级主账号 (`cloudAuthToken`) 换票,或自动通过企业级 OpenAPI 持久化密钥调用 `/api/openapi/v1/auth/getAccessToken` + `/api/openapi/v1.1/provisional/getProvisionalAuth` 签发全新会话令牌并落盘,彻底告别临时链接过期失效。
|
||||
|
||||
### 生成企业合思 Web 免密登录直达链接 (`corps link` / `auth hose-link`)
|
||||
```bash
|
||||
# 为已配置企业生成 2 小时有效期的 Web 免密直达链接 (thirdparty.html)
|
||||
hose-use corps link 新转转集团
|
||||
hose-use corps link ID01PH4Q5CJboX --json
|
||||
hose-use auth hose-link --corp=ID01PH4Q5CJboX
|
||||
```
|
||||
- 若企业已配置 OpenAPI `appKey + appSecurity`,直接调用 `getProvisionalAuth` 动态签发全新的 `thirdparty.html` 免密登录链接;
|
||||
- 若企业尚未持久化密钥,会先尝试利用当前有效会话自动提权提取 `appKey + appSecurity`,再签发直达链接。
|
||||
|
||||
### OpenAPI 持久化密钥直接接入与存量提权 (`add-persistent` / `extract-keys` / `elevate`)
|
||||
```bash
|
||||
# 1. 直接使用 appKey + appSecurity 持久化接入企业(自动探测 6 大合思域名与主管理员)
|
||||
hose-use corps add-persistent --app-key=<key> --app-security=<secret> --force --yes
|
||||
|
||||
# 2. 从协助链接中提取查看 OpenAPI 密钥(附加 --save --yes 可直接持久化落盘)
|
||||
hose-use corps extract-keys "<url>"
|
||||
hose-use corps extract-keys "<url>" --save --yes
|
||||
|
||||
# 3. 为本地已配置企业(或 --all 全部企业)提取并持久化保存 OpenAPI 密钥
|
||||
hose-use corps elevate ID01PH4Q5CJboX --yes
|
||||
hose-use corps elevate --all --yes
|
||||
hose-use keys --corp=ID01PH4Q5CJboX --save --yes
|
||||
```
|
||||
|
||||
### 代客协助凭证导入
|
||||
```bash
|
||||
@@ -67,7 +90,8 @@ hose-use auth import \
|
||||
--name="CSM代客" \
|
||||
--corp-id="Cxa3oOtQi2eS$g" \
|
||||
--staff-id="Cxa3oOtQi2eS$g:2HQbkGx2DgnM00" \
|
||||
--token="1361c470-3d7c-4a3a-a1fb-e946aee5723b"
|
||||
--token="1361c470-3d7c-4a3a-a1fb-e946aee5723b" \
|
||||
--yes
|
||||
```
|
||||
- **智能探测机制**:若 `corp-id` 包含 `$UNITY` 或特殊字符,系统会自动探测代客服务会话接口,解析 13 位过期毫秒时间戳并正确建立凭证映射。也可直接传入抓包 cURL 或包含 URL 的文本。
|
||||
|
||||
|
||||
@@ -154,7 +154,7 @@ hose-use bill download S26000001 --output-dir ./downloads
|
||||
hose-use bill download S26000001 --file-id ID01THIU98FNyT --output-dir ./downloads --json
|
||||
```
|
||||
|
||||
## 5. 单据实体元数据字典 (`bill schema`)
|
||||
## 5. 单据实体元数据字典 (`bill schema`) 与单据模板规格诊断 (`bill spec`)
|
||||
|
||||
用于探查当前企业所有单据实体、字段类型与扩展属性定义:
|
||||
|
||||
@@ -163,6 +163,15 @@ hose-use bill schema
|
||||
hose-use bill schema --json
|
||||
```
|
||||
|
||||
当需要查看某个具体单据/申请模板(如工作流 `flow-create-task` 节点绑定的 `specificationId`)的完整字段列表、必填属性、赋值优先级(`priorityList`)以及字段联动覆盖规则(`assignmentRule` / `isLinkageAssignment`)时,使用 `bill spec`(同义别名:`feetype spec`):
|
||||
|
||||
```bash
|
||||
hose-use bill spec ID01TxgE3fhD6n
|
||||
hose-use bill spec ID01TxgE3fhD6n --json
|
||||
```
|
||||
|
||||
该命令会自动标记所有配置了 `LINKAGE_ASSIGNMENT > MANUALLY_FILL_IN`(自动联动高于手动填写/工作流传入)的业务对象字段,帮助快速排查“工作流传入字段被单据模板联动静默清空或覆盖”的隐蔽问题。
|
||||
|
||||
---
|
||||
|
||||
## 6. 上下文防爆保护与安全转储
|
||||
|
||||
@@ -42,46 +42,65 @@ hose-use platform entities 新转转集团
|
||||
hose-use platform schema 新转转集团 合同
|
||||
hose-use platform schema 新转转集团 合同 --keyword="金额"
|
||||
|
||||
# 检索业务对象的底层真实数据记录
|
||||
# 检索业务对象的底层真实数据记录(支持 --all 自动翻页拉取全量记录)
|
||||
hose-use platform records 新转转集团 合同 --limit=5
|
||||
hose-use platform records 新转转集团 合同 --keyword="技术服务" --fields "合同编号,金额,经办人" --json
|
||||
hose-use platform records 新转转集团 支付计划表 --all --json -o /tmp/payment_plans.json
|
||||
```
|
||||
|
||||
### 2.1 业务对象记录操作 (`platform record`)
|
||||
### 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` 权限,并支持字段中英文短名自动解析。
|
||||
|
||||
```bash
|
||||
# 1. 查看单条记录详情 (包含基本信息、实体字段、关联台账与可见范围)
|
||||
hose-use platform record get 新转转集团 合同 ID01TqE4yUG6hF
|
||||
# 1. 查看单条记录详情 (支持直接传 recordId 免传应用与业务对象)
|
||||
hose-use platform record get ID01TqE4yUG6hF
|
||||
hose-use platform record get 新转转集团 合同 ID01TqE4yUG6hF --json
|
||||
|
||||
# 2. 切换记录停用/启用状态 (默认自动翻转,支持 --state 显式指定)
|
||||
hose-use platform record toggle 新转转集团 合同 ID01TqE4yUG6hF
|
||||
hose-use platform record toggle 新转转集团 合同 ID01TqE4yUG6hF --state=false # 停用
|
||||
hose-use platform record toggle 新转转集团 合同 ID01TqE4yUG6hF --state=true # 启用
|
||||
hose-use platform record toggle 新转转集团 合同 ID01TqE4yUG6hF --dry-run
|
||||
hose-use platform record toggle 新转转集团 合同 ID01TqE4yUG6hF --state=false --yes # 停用
|
||||
hose-use platform record toggle 新转转集团 合同 ID01TqE4yUG6hF --state=true --yes # 启用
|
||||
|
||||
# 3. 编辑更新记录字段 (传入 JSON 字典或 --data)
|
||||
hose-use platform record edit 新转转集团 合同 ID01TqE4yUG6hF --data='{"name":"新名称","项目内容":"技术支持"}'
|
||||
hose-use platform record edit 新转转集团 合同 ID01TqE4yUG6hF '{"name":"新名称"}'
|
||||
# 3. 安全编辑单条记录字段 (默认 Read-Modify-Write 安全合并,支持字段短名/中文标签)
|
||||
hose-use platform record edit 新转转集团 合同 ID01TqE4yUG6hF --data='{"我方签约主体":"ID01RnG3b79daL"}' --dry-run
|
||||
hose-use platform record edit 新转转集团 合同 ID01TqE4yUG6hF --data='{"我方签约主体":"ID01RnG3b79daL"}' --yes
|
||||
|
||||
# 4. 重新计算记录关联的全部台账
|
||||
hose-use platform record recompute 新转转集团 合同 ID01TqE4yUG6hF
|
||||
# 4. 批量安全编辑多条记录 (支持 --ids / --filter / --file,内置并发控制与逐条 diff 预览)
|
||||
hose-use platform record batch-edit 新转转集团 支付计划表 \
|
||||
--ids=ID01A,ID01B \
|
||||
--data='{"我方签约主体":"ID01RnG3b79daL"}' \
|
||||
--dry-run
|
||||
hose-use platform record batch-edit 新转转集团 支付计划表 --file=./patches.json --yes
|
||||
|
||||
# 5. 重新计算记录关联的全部台账
|
||||
hose-use platform record recompute 新转转集团 合同 ID01TqE4yUG6hF --yes
|
||||
```
|
||||
|
||||
### 2.2 业务对象健康度巡检 (`platform audit`)
|
||||
|
||||
一键扫描指定业务对象全量记录的三大高频隐患,并自动生成可直接用于修复的 `suggestedPatches`:
|
||||
1. **必填/关键字段缺失 (`MISSING_FIELD`)**:检测 Schema 必填字段或 `--check-fields` 指定字段为空的记录;
|
||||
2. **引用已停用档案 (`DISABLED_REFERENCE`)**:检测引用字段指向 `active: false` 档案的记录;
|
||||
3. **跨台账冗余字段失步 (`CROSS_LEDGER_MISSING_SYNC` / `CROSS_LEDGER_MISMATCH`)**:当子台账(如《支付计划表》)关联父台账(如《合同流程》)且存在同名冗余字段(如 `我方签约主体`)时,自动比对子表与父表值是否一致,若父表有值而子表缺失则自动生成修复补丁。
|
||||
|
||||
```bash
|
||||
hose-use platform audit 新转转集团 支付计划表 --check-fields="我方签约主体"
|
||||
hose-use platform audit 新转转集团 支付计划表 --check-fields="我方签约主体" --active-only --json
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. 跨应用工作流聚合检索 (`workflow list`)
|
||||
|
||||
合思官方后台一次只能查看单个自建应用的工作流。`hose-use` 实现了跨应用并发聚合扫描:
|
||||
合思官方后台一次只能查看单个自建应用的工作流。`hose-use` 实现了跨应用并发聚合扫描(同时支持 `--platform-id` 与 `--app-id`):
|
||||
|
||||
```bash
|
||||
# 查看所有自建应用下的全部工作流汇总
|
||||
hose-use workflow list
|
||||
|
||||
# 查看指定自建应用下的工作流
|
||||
hose-use workflow list --app-id=app_01j72x...
|
||||
hose-use workflow list --app-id=ID01RKbEvQsWbd
|
||||
```
|
||||
|
||||
---
|
||||
@@ -126,13 +145,34 @@ hose-use workflow toggle wf_01k83y... --disable
|
||||
|
||||
## 7. 工作流静态分析 (`workflow analyze`)
|
||||
|
||||
从应用中心的具体自建应用进入工作流详情后,CLI 可以读取同一份详情并生成递归节点树、代码表达式引用依赖和明显配置诊断;该命令只读,不执行工作流:
|
||||
读取工作流详情并生成递归节点树、代码表达式引用依赖和静态风险诊断(只读,不执行工作流)。内置以下核心风险检测:
|
||||
- `WORKFLOW_DISABLED`:工作流处于停用状态(`state === 0`);
|
||||
- `UNSAFE_SKIP_WITHOUT_STATUS_GUARD`:循环容器(`every`)内的创单节点(`flow-create-task`)配置了 `onError.defaultAction === "SKIP"`,且后续台账更新节点(`ekuaibao-datalink-edit`)未守卫创单节点的 `$status`,会导致创单失败时仍将台账状态改成“创建成功”;
|
||||
- `LINKAGE_PRIORITY_OVERRIDE`:创单节点绑定了 `dataLink` 台账字段,同时目标单据模板对应字段开启了自动联动赋值且优先级 `LINKAGE_ASSIGNMENT > MANUALLY_FILL_IN`,导致单据模板联动静默覆盖工作流显式传入的值。
|
||||
|
||||
```bash
|
||||
hose-use workflow analyze wf_01k83y... --json
|
||||
hose-use workflow analyze 886351399301758976 --json
|
||||
```
|
||||
|
||||
## 8. 工作流草稿保存 (`workflow save`)
|
||||
## 8. 工作流单次运行实例排障 (`workflow job`)
|
||||
|
||||
当工作流执行报错、或因为子节点配置了 `SKIP` 导致外层状态显示为 `COMPLETED` 但内部实际创单失败时,使用 `workflow job` 下钻单次运行实例:
|
||||
|
||||
```bash
|
||||
# 1. 查看 Job 概览与顶层节点执行树
|
||||
hose-use workflow job 892809886382563347
|
||||
|
||||
# 2. 直接列出该次运行中所有报错节点、错误原因(outputs.error)及入参快照(含关联业务对象 ID)
|
||||
hose-use workflow job 892809886382563347 --failed --json
|
||||
|
||||
# 3. 展开循环(every)或分支(switch)容器内的子节点迭代明细
|
||||
hose-use workflow job 892809886382563347 --parent=892809893789696012
|
||||
|
||||
# 4. 查看指定节点(如 MVEL 代码节点)的底层控制台输出与异常堆栈
|
||||
hose-use workflow job 892809886382563347 --logs=892809893789696012
|
||||
```
|
||||
|
||||
## 9. 工作流草稿保存 (`workflow save`)
|
||||
|
||||
Web 端“保存更新”是对完整 pipeline 的 PUT,而不是单节点 PATCH。推荐先导出详情,再修改 JSON,最后按版本保护保存:
|
||||
|
||||
@@ -144,21 +184,21 @@ hose-use workflow save <pipelineId> --file=workflow.json
|
||||
|
||||
命令会先重新读取远端版本;若 `version` 或 `tasksVersion` 已变化会拒绝覆盖。确认需要强制覆盖时显式使用 `--force-write`。
|
||||
|
||||
## 9. 本地节点草稿修改 (`workflow patch`)
|
||||
## 10. 本地节点草稿修改 (`workflow patch`)
|
||||
|
||||
网页编辑器最终提交的是完整 pipeline,因此节点修改先在完整 JSON 草稿上完成,再交给 `workflow save` 做版本保护和服务端持久化:
|
||||
|
||||
```bash
|
||||
hose-use workflow patch <pipelineId> \\
|
||||
--file=workflow.json \\
|
||||
--path=tasks.1.form.title \\
|
||||
--value="新的标题" \\
|
||||
hose-use workflow patch <pipelineId> \
|
||||
--file=workflow.json \
|
||||
--path=tasks.1.form.title \
|
||||
--value="新的标题" \
|
||||
--output=workflow.patched.json
|
||||
```
|
||||
|
||||
数组也可以使用 `tasks[1].form.title`。需要写入数字、布尔值或对象时加 `--value-json`;使用 `--in-place` 才会覆盖输入文件。该命令只修改本地草稿,不直接触发远端写入。
|
||||
|
||||
## 10. 工作流版本历史 (`workflow history`)
|
||||
## 11. 工作流版本历史 (`workflow history`)
|
||||
|
||||
服务端每次完整保存都会生成一个版本快照,可用以下命令读取审计历史:
|
||||
|
||||
@@ -166,11 +206,12 @@ hose-use workflow patch <pipelineId> \\
|
||||
hose-use workflow history <pipelineId> --json
|
||||
```
|
||||
|
||||
## 11. 运行日志与错误管道提醒
|
||||
## 12. 运行日志与错误管道提醒 (`workflow logs` / `workflow check`)
|
||||
|
||||
查询单个工作流的运行日志:
|
||||
查询单个工作流的运行日志(表格默认展示 `successTaskCount`、`errorTaskCount`、`hasError`;即使工作流整体状态因 `SKIP` 显示为 `COMPLETED`,也可通过 `--has-error` 精准揪出内部含报错节点的运行记录):
|
||||
|
||||
```bash
|
||||
hose-use workflow logs <pipelineId> --has-error
|
||||
hose-use workflow logs <pipelineId> --state=FAILED --json
|
||||
```
|
||||
|
||||
@@ -181,9 +222,7 @@ hose-use workflow check --json
|
||||
hose-use workflow check --json --fail-on-alert
|
||||
```
|
||||
|
||||
默认状态文件为 `~/.config/hose-use/workflow-alerts-<corp>.json`,可用 `--state-file` 指定。`--fail-on-alert` 适合被常驻服务或外部调度器检测;它只改变退出码,不自动向外部人员发送消息。
|
||||
|
||||
## 12. 发布工作流 (`workflow publish`)
|
||||
## 13. 发布工作流 (`workflow publish`)
|
||||
|
||||
网页端发布动作对应 Piper 的状态接口:`PUT /api/easo/pipelines/state/{pipelineId}?state=1`。CLI 提供同等入口:
|
||||
|
||||
@@ -192,3 +231,23 @@ hose-use workflow publish <pipelineId>
|
||||
```
|
||||
|
||||
建议先执行 `workflow save`,确认保存成功后再执行 `workflow publish`;发布只切换启用状态,不替代完整配置保存。
|
||||
|
||||
---
|
||||
|
||||
## 14. 工作流排障与创单排错三大黄金法则(必读)
|
||||
|
||||
在排查“工作流明明运行了但没生成单据”、“工作流显示 COMPLETED 但单据缺失”或“生成单据报错必填项未填”时,必须严格遵循以下三大黄金法则:
|
||||
|
||||
### 法则一:先跑 `workflow analyze <pipelineId>` 排除停用与静默吞错
|
||||
- 检查是否命中 `WORKFLOW_DISABLED`(许多名为“【生产】xxx”的工作流实际处于 `state: 0` 停用状态,切勿被名称误导);
|
||||
- 检查是否命中 `UNSAFE_SKIP_WITHOUT_STATUS_GUARD`(`every` 循环中 `flow-create-task` 配置了失败跳过 `SKIP`,导致外层 Job 状态变为 `COMPLETED`,且后续 `ekuaibao-datalink-edit` 无视创单失败直接把台账改成“已发起”)。
|
||||
|
||||
### 法则二:用 `workflow logs --has-error` 与 `workflow job <jobId> --failed` 直击真实报错与源记录 ID
|
||||
- 不要只看 `--state=FAILED`!只要节点配置了 `SKIP`,Job 顶层 `state` 就会是 `COMPLETED`,必须用 `hose-use workflow logs <pipelineId> --has-error` 找出 `errorTaskCount > 0` 的 `jobId`;
|
||||
- 拿到 `jobId` 后,立即执行 `hose-use workflow job <jobId> --failed --json`,从 `outputs.error` 读取精确报错(例如 `我方签约主体未填写`),并从 `inputs.form` 中提取触发本次创单的源业务对象记录 ID。
|
||||
|
||||
### 法则三:遇到“工作流明明传了字段但创单仍报未填”,立即用 `bill spec <specificationId>` 检查联动覆盖优先级
|
||||
- 当工作流 `flow-create-task` 已经给某字段(如 `u_我方签约主体`)传了值,但仍报该字段未填写时,根因往往在**单据模板字段的赋值优先级 (`priorityList`) 与联动规则 (`assignmentRule`)**:
|
||||
- 执行 `hose-use bill spec <specificationId>`(或直接看 `workflow analyze` 的 `LINKAGE_PRIORITY_OVERRIDE` 告警);
|
||||
- 若单据模板中某业务对象字段(如 `u_关联合同流程`)开启了联动赋值,且目标字段的优先级为 `LINKAGE_ASSIGNMENT (自动联动) > MANUALLY_FILL_IN (手动填写/工作流传入)`,则单据保存时会用被关联主表(如《合同流程》)上的字段值强行覆盖工作流传入的值;若主表对应字段为空,工作流传入的值就会被清空!
|
||||
- 定位到缺失字段的台账记录后,使用 `hose-use platform audit <应用> <对象> --check-fields="..."` 巡检全量存量数据,并用 `hose-use platform record edit` / `batch-edit`(先 `--dry-run` 再 `--yes`)安全修复。
|
||||
@@ -64,4 +64,20 @@ describe("cli/commands/auth > aliases and subcommands", () => {
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("当前登录与企业状态");
|
||||
});
|
||||
|
||||
it("supports auth sync-seal --dry-run", async () => {
|
||||
const res = await handleAuthCommand(
|
||||
{
|
||||
area: "auth",
|
||||
action: "sync-seal",
|
||||
args: [],
|
||||
options: { "dry-run": true },
|
||||
raw: ["auth", "sync-seal", "--dry-run"],
|
||||
},
|
||||
dummyRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("从 seal-use 同步企业 OpenAPI 持久化密钥");
|
||||
});
|
||||
});
|
||||
+119
-6
@@ -1,13 +1,16 @@
|
||||
import {
|
||||
canRefreshCorpAccessToken,
|
||||
fullPasswordLogin,
|
||||
fullSmsLogin,
|
||||
fullBrowserSyncLogin,
|
||||
hasOpenApiPersistentCredentials,
|
||||
sendSmsVerificationCode,
|
||||
importCredentials,
|
||||
importF12Credentials,
|
||||
importFromLink,
|
||||
parseHeadersOrCurl,
|
||||
refreshAccountCorporations,
|
||||
refreshSingleCorpAccessToken,
|
||||
} from "../../core/auth/login.js";
|
||||
import {
|
||||
listAccounts,
|
||||
@@ -19,8 +22,20 @@ import { stringOption, booleanOption } from "../parser.js";
|
||||
import { printJson, printKeyValue, printTable, formatSourceLabel, formatExpiresAt } from "../printer.js";
|
||||
import { prompt } from "../helpers.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
|
||||
import {
|
||||
handleAddPersistent,
|
||||
handleElevateCorp,
|
||||
handleExtractKeys,
|
||||
handleGenerateCorpLink,
|
||||
handleSyncFromSeal,
|
||||
resolveTargetCorpByArgOrContext,
|
||||
} from "./corps.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
|
||||
function isHttpUrl(val?: string): boolean {
|
||||
return Boolean(val && /^https?:\/\//i.test(val.trim()));
|
||||
}
|
||||
|
||||
export async function handleAuthCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
@@ -41,9 +56,36 @@ export async function handleAuthCommand(
|
||||
case "add":
|
||||
return handleImport(parsed, runtime);
|
||||
case "add-link":
|
||||
case "link":
|
||||
case "import-link":
|
||||
return handleAddLink(parsed, runtime);
|
||||
case "link": {
|
||||
const maybeUrl = parsed.args[0] || stringOption(parsed.options, ["url", "link"]);
|
||||
if (isHttpUrl(maybeUrl)) {
|
||||
return handleAddLink(parsed, runtime);
|
||||
}
|
||||
return handleGenerateCorpLink(parsed, runtime);
|
||||
}
|
||||
case "hose-link":
|
||||
case "auth-link":
|
||||
case "login-link":
|
||||
return handleGenerateCorpLink(parsed, runtime);
|
||||
case "add-persistent":
|
||||
case "add-hose-persistent":
|
||||
case "add-openapi":
|
||||
case "add-hose":
|
||||
return handleAddPersistent(parsed, runtime);
|
||||
case "extract-keys":
|
||||
case "extract-key":
|
||||
case "hose-extract-keys":
|
||||
case "extract-hose-keys":
|
||||
return handleExtractKeys(parsed, runtime);
|
||||
case "elevate":
|
||||
case "elevate-hose":
|
||||
return handleElevateCorp(parsed, runtime);
|
||||
case "sync-seal":
|
||||
case "sync-from-seal":
|
||||
case "import-seal":
|
||||
return handleSyncFromSeal(parsed, runtime);
|
||||
case "accounts":
|
||||
case "list":
|
||||
case "account":
|
||||
@@ -56,7 +98,7 @@ export async function handleAuthCommand(
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 auth 子命令: ${action}。支持: login, status, refresh, import, add-link, accounts, switch-account\n`,
|
||||
stderr: `未知 auth 子命令: ${action}。支持: login, status, refresh, import, link, add-link, add-persistent, extract-keys, elevate, sync-seal, accounts, switch-account\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
@@ -175,6 +217,9 @@ async function handleStatus(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
}
|
||||
}
|
||||
|
||||
const hasOpenApi = hasOpenApiPersistentCredentials(currentCorp);
|
||||
const isPersistent = canRefreshCorpAccessToken(currentCorp);
|
||||
|
||||
const statusObj = {
|
||||
activeAccount: activeAccount?.accountId || null,
|
||||
currentCorp: currentCorp
|
||||
@@ -184,6 +229,8 @@ async function handleStatus(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
staffId: currentCorp.credentials.staffId,
|
||||
source: currentCorp.source,
|
||||
accountId: currentCorp.accountId,
|
||||
persistent: isPersistent,
|
||||
hasOpenApiKey: hasOpenApi,
|
||||
tokenValid: sessionValid,
|
||||
}
|
||||
: null,
|
||||
@@ -199,9 +246,14 @@ async function handleStatus(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
"当前激活企业": currentCorp ? `${currentCorp.name} (${currentCorp.id})` : "未配置",
|
||||
"当前员工工号": currentCorp?.credentials.staffId || "-",
|
||||
"员工真实姓名": currentCorp?.staffName || currentCorp?.session?.staffName || "-",
|
||||
"凭证来源类型": formatSourceLabel(currentCorp?.source),
|
||||
"凭证来源类型": formatSourceLabel(currentCorp?.source, hasOpenApi),
|
||||
"持久化状态": isPersistent
|
||||
? hasOpenApi
|
||||
? `✅ OpenAPI 持久化密钥 (${currentCorp?.credentials.appKey})`
|
||||
: "✅ 统一认证主账号自动换票"
|
||||
: "⚪ 短期会话",
|
||||
"Token 有效性": sessionValid ? "✅ 有效 (已通过 Session 验证)" : "❌ 无效或未连接",
|
||||
"Token 过期时间": formatExpiresAt(currentCorp?.auth?.expiresAt || currentCorp?.session?.expTime),
|
||||
"Token 过期时间": formatExpiresAt(currentCorp?.auth?.expiresAt || currentCorp?.session?.expTime, isPersistent),
|
||||
};
|
||||
|
||||
if (currentCorp?.session) {
|
||||
@@ -239,6 +291,53 @@ async function handleStatus(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
|
||||
async function handleRefresh(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const accountId = stringOption(parsed.options, ["account", "a"]);
|
||||
const explicitCorp = parsed.args[0] || stringOption(parsed.options, ["corp"]);
|
||||
const targetCorp = explicitCorp
|
||||
? resolveTargetCorpByArgOrContext(explicitCorp, runtime)
|
||||
: !accountId && !getActiveAccount() && runtime.selectedCorp && canRefreshCorpAccessToken(runtime.selectedCorp)
|
||||
? runtime.selectedCorp
|
||||
: null;
|
||||
|
||||
if (targetCorp && !accountId) {
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "刷新单企业凭证", `${targetCorp.name} (${targetCorp.id})`, {
|
||||
corpId: targetCorp.id,
|
||||
hasOpenApiKey: hasOpenApiPersistentCredentials(targetCorp),
|
||||
});
|
||||
}
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"刷新单企业凭证",
|
||||
`hose-use auth refresh ${targetCorp.id} --yes`
|
||||
);
|
||||
const newToken = await refreshSingleCorpAccessToken(targetCorp);
|
||||
if (!newToken) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `刷新企业 [${targetCorp.name} (${targetCorp.id})] AccessToken 失败:缺少可用的账号凭证或 OpenAPI 持久化密钥\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({
|
||||
corpId: targetCorp.id,
|
||||
corpName: targetCorp.name,
|
||||
refreshed: true,
|
||||
expiresAt: targetCorp.auth?.expiresAt,
|
||||
}),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: `[SUCCESS] 成功刷新企业 [${targetCorp.name} (${targetCorp.id})] 的 AccessToken!\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "刷新账号下企业凭证", accountId || "当前账号", { saveAll: true });
|
||||
}
|
||||
@@ -265,10 +364,16 @@ async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
const overwrite = booleanOption(parsed.options, ["overwrite", "force", "f"], false);
|
||||
const ttl = stringOption(parsed.options, ["ttl"]);
|
||||
const expires = stringOption(parsed.options, ["expires", "days"]);
|
||||
const elevate = booleanOption(parsed.options, ["elevate", "elevate-hose", "as-hose"], false);
|
||||
const noElevate = booleanOption(parsed.options, ["no-elevate"], false);
|
||||
const appKey = stringOption(parsed.options, ["app-key", "appKey"]);
|
||||
const keyId = stringOption(parsed.options, ["key-id", "keyId"]);
|
||||
const force = booleanOption(parsed.options, ["force", "f"], false);
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "导入并保存企业凭证", corpId || "待解析企业", {
|
||||
source: raw ? "captured-input" : "manual-input",
|
||||
elevate: elevate ? "required" : noElevate ? "disabled" : "auto-best-effort",
|
||||
overwrite,
|
||||
ttl: ttl || null,
|
||||
expires: expires || null,
|
||||
@@ -307,6 +412,11 @@ async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
overwrite,
|
||||
ttl,
|
||||
expires,
|
||||
appKey,
|
||||
keyId,
|
||||
elevate: elevate ? true : noElevate ? false : undefined,
|
||||
autoElevate: !noElevate,
|
||||
force,
|
||||
source: raw && (raw.startsWith("http://") || raw.startsWith("https://")) ? "link" : undefined,
|
||||
});
|
||||
|
||||
@@ -314,6 +424,8 @@ async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
return { stdout: printJson(imported, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const hasOpenApi = hasOpenApiPersistentCredentials(imported);
|
||||
|
||||
const summaryPairs: Record<string, unknown> = {
|
||||
"企业名称": imported.name,
|
||||
"企业 ID": imported.id,
|
||||
@@ -322,9 +434,10 @@ async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
"员工姓名": imported.staffName || imported.session?.staffName || "-",
|
||||
"手机号码": imported.session?.cellphone || "-",
|
||||
"是否管理": imported.session?.isAdmin ? "是" : "否",
|
||||
"凭证来源": formatSourceLabel(imported.source),
|
||||
"凭证来源": formatSourceLabel(imported.source, hasOpenApi),
|
||||
"持久化密钥": hasOpenApi ? `✅ 已自动提权持久化 (appKey: ${imported.credentials.appKey})` : "⚪ 未提取到 OpenAPI 密钥 (短期会话)",
|
||||
"服务节点": imported.baseUrl,
|
||||
"过期时间": formatExpiresAt(imported.auth?.expiresAt || imported.session?.expTime),
|
||||
"过期时间": formatExpiresAt(imported.auth?.expiresAt || imported.session?.expTime, hasOpenApi),
|
||||
"保存路径": `enterprises/${imported.id}.json`,
|
||||
};
|
||||
|
||||
|
||||
@@ -19,6 +19,9 @@ import {
|
||||
addNodeBill,
|
||||
commentBill,
|
||||
resolveBillStaffIds,
|
||||
inspectFormSpecification,
|
||||
formatFormPriorityList,
|
||||
hasLinkageOverridePriority,
|
||||
} from "../../domains/bill/tools.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
|
||||
|
||||
@@ -655,7 +658,95 @@ export async function handleBillCommand(
|
||||
};
|
||||
}
|
||||
|
||||
case "spec":
|
||||
case "specification": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["id", "spec", "specification", "specification-id", "specificationId"]);
|
||||
if (!target) {
|
||||
throw new Error("请提供单据模板 ID (specificationId): hose-use bill spec <specificationId>");
|
||||
}
|
||||
|
||||
const inspection = await inspectFormSpecification(await getClient(), corpId, target);
|
||||
if (!inspection) {
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ found: false, specificationId: target }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[NOT FOUND] 未找到单据模板定义: ${target}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const { specification: spec, warnings } = inspection;
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
...spec,
|
||||
warnings,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = spec.components.map((comp, idx) => {
|
||||
const priorityStr = formatFormPriorityList(comp.priorityList);
|
||||
const overrideRisk = hasLinkageOverridePriority(comp.priorityList) ? "⚠️ 联动覆盖手动" : "-";
|
||||
return [
|
||||
idx + 1,
|
||||
comp.name,
|
||||
comp.label || "-",
|
||||
comp.type,
|
||||
comp.optional === false ? "🔴 必填" : "⚪ 选填",
|
||||
comp.isLinkageAssignment ? "🟢 开启(true)" : "⚪ 关闭(false)",
|
||||
comp.assignmentRule || "-",
|
||||
priorityStr,
|
||||
overrideRisk,
|
||||
];
|
||||
});
|
||||
|
||||
const outLines = [
|
||||
`====== 单据模板定义 (${spec.name || spec.id}) ======`,
|
||||
` 模板 ID : ${spec.id}`,
|
||||
` 模板名称 : ${spec.name || "-"}`,
|
||||
` 单据类型 : ${spec.type || "-"}`,
|
||||
` 状态 : ${spec.active ? "🟢 启用" : "🔴 停用"}`,
|
||||
` 字段总数 : ${spec.components.length} 个`,
|
||||
"",
|
||||
rows.length
|
||||
? printTable(
|
||||
["#", "字段标识 (name)", "显示名称 (label)", "类型 (type)", "必填", "联动赋值 (isLinkageAssignment)", "联动规则 (assignmentRule)", "赋值优先级 (priorityList)", "覆盖风险"],
|
||||
rows
|
||||
)
|
||||
: "暂无表单组件定义",
|
||||
];
|
||||
|
||||
if (warnings.length > 0) {
|
||||
outLines.push("");
|
||||
outLines.push("── ⚠️ 联动赋值与优先级诊断 ──");
|
||||
for (const w of warnings) {
|
||||
outLines.push(` • ${w}`);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `${outLines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
default:
|
||||
throw new Error(`未知 bill 子命令: ${action}。支持: list, get <单号> [--risk], refs <单号>, relations <单号>, attachments <单号>, download <单号>, flow <单号>, risk <单号>, budget <单号>, schema, link <单号>`);
|
||||
throw new Error(`未知 bill 子命令: ${action}。支持: list, get <单号> [--risk], spec <specificationId>, refs <单号>, relations <单号>, attachments <单号>, download <单号>, flow <单号>, risk <单号>, budget <单号>, schema, link <单号>`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { getActiveAccount } from "../../core/auth/account-store.js";
|
||||
import { canRefreshCorpAccessToken, hasOpenApiPersistentCredentials } from "../../core/auth/login.js";
|
||||
import {
|
||||
resolveGlobalConfigFile,
|
||||
resolvePrimaryEnterprisesDir,
|
||||
@@ -47,8 +48,9 @@ export async function handleContextCommand(
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const validCorps = allCorps.filter((c) => !c.expiresAt || c.expiresAt > now);
|
||||
const expiredCorps = allCorps.filter((c) => 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 currentPersistent = currentCorp ? canRefreshCorpAccessToken(currentCorp) : false;
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
@@ -76,11 +78,13 @@ export async function handleContextCommand(
|
||||
staffId: currentCorp.credentials?.staffId || currentCorp.staffId,
|
||||
userName: currentCorp.staffName || currentCorp.session?.staffName || null,
|
||||
source: currentCorp.source,
|
||||
persistent: currentPersistent,
|
||||
expiresAt: currentCorp.auth?.expiresAt || currentCorp.session?.expTime,
|
||||
expired:
|
||||
(currentCorp.auth?.expiresAt || currentCorp.session?.expTime)
|
||||
? (currentCorp.auth?.expiresAt || currentCorp.session?.expTime)! <= now
|
||||
: false,
|
||||
expired: currentPersistent
|
||||
? false
|
||||
: (currentCorp.auth?.expiresAt || currentCorp.session?.expTime)
|
||||
? (currentCorp.auth?.expiresAt || currentCorp.session?.expTime)! <= now
|
||||
: false,
|
||||
baseUrl: currentCorp.baseUrl,
|
||||
accountId: currentCorp.accountId || null,
|
||||
}
|
||||
@@ -130,8 +134,8 @@ export async function handleContextCommand(
|
||||
` 当前激活企业 : ${currentCorp ? `${currentCorp.name} (${currentCorp.id})` : "⚠️ 未激活任何企业"}`,
|
||||
` 当前操作员工 : ${corpStaffId}`,
|
||||
` 员工真实姓名 : ${corpStaffName}`,
|
||||
` 凭证来源类型 : ${currentCorp ? formatSourceLabel(currentCorp.source) : "-"}`,
|
||||
` 凭证有效状态 : ${currentCorp ? formatExpiresAt(corpExpiresAt) : "-"}`,
|
||||
` 凭证来源类型 : ${currentCorp ? formatSourceLabel(currentCorp.source, hasOpenApiPersistentCredentials(currentCorp)) : "-"}`,
|
||||
` 凭证有效状态 : ${currentCorp ? formatExpiresAt(corpExpiresAt, currentPersistent) : "-"}`,
|
||||
` 主站 BaseURL : ${currentCorp?.baseUrl || "-"}`,
|
||||
` 已配置企业总数: ${allCorps.length} 家 (有效: ${validCorps.length} 家, 已过期: ${expiredCorps.length} 家)`,
|
||||
` AI PRO 规约库 : ${scopesStr}`,
|
||||
|
||||
@@ -315,4 +315,52 @@ describe("cli/commands/corps > handleCorpsCommand search & aliases", () => {
|
||||
expect(res.stdout).toContain("search <关键词>");
|
||||
expect(res.stdout).toContain("find");
|
||||
});
|
||||
|
||||
it("generates login link via corps link [corp] with preserveSensitiveStdout=true", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
globalThis.fetch = (async () =>
|
||||
new Response(JSON.stringify({ items: [] }), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
})) as unknown as typeof fetch;
|
||||
|
||||
try {
|
||||
const res = await handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
action: "link",
|
||||
args: ["corpAlpha"],
|
||||
options: {},
|
||||
raw: ["corps", "link", "corpAlpha"],
|
||||
},
|
||||
searchRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.preserveSensitiveStdout).toBe(true);
|
||||
expect(res.stdout).toContain("thirdparty.html?accessToken=token-alpha&ekbCorpId=alphaPhysicalId");
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
it("supports corps add-persistent --dry-run", async () => {
|
||||
const res = await handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
action: "add-persistent",
|
||||
args: [],
|
||||
options: {
|
||||
"app-key": "key-1",
|
||||
"app-security": "sec-1",
|
||||
"dry-run": true,
|
||||
},
|
||||
raw: ["corps", "add-persistent", "--app-key=key-1", "--app-security=sec-1", "--dry-run"],
|
||||
},
|
||||
searchRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("通过 OpenAPI 持久化密钥接入企业");
|
||||
});
|
||||
});
|
||||
+627
-13
@@ -1,8 +1,22 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { importFromLink } from "../../core/auth/login.js";
|
||||
import {
|
||||
canRefreshCorpAccessToken,
|
||||
elevateCorpWithOpenApiKey,
|
||||
extractOpenApiKeysFromLink,
|
||||
fetchHoseRoleDefGroups,
|
||||
getCorpProvisionalAuthLink,
|
||||
hasOpenApiPersistentCredentials,
|
||||
importFromLink,
|
||||
listHoseStaffsByOpenApi,
|
||||
maskOpenApiSecurity,
|
||||
onboardHosePersistent,
|
||||
probeHoseDomain,
|
||||
syncOpenApiFromSealUse,
|
||||
} from "../../core/auth/login.js";
|
||||
import { resolveWritableEnterprisesDir } from "../../core/config/loader.js";
|
||||
import { stringOption, booleanOption } from "../parser.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import { stringOption, booleanOption, numberOption } from "../parser.js";
|
||||
import { prompt } from "../helpers.js";
|
||||
import { printJson, printKeyValue, printTable, formatSourceLabel, formatExpiresAt } from "../printer.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
|
||||
@@ -17,6 +31,34 @@ const FIELD_LABEL_MAP: Record<string, string> = {
|
||||
accountId: "所属账号",
|
||||
};
|
||||
|
||||
function isHttpUrl(val?: string): boolean {
|
||||
return Boolean(val && /^https?:\/\//i.test(val.trim()));
|
||||
}
|
||||
|
||||
export function resolveTargetCorpByArgOrContext(
|
||||
targetArg: string | undefined,
|
||||
runtime: CliRuntime
|
||||
): CorpConfig | null {
|
||||
if (targetArg && !isHttpUrl(targetArg)) {
|
||||
try {
|
||||
return runtime.corpContext.resolve(targetArg);
|
||||
} catch {
|
||||
const allCorps = typeof runtime.corpContext.getAllCorps === "function"
|
||||
? runtime.corpContext.getAllCorps()
|
||||
: [];
|
||||
const kw = targetArg.trim().toLowerCase();
|
||||
const matched = allCorps.find(
|
||||
(c) =>
|
||||
c.id.toLowerCase() === kw ||
|
||||
(c.corpId && c.corpId.toLowerCase() === kw) ||
|
||||
c.name.toLowerCase().includes(kw)
|
||||
);
|
||||
if (matched) return matched;
|
||||
}
|
||||
}
|
||||
return runtime.selectedCorp;
|
||||
}
|
||||
|
||||
export async function handleCorpsCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
@@ -41,15 +83,46 @@ export async function handleCorpsCommand(
|
||||
case "active":
|
||||
return handleCurrent(parsed, runtime);
|
||||
case "add-link":
|
||||
case "link":
|
||||
case "import-link":
|
||||
return handleAddLink(parsed, runtime);
|
||||
case "link": {
|
||||
const maybeUrl = parsed.args[0] || stringOption(parsed.options, ["url", "link"]);
|
||||
if (isHttpUrl(maybeUrl)) {
|
||||
return handleAddLink(parsed, runtime);
|
||||
}
|
||||
return handleGenerateCorpLink(parsed, runtime);
|
||||
}
|
||||
case "hose-link":
|
||||
case "auth-link":
|
||||
case "login-link":
|
||||
return handleGenerateCorpLink(parsed, runtime);
|
||||
case "add-persistent":
|
||||
case "add-hose-persistent":
|
||||
case "add-openapi":
|
||||
case "add-hose":
|
||||
return handleAddPersistent(parsed, runtime);
|
||||
case "extract-keys":
|
||||
case "extract-key":
|
||||
case "hose-extract-keys":
|
||||
case "extract-hose-keys":
|
||||
return handleExtractKeys(parsed, runtime);
|
||||
case "elevate":
|
||||
case "elevate-hose":
|
||||
return handleElevateCorp(parsed, runtime);
|
||||
case "sync-seal":
|
||||
case "sync-from-seal":
|
||||
case "import-seal":
|
||||
return handleSyncFromSeal(parsed, runtime);
|
||||
case "probe-hose":
|
||||
return handleProbeHose(parsed, runtime);
|
||||
case "hose-staffs":
|
||||
return handleHoseStaffs(parsed, runtime);
|
||||
case "help":
|
||||
return handleCorpsHelp();
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 corps 子命令: ${action}。支持: list, search, switch, current, add-link\n`,
|
||||
stderr: `未知 corps 子命令: ${action}。支持: list, search, switch, current, link, add-link, add-persistent, extract-keys, elevate, sync-seal\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
@@ -65,7 +138,12 @@ export function printCorpsHelp(): string {
|
||||
search <关键词> 根据关键词模糊搜索企业(支持 id, name, corpId, staffId, staffName, accountId,别名: find)
|
||||
switch <企业ID> 切换当前激活的工作企业 (别名: use)
|
||||
current 查看当前激活的企业配置与凭证详情
|
||||
add-link <URL> 从第三方协助/免密链接导入企业凭证
|
||||
link [企业ID|名称] 生成企业合思 Web 免密登录直达链接 (别名: hose-link)
|
||||
add-link <URL> 从第三方协助/免密链接导入企业凭证(默认自动探测并持久化 OpenAPI 密钥)
|
||||
add-persistent 通过 OpenAPI 密钥 (appKey + appSecurity) 持久化接入企业 (别名: add-hose-persistent)
|
||||
extract-keys <URL> 从协助链接提取企业 OpenAPI 密钥(附加 --save 可直接持久化保存)
|
||||
elevate [企业ID] 为已登录/已导入的企业提取并持久化保存 OpenAPI 密钥
|
||||
sync-seal [关键词] 从本机 seal-use 配置目录同步企业级 OpenAPI 持久化密钥
|
||||
|
||||
选项:
|
||||
--json, -j 以 JSON 格式输出
|
||||
@@ -76,6 +154,9 @@ export function printCorpsHelp(): string {
|
||||
hose-use corps search 某企业
|
||||
hose-use corps search 17718556446
|
||||
hose-use corps switch ID01MCcOgJl1td
|
||||
hose-use corps link 新转转集团
|
||||
hose-use corps add-link "<url>" --elevate --yes
|
||||
hose-use corps add-persistent --app-key=... --app-security=... --yes
|
||||
`.trim();
|
||||
}
|
||||
|
||||
@@ -116,6 +197,7 @@ async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
baseUrl: c.baseUrl,
|
||||
current: c.id === runtime.selectedCorp?.id,
|
||||
expiresAt: c.auth?.expiresAt || (c.session?.expTime ?? undefined),
|
||||
persistent: canRefreshCorpAccessToken(c),
|
||||
}))
|
||||
: runtime.corpContext.listCorps().map((c) => ({
|
||||
id: c.id,
|
||||
@@ -128,6 +210,7 @@ async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
baseUrl: c.baseUrl,
|
||||
current: c.current || c.id === runtime.selectedCorp?.id,
|
||||
expiresAt: c.expiresAt,
|
||||
persistent: c.persistent,
|
||||
}));
|
||||
|
||||
const matches: Array<typeof normalizedCorps[number] & { matchedFields: string[] }> = [];
|
||||
@@ -177,6 +260,7 @@ async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
baseUrl: m.baseUrl,
|
||||
current: m.current,
|
||||
expiresAt: m.expiresAt,
|
||||
persistent: m.persistent,
|
||||
matchedFields: m.matchedFields,
|
||||
})),
|
||||
},
|
||||
@@ -206,7 +290,7 @@ async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
m.staffName ? (m.matchedFields.includes("staffName") ? `[${m.staffName}]` : m.staffName) : "-",
|
||||
m.accountId ? (m.matchedFields.includes("accountId") ? `[${m.accountId}]` : m.accountId) : "-",
|
||||
matchLabels.map((l) => `命中${l}`).join(", "),
|
||||
formatExpiresAt(m.expiresAt),
|
||||
formatExpiresAt(m.expiresAt, m.persistent),
|
||||
];
|
||||
});
|
||||
|
||||
@@ -249,7 +333,7 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
|
||||
c.name,
|
||||
c.staffId,
|
||||
c.source || "manual",
|
||||
formatExpiresAt(c.expiresAt),
|
||||
formatExpiresAt(c.expiresAt, c.persistent),
|
||||
c.accountId || "-",
|
||||
]);
|
||||
|
||||
@@ -307,13 +391,17 @@ async function handleCurrent(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
||||
return { stdout: printJson(current, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const hasOpenApi = hasOpenApiPersistentCredentials(current);
|
||||
const isPersistent = canRefreshCorpAccessToken(current);
|
||||
|
||||
const pairs: Record<string, unknown> = {
|
||||
"企业 ID": current.id,
|
||||
"企业名称": current.name,
|
||||
"员工工号": current.credentials.staffId,
|
||||
"员工姓名": current.staffName || current.session?.staffName || "-",
|
||||
"凭证来源": formatSourceLabel(current.source),
|
||||
"Token 过期时间": formatExpiresAt(current.auth?.expiresAt || current.session?.expTime),
|
||||
"凭证来源": formatSourceLabel(current.source, hasOpenApi),
|
||||
"持久化状态": isPersistent ? (hasOpenApi ? `✅ 已配置 OpenAPI 持久化密钥 (${current.credentials.appKey})` : "✅ 已绑定统一认证主账号") : "⚪ 短期临时会话",
|
||||
"Token 过期时间": formatExpiresAt(current.auth?.expiresAt || current.session?.expTime, isPersistent),
|
||||
"所属账号": current.accountId || "-",
|
||||
"主站地址": current.baseUrl || "https://app.ekuaibao.com",
|
||||
"适用上下文": "同时作为 hose-use 与 hose-aipro 的统一执行环境",
|
||||
@@ -352,12 +440,85 @@ async function handleCurrent(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleGenerateCorpLink(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const targetArg = parsed.args[0];
|
||||
const targetCorp = resolveTargetCorpByArgOrContext(targetArg, runtime);
|
||||
if (!targetCorp) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未找到目标企业${targetArg ? ` [${targetArg}]` : ""}。请通过 --corp=<id> 或参数指定已配置的企业。\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const expiresIn =
|
||||
stringOption(parsed.options, ["expires-in", "expiresIn", "expire", "expires", "ttl"]) || 7200;
|
||||
const pageType = stringOption(parsed.options, ["page-type", "pageType"]) || "home";
|
||||
const force = booleanOption(parsed.options, ["force", "refresh", "f"]);
|
||||
|
||||
const linkRes = await getCorpProvisionalAuthLink(targetCorp, {
|
||||
expiresIn,
|
||||
pageType,
|
||||
force,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId: linkRes.corpId,
|
||||
corpName: linkRes.corpName,
|
||||
staffId: linkRes.staffId,
|
||||
...(linkRes.staffName ? { staffName: linkRes.staffName } : {}),
|
||||
link: linkRes.url,
|
||||
expiresAt: linkRes.expiresAt,
|
||||
expiresIn: linkRes.expiresIn,
|
||||
token: linkRes.token,
|
||||
persistent: linkRes.persistent,
|
||||
method: linkRes.method,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
preserveSensitiveStdout: true,
|
||||
};
|
||||
}
|
||||
|
||||
const lines = [
|
||||
`====== 合思企业 Web 免密登录直达链接 ======`,
|
||||
` 企业名称 : ${linkRes.corpName} (${linkRes.corpId})`,
|
||||
` 操作人身份: ${linkRes.staffName ? `${linkRes.staffName} (${linkRes.staffId})` : linkRes.staffId}`,
|
||||
` 签发通道 : ${linkRes.method === "provisional-openapi" ? "OpenAPI 持久化密钥动态签发 (getProvisionalAuth)" : "当前有效会话令牌拼装 (session-token)"}`,
|
||||
` 过期时间 : ${linkRes.expiresAt}`,
|
||||
` 直达链接 :`,
|
||||
` ${linkRes.url}`,
|
||||
``,
|
||||
`Markdown 链接: [打开 ${linkRes.corpName} 合思后台](${linkRes.url})`,
|
||||
];
|
||||
|
||||
return {
|
||||
stdout: `${lines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
preserveSensitiveStdout: true,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
let linkUrl = parsed.args[0] || stringOption(parsed.options, ["url", "link"]);
|
||||
const name = stringOption(parsed.options, ["name"]);
|
||||
const overwrite = booleanOption(parsed.options, ["overwrite", "force", "f"], false);
|
||||
const ttl = stringOption(parsed.options, ["ttl"]);
|
||||
const expires = stringOption(parsed.options, ["expires", "days"]);
|
||||
const elevate = booleanOption(parsed.options, ["elevate", "elevate-hose", "as-hose"], false);
|
||||
const noElevate = booleanOption(parsed.options, ["no-elevate"], false);
|
||||
const appKey = stringOption(parsed.options, ["app-key", "appKey"]);
|
||||
const keyId = stringOption(parsed.options, ["key-id", "keyId"]);
|
||||
const force = booleanOption(parsed.options, ["force", "f"], false);
|
||||
|
||||
if (!linkUrl && process.stdin.isTTY && !process.env.CI && process.env.NODE_ENV !== "test") {
|
||||
linkUrl = await prompt("请输入第三方协助/免密登录链接 URL: ");
|
||||
@@ -366,7 +527,7 @@ async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
||||
if (!linkUrl) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "错误:必须提供协助/免密链接 URL!用法: hose-use corps add-link <url> [--name <企业别名>] [--ttl 3d|--expires 3] [--overwrite]\n",
|
||||
stderr: "错误:必须提供协助/免密链接 URL!用法: hose-use corps add-link <url> [--name <企业别名>] [--elevate] [--ttl 3d|--expires 3] [--overwrite]\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
@@ -388,6 +549,7 @@ async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
||||
name || (targetCorpId ? `企业 [${targetCorpId}]` : "待解析企业"),
|
||||
{
|
||||
source: "assistance-link",
|
||||
elevate: elevate ? "required" : noElevate ? "disabled" : "auto-best-effort",
|
||||
overwrite,
|
||||
alreadyExists: existsAlready,
|
||||
ttl: ttl || null,
|
||||
@@ -413,14 +575,19 @@ async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
||||
overwrite,
|
||||
ttl,
|
||||
expires,
|
||||
appKey,
|
||||
keyId,
|
||||
elevate: elevate ? true : noElevate ? false : undefined,
|
||||
autoElevate: !noElevate,
|
||||
force,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(corp, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const targetDir = resolveWritableEnterprisesDir();
|
||||
const savedPath = join(targetDir, `${corp.id}.json`);
|
||||
const hasOpenApi = hasOpenApiPersistentCredentials(corp);
|
||||
|
||||
const summaryPairs: Record<string, unknown> = {
|
||||
"企业名称": corp.name,
|
||||
@@ -430,9 +597,10 @@ async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
||||
"员工姓名": corp.staffName || corp.session?.staffName || "-",
|
||||
"手机号码": corp.session?.cellphone || "-",
|
||||
"是否管理": corp.session?.isAdmin ? "是" : "否",
|
||||
"凭证来源": formatSourceLabel(corp.source),
|
||||
"凭证来源": formatSourceLabel(corp.source, hasOpenApi),
|
||||
"持久化密钥": hasOpenApi ? `✅ 已自动提权持久化 (appKey: ${corp.credentials.appKey})` : "⚪ 未提取到 OpenAPI 密钥 (短期会话)",
|
||||
"服务节点": corp.baseUrl,
|
||||
"过期时间": formatExpiresAt(corp.auth?.expiresAt || corp.session?.expTime),
|
||||
"过期时间": formatExpiresAt(corp.auth?.expiresAt || corp.session?.expTime, hasOpenApi),
|
||||
"保存路径": savedPath,
|
||||
};
|
||||
|
||||
@@ -461,3 +629,449 @@ async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export async function handleAddPersistent(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
let jsonPayload: Record<string, unknown> = {};
|
||||
const rawJsonArg = stringOption(parsed.options, ["data"]) || (parsed.args[0]?.trim().startsWith("{") ? parsed.args[0] : undefined);
|
||||
if (rawJsonArg) {
|
||||
try {
|
||||
jsonPayload = JSON.parse(rawJsonArg);
|
||||
} catch {
|
||||
return { stdout: "", stderr: "错误:提供的 JSON 参数无法解析\n", exitCode: 1 };
|
||||
}
|
||||
}
|
||||
|
||||
const appKey =
|
||||
stringOption(parsed.options, ["app-key", "appKey", "key"]) ||
|
||||
(typeof jsonPayload.appKey === "string" ? jsonPayload.appKey : undefined);
|
||||
const appSecurity =
|
||||
stringOption(parsed.options, ["app-security", "appSecurity", "secret", "password"]) ||
|
||||
(typeof jsonPayload.appSecurity === "string" ? jsonPayload.appSecurity : undefined);
|
||||
const domain =
|
||||
stringOption(parsed.options, ["domain", "base-url", "baseUrl"]) ||
|
||||
(typeof jsonPayload.domain === "string" ? jsonPayload.domain : undefined);
|
||||
const corpId =
|
||||
stringOption(parsed.options, ["corp-id", "corpId", "corp"]) ||
|
||||
(typeof jsonPayload.corpId === "string" ? jsonPayload.corpId : undefined);
|
||||
const staffId =
|
||||
stringOption(parsed.options, ["staff-id", "staffId", "proxyStaffBizId"]) ||
|
||||
(typeof jsonPayload.staffId === "string" ? jsonPayload.staffId : undefined);
|
||||
const staffName =
|
||||
stringOption(parsed.options, ["staff-name", "staffName"]) ||
|
||||
(typeof jsonPayload.staffName === "string" ? jsonPayload.staffName : undefined);
|
||||
const staffPhone =
|
||||
stringOption(parsed.options, ["staff-phone", "staffPhone"]) ||
|
||||
(typeof jsonPayload.staffPhone === "string" ? jsonPayload.staffPhone : undefined);
|
||||
const role =
|
||||
stringOption(parsed.options, ["role"]) ||
|
||||
(typeof jsonPayload.role === "string" ? jsonPayload.role : undefined);
|
||||
const name =
|
||||
stringOption(parsed.options, ["name"]) ||
|
||||
(typeof jsonPayload.name === "string" ? jsonPayload.name : undefined);
|
||||
const overwrite = booleanOption(parsed.options, ["overwrite"], Boolean(jsonPayload.overwrite));
|
||||
const force = booleanOption(parsed.options, ["force", "f"], Boolean(jsonPayload.force));
|
||||
|
||||
if (!appKey || !appSecurity) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "错误:必须提供 appKey 与 appSecurity!用法: hose-use corps add-persistent --app-key=<key> --app-security=<secret> [--staff-id=<id>] [--force] [--overwrite] --yes\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "通过 OpenAPI 持久化密钥接入企业", name || corpId || appKey, {
|
||||
source: "openapi",
|
||||
appKey,
|
||||
domain: domain || "auto-probe",
|
||||
staffId: staffId || "auto-discover",
|
||||
overwrite,
|
||||
});
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"通过 OpenAPI 持久化密钥接入企业",
|
||||
`hose-use corps add-persistent --app-key=${appKey} --app-security=<redacted> --yes`
|
||||
);
|
||||
|
||||
const saved = await onboardHosePersistent({
|
||||
name,
|
||||
appKey,
|
||||
appSecurity,
|
||||
domain,
|
||||
corpId,
|
||||
staffId,
|
||||
staffName,
|
||||
staffPhone,
|
||||
role,
|
||||
force,
|
||||
overwrite,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(saved, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const targetDir = resolveWritableEnterprisesDir();
|
||||
const savedPath = join(targetDir, `${saved.id}.json`);
|
||||
const summaryText = printKeyValue({
|
||||
"企业名称": saved.name,
|
||||
"企业 ID": saved.id,
|
||||
"服务节点": saved.baseUrl,
|
||||
"员工工号": saved.credentials.staffId,
|
||||
"员工姓名": saved.staffName || saved.session?.staffName || "-",
|
||||
"接入账号 (appKey)": saved.credentials.appKey,
|
||||
"凭证来源": formatSourceLabel(saved.source, true),
|
||||
"保存路径": savedPath,
|
||||
});
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] 成功接入并持久化企业 OpenAPI 凭证!\n${summaryText}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleExtractKeys(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const linkUrl = parsed.args[0] || stringOption(parsed.options, ["url", "link"]);
|
||||
if (!linkUrl) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use corps extract-keys <https://.../web/thirdparty.html?...> [--reveal] [--save] [--app-key <key>] [--key-id <id>] [--overwrite]\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const reveal = booleanOption(parsed.options, ["reveal", "r", "plain"], false);
|
||||
const save = booleanOption(parsed.options, ["save", "add", "persist"], false);
|
||||
const name = stringOption(parsed.options, ["name"]);
|
||||
const overwrite = booleanOption(parsed.options, ["overwrite"], true);
|
||||
const force = booleanOption(parsed.options, ["force", "f"], false);
|
||||
const appKey = stringOption(parsed.options, ["app-key", "appKey"]);
|
||||
const keyId = stringOption(parsed.options, ["key-id", "keyId"]);
|
||||
|
||||
if (save) {
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "从协助链接提取并持久化 OpenAPI 密钥", name || "待解析企业", {
|
||||
save: true,
|
||||
overwrite,
|
||||
appKey: appKey || "auto-select",
|
||||
});
|
||||
}
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"从协助链接提取并持久化 OpenAPI 密钥",
|
||||
`hose-use corps extract-keys "<url>" --save --yes`
|
||||
);
|
||||
}
|
||||
|
||||
const extracted = await extractOpenApiKeysFromLink(linkUrl, {
|
||||
save,
|
||||
name,
|
||||
overwrite,
|
||||
force,
|
||||
appKey,
|
||||
keyId,
|
||||
});
|
||||
|
||||
const formattedKeys = extracted.keys.map((k) => ({
|
||||
id: k.id,
|
||||
name: k.name || "-",
|
||||
appKey: k.appKey,
|
||||
appSecurity: reveal ? k.appSecurity : maskOpenApiSecurity(k.appSecurity),
|
||||
active: k.active,
|
||||
createTime: k.createTime,
|
||||
updateTime: k.updateTime,
|
||||
}));
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId: extracted.corpId,
|
||||
corpName: extracted.corpName || extracted.corpId,
|
||||
baseUrl: extracted.baseUrl,
|
||||
staffId: extracted.staffId,
|
||||
keyCount: formattedKeys.length,
|
||||
keys: formattedKeys,
|
||||
...(extracted.savedCorp ? { saved: true, savedCorpId: extracted.savedCorp.id } : {}),
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
preserveSensitiveStdout: reveal,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = formattedKeys.map((k, i) => [
|
||||
i + 1,
|
||||
k.name,
|
||||
k.appKey,
|
||||
k.appSecurity,
|
||||
k.active ? "🟢 启用" : "⚪ 停用",
|
||||
]);
|
||||
const table = printTable(["#", "应用名称", "appKey", "appSecurity", "状态"], rows);
|
||||
const savedNotice = extracted.savedCorp
|
||||
? `\n[SUCCESS] 已将密钥 (${extracted.selectedKey?.appKey}) 持久化保存至企业 [${extracted.savedCorp.name} (${extracted.savedCorp.id})]`
|
||||
: "";
|
||||
|
||||
return {
|
||||
stdout: `====== 协助链接 OpenAPI 密钥提取结果 (${extracted.corpName || extracted.corpId}) ======\n${table}${savedNotice}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
preserveSensitiveStdout: reveal,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleElevateCorp(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const elevateAll = booleanOption(parsed.options, ["all", "a"], false);
|
||||
const appKey = stringOption(parsed.options, ["app-key", "appKey"]);
|
||||
const keyId = stringOption(parsed.options, ["key-id", "keyId"]);
|
||||
const force = booleanOption(parsed.options, ["force", "f"], true);
|
||||
|
||||
if (elevateAll) {
|
||||
const allCorps = typeof runtime.corpContext.getAllCorps === "function"
|
||||
? runtime.corpContext.getAllCorps()
|
||||
: [];
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "批量提取并持久化全部企业 OpenAPI 密钥", `共 ${allCorps.length} 家企业`, {
|
||||
count: allCorps.length,
|
||||
});
|
||||
}
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"批量提取并持久化全部企业 OpenAPI 密钥",
|
||||
`hose-use corps elevate --all --yes`
|
||||
);
|
||||
|
||||
const results: Array<{ corpId: string; name: string; appKey?: string; status: string }> = [];
|
||||
for (const corp of allCorps) {
|
||||
if (hasOpenApiPersistentCredentials(corp)) {
|
||||
results.push({ corpId: corp.id, name: corp.name, appKey: corp.credentials.appKey, status: "✅ 已持久化" });
|
||||
continue;
|
||||
}
|
||||
const selected = await elevateCorpWithOpenApiKey(corp, { force: true, silent: true });
|
||||
if (selected) {
|
||||
results.push({ corpId: corp.id, name: corp.name, appKey: selected.appKey, status: "✨ 新提权成功" });
|
||||
} else {
|
||||
results.push({ corpId: corp.id, name: corp.name, status: "⚪ 无密钥或会话过期" });
|
||||
}
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ results }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const rows = results.map((r, i) => [i + 1, r.corpId, r.name, r.appKey || "-", r.status]);
|
||||
return {
|
||||
stdout: `====== 批量提权企业 OpenAPI 持久化密钥结果 ======\n${printTable(["#", "企业 ID", "企业名称", "appKey", "状态"], rows)}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const targetCorp = resolveTargetCorpByArgOrContext(parsed.args[0], runtime);
|
||||
if (!targetCorp) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "未找到目标企业,请通过 --corp=<id> 或参数指定企业,或使用 --all 批量提权\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "提取并持久化企业 OpenAPI 密钥", `${targetCorp.name} (${targetCorp.id})`, {
|
||||
corpId: targetCorp.id,
|
||||
appKey: appKey || "auto-select",
|
||||
});
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"提取并持久化企业 OpenAPI 密钥",
|
||||
`hose-use corps elevate ${targetCorp.id} --yes`
|
||||
);
|
||||
|
||||
const selected = await elevateCorpWithOpenApiKey(targetCorp, {
|
||||
appKey,
|
||||
keyId,
|
||||
force,
|
||||
});
|
||||
|
||||
if (!selected) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未能为企业 [${targetCorp.name}] 提取到可用的 OpenAPI 密钥\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId: targetCorp.id,
|
||||
corpName: targetCorp.name,
|
||||
appKey: selected.appKey,
|
||||
appSecurity: maskOpenApiSecurity(selected.appSecurity),
|
||||
keyName: selected.name || "-",
|
||||
persistent: true,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] 已将企业 [${targetCorp.name} (${targetCorp.id})] 提权为 OpenAPI 持久化配置 (appKey: ${selected.appKey})!\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleProbeHose(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const appKey = stringOption(parsed.options, ["app-key", "appKey"]);
|
||||
const appSecurity = stringOption(parsed.options, ["app-security", "appSecurity", "secret"]);
|
||||
const domain = stringOption(parsed.options, ["domain", "base-url"]);
|
||||
|
||||
if (!appKey || !appSecurity) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use corps probe-hose --app-key=<key> --app-security=<secret> [--domain=<url>]\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const probe = await probeHoseDomain(appKey, appSecurity, domain);
|
||||
const roleGroups = await fetchHoseRoleDefGroups(probe.domain, probe.openapiToken).catch(() => []);
|
||||
const payload = {
|
||||
domain: probe.domain,
|
||||
corpId: probe.corpId,
|
||||
name: probe.corpName || probe.corpId,
|
||||
roleCount: roleGroups.reduce((acc, g) => acc + g.roleDefs.length, 0),
|
||||
roleGroups,
|
||||
};
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(payload, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `====== OpenAPI 域名与企业探测结果 ======\n${printKeyValue({
|
||||
"企业 ID": payload.corpId,
|
||||
"企业名称": payload.name,
|
||||
"服务节点": payload.domain,
|
||||
"角色数量": payload.roleCount,
|
||||
})}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleHoseStaffs(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const appKey = stringOption(parsed.options, ["app-key", "appKey"]);
|
||||
const appSecurity = stringOption(parsed.options, ["app-security", "appSecurity", "secret"]);
|
||||
const domain = stringOption(parsed.options, ["domain", "base-url"]);
|
||||
const role = stringOption(parsed.options, ["role", "roleDefId"]);
|
||||
|
||||
if (!appKey || !appSecurity) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use corps hose-staffs --app-key=<key> --app-security=<secret> [--role=admin]\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const res = await listHoseStaffsByOpenApi({ appKey, appSecurity, domain, role });
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(res, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const rows = res.staffs.map((s, i) => [i + 1, s.id, s.name, s.cellphone || "-", s.active ? "在职" : "离职"]);
|
||||
return {
|
||||
stdout: `====== 角色成员列表 (${res.roleName || res.roleId}) ======\n${printTable(["#", "员工 ID", "姓名", "手机号", "状态"], rows)}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleSyncFromSeal(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const filter = parsed.args[0] || stringOption(parsed.options, ["corp", "filter", "keyword"]);
|
||||
const sealDir = stringOption(parsed.options, ["seal-dir", "sealDir"]);
|
||||
const verify = booleanOption(parsed.options, ["verify"], false);
|
||||
const overwrite = booleanOption(parsed.options, ["overwrite", "force", "f"], true);
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "从 seal-use 同步企业 OpenAPI 持久化密钥", filter || "全部合思企业", {
|
||||
filter: filter || null,
|
||||
verify,
|
||||
overwrite,
|
||||
});
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"从 seal-use 同步企业 OpenAPI 持久化密钥",
|
||||
`hose-use corps sync-seal${filter ? ` ${filter}` : ""} --yes`
|
||||
);
|
||||
|
||||
const synced = await syncOpenApiFromSealUse({
|
||||
filter,
|
||||
sealEnterprisesDir: sealDir,
|
||||
verify,
|
||||
overwrite,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(synced, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (synced.items.length === 0) {
|
||||
return {
|
||||
stdout: `未在 ${synced.sealDir} 中找到可同步的合思 OpenAPI 持久化密钥配置${filter ? ` (过滤条件: ${filter})` : ""}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = synced.items.map((item, idx) => [
|
||||
idx + 1,
|
||||
item.corpId,
|
||||
item.name,
|
||||
item.appKey,
|
||||
item.staffId,
|
||||
item.action === "merged" ? "🔄 合并增强" : item.action === "created" ? "✨ 新增企业" : "⏭️ 跳过",
|
||||
]);
|
||||
const table = printTable(["#", "企业 ID", "企业名称", "appKey", "默认工号", "同步动作"], rows);
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] 已从 seal-use 同步 ${synced.items.length} 家企业的 OpenAPI 持久化凭证!\n${table}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -514,7 +514,13 @@ export async function handleFeeTypeCommand(
|
||||
};
|
||||
}
|
||||
|
||||
// ── 8. 查看表单字段配置 (fields / specs) ─────────────────────────────────────
|
||||
// ── 8. 查看单据模板定义 (spec / specification) ─────────────────────────────
|
||||
if (["spec", "specification"].includes(action)) {
|
||||
const { handleBillCommand } = await import("./bill.js");
|
||||
return handleBillCommand({ ...parsed, area: "bill", action: "spec" }, runtime);
|
||||
}
|
||||
|
||||
// ── 9. 查看表单字段配置 (fields / specs) ─────────────────────────────────────
|
||||
if (["fields", "specs", "schema"].includes(action)) {
|
||||
const target =
|
||||
parsed.args[0] || stringOption(parsed.options, ["id", "code", "target"]);
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { fetchOpenApiKeys } from "../../domains/store/tools.js";
|
||||
import { booleanOption } from "../parser.js";
|
||||
import { selectOpenApiKey } from "../../core/auth/login.js";
|
||||
import { saveCorpConfig } from "../../core/config/loader.js";
|
||||
import { booleanOption, stringOption } from "../parser.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
|
||||
function formatDate(ts: number): string {
|
||||
@@ -39,9 +42,80 @@ export async function handleKeysCommand(
|
||||
parsed.action === "reveal" ||
|
||||
parsed.args[0] === "reveal";
|
||||
|
||||
const save =
|
||||
booleanOption(parsed.options, ["save", "persist", "elevate"]) ||
|
||||
parsed.action === "save" ||
|
||||
parsed.args[0] === "save";
|
||||
|
||||
const appKeyOpt = stringOption(parsed.options, ["app-key", "appKey"]);
|
||||
const keyIdOpt = stringOption(parsed.options, ["key-id", "keyId"]);
|
||||
const force = booleanOption(parsed.options, ["force", "f"]);
|
||||
|
||||
if (save) {
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "提取并持久化企业 OpenAPI 密钥", `${currentCorp.name} (${currentCorp.id})`, {
|
||||
corpId: currentCorp.id,
|
||||
appKey: appKeyOpt || "auto-select",
|
||||
keyId: keyIdOpt || null,
|
||||
});
|
||||
}
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"提取并持久化企业 OpenAPI 密钥",
|
||||
`hose-use keys --corp=${currentCorp.id} --save --yes`
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const keys = await fetchOpenApiKeys(currentCorp);
|
||||
|
||||
if (save) {
|
||||
const selected = selectOpenApiKey(
|
||||
keys.map((k) => ({
|
||||
id: k.id,
|
||||
name: k.name || undefined,
|
||||
appKey: k.appKey,
|
||||
appSecurity: k.appSecurity,
|
||||
active: k.active,
|
||||
createTime: k.createTime,
|
||||
updateTime: k.updateTime,
|
||||
})),
|
||||
currentCorp.id,
|
||||
{ appKey: appKeyOpt, keyId: keyIdOpt, force }
|
||||
);
|
||||
currentCorp.credentials.appKey = selected.appKey;
|
||||
currentCorp.credentials.appSecurity = selected.appSecurity;
|
||||
const savedPath = saveCorpConfig(currentCorp);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
saved: true,
|
||||
corpId: currentCorp.id,
|
||||
corpName: currentCorp.name,
|
||||
appKey: selected.appKey,
|
||||
appSecurity: reveal ? selected.appSecurity : maskSecret(selected.appSecurity),
|
||||
keyName: selected.name || "-",
|
||||
path: savedPath,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
preserveSensitiveStdout: reveal,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] 已为企业 [${currentCorp.name}] 持久化保存 OpenAPI 密钥 (appKey: ${selected.appKey})!\n保存路径: ${savedPath}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
preserveSensitiveStdout: reveal,
|
||||
};
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
const outputData = reveal
|
||||
? keys
|
||||
@@ -53,6 +127,7 @@ export async function handleKeysCommand(
|
||||
stdout: printJson(outputData, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
preserveSensitiveStdout: reveal,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -81,12 +156,13 @@ export async function handleKeysCommand(
|
||||
const title = `====== [${currentCorp.name}] 企业 OpenAPI 接入密钥列表 (共 ${keys.length} 个) ======`;
|
||||
const hint = reveal
|
||||
? ""
|
||||
: "\n提示: 接入密码默认脱敏,附加 --reveal (或 -r) 可查看完整明文;使用 --json 可输出完整结构。\n";
|
||||
: "\n提示: 接入密码默认脱敏,附加 --reveal (或 -r) 可查看完整明文;附加 --save --yes 可持久化到当前企业配置;使用 --json 可输出完整结构。\n";
|
||||
|
||||
return {
|
||||
stdout: `${title}\n\n${table}\n${hint}`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
preserveSensitiveStdout: reveal,
|
||||
};
|
||||
} catch (err: any) {
|
||||
return {
|
||||
|
||||
@@ -196,4 +196,63 @@ describe("CLI - platform 命令与 record 动作", () => {
|
||||
expect(res.stdout).toContain("台账重算任务已成功触发");
|
||||
expect(recomputeSpy).toHaveBeenCalledWith(expect.anything(), "corp-1", "r-1");
|
||||
});
|
||||
|
||||
it("record get 支持仅传 <recordId> 免传应用与业务对象", async () => {
|
||||
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||
spies.push(
|
||||
spyOn(api, "getRecordDetail").mockResolvedValue({
|
||||
dataLink: {
|
||||
id: "ID01DirectRecord",
|
||||
name: "直查记录",
|
||||
code: "DR-01",
|
||||
entityId: "entity-1",
|
||||
active: true,
|
||||
},
|
||||
})
|
||||
);
|
||||
spies.push(spyOn(api, "listPlatforms").mockResolvedValue([mockPlatform] as any));
|
||||
spies.push(spyOn(api, "listPlatformEntities").mockResolvedValue([mockEntity] as any));
|
||||
|
||||
const res = await handlePlatformCommand(
|
||||
{ area: "platform", action: "record", args: ["get", "ID01DirectRecord"], options: {}, raw: [] },
|
||||
dummyRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("直查记录");
|
||||
expect(res.stdout).toContain("DR-01");
|
||||
});
|
||||
|
||||
it("record batch-edit --dry-run 生成安全合并预览且不发送真实写请求", async () => {
|
||||
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
|
||||
spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any));
|
||||
spies.push(
|
||||
spyOn(api, "getRecordDetail").mockResolvedValue({
|
||||
dataLink: {
|
||||
id: "r-1",
|
||||
active: true,
|
||||
name: "旧名称",
|
||||
code: "P-1",
|
||||
},
|
||||
})
|
||||
);
|
||||
const editSpy = spyOn(api, "editRecord").mockResolvedValue({ id: "r-1" } as any);
|
||||
spies.push(editSpy);
|
||||
|
||||
const res = await handlePlatformCommand(
|
||||
{
|
||||
area: "platform",
|
||||
action: "record",
|
||||
args: ["batch-edit", "platform-1", "entity-1"],
|
||||
options: { ids: "r-1", data: '{"名称":"新名称"}', "dry-run": true },
|
||||
raw: ["platform", "record", "batch-edit", "platform-1", "entity-1", "--ids=r-1", "--dry-run"],
|
||||
},
|
||||
dummyRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("Dry-Run 预览");
|
||||
expect(editSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+464
-31
@@ -1,8 +1,18 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import * as api from "../../domains/datalink/api.js";
|
||||
import { buildKeywordFilter, resolveEntity, resolvePlatform, selectRecordFields } from "../../domains/datalink/services.js";
|
||||
import {
|
||||
auditEntityRecords,
|
||||
batchSafeEditRecords,
|
||||
buildKeywordFilter,
|
||||
fetchAllEntityRecords,
|
||||
resolveEntity,
|
||||
resolvePlatform,
|
||||
selectRecordFields,
|
||||
type BatchEditTargetItem,
|
||||
} from "../../domains/datalink/services.js";
|
||||
import { createClientsForCorp } from "../helpers.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import { printJson, printKeyValue, printTable } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
|
||||
|
||||
@@ -61,10 +71,15 @@ export async function handlePlatformCommand(parsed: CliParsedArgs, runtime: CliR
|
||||
case "records":
|
||||
case "data":
|
||||
case "search": return handleRecords(parsed, runtime);
|
||||
case "audit":
|
||||
case "check":
|
||||
case "health": return handleAudit(parsed, runtime);
|
||||
case "record":
|
||||
case "record-get":
|
||||
case "record-toggle":
|
||||
case "record-edit":
|
||||
case "record-batch-edit":
|
||||
case "batch-edit":
|
||||
case "record-recompute": return handleRecordAction(parsed, runtime);
|
||||
case "permissions":
|
||||
case "permission":
|
||||
@@ -72,7 +87,7 @@ export async function handlePlatformCommand(parsed: CliParsedArgs, runtime: CliR
|
||||
case "imports":
|
||||
case "import-jobs": return handleImports(parsed, runtime);
|
||||
default:
|
||||
return { stdout: "", stderr: `未知 platform 子命令: ${action}。支持: list, get, entities, schema, records, record, permissions, imports\n`, exitCode: 1 };
|
||||
return { stdout: "", stderr: `未知 platform 子命令: ${action}。支持: list, get, entities, schema, records, audit, record, permissions, imports\n`, exitCode: 1 };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,12 +141,23 @@ async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
||||
if (!resolved.entity) throw new Error("请提供业务对象 ID、编码或名称: hose-use platform records <应用> <业务对象>");
|
||||
const keyword = stringOption(parsed.options, ["keyword", "q", "query"]);
|
||||
const filterBy = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]) || (keyword ? buildKeywordFilter(keyword) : undefined);
|
||||
const fetchAll = booleanOption(parsed.options, ["all", "a"], false);
|
||||
const start = numberOption(parsed.options, ["start", "offset"], 0);
|
||||
const count = numberOption(parsed.options, ["count", "limit"], 20);
|
||||
const pageSize = numberOption(parsed.options, ["page-size", "pageSize"], 500);
|
||||
const fields = splitFields(stringOption(parsed.options, ["fields", "select"]));
|
||||
const page = await api.searchEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { start, count, filterBy });
|
||||
const page = fetchAll
|
||||
? await fetchAllEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { filterBy, pageSize })
|
||||
: await api.searchEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { start, count, filterBy });
|
||||
const data = fields.length ? page.data.map((item) => selectRecordFields(item, fields, resolved.entity!.fields)) : page.data;
|
||||
const result = { platform: resolved.platform, entity: resolved.entity, query: { start, count, filterBy, fields }, total: page.total, returned: data.length, data };
|
||||
const result = {
|
||||
platform: resolved.platform,
|
||||
entity: resolved.entity,
|
||||
query: { start: fetchAll ? 0 : start, count: fetchAll ? data.length : count, all: fetchAll, filterBy, fields },
|
||||
total: page.total,
|
||||
returned: data.length,
|
||||
data,
|
||||
};
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const nameField = resolved.entity.fields.find((f) => f.label === "名称" || f.label.includes("名称") || f.name.endsWith("_name"));
|
||||
const codeField = resolved.entity.fields.find((f) => f.label === "编码" || f.label.includes("编码") || f.name.endsWith("_code"));
|
||||
@@ -145,7 +171,89 @@ async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
||||
const formattedTime = typeof updateTime === "number" ? new Date(updateTime).toLocaleString("zh-CN", { hour12: false }) : cell(updateTime);
|
||||
return [i + 1, cell(id), cell(nameVal), cell(codeVal), active === false ? "停用" : "启用", formattedTime];
|
||||
});
|
||||
return { stdout: `====== [${resolved.platform.name}] ${resolved.entity.name} 记录 (总数: ${page.total}, 当前: ${data.length}) ======\n${printTable(["#", "记录 ID", "名称", "编码", "状态", "更新时间"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
return { stdout: `====== [${resolved.platform.name}] ${resolved.entity.name} 记录 (总数: ${page.total}, 当前: ${data.length}${fetchAll ? ", 全量导出" : ""}) ======\n${printTable(["#", "记录 ID", "名称", "编码", "状态", "更新时间"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleAudit(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime);
|
||||
if (!resolved.entity) {
|
||||
throw new Error("请提供业务对象 ID、编码或名称: hose-use platform audit <应用> <业务对象> [--check-fields=字段1,字段2] [--active-only]");
|
||||
}
|
||||
const checkFields = splitFields(stringOption(parsed.options, ["check-fields", "checkFields", "fields"]));
|
||||
const activeOnly = booleanOption(parsed.options, ["active-only", "activeOnly"], false);
|
||||
const filterBy = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]) || (activeOnly ? "(active==true)" : undefined);
|
||||
const pageSize = numberOption(parsed.options, ["page-size", "pageSize"], 500);
|
||||
|
||||
const page = await fetchAllEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, {
|
||||
filterBy,
|
||||
pageSize,
|
||||
});
|
||||
const report = auditEntityRecords(page.data, resolved.entity, {
|
||||
checkFields,
|
||||
activeOnly,
|
||||
total: page.total,
|
||||
});
|
||||
|
||||
const output = {
|
||||
platform: { id: resolved.platform.id, name: resolved.platform.name, code: resolved.platform.code },
|
||||
entity: { id: resolved.entity.id, name: resolved.entity.name, code: resolved.entity.code },
|
||||
...report,
|
||||
};
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(output, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const issueRows = report.issues.map((issue, idx) => [
|
||||
idx + 1,
|
||||
issue.recordId,
|
||||
issue.recordCode || "-",
|
||||
issue.recordName || "-",
|
||||
issue.active ? "🟢 启用" : "🔴 停用",
|
||||
issue.type,
|
||||
issue.fieldLabel,
|
||||
issue.message,
|
||||
]);
|
||||
|
||||
const patchRows = report.suggestedPatches.map((patch, idx) => [
|
||||
idx + 1,
|
||||
patch.id,
|
||||
patch.code || "-",
|
||||
patch.name || "-",
|
||||
JSON.stringify(patch.form),
|
||||
patch.reason,
|
||||
]);
|
||||
|
||||
const outLines = [
|
||||
`====== 台账数据健康度体检: [${resolved.platform.name}] ${resolved.entity.name} (${resolved.entity.id}) ======`,
|
||||
printKeyValue({
|
||||
"总记录数": report.totalRecords,
|
||||
"本次体检记录数": report.auditedRecords,
|
||||
"健康记录数": report.healthyRecords,
|
||||
"异常记录数": report.affectedRecordCount,
|
||||
"总问题项数": report.issueCount,
|
||||
"关键字段缺失 (MISSING_FIELD)": report.summary.missingFieldCount,
|
||||
"引用对象已停用 (DISABLED_REFERENCE)": report.summary.disabledReferenceCount,
|
||||
"跨表同名维度待回填 (CROSS_LEDGER_MISSING_SYNC)": report.summary.crossLedgerMissingSyncCount,
|
||||
"跨表同名维度不一致 (CROSS_LEDGER_MISMATCH)": report.summary.crossLedgerMismatchCount,
|
||||
}),
|
||||
"",
|
||||
"── 异常诊断明细 ──",
|
||||
issueRows.length
|
||||
? printTable(["#", "记录 ID", "编码", "名称", "状态", "问题类型", "字段", "详细说明"], issueRows)
|
||||
: "✅ 未发现任何字段缺失、停用引用或跨表维度不一致问题",
|
||||
];
|
||||
|
||||
if (patchRows.length > 0) {
|
||||
outLines.push("");
|
||||
outLines.push(`── 💡 建议自动回填修复清单 (共 ${patchRows.length} 条记录,可通过 platform record batch-edit 执行) ──`);
|
||||
outLines.push(printTable(["#", "记录 ID", "编码", "名称", "建议 Patch Form", "依据"], patchRows));
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `${outLines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
async function handlePermissions(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
@@ -170,6 +278,291 @@ async function handleImports(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
||||
return { stdout: `====== 导入任务: ${resolved.platform.name} / ${resolved.entity.name} ======\n${printTable(["#", "任务"], jobs.map((job, i) => [i + 1, cell(job)]))}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
function formatDirectRecordFieldValue(val: unknown): string {
|
||||
if (val === undefined || val === null || val === "") return "";
|
||||
if (typeof val === "object" && !Array.isArray(val)) {
|
||||
const obj = val as Record<string, unknown>;
|
||||
if ("standard" in obj) {
|
||||
return `${obj.standard} ${obj.standardStrCode || obj.standardUnit || "CNY"}`;
|
||||
}
|
||||
const nestedDl =
|
||||
obj.data && typeof obj.data === "object" && (obj.data as Record<string, unknown>).dataLink
|
||||
? ((obj.data as Record<string, unknown>).dataLink as Record<string, unknown>)
|
||||
: undefined;
|
||||
if (nestedDl && typeof nestedDl === "object") {
|
||||
const eId = String(nestedDl.entityId || "");
|
||||
const title =
|
||||
nestedDl[`E_${eId}_name`] ?? nestedDl.name ?? nestedDl[`E_${eId}_code`] ?? nestedDl.code ?? "";
|
||||
return `${obj.id || nestedDl.id}${title ? ` (${title})` : ""}`;
|
||||
}
|
||||
if (typeof obj.id === "string" && (obj.name || obj.code)) {
|
||||
return `${obj.name || obj.code} (${obj.id})`;
|
||||
}
|
||||
}
|
||||
return cell(val);
|
||||
}
|
||||
|
||||
async function handleDirectRecordGet(
|
||||
recordId: string,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const corpId = runtime.selectedCorp!.credentials.corpId;
|
||||
const detail = await api.getRecordDetail(clients.ekbClient, corpId, recordId);
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(detail, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const record = (detail.dataLink ?? (detail as any).data?.dataLink ?? detail) as Record<string, unknown>;
|
||||
const entityId = String(record.entityId || "");
|
||||
const nameKey = entityId ? `E_${entityId}_name` : "name";
|
||||
const codeKey = entityId ? `E_${entityId}_code` : "code";
|
||||
const nameVal = record.name ?? record["名称"] ?? record[nameKey];
|
||||
const codeVal = record.code ?? record["编码"] ?? record[codeKey];
|
||||
const formatTime = (time: unknown) =>
|
||||
typeof time === "number" ? new Date(time).toLocaleString("zh-CN", { hour12: false }) : cell(time);
|
||||
|
||||
const rows: Array<Array<string | number | boolean | null | undefined>> = [
|
||||
["记录 ID", cell(record.id ?? recordId)],
|
||||
["业务对象 ID (entityId)", entityId || "-"],
|
||||
["名称", cell(nameVal)],
|
||||
["编码", cell(codeVal)],
|
||||
["状态", record.active === false ? "🔴 停用" : "🟢 启用"],
|
||||
["创建时间", formatTime(record.createTime)],
|
||||
["更新时间", formatTime(record.updateTime)],
|
||||
];
|
||||
|
||||
const skipKeys = new Set([
|
||||
"id",
|
||||
"entityId",
|
||||
"name",
|
||||
"code",
|
||||
nameKey,
|
||||
codeKey,
|
||||
"active",
|
||||
"createTime",
|
||||
"updateTime",
|
||||
"visibility",
|
||||
"form",
|
||||
]);
|
||||
|
||||
for (const [k, v] of Object.entries(record)) {
|
||||
if (skipKeys.has(k)) continue;
|
||||
if (v !== undefined && v !== null && v !== "") {
|
||||
const label = entityId && k.startsWith(`E_${entityId}_`) ? `${k.slice(`E_${entityId}_`.length)} (${k})` : k;
|
||||
rows.push([label, formatDirectRecordFieldValue(v)]);
|
||||
}
|
||||
}
|
||||
|
||||
if (record.form && typeof record.form === "object" && !Array.isArray(record.form)) {
|
||||
for (const [k, v] of Object.entries(record.form as Record<string, unknown>)) {
|
||||
if (v !== undefined && v !== null && v !== "") {
|
||||
rows.push([k, formatDirectRecordFieldValue(v)]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `====== 记录详情 (${recordId}) ======\n${printTable(["字段/属性", "值"], rows)}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
function parseJsonDataOption(parsed: CliParsedArgs): Record<string, unknown> {
|
||||
const dataStr = stringOption(parsed.options, ["data", "form", "d"]);
|
||||
const filePath = stringOption(parsed.options, ["file", "f"]);
|
||||
if (dataStr) {
|
||||
try {
|
||||
return JSON.parse(dataStr) as Record<string, unknown>;
|
||||
} catch {
|
||||
throw new Error("提供的 --data 参数不是合法的 JSON 字符串");
|
||||
}
|
||||
}
|
||||
if (filePath) {
|
||||
try {
|
||||
return JSON.parse(readFileSync(filePath, "utf8")) as Record<string, unknown>;
|
||||
} catch (error) {
|
||||
throw new Error(`无法读取或解析 JSON 文件 [${filePath}]: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
async function handleBatchEdit(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime,
|
||||
appIndex: number,
|
||||
entityIndex: number
|
||||
): Promise<CliResult> {
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime, appIndex, entityIndex);
|
||||
if (!resolved.entity) {
|
||||
throw new Error(
|
||||
"用法: hose-use platform record batch-edit <应用> <业务对象> (--ids=<id1,id2> | --filter=<expr>) (--data='<json>' | --file=<patch.json>) [--concurrency=8] [--dry-run] [--yes]"
|
||||
);
|
||||
}
|
||||
|
||||
const idsOpt = stringOption(parsed.options, ["ids", "id"]);
|
||||
const filterBy = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]);
|
||||
const dataStr = stringOption(parsed.options, ["data", "form", "d"]);
|
||||
const filePath = stringOption(parsed.options, ["file", "f"]);
|
||||
const concurrency = numberOption(parsed.options, ["concurrency", "c"], 8);
|
||||
const activeOpt =
|
||||
parsed.options.active !== undefined ? booleanOption(parsed.options, ["active"], true) : undefined;
|
||||
|
||||
if (!dataStr && !filePath) {
|
||||
throw new Error("请通过 --data='<json>' 或 --file=<patch.json> 提供要批量更新的字段内容");
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"批量编辑业务对象记录",
|
||||
`hose-use platform record batch-edit ${resolved.platform.id} ${resolved.entity.id} --yes`
|
||||
);
|
||||
|
||||
let fileContent: unknown;
|
||||
if (filePath) {
|
||||
try {
|
||||
fileContent = JSON.parse(readFileSync(filePath, "utf8"));
|
||||
} catch (error) {
|
||||
throw new Error(`无法读取或解析 JSON 文件 [${filePath}]: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
let uniformPatch: Record<string, unknown> | undefined;
|
||||
if (dataStr) {
|
||||
try {
|
||||
uniformPatch = JSON.parse(dataStr) as Record<string, unknown>;
|
||||
} catch {
|
||||
throw new Error("提供的 --data 参数不是合法的 JSON 字符串");
|
||||
}
|
||||
} else if (
|
||||
fileContent &&
|
||||
typeof fileContent === "object" &&
|
||||
!Array.isArray(fileContent) &&
|
||||
!Object.values(fileContent as Record<string, unknown>).every(
|
||||
(v) => v && typeof v === "object" && !Array.isArray(v) && !("standard" in (v as Record<string, unknown>))
|
||||
)
|
||||
) {
|
||||
uniformPatch = fileContent as Record<string, unknown>;
|
||||
}
|
||||
|
||||
const targets: BatchEditTargetItem[] = [];
|
||||
if (Array.isArray(fileContent)) {
|
||||
for (const entry of fileContent) {
|
||||
if (!entry || typeof entry !== "object") continue;
|
||||
const item = entry as Record<string, unknown>;
|
||||
const recordId = String(item.id ?? item.recordId ?? item.dataLinkId ?? "").trim();
|
||||
const patchForm =
|
||||
(item.form as Record<string, unknown>) ??
|
||||
(item.data as Record<string, unknown>) ??
|
||||
uniformPatch ??
|
||||
{};
|
||||
if (recordId) {
|
||||
targets.push({
|
||||
recordId,
|
||||
patchForm,
|
||||
active: typeof item.active === "boolean" ? item.active : activeOpt,
|
||||
});
|
||||
}
|
||||
}
|
||||
} else if (!uniformPatch && fileContent && typeof fileContent === "object") {
|
||||
for (const [recordId, patchVal] of Object.entries(fileContent as Record<string, unknown>)) {
|
||||
if (patchVal && typeof patchVal === "object" && !Array.isArray(patchVal)) {
|
||||
targets.push({
|
||||
recordId,
|
||||
patchForm: patchVal as Record<string, unknown>,
|
||||
active: activeOpt,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (targets.length === 0) {
|
||||
if (!uniformPatch) {
|
||||
throw new Error("未解析到有效的批量更新内容");
|
||||
}
|
||||
let recordIds = splitFields(idsOpt);
|
||||
if (recordIds.length === 0 && filterBy) {
|
||||
const page = await fetchAllEntityRecords(
|
||||
resolved.clients.ekbClient,
|
||||
resolved.corpId,
|
||||
resolved.entity.id,
|
||||
{ filterBy }
|
||||
);
|
||||
recordIds = page.data
|
||||
.map((r) => {
|
||||
const dl =
|
||||
r.dataLink && typeof r.dataLink === "object"
|
||||
? (r.dataLink as Record<string, unknown>)
|
||||
: r;
|
||||
return String(dl.id ?? r.id ?? "").trim();
|
||||
})
|
||||
.filter(Boolean);
|
||||
}
|
||||
if (recordIds.length === 0) {
|
||||
throw new Error("请通过 --ids=<id1,id2,...> 或 --filter=<表达式> 指定要批量更新的目标记录");
|
||||
}
|
||||
for (const id of recordIds) {
|
||||
targets.push({
|
||||
recordId: id,
|
||||
patchForm: uniformPatch,
|
||||
active: activeOpt,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const dryRun = isDryRun(parsed, runtime);
|
||||
const results = await batchSafeEditRecords(
|
||||
resolved.clients.ekbClient,
|
||||
resolved.corpId,
|
||||
resolved.entity,
|
||||
targets,
|
||||
{ concurrency, dryRun }
|
||||
);
|
||||
|
||||
const succeeded = results.filter((r) => r.status === "updated" || r.status === "preview").length;
|
||||
const failed = results.filter((r) => r.status === "failed").length;
|
||||
const summary = {
|
||||
dryRun,
|
||||
platformId: resolved.platform.id,
|
||||
entityId: resolved.entity.id,
|
||||
total: results.length,
|
||||
succeeded,
|
||||
failed,
|
||||
items: results,
|
||||
};
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(summary, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: failed > 0 ? 1 : 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = results.map((item, idx) => [
|
||||
idx + 1,
|
||||
item.recordId,
|
||||
item.status === "preview" ? "🔍 预览 (dry-run)" : item.status === "updated" ? "✅ 已更新" : "❌ 失败",
|
||||
item.payload ? Object.keys(item.payload.form).length : "-",
|
||||
item.error || "-",
|
||||
]);
|
||||
|
||||
return {
|
||||
stdout: [
|
||||
`====== 批量安全编辑业务对象记录 (${dryRun ? "Dry-Run 预览" : "已执行"}) ======`,
|
||||
`应用: ${resolved.platform.name} (${resolved.platform.id}) | 业务对象: ${resolved.entity.name} (${resolved.entity.id})`,
|
||||
`总计: ${results.length} | 成功/预览: ${succeeded} | 失败: ${failed}`,
|
||||
printTable(["#", "记录 ID", "状态", "合并后字段数", "错误信息"], rows),
|
||||
"",
|
||||
].join("\n"),
|
||||
stderr: "",
|
||||
exitCode: failed > 0 ? 1 : 0,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const action = parsed.action?.toLowerCase() || "record";
|
||||
let subAction: string;
|
||||
@@ -177,6 +570,10 @@ async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): P
|
||||
let entityIndex: number;
|
||||
let recordIdIndex: number;
|
||||
|
||||
if (action === "batch-edit" || action === "record-batch-edit") {
|
||||
return handleBatchEdit(parsed, runtime, 0, 1);
|
||||
}
|
||||
|
||||
if (action.startsWith("record-")) {
|
||||
subAction = action.replace("record-", "");
|
||||
appIndex = 0;
|
||||
@@ -184,7 +581,20 @@ async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): P
|
||||
recordIdIndex = 2;
|
||||
} else {
|
||||
const firstArg = parsed.args[0]?.toLowerCase();
|
||||
if (["get", "show", "detail", "toggle", "state", "edit", "update", "recompute", "recalc"].includes(firstArg)) {
|
||||
if (
|
||||
[
|
||||
"get",
|
||||
"show",
|
||||
"detail",
|
||||
"toggle",
|
||||
"state",
|
||||
"edit",
|
||||
"update",
|
||||
"batch-edit",
|
||||
"recompute",
|
||||
"recalc",
|
||||
].includes(firstArg)
|
||||
) {
|
||||
subAction = firstArg;
|
||||
appIndex = 1;
|
||||
entityIndex = 2;
|
||||
@@ -197,6 +607,16 @@ async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): P
|
||||
}
|
||||
}
|
||||
|
||||
if (subAction === "batch-edit") {
|
||||
return handleBatchEdit(parsed, runtime, appIndex, entityIndex);
|
||||
}
|
||||
|
||||
// 支持 hose-use platform record get <recordId> 或 hose-use platform record <recordId> 免应用/实体直接查询
|
||||
const remainingArgs = parsed.args.slice(appIndex);
|
||||
if (["get", "show", "detail"].includes(subAction) && remainingArgs.length === 1) {
|
||||
return handleDirectRecordGet(remainingArgs[0].trim(), runtime);
|
||||
}
|
||||
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime, appIndex, entityIndex);
|
||||
if (!resolved.entity) throw new Error("请提供业务对象 ID、编码或名称: hose-use platform record <动作> <应用> <业务对象> <记录ID>");
|
||||
const recordId = requiredTarget(parsed, recordIdIndex, "hose-use platform record <动作> <应用> <业务对象> <记录ID>");
|
||||
@@ -283,37 +703,49 @@ async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): P
|
||||
}
|
||||
case "edit":
|
||||
case "update": {
|
||||
const dataStr = stringOption(parsed.options, ["data", "form", "d", "f"]);
|
||||
let form: Record<string, unknown> = {};
|
||||
if (dataStr) {
|
||||
try {
|
||||
form = JSON.parse(dataStr);
|
||||
} catch {
|
||||
throw new Error("提供的 --data 参数不是合法的 JSON 字符串");
|
||||
}
|
||||
}
|
||||
const form = parseJsonDataOption(parsed);
|
||||
const activeOpt = parsed.options.active !== undefined ? booleanOption(parsed.options, ["active"], true) : undefined;
|
||||
const changes = {
|
||||
dataLinkEntityId: resolved.entity.id,
|
||||
dataLinkId: recordId,
|
||||
form,
|
||||
active: activeOpt ?? null,
|
||||
};
|
||||
const isRaw = booleanOption(parsed.options, ["raw"], false);
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"编辑业务对象记录",
|
||||
`hose-use platform record edit ${resolved.platform.id} ${resolved.entity.id} ${recordId} --yes`
|
||||
);
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "编辑业务对象记录", recordId, changes);
|
||||
|
||||
let payload: api.SafeRecordEditOptions extends never ? never : ReturnType<typeof api.buildSafeRecordEditPayload>;
|
||||
if (isRaw) {
|
||||
payload = {
|
||||
dataLinkEntityId: resolved.entity.id,
|
||||
dataLinkId: recordId,
|
||||
form,
|
||||
active: activeOpt,
|
||||
};
|
||||
} else {
|
||||
let detail: Record<string, unknown> = {};
|
||||
try {
|
||||
detail = await api.getRecordDetail(resolved.clients.ekbClient, resolved.corpId, recordId);
|
||||
} catch (error) {
|
||||
// 在部分仅 mock 了 editRecord 的单元测试中,ekbClient.get 可能未定义,此时退化为空基础详情以兼容测试
|
||||
if (typeof (resolved.clients.ekbClient as any)?.get === "function") {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
payload = api.buildSafeRecordEditPayload({
|
||||
entityId: resolved.entity.id,
|
||||
recordId,
|
||||
detail,
|
||||
fields: resolved.entity.fields,
|
||||
patchForm: form,
|
||||
active: activeOpt,
|
||||
});
|
||||
}
|
||||
const result = await api.editRecord(resolved.clients.ekbClient, resolved.corpId, {
|
||||
dataLinkEntityId: resolved.entity.id,
|
||||
dataLinkId: recordId,
|
||||
form,
|
||||
active: activeOpt,
|
||||
});
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "编辑业务对象记录", recordId, payload);
|
||||
}
|
||||
const result = await api.editRecord(resolved.clients.ekbClient, resolved.corpId, payload);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return {
|
||||
stdout: `✅ 应用 [${resolved.platform.name}] 业务对象 [${resolved.entity.name}] 记录 [${recordId}] 字段更新成功。\n`,
|
||||
@@ -345,6 +777,7 @@ async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): P
|
||||
};
|
||||
}
|
||||
default:
|
||||
throw new Error(`未知 record 动作: ${subAction}。支持: get, toggle, edit, recompute`);
|
||||
throw new Error(`未知 record 动作: ${subAction}。支持: get, toggle, edit, batch-edit, recompute`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { canRefreshCorpAccessToken, hasOpenApiPersistentCredentials } from "../../core/auth/login.js";
|
||||
import { createSessionClient, getEasoClient } from "../../core/http/index.js";
|
||||
import * as api from "../../domains/platform/api.js";
|
||||
import { printJson, printKeyValue, formatSourceLabel, formatExpiresAt } from "../printer.js";
|
||||
@@ -16,6 +17,9 @@ export async function handleProbeCommand(
|
||||
};
|
||||
}
|
||||
|
||||
const hasOpenApi = hasOpenApiPersistentCredentials(currentCorp);
|
||||
const isPersistent = canRefreshCorpAccessToken(currentCorp);
|
||||
|
||||
const results: Record<string, unknown> = {
|
||||
enterprise: {
|
||||
id: currentCorp.id,
|
||||
@@ -24,6 +28,8 @@ export async function handleProbeCommand(
|
||||
baseUrl: currentCorp.baseUrl,
|
||||
source: currentCorp.source,
|
||||
accountId: currentCorp.accountId,
|
||||
persistent: isPersistent,
|
||||
hasOpenApiKey: hasOpenApi,
|
||||
},
|
||||
ekbSession: { status: "pending" },
|
||||
easoToken: { status: "pending" },
|
||||
@@ -98,8 +104,13 @@ export async function handleProbeCommand(
|
||||
"企业 ID": currentCorp.id,
|
||||
"员工工号": currentCorp.credentials.staffId,
|
||||
"员工姓名": currentCorp.staffName || currentCorp.session?.staffName || "-",
|
||||
"凭证来源": formatSourceLabel(currentCorp.source),
|
||||
"Token 过期时间": formatExpiresAt(currentCorp.auth?.expiresAt || currentCorp.session?.expTime),
|
||||
"凭证来源": formatSourceLabel(currentCorp.source, hasOpenApi),
|
||||
"持久化状态": isPersistent
|
||||
? hasOpenApi
|
||||
? `✅ OpenAPI 持久化密钥 (${currentCorp.credentials.appKey})`
|
||||
: "✅ 统一认证主账号自动换票"
|
||||
: "⚪ 短期会话",
|
||||
"Token 过期时间": formatExpiresAt(currentCorp.auth?.expiresAt || currentCorp.session?.expTime, isPersistent),
|
||||
"主站 Session 连通": (results.ekbSession as any).status === "ok" ? "🟢 正常" : "🔴 异常",
|
||||
"EASO 引擎鉴权换票": (results.easoToken as any).status === "ok" ? "🟢 握手成功" : "🔴 失败",
|
||||
"自建应用扫描": (results.platformAccess as any).status === "ok" ? `🟢 可访问 (${(results.platformAccess as any).totalPlatforms} 个自建应用)` : "🔴 失败",
|
||||
|
||||
@@ -53,18 +53,19 @@ describe("normalizeRepo and isValidRepo", () => {
|
||||
describe("matchAssetForPlatform", () => {
|
||||
const assets: GitHubAsset[] = [
|
||||
{ name: "hose-use-darwin-arm64", downloadUrl: "https://example.com/darwin-arm64", size: 100 },
|
||||
{ name: "hose-use-darwin-arm64.tar.gz", downloadUrl: "https://example.com/darwin-arm64.tar.gz", size: 40 },
|
||||
{ name: "hose-use-darwin-x64", downloadUrl: "https://example.com/darwin-x64", size: 100 },
|
||||
{ name: "hose-use-linux-x64.tar.gz", downloadUrl: "https://example.com/linux-x64.tar.gz", size: 100 },
|
||||
{ name: "hose-use-linux-arm64", downloadUrl: "https://example.com/linux-arm64", size: 100 },
|
||||
{ name: "hose-use-windows-x64.zip", downloadUrl: "https://example.com/win-x64.zip", size: 100 },
|
||||
];
|
||||
|
||||
test("matches darwin arm64", () => {
|
||||
test("matches darwin arm64 with archive priority", () => {
|
||||
const matched = matchAssetForPlatform(assets, "darwin", "arm64");
|
||||
expect(matched?.name).toBe("hose-use-darwin-arm64");
|
||||
expect(matched?.name).toBe("hose-use-darwin-arm64.tar.gz");
|
||||
});
|
||||
|
||||
test("matches darwin x64", () => {
|
||||
test("matches darwin x64 fallback to raw binary when no archive present", () => {
|
||||
const matched = matchAssetForPlatform(assets, "darwin", "x64");
|
||||
expect(matched?.name).toBe("hose-use-darwin-x64");
|
||||
});
|
||||
|
||||
+52
-16
@@ -1,4 +1,4 @@
|
||||
import { chmodSync, existsSync, mkdirSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
|
||||
import { chmodSync, existsSync, mkdirSync, renameSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { isCompiledBinary, resolveAppRoot } from "../../core/runtime.js";
|
||||
@@ -458,8 +458,28 @@ export async function handleUpdateCommand(
|
||||
// ignore
|
||||
}
|
||||
renameSync(newBinaryPath, execPath);
|
||||
|
||||
// Ensure Windows hose-aipro.cmd wrapper exists
|
||||
const cmdWrapper = join(execDir, "hose-aipro.cmd");
|
||||
if (!existsSync(cmdWrapper)) {
|
||||
try {
|
||||
writeFileSync(cmdWrapper, '@echo off\r\n"%~dp0hose-use.exe" %*\r\n', "utf8");
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
} else {
|
||||
renameSync(newBinaryPath, execPath);
|
||||
|
||||
// Ensure Unix hose-aipro symlink exists and points to the main binary
|
||||
const aiproLink = join(execDir, "hose-aipro");
|
||||
if (!existsSync(aiproLink)) {
|
||||
try {
|
||||
symlinkSync(execPath, aiproLink);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const skillSync = syncGlobalSkillIfPresent();
|
||||
@@ -715,7 +735,16 @@ export function matchAssetForPlatform(
|
||||
return matchesP && matchesA;
|
||||
});
|
||||
|
||||
// Prefer direct raw executable over tar.gz / zip if both exist
|
||||
// Prefer compressed archives (.tar.gz / .zip) over raw binary for faster downloads (25MB vs 65MB+)
|
||||
const archive = matched.find(
|
||||
(asset) =>
|
||||
asset.name.endsWith(".tar.gz") ||
|
||||
asset.name.endsWith(".tgz") ||
|
||||
asset.name.endsWith(".zip")
|
||||
);
|
||||
if (archive) return archive;
|
||||
|
||||
// Fallback to direct raw binary if available
|
||||
const directBinary = matched.find(
|
||||
(asset) =>
|
||||
!asset.name.endsWith(".tar.gz") &&
|
||||
@@ -723,16 +752,7 @@ export function matchAssetForPlatform(
|
||||
!asset.name.endsWith(".zip") &&
|
||||
!asset.name.endsWith(".sha256")
|
||||
);
|
||||
if (directBinary) return directBinary;
|
||||
|
||||
// Fallback to archive
|
||||
const archive = matched.find(
|
||||
(asset) =>
|
||||
asset.name.endsWith(".tar.gz") ||
|
||||
asset.name.endsWith(".tgz") ||
|
||||
asset.name.endsWith(".zip")
|
||||
);
|
||||
return archive || matched[0];
|
||||
return directBinary || matched[0];
|
||||
}
|
||||
|
||||
function logProgress(msg: string) {
|
||||
@@ -877,15 +897,24 @@ function extractTarGz(archivePath: string, targetDir: string, platform: string):
|
||||
}
|
||||
unlinkSync(archivePath);
|
||||
|
||||
const expectedName = platform === "windows" ? "hose-use.exe" : "hose-use";
|
||||
const files = spawnSync("find", [targetDir, "-type", "f"], { encoding: "utf8" })
|
||||
.stdout.trim()
|
||||
.split("\n")
|
||||
.filter(Boolean);
|
||||
|
||||
// Exact match for hose-use or hose-use.exe
|
||||
const expectedName = platform === "windows" ? "hose-use.exe" : "hose-use";
|
||||
const exact = files.find((f) => f.endsWith(`/${expectedName}`) || f.endsWith(expectedName));
|
||||
if (exact) return exact;
|
||||
return files[0] || archivePath;
|
||||
|
||||
// Next match for hose-use-darwin-arm64 etc., excluding hose-aipro
|
||||
const platformBinary = files.find((f) => {
|
||||
const base = f.split("/").pop() || "";
|
||||
return base.startsWith("hose-use-") && !base.endsWith(".cmd") && !base.endsWith(".json");
|
||||
});
|
||||
if (platformBinary) return platformBinary;
|
||||
|
||||
return files.find((f) => !f.endsWith("hose-aipro")) || files[0] || archivePath;
|
||||
}
|
||||
|
||||
function extractZip(archivePath: string, targetDir: string, platform: string): string {
|
||||
@@ -895,15 +924,22 @@ function extractZip(archivePath: string, targetDir: string, platform: string): s
|
||||
}
|
||||
unlinkSync(archivePath);
|
||||
|
||||
const expectedName = platform === "windows" ? "hose-use.exe" : "hose-use";
|
||||
const files = spawnSync("find", [targetDir, "-type", "f"], { encoding: "utf8" })
|
||||
.stdout.trim()
|
||||
.split("\n")
|
||||
.filter(Boolean);
|
||||
|
||||
const expectedName = platform === "windows" ? "hose-use.exe" : "hose-use";
|
||||
const exact = files.find((f) => f.endsWith(`/${expectedName}`) || f.endsWith(expectedName));
|
||||
if (exact) return exact;
|
||||
return files[0] || archivePath;
|
||||
|
||||
const platformBinary = files.find((f) => {
|
||||
const base = f.split("/").pop() || "";
|
||||
return base.startsWith("hose-use-") && !base.endsWith(".cmd") && !base.endsWith(".json");
|
||||
});
|
||||
if (platformBinary) return platformBinary;
|
||||
|
||||
return files.find((f) => !f.endsWith("hose-aipro")) || files[0] || archivePath;
|
||||
}
|
||||
|
||||
export function compareSemVer(v1: string, v2: string): number {
|
||||
|
||||
+466
-15
@@ -7,11 +7,16 @@ import { stringOption, numberOption, booleanOption } from "../parser.js";
|
||||
import { createClientsForCorp, createPiperClientForCorp } from "../helpers.js";
|
||||
import { printJson, printTable, printKeyValue } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { analyzeWorkflow } from "../../domains/platform/analysis.js";
|
||||
import {
|
||||
analyzeWorkflow,
|
||||
extractWorkflowSpecificationIds,
|
||||
type WorkflowFormSpecLike,
|
||||
} from "../../domains/platform/analysis.js";
|
||||
import { getFormSpecification } from "../../domains/bill/tools.js";
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { WorkflowDetailSchema } from "../../domains/platform/types.js";
|
||||
import { WorkflowDetailSchema, type WorkflowTaskExecution } from "../../domains/platform/types.js";
|
||||
import {
|
||||
createWorkflowDraft,
|
||||
beginWorkflowSave,
|
||||
@@ -24,6 +29,7 @@ import { WorkflowAlertStore } from "../../domains/platform/workflow-alert-store.
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
|
||||
|
||||
const WORKFLOW_STATE_DIR = process.env.HOSE_STATE_DIR || join(homedir(), ".config", "hose-use");
|
||||
const PLATFORM_ID_OPTION_KEYS = ["platform-id", "platformId", "app-id", "appId"];
|
||||
|
||||
export async function handleWorkflowCommand(
|
||||
parsed: CliParsedArgs,
|
||||
@@ -68,6 +74,9 @@ export async function handleWorkflowCommand(
|
||||
case "logs":
|
||||
case "log":
|
||||
return handleLogs(parsed, runtime);
|
||||
case "job":
|
||||
case "execution":
|
||||
return handleJob(parsed, runtime);
|
||||
case "check":
|
||||
case "health":
|
||||
return handleCheck(parsed, runtime);
|
||||
@@ -77,7 +86,7 @@ export async function handleWorkflowCommand(
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, history, logs, check\n`,
|
||||
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, history, logs, job, check\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
@@ -226,12 +235,12 @@ async function resolveWorkflowPlatformId(
|
||||
clients: Awaited<ReturnType<typeof createClientsForCorp>>,
|
||||
pipelineId: string
|
||||
): Promise<string> {
|
||||
const explicit = stringOption(parsed.options, ["platform-id", "platformId"]);
|
||||
const explicit = stringOption(parsed.options, PLATFORM_ID_OPTION_KEYS);
|
||||
if (explicit) return explicit;
|
||||
const all = await listAllWorkflows(clients, { page: 1, pageSize: 100 });
|
||||
const match = all.workflows.find((workflow) => workflow.id === pipelineId);
|
||||
if (!match?.platformId) {
|
||||
throw new Error(`无法确定工作流 [${pipelineId}] 所属自建应用,请使用 --platform-id=<platformId>`);
|
||||
throw new Error(`无法确定工作流 [${pipelineId}] 所属自建应用,请使用 --platform-id=<platformId> 或 --app-id=<appId>`);
|
||||
}
|
||||
return match.platformId;
|
||||
}
|
||||
@@ -239,15 +248,36 @@ async function resolveWorkflowPlatformId(
|
||||
async function handleAnalyze(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow analyze <pipelineId>\n", exitCode: 1 };
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const { client, clients } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const detail = await api.getWorkflowDetail(client, pipelineId);
|
||||
const result = analyzeWorkflow(detail);
|
||||
const specIds = extractWorkflowSpecificationIds(detail);
|
||||
const specifications: Record<string, WorkflowFormSpecLike | undefined> = {};
|
||||
if (specIds.length > 0) {
|
||||
const corpId = runtime.selectedCorp!.corpId || runtime.selectedCorp!.id;
|
||||
await Promise.all(
|
||||
specIds.map(async (specId) => {
|
||||
try {
|
||||
const spec = await getFormSpecification(clients.ekbClient, corpId, specId);
|
||||
if (spec) specifications[specId] = spec;
|
||||
} catch {
|
||||
// Ignore specification fetch failure in offline or restricted environments
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
const result = analyzeWorkflow(detail, { specifications });
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const diagnosticRows = result.diagnostics.map((item) => [item.severity, item.code, item.path, item.message]);
|
||||
const dependencyRows = result.dependencies.map((item) => [item.path, item.taskType, item.references.join(", ")]);
|
||||
return { stdout: [
|
||||
`====== 工作流静态分析 (${detail.label || detail.id}) ======`,
|
||||
printKeyValue({ "工作流 ID": detail.id, "根节点数": result.ast.length, "依赖节点数": result.dependencies.length, "诊断数": result.diagnostics.length }),
|
||||
printKeyValue({
|
||||
"工作流 ID": detail.id,
|
||||
"状态": detail.state === 1 ? "🟢 启用 (state=1)" : "⚪ 停用/草稿 (state=0)",
|
||||
"根节点数": result.ast.length,
|
||||
"依赖节点数": result.dependencies.length,
|
||||
"诊断数": result.diagnostics.length,
|
||||
}),
|
||||
`\n依赖引用:\n${dependencyRows.length ? printTable(["节点路径", "类型", "引用"], dependencyRows) : "暂无代码引用"}`,
|
||||
`\n诊断:\n${diagnosticRows.length ? printTable(["级别", "代码", "节点路径", "说明"], diagnosticRows) : "未发现明显配置问题"}`, "",
|
||||
].join("\n"), stderr: "", exitCode: 0 };
|
||||
@@ -277,17 +307,423 @@ async function handleHistory(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
||||
|
||||
async function handleLogs(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow logs <pipelineId> [--state=FAILED] [--start-time=YYYY-MM-DD] [--end-time=YYYY-MM-DD]\n", exitCode: 1 };
|
||||
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 };
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const result = await api.listWorkflowLogs(client, pipelineId, {
|
||||
const rawResult = await api.listWorkflowLogs(client, pipelineId, {
|
||||
state: stringOption(parsed.options, ["state"]),
|
||||
page: numberOption(parsed.options, ["page"]),
|
||||
pageSize: numberOption(parsed.options, ["page-size", "pageSize", "size"]),
|
||||
startTime: stringOption(parsed.options, ["start-time", "startTime"]),
|
||||
endTime: stringOption(parsed.options, ["end-time", "endTime"]),
|
||||
});
|
||||
const hasErrorFilter = booleanOption(parsed.options, ["has-error", "hasError", "errors"]);
|
||||
const filteredJobList = hasErrorFilter
|
||||
? rawResult.jobList.filter(
|
||||
(job) => job.hasError === true || job.errorTaskCount > 0 || job.state === "FAILED"
|
||||
)
|
||||
: rawResult.jobList;
|
||||
const result = hasErrorFilter
|
||||
? { ...rawResult, jobList: filteredJobList }
|
||||
: rawResult;
|
||||
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `====== 工作流运行日志 [${pipelineId}] ======\n${printKeyValue({ "执行次数": result.executeCount, "成功次数": result.successCount, "错误次数": result.errorCount, "日志条数": result.totalItems, "运行记录": result.jobList.length })}\n${printJson(result, runtime.outputOptions)}\n`, stderr: "", exitCode: 0 };
|
||||
|
||||
const rows = result.jobList.map((job, idx) => [
|
||||
idx + 1,
|
||||
job.id,
|
||||
job.state,
|
||||
job.successTaskCount,
|
||||
job.errorTaskCount,
|
||||
job.hasError || job.errorTaskCount > 0 ? "⚠️ 是 (true)" : "否 (false)",
|
||||
job.durationTime ?? "-",
|
||||
job.startTime || "-",
|
||||
]);
|
||||
const tableStr = rows.length
|
||||
? printTable(
|
||||
["#", "Job ID", "状态 (state)", "成功节点 (successTaskCount)", "失败节点 (errorTaskCount)", "有错误 (hasError)", "耗时(ms)", "开始时间"],
|
||||
rows
|
||||
)
|
||||
: "暂无匹配的运行记录";
|
||||
|
||||
return {
|
||||
stdout: [
|
||||
`====== 工作流运行日志 [${pipelineId}] ======`,
|
||||
printKeyValue({
|
||||
"执行次数": result.executeCount,
|
||||
"成功次数": result.successCount,
|
||||
"错误次数": result.errorCount,
|
||||
"日志条数": result.totalItems,
|
||||
"当前返回记录": result.jobList.length,
|
||||
}),
|
||||
"",
|
||||
tableStr,
|
||||
"\n提示: 运行 hose-use workflow job <jobId> [--failed] 下钻查看单次 Job 节点级报错与入参明细\n",
|
||||
].join("\n"),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
async function createJobPiperClient(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<Awaited<ReturnType<typeof createPiperClientForCorp>>> {
|
||||
const corp = runtime.selectedCorp!;
|
||||
const explicit = stringOption(parsed.options, PLATFORM_ID_OPTION_KEYS);
|
||||
if (explicit) {
|
||||
return createPiperClientForCorp(corp, explicit);
|
||||
}
|
||||
const clients = await createClientsForCorp(corp);
|
||||
try {
|
||||
const corpId = corp.corpId || corp.id;
|
||||
const platforms = await api.listPlatforms(clients.ekbClient, corpId);
|
||||
const firstActive = platforms.find((p) => p.active) ?? platforms[0];
|
||||
if (firstActive?.id) {
|
||||
return await createPiperClientForCorp(corp, firstActive.id);
|
||||
}
|
||||
} catch {
|
||||
// Fall back to default easoClient
|
||||
}
|
||||
return clients.easoClient;
|
||||
}
|
||||
|
||||
async function enrichFailedExecutions(
|
||||
client: Awaited<ReturnType<typeof createPiperClientForCorp>>,
|
||||
jobId: string,
|
||||
items: WorkflowTaskExecution[]
|
||||
): Promise<WorkflowTaskExecution[]> {
|
||||
const parentCache = new Map<string, WorkflowTaskExecution[]>();
|
||||
const enriched: WorkflowTaskExecution[] = [];
|
||||
|
||||
for (const item of items) {
|
||||
if (item.parentId && (!item.currentLoopPath || !item.name || !item.form)) {
|
||||
let siblings = parentCache.get(item.parentId);
|
||||
if (!siblings) {
|
||||
try {
|
||||
const level = await api.getJobExecutionLevel(client, jobId, {
|
||||
parentId: item.parentId,
|
||||
page: 1,
|
||||
pageSize: 100,
|
||||
});
|
||||
siblings = level.items;
|
||||
} catch {
|
||||
siblings = [];
|
||||
}
|
||||
parentCache.set(item.parentId, siblings);
|
||||
}
|
||||
const matched = siblings.find((s) => s.id === item.id);
|
||||
if (matched) {
|
||||
const itemInputs = item.inputs;
|
||||
const matchedInputs = matched.inputs;
|
||||
const hasItemInputs = Array.isArray(itemInputs)
|
||||
? itemInputs.length > 0
|
||||
: Boolean(itemInputs && typeof itemInputs === "object" && Object.keys(itemInputs as Record<string, unknown>).length > 0);
|
||||
const itemOutputs = item.outputs;
|
||||
const matchedOutputs = matched.outputs;
|
||||
const hasItemOutputs = Boolean(
|
||||
itemOutputs && typeof itemOutputs === "object" && Object.keys(itemOutputs as Record<string, unknown>).length > 0
|
||||
);
|
||||
enriched.push({
|
||||
...matched,
|
||||
...item,
|
||||
name: item.name || matched.name,
|
||||
label: item.label || matched.label,
|
||||
displayName: item.displayName || matched.displayName,
|
||||
type: item.type || matched.type,
|
||||
status: item.status || matched.status,
|
||||
currentLoopPath: item.currentLoopPath || matched.currentLoopPath,
|
||||
levelIndex: item.levelIndex?.length ? item.levelIndex : matched.levelIndex,
|
||||
form: item.form ?? matched.form,
|
||||
details: item.details ?? matched.details,
|
||||
inputs: hasItemInputs ? itemInputs : matchedInputs,
|
||||
outputs: hasItemOutputs ? itemOutputs : matchedOutputs,
|
||||
error: item.error ?? matched.error,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
}
|
||||
enriched.push(item);
|
||||
}
|
||||
return enriched;
|
||||
}
|
||||
|
||||
async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const jobId = parsed.args[0] || stringOption(parsed.options, ["id", "job-id", "jobId"]);
|
||||
if (!jobId) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use workflow job <jobId> [--failed] [--parent=<executionId>] [--logs=<executionId>]\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const client = await createJobPiperClient(parsed, runtime);
|
||||
const page = numberOption(parsed.options, ["page"]) || 1;
|
||||
const pageSize = numberOption(parsed.options, ["page-size", "pageSize", "size"]) || 100;
|
||||
const logsExecutionId = stringOption(parsed.options, ["logs", "log", "execution-logs"]);
|
||||
const parentExecutionId = stringOption(parsed.options, ["parent", "parent-id", "parentId"]);
|
||||
const onlyFailed = booleanOption(parsed.options, ["failed", "fail", "errors"]);
|
||||
|
||||
// 1. --logs=<executionId>
|
||||
if (logsExecutionId) {
|
||||
const logs = await api.getExecutionLogs(client, logsExecutionId);
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ jobId, executionId: logsExecutionId, logs }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
const rows = logs.map((log, i) => [
|
||||
i + 1,
|
||||
String(log.id ?? "-"),
|
||||
String(log.createAt ?? (log as Record<string, unknown>).createTime ?? (log as Record<string, unknown>).timestamp ?? "-"),
|
||||
String(log.level || "INFO"),
|
||||
String(log.message || JSON.stringify(log)),
|
||||
]);
|
||||
return {
|
||||
stdout: [
|
||||
`====== 节点执行日志 (Job: ${jobId} | Execution: ${logsExecutionId}) ======`,
|
||||
rows.length ? printTable(["#", "日志 ID", "时间", "级别", "内容"], rows) : "该节点暂无输出日志",
|
||||
"",
|
||||
].join("\n"),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 2. --parent=<executionId>
|
||||
if (parentExecutionId) {
|
||||
const levelPage = await api.getJobExecutionLevel(client, jobId, {
|
||||
parentId: parentExecutionId,
|
||||
page,
|
||||
pageSize,
|
||||
});
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
jobId,
|
||||
parentId: parentExecutionId,
|
||||
...levelPage,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = levelPage.items.map((item, idx) => [
|
||||
idx + 1,
|
||||
item.id,
|
||||
item.name || "-",
|
||||
item.label || item.displayName || "-",
|
||||
item.type || "-",
|
||||
item.status || "-",
|
||||
item.currentLoopPath || "-",
|
||||
item.error?.message || "-",
|
||||
]);
|
||||
const extraDetails: string[] = [];
|
||||
for (const item of levelPage.items) {
|
||||
if (item.form !== undefined || item.error?.message) {
|
||||
extraDetails.push(
|
||||
`\n── 节点明细 [${item.id}] (${item.name || "-"} | loop=${item.currentLoopPath || "-"} | status=${item.status}) ──`
|
||||
);
|
||||
if (item.error?.message) {
|
||||
extraDetails.push(` 错误原因: ${item.error.message}`);
|
||||
}
|
||||
if (item.form !== undefined) {
|
||||
extraDetails.push(` 传入表单 (form): ${JSON.stringify(item.form)}`);
|
||||
}
|
||||
if (item.details !== undefined) {
|
||||
extraDetails.push(` 明细数据 (details): ${JSON.stringify(item.details)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: [
|
||||
`====== 子节点执行层级明细 (Job: ${jobId} | Parent: ${parentExecutionId} | 共 ${levelPage.totalItems} 项) ======`,
|
||||
rows.length
|
||||
? printTable(
|
||||
["#", "Execution ID", "节点标识 (name)", "节点名称", "类型 (type)", "状态 (status)", "循环路径 (currentLoopPath)", "错误原因"],
|
||||
rows
|
||||
)
|
||||
: "暂无子节点执行记录",
|
||||
...extraDetails,
|
||||
"",
|
||||
].join("\n"),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 3. --failed
|
||||
if (onlyFailed) {
|
||||
const [job, failedPage] = await Promise.all([
|
||||
api.getJob(client, jobId).catch(() => undefined),
|
||||
api.getJobFailedExecutions(client, jobId),
|
||||
]);
|
||||
const enrichedItems = await enrichFailedExecutions(client, jobId, failedPage.items);
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
jobId,
|
||||
job: job ?? null,
|
||||
totalItems: failedPage.totalItems,
|
||||
items: enrichedItems,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = enrichedItems.map((item, idx) => [
|
||||
idx + 1,
|
||||
item.id,
|
||||
item.parentId || "-",
|
||||
item.name || "-",
|
||||
item.type || "-",
|
||||
item.status || "-",
|
||||
item.currentLoopPath || "-",
|
||||
item.error?.message || "-",
|
||||
]);
|
||||
const formSummaries: string[] = [];
|
||||
for (const item of enrichedItems) {
|
||||
if (item.error?.message || item.form !== undefined) {
|
||||
formSummaries.push(
|
||||
`\n── ⚠️ 异常节点 [${item.id}] (${item.name || "-"} | status=${item.status} | loop=${item.currentLoopPath || "-"}) ──`
|
||||
);
|
||||
if (item.error?.message) {
|
||||
formSummaries.push(` 错误详情: ${item.error.message}`);
|
||||
}
|
||||
if (item.form !== undefined) {
|
||||
formSummaries.push(` 表单入参 (form): ${JSON.stringify(item.form)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: [
|
||||
`====== Job 异常/跳过执行节点明细 (Job: ${jobId}) ======`,
|
||||
job
|
||||
? printKeyValue({
|
||||
"Job ID": job.id,
|
||||
"工作流 ID": job.pipelineId,
|
||||
"Job 状态": job.state ?? job.status,
|
||||
"开始时间": job.startTime || "-",
|
||||
"耗时(ms)": String(job.durationTime ?? "-"),
|
||||
})
|
||||
: "",
|
||||
"",
|
||||
rows.length
|
||||
? printTable(
|
||||
["#", "Execution ID", "Parent ID", "节点标识 (name)", "类型 (type)", "状态 (status)", "循环路径 (currentLoopPath)", "错误原因 (error.message)"],
|
||||
rows
|
||||
)
|
||||
: "未发现异常或报错跳过的执行节点",
|
||||
...formSummaries,
|
||||
"",
|
||||
].filter(Boolean).join("\n"),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 4. Default mode: Job overview + top-level tree + failed executions
|
||||
const [job, tree, failedPage] = await Promise.all([
|
||||
api.getJob(client, jobId),
|
||||
api.getJobExecutionTree(client, jobId),
|
||||
api.getJobFailedExecutions(client, jobId).catch(() => ({
|
||||
number: 1,
|
||||
size: 100,
|
||||
totalPages: 0,
|
||||
totalItems: 0,
|
||||
items: [] as WorkflowTaskExecution[],
|
||||
})),
|
||||
]);
|
||||
const failedExecutions = await enrichFailedExecutions(client, jobId, failedPage.items);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
jobId,
|
||||
job,
|
||||
executionTree: tree,
|
||||
failedExecutions,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const treeRows = tree.map((node, idx) => [
|
||||
idx + 1,
|
||||
node.id,
|
||||
node.name || "-",
|
||||
node.label || node.displayName || "-",
|
||||
node.type || "-",
|
||||
node.status || "-",
|
||||
String((node as Record<string, unknown>).durationTime ?? node.executionTime ?? "-"),
|
||||
node.error?.message || "-",
|
||||
]);
|
||||
|
||||
const failedRows = failedExecutions.map((item, idx) => [
|
||||
idx + 1,
|
||||
item.id,
|
||||
item.parentId || "-",
|
||||
item.name || "-",
|
||||
item.type || "-",
|
||||
item.status || "-",
|
||||
item.currentLoopPath || "-",
|
||||
item.error?.message || "-",
|
||||
]);
|
||||
|
||||
const outLines = [
|
||||
`====== 工作流 Job 执行详情 [${job.id}] ======`,
|
||||
printKeyValue({
|
||||
"Job ID": job.id,
|
||||
"工作流 ID (pipelineId)": job.pipelineId,
|
||||
"Job 状态 (state)": job.state ?? job.status,
|
||||
"开始时间": job.startTime || "-",
|
||||
"结束时间": job.endTime || "-",
|
||||
"耗时(ms)": String(job.durationTime ?? "-"),
|
||||
"顶层节点数": tree.length,
|
||||
"异常/跳过节点数": failedExecutions.length,
|
||||
}),
|
||||
"",
|
||||
"── 顶层节点执行树 ──",
|
||||
treeRows.length
|
||||
? printTable(
|
||||
["#", "Execution ID", "节点标识 (name)", "节点名称", "类型 (type)", "状态 (status)", "耗时(ms)", "错误信息"],
|
||||
treeRows
|
||||
)
|
||||
: "暂无顶层节点执行记录",
|
||||
];
|
||||
|
||||
if (failedRows.length > 0) {
|
||||
outLines.push("");
|
||||
outLines.push("── ⚠️ 失败/报错跳过节点明细 (含循环子项) ──");
|
||||
outLines.push(
|
||||
printTable(
|
||||
["#", "Execution ID", "Parent ID", "节点标识 (name)", "类型 (type)", "状态 (status)", "循环路径 (currentLoopPath)", "错误原因 (error.message)"],
|
||||
failedRows
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `${outLines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleCheck(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
@@ -349,8 +785,17 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const page = numberOption(parsed.options, ["page"]) || 1;
|
||||
const pageSize = numberOption(parsed.options, ["pageSize", "size"]) || 50;
|
||||
const filterPlatformId = stringOption(parsed.options, PLATFORM_ID_OPTION_KEYS);
|
||||
|
||||
const result = await listAllWorkflows(clients, { page, pageSize });
|
||||
const rawResult = await listAllWorkflows(clients, { page, pageSize });
|
||||
const workflows = filterPlatformId
|
||||
? rawResult.workflows.filter(
|
||||
(wf) => wf.platformId === filterPlatformId || wf.platformName === filterPlatformId
|
||||
)
|
||||
: rawResult.workflows;
|
||||
const result = filterPlatformId
|
||||
? { ...rawResult, workflows, totalWorkflows: workflows.length }
|
||||
: rawResult;
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
@@ -429,15 +874,21 @@ async function createWorkflowDetailClient(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime,
|
||||
pipelineId: string,
|
||||
): Promise<{ client: Awaited<ReturnType<typeof createPiperClientForCorp>> }> {
|
||||
): Promise<{
|
||||
client: Awaited<ReturnType<typeof createPiperClientForCorp>>;
|
||||
clients: Awaited<ReturnType<typeof createClientsForCorp>>;
|
||||
}> {
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const explicit = stringOption(parsed.options, ["platform-id", "platformId"]);
|
||||
const explicit = stringOption(parsed.options, PLATFORM_ID_OPTION_KEYS);
|
||||
let platformId = explicit;
|
||||
if (!platformId) {
|
||||
const all = await listAllWorkflows(clients, { page: 1, pageSize: 100 });
|
||||
platformId = all.workflows.find((workflow) => workflow.id === pipelineId)?.platformId;
|
||||
}
|
||||
return { client: platformId ? await createPiperClientForCorp(runtime.selectedCorp!, platformId) : clients.easoClient };
|
||||
return {
|
||||
client: platformId ? await createPiperClientForCorp(runtime.selectedCorp!, platformId) : clients.easoClient,
|
||||
clients,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleFind(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
|
||||
+36
-7
@@ -7,13 +7,42 @@ export interface HelpTopic {
|
||||
|
||||
export const HELP_REGISTRY: Record<string, HelpTopic> = {
|
||||
context: { summary: "全局运行上下文与身份诊断", usage: "hose-use context [--json]", commands: { context: "输出当前企业、账号、运行模式与认证状态" } },
|
||||
auth: { summary: "认证与凭证管理", usage: "hose-use auth <子命令>", commands: { login: "登录并保存企业凭证", status: "查看当前认证状态", accounts: "列出已保存账号", "switch-account": "切换默认账号" } },
|
||||
corps: { summary: "多企业租户管理", usage: "hose-use corps <子命令>", commands: { list: "列出本地企业配置", search: "搜索企业与员工", switch: "切换当前工作企业", current: "查看当前企业", "add-link": "从链接导入企业凭证" } },
|
||||
auth: {
|
||||
summary: "认证与凭证管理(支持主账号登录与企业级 OpenAPI 持久化)",
|
||||
usage: "hose-use auth <子命令>",
|
||||
commands: {
|
||||
login: "登录并保存企业凭证",
|
||||
status: "查看当前认证状态",
|
||||
refresh: "刷新账号或企业 AccessToken",
|
||||
link: "生成企业 Web 免密登录直达链接 (别名: hose-link)",
|
||||
"add-link": "从协助链接导入企业凭证(自动探测并持久化 OpenAPI 密钥)",
|
||||
"add-persistent": "通过 OpenAPI 密钥 (appKey + appSecurity) 持久化接入企业",
|
||||
"extract-keys": "从协助链接提取 OpenAPI 密钥",
|
||||
elevate: "为已配置企业提取并持久化保存 OpenAPI 密钥",
|
||||
accounts: "列出已保存账号",
|
||||
"switch-account": "切换默认账号",
|
||||
},
|
||||
},
|
||||
corps: {
|
||||
summary: "多企业租户管理",
|
||||
usage: "hose-use corps <子命令>",
|
||||
commands: {
|
||||
list: "列出本地企业配置",
|
||||
search: "搜索企业与员工",
|
||||
switch: "切换当前工作企业",
|
||||
current: "查看当前企业",
|
||||
link: "生成企业 Web 免密登录直达链接 (别名: hose-link)",
|
||||
"add-link": "从链接导入企业凭证(自动探测并持久化 OpenAPI 密钥)",
|
||||
"add-persistent": "通过 OpenAPI 密钥持久化接入企业",
|
||||
"extract-keys": "从协助链接提取 OpenAPI 密钥",
|
||||
elevate: "为已配置企业提取并持久化保存 OpenAPI 密钥",
|
||||
},
|
||||
},
|
||||
config: { summary: "全局运行模式与路径配置", usage: "hose-use config <子命令>", commands: { paths: "诊断配置目录链", get: "查看全局配置", mode: "切换 stateful/stateless", set: "更新指定配置项" } },
|
||||
workflow: { summary: "工作流查询、草稿与生命周期管理", usage: "hose-use workflow <子命令> [参数] [选项]", commands: { list: "列出工作流", get: "查看工作流详情", find: "按节点类型搜索", analyze: "静态分析工作流", patch: "生成草稿字段补丁", save: "保存草稿到远端", toggle: "切换启停状态", publish: "发布并启用工作流", history: "查看版本历史", logs: "查看运行日志", check: "检查错误管道" }, options: ["--dry-run 只预览写操作", "--yes/--confirm 确认写操作", "--file=<workflow.json> 指定工作流快照"] },
|
||||
bill: { summary: "单据检索与审批动作", usage: "hose-use bill <子命令> [单号|ID] [选项]", commands: { list: "查询单据", get: "查看单据详情", flow: "查看审批流程", approve: "同意审批", reject: "驳回审批", transfer: "转交审批", "add-node": "加签审批", comment: "添加评论" }, options: ["--dry-run 只预览审批动作", "--yes/--confirm 确认执行审批动作", "--comment=<原因> 驳回或评论内容"] },
|
||||
platform: { summary: "自建应用、业务对象与底层记录", usage: "hose-use platform <子命令> [参数]", commands: { list: "列出自建应用", entities: "列出业务对象", schema: "查看字段定义", records: "查询记录", record: "查看或修改单条记录", permissions: "查看权限", imports: "查看导入任务" }, options: ["--dry-run 只预览记录写操作", "--yes/--confirm 确认记录写操作"] },
|
||||
feetype: { summary: "费用类型全生命周期管理", usage: "hose-use feetype <子命令> [参数]", commands: { list: "查看费用类型树", get: "查看详情与字段", create: "新建费用类型", update: "修改属性", disable: "停用", enable: "启用", move: "移动层级", fields: "查看字段配置" }, options: ["--dry-run 只预览写操作", "--yes/--confirm 确认写操作"] },
|
||||
workflow: { summary: "工作流查询、草稿、运行排障与生命周期管理", usage: "hose-use workflow <子命令> [参数] [选项]", commands: { list: "列出工作流", get: "查看工作流详情", find: "按节点类型搜索", analyze: "静态分析工作流(含禁用/SKIP/联动覆盖检查)", job: "查看单次运行实例树、报错节点与MVEL日志", patch: "生成草稿字段补丁", save: "保存草稿到远端", toggle: "切换启停状态", publish: "发布并启用工作流", history: "查看版本历史", logs: "查看运行日志", check: "检查错误管道" }, options: ["--dry-run 只预览写操作", "--yes/--confirm 确认写操作", "--file=<workflow.json> 指定工作流快照", "--failed 只看失败节点", "--parent=<executionId> 展开循环/分支子节点", "--logs=<executionId> 查看节点执行日志"] },
|
||||
bill: { summary: "单据检索、表单规格诊断与审批动作", usage: "hose-use bill <子命令> [单号|ID] [选项]", commands: { list: "查询单据", get: "查看单据详情", spec: "查看单据模板字段配置与联动覆盖规则", flow: "查看审批流程", approve: "同意审批", reject: "驳回审批", transfer: "转交审批", "add-node": "加签审批", comment: "添加评论" }, options: ["--dry-run 只预览审批动作", "--yes/--confirm 确认执行审批动作", "--comment=<原因> 驳回或评论内容"] },
|
||||
platform: { summary: "自建应用、业务对象、全量记录安全更新与台账体检", usage: "hose-use platform <子命令> [参数]", commands: { list: "列出自建应用", entities: "列出业务对象", schema: "查看字段定义", records: "查询记录(支持 --all 全量拉取)", record: "查看或安全修改单条/批量记录 (get/create/edit/batch-edit)", audit: "业务对象健康度巡检(必填缺失/禁用引用/跨表同步差异)", permissions: "查看权限", imports: "查看导入任务" }, options: ["--all 自动翻页拉取全量记录", "--dry-run 只预览记录写操作", "--yes/--confirm 确认记录写操作", "--raw 跳过安全合并直接发送原始补丁"] },
|
||||
feetype: { summary: "费用类型全生命周期管理与模板规格查询", usage: "hose-use feetype <子命令> [参数]", commands: { list: "查看费用类型树", get: "查看详情与字段", spec: "查看单据/申请模板字段与联动规则", create: "新建费用类型", update: "修改属性", disable: "停用", enable: "启用", move: "移动层级", fields: "查看字段配置" }, options: ["--dry-run 只预览写操作", "--yes/--confirm 确认写操作"] },
|
||||
rule: { summary: "本地审批规约管理", usage: "hose-use rule <子命令> [参数]", commands: { scopes: "列出适用场景", scope: "查看场景明细", list: "列出规则", get: "查看规则详情", add: "新增规则", delete: "删除规则" }, options: ["--dry-run 只预览增删", "--yes/--confirm 确认增删"] },
|
||||
approval: { summary: "确定性审批网关与要点仲裁", usage: "hose-use approval audit <子命令> [单号]", commands: { points: "查看审核要点", checklist: "查看核验清单", review: "核验事实", decide: "生成或执行仲裁决定" }, options: ["--apply --yes 执行真实审批流转"] },
|
||||
message: { summary: "消息中心与通知管理", usage: "hose-use message <子命令>", commands: { list: "查询消息", count: "查看未读数", read: "标记消息已读", "read-all": "全部标记已读" } },
|
||||
@@ -25,7 +54,7 @@ export const HELP_REGISTRY: Record<string, HelpTopic> = {
|
||||
app: { summary: "桌面端工作台应用管理", usage: "hose-use app <子命令>", commands: { list: "列出应用", get: "查看应用详情" } },
|
||||
menu: { summary: "桌面端主导航菜单树", usage: "hose-use menu list", commands: { list: "查看主导航", apps: "查看应用入口" } },
|
||||
openapi: { summary: "OpenAPI 规范导出与路径查询", usage: "hose-use openapi [paths|info|--raw|keys]", commands: { paths: "列出路径概要", info: "查看规范元数据", keys: "查看企业接入密钥" } },
|
||||
keys: { summary: "企业 OpenAPI 接入凭证", usage: "hose-use keys [--json] [--reveal]", commands: { keys: "读取当前企业密钥(默认脱敏)" }, options: ["--reveal 仅在明确授权后查看明文"] },
|
||||
keys: { summary: "企业 OpenAPI 接入凭证", usage: "hose-use keys [--json] [--reveal] [--save]", commands: { keys: "读取当前企业密钥(默认脱敏)" }, options: ["--reveal 仅在明确授权后查看明文", "--save --yes 提取并持久化保存到本地企业配置"] },
|
||||
store: { summary: "已购应用与应用商店探查", usage: "hose-use store <list|search|get>", commands: { list: "列出已购应用", search: "搜索应用商店", get: "查看应用详情" } },
|
||||
update: { summary: "版本自更新与发布记录", usage: "hose-use update [check|--changelog]", commands: { update: "检查并升级版本", check: "只检查可用版本", changelog: "查看发布记录" } },
|
||||
skill: { summary: "Agent Skill 管理", usage: "hose-use skill <install|status|dump>", commands: { install: "安装内嵌 Skill", status: "查看安装状态", dump: "导出 Skill 文件" } },
|
||||
|
||||
+13
-2
@@ -4,6 +4,7 @@ import { CorpContext, resolveCorpConfig } from "../core/config/manager.js";
|
||||
import { CorpConfig } from "../core/config/types.js";
|
||||
import {
|
||||
createSessionClient,
|
||||
getEasoClient,
|
||||
getUnityClient,
|
||||
getScriptEngineClient,
|
||||
} from "../core/http/index.js";
|
||||
@@ -63,13 +64,23 @@ export function initCorpRuntime(
|
||||
|
||||
export async function createClientsForCorp(corp: CorpConfig) {
|
||||
const sessionClient = await createSessionClient(corp);
|
||||
const { client: unityClient } = await getUnityClient(corp);
|
||||
let easoClient: Awaited<ReturnType<typeof getEasoClient>>["client"];
|
||||
let unityClient: Awaited<ReturnType<typeof getUnityClient>>["client"];
|
||||
try {
|
||||
const easo = await getEasoClient(corp);
|
||||
easoClient = easo.client;
|
||||
unityClient = easo.client;
|
||||
} catch {
|
||||
const unity = await getUnityClient(corp);
|
||||
unityClient = unity.client;
|
||||
easoClient = unity.client;
|
||||
}
|
||||
return {
|
||||
corp,
|
||||
sessionClient,
|
||||
ekbClient: sessionClient,
|
||||
unityClient,
|
||||
easoClient: unityClient,
|
||||
easoClient,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+21
-15
@@ -41,40 +41,46 @@ export function printJson(data: unknown, options: OutputOptions = {}): string {
|
||||
return json;
|
||||
}
|
||||
|
||||
export function formatSourceLabel(source?: string): string {
|
||||
export function formatSourceLabel(source?: string, persistentOpenApi?: boolean): string {
|
||||
const suffix = persistentOpenApi && source !== "openapi" ? " + OpenAPI 持久化密钥" : "";
|
||||
switch (source) {
|
||||
case "openapi":
|
||||
return "开放平台持久化密钥 (OpenAPI AppKey)";
|
||||
case "assist":
|
||||
return "官方协助/代客平台 (Assist Platform)";
|
||||
return `官方协助/代客平台 (Assist Platform)${suffix}`;
|
||||
case "account":
|
||||
return "统一认证中心 (IDP 账密/短信)";
|
||||
return `统一认证中心 (IDP 账密/短信)${suffix}`;
|
||||
case "browser":
|
||||
return "浏览器会话同步 (WebBridge)";
|
||||
return `浏览器会话同步 (WebBridge)${suffix}`;
|
||||
case "link":
|
||||
return "协助/免密链接导入 (Assistance Link)";
|
||||
return `协助/免密链接导入 (Assistance Link)${suffix}`;
|
||||
case "curl":
|
||||
case "f12":
|
||||
return "cURL 抓包导入 (cURL/F12)";
|
||||
return `cURL 抓包导入 (cURL/F12)${suffix}`;
|
||||
case "manual":
|
||||
return "手动配置";
|
||||
return `手动配置${suffix}`;
|
||||
default:
|
||||
return source || "未知来源";
|
||||
return (source || "未知来源") + suffix;
|
||||
}
|
||||
}
|
||||
|
||||
export function formatExpiresAt(expiresAt?: number | null): string {
|
||||
export function formatExpiresAt(expiresAt?: number | null, persistent?: boolean): string {
|
||||
if (!expiresAt || expiresAt <= 0) return "长期有效 / 服务端未显式限制";
|
||||
const diffMs = expiresAt - Date.now();
|
||||
const dateStr = new Date(expiresAt).toLocaleString("zh-CN", { hour12: false });
|
||||
if (diffMs <= 0) {
|
||||
if (persistent) {
|
||||
return `${dateStr} (🔄 持久化密钥自动续期)`;
|
||||
}
|
||||
return `${dateStr} (⚠️ 已过期)`;
|
||||
}
|
||||
const diffMins = Math.floor(diffMs / 60000);
|
||||
if (diffMins < 60) {
|
||||
return `${dateStr} (约剩余 ${diffMins} 分钟)`;
|
||||
return `${dateStr} (约剩余 ${diffMins} 分钟${persistent ? ",支持自动续期" : ""})`;
|
||||
}
|
||||
const diffHours = (diffMs / 3600000).toFixed(1);
|
||||
if (Number(diffHours) < 24) {
|
||||
return `${dateStr} (约剩余 ${diffHours} 小时)`;
|
||||
return `${dateStr} (约剩余 ${diffHours} 小时${persistent ? ",支持自动续期" : ""})`;
|
||||
}
|
||||
const diffDays = Math.floor(diffMs / 86400000);
|
||||
return `${dateStr} (约剩余 ${diffDays} 天)`;
|
||||
@@ -126,17 +132,17 @@ export function printHelp(target: string[] = []): string {
|
||||
corps 多企业租户管理 (list, search <关键词>, switch, current, add-link)
|
||||
aipro 合思 AI PRO 确定性审批仲裁网关入口 (status, scopes, bind, checklist, review, decide, logs)
|
||||
config 全局运行模式与路径诊断 (show, paths, mode <stateful|stateless>, set)
|
||||
workflow 工作流管理 (list, get, find, analyze, toggle, publish, patch, save, history, logs, check)
|
||||
bill 单据检索与审批动作 (list, get <单号|ID> [--risk], approve|reject|transfer|add-node|comment <单号|ID> [选项], refs, relations, attachments, download, flow, risk, budget, schema, link)
|
||||
workflow 工作流管理 (list, get, find, analyze, job, toggle, publish, patch, save, history, logs, check)
|
||||
bill 单据检索、模板规格与审批动作 (list, get <单号|ID> [--risk], spec <模板ID>, approve|reject|transfer|add-node|comment <单号|ID> [选项], refs, relations, attachments, download, flow, risk, budget, schema, link)
|
||||
contact 企业通讯录与人员检索 (list, search <关键词>, get <staffId>)
|
||||
task 待办中心与审批任务 (todo, approved, records, submitted, cc)
|
||||
message 消息中心与通知管理 (list, count, read, read-all)
|
||||
app 应用管理 (桌面端工作台业务应用: list [--keyword], get <应用ID|名称>)
|
||||
menu 桌面端主导航菜单树与模块 (list, tree, apps)
|
||||
platform 自建应用与数据模型 (开放平台业务对象、字段与底层记录: list, get, entities, schema, records, permissions, imports)
|
||||
platform 自建应用与数据模型 (list, get, entities, schema, records [--all], record get|create|edit|batch-edit, audit, permissions, imports)
|
||||
datalink platform 的同义入口,面向 DataLink 业务对象查询
|
||||
dimension 系统/自定义档案维度 (list, items <维度>)
|
||||
feetype 费用类型管理与字段规格配置 (list, get, create, update, disable, enable, move, fields)
|
||||
feetype 费用类型管理与字段规格配置 (list, get, spec <模板ID>, create, update, disable, enable, move, fields)
|
||||
role 角色定义与成员 (list, groups, members <角色>)
|
||||
permission 权限模型快照 (get)
|
||||
rule 本地 AI 审批规约管理 (scopes, scope <索引号|场景>, list, get, add, delete)
|
||||
|
||||
+5
-1
@@ -82,10 +82,14 @@ async function runCliOnce(
|
||||
const result = await dispatchCli(rawArgs, options);
|
||||
const extraStdout = stdoutChunks.length ? `${stdoutChunks.join("\n")}\n` : "";
|
||||
const extraStderr = stderrChunks.length ? `${stderrChunks.join("\n")}\n` : "";
|
||||
const bodyStdout = result.preserveSensitiveStdout
|
||||
? result.stdout || ""
|
||||
: redactSensitiveText(result.stdout || "");
|
||||
return {
|
||||
stdout: redactSensitiveText(extraStdout + (result.stdout || "")),
|
||||
stdout: redactSensitiveText(extraStdout) + bodyStdout,
|
||||
stderr: redactSensitiveText(extraStderr + (result.stderr || "")),
|
||||
exitCode: result.exitCode,
|
||||
preserveSensitiveStdout: result.preserveSensitiveStdout,
|
||||
};
|
||||
} finally {
|
||||
console.log = originalLog;
|
||||
|
||||
@@ -22,6 +22,7 @@ export interface CliResult {
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
exitCode: number;
|
||||
preserveSensitiveStdout?: boolean;
|
||||
}
|
||||
|
||||
export interface OutputOptions {
|
||||
|
||||
@@ -6,18 +6,18 @@ Core 层负责基础设施:企业配置管理、认证 Token 获取与缓存
|
||||
|
||||
```text
|
||||
src/core/
|
||||
├── auth/ # 登录认证协议与凭证存储(纯凭据层)
|
||||
│ ├── login.ts # 登录四矩阵(RSA账密登录、短信验证码、F12/cURL凭证导入、浏览器同步)
|
||||
│ ├── account-store.ts # 多账号持久化存储 (~/.cache/ekb-mcp/accounts.json)
|
||||
├── auth/ # 登录认证协议与凭证存储(纯凭据层:用户级主账号 + 企业级 OpenAPI 持久化双通道)
|
||||
│ ├── login.ts # 登录与换票矩阵(RSA账密、短信、F12/协助链接导入、浏览器同步、OpenAPI 密钥持久化与 getProvisionalAuth 续期)
|
||||
│ ├── account-store.ts # 多账号持久化存储 (~/.config/hose-use/accounts.json)
|
||||
│ ├── tools.ts # MCP Auth Tools 注册与调度
|
||||
│ ├── token-store.ts # 动态 Token 缓存(兼容 ~/.config/hose-use/tokens.json 与历史路径)
|
||||
│ ├── token-store.ts # 动态 Token 缓存 (~/.config/hose-use/tokens.json)
|
||||
│ └── types.ts
|
||||
├── http/ # 统一 HTTP 客户端装配与网络传输(语义化客户端)
|
||||
│ ├── factory.ts # Ky 底层客户端工厂(超时、重试、错误钩子)
|
||||
│ ├── fingerprint.ts # 统一浏览器指纹、User-Agent、Cookie 与 WAF 策略头
|
||||
│ ├── session-client.ts # 闭合用户会话客户端(三 Header + 指纹 + 401 续杯)
|
||||
│ ├── session-client.ts # 闭合用户会话客户端(三 Header + 指纹 + 账号/OpenAPI 双通道自动续杯)
|
||||
│ ├── openapi-client.ts # 开放平台应用客户端(appKey 换票与签名机制)
|
||||
│ ├── unity-client.ts # 应用中心与动态集群寻址客户端
|
||||
│ ├── unity-client.ts # 应用中心与动态集群寻址客户端(支持账号/OpenAPI 双通道预续期)
|
||||
│ ├── script-engine-client.ts # 工作流 MVEL/Python 脚本调试引擎客户端
|
||||
│ └── index.ts # 统一导出入口
|
||||
├── cache/ # 统一多级协同缓存
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { readFileSync, writeFileSync, mkdirSync } from "fs";
|
||||
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
|
||||
import { join, dirname } from "path";
|
||||
import { homedir } from "os";
|
||||
import { z } from "zod";
|
||||
|
||||
const ACCOUNT_CACHE_PATH = join(
|
||||
export const ACCOUNT_CACHE_PATH = join(
|
||||
homedir(),
|
||||
".cache",
|
||||
"ekb-mcp",
|
||||
".config",
|
||||
"hose-use",
|
||||
"accounts.json"
|
||||
);
|
||||
|
||||
@@ -38,7 +38,13 @@ export type AccountEntry = z.infer<typeof AccountEntrySchema>;
|
||||
export type AccountStore = z.infer<typeof AccountStoreSchema>;
|
||||
|
||||
function ensureDir(path: string): void {
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
const dir = dirname(path);
|
||||
if (!existsSync(dir)) {
|
||||
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
||||
}
|
||||
try {
|
||||
chmodSync(dir, 0o700);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
export function loadAccountStore(): AccountStore {
|
||||
|
||||
+1362
-37
File diff suppressed because it is too large.
Load diff
@@ -10,20 +10,9 @@ export const PRIMARY_TOKEN_CACHE_PATH = join(
|
||||
"tokens.json"
|
||||
);
|
||||
|
||||
export const LEGACY_TOKEN_CACHE_PATH = join(
|
||||
homedir(),
|
||||
".cache",
|
||||
"ekb-mcp",
|
||||
"tokens.json"
|
||||
);
|
||||
export const TOKEN_CACHE_PATH = PRIMARY_TOKEN_CACHE_PATH;
|
||||
|
||||
function resolveTokenCachePath(): string {
|
||||
if (existsSync(PRIMARY_TOKEN_CACHE_PATH)) {
|
||||
return PRIMARY_TOKEN_CACHE_PATH;
|
||||
}
|
||||
if (existsSync(LEGACY_TOKEN_CACHE_PATH)) {
|
||||
return LEGACY_TOKEN_CACHE_PATH;
|
||||
}
|
||||
return PRIMARY_TOKEN_CACHE_PATH;
|
||||
}
|
||||
|
||||
|
||||
@@ -208,6 +208,26 @@ export function loadCorpConfigs(overrideDirs?: string[]): CorpConfig[] {
|
||||
export function saveCorpConfig(config: CorpConfig, dir?: string): string {
|
||||
const targetDir = dir || resolveWritableEnterprisesDir();
|
||||
ensureDir(targetDir);
|
||||
const candidatePath = join(targetDir, `${config.id}.json`);
|
||||
if (!config.credentials?.appKey && existsSync(candidatePath)) {
|
||||
try {
|
||||
const existing = JSON.parse(readFileSync(candidatePath, "utf-8"));
|
||||
const existingKey = existing?.credentials?.appKey || existing?.auth?.appKey;
|
||||
const existingSec = existing?.credentials?.appSecurity || existing?.auth?.appSecurity;
|
||||
if (existingKey && existingSec) {
|
||||
config = {
|
||||
...config,
|
||||
credentials: {
|
||||
...config.credentials,
|
||||
appKey: existingKey,
|
||||
appSecurity: existingSec,
|
||||
},
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// ignore malformed existing file
|
||||
}
|
||||
}
|
||||
const validated = CorpConfigSchema.parse(config);
|
||||
const filePath = join(targetDir, `${validated.id}.json`);
|
||||
writeFileSync(filePath, JSON.stringify(validated, null, 2), "utf-8");
|
||||
|
||||
+21
-12
@@ -12,6 +12,7 @@ export interface CorpSummary {
|
||||
baseUrl?: string;
|
||||
current: boolean;
|
||||
expiresAt?: number;
|
||||
persistent?: boolean;
|
||||
}
|
||||
|
||||
export function resolveCorpConfig(
|
||||
@@ -150,17 +151,25 @@ export class CorpContext {
|
||||
}
|
||||
|
||||
listCorps(): CorpSummary[] {
|
||||
return Array.from(this.corps.values()).map((corp) => ({
|
||||
id: corp.id,
|
||||
name: corp.name,
|
||||
corpId: corp.corpId || corp.credentials.corpId,
|
||||
staffId: corp.credentials.staffId,
|
||||
staffName: corp.staffName || corp.session?.staffName || undefined,
|
||||
source: corp.source || "manual",
|
||||
accountId: corp.accountId,
|
||||
baseUrl: corp.baseUrl,
|
||||
current: corp.id === this.current?.id,
|
||||
expiresAt: corp.auth?.expiresAt || (corp.session?.expTime ?? undefined),
|
||||
}));
|
||||
return Array.from(this.corps.values()).map((corp) => {
|
||||
const hasOpenApiKeys = Boolean(
|
||||
(corp.credentials?.appKey || corp.auth?.appKey) &&
|
||||
(corp.credentials?.appSecurity || corp.auth?.appSecurity)
|
||||
);
|
||||
const hasAccountBinding = corp.source === "account" && !corp.session?.isShortTermToken && Boolean(corp.accountId);
|
||||
return {
|
||||
id: corp.id,
|
||||
name: corp.name,
|
||||
corpId: corp.corpId || corp.credentials.corpId,
|
||||
staffId: corp.credentials.staffId,
|
||||
staffName: corp.staffName || corp.session?.staffName || undefined,
|
||||
source: corp.source || "manual",
|
||||
accountId: corp.accountId,
|
||||
baseUrl: corp.baseUrl,
|
||||
current: corp.id === this.current?.id,
|
||||
expiresAt: corp.auth?.expiresAt || (corp.session?.expTime ?? undefined),
|
||||
persistent: hasOpenApiKeys || hasAccountBinding,
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { z } from "zod";
|
||||
|
||||
export const CredentialSourceSchema = z.enum([
|
||||
"account", // 官方统一认证中心 (IDP) 账密/短信登录
|
||||
"openapi", // 开放平台持久化密钥 (appKey + appSecurity)
|
||||
"assist", // 官方协助/代客平台 (Assist Platform) 调试授权会话
|
||||
"browser", // 浏览器会话 / Cookie 同步
|
||||
"link", // 协助/免密链接导入 (thirdparty.html / assistance link)
|
||||
@@ -12,15 +13,19 @@ export const CredentialSourceSchema = z.enum([
|
||||
export type CredentialSource = z.infer<typeof CredentialSourceSchema>;
|
||||
|
||||
export const CorpCredentialsSchema = z.object({
|
||||
accessToken: z.string().describe("主站访问令牌"),
|
||||
accessToken: z.string().default("").describe("主站访问令牌"),
|
||||
corpId: z.string().describe("企业 ID"),
|
||||
staffId: z.string().describe("员工 ID"),
|
||||
appKey: z.string().optional().describe("开放平台应用 AppKey (持久化凭证)"),
|
||||
appSecurity: z.string().optional().describe("开放平台应用 AppSecurity (持久化凭证)"),
|
||||
});
|
||||
|
||||
export const CorpAuthConfigSchema = z.object({
|
||||
refreshTtl: z.number().default(300).describe("提前多少秒刷新,默认 5 分钟"),
|
||||
refreshToken: z.string().optional().describe("OAuth2 Refresh Token"),
|
||||
expiresAt: z.number().optional().describe("AccessToken 到期时间戳 (ms)"),
|
||||
appKey: z.string().optional().describe("开放平台应用 AppKey (兼容冗余字段)"),
|
||||
appSecurity: z.string().optional().describe("开放平台应用 AppSecurity (兼容冗余字段)"),
|
||||
});
|
||||
|
||||
export const CorpSessionInfoSchema = z.object({
|
||||
|
||||
@@ -27,3 +27,11 @@ export class BusinessError extends EkbError {
|
||||
this.name = "BusinessError";
|
||||
}
|
||||
}
|
||||
|
||||
export class EkbApiError extends EkbError {
|
||||
constructor(message: string, code = "API_ERROR", status = 500) {
|
||||
super(message, code, status);
|
||||
this.name = "EkbApiError";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,10 @@ import {
|
||||
fetchHoseToken,
|
||||
EKB_BASE_URL,
|
||||
} from "./unity-client.js";
|
||||
import {
|
||||
canRefreshCorpAccessToken,
|
||||
refreshSingleCorpAccessToken,
|
||||
} from "../auth/login.js";
|
||||
|
||||
export const SCRIPT_ENGINE_BASE_URL = "https://piper.ekuaibao.com";
|
||||
|
||||
@@ -16,9 +20,22 @@ export const PIPER_BASE_URL = SCRIPT_ENGINE_BASE_URL;
|
||||
// 内存缓存
|
||||
const scriptEngineMemoryCache = new Map<
|
||||
string,
|
||||
{ jwt: string; hoseToken: string; expiresAt: number }
|
||||
{ jwt: string; hoseToken: string; expiresAt: number; sourceAccessToken?: string }
|
||||
>();
|
||||
|
||||
export function clearScriptEngineClientCache(corpId?: string): void {
|
||||
if (!corpId) {
|
||||
scriptEngineMemoryCache.clear();
|
||||
return;
|
||||
}
|
||||
const prefix = `${corpId}:`;
|
||||
for (const key of scriptEngineMemoryCache.keys()) {
|
||||
if (key.startsWith(prefix)) {
|
||||
scriptEngineMemoryCache.delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function isExpired(entry: { expiresAt: number }, refreshTtl: number): boolean {
|
||||
return Date.now() >= entry.expiresAt - refreshTtl * 1000;
|
||||
}
|
||||
@@ -59,7 +76,7 @@ export async function getScriptEngineClient(
|
||||
|
||||
// 检查内存缓存
|
||||
const mem = scriptEngineMemoryCache.get(cacheKey);
|
||||
if (mem && !isExpired(mem, refreshTtl)) {
|
||||
if (mem && mem.sourceAccessToken === corp.credentials.accessToken && !isExpired(mem, refreshTtl)) {
|
||||
return createAuthClient({
|
||||
prefixUrl: SCRIPT_ENGINE_BASE_URL,
|
||||
getHeaders: () => ({
|
||||
@@ -72,6 +89,13 @@ export async function getScriptEngineClient(
|
||||
});
|
||||
}
|
||||
|
||||
if (canRefreshCorpAccessToken(corp)) {
|
||||
const expiresAt = corp.auth?.expiresAt || corp.session?.expTime;
|
||||
if (!corp.credentials.accessToken || (expiresAt && Date.now() >= expiresAt - refreshTtl * 1000)) {
|
||||
await refreshSingleCorpAccessToken(corp);
|
||||
}
|
||||
}
|
||||
|
||||
const corpId = corp.corpId || corp.credentials.corpId;
|
||||
const staffId = corp.staffId || corp.credentials.staffId;
|
||||
const environment = resolveCorpCluster(corp);
|
||||
@@ -94,6 +118,7 @@ export async function getScriptEngineClient(
|
||||
jwt: easoJwt,
|
||||
hoseToken,
|
||||
expiresAt: Date.now() + 2 * 60 * 60 * 1000, // 2小时
|
||||
sourceAccessToken: corp.credentials.accessToken,
|
||||
};
|
||||
|
||||
scriptEngineMemoryCache.set(cacheKey, entry);
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { canRefreshCorpAccessToken, resolveLinkExpiresAt } from "../auth/login.js";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
canRefreshCorpAccessToken,
|
||||
getCorpProvisionalAuthLink,
|
||||
hasOpenApiPersistentCredentials,
|
||||
parseExpiresInSeconds,
|
||||
resolveLinkExpiresAt,
|
||||
selectOpenApiKey,
|
||||
} from "../auth/login.js";
|
||||
import { createSessionClient } from "./session-client.js";
|
||||
import type { CorpConfig } from "../config/types.js";
|
||||
|
||||
@@ -8,19 +18,32 @@ function corp(overrides: Partial<CorpConfig> = {}): CorpConfig {
|
||||
id: "corp-1",
|
||||
name: "测试企业",
|
||||
source: "link",
|
||||
credentials: { accessToken: "token", corpId: "corp-1", staffId: "staff-1" },
|
||||
credentials: { accessToken: "token", corpId: "corp-1", staffId: "corp-1:staff-1" },
|
||||
...overrides,
|
||||
baseUrl: overrides.baseUrl ?? "https://app.ekuaibao.com",
|
||||
};
|
||||
}
|
||||
|
||||
describe("core/http/session-client refresh policy", () => {
|
||||
it("only allows account credentials with an explicit account binding to refresh", () => {
|
||||
it("allows refresh for account credentials or OpenAPI persistent credentials", () => {
|
||||
expect(canRefreshCorpAccessToken(corp())).toBe(false);
|
||||
expect(canRefreshCorpAccessToken(corp({ source: "browser", accountId: "86-1" }))).toBe(false);
|
||||
expect(canRefreshCorpAccessToken(corp({ source: "account" }))).toBe(false);
|
||||
expect(canRefreshCorpAccessToken(corp({ source: "account", accountId: "86-1" }))).toBe(true);
|
||||
expect(canRefreshCorpAccessToken(corp({ source: "account", accountId: "86-1", session: { isShortTermToken: true } }))).toBe(false);
|
||||
|
||||
const openApiCorp = corp({
|
||||
source: "link",
|
||||
credentials: {
|
||||
accessToken: "token",
|
||||
corpId: "corp-1",
|
||||
staffId: "corp-1:staff-1",
|
||||
appKey: "key-123",
|
||||
appSecurity: "sec-456",
|
||||
},
|
||||
});
|
||||
expect(hasOpenApiPersistentCredentials(openApiCorp)).toBe(true);
|
||||
expect(canRefreshCorpAccessToken(openApiCorp)).toBe(true);
|
||||
});
|
||||
|
||||
it("fails expired temporary credentials without retrying or refreshing", async () => {
|
||||
@@ -39,6 +62,96 @@ describe("core/http/session-client refresh policy", () => {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
it("automatically refreshes expired token via OpenAPI getProvisionalAuth when appKey/appSecurity are present", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
const tempDir = mkdtempSync(join(tmpdir(), "hose-use-test-"));
|
||||
const prevEnv = process.env.HOSE_ENTERPRISES_DIR;
|
||||
process.env.HOSE_ENTERPRISES_DIR = tempDir;
|
||||
|
||||
const seenUrls: string[] = [];
|
||||
globalThis.fetch = (async (input: string | URL | Request) => {
|
||||
const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
||||
seenUrls.push(url);
|
||||
if (url.includes("/api/openapi/v1/auth/getAccessToken")) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
value: {
|
||||
accessToken: "openapi-token-xyz",
|
||||
corporationId: "corp-1",
|
||||
expireTime: Date.now() + 7200_000,
|
||||
},
|
||||
}),
|
||||
{ status: 200, headers: { "content-type": "application/json" } }
|
||||
);
|
||||
}
|
||||
if (url.includes("/api/openapi/v1.1/provisional/getProvisionalAuth")) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
value: {
|
||||
message:
|
||||
"https://app.ekuaibao.com/web/thirdparty.html?accessToken=fresh-session-token-999&ekbCorpId=corp-1",
|
||||
},
|
||||
}),
|
||||
{ status: 200, headers: { "content-type": "application/json" } }
|
||||
);
|
||||
}
|
||||
return new Response(JSON.stringify({ value: { ok: true } }), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
}) as unknown as typeof fetch;
|
||||
|
||||
try {
|
||||
const persistentCorp = corp({
|
||||
source: "openapi",
|
||||
credentials: {
|
||||
accessToken: "",
|
||||
corpId: "corp-1",
|
||||
staffId: "corp-1:staff-1",
|
||||
appKey: "test-app-key",
|
||||
appSecurity: "test-app-security",
|
||||
},
|
||||
auth: {
|
||||
refreshTtl: 300,
|
||||
expiresAt: Date.now() - 10_000,
|
||||
},
|
||||
});
|
||||
|
||||
const client = await createSessionClient(persistentCorp);
|
||||
expect(persistentCorp.credentials.accessToken).toBe("fresh-session-token-999");
|
||||
|
||||
const linkRes = await getCorpProvisionalAuthLink(persistentCorp, { enterprisesDir: tempDir });
|
||||
expect(linkRes.method).toBe("provisional-openapi");
|
||||
expect(linkRes.url).toContain("accessToken=fresh-session-token-999");
|
||||
expect(client).toBeDefined();
|
||||
expect(seenUrls.some((u) => u.includes("getProvisionalAuth"))).toBe(true);
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
if (prevEnv === undefined) delete process.env.HOSE_ENTERPRISES_DIR;
|
||||
else process.env.HOSE_ENTERPRISES_DIR = prevEnv;
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("core/auth/login > selectOpenApiKey", () => {
|
||||
const sampleKeys = [
|
||||
{ id: "k1", name: "停用密钥", appKey: "ak-1", appSecurity: "sec-1", active: false },
|
||||
{ id: "k2", name: "启用密钥A", appKey: "ak-2", appSecurity: "sec-2", active: true },
|
||||
{ id: "k3", name: "启用密钥B", appKey: "ak-3", appSecurity: "sec-3", active: true },
|
||||
];
|
||||
|
||||
it("auto-selects when only one active key exists", () => {
|
||||
const picked = selectOpenApiKey([sampleKeys[0]!, sampleKeys[1]!], "corp-1");
|
||||
expect(picked.appKey).toBe("ak-2");
|
||||
});
|
||||
|
||||
it("requires explicit selection or --force when multiple active keys exist", () => {
|
||||
expect(() => selectOpenApiKey(sampleKeys, "corp-1")).toThrow("存在多套");
|
||||
expect(selectOpenApiKey(sampleKeys, "corp-1", { force: true }).appKey).toBe("ak-2");
|
||||
expect(selectOpenApiKey(sampleKeys, "corp-1", { appKey: "ak-3" }).appKey).toBe("ak-3");
|
||||
});
|
||||
});
|
||||
|
||||
describe("core/auth/login link expiry", () => {
|
||||
@@ -49,4 +162,11 @@ describe("core/auth/login link expiry", () => {
|
||||
expect(resolveLinkExpiresAt({ expires: "3" }, base)).toBe(base + 3 * 24 * 60 * 60 * 1000);
|
||||
expect(resolveLinkExpiresAt({}, base)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("parses expires-in / ttl strings to seconds for provisional auth link", () => {
|
||||
expect(parseExpiresInSeconds("24h")).toBe(86400);
|
||||
expect(parseExpiresInSeconds("7d")).toBe(604800);
|
||||
expect(parseExpiresInSeconds("86400")).toBe(86400);
|
||||
expect(parseExpiresInSeconds(3600)).toBe(3600);
|
||||
});
|
||||
});
|
||||
@@ -44,15 +44,16 @@ export async function createSessionClient(
|
||||
) {
|
||||
const canRefresh = canRefreshCorpAccessToken(corp);
|
||||
|
||||
// 1. 预检:若 Token 即将过期 (提前 refreshTtl 秒),静默无感自动续杯
|
||||
if (canRefresh && corp.auth?.expiresAt) {
|
||||
const ttlMs = (corp.auth.refreshTtl || 300) * 1000;
|
||||
if (Date.now() >= corp.auth.expiresAt - ttlMs) {
|
||||
// 1. 预检:若 Token 缺失或即将过期 (提前 refreshTtl 秒),静默无感自动续杯
|
||||
if (canRefresh) {
|
||||
const ttlMs = (corp.auth?.refreshTtl || 300) * 1000;
|
||||
const expiresAt = corp.auth?.expiresAt || corp.session?.expTime;
|
||||
if (!corp.credentials.accessToken || (expiresAt && Date.now() >= expiresAt - ttlMs)) {
|
||||
await refreshSingleCorpAccessToken(corp);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 仅账号凭证启用 401 自动重试与换票;临时凭证直接给出可操作错误
|
||||
// 2. 具备续期能力(主账号或 OpenAPI 持久化密钥)时启用 401 自动重试与换票;临时凭证直接给出可操作错误
|
||||
return createAuthClient({
|
||||
prefixUrl: corp.baseUrl || "https://app.ekuaibao.com",
|
||||
getHeaders: () => getSessionHeaders(corp, options.fingerprint),
|
||||
|
||||
@@ -2,6 +2,10 @@ import ky from "ky";
|
||||
import type { CorpConfig } from "../config/types.js";
|
||||
import { createAuthClient } from "./factory.js";
|
||||
import { AuthenticationError } from "../errors.js";
|
||||
import {
|
||||
canRefreshCorpAccessToken,
|
||||
refreshSingleCorpAccessToken,
|
||||
} from "../auth/login.js";
|
||||
|
||||
export const EASO_BASE_URL = "https://unity.ekuaibao.com";
|
||||
export const BUSINESS_CENTER_URL = "https://business-center.ekuaibao.com";
|
||||
@@ -29,14 +33,24 @@ export function resolveCorpCluster(corp: { cluster?: string; baseUrl?: string })
|
||||
// 内存缓存
|
||||
const easoMemoryCache = new Map<
|
||||
string,
|
||||
{ token: string; hoseToken: string; expiresAt: number }
|
||||
{ token: string; hoseToken: string; expiresAt: number; sourceAccessToken?: string }
|
||||
>();
|
||||
|
||||
const unityMemoryCache = new Map<
|
||||
string,
|
||||
{ token: string; expiresAt: number }
|
||||
{ token: string; expiresAt: number; sourceAccessToken?: string }
|
||||
>();
|
||||
|
||||
export function clearUnityClientCache(corpId?: string): void {
|
||||
if (!corpId) {
|
||||
easoMemoryCache.clear();
|
||||
unityMemoryCache.clear();
|
||||
return;
|
||||
}
|
||||
easoMemoryCache.delete(`${corpId}:easo`);
|
||||
unityMemoryCache.delete(`${corpId}:unity`);
|
||||
}
|
||||
|
||||
function isExpired(entry: { expiresAt: number }, refreshTtl: number): boolean {
|
||||
return Date.now() >= entry.expiresAt - refreshTtl * 1000;
|
||||
}
|
||||
@@ -116,7 +130,7 @@ export async function getEasoClient(corp: CorpConfig): Promise<{
|
||||
|
||||
// 检查内存缓存
|
||||
const mem = easoMemoryCache.get(cacheKey);
|
||||
if (mem && !isExpired(mem, refreshTtl)) {
|
||||
if (mem && mem.sourceAccessToken === corp.credentials.accessToken && !isExpired(mem, refreshTtl)) {
|
||||
return {
|
||||
client: createAuthClient({
|
||||
prefixUrl: EASO_BASE_URL,
|
||||
@@ -133,6 +147,13 @@ export async function getEasoClient(corp: CorpConfig): Promise<{
|
||||
};
|
||||
}
|
||||
|
||||
if (canRefreshCorpAccessToken(corp)) {
|
||||
const expiresAt = corp.auth?.expiresAt || corp.session?.expTime;
|
||||
if (!corp.credentials.accessToken || (expiresAt && Date.now() >= expiresAt - refreshTtl * 1000)) {
|
||||
await refreshSingleCorpAccessToken(corp);
|
||||
}
|
||||
}
|
||||
|
||||
const corpId = corp.corpId || corp.credentials.corpId;
|
||||
const staffId = corp.staffId || corp.credentials.staffId;
|
||||
const environment = resolveCorpCluster(corp);
|
||||
@@ -160,6 +181,7 @@ export async function getEasoClient(corp: CorpConfig): Promise<{
|
||||
token: easoToken,
|
||||
hoseToken,
|
||||
expiresAt: Date.now() + 2 * 60 * 60 * 1000, // 2小时
|
||||
sourceAccessToken: corp.credentials.accessToken,
|
||||
};
|
||||
|
||||
easoMemoryCache.set(cacheKey, entry);
|
||||
@@ -192,7 +214,7 @@ export async function getUnityClient(corp: CorpConfig): Promise<{
|
||||
const cacheKey = `${corp.id}:unity`;
|
||||
|
||||
const mem = unityMemoryCache.get(cacheKey);
|
||||
if (mem && !isExpired(mem, refreshTtl)) {
|
||||
if (mem && mem.sourceAccessToken === corp.credentials.accessToken && !isExpired(mem, refreshTtl)) {
|
||||
return {
|
||||
unityJwt: mem.token,
|
||||
client: createAuthClient({
|
||||
@@ -207,6 +229,13 @@ export async function getUnityClient(corp: CorpConfig): Promise<{
|
||||
};
|
||||
}
|
||||
|
||||
if (canRefreshCorpAccessToken(corp)) {
|
||||
const expiresAt = corp.auth?.expiresAt || corp.session?.expTime;
|
||||
if (!corp.credentials.accessToken || (expiresAt && Date.now() >= expiresAt - refreshTtl * 1000)) {
|
||||
await refreshSingleCorpAccessToken(corp);
|
||||
}
|
||||
}
|
||||
|
||||
const corpId = corp.corpId || corp.credentials.corpId;
|
||||
const staffId = corp.staffId || corp.credentials.staffId;
|
||||
const baseUrl = corp.baseUrl || EKB_BASE_URL;
|
||||
@@ -221,6 +250,7 @@ export async function getUnityClient(corp: CorpConfig): Promise<{
|
||||
const entry = {
|
||||
token: unityJwt,
|
||||
expiresAt: Date.now() + 2 * 60 * 60 * 1000,
|
||||
sourceAccessToken: corp.credentials.accessToken,
|
||||
};
|
||||
unityMemoryCache.set(cacheKey, entry);
|
||||
|
||||
|
||||
@@ -4,9 +4,11 @@ import {
|
||||
RawBillSearchResponseSchema,
|
||||
RawBillBatchGetResponseSchema,
|
||||
EntityListResponseSchema,
|
||||
FormSpecificationSchema,
|
||||
type RawBillSearchResponse,
|
||||
type RawBillItem,
|
||||
type EntityMeta,
|
||||
type FormSpecification,
|
||||
} from "./types.js";
|
||||
|
||||
function quoted(value: string): string {
|
||||
@@ -472,3 +474,31 @@ export async function getDatalinkCard(
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// ── 单据模板规格定义 API(GET api/form/v2/specifications/[{specificationId}])──
|
||||
|
||||
export async function getFormSpecification(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
specificationId: string
|
||||
): Promise<FormSpecification | undefined> {
|
||||
const cleanId = specificationId.replace(/^\[|\]$/g, "").trim();
|
||||
if (!cleanId) return undefined;
|
||||
const response = await client.get(
|
||||
`api/form/v2/specifications/[${encodeURIComponent(cleanId)}]`,
|
||||
{
|
||||
searchParams: { corpId },
|
||||
}
|
||||
);
|
||||
const json = (await response.json()) as {
|
||||
items?: unknown[];
|
||||
value?: unknown;
|
||||
id?: string;
|
||||
};
|
||||
const raw = Array.isArray(json.items)
|
||||
? json.items[0]
|
||||
: json.value ?? (typeof json.id === "string" ? json : undefined);
|
||||
if (!raw || typeof raw !== "object") return undefined;
|
||||
return FormSpecificationSchema.parse(raw);
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
commentBillAction,
|
||||
getInvoiceValidationDetail,
|
||||
getDatalinkCard,
|
||||
getFormSpecification,
|
||||
type BillActionOptions,
|
||||
type BillActionTarget,
|
||||
} from "./api.js";
|
||||
@@ -48,6 +49,9 @@ import {
|
||||
type BillRelationsReport,
|
||||
type BillAttachment,
|
||||
type BillAttachmentReport,
|
||||
type FormSpecification,
|
||||
type FormSpecificationComponent,
|
||||
type FormPriorityItem,
|
||||
} from "./types.js";
|
||||
import { CorpContext } from "../../core/config/manager.js";
|
||||
import { createSessionClient } from "../../core/http/session-client.js";
|
||||
@@ -1596,6 +1600,73 @@ export async function getTranslatorContext(
|
||||
};
|
||||
}
|
||||
|
||||
export function formatFormPriorityList(priorityList: FormPriorityItem[] | undefined): string {
|
||||
if (!Array.isArray(priorityList) || priorityList.length === 0) return "-";
|
||||
const sorted = [...priorityList].sort((a, b) => b.priority - a.priority);
|
||||
return sorted.map((p) => `${p.type}(${p.priority})`).join(" > ");
|
||||
}
|
||||
|
||||
export function hasLinkageOverridePriority(priorityList: FormPriorityItem[] | undefined): boolean {
|
||||
if (!Array.isArray(priorityList) || priorityList.length === 0) return false;
|
||||
const linkage = priorityList.find((p) => p.type === "LINKAGE_ASSIGNMENT");
|
||||
const manual = priorityList.find((p) => p.type === "MANUALLY_FILL_IN");
|
||||
if (!linkage || !manual) return false;
|
||||
return linkage.priority > manual.priority;
|
||||
}
|
||||
|
||||
export interface FormSpecificationInspection {
|
||||
specification: FormSpecification;
|
||||
warnings: string[];
|
||||
}
|
||||
|
||||
export async function inspectFormSpecification(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
specificationId: string
|
||||
): Promise<FormSpecificationInspection | undefined> {
|
||||
const spec = await getFormSpecification(client, corpId, specificationId);
|
||||
if (!spec) return undefined;
|
||||
|
||||
const warnings: string[] = [];
|
||||
const linkageSources = spec.components.filter(
|
||||
(c) => c.isLinkageAssignment === true || Boolean(c.assignmentRule)
|
||||
);
|
||||
const overrideTargets = spec.components.filter((c) =>
|
||||
hasLinkageOverridePriority(c.priorityList)
|
||||
);
|
||||
|
||||
for (const src of linkageSources) {
|
||||
if (src.isLinkageAssignment) {
|
||||
warnings.push(
|
||||
`字段 [${src.label || src.name}] (${src.name}, type=${src.type}) 开启了联动赋值 (isLinkageAssignment=true, assignmentRule=${src.assignmentRule || "-"})`
|
||||
);
|
||||
} else if (src.assignmentRule) {
|
||||
warnings.push(
|
||||
`字段 [${src.label || src.name}] (${src.name}, type=${src.type}) 配置了联动规则 (assignmentRule=${src.assignmentRule}, 当前 isLinkageAssignment=false)`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (linkageSources.length > 0 && overrideTargets.length > 0) {
|
||||
const targetNames = overrideTargets.map((t) => `${t.label || t.name}(${t.name})`).join("、");
|
||||
warnings.push(
|
||||
`优先级覆盖风险: 字段 [${targetNames}] 的赋值优先级中 LINKAGE_ASSIGNMENT 高于 MANUALLY_FILL_IN(如 LINKAGE_ASSIGNMENT(10) > MANUALLY_FILL_IN(5)),当关联业务对象触发联动赋值时,手动填写或工作流 API 显式传入的值将被联动值覆盖!`
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
specification: spec,
|
||||
warnings,
|
||||
};
|
||||
}
|
||||
|
||||
export {
|
||||
getFormSpecification,
|
||||
type FormSpecification,
|
||||
type FormSpecificationComponent,
|
||||
type FormPriorityItem,
|
||||
};
|
||||
|
||||
export {
|
||||
translateBillFlowToMarkdown,
|
||||
formatBillFlowOperator,
|
||||
@@ -1612,3 +1683,4 @@ export {
|
||||
formatDynamicField,
|
||||
type TranslatorOptions,
|
||||
} from "./translator.js";
|
||||
|
||||
@@ -26,6 +26,60 @@ export const EntityListResponseSchema = z.object({
|
||||
items: z.array(EntitySchema).default([]),
|
||||
});
|
||||
|
||||
export const FormPriorityItemSchema = z
|
||||
.object({
|
||||
type: z.string(),
|
||||
label: z.string().optional().default(""),
|
||||
priority: z.number().optional(),
|
||||
value: z.number().optional(),
|
||||
})
|
||||
.passthrough()
|
||||
.transform((item) => ({
|
||||
...item,
|
||||
priority: item.priority ?? item.value ?? 0,
|
||||
}));
|
||||
|
||||
export const FormSpecificationComponentSchema = z
|
||||
.object({
|
||||
id: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
field: z.string().optional(),
|
||||
label: z.string().optional().default(""),
|
||||
type: z.string().default("text"),
|
||||
optional: z.boolean().optional().default(true),
|
||||
editable: z.boolean().optional().default(true),
|
||||
hidden: z.boolean().optional().default(false),
|
||||
isLinkageAssignment: z.boolean().optional().default(false),
|
||||
assignmentRule: z.string().nullable().optional(),
|
||||
priorityList: z.array(FormPriorityItemSchema).nullable().optional(),
|
||||
priority: z.array(FormPriorityItemSchema).nullable().optional(),
|
||||
entityId: z.string().nullable().optional(),
|
||||
referenceData: z.string().nullable().optional(),
|
||||
dimensionId: z.string().nullable().optional(),
|
||||
})
|
||||
.passthrough()
|
||||
.transform((comp) => ({
|
||||
...comp,
|
||||
name: comp.name || comp.field || comp.label || "",
|
||||
priorityList: comp.priorityList ?? comp.priority ?? [],
|
||||
entityId: comp.entityId ?? comp.referenceData ?? null,
|
||||
}));
|
||||
|
||||
export const FormSpecificationSchema = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
name: z.string().optional().default(""),
|
||||
type: z.string().optional().default(""),
|
||||
active: z.boolean().optional().default(true),
|
||||
configs: z.unknown().optional(),
|
||||
components: z.array(FormSpecificationComponentSchema).optional().default([]),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export type FormPriorityItem = z.infer<typeof FormPriorityItemSchema>;
|
||||
export type FormSpecificationComponent = z.infer<typeof FormSpecificationComponentSchema>;
|
||||
export type FormSpecification = z.infer<typeof FormSpecificationSchema>;
|
||||
|
||||
// ── 原始单据条目(Raw Bill Item from /api/v2/invoice/search)─────────────────────
|
||||
|
||||
export const RawBillMoneySchema = z.object({
|
||||
|
||||
@@ -30,15 +30,20 @@ hose-use platform list
|
||||
hose-use platform get <应用 ID|名称>
|
||||
hose-use platform entities <应用 ID|名称>
|
||||
hose-use platform schema <应用 ID|名称> [对象 ID|名称] [--keyword <字段关键词>]
|
||||
hose-use platform records <应用 ID|名称> <对象 ID|名称> [--keyword <关键词>] [--filter <表达式>] [--fields <字段列表>]
|
||||
hose-use platform record get <应用> <业务对象> <记录ID>
|
||||
hose-use platform records <应用 ID|名称> <对象 ID|名称> [--all] [--keyword <关键词>] [--filter <表达式>] [--fields <字段列表>]
|
||||
hose-use platform record get [<应用> <业务对象>] <记录ID>
|
||||
hose-use platform record toggle <应用> <业务对象> <记录ID> [--state=true|false] [--dry-run|--yes]
|
||||
hose-use platform record edit <应用> <业务对象> <记录ID> --data='{"field": "val"}' [--dry-run|--yes]
|
||||
hose-use platform record edit <应用> <业务对象> <记录ID> --data='{"field": "val"}' [--raw] [--dry-run|--yes]
|
||||
hose-use platform record batch-edit <应用> <业务对象> [--ids=id1,id2|--filter=...] --data='{"field": "val"}' [--concurrency=8] [--dry-run|--yes]
|
||||
hose-use platform record recompute <应用> <业务对象> <记录ID> [--dry-run|--yes]
|
||||
hose-use platform audit <应用 ID|名称> <对象 ID|名称> [--check-fields=字段1,字段2] [--active-only]
|
||||
hose-use platform permissions <应用 ID|名称> [对象 ID|名称]
|
||||
hose-use platform imports <应用 ID|名称> <对象 ID|名称>
|
||||
```
|
||||
|
||||
也可以使用 `datalink` / `data-link` 作为同义命令域。
|
||||
|
||||
单条业务对象记录支持通过 `record get`(详情)、`record toggle`(启停用)、`record edit`(字段编辑更新)以及 `record recompute`(台账重算)进行维护。Excel 批量上传与流程引擎触发暂不在本域开放。
|
||||
- `record get` 支持直传 `<记录ID>` 免传应用与业务对象。
|
||||
- `record edit` 与 `record batch-edit` 默认启用 **Read-Modify-Write 安全全量合并**(保留全部 `E_<entityId>_*` 字段、将嵌套引用对象归一化为字符串 ID、保留 `active` 与 `visibility` 结构,支持字段短名/中文标签映射);仅当显式传入 `--raw` 时才直接透传原始补丁。
|
||||
- `records --all` 自动按 `500` 条/页循环拉取全量台账记录。
|
||||
- `audit` 一键巡检必填/指定字段缺失、引用已停用档案以及跨台账同名字段同步差异,并输出 `suggestedPatches`。
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
DatalinkEntitySchema,
|
||||
DatalinkPlatformDetailSchema,
|
||||
type DatalinkEntity,
|
||||
type DatalinkField,
|
||||
type DatalinkImportJob,
|
||||
type DatalinkPlatformDetail,
|
||||
type DatalinkRecord,
|
||||
@@ -266,6 +267,248 @@ export async function editRecord(
|
||||
return (json.value ?? json.data ?? json) as Record<string, unknown>;
|
||||
}
|
||||
|
||||
const REFERENCE_FIELD_TYPES = new Set([
|
||||
"dimension",
|
||||
"dataLink",
|
||||
"staff",
|
||||
"department",
|
||||
"role",
|
||||
"reference",
|
||||
]);
|
||||
|
||||
const SYSTEM_RECORD_KEYS = new Set([
|
||||
"id",
|
||||
"entityId",
|
||||
"active",
|
||||
"visibility",
|
||||
"createTime",
|
||||
"updateTime",
|
||||
"corporationId",
|
||||
"platformId",
|
||||
"ownerId",
|
||||
"creatorId",
|
||||
"form",
|
||||
"fieldAuth",
|
||||
"actions",
|
||||
"source",
|
||||
"sourceId",
|
||||
]);
|
||||
|
||||
function extractReferenceId(value: unknown): string | undefined {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
||||
const obj = value as Record<string, unknown>;
|
||||
if ("standard" in obj) return undefined;
|
||||
if (typeof obj.id === "string" && obj.id) return obj.id;
|
||||
if (obj.dataLink && typeof obj.dataLink === "object" && !Array.isArray(obj.dataLink)) {
|
||||
const dl = obj.dataLink as Record<string, unknown>;
|
||||
if (typeof dl.id === "string" && dl.id) return dl.id;
|
||||
}
|
||||
if (obj.data && typeof obj.data === "object" && !Array.isArray(obj.data)) {
|
||||
const dataObj = obj.data as Record<string, unknown>;
|
||||
if (typeof dataObj.id === "string" && dataObj.id) return dataObj.id;
|
||||
if (dataObj.dataLink && typeof dataObj.dataLink === "object" && !Array.isArray(dataObj.dataLink)) {
|
||||
const dl = dataObj.dataLink as Record<string, unknown>;
|
||||
if (typeof dl.id === "string" && dl.id) return dl.id;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function normalizeRecordFieldValue(
|
||||
value: unknown,
|
||||
fieldDef?: DatalinkField
|
||||
): unknown {
|
||||
if (value === undefined) return undefined;
|
||||
if (value === null) return "";
|
||||
const isRefType = fieldDef ? REFERENCE_FIELD_TYPES.has(fieldDef.type) : false;
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((item) => {
|
||||
const refId = extractReferenceId(item);
|
||||
if (refId && (isRefType || refId)) {
|
||||
return refId;
|
||||
}
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
if (typeof value === "object" && "standard" in (value as Record<string, unknown>)) {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
const refId = extractReferenceId(value);
|
||||
if (refId && (isRefType || refId)) {
|
||||
return refId;
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
export function resolveEntityFieldKey(
|
||||
inputKey: string,
|
||||
entityId: string,
|
||||
fields: DatalinkField[] = [],
|
||||
existingForm: Record<string, unknown> = {}
|
||||
): { key: string; fieldDef?: DatalinkField } {
|
||||
const bareEntityId = entityId.startsWith("$") ? entityId.slice(1) : entityId;
|
||||
const exactByName = fields.find((f) => f.name === inputKey);
|
||||
if (exactByName) {
|
||||
return { key: exactByName.name, fieldDef: exactByName };
|
||||
}
|
||||
const prefixedKey = `E_${bareEntityId}_${inputKey}`;
|
||||
const byPrefixedName = fields.find((f) => f.name === prefixedKey);
|
||||
if (byPrefixedName) {
|
||||
return { key: byPrefixedName.name, fieldDef: byPrefixedName };
|
||||
}
|
||||
const byLabel = fields.find((f) => f.label === inputKey);
|
||||
if (byLabel && byLabel.name) {
|
||||
return { key: byLabel.name, fieldDef: byLabel };
|
||||
}
|
||||
if (inputKey.startsWith(`E_${bareEntityId}_`)) {
|
||||
return { key: inputKey };
|
||||
}
|
||||
if (prefixedKey in existingForm) {
|
||||
return { key: prefixedKey };
|
||||
}
|
||||
if (fields.some((f) => f.name.startsWith(`E_${bareEntityId}_`)) && !(inputKey in existingForm)) {
|
||||
return { key: prefixedKey };
|
||||
}
|
||||
return { key: inputKey };
|
||||
}
|
||||
|
||||
export interface SafeRecordEditOptions {
|
||||
entityId: string;
|
||||
recordId: string;
|
||||
detail?: DatalinkRecordDetail | Record<string, unknown>;
|
||||
fields?: DatalinkField[];
|
||||
patchForm: Record<string, unknown>;
|
||||
active?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建安全的业务对象记录 Read-Modify-Write 编辑 Payload:
|
||||
* 1. 自动提取并保留原记录全部 E_<entityId>_* 及已有业务字段;
|
||||
* 2. 自动将 dimension / dataLink / staff / department 等引用对象 { id: "ID01..." } 归一化为字符串 ID;
|
||||
* 3. 自动保留 active 与 visibility(将 staff/role/department 映射为 staffs/roles/departments);
|
||||
* 4. 支持按完整字段名(E_<entityId>_xxx)或简写字段显示名/后缀(我方签约主体、name、code)合并变更。
|
||||
*/
|
||||
export function buildSafeRecordEditPayload(
|
||||
options: SafeRecordEditOptions
|
||||
): DatalinkRecordEditPayload {
|
||||
const bareEntityId = options.entityId.startsWith("$")
|
||||
? options.entityId.slice(1)
|
||||
: options.entityId;
|
||||
const bareRecordId = options.recordId.startsWith("$")
|
||||
? options.recordId.slice(1)
|
||||
: options.recordId;
|
||||
const fields = options.fields ?? [];
|
||||
const detailObj = asRecord(options.detail);
|
||||
const nestedData = asRecord(detailObj.data);
|
||||
const record = asRecord(
|
||||
detailObj.dataLink ?? nestedData.dataLink ?? detailObj
|
||||
);
|
||||
|
||||
const mergedForm: Record<string, unknown> = {};
|
||||
const fieldByName = new Map<string, DatalinkField>();
|
||||
for (const f of fields) {
|
||||
if (f.name) fieldByName.set(f.name, f);
|
||||
}
|
||||
|
||||
// 1. 提取 record.form 中的字段(兼容测试与部分特殊实体结构)
|
||||
if (record.form && typeof record.form === "object" && !Array.isArray(record.form)) {
|
||||
for (const [k, v] of Object.entries(record.form as Record<string, unknown>)) {
|
||||
const fDef = fieldByName.get(k);
|
||||
mergedForm[k] = normalizeRecordFieldValue(v, fDef);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 提取原记录中的 E_<entityId>_* 字段与 schema 中定义的业务字段
|
||||
const entityPrefix = `E_${bareEntityId}_`;
|
||||
for (const [k, v] of Object.entries(record)) {
|
||||
if (SYSTEM_RECORD_KEYS.has(k)) continue;
|
||||
const fDef = fieldByName.get(k);
|
||||
if (k.startsWith(entityPrefix) || k.startsWith("E_") || fDef) {
|
||||
mergedForm[k] = normalizeRecordFieldValue(v, fDef);
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 合并用户传入的 patchForm(支持字段名、中文显示名或后缀简写)
|
||||
for (const [rawKey, rawVal] of Object.entries(options.patchForm)) {
|
||||
const { key, fieldDef } = resolveEntityFieldKey(
|
||||
rawKey,
|
||||
bareEntityId,
|
||||
fields,
|
||||
mergedForm
|
||||
);
|
||||
mergedForm[key] = normalizeRecordFieldValue(rawVal, fieldDef);
|
||||
}
|
||||
|
||||
// 4. 保留 active 与 visibility
|
||||
const resolvedActive =
|
||||
options.active !== undefined
|
||||
? options.active
|
||||
: typeof record.active === "boolean"
|
||||
? record.active
|
||||
: true;
|
||||
|
||||
const rawVis = asRecord(record.visibility);
|
||||
const normalizeRefIdList = (list: unknown): string[] => {
|
||||
if (!Array.isArray(list)) return [];
|
||||
return list
|
||||
.map((item) =>
|
||||
typeof item === "string"
|
||||
? item
|
||||
: item && typeof item === "object" && typeof (item as Record<string, unknown>).id === "string"
|
||||
? String((item as Record<string, unknown>).id)
|
||||
: undefined
|
||||
)
|
||||
.filter((item): item is string => Boolean(item));
|
||||
};
|
||||
|
||||
const visibility = {
|
||||
fullVisible:
|
||||
typeof rawVis.fullVisible === "boolean" ? rawVis.fullVisible : true,
|
||||
staffs: normalizeRefIdList(rawVis.staffs ?? rawVis.staff),
|
||||
roles: normalizeRefIdList(rawVis.roles ?? rawVis.role),
|
||||
departments: normalizeRefIdList(rawVis.departments ?? rawVis.department),
|
||||
departmentsIncludeChildren:
|
||||
typeof rawVis.departmentsIncludeChildren === "boolean"
|
||||
? rawVis.departmentsIncludeChildren
|
||||
: false,
|
||||
};
|
||||
|
||||
return {
|
||||
dataLinkEntityId: bareEntityId,
|
||||
dataLinkId: bareRecordId,
|
||||
active: resolvedActive,
|
||||
form: mergedForm,
|
||||
visibility,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全编辑单条业务对象记录(Read-Modify-Write 模式)。
|
||||
*/
|
||||
export async function safeEditRecord(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
options: Omit<SafeRecordEditOptions, "detail"> & {
|
||||
detail?: DatalinkRecordDetail | Record<string, unknown>;
|
||||
}
|
||||
): Promise<{
|
||||
payload: DatalinkRecordEditPayload;
|
||||
result: Record<string, unknown>;
|
||||
}> {
|
||||
const detail =
|
||||
options.detail ?? (await getRecordDetail(client, corpId, options.recordId));
|
||||
const payload = buildSafeRecordEditPayload({
|
||||
...options,
|
||||
detail,
|
||||
});
|
||||
const result = await editRecord(client, corpId, payload);
|
||||
return { payload, result };
|
||||
}
|
||||
|
||||
/** 重算业务对象记录下的台账信息。 */
|
||||
export async function recomputeRecordLedger(
|
||||
client: KyInstance,
|
||||
@@ -278,3 +521,4 @@ export async function recomputeRecordLedger(
|
||||
});
|
||||
return asRecord(await response.json());
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import {
|
||||
buildSafeRecordEditPayload,
|
||||
editRecord,
|
||||
getPlatform,
|
||||
getRecordDetail,
|
||||
@@ -9,7 +10,13 @@ import {
|
||||
searchEntityRecords,
|
||||
toggleRecordState,
|
||||
} from "./api.js";
|
||||
import { buildKeywordFilter, selectRecordFields } from "./services.js";
|
||||
import {
|
||||
auditEntityRecords,
|
||||
batchSafeEditRecords,
|
||||
buildKeywordFilter,
|
||||
fetchAllEntityRecords,
|
||||
selectRecordFields,
|
||||
} from "./services.js";
|
||||
|
||||
const platform = {
|
||||
id: "platform-1",
|
||||
@@ -167,5 +174,217 @@ describe("DataLink Domain - 应用、业务对象与记录查询", () => {
|
||||
const result = await recomputeRecordLedger(client, "corp-1", "record-1");
|
||||
expect(result.id).toBe("ok");
|
||||
});
|
||||
|
||||
test("buildSafeRecordEditPayload 执行 Read-Modify-Write 安全合并并归一化嵌套引用 ID 与 visibility", async () => {
|
||||
const fields = [
|
||||
{ name: "E_e1_name", label: "合同名称", type: "text" },
|
||||
{ name: "E_e1_company", label: "我方签约主体", type: "dimension" },
|
||||
{ name: "E_e1_supplier", label: "供应商", type: "supplier" },
|
||||
{ name: "E_e1_amount", label: "合同金额", type: "money" },
|
||||
];
|
||||
const detail = {
|
||||
dataLink: {
|
||||
id: "ID01VSau4VJWSH",
|
||||
active: true,
|
||||
E_e1_name: "年度采购合同",
|
||||
E_e1_company: null,
|
||||
E_e1_supplier: { id: "ID01SUP123", name: "测试供应商" },
|
||||
E_e1_amount: { standard: "1000.00", standardUnit: "元", standardScale: 2 },
|
||||
visibility: {
|
||||
fullVisible: false,
|
||||
staff: [{ id: "staff-1" }],
|
||||
role: ["role-1"],
|
||||
department: [],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const payload = buildSafeRecordEditPayload({
|
||||
entityId: "e1",
|
||||
recordId: "ID01VSau4VJWSH",
|
||||
detail,
|
||||
fields: fields as any,
|
||||
patchForm: {
|
||||
我方签约主体: "ID01RnG3b79daL",
|
||||
},
|
||||
});
|
||||
|
||||
expect(payload.dataLinkEntityId).toBe("e1");
|
||||
expect(payload.dataLinkId).toBe("ID01VSau4VJWSH");
|
||||
expect(payload.active).toBe(true);
|
||||
expect(payload.form.E_e1_name).toBe("年度采购合同");
|
||||
expect(payload.form.E_e1_company).toBe("ID01RnG3b79daL");
|
||||
expect(payload.form.E_e1_supplier).toBe("ID01SUP123");
|
||||
expect(payload.form.E_e1_amount).toBe(
|
||||
JSON.stringify({
|
||||
standard: "1000.00",
|
||||
standardUnit: "元",
|
||||
standardScale: 2,
|
||||
})
|
||||
);
|
||||
expect(payload.visibility).toEqual({
|
||||
fullVisible: false,
|
||||
staffs: ["staff-1"],
|
||||
roles: ["role-1"],
|
||||
departments: [],
|
||||
departmentsIncludeChildren: false,
|
||||
});
|
||||
|
||||
let postUrl = "";
|
||||
let postBody: any = null;
|
||||
const client = {
|
||||
post: async (url: string, options: any) => {
|
||||
postUrl = url;
|
||||
postBody = options.json;
|
||||
return { json: async () => ({ value: { id: "ID01VSau4VJWSH" } }) };
|
||||
},
|
||||
} as any;
|
||||
|
||||
await editRecord(client, "corp-1", payload);
|
||||
expect(postUrl).toBe("api/v2/datalink/entityEdit/edit");
|
||||
expect(postBody.form.E_e1_company).toBe("ID01RnG3b79daL");
|
||||
expect(postBody.visibility.staffs).toEqual(["staff-1"]);
|
||||
});
|
||||
|
||||
test("fetchAllEntityRecords 自动分页拉取全量记录", async () => {
|
||||
const calls: Array<{ start: number; count: number }> = [];
|
||||
const client = {
|
||||
post: async (_url: string, options: any) => {
|
||||
const limit = options.json.query.limit;
|
||||
calls.push(limit);
|
||||
if (limit.start === 0) {
|
||||
return {
|
||||
json: async () => ({
|
||||
items: {
|
||||
total: 3,
|
||||
data: [
|
||||
{ id: "r-1", dataLink: { id: "r-1" } },
|
||||
{ id: "r-2", dataLink: { id: "r-2" } },
|
||||
],
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
return {
|
||||
json: async () => ({
|
||||
items: {
|
||||
total: 3,
|
||||
data: [{ id: "r-3", dataLink: { id: "r-3" } }],
|
||||
},
|
||||
}),
|
||||
};
|
||||
},
|
||||
} as any;
|
||||
|
||||
const result = await fetchAllEntityRecords(client, "corp-1", "entity-1", { pageSize: 2 });
|
||||
expect(calls).toEqual([
|
||||
{ start: 0, count: 2 },
|
||||
{ start: 2, count: 2 },
|
||||
]);
|
||||
expect(result.data).toHaveLength(3);
|
||||
});
|
||||
|
||||
test("auditEntityRecords 巡检必填缺失、停用引用与跨台账同名字段同步差异", () => {
|
||||
const childEntity = {
|
||||
id: "e_plan",
|
||||
name: "支付计划表",
|
||||
fields: [
|
||||
{ name: "E_e_plan_code", label: "编码", type: "text", optional: true },
|
||||
{ name: "E_e_plan_company", label: "我方签约主体", type: "dimension", optional: false },
|
||||
{
|
||||
name: "E_e_plan_contract",
|
||||
label: "关联合同流程",
|
||||
type: "dataLink",
|
||||
optional: true,
|
||||
entityId: "e_contract",
|
||||
},
|
||||
],
|
||||
actions: [],
|
||||
importMethod: [],
|
||||
};
|
||||
|
||||
const records = [
|
||||
{
|
||||
id: "plan-1",
|
||||
dataLink: {
|
||||
id: "plan-1",
|
||||
code: "PL-001",
|
||||
name: "第一期付款",
|
||||
active: true,
|
||||
E_e_plan_company: null,
|
||||
E_e_plan_contract: {
|
||||
id: "contract-1",
|
||||
name: "测试合同",
|
||||
active: false,
|
||||
data: {
|
||||
dataLink: {
|
||||
id: "contract-1",
|
||||
code: "HT-001",
|
||||
active: false,
|
||||
E_e_contract_company: {
|
||||
id: "ID01RnG3b79daL",
|
||||
name: "北京转转精神科技有限责任公司",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const report = auditEntityRecords(records as any, childEntity as any, {
|
||||
checkFields: ["我方签约主体"],
|
||||
});
|
||||
|
||||
expect(report.totalRecords).toBe(1);
|
||||
expect(report.summary.missingFieldCount).toBe(1);
|
||||
expect(report.summary.disabledReferenceCount).toBe(1);
|
||||
expect(report.summary.crossLedgerMissingSyncCount).toBe(1);
|
||||
expect(report.suggestedPatches).toEqual([
|
||||
{
|
||||
id: "plan-1",
|
||||
code: "PL-001",
|
||||
name: "第一期付款",
|
||||
form: {
|
||||
E_e_plan_company: "ID01RnG3b79daL",
|
||||
},
|
||||
reason: "我方签约主体 <- 北京转转精神科技有限责任公司 (ID01RnG3b79daL)",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("batchSafeEditRecords 支持 dryRun 预览与并发安全合并", async () => {
|
||||
const entity = {
|
||||
id: "e1",
|
||||
name: "合同流程",
|
||||
fields: [{ name: "E_e1_company", label: "我方签约主体", type: "dimension" }],
|
||||
actions: [],
|
||||
importMethod: [],
|
||||
};
|
||||
const client = {
|
||||
get: async () => ({
|
||||
json: async () => ({
|
||||
value: {
|
||||
dataLink: {
|
||||
id: "r-1",
|
||||
active: true,
|
||||
E_e1_company: null,
|
||||
},
|
||||
},
|
||||
}),
|
||||
}),
|
||||
} as any;
|
||||
|
||||
const results = await batchSafeEditRecords(
|
||||
client,
|
||||
"corp-1",
|
||||
entity as any,
|
||||
[{ recordId: "r-1", patchForm: { 我方签约主体: "ID01RnG3b79daL" } }],
|
||||
{ dryRun: true }
|
||||
);
|
||||
expect(results).toHaveLength(1);
|
||||
expect(results[0]?.status).toBe("preview");
|
||||
expect(results[0]?.payload?.form.E_e1_company).toBe("ID01RnG3b79daL");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import * as api from "./api.js";
|
||||
import type { DatalinkEntity, DatalinkField, DatalinkPlatformDetail } from "./types.js";
|
||||
import type {
|
||||
DatalinkEntity,
|
||||
DatalinkField,
|
||||
DatalinkPlatformDetail,
|
||||
DatalinkRecord,
|
||||
DatalinkRecordEditPayload,
|
||||
DatalinkRecordPage,
|
||||
} from "./types.js";
|
||||
|
||||
function matches(value: unknown, target: string): boolean {
|
||||
return typeof value === "string" && value.toLowerCase() === target.toLowerCase();
|
||||
@@ -35,14 +42,21 @@ export function buildKeywordFilter(keyword: string): string {
|
||||
return `(name.containsIgnoreCase("${escaped}")||code.containsIgnoreCase("${escaped}"))&&(active.in(true,false))`;
|
||||
}
|
||||
|
||||
export function selectRecordFields(record: Record<string, unknown>, fields: string[], definitions: DatalinkField[] = []): Record<string, unknown> {
|
||||
export function selectRecordFields(
|
||||
record: Record<string, unknown>,
|
||||
fields: string[],
|
||||
definitions: DatalinkField[] = []
|
||||
): Record<string, unknown> {
|
||||
if (fields.length === 0) return record;
|
||||
const dataLink = record.dataLink && typeof record.dataLink === "object" && !Array.isArray(record.dataLink)
|
||||
? (record.dataLink as Record<string, unknown>)
|
||||
: record;
|
||||
const dataLink =
|
||||
record.dataLink && typeof record.dataLink === "object" && !Array.isArray(record.dataLink)
|
||||
? (record.dataLink as Record<string, unknown>)
|
||||
: record;
|
||||
const selected: Record<string, unknown> = {};
|
||||
for (const selector of fields) {
|
||||
const definition = definitions.find((field) => field.name === selector || field.label === selector);
|
||||
const definition = definitions.find(
|
||||
(field) => field.name === selector || field.label === selector
|
||||
);
|
||||
const sourceName = definition?.name ?? selector;
|
||||
if (sourceName in dataLink) selected[definition?.label || selector] = dataLink[sourceName];
|
||||
}
|
||||
@@ -50,3 +64,493 @@ export function selectRecordFields(record: Record<string, unknown>, fields: stri
|
||||
? { ...record, dataLink: selected }
|
||||
: selected;
|
||||
}
|
||||
|
||||
/**
|
||||
* 自动分页全量拉取指定业务对象的全部记录(默认每页 500 条循环直到底)。
|
||||
*/
|
||||
export async function fetchAllEntityRecords(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
entityId: string,
|
||||
options: { filterBy?: string; pageSize?: number; orderBy?: unknown } = {}
|
||||
): Promise<DatalinkRecordPage> {
|
||||
const pageSize = Math.max(1, Math.min(options.pageSize ?? 500, 1000));
|
||||
let start = 0;
|
||||
let total = 0;
|
||||
const allData: DatalinkRecord[] = [];
|
||||
let firstPage: DatalinkRecordPage | undefined;
|
||||
|
||||
while (true) {
|
||||
const page = await api.searchEntityRecords(client, corpId, entityId, {
|
||||
start,
|
||||
count: pageSize,
|
||||
filterBy: options.filterBy,
|
||||
orderBy: options.orderBy,
|
||||
});
|
||||
firstPage ??= page;
|
||||
total = page.total;
|
||||
if (page.data.length === 0) break;
|
||||
allData.push(...page.data);
|
||||
start += page.data.length;
|
||||
if (allData.length >= total || page.data.length < pageSize) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
total: Math.max(total, allData.length),
|
||||
data: allData,
|
||||
actions: firstPage?.actions ?? [],
|
||||
components: firstPage?.components ?? [],
|
||||
path: firstPage?.path,
|
||||
template: firstPage?.template,
|
||||
};
|
||||
}
|
||||
|
||||
export interface DatalinkAuditIssue {
|
||||
recordId: string;
|
||||
recordCode: string;
|
||||
recordName: string;
|
||||
active: boolean;
|
||||
type:
|
||||
| "MISSING_FIELD"
|
||||
| "DISABLED_REFERENCE"
|
||||
| "CROSS_LEDGER_MISSING_SYNC"
|
||||
| "CROSS_LEDGER_MISMATCH";
|
||||
field: string;
|
||||
fieldLabel: string;
|
||||
message: string;
|
||||
linkedField?: string;
|
||||
linkedFieldLabel?: string;
|
||||
linkedRecordId?: string;
|
||||
actualId?: string;
|
||||
actualName?: string;
|
||||
expectedId?: string;
|
||||
expectedName?: string;
|
||||
}
|
||||
|
||||
export interface DatalinkAuditReport {
|
||||
entityId: string;
|
||||
entityName: string;
|
||||
totalRecords: number;
|
||||
auditedRecords: number;
|
||||
healthyRecords: number;
|
||||
affectedRecordCount: number;
|
||||
issueCount: number;
|
||||
summary: {
|
||||
missingFieldCount: number;
|
||||
disabledReferenceCount: number;
|
||||
crossLedgerMissingSyncCount: number;
|
||||
crossLedgerMismatchCount: number;
|
||||
};
|
||||
issues: DatalinkAuditIssue[];
|
||||
suggestedPatches: Array<{
|
||||
id: string;
|
||||
code: string;
|
||||
name: string;
|
||||
form: Record<string, string>;
|
||||
reason: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
function isEmptyFieldValue(value: unknown): boolean {
|
||||
if (value === undefined || value === null || value === "") return true;
|
||||
if (Array.isArray(value)) return value.length === 0;
|
||||
if (typeof value === "object") {
|
||||
const obj = value as Record<string, unknown>;
|
||||
if ("id" in obj) {
|
||||
return obj.id === undefined || obj.id === null || obj.id === "";
|
||||
}
|
||||
if ("standard" in obj) {
|
||||
return obj.standard === undefined || obj.standard === null || obj.standard === "";
|
||||
}
|
||||
return Object.keys(obj).length === 0;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function extractRefIdAndName(value: unknown): {
|
||||
id?: string;
|
||||
name?: string;
|
||||
active?: boolean;
|
||||
} {
|
||||
if (typeof value === "string" && value.trim()) {
|
||||
return { id: value.trim() };
|
||||
}
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
||||
return {};
|
||||
}
|
||||
const obj = value as Record<string, unknown>;
|
||||
const nestedData =
|
||||
obj.data && typeof obj.data === "object"
|
||||
? (obj.data as Record<string, unknown>)
|
||||
: undefined;
|
||||
const nestedDl =
|
||||
nestedData?.dataLink && typeof nestedData.dataLink === "object"
|
||||
? (nestedData.dataLink as Record<string, unknown>)
|
||||
: obj.dataLink && typeof obj.dataLink === "object"
|
||||
? (obj.dataLink as Record<string, unknown>)
|
||||
: undefined;
|
||||
const id =
|
||||
typeof obj.id === "string" && obj.id.trim()
|
||||
? obj.id.trim()
|
||||
: typeof nestedDl?.id === "string" && nestedDl.id.trim()
|
||||
? nestedDl.id.trim()
|
||||
: undefined;
|
||||
const name =
|
||||
typeof obj.name === "string" && obj.name.trim()
|
||||
? obj.name.trim()
|
||||
: typeof nestedDl?.name === "string" && nestedDl.name.trim()
|
||||
? nestedDl.name.trim()
|
||||
: undefined;
|
||||
const active =
|
||||
typeof obj.active === "boolean"
|
||||
? obj.active
|
||||
: typeof nestedDl?.active === "boolean"
|
||||
? nestedDl.active
|
||||
: undefined;
|
||||
return { id, name, active };
|
||||
}
|
||||
|
||||
/**
|
||||
* 对业务对象记录集合执行数据健康度体检:
|
||||
* 1. 必填/关键字段缺失检查 (MISSING_FIELD)
|
||||
* 2. 关联对象/档案停用检查 (DISABLED_REFERENCE)
|
||||
* 3. 跨表关联同名维度一致性检查 (CROSS_LEDGER_MISSING_SYNC / CROSS_LEDGER_MISMATCH)
|
||||
*/
|
||||
export function auditEntityRecords(
|
||||
records: DatalinkRecord[],
|
||||
entity: DatalinkEntity,
|
||||
options: { checkFields?: string[]; activeOnly?: boolean; total?: number } = {}
|
||||
): DatalinkAuditReport {
|
||||
const bareEntityId = entity.id.startsWith("$") ? entity.id.slice(1) : entity.id;
|
||||
const nameField = entity.fields.find(
|
||||
(f) => f.label === "名称" || f.label === "标题" || f.name === `E_${bareEntityId}_name` || f.name.endsWith("_name")
|
||||
);
|
||||
const codeField = entity.fields.find(
|
||||
(f) => f.label === "编码" || f.name === `E_${bareEntityId}_code` || f.name.endsWith("_code")
|
||||
);
|
||||
|
||||
// 解析需要检查缺失的字段集合
|
||||
const explicitSelectors = (options.checkFields ?? []).map((s) => s.trim()).filter(Boolean);
|
||||
const fieldsToCheck: DatalinkField[] =
|
||||
explicitSelectors.length > 0
|
||||
? explicitSelectors.map((selector) => {
|
||||
const found = entity.fields.find(
|
||||
(f) =>
|
||||
f.name === selector ||
|
||||
f.label === selector ||
|
||||
f.name === `E_${bareEntityId}_${selector}`
|
||||
);
|
||||
return (
|
||||
found ?? {
|
||||
name: selector.startsWith("E_") ? selector : `E_${bareEntityId}_${selector}`,
|
||||
label: selector,
|
||||
type: "text",
|
||||
}
|
||||
);
|
||||
})
|
||||
: entity.fields.filter(
|
||||
(f) =>
|
||||
f.optional === false ||
|
||||
f.type === "dimension" ||
|
||||
f.type === "dataLink"
|
||||
);
|
||||
|
||||
const dataLinkFields = entity.fields.filter((f) => f.type === "dataLink");
|
||||
const dimensionFields = entity.fields.filter((f) => f.type === "dimension");
|
||||
|
||||
const issues: DatalinkAuditIssue[] = [];
|
||||
const suggestedPatchesMap = new Map<
|
||||
string,
|
||||
{ id: string; code: string; name: string; form: Record<string, string>; reasons: string[] }
|
||||
>();
|
||||
const affectedRecordIds = new Set<string>();
|
||||
let auditedRecords = 0;
|
||||
|
||||
let missingFieldCount = 0;
|
||||
let disabledReferenceCount = 0;
|
||||
let crossLedgerMissingSyncCount = 0;
|
||||
let crossLedgerMismatchCount = 0;
|
||||
|
||||
for (const rawRecord of records) {
|
||||
const dl =
|
||||
rawRecord.dataLink &&
|
||||
typeof rawRecord.dataLink === "object" &&
|
||||
!Array.isArray(rawRecord.dataLink)
|
||||
? (rawRecord.dataLink as Record<string, unknown>)
|
||||
: (rawRecord as Record<string, unknown>);
|
||||
const recordId = String(dl.id ?? rawRecord.id ?? "");
|
||||
const active = (dl.active ?? rawRecord.active) !== false;
|
||||
if (options.activeOnly && !active) continue;
|
||||
|
||||
auditedRecords++;
|
||||
const recordName = String(
|
||||
dl.name ??
|
||||
dl["名称"] ??
|
||||
(nameField ? dl[nameField.name] : undefined) ??
|
||||
dl[`E_${bareEntityId}_name`] ??
|
||||
""
|
||||
);
|
||||
const recordCode = String(
|
||||
dl.code ??
|
||||
dl["编码"] ??
|
||||
(codeField ? dl[codeField.name] : undefined) ??
|
||||
dl[`E_${bareEntityId}_code`] ??
|
||||
""
|
||||
);
|
||||
|
||||
const getFieldVal = (field: DatalinkField): unknown =>
|
||||
dl[field.name] ??
|
||||
dl[`E_${bareEntityId}_${field.name}`] ??
|
||||
(dl.form && typeof dl.form === "object"
|
||||
? (dl.form as Record<string, unknown>)[field.name]
|
||||
: undefined) ??
|
||||
dl[field.label];
|
||||
|
||||
// 1. 必填/关键字段缺失检查
|
||||
for (const field of fieldsToCheck) {
|
||||
const val = getFieldVal(field);
|
||||
if (isEmptyFieldValue(val)) {
|
||||
missingFieldCount++;
|
||||
affectedRecordIds.add(recordId);
|
||||
issues.push({
|
||||
recordId,
|
||||
recordCode,
|
||||
recordName,
|
||||
active,
|
||||
type: "MISSING_FIELD",
|
||||
field: field.name,
|
||||
fieldLabel: field.label || field.name,
|
||||
message: `字段 [${field.label || field.name}] (${field.name}) 为空`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 关联对象/档案停用检查
|
||||
for (const field of entity.fields) {
|
||||
if (field.type !== "dimension" && field.type !== "dataLink") continue;
|
||||
const val = getFieldVal(field);
|
||||
const items = Array.isArray(val) ? val : val ? [val] : [];
|
||||
for (const item of items) {
|
||||
const refInfo = extractRefIdAndName(item);
|
||||
if (refInfo.active === false) {
|
||||
disabledReferenceCount++;
|
||||
affectedRecordIds.add(recordId);
|
||||
issues.push({
|
||||
recordId,
|
||||
recordCode,
|
||||
recordName,
|
||||
active,
|
||||
type: "DISABLED_REFERENCE",
|
||||
field: field.name,
|
||||
fieldLabel: field.label || field.name,
|
||||
actualId: refInfo.id,
|
||||
actualName: refInfo.name,
|
||||
message: `字段 [${field.label || field.name}] 引用的${
|
||||
field.type === "dataLink" ? "业务对象记录" : "维度档案"
|
||||
} [${refInfo.name || refInfo.id || "-"}] (${refInfo.id || "-"}) 已停用 (active=false)`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 跨表关联同名维度一致性检查
|
||||
for (const linkField of dataLinkFields) {
|
||||
const linkVal = getFieldVal(linkField);
|
||||
if (!linkVal || typeof linkVal !== "object" || Array.isArray(linkVal)) continue;
|
||||
const linkObj = linkVal as Record<string, unknown>;
|
||||
const parentDl =
|
||||
linkObj.data &&
|
||||
typeof linkObj.data === "object" &&
|
||||
(linkObj.data as Record<string, unknown>).dataLink &&
|
||||
typeof (linkObj.data as Record<string, unknown>).dataLink === "object"
|
||||
? ((linkObj.data as Record<string, unknown>).dataLink as Record<string, unknown>)
|
||||
: linkObj.dataLink && typeof linkObj.dataLink === "object"
|
||||
? (linkObj.dataLink as Record<string, unknown>)
|
||||
: linkObj;
|
||||
const linkedRecordId = String(parentDl.id ?? linkObj.id ?? "");
|
||||
|
||||
for (const dimField of dimensionFields) {
|
||||
const entityPrefix = `E_${bareEntityId}_`;
|
||||
const suffix = dimField.name.startsWith(entityPrefix)
|
||||
? dimField.name.slice(entityPrefix.length)
|
||||
: dimField.name.replace(/^E_[^_]+_/, "");
|
||||
const parentKey = Object.keys(parentDl).find(
|
||||
(k) =>
|
||||
k === dimField.label ||
|
||||
k === suffix ||
|
||||
k.endsWith(`_${suffix}`) ||
|
||||
(Boolean(dimField.label) && k.endsWith(`_${dimField.label}`))
|
||||
);
|
||||
if (!parentKey) continue;
|
||||
|
||||
const parentRef = extractRefIdAndName(parentDl[parentKey]);
|
||||
if (!parentRef.id) continue;
|
||||
|
||||
const childRef = extractRefIdAndName(getFieldVal(dimField));
|
||||
if (!childRef.id) {
|
||||
crossLedgerMissingSyncCount++;
|
||||
affectedRecordIds.add(recordId);
|
||||
const reason = `子表字段 [${dimField.label || dimField.name}] 为空,但关联 [${
|
||||
linkField.label || linkField.name
|
||||
}] (${linkedRecordId}) 中同名字段有值 [${parentRef.name || parentRef.id}] (${
|
||||
parentRef.id
|
||||
}),建议回填修复`;
|
||||
issues.push({
|
||||
recordId,
|
||||
recordCode,
|
||||
recordName,
|
||||
active,
|
||||
type: "CROSS_LEDGER_MISSING_SYNC",
|
||||
field: dimField.name,
|
||||
fieldLabel: dimField.label || dimField.name,
|
||||
linkedField: linkField.name,
|
||||
linkedFieldLabel: linkField.label || linkField.name,
|
||||
linkedRecordId,
|
||||
expectedId: parentRef.id,
|
||||
expectedName: parentRef.name,
|
||||
message: reason,
|
||||
});
|
||||
|
||||
const existingPatch = suggestedPatchesMap.get(recordId) ?? {
|
||||
id: recordId,
|
||||
code: recordCode,
|
||||
name: recordName,
|
||||
form: {},
|
||||
reasons: [],
|
||||
};
|
||||
existingPatch.form[dimField.name] = parentRef.id;
|
||||
existingPatch.reasons.push(
|
||||
`${dimField.label || dimField.name} <- ${parentRef.name || parentRef.id} (${parentRef.id})`
|
||||
);
|
||||
suggestedPatchesMap.set(recordId, existingPatch);
|
||||
} else if (childRef.id !== parentRef.id) {
|
||||
crossLedgerMismatchCount++;
|
||||
affectedRecordIds.add(recordId);
|
||||
issues.push({
|
||||
recordId,
|
||||
recordCode,
|
||||
recordName,
|
||||
active,
|
||||
type: "CROSS_LEDGER_MISMATCH",
|
||||
field: dimField.name,
|
||||
fieldLabel: dimField.label || dimField.name,
|
||||
linkedField: linkField.name,
|
||||
linkedFieldLabel: linkField.label || linkField.name,
|
||||
linkedRecordId,
|
||||
actualId: childRef.id,
|
||||
actualName: childRef.name,
|
||||
expectedId: parentRef.id,
|
||||
expectedName: parentRef.name,
|
||||
message: `子表字段 [${dimField.label || dimField.name}] 当前值 [${
|
||||
childRef.name || childRef.id
|
||||
}] (${childRef.id}) 与关联 [${
|
||||
linkField.label || linkField.name
|
||||
}] (${linkedRecordId}) 中的值 [${parentRef.name || parentRef.id}] (${
|
||||
parentRef.id
|
||||
}) 不一致`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const suggestedPatches = [...suggestedPatchesMap.values()].map((item) => ({
|
||||
id: item.id,
|
||||
code: item.code,
|
||||
name: item.name,
|
||||
form: item.form,
|
||||
reason: item.reasons.join("; "),
|
||||
}));
|
||||
|
||||
return {
|
||||
entityId: entity.id,
|
||||
entityName: entity.name,
|
||||
totalRecords: options.total ?? records.length,
|
||||
auditedRecords,
|
||||
healthyRecords: Math.max(0, auditedRecords - affectedRecordIds.size),
|
||||
affectedRecordCount: affectedRecordIds.size,
|
||||
issueCount: issues.length,
|
||||
summary: {
|
||||
missingFieldCount,
|
||||
disabledReferenceCount,
|
||||
crossLedgerMissingSyncCount,
|
||||
crossLedgerMismatchCount,
|
||||
},
|
||||
issues,
|
||||
suggestedPatches,
|
||||
};
|
||||
}
|
||||
|
||||
export interface BatchEditTargetItem {
|
||||
recordId: string;
|
||||
patchForm: Record<string, unknown>;
|
||||
active?: boolean;
|
||||
}
|
||||
|
||||
export interface BatchEditItemResult {
|
||||
recordId: string;
|
||||
status: "preview" | "updated" | "failed";
|
||||
payload?: DatalinkRecordEditPayload;
|
||||
result?: Record<string, unknown>;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export async function batchSafeEditRecords(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
entity: DatalinkEntity,
|
||||
targets: BatchEditTargetItem[],
|
||||
options: { concurrency?: number; dryRun?: boolean } = {}
|
||||
): Promise<BatchEditItemResult[]> {
|
||||
const concurrency = Math.max(1, Math.min(options.concurrency ?? 8, 32));
|
||||
const results: BatchEditItemResult[] = new Array(targets.length);
|
||||
let cursor = 0;
|
||||
|
||||
const worker = async () => {
|
||||
while (true) {
|
||||
const idx = cursor++;
|
||||
if (idx >= targets.length) break;
|
||||
const target = targets[idx];
|
||||
try {
|
||||
const detail = await api.getRecordDetail(client, corpId, target.recordId);
|
||||
const payload = api.buildSafeRecordEditPayload({
|
||||
entityId: entity.id,
|
||||
recordId: target.recordId,
|
||||
detail,
|
||||
fields: entity.fields,
|
||||
patchForm: target.patchForm,
|
||||
active: target.active,
|
||||
});
|
||||
if (options.dryRun) {
|
||||
results[idx] = {
|
||||
recordId: target.recordId,
|
||||
status: "preview",
|
||||
payload,
|
||||
};
|
||||
} else {
|
||||
const res = await api.editRecord(client, corpId, payload);
|
||||
results[idx] = {
|
||||
recordId: target.recordId,
|
||||
status: "updated",
|
||||
payload,
|
||||
result: res,
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
results[idx] = {
|
||||
recordId: target.recordId,
|
||||
status: "failed",
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
await Promise.all(
|
||||
Array.from({ length: Math.min(concurrency, targets.length) }, () => worker())
|
||||
);
|
||||
return results;
|
||||
}
|
||||
|
||||
@@ -6,9 +6,20 @@ Platform 域负责工作流(EASO/Piper)以及自建应用容器的兼容能
|
||||
|
||||
```text
|
||||
src/domains/platform/
|
||||
├── types.ts # Zod schema 与类型定义
|
||||
├── api.ts # HTTP 传输层
|
||||
└── tools.ts # MCP tool 注册 + 服务层聚合函数
|
||||
├── types.ts # Zod schema 与类型定义(含 Job 执行树、失败节点、节点日志)
|
||||
├── api.ts # HTTP 传输层(含 unwrap 空安全校验与 Piper Job 5 大诊断端点)
|
||||
├── analysis.ts # 工作流静态分析(禁用状态、SKIP 无状态守卫、单据联动覆盖诊断)
|
||||
└── tools.ts # MCP tool 注册 + 服务层聚合函数
|
||||
```
|
||||
|
||||
## CLI 常用命令
|
||||
|
||||
```bash
|
||||
hose-use workflow list [--platform-id=<id>|--app-id=<id>]
|
||||
hose-use workflow get <pipelineId>
|
||||
hose-use workflow analyze <pipelineId> [--json]
|
||||
hose-use workflow logs <pipelineId> [--has-error] [--state=FAILED]
|
||||
hose-use workflow job <jobId> [--failed] [--parent=<executionId>] [--logs=<executionId>]
|
||||
```
|
||||
|
||||
## 详细文档
|
||||
|
||||
@@ -13,8 +13,102 @@ describe("Workflow static analysis", () => {
|
||||
const result = analyzeWorkflow({ id: "wf-1", label: "审批", state: 1, version: "3", tasks: [{ name: "条件", type: "condition", label: "条件", groupName: "", orderIndex: 0, levelIndex: [0], status: "", tasks: [{ name: "脚本", type: "code-js2", label: "脚本", groupName: "", orderIndex: 1, levelIndex: [0, 0], status: "", code: "return {{bill.amount}} + ctx.user.id;" }] }] } as any);
|
||||
expect(result.ast[0]?.children[0]?.path).toBe("0.0"); expect(result.dependencies[0]?.references).toEqual(["bill.amount", "user.id"]); expect(result.diagnostics).toHaveLength(0);
|
||||
});
|
||||
it("reports empty scripts and branches", () => {
|
||||
it("reports empty scripts, branches, and disabled workflow state", () => {
|
||||
const result = analyzeWorkflow({ id: "wf-2", label: "异常", state: 0, version: "", tasks: [{ name: "脚本", type: "code", label: "", groupName: "", orderIndex: 0, levelIndex: [0], status: "", code: "" }, { name: "条件", type: "condition", label: "", groupName: "", orderIndex: 1, levelIndex: [1], status: "", tasks: [] }] } as any);
|
||||
expect(result.diagnostics.map((item) => item.code)).toEqual(["EMPTY_CODE", "EMPTY_BRANCH"]);
|
||||
expect(result.diagnostics.map((item) => item.code)).toEqual(["WORKFLOW_DISABLED", "EMPTY_CODE", "EMPTY_BRANCH"]);
|
||||
});
|
||||
|
||||
it("detects UNSAFE_SKIP_WITHOUT_STATUS_GUARD and LINKAGE_PRIORITY_OVERRIDE", () => {
|
||||
const wf = {
|
||||
id: "886351399301758976",
|
||||
label: "【生产】每30分钟创建采购申请单",
|
||||
state: 1,
|
||||
version: "10",
|
||||
tasks: [
|
||||
{
|
||||
name: "every_0",
|
||||
type: "every",
|
||||
label: "循环每条支付计划",
|
||||
groupName: "control",
|
||||
orderIndex: 1,
|
||||
levelIndex: [0],
|
||||
status: "",
|
||||
tasks: [
|
||||
{
|
||||
name: "ekuaibao_flow_create_task_0",
|
||||
type: "flow-create-task",
|
||||
label: "创建预付申请单",
|
||||
groupName: "ekuaibao",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0, 0],
|
||||
status: "",
|
||||
onError: { defaultAction: "SKIP" },
|
||||
inputs: {
|
||||
specificationId: "ID01TxgE3fhD6n",
|
||||
form: {
|
||||
u_关联合同流程: "{{every_0.item.E_contract}}",
|
||||
u_我方签约主体: "{{every_0.item.E_company}}",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "ekuaibao_datalink_edit_0",
|
||||
type: "ekuaibao-datalink-edit",
|
||||
label: "更新支付计划状态为创建成功",
|
||||
groupName: "ekuaibao",
|
||||
orderIndex: 1,
|
||||
levelIndex: [0, 1],
|
||||
status: "",
|
||||
inputs: {
|
||||
dataLinkId: "{{every_0.item.id}}",
|
||||
form: {
|
||||
状态: "创建成功",
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const specifications = {
|
||||
ID01TxgE3fhD6n: {
|
||||
id: "ID01TxgE3fhD6n",
|
||||
name: "预付申请单",
|
||||
form: [
|
||||
{
|
||||
id: "f1",
|
||||
name: "u_关联合同流程",
|
||||
label: "关联合同流程",
|
||||
type: "dataLink",
|
||||
optional: false,
|
||||
entityId: "e23d0d5451b1ccabfd7a",
|
||||
assignmentRule: "ID01TRWvYFAulh",
|
||||
isLinkageAssignment: false,
|
||||
priorityList: [
|
||||
{ type: "LINKAGE_ASSIGNMENT", priority: 10 },
|
||||
{ type: "MANUALLY_FILL_IN", priority: 5 },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "f2",
|
||||
name: "u_我方签约主体",
|
||||
label: "我方签约主体",
|
||||
type: "dimension",
|
||||
optional: false,
|
||||
isLinkageAssignment: true,
|
||||
priorityList: [
|
||||
{ type: "LINKAGE_ASSIGNMENT", priority: 10 },
|
||||
{ type: "MANUALLY_FILL_IN", priority: 5 },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const result = analyzeWorkflow(wf as any, { specifications: specifications as any });
|
||||
const codes = result.diagnostics.map((d) => d.code);
|
||||
expect(codes).toContain("UNSAFE_SKIP_WITHOUT_STATUS_GUARD");
|
||||
expect(codes).toContain("LINKAGE_PRIORITY_OVERRIDE");
|
||||
});
|
||||
});
|
||||
@@ -1,19 +1,400 @@
|
||||
import type { WorkflowDetail, WorkflowTask } from "./types.js";
|
||||
|
||||
export interface WorkflowAstNode { type: string; name: string; label: string; path: string; orderIndex: number; levelIndex: number[]; children: WorkflowAstNode[]; }
|
||||
export interface WorkflowDependency { path: string; taskType: string; references: string[]; }
|
||||
export interface WorkflowDiagnostic { severity: "warning" | "error"; code: string; path: string; message: string; }
|
||||
export interface WorkflowAnalysis { workflow: { id: string; label: string; state: number; version: string }; ast: WorkflowAstNode[]; dependencies: WorkflowDependency[]; diagnostics: WorkflowDiagnostic[]; }
|
||||
export interface WorkflowAstNode {
|
||||
type: string;
|
||||
name: string;
|
||||
label: string;
|
||||
path: string;
|
||||
orderIndex: number;
|
||||
levelIndex: number[];
|
||||
children: WorkflowAstNode[];
|
||||
}
|
||||
|
||||
export interface WorkflowDependency {
|
||||
path: string;
|
||||
taskType: string;
|
||||
references: string[];
|
||||
}
|
||||
|
||||
export interface WorkflowDiagnostic {
|
||||
severity: "warning" | "error";
|
||||
code: string;
|
||||
path: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface WorkflowAnalysis {
|
||||
workflow: { id: string; label: string; state: number; version: string };
|
||||
ast: WorkflowAstNode[];
|
||||
dependencies: WorkflowDependency[];
|
||||
diagnostics: WorkflowDiagnostic[];
|
||||
}
|
||||
|
||||
export interface WorkflowFormSpecComponentLike {
|
||||
name?: string;
|
||||
field?: string;
|
||||
label?: string;
|
||||
type?: string;
|
||||
isLinkageAssignment?: boolean;
|
||||
assignmentRule?: string | null;
|
||||
priorityList?: Array<{ type: string; label?: string; priority?: number; value?: number }>;
|
||||
priority?: Array<{ type: string; label?: string; priority?: number; value?: number }> | null;
|
||||
}
|
||||
|
||||
export interface WorkflowFormSpecLike {
|
||||
id: string;
|
||||
name?: string;
|
||||
components?: WorkflowFormSpecComponentLike[];
|
||||
}
|
||||
|
||||
export interface AnalyzeWorkflowOptions {
|
||||
specifications?: Record<string, WorkflowFormSpecLike | undefined>;
|
||||
}
|
||||
|
||||
const KNOWN_TYPES = new Set([
|
||||
"webhook",
|
||||
"crontab",
|
||||
"clock",
|
||||
"condition",
|
||||
"every",
|
||||
"stop",
|
||||
"http",
|
||||
"flow-detail",
|
||||
"code",
|
||||
"code-js2",
|
||||
"ekuaibao-datalink-filter",
|
||||
"ekuaibao-datalink-create",
|
||||
"ekuaibao-datalink-edit",
|
||||
"ekuaibao-datalink-delete",
|
||||
"data-convert",
|
||||
"flow-create-task",
|
||||
]);
|
||||
|
||||
const KNOWN_TYPES = new Set(["webhook", "condition", "every", "stop", "http", "flow-detail", "code", "code-js2", "ekuaibao-datalink-filter", "ekuaibao-datalink-create", "data-convert", "flow-create-task"]);
|
||||
function referencesFromTask(task: WorkflowTask): string[] {
|
||||
const code = typeof task.code === "string" ? task.code : "";
|
||||
const values = [...code.matchAll(/\{\{\s*([^{}]+?)\s*\}\}|\b(?:ctx|input|output|context)\.([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)/g)].map((match) => (match[1] || match[2] || "").trim()).filter(Boolean);
|
||||
const values = [
|
||||
...code.matchAll(
|
||||
/\{\{\s*([^{}]+?)\s*\}\}|\b(?:ctx|input|output|context)\.([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)/g
|
||||
),
|
||||
]
|
||||
.map((match) => (match[1] || match[2] || "").trim())
|
||||
.filter(Boolean);
|
||||
return [...new Set(values)];
|
||||
}
|
||||
function toAst(tasks: WorkflowTask[], parentPath = ""): WorkflowAstNode[] { return tasks.map((task, index) => { const path = parentPath ? `${parentPath}.${index}` : String(index); return { type: task.type, name: task.name, label: task.label || task.displayName || "", path, orderIndex: task.orderIndex, levelIndex: task.levelIndex, children: toAst(task.tasks || [], path) }; }); }
|
||||
export function analyzeWorkflow(detail: WorkflowDetail): WorkflowAnalysis {
|
||||
const ast = toAst(detail.tasks); const dependencies: WorkflowDependency[] = []; const diagnostics: WorkflowDiagnostic[] = [];
|
||||
const visit = (tasks: WorkflowTask[], parentPath = "") => tasks.forEach((task, index) => { const path = parentPath ? `${parentPath}.${index}` : String(index); const refs = referencesFromTask(task); if (refs.length) dependencies.push({ path, taskType: task.type, references: refs }); if ((task.type === "code" || task.type === "code-js2") && !String(task.code || "").trim()) diagnostics.push({ severity: "error", code: "EMPTY_CODE", path, message: "代码节点没有可执行脚本" }); if ((task.type === "condition" || task.type === "every") && !(task.tasks || []).length) diagnostics.push({ severity: "warning", code: "EMPTY_BRANCH", path, message: `${task.type} 控制节点没有子节点` }); if (!KNOWN_TYPES.has(task.type)) diagnostics.push({ severity: "warning", code: "UNKNOWN_TASK_TYPE", path, message: `未收录的节点类型: ${task.type}` }); visit(task.tasks || [], path); });
|
||||
visit(detail.tasks); return { workflow: { id: detail.id, label: detail.label, state: detail.state, version: detail.version }, ast, dependencies, diagnostics };
|
||||
|
||||
function toAst(tasks: WorkflowTask[], parentPath = ""): WorkflowAstNode[] {
|
||||
return tasks.map((task, index) => {
|
||||
const path = parentPath ? `${parentPath}.${index}` : String(index);
|
||||
return {
|
||||
type: task.type,
|
||||
name: task.name,
|
||||
label: task.label || task.displayName || "",
|
||||
path,
|
||||
orderIndex: task.orderIndex,
|
||||
levelIndex: task.levelIndex,
|
||||
children: toAst(task.tasks || [], path),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function getTaskSpecificationId(task: WorkflowTask): string | undefined {
|
||||
const raw = task as Record<string, unknown>;
|
||||
if (typeof raw.specificationId === "string" && raw.specificationId.trim()) {
|
||||
return raw.specificationId.trim();
|
||||
}
|
||||
if (Array.isArray(task.inputs)) {
|
||||
const found = task.inputs.find((item) => item.key === "specificationId");
|
||||
if (found && typeof found.value === "string" && found.value.trim()) {
|
||||
return found.value.trim();
|
||||
}
|
||||
} else if (raw.inputs && typeof raw.inputs === "object") {
|
||||
const specId = (raw.inputs as Record<string, unknown>).specificationId;
|
||||
if (typeof specId === "string" && specId.trim()) {
|
||||
return specId.trim();
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function getTaskFormEntries(
|
||||
task: WorkflowTask
|
||||
): Array<{ key?: string; label?: string; type?: string; value?: unknown }> {
|
||||
const raw = task as Record<string, unknown>;
|
||||
if (Array.isArray(raw.form)) {
|
||||
return raw.form.filter(
|
||||
(item): item is { key?: string; label?: string; type?: string; value?: unknown } =>
|
||||
Boolean(item && typeof item === "object")
|
||||
);
|
||||
}
|
||||
if (raw.form && typeof raw.form === "object") {
|
||||
return Object.entries(raw.form as Record<string, unknown>).map(([key, value]) => ({
|
||||
key,
|
||||
value,
|
||||
}));
|
||||
}
|
||||
if (Array.isArray(task.inputs)) {
|
||||
const formInput = task.inputs.find((item) => item.key === "form");
|
||||
if (formInput && Array.isArray(formInput.value)) {
|
||||
return formInput.value.filter(
|
||||
(item: unknown): item is { key?: string; label?: string; type?: string; value?: unknown } =>
|
||||
Boolean(item && typeof item === "object")
|
||||
);
|
||||
}
|
||||
if (formInput && formInput.value && typeof formInput.value === "object") {
|
||||
return Object.entries(formInput.value as Record<string, unknown>).map(([key, value]) => ({
|
||||
key,
|
||||
value,
|
||||
}));
|
||||
}
|
||||
} else if (raw.inputs && typeof raw.inputs === "object") {
|
||||
const formVal = (raw.inputs as Record<string, unknown>).form;
|
||||
if (Array.isArray(formVal)) {
|
||||
return formVal.filter(
|
||||
(item): item is { key?: string; label?: string; type?: string; value?: unknown } =>
|
||||
Boolean(item && typeof item === "object")
|
||||
);
|
||||
}
|
||||
if (formVal && typeof formVal === "object") {
|
||||
return Object.entries(formVal as Record<string, unknown>).map(([key, value]) => ({
|
||||
key,
|
||||
value,
|
||||
}));
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
export function extractWorkflowSpecificationIds(detail: WorkflowDetail): string[] {
|
||||
const ids = new Set<string>();
|
||||
const walk = (tasks: WorkflowTask[]) => {
|
||||
for (const task of tasks) {
|
||||
if (task.type === "flow-create-task") {
|
||||
const specId = getTaskSpecificationId(task);
|
||||
if (specId) ids.add(specId);
|
||||
}
|
||||
if (Array.isArray(task.tasks) && task.tasks.length > 0) {
|
||||
walk(task.tasks);
|
||||
}
|
||||
}
|
||||
};
|
||||
walk(detail.tasks || []);
|
||||
return [...ids];
|
||||
}
|
||||
|
||||
function taskGuardsStatusOf(task: WorkflowTask, targetTaskName: string): boolean {
|
||||
if (task.type !== "condition") return false;
|
||||
const raw = task as Record<string, unknown>;
|
||||
const filterSource = raw.combineFilters ?? raw.filters ?? task.inputs ?? raw.conditions ?? {};
|
||||
const serialized = JSON.stringify(filterSource);
|
||||
if (
|
||||
serialized.includes(`${targetTaskName}.$status`) ||
|
||||
serialized.includes(`${targetTaskName}.status`) ||
|
||||
serialized.includes(`${targetTaskName}.result`) ||
|
||||
serialized.includes(`${targetTaskName}.data`)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
return (
|
||||
serialized.includes(targetTaskName) &&
|
||||
(serialized.includes("$status") || serialized.includes("是否运行成功"))
|
||||
);
|
||||
}
|
||||
|
||||
function findUnguardedDatalinkEdits(
|
||||
tasks: WorkflowTask[],
|
||||
basePath: string,
|
||||
createTaskName: string
|
||||
): Array<{ task: WorkflowTask; path: string }> {
|
||||
const found: Array<{ task: WorkflowTask; path: string }> = [];
|
||||
tasks.forEach((task, idx) => {
|
||||
const path = `${basePath}.${idx}`;
|
||||
if (task.type === "ekuaibao-datalink-edit") {
|
||||
found.push({ task, path });
|
||||
return;
|
||||
}
|
||||
if (taskGuardsStatusOf(task, createTaskName)) {
|
||||
return;
|
||||
}
|
||||
if (Array.isArray(task.tasks) && task.tasks.length > 0) {
|
||||
found.push(...findUnguardedDatalinkEdits(task.tasks, path, createTaskName));
|
||||
}
|
||||
});
|
||||
return found;
|
||||
}
|
||||
|
||||
export function analyzeWorkflow(
|
||||
detail: WorkflowDetail,
|
||||
options: AnalyzeWorkflowOptions = {}
|
||||
): WorkflowAnalysis {
|
||||
const ast = toAst(detail.tasks);
|
||||
const dependencies: WorkflowDependency[] = [];
|
||||
const diagnostics: WorkflowDiagnostic[] = [];
|
||||
|
||||
if (detail.state === 0) {
|
||||
diagnostics.push({
|
||||
severity: "warning",
|
||||
code: "WORKFLOW_DISABLED",
|
||||
path: "workflow",
|
||||
message:
|
||||
"工作流当前处于未启用/草稿状态 (state=0),修改或排障后需 publish/toggle --state=1 方可生效",
|
||||
});
|
||||
}
|
||||
|
||||
const visit = (tasks: WorkflowTask[], parentPath = "", insideEvery = false) => {
|
||||
tasks.forEach((task, index) => {
|
||||
const path = parentPath ? `${parentPath}.${index}` : String(index);
|
||||
const refs = referencesFromTask(task);
|
||||
if (refs.length) {
|
||||
dependencies.push({ path, taskType: task.type, references: refs });
|
||||
}
|
||||
if ((task.type === "code" || task.type === "code-js2") && !String(task.code || "").trim()) {
|
||||
diagnostics.push({
|
||||
severity: "error",
|
||||
code: "EMPTY_CODE",
|
||||
path,
|
||||
message: "代码节点没有可执行脚本",
|
||||
});
|
||||
}
|
||||
if ((task.type === "condition" || task.type === "every") && !(task.tasks || []).length) {
|
||||
diagnostics.push({
|
||||
severity: "warning",
|
||||
code: "EMPTY_BRANCH",
|
||||
path,
|
||||
message: `${task.type} 控制节点没有子节点`,
|
||||
});
|
||||
}
|
||||
if (!KNOWN_TYPES.has(task.type)) {
|
||||
diagnostics.push({
|
||||
severity: "warning",
|
||||
code: "UNKNOWN_TASK_TYPE",
|
||||
path,
|
||||
message: `未收录的节点类型: ${task.type}`,
|
||||
});
|
||||
}
|
||||
|
||||
// 诊断 2: every 循环内 flow-create-task (SKIP) 后跟无状态守卫的 ekuaibao-datalink-edit
|
||||
if (insideEvery && task.type === "flow-create-task") {
|
||||
const onError = (task as Record<string, unknown>).onError as
|
||||
| { defaultAction?: string }
|
||||
| undefined;
|
||||
if (onError?.defaultAction === "SKIP") {
|
||||
const subsequentSiblings = tasks.slice(index + 1);
|
||||
const unguardedEdits: Array<{ task: WorkflowTask; path: string }> = [];
|
||||
subsequentSiblings.forEach((sibling, relIdx) => {
|
||||
const siblingIndex = index + 1 + relIdx;
|
||||
const siblingPath = parentPath ? `${parentPath}.${siblingIndex}` : String(siblingIndex);
|
||||
if (sibling.type === "ekuaibao-datalink-edit") {
|
||||
unguardedEdits.push({ task: sibling, path: siblingPath });
|
||||
} else if (!taskGuardsStatusOf(sibling, task.name) && sibling.tasks?.length) {
|
||||
unguardedEdits.push(
|
||||
...findUnguardedDatalinkEdits(sibling.tasks, siblingPath, task.name)
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
for (const edit of unguardedEdits) {
|
||||
diagnostics.push({
|
||||
severity: "warning",
|
||||
code: "UNSAFE_SKIP_WITHOUT_STATUS_GUARD",
|
||||
path: edit.path,
|
||||
message: `节点 [${task.label || task.name}] (${task.name}) 配置了报错跳过(SKIP),但后续台账更新节点 [${edit.task.label || edit.task.name}] (${edit.task.name}) 未校验其执行状态(如 ${task.name}.$status),前序建单失败时仍会误改台账状态!`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 诊断 3: flow-create-task 表单字段联动覆盖告警 (LINKAGE_ASSIGNMENT > MANUALLY_FILL_IN)
|
||||
if (task.type === "flow-create-task") {
|
||||
const specId = getTaskSpecificationId(task);
|
||||
const spec = specId ? options.specifications?.[specId] : undefined;
|
||||
const formEntries = getTaskFormEntries(task).filter(
|
||||
(entry) =>
|
||||
entry.value !== undefined &&
|
||||
entry.value !== null &&
|
||||
String(entry.value).trim() !== ""
|
||||
);
|
||||
|
||||
const specComponents =
|
||||
spec?.components ??
|
||||
(Array.isArray((spec as unknown as Record<string, unknown> | undefined)?.form)
|
||||
? ((spec as unknown as Record<string, unknown>).form as WorkflowFormSpecComponentLike[])
|
||||
: []);
|
||||
|
||||
if (spec && specComponents.length && formEntries.length > 0) {
|
||||
const matchedComponents = specComponents.filter((comp) => {
|
||||
const compKey = comp.name || comp.field || "";
|
||||
return formEntries.some(
|
||||
(entry) =>
|
||||
(Boolean(compKey) && entry.key === compKey) ||
|
||||
(Boolean(entry.label) && Boolean(comp.label) && entry.label === comp.label)
|
||||
);
|
||||
});
|
||||
|
||||
const linkageSources = matchedComponents.filter(
|
||||
(comp) =>
|
||||
Boolean(comp.assignmentRule) ||
|
||||
(comp.type === "dataLink" && comp.isLinkageAssignment === true)
|
||||
);
|
||||
|
||||
for (const src of linkageSources) {
|
||||
const srcKey = src.name || src.field || src.label || "";
|
||||
const overrideTargets = matchedComponents
|
||||
.filter((comp) => (comp.name || comp.field || comp.label || "") !== srcKey)
|
||||
.map((comp) => {
|
||||
const list = comp.priorityList || comp.priority || [];
|
||||
const linkage = list.find((p) => p.type === "LINKAGE_ASSIGNMENT");
|
||||
const manual = list.find((p) => p.type === "MANUALLY_FILL_IN");
|
||||
const linkagePriority = linkage?.priority ?? linkage?.value;
|
||||
const manualPriority = manual?.priority ?? manual?.value;
|
||||
if (
|
||||
linkagePriority !== undefined &&
|
||||
manualPriority !== undefined &&
|
||||
linkagePriority > manualPriority
|
||||
) {
|
||||
return {
|
||||
comp,
|
||||
compKey: comp.name || comp.field || comp.label || "",
|
||||
linkagePriority,
|
||||
manualPriority,
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
})
|
||||
.filter((item): item is NonNullable<typeof item> => Boolean(item));
|
||||
|
||||
if (overrideTargets.length > 0) {
|
||||
const affectedDesc = overrideTargets
|
||||
.map(
|
||||
(t) =>
|
||||
`${t.comp.label || t.compKey}(${t.compKey}: LINKAGE_ASSIGNMENT(${t.linkagePriority}) > MANUALLY_FILL_IN(${t.manualPriority}))`
|
||||
)
|
||||
.join("、");
|
||||
diagnostics.push({
|
||||
severity: "warning",
|
||||
code: "LINKAGE_PRIORITY_OVERRIDE",
|
||||
path,
|
||||
message: `表单模板 [${spec.name || spec.id}] 中字段 [${src.label || srcKey}] (${srcKey}) 存在业务对象联动配置 (isLinkageAssignment=${Boolean(src.isLinkageAssignment)}, assignmentRule=${src.assignmentRule || "-"}),且当前节点同时传入了 [${affectedDesc}],联动赋值优先级高于手动/API 传入,显式传入的值可能被关联对象中的字段值覆盖!`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
visit(task.tasks || [], path, insideEvery || task.type === "every");
|
||||
});
|
||||
};
|
||||
|
||||
visit(detail.tasks);
|
||||
return {
|
||||
workflow: {
|
||||
id: detail.id,
|
||||
label: detail.label,
|
||||
state: detail.state,
|
||||
version: detail.version,
|
||||
},
|
||||
ast,
|
||||
dependencies,
|
||||
diagnostics,
|
||||
};
|
||||
}
|
||||
|
||||
+113
-5
@@ -1,5 +1,6 @@
|
||||
import { z } from "zod";
|
||||
import { KyInstance } from "ky";
|
||||
import { AuthenticationError, EkbApiError } from "../../core/errors.js";
|
||||
import {
|
||||
PlatformSchema,
|
||||
WorkflowPageSchema,
|
||||
@@ -9,6 +10,10 @@ import {
|
||||
WorkflowSnapshotPageSchema,
|
||||
WorkflowLogPageSchema,
|
||||
WorkflowJobSchema,
|
||||
WorkflowJobDetailSchema,
|
||||
WorkflowTaskExecutionSchema,
|
||||
WorkflowExecutionPageSchema,
|
||||
WorkflowExecutionLogSchema,
|
||||
WorkflowDslSchema,
|
||||
StaffSchema,
|
||||
WebhookInfoSchema,
|
||||
@@ -16,10 +21,35 @@ import {
|
||||
} from "./types.js";
|
||||
import type { WorkflowState } from "./types.js";
|
||||
|
||||
// Helper to unwrap { data: T } response
|
||||
async function unwrap<T>(response: Response, schema: z.ZodType<T>): Promise<T> {
|
||||
const json = (await response.json()) as { data: unknown };
|
||||
return schema.parse(json.data);
|
||||
// Helper to unwrap { data: T } / { value: T } response with null/error defense
|
||||
export async function unwrap<T>(response: Response, schema: z.ZodType<T>): Promise<T> {
|
||||
const raw = await response.json();
|
||||
const record =
|
||||
raw !== null && typeof raw === "object" && !Array.isArray(raw)
|
||||
? (raw as Record<string, unknown>)
|
||||
: undefined;
|
||||
|
||||
const code = record?.code;
|
||||
const hasCodeError = code !== undefined && code !== null && Number(code) !== 200;
|
||||
const hasWrapper = Boolean(record && ("data" in record || "value" in record));
|
||||
const payload = hasWrapper ? (record!.data ?? record!.value) : raw;
|
||||
|
||||
if (hasCodeError || payload === null || payload === undefined) {
|
||||
const status = typeof code === "number" ? code : response.status || 500;
|
||||
const urlInfo = response.url ? ` [${response.url}]` : "";
|
||||
const reason =
|
||||
(typeof record?.msg === "string" && record.msg.trim()) ||
|
||||
(typeof record?.errorMessage === "string" && record.errorMessage.trim()) ||
|
||||
(typeof record?.message === "string" && record.message.trim()) ||
|
||||
"服务端返回空数据 (可能凭证已过期或无该自建应用权限)";
|
||||
const fullMsg = `EASO/Piper API 请求失败 (HTTP ${response.status || status}${urlInfo}): ${reason}`;
|
||||
if (status === 401 || status === 403 || Number(code) === 401 || Number(code) === 403) {
|
||||
throw new AuthenticationError(fullMsg);
|
||||
}
|
||||
throw new EkbApiError(fullMsg, "EASO_API_ERROR", status);
|
||||
}
|
||||
|
||||
return schema.parse(payload);
|
||||
}
|
||||
|
||||
// Helper for simple success responses
|
||||
@@ -146,7 +176,7 @@ export async function toggleWorkflow(
|
||||
return ok(response);
|
||||
}
|
||||
|
||||
// ── 运行中的任务(Piper)──────────────────────────────────────────────────────
|
||||
// ── 运行中的任务与单次 Job 执行详情(Piper)────────────────────────────────────
|
||||
|
||||
export async function listRunningJobs(
|
||||
client: KyInstance,
|
||||
@@ -159,6 +189,83 @@ export async function listRunningJobs(
|
||||
return unwrap(response, z.array(WorkflowJobSchema));
|
||||
}
|
||||
|
||||
export async function getJob(
|
||||
client: KyInstance,
|
||||
jobId: string
|
||||
): Promise<import("./types.js").WorkflowJobDetail> {
|
||||
const response = await client.get(`api/easo/jobs/${jobId}`);
|
||||
return unwrap(response, WorkflowJobDetailSchema);
|
||||
}
|
||||
|
||||
export async function getJobExecutionTree(
|
||||
client: KyInstance,
|
||||
jobId: string,
|
||||
options: { page?: number; pageSize?: number } = {}
|
||||
): Promise<import("./types.js").WorkflowTaskExecution[]> {
|
||||
const response = await client.get(`api/easo/jobs/${jobId}/execution`, {
|
||||
searchParams: {
|
||||
number: String(options.page ?? 1),
|
||||
pageSize: String(options.pageSize ?? 100),
|
||||
},
|
||||
});
|
||||
const parsed = await unwrap(
|
||||
response,
|
||||
z.union([z.array(WorkflowTaskExecutionSchema), WorkflowExecutionPageSchema])
|
||||
);
|
||||
return Array.isArray(parsed) ? parsed : parsed.items;
|
||||
}
|
||||
|
||||
export async function getJobFailedExecutions(
|
||||
client: KyInstance,
|
||||
jobId: string
|
||||
): Promise<import("./types.js").WorkflowExecutionPage> {
|
||||
const response = await client.get(`api/easo/jobs/${jobId}/execution/level/failed`);
|
||||
const parsed = await unwrap(
|
||||
response,
|
||||
z.union([WorkflowExecutionPageSchema, z.array(WorkflowTaskExecutionSchema)])
|
||||
);
|
||||
if (Array.isArray(parsed)) {
|
||||
return {
|
||||
number: 1,
|
||||
size: parsed.length,
|
||||
totalPages: 1,
|
||||
totalItems: parsed.length,
|
||||
items: parsed,
|
||||
};
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
export async function getJobExecutionLevel(
|
||||
client: KyInstance,
|
||||
jobId: string,
|
||||
options: { parentId: string; page?: number; pageSize?: number }
|
||||
): Promise<import("./types.js").WorkflowExecutionPage> {
|
||||
const response = await client.get(`api/easo/jobs/${jobId}/execution/level`, {
|
||||
searchParams: {
|
||||
parentId: options.parentId,
|
||||
number: String(options.page ?? 1),
|
||||
pageSize: String(options.pageSize ?? 20),
|
||||
},
|
||||
});
|
||||
return unwrap(response, WorkflowExecutionPageSchema);
|
||||
}
|
||||
|
||||
export async function getExecutionLogs(
|
||||
client: KyInstance,
|
||||
executionId: string
|
||||
): Promise<import("./types.js").WorkflowExecutionLog[]> {
|
||||
const response = await client.get(`api/easo/executions/${executionId}/logs`);
|
||||
const parsed = await unwrap(
|
||||
response,
|
||||
z.union([
|
||||
z.array(WorkflowExecutionLogSchema),
|
||||
z.object({ items: z.array(WorkflowExecutionLogSchema).default([]) }).passthrough(),
|
||||
])
|
||||
);
|
||||
return Array.isArray(parsed) ? parsed : parsed.items;
|
||||
}
|
||||
|
||||
// ── DSL 配置(Piper)──────────────────────────────────────────────────────────
|
||||
|
||||
export async function listDsl(
|
||||
@@ -199,3 +306,4 @@ export async function sampleWorkflowData(
|
||||
const response = await client.post(`api/easo/pipelines/${pipelineId}/sampleData`);
|
||||
return WorkflowSampleDataSchema.parse(await response.json());
|
||||
}
|
||||
|
||||
@@ -338,17 +338,87 @@ export const WorkflowChargeSchema = z.object({
|
||||
remaining: z.number().default(0),
|
||||
});
|
||||
|
||||
// ── 运行中的任务 ──────────────────────────────────────────────────────────────
|
||||
// ── 运行中的任务与单次 Job 执行详情 ──────────────────────────────────────────
|
||||
|
||||
export const WorkflowJobSchema = z.object({
|
||||
id: z.string(),
|
||||
pipelineId: z.string(),
|
||||
status: z.string().default(""),
|
||||
startTime: z.string().optional(),
|
||||
endTime: z.string().optional(),
|
||||
startTime: z.union([z.string(), z.number()]).optional(),
|
||||
endTime: z.union([z.string(), z.number()]).optional(),
|
||||
triggerType: z.string().default(""),
|
||||
});
|
||||
|
||||
export const WorkflowJobDetailSchema = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
pipelineId: z.string().default(""),
|
||||
label: z.string().default(""),
|
||||
status: z.string().default(""),
|
||||
runType: z.string().default(""),
|
||||
startTime: z.union([z.number(), z.string()]).nullable().optional(),
|
||||
endTime: z.union([z.number(), z.string()]).nullable().optional(),
|
||||
createTime: z.union([z.number(), z.string()]).nullable().optional(),
|
||||
inputs: z.any().optional(),
|
||||
outputs: z.any().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export const WorkflowExecutionErrorSchema = z
|
||||
.object({
|
||||
message: z.string().default(""),
|
||||
stackTrace: z.array(z.string()).nullish().transform((v) => v ?? []),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export const WorkflowExecutionLogSchema = z
|
||||
.object({
|
||||
id: z.union([z.string(), z.number()]).optional(),
|
||||
level: z.string().default("INFO"),
|
||||
message: z.string().default(""),
|
||||
createAt: z.union([z.string(), z.number()]).optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export const WorkflowTaskExecutionSchema = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
parentId: z.string().nullable().optional(),
|
||||
jobId: z.string().optional(),
|
||||
pipelineId: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
displayName: z.string().nullable().optional(),
|
||||
label: z.string().nullable().optional(),
|
||||
type: z.string().default(""),
|
||||
orderIndex: z.number().optional(),
|
||||
levelIndex: z.array(z.number()).optional(),
|
||||
status: z.string().default(""),
|
||||
executionTime: z.number().optional(),
|
||||
startTime: z.union([z.number(), z.string()]).nullable().optional(),
|
||||
endTime: z.union([z.number(), z.string()]).nullable().optional(),
|
||||
createTime: z.union([z.number(), z.string()]).nullable().optional(),
|
||||
currentLoopPath: z.string().nullable().optional(),
|
||||
error: WorkflowExecutionErrorSchema.nullable().optional(),
|
||||
output: z.any().optional(),
|
||||
form: z.record(z.string(), z.any()).nullable().optional(),
|
||||
details: z.record(z.string(), z.any()).nullable().optional(),
|
||||
executionLogs: z.array(z.any()).optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export const WorkflowExecutionPageSchema = z
|
||||
.object({
|
||||
number: z.number().default(1),
|
||||
size: z.number().default(20),
|
||||
totalPages: z.number().default(0),
|
||||
totalItems: z.number().default(0),
|
||||
items: z
|
||||
.array(z.union([WorkflowTaskExecutionSchema, z.array(WorkflowTaskExecutionSchema)]))
|
||||
.default([])
|
||||
.transform((arr) => arr.flat()),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
// ── DSL 配置 ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export const WorkflowDslSchema = z.object({
|
||||
@@ -423,6 +493,11 @@ export type WorkflowLogItem = z.infer<typeof WorkflowLogItemSchema>;
|
||||
export type WorkflowLogPage = z.infer<typeof WorkflowLogPageSchema>;
|
||||
export type WorkflowCharge = z.infer<typeof WorkflowChargeSchema>;
|
||||
export type WorkflowJob = z.infer<typeof WorkflowJobSchema>;
|
||||
export type WorkflowJobDetail = z.infer<typeof WorkflowJobDetailSchema>;
|
||||
export type WorkflowExecutionError = z.infer<typeof WorkflowExecutionErrorSchema>;
|
||||
export type WorkflowExecutionLog = z.infer<typeof WorkflowExecutionLogSchema>;
|
||||
export type WorkflowTaskExecution = z.infer<typeof WorkflowTaskExecutionSchema>;
|
||||
export type WorkflowExecutionPage = z.infer<typeof WorkflowExecutionPageSchema>;
|
||||
export type WorkflowDsl = z.infer<typeof WorkflowDslSchema>;
|
||||
export type Staff = z.infer<typeof StaffSchema>;
|
||||
export type WebhookInfo = z.infer<typeof WebhookInfoSchema>;
|
||||
@@ -431,3 +506,4 @@ export type WorkflowSummary = z.infer<typeof WorkflowSummarySchema>;
|
||||
export type WorkflowListAllError = z.infer<typeof WorkflowListAllErrorSchema>;
|
||||
export type TaskMatch = z.infer<typeof TaskMatchSchema>;
|
||||
export type WorkflowWithMatches = z.infer<typeof WorkflowWithMatchesSchema>;
|
||||
|
||||
@@ -10,7 +10,19 @@ import {
|
||||
} from "./workflow-state.js";
|
||||
import { WorkflowDetailSchema } from "./types.js";
|
||||
import type { WorkflowDetail } from "./types.js";
|
||||
import { listWorkflowSnapshots, listWorkflowLogs, toggleWorkflow, updateWorkflow } from "./api.js";
|
||||
import {
|
||||
getExecutionLogs,
|
||||
getJob,
|
||||
getJobExecutionLevel,
|
||||
getJobExecutionTree,
|
||||
getJobFailedExecutions,
|
||||
getWorkflowDetail,
|
||||
listWorkflowSnapshots,
|
||||
listWorkflowLogs,
|
||||
toggleWorkflow,
|
||||
updateWorkflow,
|
||||
} from "./api.js";
|
||||
import { AuthenticationError, EkbApiError } from "../../core/errors.js";
|
||||
import { WorkflowAlertStore } from "./workflow-alert-store.js";
|
||||
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
@@ -150,4 +162,144 @@ describe("workflow draft state machine", () => {
|
||||
expect(failed.status).toBe("failed");
|
||||
expect(failed.error).toBe("网络错误");
|
||||
});
|
||||
|
||||
it("throws structured AuthenticationError or EkbApiError when Piper unwrap receives null data or non-200 code", async () => {
|
||||
const unauthorizedClient = {
|
||||
get: async () =>
|
||||
new Response(JSON.stringify({ code: 401, message: "登录已过期", data: null }), {
|
||||
status: 200,
|
||||
}),
|
||||
} as any;
|
||||
await expect(getWorkflowDetail(unauthorizedClient, "wf-1")).rejects.toBeInstanceOf(AuthenticationError);
|
||||
|
||||
const nullDataClient = {
|
||||
get: async () =>
|
||||
new Response(JSON.stringify({ code: 200, msg: "pipeline not found", data: null }), {
|
||||
status: 200,
|
||||
}),
|
||||
} as any;
|
||||
await expect(getWorkflowDetail(nullDataClient, "wf-1")).rejects.toBeInstanceOf(EkbApiError);
|
||||
});
|
||||
|
||||
it("calls the 5 Piper Job diagnostic endpoints and parses execution trees, failed nodes, child levels, and logs", async () => {
|
||||
const client = {
|
||||
get: async (url: string, options?: any) => {
|
||||
if (url === "api/easo/jobs/892809886382563347") {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
code: 200,
|
||||
data: {
|
||||
id: "892809886382563347",
|
||||
pipelineId: "886351399301758976",
|
||||
label: "每30分钟创建采购申请单",
|
||||
state: "COMPLETED",
|
||||
successTaskCount: 5,
|
||||
errorTaskCount: 1,
|
||||
hasError: true,
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
if (url === "api/easo/jobs/892809886382563347/execution") {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
code: 200,
|
||||
data: [
|
||||
{
|
||||
id: "892809893789696012",
|
||||
jobId: "892809886382563347",
|
||||
name: "every_0",
|
||||
label: "循环",
|
||||
type: "every",
|
||||
state: "COMPLETED",
|
||||
levelIndex: [0],
|
||||
},
|
||||
],
|
||||
})
|
||||
);
|
||||
}
|
||||
if (url === "api/easo/jobs/892809886382563347/execution/level/failed") {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
code: 200,
|
||||
data: [
|
||||
{
|
||||
id: "892809900000000001",
|
||||
jobId: "892809886382563347",
|
||||
parentId: "892809893789696012",
|
||||
name: "ekuaibao_flow_create_task_0",
|
||||
label: "创建预付申请单",
|
||||
type: "flow-create-task",
|
||||
state: "FAILED",
|
||||
inputs: { form: { u_关联合同流程: "ID01VSau4VJWSH" } },
|
||||
outputs: { error: "我方签约主体未填写" },
|
||||
},
|
||||
],
|
||||
})
|
||||
);
|
||||
}
|
||||
if (url === "api/easo/jobs/892809886382563347/execution/level") {
|
||||
expect(options?.searchParams).toEqual({
|
||||
parentId: "892809893789696012",
|
||||
number: "1",
|
||||
pageSize: "20",
|
||||
});
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
code: 200,
|
||||
data: {
|
||||
number: 1,
|
||||
size: 20,
|
||||
totalPages: 1,
|
||||
totalItems: 1,
|
||||
items: [
|
||||
[
|
||||
{
|
||||
id: "892809900000000001",
|
||||
name: "ekuaibao_flow_create_task_0",
|
||||
state: "FAILED",
|
||||
inputs: { form: { u_关联合同流程: "ID01VSau4VJWSH" } },
|
||||
outputs: { error: "我方签约主体未填写" },
|
||||
},
|
||||
],
|
||||
],
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
if (url === "api/easo/executions/892809893789696012/logs") {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
code: 200,
|
||||
data: {
|
||||
total: 1,
|
||||
items: [{ id: "log-1", message: "MVEL script executed", level: "INFO" }],
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
throw new Error(`Unexpected URL: ${url}`);
|
||||
},
|
||||
} as any;
|
||||
|
||||
const job = await getJob(client, "892809886382563347");
|
||||
expect(job.hasError).toBe(true);
|
||||
expect(job.errorTaskCount).toBe(1);
|
||||
|
||||
const tree = await getJobExecutionTree(client, "892809886382563347");
|
||||
expect(tree).toHaveLength(1);
|
||||
expect(tree[0]?.name).toBe("every_0");
|
||||
|
||||
const failed = await getJobFailedExecutions(client, "892809886382563347");
|
||||
expect(failed.items).toHaveLength(1);
|
||||
expect((failed.items[0]?.outputs as any)?.error).toBe("我方签约主体未填写");
|
||||
|
||||
const level = await getJobExecutionLevel(client, "892809886382563347", {
|
||||
parentId: "892809893789696012",
|
||||
});
|
||||
expect(level.items).toHaveLength(1);
|
||||
|
||||
const logs = await getExecutionLogs(client, "892809893789696012");
|
||||
expect(logs[0]?.message).toBe("MVEL script executed");
|
||||
});
|
||||
});
|
||||
+5
-3
@@ -5,7 +5,7 @@ import { dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { loadCorpConfigs } from "./core/config/loader.js";
|
||||
import { CorpContext } from "./core/config/manager.js";
|
||||
import { createSessionClient, getUnityClient } from "./core/http/index.js";
|
||||
import { createSessionClient, getEasoClient, getUnityClient } from "./core/http/index.js";
|
||||
import { AuthenticationError, EkbError, NotLoggedInError } from "./core/errors.js";
|
||||
import { authTools } from "./core/auth/tools.js";
|
||||
import { platformTools } from "./domains/platform/tools.js";
|
||||
@@ -344,9 +344,11 @@ export function createServer(options: { mode?: HoseMcpMode; enabled?: boolean }
|
||||
};
|
||||
}
|
||||
const sessionClient = await createSessionClient(currentCorp);
|
||||
const { client: unityClient } = await getUnityClient(currentCorp);
|
||||
const { client: easoClient } = await getEasoClient(currentCorp).catch(() =>
|
||||
getUnityClient(currentCorp)
|
||||
);
|
||||
const result = await platformTool.handler(
|
||||
{ corp: currentCorp, ekbClient: sessionClient, easoClient: unityClient },
|
||||
{ corp: currentCorp, ekbClient: sessionClient, easoClient },
|
||||
parsed.data as never
|
||||
);
|
||||
return {
|
||||
|
||||
Reference in new issue
Block a user