Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4d921c09b3 | ||
|
|
3fee9a2a6f | ||
|
|
32a509aa0e | ||
|
|
ad771e92e0 | ||
|
|
1739daacf2 | ||
|
|
1c2e97486b | ||
|
|
a5f685045e | ||
|
|
fbdb38bfb2 | ||
|
|
f834822f36 | ||
|
|
37f5e5c74b | ||
|
|
fa55e45acd | ||
|
|
975f76af74 | ||
|
|
deed5a5628 | ||
|
|
576d98a85f | ||
|
|
aea30fbcd5 | ||
|
|
36a4d3b27b | ||
|
|
3f3bd8183b | ||
|
|
8a5dc1133d | ||
|
|
88a0d97974 | ||
|
|
6ce83dd8a7 | ||
|
|
3597ec6694 | ||
|
|
4e53c88a51 | ||
|
|
33ea49c9fe | ||
|
|
b671b63e99 | ||
|
|
7a396f8a95 | ||
|
|
82fa0fca0c | ||
|
|
8d72e94d52 | ||
|
|
3c2c82c3f7 | ||
|
|
6e40faccff | ||
|
|
b3371ee327 | ||
|
|
2ace4e2378 | ||
|
|
60d0b8ffc1 | ||
|
|
16507da470 | ||
|
|
f0fc7148ec | ||
|
|
e98948529e | ||
|
|
1e45c441c6 | ||
|
|
2e6fe1a94a | ||
|
|
e2e730c07d | ||
|
|
9b4b9b3756 | ||
|
|
35552944d1 | ||
|
|
37cf784ba1 | ||
|
|
6816ea7a75 | ||
|
|
ed9fa979e0 | ||
|
|
d839fcbe2b | ||
|
|
080341b7ca | ||
|
|
3d1286f62d | ||
|
|
9d895866e6 | ||
|
|
3c1237ff31 | ||
|
|
2e5e3c208c | ||
|
|
1e09b5b85e | ||
|
|
ec7584c194 | ||
|
|
ae76b33c38 | ||
|
|
4537c6eb53 | ||
|
|
1197b5b985 | ||
|
|
e872beaab8 | ||
|
|
fae36f8c96 | ||
|
|
c705cffaf4 | ||
|
|
6f4608635b | ||
|
|
2be973ddf4 | ||
|
|
bf80273891 | ||
|
|
d1a75c011a | ||
|
|
0f781fda53 | ||
|
|
29841a2374 | ||
|
|
a1527246da | ||
|
|
b2059ec350 | ||
|
|
e7cac3aec3 | ||
|
|
51e4b39807 | ||
|
|
6269dd21ab | ||
|
|
70d619e464 | ||
|
|
48ab35a8ac | ||
|
|
813d190524 | ||
|
|
e86c05d51a | ||
|
|
55c3521c48 | ||
|
|
98ceb85a5c | ||
|
|
b91b5d2635 | ||
|
|
3141cc3b29 | ||
|
|
2aea435116 | ||
|
|
4c4cd42edd | ||
|
|
6451c120f0 | ||
|
|
298a02a3a3 | ||
|
|
85384bc136 | ||
|
|
b69b78fc30 | ||
|
|
53689e89d0 | ||
|
|
b232e934fc | ||
|
|
32610e0b11 | ||
|
|
d2e0d564ca | ||
|
|
f46e0e7b0a | ||
|
|
0e6090a92c | ||
|
|
ae2a1a9d60 | ||
|
|
a5abfbe077 | ||
|
|
221b9596b8 | ||
|
|
2844fd49dd | ||
|
|
fac81b08e8 | ||
|
|
74954b3e7a | ||
|
|
99e1e0c4b6 | ||
|
|
18da4cc066 | ||
|
|
c1e94ce63e | ||
|
|
9ca9af97e5 | ||
|
|
0768b94d65 | ||
|
|
4f0eea5725 | ||
|
|
9a9e857606 |
No files matched your search
@@ -10,6 +10,11 @@ on:
|
||||
description: Release tag already merged into main (e.g. v0.8.14)
|
||||
required: true
|
||||
type: string
|
||||
mirror_only:
|
||||
description: Reuse the existing GitHub assets and repair only the Gitea mirror
|
||||
required: false
|
||||
default: false
|
||||
type: boolean
|
||||
|
||||
concurrency:
|
||||
group: release-${{ inputs.tag || github.ref_name }}
|
||||
@@ -27,6 +32,7 @@ jobs:
|
||||
contents: write
|
||||
env:
|
||||
RELEASE_TAG: ${{ inputs.tag || github.ref_name }}
|
||||
MIRROR_ONLY: ${{ inputs.mirror_only || false }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
@@ -47,34 +53,43 @@ jobs:
|
||||
bun run scripts/verify-release.ts "$RELEASE_TAG"
|
||||
|
||||
- name: Install dependencies
|
||||
if: ${{ !inputs.mirror_only }}
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Check committed version consistency
|
||||
if: ${{ !inputs.mirror_only }}
|
||||
run: bun run check:version
|
||||
|
||||
- name: Generate & bundle OpenAPI
|
||||
if: ${{ !inputs.mirror_only }}
|
||||
run: bun run openapi:all
|
||||
|
||||
- name: Type-check
|
||||
if: ${{ !inputs.mirror_only }}
|
||||
run: bun run check
|
||||
|
||||
- name: Test
|
||||
if: ${{ !inputs.mirror_only }}
|
||||
run: bun test
|
||||
|
||||
- name: Compile multi-target binaries
|
||||
if: ${{ !inputs.mirror_only }}
|
||||
run: |
|
||||
mkdir -p dist/bin
|
||||
node scripts/build-binary.mjs --all --release
|
||||
|
||||
- name: Verify packaged MCP entrypoint
|
||||
if: ${{ !inputs.mirror_only }}
|
||||
run: bun run scripts/verify-binary.ts dist/bin/hose-use-linux-x64
|
||||
|
||||
- name: Verify plugin bundle runtime
|
||||
if: ${{ !inputs.mirror_only }}
|
||||
run: |
|
||||
bun run build:plugin
|
||||
bun run scripts/verify-binary.ts dist/mcp/server.js --plugin
|
||||
|
||||
- name: Package release archives
|
||||
if: ${{ !inputs.mirror_only }}
|
||||
run: |
|
||||
sudo apt-get update && sudo apt-get install -y zip
|
||||
package_unix() {
|
||||
@@ -102,6 +117,7 @@ jobs:
|
||||
(cd dist/bin && sha256sum hose-use-* > checksums.txt)
|
||||
|
||||
- name: Publish GitHub Release
|
||||
if: ${{ !inputs.mirror_only }}
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
@@ -115,28 +131,40 @@ jobs:
|
||||
|
||||
- name: Publish Gitea Release
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
GITEA_HOST: "https://git.ying-qing.cn"
|
||||
GITEA_REPO: "gitea/hose-use"
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [ -z "$GITEA_TOKEN" ]; then
|
||||
if [ "${MIRROR_ONLY:-false}" = "true" ]; then
|
||||
echo "::error::GITEA_TOKEN is required to repair the mirror."
|
||||
exit 1
|
||||
fi
|
||||
echo "::notice::GITEA_TOKEN secret not configured, skipping Gitea upload."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
TAG_NAME="${RELEASE_TAG}"
|
||||
if [ "${MIRROR_ONLY:-false}" = "true" ]; then
|
||||
# Preserve the published bytes and checksums; never rebuild or replace GitHub assets.
|
||||
mkdir -p dist/bin
|
||||
gh release download "$TAG_NAME" --repo "$GITHUB_REPOSITORY" --dir dist/bin --pattern 'hose-use-*' --pattern checksums.txt
|
||||
(cd dist/bin && sha256sum --strict -c checksums.txt)
|
||||
fi
|
||||
TAG_MSG=$(git tag -l --format='%(contents)' "${TAG_NAME}" | sed '/^$/d')
|
||||
NOTES="${TAG_MSG:-Automated release for ${TAG_NAME}}"
|
||||
|
||||
echo "==> Creating release on Gitea for ${TAG_NAME}..."
|
||||
RELEASE_RESP=$(curl -s -X POST "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases" \
|
||||
RELEASE_RESP=$(curl -sS --connect-timeout 15 --max-time 60 -X POST "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases" \
|
||||
-H "Authorization: token ${GITEA_TOKEN}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"tag_name\":\"${TAG_NAME}\",\"name\":\"${TAG_NAME}\",\"body\":$(echo "$NOTES" | jq -Rsa .),\"draft\":false,\"prerelease\":false}")
|
||||
|
||||
RELEASE_ID=$(echo "$RELEASE_RESP" | jq -r '.id // empty')
|
||||
if [ -z "$RELEASE_ID" ]; then
|
||||
RELEASE_ID=$(curl -s -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/tags/${TAG_NAME}" | jq -r '.id // empty')
|
||||
RELEASE_ID=$(curl -fsS --connect-timeout 15 --max-time 60 -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/tags/${TAG_NAME}" | jq -r '.id // empty')
|
||||
fi
|
||||
|
||||
if [ -z "$RELEASE_ID" ]; then
|
||||
@@ -146,32 +174,56 @@ jobs:
|
||||
|
||||
echo "==> Uploading assets to Gitea release ID ${RELEASE_ID}..."
|
||||
upload_asset() {
|
||||
local file="$1"
|
||||
local filename
|
||||
local file="$1" filename expected_hash attempt info existing remote_hash asset_id response delete_failed
|
||||
filename=$(basename "$file")
|
||||
echo " [start] Uploading ${filename} to Gitea..."
|
||||
# Match GitHub --clobber when retrying the same verified release.
|
||||
existing=$(curl -fsS -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}" | jq -r --arg name "$filename" '.assets[]? | select(.name == $name) | .id')
|
||||
for asset_id in $existing; do
|
||||
curl -fsS -X DELETE -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}/assets/${asset_id}"
|
||||
expected_hash=$(sha256sum "$file" | awk '{ print $1 }')
|
||||
for attempt in 1 2 3; do
|
||||
if [ "$attempt" -gt 1 ]; then sleep "${GITEA_RETRY_DELAY:-3}"; fi
|
||||
echo " [start] Uploading ${filename} to Gitea (attempt ${attempt}/3)..."
|
||||
if ! info=$(curl -fsS --connect-timeout 15 --max-time 60 -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}"); then
|
||||
continue
|
||||
fi
|
||||
existing=$(printf '%s' "$info" | jq -r --arg name "$filename" '.assets[]? | select(.name == $name) | .id')
|
||||
if [ -n "$existing" ]; then
|
||||
if ! remote_hash=$(curl -fLsS --connect-timeout 15 --max-time 600 -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_HOST}/${GITEA_REPO}/releases/download/${TAG_NAME}/${filename}" | sha256sum | awk '{ print $1 }'); then
|
||||
continue
|
||||
fi
|
||||
if [ "$remote_hash" = "$expected_hash" ]; then
|
||||
echo " [skip] ${filename} already matches SHA-256"
|
||||
return 0
|
||||
fi
|
||||
# Match GitHub --clobber only when the existing bytes differ.
|
||||
delete_failed=0
|
||||
for asset_id in $existing; do
|
||||
curl -fsS --connect-timeout 15 --max-time 60 -X DELETE -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}/assets/${asset_id}" || delete_failed=1
|
||||
done
|
||||
if [ "$delete_failed" -ne 0 ]; then continue; fi
|
||||
fi
|
||||
if response=$(curl -fsS --connect-timeout 15 --max-time 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}"); then
|
||||
echo " [done] ${filename} -> $(printf '%s' "$response" | tail -n 1)"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
RESP=$(curl -fsS -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)
|
||||
echo " [done] ${filename} -> ${STATUS}"
|
||||
echo "::error::Failed to upload ${filename} after 3 attempts."
|
||||
return 1
|
||||
}
|
||||
|
||||
# Bound outbound traffic: large raw binaries must not compete with all archives.
|
||||
pids=()
|
||||
failed=0
|
||||
for file in dist/bin/hose-use-* dist/bin/checksums.txt; do
|
||||
upload_asset "$file" &
|
||||
pids+=($!)
|
||||
if [ "${#pids[@]}" -eq 2 ]; then
|
||||
for pid in "${pids[@]}"; do wait "$pid" || failed=1; done
|
||||
pids=()
|
||||
fi
|
||||
done
|
||||
|
||||
failed=0
|
||||
for pid in "${pids[@]}"; do
|
||||
wait "$pid" || failed=1
|
||||
done
|
||||
if [ "${#pids[@]}" -gt 0 ]; then
|
||||
for pid in "${pids[@]}"; do wait "$pid" || failed=1; done
|
||||
fi
|
||||
if [ "$failed" -ne 0 ]; then
|
||||
echo "::error::One or more Gitea assets failed to upload."
|
||||
exit 1
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.8.14",
|
||||
"version": "0.8.20",
|
||||
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
|
||||
"author": {
|
||||
"name": "yingqing"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# hose-use (v0.8.14)
|
||||
# hose-use (v0.8.20)
|
||||
|
||||
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
|
||||
|
||||
|
||||
@@ -5,9 +5,11 @@
|
||||
"": {
|
||||
"name": "ekb-mcp",
|
||||
"dependencies": {
|
||||
"@jitl/quickjs-singlefile-cjs-release-sync": "0.32.0",
|
||||
"@modelcontextprotocol/core": "^2.0.0",
|
||||
"@modelcontextprotocol/server": "^2.0.0",
|
||||
"ky": "^2.0.2",
|
||||
"quickjs-emscripten-core": "0.32.0",
|
||||
"yaml": "^2.9.0",
|
||||
"zod": "^4.4.3",
|
||||
},
|
||||
@@ -19,6 +21,10 @@
|
||||
},
|
||||
},
|
||||
"packages": {
|
||||
"@jitl/quickjs-ffi-types": ["@jitl/quickjs-ffi-types@0.32.0", "", {}, "sha512-v9T+GQpmk43VDJ7d72sf0Nexhk+ArvtUihW27dy7lqAl0zBObFKtSBBIm5RBjwIhE8VwsPPm9PNuvPvNqLWUEg=="],
|
||||
|
||||
"@jitl/quickjs-singlefile-cjs-release-sync": ["@jitl/quickjs-singlefile-cjs-release-sync@0.32.0", "", { "dependencies": { "@jitl/quickjs-ffi-types": "0.32.0" } }, "sha512-NjUUcw26PoeJHND6nmflAH8nIvAJvxJ2qkSPi95wfiBqPim80GtcdWommroiWb8hh1/7fVettEwodAsGt2Mrsg=="],
|
||||
|
||||
"@modelcontextprotocol/client": ["@modelcontextprotocol/client@2.0.0", "", { "dependencies": { "@modelcontextprotocol/core": "2.0.0", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "jose": "^6.1.3", "pkce-challenge": "^5.0.0", "zod": "^4.2.0" } }, "sha512-8f1OghQ2rjzIOfqgUCP+8GiUWqRs89njoWLNqAe8kWmDePv3s1fZXseej+QXemssEuuOvLLmLO/kqM3IQHtISw=="],
|
||||
|
||||
"@modelcontextprotocol/core": ["@modelcontextprotocol/core@2.0.0", "", { "dependencies": { "zod": "^4.2.0" } }, "sha512-pJCEwGG7Lfr/+PQp9ZTwKXNeO5wzbfKL7H3MYpCorM4oFBoQrdjnBgEoqG+RjhsvS1FKrDbKux+M1HhlnGWqcA=="],
|
||||
@@ -47,6 +53,8 @@
|
||||
|
||||
"pkce-challenge": ["pkce-challenge@5.0.1", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="],
|
||||
|
||||
"quickjs-emscripten-core": ["quickjs-emscripten-core@0.32.0", "", { "dependencies": { "@jitl/quickjs-ffi-types": "0.32.0" } }, "sha512-QFnPfjFey8EqknSrSxe1hZrf1/8z7/6s1QzGOmKo6++02r7QRRX7ZoyNaZh7JuVjWsVW87KnQrbZqnHkOAzUyg=="],
|
||||
|
||||
"shebang-command": ["shebang-command@2.0.0", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="],
|
||||
|
||||
"shebang-regex": ["shebang-regex@3.0.0", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="],
|
||||
|
||||
Vendored
+900
-638
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,201 @@
|
||||
# hose-use 全局审查修复完成报告
|
||||
|
||||
日期:2026-10-20。基线:`fac81b0`(v0.8.15)。
|
||||
|
||||
已完成已确认范围内的 20 项修复,每项保留独立本地分支和对应测试,并全部合入 `fix/review-all-integration`。功能整合提交为 `2e5e3c2`;本报告随后独立提交。原工作区 `/Users/yingqing/Code/hose-use` 的 `main` 保持基线且干净。未推送远端、创建 PR、合入 main 或发布版本。
|
||||
|
||||
整合工作树:`/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use`。下列链接指向此次实际整合后的文件;可用 `git show <提交>` 或 `git diff fac81b0...<分支>` 分别复查独立修复。
|
||||
|
||||
## 逐项实际修改
|
||||
|
||||
### 01. 脚本执行隔离
|
||||
|
||||
分支:`fix/review-01-script-sandbox`;提交:`2844fd4`。
|
||||
|
||||
原来的 node:vm 共享宿主构造器,代码可能间接访问宿主能力。改为独立 QuickJS WASM 上下文,输入经 JSON 复制;构造器、日志回调和内建对象均属于客体运行时。默认执行预算 3 秒、客体堆上限 32 MiB、栈上限 512 KiB,输入/返回值上限各 1 MiB,日志上限 64 KiB/500 条。Promise 返回值明确失败;普通同步代码、输入、日志和错误行号继续支持。
|
||||
|
||||
实现:[src/domains/platform/workflow/script/sandbox.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/platform/workflow/script/sandbox.ts)。回归:[src/domains/platform/workflow/script/index.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/platform/workflow/script/index.test.ts)。验证宿主构造器逃逸、输入与原型隔离、死循环、分配/日志边界、Promise 拒绝及失败后再次执行;打包冒烟额外验证 WASM 随插件和独立二进制可用。
|
||||
|
||||
### 02. 审批企业边界
|
||||
|
||||
分支:`fix/review-02-approval-corp-boundary`;提交:`221b959`。
|
||||
|
||||
原来可在企业 B 的上下文使用企业 A 的审批结果执行同号单据。现在 apply 前校验会话企业、当前配置企业和取得的客户端企业,任何缺失或不一致均拒绝远端审批。
|
||||
|
||||
实现:[src/cli/commands/aipro/session.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/cli/commands/aipro/session.ts)。回归:[src/cli/commands/aipro/session-corp.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/cli/commands/aipro/session-corp.test.ts)。跨企业批准、驳回均被阻止;同企业路径仍能提交。
|
||||
|
||||
### 03. 审批检查状态校验
|
||||
|
||||
分支:`fix/review-03-finding-status-validation`;提交:`a5abfbe`。
|
||||
|
||||
原来未知检查状态可能绕过审批门禁。统一状态类型守卫,在批量写入、更新和评估结果应用前校验,网关对历史非法状态按失败处理;批量数据先整体校验再修改,避免留下半批结果。
|
||||
|
||||
实现:[src/domains/approval/repository.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/approval/repository.ts)。回归:[src/domains/approval/status-validation.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/approval/status-validation.test.ts)。覆盖非法写入/更新、批量写入原子性和历史异常状态的门禁处理;配套修改 service.ts、gateway.ts、types.ts。
|
||||
|
||||
### 04. 审批命令预演
|
||||
|
||||
分支:`fix/review-04-approval-dry-run`;提交:`ae2a1a9`。
|
||||
|
||||
原来的 dry-run 仍可能初始化数据库、改审批状态或进入提交路径。approval 与 aipro 的变更命令现在在构造仓储和客户端之前返回预演;--dry-run 同时遇到 --apply/--yes 时仍优先预演。恢复建议保留正确的 aipro 命令入口。
|
||||
|
||||
实现:[src/cli/commands/approval.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/cli/commands/approval.ts)。回归:[src/cli/approval-dry-run.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/cli/approval-dry-run.test.ts)。覆盖 11 条命令路径,断言无请求且不创建数据库;同时修改 src/aipro-cli.ts。
|
||||
|
||||
### 05. 节点开通确认
|
||||
|
||||
分支:`fix/review-05-node-grant-confirmation`;提交:`0e6090a`。
|
||||
|
||||
原来管理密码通过后即可开通灰度节点,未使用统一变更确认。现在 grant 在取密码或调用网关之前要求显式确认,并支持 dry-run;密码校验与用户确认分别执行。
|
||||
|
||||
实现:[src/cli/commands/workflow/node.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/cli/commands/workflow/node.ts)。回归:[src/cli/commands/workflow-nodes-confirmation.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/cli/commands/workflow-nodes-confirmation.test.ts)。验证缺少确认被阻止、预演零网关调用、确认后继续;原有开通测试同步传入 --yes。
|
||||
|
||||
### 06. 节点索引定位
|
||||
|
||||
分支:`fix/review-06-node-index-resolution`;提交:`f46e0e7`。
|
||||
|
||||
原来 CLI 字符串索引 3 可能被当作全局遍历序号,命中 2.1 的子节点。字符串现在只按节点名或层级索引定位;SDK 的数字参数保留原有全局遍历语义。
|
||||
|
||||
实现:[src/domains/platform/workflow/nodes/locator.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/platform/workflow/nodes/locator.ts)。回归:[src/domains/platform/workflow/nodes/locator-index.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/platform/workflow/nodes/locator-index.test.ts)。嵌套工作流中验证定位、编辑和删除均作用于所选节点。
|
||||
|
||||
### 07. 路径原型污染与继承选项
|
||||
|
||||
分支:`fix/review-07-patch-prototype-guard`;提交:`d2e0d56`。
|
||||
|
||||
路径补丁拒绝 __proto__、constructor、prototype 等危险段,只遍历对象自有属性。CLI 参数表改为无原型对象,选项读取和变更确认也只接受自有属性,阻止继承来的 yes/confirmed 等标记授权写操作。
|
||||
|
||||
实现:[src/domains/platform/workflow/state/index.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/platform/workflow/state/index.ts)。回归:[src/cli/prototype-guard.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/cli/prototype-guard.test.ts)。覆盖危险路径被拒、普通补丁可用,以及继承选项无法确认或改变命令;配套修改 parser.ts、mutation.ts。
|
||||
|
||||
### 08. 升级预演
|
||||
|
||||
分支:`fix/review-08-update-dry-run`;提交:`32610e0`。
|
||||
|
||||
update dry-run 现在在网络查询、安装、源码更新或二进制替换前返回预演;只读 check/changelog 保留原有行为。
|
||||
|
||||
实现:[src/cli/commands/update/index.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/cli/commands/update/index.ts)。回归:[src/cli/commands/update/dry-run.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/cli/commands/update/dry-run.test.ts)。源码与二进制模式下,均断言无 fetch、子进程和 Skill 安装调用。
|
||||
|
||||
### 09. 服务生命周期预演
|
||||
|
||||
分支:`fix/review-09-service-dry-run`;提交:`b232e93`。
|
||||
|
||||
service start/stop/restart/run 的 dry-run 在分发前返回,不创建或修改 PID、日志和后台进程;status 仍可读取服务状态。
|
||||
|
||||
实现:[src/cli/commands/service.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/cli/commands/service.ts)。回归:[src/cli/commands/service-dry-run.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/cli/commands/service-dry-run.test.ts)。覆盖生命周期预演及只读状态查询。
|
||||
|
||||
### 10. 认证续期与单次重放
|
||||
|
||||
分支:`fix/review-10-client-auth-refresh`;提交:`53689e8`。
|
||||
|
||||
原来的脚本引擎和 Unity 客户端闭包继续使用旧票据,401 后也可能重复续期。现在每次取最新缓存,失效后重新换票,Unity 同步清除失效的 eas 持久票据;认证最多重放一次,并在发送前克隆请求以保留 POST 请求体。
|
||||
|
||||
实现:[src/core/http/factory.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/core/http/factory.ts)。回归:[src/core/http/token-renewal.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/core/http/token-renewal.test.ts)。覆盖 Piper、EASO、Unity 三类客户端续期成功及持续 401 的最多两次请求;断言 POST 请求体完整。配套修改 script-engine-client.ts、unity-client.ts。
|
||||
|
||||
### 11. 审批会话有效期
|
||||
|
||||
分支:`fix/review-11-session-expiry`;提交:`813d190`。
|
||||
|
||||
短 ID、UUID、单号以及常规审批检查统一执行 TTL 校验,避免换一种句柄绕过过期限制;expires_at=0 正确视为过期。显式重新初始化刷新有效期。历史日志单独允许读取过期记录,并保持企业作用域校验。
|
||||
|
||||
实现:[src/domains/approval/repository.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/approval/repository.ts)。回归:[src/domains/approval/session-expiry.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/approval/session-expiry.test.ts)。覆盖三类句柄、常规审批检查、零时间戳、重新初始化和历史读取;配套修改 aipro/status.ts。
|
||||
|
||||
### 12. 赋值分隔符解析
|
||||
|
||||
分支:`fix/review-12-set-quoted-separators`;提交:`298a02a`。
|
||||
|
||||
原来 --set 按逗号直接拆分,name="ACME, Inc.", code=C 会产生错误赋值。现在复用识别引号和转义的解析器;缺少等号、空字段或不匹配引号在写入前报错。
|
||||
|
||||
实现:[src/domains/datalink/services.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/datalink/services.ts)。回归:[src/domains/datalink/set-separators.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/datalink/set-separators.test.ts)。覆盖引号内逗号、转义引号、多项赋值与非法输入;与第 13 项累计验证。
|
||||
|
||||
### 13. 显式字符串类型
|
||||
|
||||
分支:`fix/review-13-set-literal-types`;提交:`6451c12`。
|
||||
|
||||
原来去掉引号后再做自动转换,使 "001"、"true"、"null" 变成数字、布尔或空值。现在带引号值按字符串解码并保留类型;未加引号的 1、true、null 仍按既有规则转换。
|
||||
|
||||
实现:[src/domains/datalink/services.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/datalink/services.ts)。回归:[src/domains/datalink/set-literals.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/datalink/set-literals.test.ts)。覆盖前导零、布尔/空值文本与未加引号值的类型差异。
|
||||
|
||||
### 14. 脚本 JSON 输出
|
||||
|
||||
分支:`fix/review-14-script-json-output`;提交:`4c4cd42`。
|
||||
|
||||
lint/eval 的本地与远端四个 JSON 分支原来遗漏返回输出。现在统一返回 printJson 结果并遵循 runtime.jsonMode、--json/-j 和文件输出选项;失败仍返回非零退出码。
|
||||
|
||||
实现:[src/cli/commands/workflow/script.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/cli/commands/workflow/script.ts)。回归:[src/cli/commands/workflow/script-json.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/cli/commands/workflow/script-json.test.ts)。覆盖本地/远端 lint 与 eval、JSON 可解析、文件输出及失败退出码。
|
||||
|
||||
### 15. 工作流快照比较完整性
|
||||
|
||||
分支:`fix/review-15-snapshot-config-diff`;提交:`2aea435`。
|
||||
|
||||
原来的配置字段白名单漏掉映射、请求头等真实修改。现在比较节点自身配置的全部字段,保留 code/filter 等已有专项比较;用实际树路径记录顺序和父节点变化,不依赖已保存的索引元数据。空 tasks 也可处理。
|
||||
|
||||
实现:[src/domains/platform/services.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/platform/services.ts)。回归:[src/domains/platform/snapshot-config-diff.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/platform/snapshot-config-diff.test.ts)。覆盖 mapping、inputs、fields、form、header、params、onError、自定义配置,以及节点移动和无变化快照。
|
||||
|
||||
### 16. 节点开通失败退出码
|
||||
|
||||
分支:`fix/review-16-node-grant-failure`;提交:`3141cc3`。
|
||||
|
||||
网关 success=false 原来仍可能输出成功文案并退出 0。现在 JSON 与人类输出都返回退出码 1;人类输出写入失败原因且不显示成功信息。
|
||||
|
||||
实现:[src/cli/commands/workflow/node.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/cli/commands/workflow/node.ts)。回归:[src/cli/commands/workflow-nodes-failure.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/cli/commands/workflow-nodes-failure.test.ts)。覆盖网关业务失败的两种输出模式,并与第 5 项确认流程共同验证。
|
||||
|
||||
### 17. 事件全量分页与去重
|
||||
|
||||
分支:`fix/review-17-event-pagination`;提交:`b91b5d2`。
|
||||
|
||||
原来只扫描首批事件,且超过固定去重容量会反复通知。现在完整读取待办和未读消息的所有分页,再统一提交去重状态;保留本轮活跃事件的全部 ID。分页失败、重复页不前进或超过 10000 页时整轮失败,不提交半轮状态。
|
||||
|
||||
实现:[src/domains/events/poller.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/events/poller.ts)。回归:[src/domains/events/pagination.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/events/pagination.test.ts)。覆盖第 51 条事件、2501 条活跃事件重复轮询、停滞与失败分页;store.ts 同步调整 SQLite/JSON 存储容量策略。
|
||||
|
||||
### 18. 监听超时与取消状态
|
||||
|
||||
分支:`fix/review-18-watch-timeout`;提交:`70d619e`。
|
||||
|
||||
原来预算耗尽或取消后仍可能上报 job_completed。现在仅真实终态上报完成,分别返回 timeout/cancelled 事件与状态;单任务、连续监听和最新任务快照均传递标记。CLI 遇到超时/取消返回 1,连续监听向子任务传递剩余预算。
|
||||
|
||||
实现:[src/domains/platform/workflow/watch/pipeline-watcher.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/platform/workflow/watch/pipeline-watcher.ts)。回归:[src/domains/platform/workflow/watch/timeout.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/platform/workflow/watch/timeout.test.ts)。覆盖单任务超时、取消、once 快照及最新任务取消传播;CLI tail-timeout.test.ts 验证退出码。types.ts、single-job.ts、formatter.ts 和 tail.ts 配套更新。
|
||||
|
||||
### 19. 公式误报边界
|
||||
|
||||
分支:`fix/review-19-formula-diagnostics`;提交:`55c3521`。
|
||||
|
||||
原来文本里出现 ROUND/IF 等片段就可能被硬拦截。现在只识别完整公式表达式;明确文本字段不拦截,类型未知仅给建议,明确数字/日期等强类型字段才产生硬阻断。
|
||||
|
||||
实现:[src/domains/platform/workflow/analysis/analyzer.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/platform/workflow/analysis/analyzer.ts)。回归:[src/domains/platform/workflow/analysis/formula-boundaries.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/platform/workflow/analysis/formula-boundaries.test.ts)。覆盖普通句子、文本公式、未知类型软建议和明确强类型硬阻断;旧测试补充日期类型以保留原本意图。
|
||||
|
||||
### 20. 唯一触发器删除保护
|
||||
|
||||
分支:`fix/review-20-trigger-removal-guard`;提交:`e86c05d`。
|
||||
|
||||
原来只有多个顶层节点时才执行触发器保护,单节点工作流可以删除唯一触发器。现在无论节点数量都禁止删除触发器;正常动作节点仍可删除。
|
||||
|
||||
实现:[src/domains/platform/workflow/nodes/mutations.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/platform/workflow/nodes/mutations.ts)。回归:[src/domains/platform/workflow/nodes/trigger-removal.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/platform/workflow/nodes/trigger-removal.test.ts)。覆盖单个 webhook、定时和数据联动触发器,以及普通动作节点。
|
||||
|
||||
## 验证结果
|
||||
|
||||
- 每个修复分支均执行完整 `bun test`(部分使用 `--timeout 60000`)、`bun run check` 和 `bun run build:plugin` 后提交。
|
||||
- 整合从第 01 项开始,逐项合并其余 19 项;每一步均重新执行完整测试、类型检查和插件构建。最终默认命令 `bun test`:**606 通过、0 失败,87 个测试文件**(基线 547 项,净增 59 项)。
|
||||
- 最终 `bun run check`、`bun run check:version`、`git diff --check` 通过。
|
||||
- `bun run build:plugin` 通过;`bun scripts/verify-binary.ts dist/mcp/server.js --plugin` 通过,验证版本、沙箱求和/宿主隔离和 MCP stdio 单工具协议。
|
||||
- `bun run build:binary` 及 `bun scripts/verify-binary.ts dist/bin/hose-use` 通过;冒烟在临时目录执行,PATH 不含 Bun 或源码,使用本地假凭据且不提交业务请求。
|
||||
- `bun run build:binary --all` 编译 Darwin arm64/x64、Linux arm64/x64 和 Windows x64 五个目标通过。跨平台编译不等于这些系统上的运行验证。
|
||||
- 所有 20 个修复分支头及测试维护分支均已确认是整合分支的祖先;生成的 `dist/mcp/server.js` 已按最终源码重新构建并提交。
|
||||
- 详细最终验证日志:`/tmp/hose-review-final-validation-20261020.log`;逐步整合日志:`/tmp/hose-integration-review-*.log`。日志保存在本机,测试代码与分支提交可重复执行。
|
||||
|
||||
## 相对方案的补充与影响
|
||||
|
||||
1. 增加测试维护分支 `fix/review-validation-fixture-deadlines`(`48ab35a`)。验证期间原有安装/发布 Shell 测试的固定 5 秒/10 秒子进程截止导致 `status=null`,单独重跑成功。仅将测试子进程上限设为 30 秒、对应测试上限设为 60 秒;断言、重试次数及生产超时均不变。[scripts/release-validation.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/scripts/release-validation.test.ts)、[scripts/install.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/scripts/install.test.ts)。第 18 项的后续提交也包含该维护分支,功能修复仍独立于其他 19 项。
|
||||
2. 认证重放验证要求保留 POST 请求体,因此补充发送前的请求克隆;会话有效期验证补充常规审批入口和显式重置;监听验证补充最新任务的取消传播。这些均是对应问题在不同入口的同范围修复。
|
||||
3. 沙箱新增两个精确版本依赖 `quickjs-emscripten-core@0.32.0`、`@jitl/quickjs-singlefile-cjs-release-sync@0.32.0` 并更新锁文件。插件产物约从 1.53 MB 增至 2.9 MB。执行仅接受可 JSON 复制的输入和同步返回值;日志/输出、内存和时间限制可能使之前无限制的脚本失败。[package.json](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/package.json)、[bun.lock](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/bun.lock)。
|
||||
4. 按实际实现更新对应域层、CLI/Core/HTTP 文档,根目录规则和版本号未调整。整合时保留各分支文档补充;生成文件冲突以重新构建解决。未做跨模块重构或数据库结构迁移。
|
||||
|
||||
## 未覆盖与重点复查
|
||||
|
||||
- 业务网络路径使用模拟客户端验证,未对真实企业进行审批、节点开通或工作流写操作;真实上游服务的票据换取、权限和动态分页变化仍需集成环境验收。
|
||||
- 二进制运行冒烟仅在当前 macOS 主机执行;Linux、Windows 与其他 CPU 架构本轮仅完成编译。尚未运行远端 CI。
|
||||
- 安全相关测试证明已覆盖的逃逸/原型路径被阻止,不代表对 QuickJS 或全部 SDK 的形式化安全证明。客体 32 MiB 是运行时堆限制,并非整个宿主进程内存上限。
|
||||
- 建议审阅重点:QuickJS 兼容性与新增依赖、认证单次重放的票据刷新、审批企业/TTL 门禁、事件全量分页的上游稳定性。20 项确认问题在本轮覆盖范围内均已解决,无已知待修项。
|
||||
- 此次交付停留在本地提交;后续进入 PR/发布时仍需遵循仓库规定的远端 CI、审查和发布顺序。
|
||||
|
||||
## 发布前 CI 补充
|
||||
|
||||
首次远端 CI 中,606 项测试、类型检查、版本检查和 Linux 独立二进制冒烟均通过,但插件重建一致性检查失败。完整日志确认唯一差异是 Bun 为 QuickJS CommonJS 模块注入的构建机绝对 `__filename`。
|
||||
|
||||
在 `scripts/build-plugin.mjs` 为构建添加 `__filename=import.meta.path` 定义,使嵌入加载器使用运行时插件路径,并重新生成 `dist/mcp/server.js`。在两个独立目录安装锁定依赖并分别构建,SHA-256 完全一致;本机插件与独立二进制冒烟、606 项测试和类型/版本检查再次通过。该补充只修复插件产物的可重现构建,不改变 20 项业务修复的范围。远端最终结果以 PR #124 和发布工作流记录为准。
|
||||
+3
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.8.14",
|
||||
"version": "0.8.20",
|
||||
"module": "src/server.ts",
|
||||
"type": "module",
|
||||
"exports": {
|
||||
@@ -40,9 +40,11 @@
|
||||
"export:workflow-schema": "bun run scripts/export-workflow-schema.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@jitl/quickjs-singlefile-cjs-release-sync": "0.32.0",
|
||||
"@modelcontextprotocol/core": "^2.0.0",
|
||||
"@modelcontextprotocol/server": "^2.0.0",
|
||||
"ky": "^2.0.2",
|
||||
"quickjs-emscripten-core": "0.32.0",
|
||||
"yaml": "^2.9.0",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
|
||||
@@ -20,6 +20,7 @@ function run(args) {
|
||||
const mcpOutput = resolve(root, "dist/mcp/server.js");
|
||||
mkdirSync(dirname(mcpOutput), { recursive: true });
|
||||
// The shared CLI uses bun:sqlite; the plugin manifest must use this runtime too.
|
||||
run(["build", "src/server.ts", "--minify", "--target=bun", "--outfile", mcpOutput]);
|
||||
// Embedded CommonJS loaders must use the bundle path, not the build host's absolute checkout path.
|
||||
run(["build", "src/server.ts", "--minify", "--target=bun", "--define", "__filename=import.meta.path", "--outfile", mcpOutput]);
|
||||
writeFileSync(mcpOutput, readFileSync(mcpOutput, "utf8").replace(/[ \t]+$/gm, ""));
|
||||
console.log(`✓ Successfully bundled MCP server: ${mcpOutput}`);
|
||||
@@ -5,6 +5,7 @@ import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
|
||||
// Shell fixtures start several processes; allow headroom on a busy host.
|
||||
const fixtures: string[] = [];
|
||||
afterEach(() => { for (const root of fixtures.splice(0)) rmSync(root, { recursive: true, force: true }); });
|
||||
const hash = (data: Buffer | string) => createHash("sha256").update(data).digest("hex");
|
||||
@@ -63,7 +64,7 @@ if [ -n "$dest" ]; then cp "$file" "$dest"; else cat "$file"; fi
|
||||
const run = (env: Record<string, string> = {}) => spawnSync("bash", [resolve(import.meta.dir, "install.sh")], {
|
||||
cwd: root,
|
||||
env: { ...process.env, PATH: `${tools}:${process.env.PATH}`, HOSE_USE_INSTALL_DIR: target, HOSE_USE_VERSION: "9.9.9", HOSE_USE_MIRROR: "auto", HOSE_FIXTURE_SOURCE: source, HOSE_FIXTURE_LOG: join(root, "skill.log"), HOSE_FIXTURE_REQUESTS: join(root, "requests.log"), ...env },
|
||||
encoding: "utf8", timeout: 10_000,
|
||||
encoding: "utf8", timeout: 30_000,
|
||||
});
|
||||
return { root, source, target, run, binary };
|
||||
}
|
||||
@@ -77,7 +78,7 @@ describe("verified standalone installer", () => {
|
||||
expect(readlinkSync(join(f.target, "hose-aipro"))).toBe("hose-use");
|
||||
expect(readFileSync(join(f.root, "skill.log"), "utf8").trim()).toBe("skill install --yes");
|
||||
expect(readdirSync(f.target).sort()).toEqual(["hose-aipro", "hose-use"]);
|
||||
});
|
||||
}, 60_000);
|
||||
|
||||
for (const options of [{ badHash: true }, { missingEntry: true }, { duplicate: true }]) {
|
||||
test(`rejects an invalid manifest/archive and preserves the old binary: ${JSON.stringify(options)}`, () => {
|
||||
@@ -89,7 +90,7 @@ describe("verified standalone installer", () => {
|
||||
expect(result.status).toBe(1);
|
||||
expect(readFileSync(join(f.target, "hose-use"), "utf8")).toBe("old binary");
|
||||
expect(existsSync(join(f.root, "skill.log"))).toBe(false);
|
||||
});
|
||||
}, 60_000);
|
||||
}
|
||||
|
||||
test("does not silently bypass missing checksums or guess an old tag", () => {
|
||||
@@ -100,7 +101,7 @@ describe("verified standalone installer", () => {
|
||||
expect(unknown.stderr).toContain("could not resolve");
|
||||
expect(existsSync(join(f.target, "hose-use"))).toBe(false);
|
||||
expect(readFileSync(join(f.root, "requests.log"), "utf8")).not.toContain("v0.8.9");
|
||||
});
|
||||
}, 60_000);
|
||||
|
||||
test("uses a verified raw fallback and a fixed tag when the first mirror fails", () => {
|
||||
const f = fixture({ rawOnly: true });
|
||||
@@ -110,7 +111,7 @@ describe("verified standalone installer", () => {
|
||||
const requests = readFileSync(join(f.root, "requests.log"), "utf8");
|
||||
expect(requests).toContain("/download/v9.9.9/");
|
||||
expect(requests).not.toContain("/latest/download/");
|
||||
});
|
||||
}, 60_000);
|
||||
|
||||
test("reports Skill failure without claiming it was installed", () => {
|
||||
const f = fixture();
|
||||
@@ -119,7 +120,7 @@ describe("verified standalone installer", () => {
|
||||
expect(result.stderr).toContain("binary installed");
|
||||
expect(result.stdout).not.toContain("Agent skill installed");
|
||||
expect(result.stdout).not.toContain("successfully installed");
|
||||
});
|
||||
}, 60_000);
|
||||
|
||||
test("does not replace directories or follow an existing alias into a directory", () => {
|
||||
const f = fixture();
|
||||
@@ -133,5 +134,5 @@ describe("verified standalone installer", () => {
|
||||
writeFileSync(join(f.target, "hose-use"), "old binary");
|
||||
expect(f.run().status).toBe(1);
|
||||
expect(readFileSync(join(f.target, "hose-use"), "utf8")).toBe("old binary");
|
||||
});
|
||||
}, 60_000);
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { execFileSync, spawnSync } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
@@ -7,6 +8,7 @@ import { parse } from "yaml";
|
||||
import { bumpVersion } from "./bump-version.js";
|
||||
import { verifyReleaseTag } from "./verify-release.js";
|
||||
|
||||
// Shell fixtures start several processes; allow headroom on a busy host.
|
||||
const roots: string[] = [];
|
||||
afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });
|
||||
|
||||
@@ -32,6 +34,48 @@ function repository() {
|
||||
return { root, git, version: () => JSON.parse(readFileSync(join(root, "package.json"), "utf8")).version };
|
||||
}
|
||||
|
||||
function mirrorFixture(mode: "retry" | "skip" | "concurrency", mirrorOnly = false) {
|
||||
const f = repository();
|
||||
const tools = join(f.root, "tools"), published = join(f.root, "published");
|
||||
mkdirSync(tools); mkdirSync(published); mkdirSync(join(f.root, "dist/bin"), { recursive: true });
|
||||
const names = mode === "concurrency" ? Array.from({ length: 5 }, (_, i) => `hose-use-fixture-${i}`) : ["hose-use-linux-x64"];
|
||||
const manifest = names.map(name => {
|
||||
const data = `published bytes for ${name}`;
|
||||
writeFileSync(join(published, name), data);
|
||||
return `${createHash("sha256").update(data).digest("hex")} ${name}\n`;
|
||||
}).join("");
|
||||
writeFileSync(join(published, "checksums.txt"), manifest);
|
||||
const files = [...names, "checksums.txt"];
|
||||
if (!mirrorOnly) for (const name of files) writeFileSync(join(f.root, "dist/bin", name), readFileSync(join(published, name)));
|
||||
writeFileSync(join(f.root, "info.json"), JSON.stringify({ assets: mode === "skip" ? files.map((name, i) => ({ id: i + 1, name })) : [] }));
|
||||
writeFileSync(join(tools, "gh"), '#!/bin/sh\nprintf "%s\\n" "$*" > "$MIRROR_FIXTURE/gh.log"\ncp "$MIRROR_FIXTURE"/published/* dist/bin/\n', { mode: 0o755 });
|
||||
writeFileSync(join(tools, "curl"), `#!/bin/bash
|
||||
url=""
|
||||
for arg in "$@"; do case "$arg" in https://*) url="$arg" ;; esac; done
|
||||
case "$url" in
|
||||
*/assets?*)
|
||||
name="\${url##*name=}"
|
||||
printf 'start\\n' >> "$MIRROR_FIXTURE/events"
|
||||
if [ "$MIRROR_MODE" = "skip" ]; then printf 'unexpected upload\\n' >> "$MIRROR_FIXTURE/uploads"; exit 22; fi
|
||||
count_file="$MIRROR_FIXTURE/count-$name"
|
||||
count=0; [ ! -f "$count_file" ] || count=$(cat "$count_file")
|
||||
count=$((count + 1)); printf '%s' "$count" > "$count_file"
|
||||
if [ "$MIRROR_MODE" = "retry" ] && [ "$count" -eq 1 ]; then printf 'end\\n' >> "$MIRROR_FIXTURE/events"; exit 28; fi
|
||||
if [ "$MIRROR_MODE" = "concurrency" ]; then sleep 0.1; fi
|
||||
printf 'end\\n' >> "$MIRROR_FIXTURE/events"
|
||||
printf '{"id":100}\\nHTTP_STATUS:201'
|
||||
;;
|
||||
*/download/*) cat "$MIRROR_FIXTURE/published/\${url##*/}" ;;
|
||||
*/releases) printf '{"id":42}' ;;
|
||||
*/releases/42) cat "$MIRROR_FIXTURE/info.json" ;;
|
||||
*) exit 22 ;;
|
||||
esac
|
||||
`, { mode: 0o755 });
|
||||
const workflow = parse(readFileSync(join(import.meta.dir, "../.github/workflows/release.yml"), "utf8"));
|
||||
const step = workflow.jobs["build-and-publish"].steps.find((s: { name?: string }) => s.name === "Publish Gitea Release");
|
||||
return { ...f, files, run: () => spawnSync("bash", ["-eo", "pipefail", "-c", step.run], { cwd: f.root, env: { ...process.env, PATH: `${tools}:${process.env.PATH}`, GITEA_TOKEN: "fixture", GITEA_RETRY_DELAY: "0", GITEA_HOST: "https://example.test", GITEA_REPO: "test/repo", RELEASE_TAG: "v1.0.0", MIRROR_ONLY: String(mirrorOnly), GITHUB_REPOSITORY: "test/repo", MIRROR_FIXTURE: f.root, MIRROR_MODE: mode }, encoding: "utf8", timeout: 30_000 }) };
|
||||
}
|
||||
|
||||
describe("release preparation and publication guards", () => {
|
||||
test("bump rejects wrong branches, dirty trees and invalid/non-increasing versions before writes", () => {
|
||||
const f = repository();
|
||||
@@ -43,7 +87,7 @@ describe("release preparation and publication guards", () => {
|
||||
for (const version of ["1.0.0", "0.9.9", "1.0.01", "1.0.1-rc.01", "invalid"]) expect(() => bumpVersion(f.root, version, () => {})).toThrow();
|
||||
expect(f.version()).toBe("1.0.0");
|
||||
expect(f.git("status", "--porcelain")).toBe("");
|
||||
});
|
||||
}, 60_000);
|
||||
|
||||
test("bump updates sources on its release branch and explicitly invokes regeneration", () => {
|
||||
const f = repository();
|
||||
@@ -54,7 +98,7 @@ describe("release preparation and publication guards", () => {
|
||||
expect(f.version()).toBe("1.0.1");
|
||||
expect(readFileSync(join(f.root, "skills/hose-use/SKILL.md"), "utf8")).toContain("version: 1.0.1");
|
||||
expect(parse(readFileSync(join(f.root, "specs/openapi/openapi.yaml"), "utf8")).info.version).toBe("1.0.1");
|
||||
});
|
||||
}, 60_000);
|
||||
|
||||
test("an existing release tag cannot be reused during bump", () => {
|
||||
const f = repository();
|
||||
@@ -62,7 +106,7 @@ describe("release preparation and publication guards", () => {
|
||||
f.git("tag", "v1.0.1");
|
||||
expect(() => bumpVersion(f.root, "patch", () => {})).toThrow("already exists");
|
||||
expect(f.version()).toBe("1.0.0");
|
||||
});
|
||||
}, 60_000);
|
||||
|
||||
test("publication validates the actual HEAD, main ancestry and package version", () => {
|
||||
const f = repository();
|
||||
@@ -77,7 +121,7 @@ describe("release preparation and publication guards", () => {
|
||||
expect(() => verifyReleaseTag(f.root, "v1.0.0")).toThrow("exact tagged commit");
|
||||
f.git("tag", "v1.0.1");
|
||||
expect(() => verifyReleaseTag(f.root, "v1.0.1")).toThrow("ancestor");
|
||||
});
|
||||
}, 60_000);
|
||||
|
||||
test("workflows validate committed versions before generation and ship the checksum manifest", () => {
|
||||
const root = join(import.meta.dir, "..");
|
||||
@@ -93,7 +137,11 @@ describe("release preparation and publication guards", () => {
|
||||
expect(runs.some((s: string) => s.includes("sha256sum hose-use-* > checksums.txt"))).toBe(true);
|
||||
for (const step of [...ci.jobs.validate.steps, ...steps]) if (step.uses) expect(step.uses).toMatch(/@[a-f0-9]{40}$/);
|
||||
expect(JSON.parse(readFileSync(join(root, ".mcp.json"), "utf8")).mcpServers["hose-use"].command).toBe("bun");
|
||||
});
|
||||
expect(release.on.workflow_dispatch.inputs.mirror_only.type).toBe("boolean");
|
||||
for (const name of ["Compile multi-target binaries", "Package release archives", "Publish GitHub Release"]) {
|
||||
expect(steps.find((s: { name?: string }) => s.name === name).if).toBe("${{ !inputs.mirror_only }}");
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test("a failed background Gitea upload makes the Release step fail", () => {
|
||||
const f = repository();
|
||||
@@ -112,9 +160,42 @@ for arg in "$@"; do
|
||||
done
|
||||
exit 22
|
||||
`, { mode: 0o755 });
|
||||
const result = spawnSync("bash", ["-eo", "pipefail", "-c", step.run], { cwd: f.root, env: { ...process.env, PATH: `${join(f.root, "tools")}:${process.env.PATH}`, GITEA_TOKEN: "fixture", GITEA_HOST: "https://example.test", GITEA_REPO: "test/repo", RELEASE_TAG: "v1.0.0" }, encoding: "utf8", timeout: 5000 });
|
||||
const result = spawnSync("bash", ["-eo", "pipefail", "-c", step.run], { cwd: f.root, env: { ...process.env, PATH: `${join(f.root, "tools")}:${process.env.PATH}`, GITEA_TOKEN: "fixture", GITEA_RETRY_DELAY: "0", GITEA_HOST: "https://example.test", GITEA_REPO: "test/repo", RELEASE_TAG: "v1.0.0" }, encoding: "utf8", timeout: 30_000 });
|
||||
expect(result.status).toBe(1);
|
||||
expect(result.stdout).toContain("assets failed to upload");
|
||||
expect(result.stdout).not.toContain("Successfully published");
|
||||
});
|
||||
}, 60_000);
|
||||
|
||||
test("transient asset upload failures are retried", () => {
|
||||
const f = mirrorFixture("retry");
|
||||
const result = f.run();
|
||||
expect(result.status).toBe(0);
|
||||
for (const name of f.files) expect(readFileSync(join(f.root, `count-${name}`), "utf8")).toBe("2");
|
||||
expect(result.stdout).toContain("attempt 2/3");
|
||||
}, 60_000);
|
||||
|
||||
test("correct mirror assets are verified and retained without uploading replacements", () => {
|
||||
const f = mirrorFixture("skip");
|
||||
const result = f.run();
|
||||
expect(result.status).toBe(0);
|
||||
expect(result.stdout.match(/already matches SHA-256/g)).toHaveLength(f.files.length);
|
||||
}, 60_000);
|
||||
|
||||
test("mirror-only recovery downloads and verifies the existing GitHub assets", () => {
|
||||
const f = mirrorFixture("skip", true);
|
||||
expect(f.run().status).toBe(0);
|
||||
expect(readFileSync(join(f.root, "gh.log"), "utf8")).toContain("release download v1.0.0");
|
||||
}, 60_000);
|
||||
|
||||
test("asset transfers never exceed two concurrent workers", () => {
|
||||
const f = mirrorFixture("concurrency");
|
||||
expect(f.run().status).toBe(0);
|
||||
let active = 0, peak = 0;
|
||||
for (const event of readFileSync(join(f.root, "events"), "utf8").trim().split("\n")) {
|
||||
active += event === "start" ? 1 : -1;
|
||||
peak = Math.max(peak, active);
|
||||
}
|
||||
expect(active).toBe(0);
|
||||
expect(peak).toBeLessThanOrEqual(2);
|
||||
}, 60_000);
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env bun
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { resolve, join } from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
@@ -23,6 +23,11 @@ try {
|
||||
const version = spawnSync(command, [...prefix, ...(plugin ? ["--hose-use-cli"] : []), "version", "--json"], { cwd, env, encoding: "utf8", timeout: 5000 });
|
||||
assert.equal(version.status, 0, version.stderr);
|
||||
assert.ok(JSON.parse(version.stdout).version);
|
||||
writeFileSync(join(cwd, "smoke.json"), JSON.stringify({ id: "smoke", name: "Smoke", source: "manual", credentials: { accessToken: "fixture", corpId: "smoke", staffId: "smoke:staff" } }));
|
||||
const sandbox = spawnSync(command, [...prefix, ...(plugin ? ["--hose-use-cli"] : []), "workflow", "eval-script", "--code", 'return { total: items.reduce((a, b) => a + b, 0), host: typeof process };', "--input", '{"items":[1,2,3]}', "--corp", "smoke"], { cwd, env, encoding: "utf8", timeout: 5000 });
|
||||
assert.equal(sandbox.status, 0, sandbox.stderr);
|
||||
assert.match(sandbox.stdout, /"total": 6/);
|
||||
assert.match(sandbox.stdout, /"host": "undefined"/);
|
||||
await client.connect(transport, { timeout: 5000 });
|
||||
const tools = await client.listTools();
|
||||
assert.deepEqual(tools.tools.map(tool => tool.name), ["hose_cli"]);
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
name: hose-use
|
||||
description: "合思/易快报(Ekuaibao)企业级 SaaS 一站式能力:hose-use CLI/SDK 多账号登录、租户切换、单据检索与审批动作、自建应用与工作流扫描、密钥与应用中心、常驻守护进程与 HTTP 文档/OpenAPI,以及工作流 MVEL 代码节点脚本生成调试、节点批量开通。用于一切合思/易快报相关请求。"
|
||||
metadata:
|
||||
version: 0.8.14
|
||||
version: 0.8.20
|
||||
short-description: 合思/易快报 企业级 CLI 与工作流 skill 套件(含 MVEL 代码节点)
|
||||
---
|
||||
|
||||
# hose-use (v0.8.14)
|
||||
# hose-use (v0.8.20)
|
||||
|
||||
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
|
||||
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
|
||||
@@ -52,6 +52,26 @@ metadata:
|
||||
10. **单据检索服务端过滤优先(Server-Side Filtering First)**:
|
||||
- 查询单据列表优先使用服务端时间过滤 `--since=7d`、`--since=30d`、`--start-date`、`--end-date` 或指定 `--code`,服务端毫秒级利用索引返回;
|
||||
- 在海量单据租户下,严禁无参数滥用全量检索,优先引导用户查看个人发起单据(`hose-use bill list --mine`)或待办(`hose-use task todo`)。
|
||||
11. **本地企业名录最高可信度与合思 payType 混淆防范(Local Config as Source of Truth & PayType Trap)**:
|
||||
- **本地配置具有最高权威性**:本地企业名录(`hose-use corps list` / `enterprises/*.json`)标注的环境类别(🏭 正式 / 🧪 测试 / 🎪 演示)经过人工审核确认,是判断企业真实性质的唯一权威来源;
|
||||
- **合思云端 payType 极度混乱陷阱**:合思数据库中的元数据 `payType`(如 `TRYOUT` 试用 / `PAY` 付费)存在严重的业务历史包袱,**大量真实商业付费的正式客户租户在系统底层依然被标记为 `TRYOUT`(试用)**;
|
||||
- **严禁仅凭云端标记臆断测试沙箱**:严禁仅凭云端返回的 `payType: "TRYOUT"`、或企业名称简短/包含英文就盲目认定为测试沙箱。任何写操作(包括发起协助工单 `assist-platform apply`、单据或配置变更)必须严格核对本地企业环境,仅在明确标记为 🧪 测试 的企业中进行,正式企业必须有用户显式指令与二次确认。
|
||||
12. **工作流草稿非隔离副本与生产介入明确知情权(Draft != Isolated Clone & Explicit Awareness)**:
|
||||
- **草稿绝非独立副本**:合思工作流处于草稿态(`state: 0`)仅代表“修改尚未发布生效”,它与生产流程是**同一个实体**。若直接在原流程上修改草稿,一旦点击发布就会直接覆盖生产运行逻辑,绝不可将其误认为互不影响的沙箱副本;
|
||||
- **排障或改造的知情选择权**:客户现场常存在“原本有一个生产在跑的工作流,因出错或特殊情况被停用或直接处于草稿修改中”。Agent 介入排障或调整前,**必须向用户明确揭示实体归属与当前状态**,并提供两条明确路径供用户决策:
|
||||
1. **克隆独立副本(推荐稳健路径)**:使用 `hose-use workflow copy <pipelineId>` 创建真正的独立工作流副本(如 `<原名称> 副本`),在副本上修改与联调测试,原流程不受任何触碰;
|
||||
2. **直接就地修改当前停用/草稿流程(快速就地路径)**:若用户明确知情并授权直接修复当前草稿,则就地修改,但**严格禁止擅自点击发布(publish)**,必须完成全链路验证并获得用户明确指令后方可上线。
|
||||
13. **协助会话人员身份角色穿透与高管权限防误用守则 (Assist Identity Profile & Executive Privilege Guard)**:
|
||||
- **身份与角色权限第一时间穿透呈现**:通过协助链接进入企业(`hose-use assist-platform enter`)或生成免密会话时,系统自动穿透解析并输出当前获得的员工姓名、工号、所属部门、所配角色清单以及核心系统权限;并自动将该人员画像与风控等级持久化落盘至本地企业配置(`enterprises/<corpId>.json`);
|
||||
- **高阶管理人员权限风控识别**:合思协助平台具备直接借用企业任意员工身份(包含主管理员、企业法定代表人、财务负责人/总监、VP/总裁等高管身份)的高危能力。当获取的身份命中高管关键词(总监、主管、主管理员、总经理等)或具备 `SYS_ADMIN` / `CORP_PAYMENT_MANAGE` 权限时,系统会自动发出醒目的高管权限风控警示框;
|
||||
- **防范越权与误用硬约束**:一线实施、运维人员或 AI Agent 严禁借用高管特权身份在系统内代行审批通过、款项拨付或提交非授权配置!所有协助权限必须严格局限在系统排障、配置诊断、数据核验与接口联调,严禁进行越权业务审批;
|
||||
- **协助时长服务端硬性上限**:协助平台工单申请(`POST /api/assistPlatform/create`)受服务端硬性安全管控,单次最长有效时间为 24 小时(1天),超过 24 小时服务端直接返回 400 拒绝。如需持续维护,可在工单到期后再次发起或在端内续签。
|
||||
14. **工作流代码节点文件映射与 Token 防膨胀守则 (Workflow Code Node File Mapping & Zero-Token-Waste Rule)**:
|
||||
- **严禁终端内联大段代码**:在新建或修改工作流代码节点(`code-js2` / `code`)时,**严禁使用 `--code="..."` 或在终端命令(如 `bun -e '...'`)中内联几十上百行的长代码**。内联大段代码会导致命令行参数急剧膨胀,在 Tool Calls 中产生严重的输入输出 Token 浪费,且极易因 Shell 引号转义损坏脚本语法;
|
||||
- **必须走本地文件映射与 `--code-file`**:
|
||||
1. **导出/映射**:先将节点代码提取至本地独立文件(如 `scripts/clean.js` 或 `scripts/amortize.mvel`),或使用 `hose-use workflow node get <pipelineId> <nodeName> > ./scripts/xxx.mvel`;
|
||||
2. **微创修改(Diff Edit)**:在本地文件上使用编辑工具进行精准、局部的差异修改(仅消耗几行 diff 的极少 Token);
|
||||
3. **一键同步**:使用 `hose-use workflow node edit <pipelineId> <nodeName> --code-file=./scripts/xxx.mvel --yes`(或 `node add ... --code-file=...`)通过文件流同步至云端。
|
||||
|
||||
---
|
||||
|
||||
@@ -67,6 +87,7 @@ metadata:
|
||||
| 首次登录 / 账密认证 / Token过期 / 多账号 | `hose-use auth login`, `hose-use auth status`, `hose-use auth refresh` | [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) |
|
||||
| 合思协助平台(Unity 运营平台)扫码登录/租户全量库/工单/指定身份直通/权限转交 | `hose-use assist-platform login/search/detail/tickets/staff/apply/enter/transfer` | [references/assist-platform.md](references/assist-platform.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) |
|
||||
@@ -95,7 +116,8 @@ metadata:
|
||||
| 模糊搜索已保存的企业与员工信息 | `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 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) |
|
||||
| 工作流节点树、代码依赖与静态门禁诊断(硬门禁/软建议/权限/DataLink公式) | `hose-use workflow analyze <pipelineId> [--fail]` | [references/workflow.md](references/workflow.md) |
|
||||
| 企业已开通工作流节点字典探针与灰度开通 | `hose-use workflow nodes [--all]`, `hose-use workflow nodes grant <type...>` | [references/workflow.md](references/workflow.md) |
|
||||
| 工作流错误管道扫描与本地去重提醒 | `hose-use workflow 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) |
|
||||
@@ -202,13 +224,17 @@ hose-use workflow patch wf_01k83y... --file=workflow.json --path=tasks.0.code --
|
||||
hose-use workflow history wf_01k83y... --json # 查看服务端版本快照历史
|
||||
hose-use workflow check --json --fail-on-alert # 扫描错误管道并只提醒新增错误计数
|
||||
hose-use workflow publish wf_01k83y... --yes # 将保存后的工作流发布/启用
|
||||
hose-use workflow nodes # 探查当前企业已开通的工作流节点字典(动作/控制/触发器)
|
||||
hose-use workflow nodes --all # 对照官方 108 个灰度节点清单查看全量开通状态
|
||||
hose-use workflow nodes grant code-js2 # 申请开通灰度节点(支持免密模式或 --password 预留密码管控)
|
||||
hose-use workflow create --name="风险推送" --trigger=webhook --yes # 从零新建工作流 (支持 new, add, 自动分配 Webhook UUID, 强制草稿 state=0)
|
||||
hose-use workflow copy wf_01k83y... --name="监控克隆版" --yes # 复制工作流为新草稿 (支持 cp, clone, 自动重置 Webhook urlPath)
|
||||
hose-use workflow webhook send wf_01k83y... --bill=<单号> --yes # 向 Webhook 发送测试载荷(解决【获取更多数据样本】无事件问题)
|
||||
hose-use workflow delete wf_01k83y... --yes # 安全删除工作流 (支持 rm, remove, 带 --dry-run 预览)
|
||||
hose-use workflow node list wf_01k83y... # 树形层级索引查看工作流任务节点树与摘要 (别名 ls)
|
||||
hose-use workflow node get wf_01k83y... <节点name或#序号> # 查看指定节点的完整配置 (别名 show, info)
|
||||
hose-use workflow node add wf_01k83y... --type=code-js2 --label="清洗" --code="return items;" --yes # 声明式追加节点 (--after/--parent 插入)
|
||||
hose-use workflow node edit wf_01k83y... <节点name或#序号> --label="新标题" --yes # 定向修改节点配置
|
||||
hose-use workflow node add wf_01k83y... --type=code-js2 --label="清洗" --code-file=./clean.js --yes # 声明式追加节点 (支持 --code-file 导入)
|
||||
hose-use workflow node edit wf_01k83y... <节点name或#序号> --code-file=./clean.js --yes # 从本地文件同步最新脚本 (推荐,零 Token 浪费)
|
||||
hose-use workflow node rm wf_01k83y... <节点name或#序号> --yes # 安全移除任务节点 (首节点触发器安全防御)
|
||||
hose-use workflow tail wf_01k83y... # 类似 tail -f 实时监听新任务派发与节点执行日志流 (别名 watch, follow)
|
||||
hose-use workflow tail wf_01k83y... --job=<jobId> # 针对单个执行中的 Job 实时跟踪直至终态
|
||||
|
||||
@@ -144,3 +144,11 @@ result;
|
||||
Then add one field access at a time. For code nodes nested inside a condition branch, still return a normal object from the code node; only condition expressions themselves must return boolean.
|
||||
|
||||
Treat tenant-specific behavior as evidence, not a universal rule. Say what assumption the code is using when syntax compatibility is uncertain.
|
||||
|
||||
## Deployment & CLI Integration (Zero-Token-Waste Rule)
|
||||
|
||||
- **Always maintain MVEL scripts in local dedicated files** (e.g. `./scripts/node_calc.mvel`), never pass long scripts inline in `--code="..."` or in terminal `bun -e '...'` expressions.
|
||||
- **Local syntax check**: `hose-use workflow lint-script --file=./scripts/node_calc.mvel --type=code`
|
||||
- **Deploy to workflow node**: `hose-use workflow node edit <pipelineId> <nodeName> --code-file=./scripts/node_calc.mvel --yes`
|
||||
- **End-to-end cloud simulation test**: `hose-use workflow test <pipelineId> --flow <billCode> --yes --force`
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
# 合思协助平台(Unity 运营中心)
|
||||
|
||||
本专卷覆盖对接合思官方内部运营平台(Unity Assist Platform,`https://unity.ekuaibao.com/platform-charge/`)及其统一身份认证(SSO,`https://sso.hosecloud.com`)的自动化能力。
|
||||
|
||||
合思协助平台是面向实施、运维与服务团队的专属运营系统(管理 34 万+ 企业租户库),与终端企业 SaaS 门户(`app.ekuaibao.com`)互为独立站点。通过本模块,Agent 可完成从扫码登录、多租户全量库检索、协助工单提取、指定员工身份免密换票,到自动将目标企业一键持久化落盘至本地名录的全流程。
|
||||
|
||||
支持顶层命令:`hose-use assist-platform`(别名:`hose-use assist-center`, `hose-use ap`)。
|
||||
|
||||
---
|
||||
|
||||
## 1. 协助平台会话登录 (`login`)
|
||||
|
||||
协助平台基于合思 SSO 进行钉钉扫码登录。本工具支持自动轮询二维码状态,也支持直接导入已有 Session Token。
|
||||
|
||||
```bash
|
||||
# 检查当前协助平台的登录状态与有效性
|
||||
hose-use assist-platform login --status
|
||||
|
||||
# 交互式二维码登录(输出终端二维码,并监听钉钉扫码与确认事件)
|
||||
hose-use assist-platform login
|
||||
|
||||
# 直接绑定已有 Token 会话并持久化
|
||||
hose-use assist-platform login --token <session-token>
|
||||
|
||||
# 退出协助平台登录态
|
||||
hose-use assist-platform login --logout
|
||||
```
|
||||
|
||||
凭证安全落盘位置:`~/.config/hose-use/assist-platform.json`(权限 0600)。
|
||||
|
||||
---
|
||||
|
||||
## 2. 检索企业库 (`search` / `detail`)
|
||||
|
||||
在拥有 34 万+ 企业的全量库中检索目标租户,获取企业 ID 与基本信息。
|
||||
|
||||
```bash
|
||||
# 按关键词或企业 ID 检索企业
|
||||
hose-use assist-platform search "示例公司"
|
||||
hose-use assist-platform search "Cxa3oOtQi2eS$g" --json
|
||||
|
||||
# 查看企业详细画像(创建时间、版本、授权范围、联系人及备注)
|
||||
hose-use assist-platform detail "Cxa3oOtQi2eS$g"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. 协助工单探查 (`tickets`)
|
||||
|
||||
协助平台进入客户租户必须依赖有效的协助工单。
|
||||
|
||||
```bash
|
||||
# 查询指定企业当前所有协助工单
|
||||
hose-use assist-platform tickets <企业ID>
|
||||
|
||||
# 查看历史全部工单(包含已结束/已撤回)
|
||||
hose-use assist-platform tickets <企业ID> --all --limit 20
|
||||
```
|
||||
|
||||
工单信息包含:工单编号 (`ticketId`)、申请人、申请事由、起始时间与过期时间。
|
||||
|
||||
> [!WARNING] 合思底层 payType 混淆与本地企业名录可信度原则
|
||||
> 1. **合思付费模式混乱**:合思数据库中的 `payType`(`TRYOUT` 试用 / `PAY` 付费)存在严重的业务历史包袱,**大量真实商业付费的正式生产客户在系统中依然被标记为 `TRYOUT`(试用)**。
|
||||
> 2. **严禁仅凭云端标记臆断沙箱**:严禁仅凭云端返回的 `payType: "TRYOUT"` 擅自推断企业为测试沙箱!
|
||||
> 3. **本地配置权威优先**:判断企业性质必须以本地企业配置(`hose-use corps list` / `enterprises/*.json`)标注的环境类别(🏭 正式 / 🧪 测试 / 🎪 演示)为准,本地配置具有最高权威性。任何写操作(如发起协助工单 `apply`)严禁在未经授权的正式企业上执行。
|
||||
|
||||
---
|
||||
|
||||
## 4. 员工名录检索 (`staff`)
|
||||
|
||||
当需要以客户企业内特定员工身份(而非主管理员)代客进入时,可通过 `staff` 检索目标人员的 `staffId`。
|
||||
|
||||
```bash
|
||||
# 按姓名精确或模糊搜索员工
|
||||
hose-use assist-platform staff <企业ID> --name "李志财"
|
||||
|
||||
# 按手机号或工号过滤
|
||||
hose-use assist-platform staff <企业ID> --mobile "13800000000"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. 发起协助申请工单 (`apply`)
|
||||
|
||||
当企业名下没有生效工单或工单已过期时,可向目标企业发起新的协助授权申请。**注意:写操作仅限在本地确认的 🧪 测试企业中进行,正式企业必须获得用户明确指示。**
|
||||
|
||||
> [!IMPORTANT] 协助时长服务端硬性上限与 24 小时限制
|
||||
> 合思协助平台服务端(`POST /api/assistPlatform/create`)实施了底层的硬性安全管控:
|
||||
> - 单次协助工单最长有效期限为 **24 小时 (1天)**;
|
||||
> - 超过 24 小时(如 48 小时或 7 天)服务端会直接报错 `{"errorCode":400,"errorMessage":"参数错误,申请时间不能超过24小时"}` 并拒绝受理;
|
||||
> - 命令行同时支持 `--hours <小时>` 与 `--days <天数>`,传入超过 24 小时(> 1 天)将即时给出阻断与友好提示。如需持续维护,可在工单到期后再次发起或在端内续签。
|
||||
|
||||
```bash
|
||||
# 查看变更预览(安全 Dry-Run)
|
||||
hose-use assist-platform apply ID01ofWoOC1wiX --dry-run
|
||||
|
||||
# 向测试企业发起 24 小时(1天)协助工单申请
|
||||
hose-use assist-platform apply ID01ofWoOC1wiX --message "测试环境接口联调" --hours 24 --yes
|
||||
hose-use assist-platform apply ID01ofWoOC1wiX --message "测试环境接口联调" --days 1 --yes
|
||||
```
|
||||
|
||||
提交后工单初始状态为 `🟡 待提供`,等待企业管理员登录合思 Web/桌面端确认开启授权即可激活。
|
||||
|
||||
---
|
||||
|
||||
## 6. 企业端通过协助授权 (`approve`)
|
||||
|
||||
当企业端收到协助申请后,企业管理员可在 Web 端【系统配置 ➔ 合思助手 ➔ 工单列表】中点击“授权”,亦可通过本 CLI 命令直接审批通过工单(需要本地具备该企业的管理员会话凭证)。
|
||||
|
||||
```bash
|
||||
# 查看变更预览(安全 Dry-Run)
|
||||
hose-use assist-platform approve --corp ID01ofWoOC1wiX --dry-run
|
||||
|
||||
# 自动寻找最新待提供工单并批准生效
|
||||
hose-use assist-platform approve --corp ID01ofWoOC1wiX --yes
|
||||
|
||||
# 显式指定工单编号批准生效
|
||||
hose-use assist-platform approve ID01Xeno3GpoNV --corp ID01ofWoOC1wiX --yes
|
||||
```
|
||||
|
||||
批准通过后,工单状态立即变为 `🟢 生效中`,可由运维侧立即免密进入。
|
||||
|
||||
---
|
||||
|
||||
## 7. 免密代客进入、身份穿透与高管风控 (`enter`)
|
||||
|
||||
基于选定工单与身份(管理员或指定员工),向协助平台换取免密直通链接,并支持一键落盘到本地企业库和自动提权。
|
||||
|
||||
### 7.1 人员身份画像穿透与高管权限防误用守则
|
||||
|
||||
> [!WARNING] 高阶管理人员权限风控警示 (Executive Role Risk Warning)
|
||||
> 1. **人员身份全景穿透**:通过协助链接进入企业或生成免密会话时,CLI 会自动向合思组织架构服务下钻查询,第一时间提取当前获得的员工姓名、工号、绑定手机、所属部门、所配角色清单以及核心系统权限;
|
||||
> 2. **持久化落盘安全标记**:落盘至本地(`enterprises/<corpId>.json`)时,会将 `departmentName`, `roles`, `roleTitles`, `isSeniorExecutive`, `riskLevel`, `permissions` 完整写入 `session` 元数据中,确保后续执行可知;
|
||||
> 3. **高管身份命中与警示框**:当角色命中总监、主管理员、财务负责人、总经理、CEO/CFO 等高级头衔,或包含 `SYS_ADMIN` / `CORP_PAYMENT_MANAGE` 时,终端将输出醒目的高管权限风控警示框;
|
||||
> 4. **严禁越权业务审批**:一线实施、运维人员或 AI Agent 严禁代用高管身份进行业务审批通过、款项拨付或非授权单据提交,仅限用于排障与配置诊断。
|
||||
|
||||
```bash
|
||||
# 1. 仅获取免密直达 URL 与临时 Token(默认自动寻找最新有效工单,即时输出身份画像与风控警示)
|
||||
hose-use assist-platform enter <企业ID>
|
||||
|
||||
# 2. 以主管理员身份进入
|
||||
hose-use assist-platform enter <企业ID> --admin
|
||||
|
||||
# 3. 指定员工姓名代客进入(内部自动匹配员工库 staffId)
|
||||
hose-use assist-platform enter <企业ID> --name "李志财"
|
||||
|
||||
# 4. 指定工单 ID 与 staffId 进入
|
||||
hose-use assist-platform enter <企业ID> --ticket <ticketId> --staff <staffId>
|
||||
|
||||
# 5. 【推荐一键流】获取免密链接后,自动落盘至本地企业名录并切换为当前上下文(持久化保存身份与权限元数据)
|
||||
hose-use assist-platform enter <企业ID> --name "李志财" --save --switch
|
||||
|
||||
# 6. 【高阶全自动】落盘并自动提权(换取永久 OpenAPI 密钥,避免 2 小时临时 Token 过期中断业务)
|
||||
hose-use assist-platform enter <企业ID> --name "李志财" --save --switch --elevate
|
||||
```
|
||||
|
||||
### 参数说明
|
||||
|
||||
| 参数 | 说明 |
|
||||
|---|---|
|
||||
| `<corpId>` | 目标企业 ID(必填) |
|
||||
| `--ticket <id>` | 指定协助工单 ID(缺省时自动采用最新有效工单) |
|
||||
| `--admin` | 以企业主管理员身份进入 |
|
||||
| `--staff <id>` | 指定代客员工的内部 ID (`staffId`) |
|
||||
| `--name <姓名>` | 指定代客员工的真实姓名(自动检索匹配并转换) |
|
||||
| `--save` | 换取成功后直接调用底层能力导入本地企业名录(`enterprises/<id>.json`) |
|
||||
| `--switch` | 导入后自动切换为当前活跃企业租户 |
|
||||
| `--elevate` | 导入后自动探测并保存持久化 OpenAPI Key 与 Secret,实现长期免密接入 |
|
||||
| `--json` | 输出结构化 JSON 结果 |
|
||||
|
||||
---
|
||||
|
||||
## 8. 协助工单转交 (`transfer`)
|
||||
|
||||
当已获得客户授权的工单需要移交给其他运维、实施或研发同事时,可使用转交功能直接将权限移交给目标人员,**无需客户侧重新发起审批授权**。
|
||||
|
||||
```bash
|
||||
# 查看具备协助权限的可转交人员列表
|
||||
hose-use assist-platform transfer --candidates
|
||||
hose-use assist-platform transfer --candidates "陈龙"
|
||||
|
||||
# 查看转交预览(安全 Dry-Run)
|
||||
hose-use assist-platform transfer <企业ID> --to "陈龙" --dry-run
|
||||
|
||||
# 一键转交指定企业的当前生效协助工单
|
||||
hose-use assist-platform transfer <企业ID> --to "陈龙" --remarks "排障任务交接" --yes
|
||||
|
||||
# 显式指定工单号转交
|
||||
hose-use assist-platform transfer <企业ID> <工单ID> --to "陈龙" --yes
|
||||
```
|
||||
|
||||
### 参数说明
|
||||
|
||||
| 参数 | 说明 |
|
||||
|---|---|
|
||||
| `<corpId>` | 目标企业 ID(必填) |
|
||||
| `[ticketId]` | 指定转交的协助工单编号(缺省时自动采用企业当前生效的工单) |
|
||||
| `--to <姓名\|工号\|账号>` | 转交接收人,支持输入姓名(如“陈龙”)、工号(如“3016”)或账号(如“chenlong3016”) |
|
||||
| `--candidates` | 查询内部具备协助权限的可转交人员名单 |
|
||||
| `--remarks <备注>` | 添加转交附言或任务交接说明(100 字以内) |
|
||||
| `--dry-run` | 预览转交参数与接收人匹配结果,不发起网络写操作 |
|
||||
| `--yes, -y` | 显式确认执行转交 |
|
||||
@@ -143,17 +143,49 @@ hose-use workflow toggle wf_01k83y... --enable
|
||||
hose-use workflow toggle wf_01k83y... --disable
|
||||
```
|
||||
|
||||
## 7. 工作流静态分析 (`workflow analyze`)
|
||||
## 7. 工作流静态分析与发布门禁 (`workflow analyze`)
|
||||
|
||||
读取工作流详情并生成递归节点树、代码表达式引用依赖和静态风险诊断(只读,不执行工作流)。内置以下核心风险检测:
|
||||
- `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`,导致单据模板联动静默覆盖工作流显式传入的值。
|
||||
读取工作流详情并生成递归节点树、代码表达式引用依赖和静态风险诊断(只读,不执行工作流)。
|
||||
诊断结果显式划分为 **⛔ 硬门禁 (Hard Block)** 与 **💡 软建议 (Soft Advice)**:
|
||||
- **⛔ 硬门禁**(必挂致命缺陷):
|
||||
- `PERMISSION_MISSING_NODE`:使用了租户未开通的灰度节点(如未开通时的 `code-js2`);
|
||||
- `MISPLACED_FORMULA_IN_DATALINK_MAPPING`:在底层 DataLink 数据写入节点中配置了前端表单公式(如 `AddMonths(...)`);
|
||||
- `DOCS_DOMAIN_USED`:HTTP 节点误配开放平台文档域名 `docs.ekuaibao.com`(接口实际网关为 `app.ekuaibao.com`);
|
||||
- `UNLICENSED_POWER_CODE`:HTTP 节点携带了未开通功能代码(如 `TICKET_AUDIT_switch`),网关将返回 403 Forbidden;
|
||||
- `EMPTY_CODE`:代码节点缺少可执行脚本;
|
||||
- `DEADLOCK_TRIGGER_STATE_FILTER` / `DEADLOCK_CONDITION_STATE_FILTER`:单据状态误配置导致事件静默丢弃或条件恒假;
|
||||
- `INVALID_ACTION_ENUM_TEXT_VALUE`:枚举字段误配纯中文文本导致无法匹配。
|
||||
- **💡 软建议**(最佳实践与潜在风险):
|
||||
- `WORKFLOW_DISABLED`:工作流处于停用状态(`state === 0`);
|
||||
- `UNSAFE_SKIP_WITHOUT_STATUS_GUARD`:循环容器(`every`)内创单节点配置了 SKIP 跳过,但后续节点未校验前序状态;
|
||||
- `LINKAGE_PRIORITY_OVERRIDE`:单据模板联动优先级高于手工/API 传入。
|
||||
|
||||
```bash
|
||||
# 1. 静态分析指定工作流(直观展示硬门禁与软建议分类表格)
|
||||
hose-use workflow analyze 886351399301758976
|
||||
|
||||
# 2. 作为 CI/CD 或脚本门禁运行(存在硬门禁时 exitCode = 2 阻断发布)
|
||||
hose-use workflow analyze 886351399301758976 --fail
|
||||
|
||||
# 3. 输出结构化 JSON
|
||||
hose-use workflow analyze 886351399301758976 --json
|
||||
```
|
||||
|
||||
## 7.1 企业已开通节点探针与灰度开通 (`workflow nodes`)
|
||||
|
||||
合思微前端(Piper)仅向开通了权限的租户展示对应节点,未开通节点在界面中隐身且运行时直接报错:
|
||||
|
||||
```bash
|
||||
# 1. 查看当前企业已开通的节点字典(动作/控制/触发)
|
||||
hose-use workflow nodes
|
||||
|
||||
# 2. 与官方全量 108 个灰度节点清单进行完整对照
|
||||
hose-use workflow nodes --all
|
||||
|
||||
# 3. 申请开通灰度节点(支持节点拼音与中文名)
|
||||
hose-use workflow nodes grant code-js2
|
||||
```
|
||||
|
||||
## 8. 工作流单次运行实例排障 (`workflow job`)
|
||||
|
||||
当工作流执行报错、或因为子节点配置了 `SKIP` 导致外层状态显示为 `COMPLETED` 但内部实际创单失败时,使用 `workflow job` 下钻单次运行实例:
|
||||
@@ -238,6 +270,13 @@ hose-use workflow publish <pipelineId>
|
||||
|
||||
对标合思 EASO/Piper 网页端“新建工作流”、“复制流水线”与“删除”功能,严格遵循 `--dry-run` 预览与 `--yes` 安全确认门禁,且新流程初始状态**强制锁定为草稿未启用(`state = 0`)**:
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **核心避坑认知:草稿不等于隔离副本(Draft != Isolated Clone)**
|
||||
> - **草稿态实质**:合思工作流的草稿状态(`state: 0`)仅表示“改动尚未发布对线上生效”,它与线上流程是**同一个实体**。直接在生产工作流上改草稿,一旦点击发布就会直接覆盖线上运行逻辑,绝不可将其误认为独立的沙箱副本;
|
||||
> - **生产排障与改造的知情权**:客户现场常存在“原有一个生产在跑的工作流,因出错或特殊情况被停用或直接处于草稿修改中”。介入排障或调整前,**必须向用户明确说明当前实体性质**,并提供清晰决策路径:
|
||||
> 1. **克隆独立副本(推荐稳健路径)**:使用 `workflow copy` 克隆出新流水线(如 `<原名称> 副本`),在副本上修改与联调测试,原流程不受任何触碰;
|
||||
> 2. **就地修改当前停用/草稿流程(快速就地路径)**:若用户明确知情并同意直接修复当前草稿,则就地修改,但**严格禁止擅自点击发布(publish)**,必须完成全链路验证并获得用户明确指令后方可上线。
|
||||
|
||||
```bash
|
||||
# 1. 从零新建工作流(支持自动初始化 Webhook、定时 Clock、业务对象 DataLink 或单据 Flowform 首节点)
|
||||
hose-use workflow create --name="外部风险推送" --trigger=webhook --yes
|
||||
@@ -282,15 +321,17 @@ hose-use workflow node get <pipelineId> 2 --json
|
||||
|
||||
# 3. 声明式向工作流追加或定向插入新节点 (别名: append, insert)
|
||||
# 默认追加至流程末尾;支持通过 --parent=<容器节点> 插入循环/分支内,或 --after=<节点> 插入指定节点后
|
||||
hose-use workflow node add <pipelineId> --type=code-js2 --label="数据过滤" --code="return items.filter(x => x.amount > 0);" --dry-run
|
||||
hose-use workflow node add <pipelineId> --type=code-js2 --label="数据过滤" --code="return items.filter(x => x.amount > 0);" --yes
|
||||
# 推荐做法(零 Token 浪费 & 避开命令行转义):从本地脚本文件导入代码
|
||||
hose-use workflow node add <pipelineId> --type=code-js2 --label="数据过滤" --code-file=./scripts/filter.js --yes
|
||||
hose-use workflow node add <pipelineId> --type=stop --label="超额阻断" --after=action_dx9cci --yes
|
||||
hose-use workflow node add <pipelineId> --type=http --label="外部通知" --parent=control_every_1 --yes
|
||||
|
||||
# 4. 定向修改指定节点配置 (别名: update, set)
|
||||
# 支持修改 --label, --desc, --code, 或通过 --set="key=value" 定向覆盖任意属性
|
||||
hose-use workflow node edit <pipelineId> action_dx9cci --label="清洗增强版" --code="return items;" --dry-run
|
||||
hose-use workflow node edit <pipelineId> action_dx9cci --label="清洗增强版" --code="return items;" --yes
|
||||
# 支持修改 --label, --desc, --code, --code-file, 或通过 --set="key=value" 定向覆盖任意属性
|
||||
# 推荐做法(零 Token 浪费 & 避开命令行转义):从本地文件导入脚本
|
||||
hose-use workflow node edit <pipelineId> action_dx9cci --code-file=./scripts/clean.js --dry-run
|
||||
hose-use workflow node edit <pipelineId> action_dx9cci --code-file=./scripts/clean.js --yes
|
||||
hose-use workflow node edit <pipelineId> action_dx9cci --label="清洗增强版" --yes
|
||||
hose-use workflow node edit <pipelineId> 2 --set="method=GET" --yes
|
||||
|
||||
# 5. 安全移除指定任务节点 (别名: remove, delete, del)
|
||||
@@ -379,3 +420,26 @@ hose-use workflow eval-script --code="console.log(items); return items.filter(x
|
||||
- 执行 `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`)安全修复。
|
||||
|
||||
---
|
||||
|
||||
## 19. Webhook 触发器测试样本打桩与注入 (`workflow webhook send`)
|
||||
|
||||
当在合思 Web 控制台复制或新建 Webhook 触发的工作流时,经常遇到点击【获取更多数据样本】一直转圈等待外部事件打过来的情况。`hose-use` 提供了直接向工作流专属 Webhook 发送测试载荷的注入命令:
|
||||
|
||||
```bash
|
||||
# 1. 抓取真实单据数据作为测试载荷发送,立即生成最新数据样本
|
||||
hose-use workflow webhook send <pipelineId> --bill=<单号或ID> --yes
|
||||
|
||||
# 2. 发送自定义 JSON 请求体
|
||||
hose-use workflow webhook send <pipelineId> --body='{"event":"test","amount":100}' --yes
|
||||
|
||||
# 3. 从文件读取载荷
|
||||
hose-use workflow webhook send <pipelineId> --file=./mock_payload.json --yes
|
||||
|
||||
# 4. 预演检查(查看目标 Webhook 真实地址与组装后的 Payload)
|
||||
hose-use workflow webhook send <pipelineId> --bill=<单号> --dry-run
|
||||
```
|
||||
|
||||
发送成功后,Piper 后端立刻捕获该记录,在 Web 界面点击【获取更多数据样本】即可秒级看到该样本;在命令行也可以直接用 `hose-use workflow test <pipelineId> --sample=1` 进行沙箱调测。
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
"openapi": "3.1.0",
|
||||
"info": {
|
||||
"title": "hose-use API & MCP Tools Specification",
|
||||
"version": "0.8.14",
|
||||
"version": "0.8.20",
|
||||
"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.14
|
||||
version: 0.8.20
|
||||
description: >-
|
||||
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
|
||||
servers:
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#!/usr/bin/env bun
|
||||
import { isDryRun, mutationPreview } from "./cli/mutation.js";
|
||||
import { parseArgs, stringOption, booleanOption, isJsonRequested } from "./cli/parser.js";
|
||||
import { cliErrorResult } from "./cli/runner.js";
|
||||
import { printHelp, printJson, redactSensitiveText } from "./cli/printer.js";
|
||||
@@ -48,6 +49,12 @@ async function runAiProCliOnce(rawArgs: string[]): Promise<{ stdout: string; std
|
||||
});
|
||||
|
||||
const corp = runtime.selectedCorp;
|
||||
const previewPositional = parsed.positional || [];
|
||||
const previewCommand = (previewPositional[0] || "help").toLowerCase();
|
||||
const mutating = ["init", "start", "bind", "mount", "review", "eval", "evaluate", "decide", "approve", "reject"].includes(previewCommand) || (["points", "clauses"].includes(previewCommand) && previewPositional.length >= 3);
|
||||
if (mutating && isDryRun(parsed, runtime)) {
|
||||
return mutationPreview({ ...parsed, raw: ["aipro", ...rawArgs] }, runtime, "预览 AI PRO 审批操作", stringOption(parsed.options, ["run", "r", "code", "sn", "id", "target"]) || previewPositional[1] || "未指定", { action: previewCommand, corpId: corp?.corpId || corp?.id, apply: booleanOption(parsed.options, ["apply", "execute", "run", "do"]) });
|
||||
}
|
||||
const repo = new ApprovalRepository();
|
||||
const service = new ApprovalService(repo);
|
||||
let cachedSession: Awaited<ReturnType<typeof getSessionClientForRuntime>> | undefined;
|
||||
|
||||
@@ -32,3 +32,5 @@
|
||||
优先用 `--corp` 明确指定企业。短参数 `-c` 在命令之前表示全局企业选择;在声明了同名参数的命令之后,遵循该命令的含义(例如 `bill list -c` 为单号)。布尔值可写 `--active=false` 或 `--active false`;数字形式使用 `=0` / `=1`,空格后的数字保留为可能的位置 ID。`--` 之后的内容全部作为位置参数。
|
||||
|
||||
`hose-use mcp [serve]` 在当前进程启动服务,不派生 Bun 或访问源码脚本;MCP 调用继续只通过 `hose_cli` 分发,流式终端回调不会被注入协议通道。
|
||||
|
||||
`update --dry-run` 返回源码或二进制更新计划,不请求发布源、不执行 git/依赖安装、不替换二进制或同步技能;`update check` 和发布历史查询保留只读查询行为。
|
||||
@@ -0,0 +1,33 @@
|
||||
import { afterEach, expect, test } from "bun:test";
|
||||
import { mkdtempSync, mkdirSync, writeFileSync, existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
import { runAiProCli } from "../aipro-cli.js";
|
||||
import { runCli } from "./runner.js";
|
||||
import { closeDatabase } from "../core/db/index.js";
|
||||
const keys = ["HOSE_APPROVAL_DB", "HOSE_ENTERPRISES_DIR", "HOSE_CONFIG_FILE"] as const;
|
||||
const original = keys.map(key => process.env[key]);
|
||||
afterEach(() => { closeDatabase(); keys.forEach((key, i) => { if (original[i] === undefined) delete process.env[key]; else process.env[key] = original[i]; }); });
|
||||
test("approval and aipro dry-runs override apply/yes without requests or database creation", async () => {
|
||||
const root = mkdtempSync(join(tmpdir(), "hose-approval-preview-"));
|
||||
const corps = join(root, "corps"); mkdirSync(corps);
|
||||
writeFileSync(join(corps, "corp.json"), JSON.stringify({ id: "corp", name: "Preview", source: "manual", credentials: { accessToken: "fixture", corpId: "corp", staffId: "staff" } }));
|
||||
process.env.HOSE_ENTERPRISES_DIR = corps;
|
||||
process.env.HOSE_CONFIG_FILE = join(root, "config.json");
|
||||
process.env.HOSE_APPROVAL_DB = join(root, "approval.db");
|
||||
const originalFetch = globalThis.fetch;
|
||||
let requests = 0;
|
||||
globalThis.fetch = (async () => { requests++; throw new Error("No network during preview"); }) as any;
|
||||
try {
|
||||
for (const action of ["points", "review", "decide", "approve", "reject"]) {
|
||||
const result = await runCli(["approval", action, "SN", "--apply", "--yes", "--dry-run", "--json"]);
|
||||
expect(result.exitCode).toBe(0); expect(JSON.parse(result.stdout).dryRun).toBe(true);
|
||||
}
|
||||
for (const action of ["init", "bind", "review", "decide", "approve", "reject"]) {
|
||||
const result = await runAiProCli([action, "approve", "--run", "ABC123", "--apply", "--yes", "--dry-run", "--json"]);
|
||||
expect(result.exitCode).toBe(0); expect(JSON.parse(result.stdout).dryRun).toBe(true);
|
||||
expect(JSON.parse(result.stdout).nextAction).toStartWith("hose-use aipro ");
|
||||
}
|
||||
expect(requests).toBe(0); expect(existsSync(process.env.HOSE_APPROVAL_DB)).toBe(false);
|
||||
} finally { globalThis.fetch = originalFetch; }
|
||||
});
|
||||
@@ -0,0 +1,260 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, spyOn } from "bun:test";
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import ky from "ky";
|
||||
import { saveAssistPlatformSession } from "../core/auth/assist-platform-store.js";
|
||||
import { saveCorpConfig } from "../core/config/loader.js";
|
||||
import { CorpContext } from "../core/config/manager.js";
|
||||
import { BusinessError } from "../core/errors.js";
|
||||
import { importAssistSessionToLocal, inspectAssistIdentity } from "../domains/assist-platform/services.js";
|
||||
import { runCli } from "./runner.js";
|
||||
|
||||
const envKeys = ["HOSE_STATE_DIR", "HOSE_ASSIST_PLATFORM_FILE", "HOSE_CONFIG_FILE", "HOSE_ENTERPRISES_DIR"] as const;
|
||||
const token = "fixture-session-token";
|
||||
const loginUrl = `https://session.example/web/thirdparty.html?accessToken=${token}&ekbCorpId=NEW`;
|
||||
const baseUrl = "https://session.example";
|
||||
|
||||
describe("assist session lifecycle regressions", () => {
|
||||
let root: string;
|
||||
let corps: string;
|
||||
let originalEnv: Array<string | undefined>;
|
||||
let originalFetch: typeof fetch;
|
||||
let requests: string[];
|
||||
let handleRequest: (req: Request) => Response | Promise<Response>;
|
||||
let staffAvailable: boolean;
|
||||
let rolesAvailable: boolean;
|
||||
let jwtAdmin: boolean | undefined;
|
||||
let keysResponse: () => Response;
|
||||
let logCredentials: boolean;
|
||||
|
||||
beforeEach(() => {
|
||||
root = mkdtempSync(join(tmpdir(), "hose-assist-session-"));
|
||||
corps = join(root, "corps");
|
||||
mkdirSync(corps);
|
||||
originalEnv = envKeys.map((key) => process.env[key]);
|
||||
process.env.HOSE_STATE_DIR = root;
|
||||
process.env.HOSE_ASSIST_PLATFORM_FILE = join(root, "assist.json");
|
||||
process.env.HOSE_CONFIG_FILE = join(root, "config.json");
|
||||
process.env.HOSE_ENTERPRISES_DIR = corps;
|
||||
saveAssistPlatformSession({ token: "fixture-platform-token", baseUrl: "https://assist.example/api", updatedAt: Date.now() });
|
||||
requests = [];
|
||||
staffAvailable = true;
|
||||
rolesAvailable = true;
|
||||
jwtAdmin = false;
|
||||
logCredentials = false;
|
||||
keysResponse = () => Response.json({ items: [] });
|
||||
handleRequest = async (req) => {
|
||||
const url = req.url;
|
||||
if (url.includes("assistPlatform/getToken")) {
|
||||
if (logCredentials) {
|
||||
console.log(`diagnostic ${loginUrl}`);
|
||||
console.error(`diagnostic ${loginUrl}`);
|
||||
}
|
||||
return Response.json({ value: { token, loginUrl, baseUrl } });
|
||||
}
|
||||
if (url.includes("organization/staffs/me")) {
|
||||
return staffAvailable
|
||||
? Response.json({ value: { staff: { id: "NEW:staff", name: "员工", admin: false }, permissions: [] } })
|
||||
: new Response("Forbidden", { status: 403 });
|
||||
}
|
||||
if (url.includes("/roles")) {
|
||||
return rolesAvailable ? Response.json({ items: [] }) : new Response("Forbidden", { status: 403 });
|
||||
}
|
||||
if (url.includes("actions/jwt")) {
|
||||
const payload = Buffer.from(JSON.stringify({ staffId: "NEW:staff", staffName: "JWT员工", isAdmin: jwtAdmin, corporationName: "新企业" })).toString("base64url");
|
||||
return Response.json({ id: `fixture.${payload}.signature` });
|
||||
}
|
||||
if (url.includes("/account/v2/session")) {
|
||||
return Response.json({ value: { id: "session", corporationId: "NEW", loginStaffId: "NEW:staff", platform: "ASSIST" } });
|
||||
}
|
||||
if (url.includes("/innerapi/v1/key")) return keysResponse();
|
||||
throw new Error(`Unexpected mocked request: ${url}`);
|
||||
};
|
||||
originalFetch = globalThis.fetch;
|
||||
globalThis.fetch = (async (input: string | Request | URL, init?: RequestInit) => {
|
||||
const req = input instanceof Request ? input : new Request(input.toString(), init);
|
||||
requests.push(req.url);
|
||||
return handleRequest(req);
|
||||
}) as typeof fetch;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
globalThis.fetch = originalFetch;
|
||||
envKeys.forEach((key, index) => {
|
||||
if (originalEnv[index] === undefined) delete process.env[key];
|
||||
else process.env[key] = originalEnv[index];
|
||||
});
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const enterArgs = ["assist-platform", "enter", "NEW", "--ticket", "T"];
|
||||
const importSession = (options: { elevate?: boolean } = {}) => importAssistSessionToLocal(
|
||||
ky.create({ prefix: "https://assist.example/api" }),
|
||||
{ corpId: "NEW", ticketId: "T", enterprisesDir: corps, ...options }
|
||||
);
|
||||
|
||||
it("dry-run previews every enter branch without authentication, requests or persistence", async () => {
|
||||
rmSync(process.env.HOSE_ASSIST_PLATFORM_FILE!);
|
||||
for (const extra of [[], ["--save"], ["--switch"], ["--save", "--switch", "--yes"]]) {
|
||||
for (const json of [[], ["--json"]]) {
|
||||
const result = await runCli([...enterArgs, ...extra, "--dry-run", ...json]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(json.length ? JSON.parse(result.stdout).dryRun : result.stdout.includes("[DRY-RUN]")).toBe(true);
|
||||
}
|
||||
}
|
||||
expect(requests).toHaveLength(0);
|
||||
expect(existsSync(join(corps, "NEW.json"))).toBe(false);
|
||||
expect(existsSync(process.env.HOSE_CONFIG_FILE!)).toBe(false);
|
||||
});
|
||||
|
||||
it("runCli preserves delivered login URLs in text and JSON while redacting captured diagnostics", async () => {
|
||||
logCredentials = true;
|
||||
for (const extra of [[], ["--json"]]) {
|
||||
const result = await runCli([...enterArgs, ...extra]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.preserveSensitiveStdout).toBe(true);
|
||||
expect(result.stdout).toContain(loginUrl);
|
||||
expect(result.stderr).not.toContain(token);
|
||||
expect(result.stderr).toContain("accessToken=<redacted>");
|
||||
if (extra.length) expect(JSON.parse(result.stdout).loginUrl).toBe(loginUrl);
|
||||
else expect(result.stdout).toContain("diagnostic https://session.example/web/thirdparty.html?accessToken=<redacted>");
|
||||
}
|
||||
});
|
||||
|
||||
it("registers a newly imported enterprise before switching and persists its default", async () => {
|
||||
const result = await runCli([...enterArgs, "--save", "--switch", "--yes", "--json"]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(JSON.parse(result.stdout).enterprise.switched).toBe(true);
|
||||
expect(JSON.parse(result.stdout).sessionResult.loginUrl).toBe(loginUrl);
|
||||
expect(JSON.parse(readFileSync(process.env.HOSE_CONFIG_FILE!, "utf8")).defaultCorpId).toBe("NEW");
|
||||
expect(existsSync(join(corps, "NEW.json"))).toBe(true);
|
||||
});
|
||||
|
||||
it("reports a failed switch without claiming success after saving the enterprise", async () => {
|
||||
const switchMock = spyOn(CorpContext.prototype, "switchCorp").mockReturnValue(false);
|
||||
try {
|
||||
const result = await runCli([...enterArgs, "--save", "--switch", "--yes", "--json"]);
|
||||
expect(result.exitCode).not.toBe(0);
|
||||
expect(JSON.parse(result.stdout).message).toContain("配置已保存,但切换当前工作企业失败");
|
||||
expect(result.stdout).not.toContain('"switched": true');
|
||||
expect(existsSync(join(corps, "NEW.json"))).toBe(true);
|
||||
} finally { switchMock.mockRestore(); }
|
||||
});
|
||||
|
||||
it("keeps error output redacted in text and JSON", async () => {
|
||||
handleRequest = () => { throw new BusinessError(`换票失败 ${loginUrl}`); };
|
||||
for (const extra of [[], ["--json"]]) {
|
||||
const result = await runCli([...enterArgs, ...extra]);
|
||||
expect(result.exitCode).not.toBe(0);
|
||||
expect(result.preserveSensitiveStdout).not.toBe(true);
|
||||
expect(result.stdout + result.stderr).not.toContain(token);
|
||||
expect(result.stdout + result.stderr).toContain("accessToken=<redacted>");
|
||||
}
|
||||
});
|
||||
|
||||
it("saves a valid temporary session without keys or key permission and tolerates multiple keys", async () => {
|
||||
for (const response of [
|
||||
() => Response.json({ items: [] }),
|
||||
() => new Response("Forbidden", { status: 403 }),
|
||||
() => Response.json({ items: [{ appKey: "a", appSecurity: "fixture-a" }, { appKey: "b", appSecurity: "fixture-b" }] }),
|
||||
]) {
|
||||
keysResponse = response;
|
||||
const { corpConfig } = await importSession();
|
||||
expect(corpConfig.credentials.accessToken).toBe(token);
|
||||
expect(existsSync(join(corps, "NEW.json"))).toBe(true);
|
||||
}
|
||||
requests = [];
|
||||
await importSession({ elevate: false });
|
||||
expect(requests.some((url) => url.includes("/innerapi/v1/key"))).toBe(false);
|
||||
});
|
||||
|
||||
it("marks failed or partial identity probes unknown instead of falsely reporting normal risk", async () => {
|
||||
staffAvailable = false;
|
||||
let identity = await inspectAssistIdentity(token, "NEW", baseUrl);
|
||||
expect(identity.isAdmin).toBeNull();
|
||||
expect(identity.isSeniorExecutive).toBeNull();
|
||||
expect(identity.riskLevel).toBe("UNKNOWN");
|
||||
expect(identity.profileComplete).toBe(false);
|
||||
expect(identity.unavailableFields).toContain("staff");
|
||||
staffAvailable = true;
|
||||
rolesAvailable = false;
|
||||
identity = await inspectAssistIdentity(token, "NEW", baseUrl);
|
||||
expect(identity.isAdmin).toBe(false);
|
||||
expect(identity.riskLevel).toBe("UNKNOWN");
|
||||
expect(identity.unavailableFields).toContain("roles");
|
||||
rolesAvailable = true;
|
||||
identity = await inspectAssistIdentity(token, "NEW", baseUrl);
|
||||
expect(identity.riskLevel).toBe("NORMAL");
|
||||
expect(identity.profileComplete).toBe(true);
|
||||
});
|
||||
|
||||
it("preserves a known JWT admin and records incomplete profile metadata on disk", async () => {
|
||||
staffAvailable = false;
|
||||
jwtAdmin = true;
|
||||
const { corpConfig, sessionResult } = await importSession();
|
||||
expect(corpConfig.session?.isAdmin).toBe(true);
|
||||
expect(corpConfig.session?.riskLevel).toBe("HIGH");
|
||||
expect(corpConfig.session?.staffName).toBe("JWT员工");
|
||||
expect(sessionResult.identity?.riskLevel).toBe("HIGH");
|
||||
const persisted = JSON.parse(readFileSync(join(corps, "NEW.json"), "utf8"));
|
||||
expect(persisted.session.identityComplete).toBe(false);
|
||||
expect(persisted.session.identityUnavailableFields).toContain("staff");
|
||||
expect(persisted.session.isAdmin).toBe(true);
|
||||
});
|
||||
|
||||
it("does not reuse a different employee's administrator or risk profile", async () => {
|
||||
saveCorpConfig({ id: "NEW", name: "旧企业", baseUrl, source: "assist", credentials: { corpId: "NEW", staffId: "NEW:other", accessToken: "old-fixture" }, session: { permissions: ["SYS_ADMIN"], isAdmin: true, riskLevel: "HIGH" } }, corps);
|
||||
staffAvailable = false;
|
||||
jwtAdmin = undefined;
|
||||
const { corpConfig } = await importSession();
|
||||
expect(corpConfig.session?.isAdmin).toBeUndefined();
|
||||
expect(corpConfig.session?.permissions).toEqual([]);
|
||||
expect(corpConfig.session?.riskLevel).toBe("UNKNOWN");
|
||||
});
|
||||
|
||||
it("does not treat malformed permissions or roles as an empty complete profile", async () => {
|
||||
handleRequest = (req) => req.url.includes("/staffs/me")
|
||||
? Response.json({ value: { staff: { id: "NEW:staff", admin: false }, permissions: [{}] } })
|
||||
: Response.json({ items: [{}] });
|
||||
const identity = await inspectAssistIdentity(token, "NEW", baseUrl);
|
||||
expect(identity.profileComplete).toBe(false);
|
||||
expect(identity.unavailableFields).toContain("permissions");
|
||||
expect(identity.unavailableFields).toContain("roles");
|
||||
expect(identity.riskLevel).toBe("UNKNOWN");
|
||||
});
|
||||
|
||||
it("retains known permissions for the same staff when a later probe is incomplete", async () => {
|
||||
saveCorpConfig({ id: "NEW", name: "旧企业", baseUrl, source: "assist", credentials: { corpId: "NEW", staffId: "NEW:staff", accessToken: "old-fixture" }, session: { permissions: ["SYS_ADMIN"], isAdmin: true, riskLevel: "HIGH" } }, corps);
|
||||
staffAvailable = false;
|
||||
jwtAdmin = undefined;
|
||||
const { corpConfig } = await importSession();
|
||||
expect(corpConfig.session?.isAdmin).toBe(true);
|
||||
expect(corpConfig.session?.permissions).toContain("SYS_ADMIN");
|
||||
expect(corpConfig.session?.riskLevel).toBe("HIGH");
|
||||
});
|
||||
|
||||
it("merges known partial roles with the same staff's previous roles before risk analysis", async () => {
|
||||
saveCorpConfig({
|
||||
id: "NEW",
|
||||
name: "旧企业",
|
||||
baseUrl,
|
||||
source: "assist",
|
||||
credentials: { corpId: "NEW", staffId: "NEW:staff", accessToken: "old-fixture" },
|
||||
session: { roles: ["普通员工"], riskLevel: "NORMAL" },
|
||||
}, corps);
|
||||
const originalHandler = handleRequest;
|
||||
handleRequest = (req) => req.url.includes("/roles")
|
||||
? Response.json({ items: [{ roleDefName: "财务总监" }, {}] })
|
||||
: originalHandler(req);
|
||||
|
||||
const { corpConfig, sessionResult } = await importSession();
|
||||
|
||||
expect(sessionResult.identity?.roleNames).toEqual(["财务总监", "普通员工"]);
|
||||
expect(sessionResult.identity?.seniorTitles).toContain("财务总监");
|
||||
expect(sessionResult.identity?.riskLevel).toBe("HIGH");
|
||||
expect(corpConfig.session?.roles).toEqual(["财务总监", "普通员工"]);
|
||||
expect(corpConfig.session?.roleTitles).toContain("财务总监");
|
||||
expect(corpConfig.session?.riskLevel).toBe("HIGH");
|
||||
});
|
||||
});
|
||||
@@ -205,6 +205,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"diff-job": "对比两次执行的节点分支与报错发散点",
|
||||
"test": "端到端一键调试单据(替代前端手工调测)",
|
||||
"node": "声明式节点编排与增删改 (list|get|add|edit|rm)",
|
||||
"nodes": "查询企业已开通工作流节点字典或开通灰度节点 (list|grant)",
|
||||
"tail": "实时监听任务派发与节点执行日志流 (watch|follow)",
|
||||
"create": "从零新建工作流草稿",
|
||||
"copy": "复制克隆工作流",
|
||||
@@ -271,7 +272,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"dictionary": "enum",
|
||||
"dict": "enum"
|
||||
},
|
||||
flags: { ...flagList("allow-prod allow-production auto-publish autoPublish detail empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite has-error hasError in-place inPlace includeDetail json none once publish snapshot v value-json valueJson verbose", "boolean"), ...flagList("a after app-id appId b bill body c code code-file container count d data desc description end-time endTime entity execution-logs field file flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId l label log logs max-jobs maxJobs n name node node-id nodeId output output-file outputFile p page page-size pageSize parent parent-id parentId path payload pipeline pipeline-id pipelineId platform-id platformId record s sample sample-id sampleId set size snapshot1 snapshot2 snapshotA snapshotB source start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type value workflowId", "value") }
|
||||
flags: { ...flagList("all allow-prod allow-production auto-publish autoPublish compare detail diff empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite full has-error hasError in-place inPlace includeDetail json none once publish snapshot v value-json valueJson verbose with-tasks withTasks timeline progress steps", "boolean"), ...flagList("a admin-key adminKey after app app-id appId b bill body c code code-file container count d data desc description end-time endTime entity execution-logs field file filter flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId json-file keyword l label limit log logs mapping mapping-file max-jobs maxJobs n name node node-id nodeId nodes output output-file outputFile p page page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform platform-id platformId pwd q query record s sample sample-id sampleId set size snapshot1 snapshot2 snapshotA snapshotB source start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type types value workflowId", "value") }
|
||||
},
|
||||
"bill": {
|
||||
"summary": "单据检索、表单规格诊断与审批动作",
|
||||
@@ -338,7 +339,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"url": "link",
|
||||
"specification": "spec"
|
||||
},
|
||||
flags: { ...flagList("audit confirm distinct force-write keep-it-secret mine my private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target to", "value") }
|
||||
flags: { ...flagList("audit basic confirm distinct force-write keep-it-secret mine my no-invoice noInvoice private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target to", "value") }
|
||||
},
|
||||
"flow": {
|
||||
"summary": "审批流全域透视与穿透诊断",
|
||||
@@ -367,7 +368,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"show": "get",
|
||||
"find": "get"
|
||||
},
|
||||
flags: { ...flagList("audit confirm distinct force-write keep-it-secret mine my private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target to", "value") }
|
||||
flags: { ...flagList("audit basic confirm distinct force-write keep-it-secret mine my no-invoice noInvoice private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target to", "value") }
|
||||
},
|
||||
"contact": {
|
||||
"summary": "企业通讯录与人员检索",
|
||||
@@ -444,7 +445,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"costtype"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("a all fields flat flatten include-disabled r recursive spec specs table", "boolean"), ...flagList("code color desc description en-name enName icon id keyword name parent parent-id parentId q query target title to", "value") }
|
||||
flags: { ...flagList("a all fields flat flatten ids ids-only include-disabled r recursive spec specs table", "boolean"), ...flagList("code color desc description en-name enName icon id keyword name parent parent-id parentId q query subtree subtree-id target title to", "value") }
|
||||
},
|
||||
"role": {
|
||||
"summary": "企业角色定义与成员",
|
||||
@@ -540,6 +541,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"records": "查询记录(支持 --all / --ndjson 流式 / --stats 画像)",
|
||||
"record": "查看或安全修改单条/批量记录 (get/create/edit/batch-edit)",
|
||||
"audit": "业务对象健康度巡检(必填缺失/禁用引用/跨表同步差异)",
|
||||
"gen-props": "生成业务对象字段常量与代码模板 (支持 MVEL / JS)",
|
||||
"permissions": "查看权限",
|
||||
"imports": "查看导入任务",
|
||||
"get": "查看应用详情"
|
||||
@@ -579,11 +581,13 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"update": "record",
|
||||
"batch-update": "record",
|
||||
"record-recompute": "record",
|
||||
"gen-mvel-props": "gen-props",
|
||||
"props": "gen-props",
|
||||
"permission": "permissions",
|
||||
"auth": "permissions",
|
||||
"import-jobs": "imports"
|
||||
},
|
||||
flags: { ...flagList("a active active-only activeOnly all flat ndjson normalize normalized profile raw state stats stream w workbench", "boolean"), ...flagList("aggregate baseline c check-continuous check-fields checkContinuous checkFields concurrency continuous count d data expect expect-value expectValue f field fields file filter filter-by filterBy form group-by groupBy id ids keyword limit name offset page-size pageSize q query select seq sequence set start sum where", "value") }
|
||||
flags: { ...flagList("a active active-only activeOnly all flat ndjson normalize normalized profile raw state stats stream w workbench", "boolean"), ...flagList("aggregate baseline c check-continuous check-fields checkContinuous checkFields concurrency continuous count d data expect expect-value expectValue f field fields file filter filter-by filterBy form group-by groupBy id ids keyword lang language limit name offset page-size pageSize q query search-field searchField search-fields searchFields select seq sequence set start sum where", "value") }
|
||||
},
|
||||
"app": {
|
||||
"summary": "桌面端工作台应用管理",
|
||||
@@ -769,6 +773,57 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"aliases": [],
|
||||
"commandAliases": {},
|
||||
flags: { }
|
||||
},
|
||||
"assist-platform": {
|
||||
"summary": "合思协助/运营平台 (Assist Platform) 自动化运维",
|
||||
"usage": "hose-use assist-platform <子命令> [参数] [选项]",
|
||||
"commands": {
|
||||
"login": "查看或保存协助平台凭证会话",
|
||||
"search": "在协助中心 34 万家企业库中分页检索企业",
|
||||
"detail": "查看企业详细业务配置与开通商品能力",
|
||||
"tickets": "查询指定企业的协助工单与授权码",
|
||||
"staff": "查询企业内部员工工号与角色",
|
||||
"apply": "向目标企业发起新的协助授权工单申请",
|
||||
"approve": "审批通过协助授权工单申请(端内管理员授权)",
|
||||
"enter": "一键换取免密直通链接并落盘为本地工作企业",
|
||||
"transfer": "转交协助工单权限给其他同事",
|
||||
"help": "查看帮助信息"
|
||||
},
|
||||
"aliases": [
|
||||
"assist-center",
|
||||
"ap"
|
||||
],
|
||||
"commandAliases": {
|
||||
"auth": "login",
|
||||
"status": "login",
|
||||
"find": "search",
|
||||
"list": "search",
|
||||
"ls": "search",
|
||||
"info": "detail",
|
||||
"config": "detail",
|
||||
"ticket": "tickets",
|
||||
"order": "tickets",
|
||||
"orders": "tickets",
|
||||
"user": "staff",
|
||||
"users": "staff",
|
||||
"apply": "apply",
|
||||
"create": "apply",
|
||||
"request": "apply",
|
||||
"new": "apply",
|
||||
"approve": "approve",
|
||||
"authorize": "approve",
|
||||
"pass": "approve",
|
||||
"import": "enter",
|
||||
"token": "enter",
|
||||
"get-token": "enter",
|
||||
"transfer": "transfer",
|
||||
"transmit": "transfer",
|
||||
"forward": "transfer"
|
||||
},
|
||||
flags: {
|
||||
...flagList("token t user name u hose-token jwt ticket ticket-id auth-code staff alias corp-name count limit n start offset state status corpid id keyword query q message msg reason matter hours hour duration days day to recipient target remarks comment corp", "value"),
|
||||
...flagList("all a logout admin save import persist switch current overwrite candidates list-candidates", "boolean")
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { afterEach, expect, mock, spyOn, test } from "bun:test";
|
||||
import { getDatabase, closeDatabase } from "../../../core/db/index.js";
|
||||
import { ApprovalRepository } from "../../../domains/approval/repository.js";
|
||||
import * as bills from "../../../domains/bill/tools.js";
|
||||
import { handleAiProDecide } from "./session.js";
|
||||
|
||||
afterEach(() => { closeDatabase(); });
|
||||
for (const action of ["approve", "reject"] as const) {
|
||||
test(`blocks cross-corp ${action} before creating a client or changing the run`, async () => {
|
||||
const repo = new ApprovalRepository(getDatabase(":memory:"));
|
||||
const run = repo.createApprovalRun({ documentSn: "SAME-SN", corpId: "corp-A" });
|
||||
repo.injectFindings(run.id, [{ clauseText: "invoice", strictness: "硬性", checkStatus: action === "approve" ? "PASS" : "FAIL" }]);
|
||||
const getClient = mock(async () => ({ client: {} as any, corpId: "corp-B" }));
|
||||
await expect(handleAiProDecide({ repo, corpId: "corp-B", command: action, positional: [action, run.shortId!], parsed: { options: { apply: true, yes: true, opinion: "checked" } }, getClient } as any)).rejects.toThrow("不一致");
|
||||
expect(getClient).not.toHaveBeenCalled();
|
||||
expect(repo.getRunById(run.id)?.decision).toBe("PENDING");
|
||||
});
|
||||
}
|
||||
test("uses the checked corp client for same-corp approval", async () => {
|
||||
const repo = new ApprovalRepository(getDatabase(":memory:"));
|
||||
const run = repo.createApprovalRun({ documentSn: "SAME-SN", corpId: "corp-A" });
|
||||
repo.injectFindings(run.id, [{ clauseText: "invoice", strictness: "硬性", checkStatus: "PASS" }]);
|
||||
const approve = spyOn(bills, "approveBill").mockResolvedValue({} as any);
|
||||
const client = {} as any;
|
||||
try {
|
||||
const result = await handleAiProDecide({ repo, corpId: "corp-A", command: "approve", positional: ["approve", run.shortId!], parsed: { options: { apply: true, yes: true, opinion: "checked" } }, getClient: async () => ({ client, corpId: "corp-A" }), rawArgs: [], operator: "staff" } as any);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(approve).toHaveBeenCalledWith(client, "corp-A", "SAME-SN", { comment: "checked" });
|
||||
} finally { approve.mockRestore(); }
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
import { PermissionError } from "../../../core/errors.js";
|
||||
import {
|
||||
type ApprovalRunRecord,
|
||||
type CreateFindingInput,
|
||||
@@ -440,6 +441,9 @@ export async function handleAiProDecide(ctx: AiProExecutionContext): Promise<AiP
|
||||
let executionStatus = "模拟完成(未带 --apply,未真实修改线上单据)";
|
||||
|
||||
if (apply) {
|
||||
if (!runRecord.corpId || ctx.corpId !== runRecord.corpId) {
|
||||
throw new PermissionError(`审批会话所属企业 [${runRecord.corpId || "未知"}] 与当前企业 [${ctx.corpId || "未选择"}] 不一致,请显式选择会话所属企业。`);
|
||||
}
|
||||
const confirmed = booleanOption(parsed.options, ["yes", "y", "confirm"]);
|
||||
if (!confirmed) {
|
||||
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
||||
@@ -453,6 +457,7 @@ export async function handleAiProDecide(ctx: AiProExecutionContext): Promise<AiP
|
||||
}
|
||||
|
||||
const context = await getClient();
|
||||
if (context.corpId !== runRecord.corpId) throw new PermissionError("审批客户端企业与会话所属企业不一致");
|
||||
if (action === "APPROVE") {
|
||||
await approveBill(context.client, context.corpId, runRecord.documentSn, {
|
||||
comment: opinion,
|
||||
|
||||
@@ -88,9 +88,9 @@ export async function handleAiProLogs(ctx: AiProExecutionContext): Promise<AiPro
|
||||
|
||||
let runRecord: ApprovalRunRecord | null = null;
|
||||
if (runHandle) {
|
||||
runRecord = repo.getRunByHandle(runHandle);
|
||||
runRecord = repo.getRunByHandle(runHandle, undefined, { allowExpired: true });
|
||||
} else if (targetSn) {
|
||||
const maybeRun = repo.getRunByHandle(targetSn);
|
||||
const maybeRun = repo.getRunByHandle(targetSn, undefined, { allowExpired: true });
|
||||
if (maybeRun?.shortId && maybeRun.shortId.toUpperCase() === targetSn.toUpperCase()) {
|
||||
runRecord = maybeRun;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isDryRun, mutationPreview } from "../mutation.js";
|
||||
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import { stringOption, booleanOption, numberOption } from "../parser.js";
|
||||
@@ -19,9 +20,7 @@ export async function handleApprovalCommand(
|
||||
);
|
||||
}
|
||||
|
||||
const client = await createSessionClient(corp);
|
||||
const corpId = corp.corpId || corp.id;
|
||||
const service = new ApprovalService();
|
||||
|
||||
// 解析命令层级:
|
||||
// 形式 A: hose-use approval audit points S26000001
|
||||
@@ -40,6 +39,12 @@ export async function handleApprovalCommand(
|
||||
|
||||
const targetSn = args[0] || stringOption(parsed.options, ["code", "sn", "target", "id"]);
|
||||
|
||||
if (targetSn && isDryRun(parsed, runtime) && ["audit", "points", "inject", "review", "eval", "evaluate", "decide", "approve", "reject"].includes(subAction || "audit")) {
|
||||
return mutationPreview(parsed, runtime, "预览审批操作", targetSn, { action: subAction || "audit", corpId, apply: booleanOption(parsed.options, ["apply", "execute", "run", "do"]) });
|
||||
}
|
||||
const client = await createSessionClient(corp);
|
||||
const service = new ApprovalService();
|
||||
|
||||
switch (subAction) {
|
||||
// ── 1. 规则注入与出明细级审核要点清单 ─────────────────────────────────────
|
||||
case "points":
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
import { describe, expect, it, beforeEach } from "bun:test";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { handleAssistPlatformCommand } from "./assist-platform/index.js";
|
||||
import {
|
||||
saveAssistPlatformSession,
|
||||
clearAssistPlatformSession,
|
||||
} from "../../core/auth/assist-platform-store.js";
|
||||
import type { CliParsedArgs, CliRuntime } from "../types.js";
|
||||
|
||||
function createMockRuntime(enterprisesDir: string): CliRuntime {
|
||||
return {
|
||||
jsonMode: false,
|
||||
selectedCorp: null,
|
||||
corpContext: {
|
||||
enterprisesDir,
|
||||
corps: new Map(),
|
||||
stateful: true,
|
||||
current: undefined,
|
||||
defaultCorpId: undefined,
|
||||
getCorp: () => undefined,
|
||||
switchCorp: () => true,
|
||||
listCorps: () => [],
|
||||
getAllCorps: () => [],
|
||||
} as any,
|
||||
};
|
||||
}
|
||||
|
||||
describe("CLI Commands - assist-platform (合思协助平台)", () => {
|
||||
let tempDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
tempDir = mkdtempSync(join(tmpdir(), "hose-assist-test-"));
|
||||
process.env.HOSE_STATE_DIR = tempDir;
|
||||
clearAssistPlatformSession();
|
||||
});
|
||||
|
||||
it("assist-platform help 输出完整使用指南与子命令", async () => {
|
||||
const runtime = createMockRuntime(tempDir);
|
||||
const parsed: CliParsedArgs = {
|
||||
action: "help",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["assist-platform", "help"],
|
||||
};
|
||||
|
||||
const res = await handleAssistPlatformCommand(parsed, runtime);
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("合思协助平台");
|
||||
expect(res.stdout).toContain("login");
|
||||
expect(res.stdout).toContain("search");
|
||||
expect(res.stdout).toContain("tickets");
|
||||
expect(res.stdout).toContain("enter");
|
||||
expect(res.stdout).toContain("assist-center");
|
||||
});
|
||||
|
||||
it("assist-platform login 无凭证时给出指引", async () => {
|
||||
const runtime = createMockRuntime(tempDir);
|
||||
const parsed: CliParsedArgs = {
|
||||
action: "login",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["assist-platform", "login"],
|
||||
};
|
||||
|
||||
const res = await handleAssistPlatformCommand(parsed, runtime);
|
||||
expect(res.exitCode).toBe(1);
|
||||
expect(res.stderr).toContain("未检测到协助平台登录凭证");
|
||||
});
|
||||
|
||||
it("assist-platform login --logout 能够注销凭证", async () => {
|
||||
saveAssistPlatformSession({
|
||||
token: "mock-token",
|
||||
userName: "测试人员",
|
||||
baseUrl: "https://unity.ekuaibao.com/api",
|
||||
updatedAt: Date.now(),
|
||||
});
|
||||
|
||||
const runtime = createMockRuntime(tempDir);
|
||||
const parsed: CliParsedArgs = {
|
||||
action: "login",
|
||||
args: [],
|
||||
options: { logout: true },
|
||||
raw: ["assist-platform", "login", "--logout"],
|
||||
};
|
||||
|
||||
const res = await handleAssistPlatformCommand(parsed, runtime);
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("已成功注销");
|
||||
});
|
||||
|
||||
it("未登录时运行 tickets 提示需要先登录", async () => {
|
||||
const runtime = createMockRuntime(tempDir);
|
||||
const parsed: CliParsedArgs = {
|
||||
action: "tickets",
|
||||
args: ["Cxa3oOtQi2eS$g"],
|
||||
options: {},
|
||||
raw: ["assist-platform", "tickets", "Cxa3oOtQi2eS$g"],
|
||||
};
|
||||
|
||||
try {
|
||||
await handleAssistPlatformCommand(parsed, runtime);
|
||||
expect(true).toBe(false);
|
||||
} catch (err: any) {
|
||||
expect(err.message).toContain("未检测到协助平台登录凭证");
|
||||
}
|
||||
});
|
||||
|
||||
it("assist-platform enter --save --dry-run 能够输出变更预览", async () => {
|
||||
saveAssistPlatformSession({
|
||||
token: "mock-token",
|
||||
userName: "测试人员",
|
||||
baseUrl: "https://unity.ekuaibao.com/api",
|
||||
updatedAt: Date.now(),
|
||||
});
|
||||
|
||||
const runtime = createMockRuntime(tempDir);
|
||||
const parsed: CliParsedArgs = {
|
||||
action: "enter",
|
||||
args: ["Cxa3oOtQi2eS$g"],
|
||||
options: { save: true, dryRun: true },
|
||||
raw: ["assist-platform", "enter", "Cxa3oOtQi2eS$g", "--save", "--dry-run"],
|
||||
};
|
||||
|
||||
const res = await handleAssistPlatformCommand(parsed, runtime);
|
||||
expect(res.stdout).toContain("[DRY-RUN]");
|
||||
expect(res.stdout).toContain("Cxa3oOtQi2eS$g");
|
||||
});
|
||||
|
||||
it("assist-platform apply --dry-run 能够输出申请工单变更预览", async () => {
|
||||
saveAssistPlatformSession({
|
||||
token: "mock-token",
|
||||
userName: "测试人员",
|
||||
baseUrl: "https://unity.ekuaibao.com/api",
|
||||
updatedAt: Date.now(),
|
||||
});
|
||||
|
||||
const runtime = createMockRuntime(tempDir);
|
||||
const parsed: CliParsedArgs = {
|
||||
action: "apply",
|
||||
args: ["ID01KrLMQJWdMH"],
|
||||
options: { dryRun: true, hours: 12, message: "测试联调" },
|
||||
raw: ["assist-platform", "apply", "ID01KrLMQJWdMH", "--dry-run", "--hours", "12"],
|
||||
};
|
||||
|
||||
const res = await handleAssistPlatformCommand(parsed, runtime);
|
||||
expect(res.stdout).toContain("[DRY-RUN]");
|
||||
expect(res.stdout).toContain("ID01KrLMQJWdMH");
|
||||
expect(res.stdout).toContain("12 小时");
|
||||
});
|
||||
|
||||
it("assist-platform approve --dry-run 能够输出工单审批变更预览", async () => {
|
||||
const runtime = createMockRuntime(tempDir);
|
||||
runtime.selectedCorp = {
|
||||
id: "ID01ofWoOC1wiX",
|
||||
name: "沈玥妍测试企业",
|
||||
corpId: "ID01ofWoOC1wiX",
|
||||
credentials: { accessToken: "mock-token" },
|
||||
} as any;
|
||||
|
||||
const parsed: CliParsedArgs = {
|
||||
action: "approve",
|
||||
args: ["ID01Xeno3GpoNV"],
|
||||
options: { dryRun: true },
|
||||
raw: ["assist-platform", "approve", "ID01Xeno3GpoNV", "--dry-run"],
|
||||
};
|
||||
|
||||
const res = await handleAssistPlatformCommand(parsed, runtime);
|
||||
expect(res.stdout).toContain("[DRY-RUN]");
|
||||
expect(res.stdout).toContain("ID01Xeno3GpoNV");
|
||||
expect(res.stdout).toContain("同意授权");
|
||||
});
|
||||
|
||||
it("assist-platform apply 传入超过 24 小时或多天时返回明确拒绝提示", async () => {
|
||||
saveAssistPlatformSession({
|
||||
token: "mock-token",
|
||||
userName: "测试人员",
|
||||
baseUrl: "https://unity.ekuaibao.com/api",
|
||||
updatedAt: Date.now(),
|
||||
});
|
||||
|
||||
const runtime = createMockRuntime(tempDir);
|
||||
const parsed: CliParsedArgs = {
|
||||
action: "apply",
|
||||
args: ["ID01KrLMQJWdMH"],
|
||||
options: { days: 2 },
|
||||
raw: ["assist-platform", "apply", "ID01KrLMQJWdMH", "--days", "2"],
|
||||
};
|
||||
|
||||
const res = await handleAssistPlatformCommand(parsed, runtime);
|
||||
expect(res.exitCode).toBe(1);
|
||||
expect(res.stderr).toContain("申请协助时长不能超过 24 小时 (1 天)");
|
||||
expect(res.stderr).toContain("2 天 (48 小时)");
|
||||
expect(res.stderr).toContain("POST /api/assistPlatform/create");
|
||||
expect(res.stderr).toContain("单次协助工单最长有效期限为 24 小时");
|
||||
});
|
||||
|
||||
it("assist-platform apply --days 1 --dry-run 成功换算为 24 小时并预览", async () => {
|
||||
saveAssistPlatformSession({
|
||||
token: "mock-token",
|
||||
userName: "测试人员",
|
||||
baseUrl: "https://unity.ekuaibao.com/api",
|
||||
updatedAt: Date.now(),
|
||||
});
|
||||
|
||||
const runtime = createMockRuntime(tempDir);
|
||||
const parsed: CliParsedArgs = {
|
||||
action: "apply",
|
||||
args: ["ID01KrLMQJWdMH"],
|
||||
options: { days: 1, dryRun: true },
|
||||
raw: ["assist-platform", "apply", "ID01KrLMQJWdMH", "--days", "1", "--dry-run"],
|
||||
};
|
||||
|
||||
const res = await handleAssistPlatformCommand(parsed, runtime);
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("[DRY-RUN]");
|
||||
expect(res.stdout).toContain("24 小时");
|
||||
});
|
||||
|
||||
it("assist-platform transfer 缺少 --to 参数时报错提示", async () => {
|
||||
saveAssistPlatformSession({
|
||||
token: "mock-token",
|
||||
userName: "测试人员",
|
||||
baseUrl: "https://unity.ekuaibao.com/api",
|
||||
updatedAt: Date.now(),
|
||||
});
|
||||
|
||||
const runtime = createMockRuntime(tempDir);
|
||||
const parsed: CliParsedArgs = {
|
||||
action: "transfer",
|
||||
args: ["ID01ofWoOC1wiX"],
|
||||
options: {},
|
||||
raw: ["assist-platform", "transfer", "ID01ofWoOC1wiX"],
|
||||
};
|
||||
|
||||
const res = await handleAssistPlatformCommand(parsed, runtime);
|
||||
expect(res.exitCode).toBe(1);
|
||||
expect(res.stderr).toContain("必须通过 --to 指定接收人员姓名、工号或账号");
|
||||
});
|
||||
|
||||
it("assist-platform transfer --dry-run 能够输出工单转交变更预览", async () => {
|
||||
saveAssistPlatformSession({
|
||||
token: "mock-token",
|
||||
userName: "测试人员",
|
||||
baseUrl: "https://unity.ekuaibao.com/api",
|
||||
updatedAt: Date.now(),
|
||||
});
|
||||
|
||||
const runtime = createMockRuntime(tempDir);
|
||||
const parsed: CliParsedArgs = {
|
||||
action: "transfer",
|
||||
args: ["ID01ofWoOC1wiX", "ID01Xenwiu9w0D"],
|
||||
options: { to: "陈龙", dryRun: true },
|
||||
raw: ["assist-platform", "transfer", "ID01ofWoOC1wiX", "ID01Xenwiu9w0D", "--to", "陈龙", "--dry-run"],
|
||||
};
|
||||
|
||||
const originalFetch = globalThis.fetch;
|
||||
globalThis.fetch = (async () => Response.json({
|
||||
items: [{
|
||||
id: "role-chenlong",
|
||||
userId: { id: "chenlong3016", name: "陈龙", code: "3016" },
|
||||
}],
|
||||
})) as unknown as typeof globalThis.fetch;
|
||||
try {
|
||||
const res = await handleAssistPlatformCommand(parsed, runtime);
|
||||
expect(res.stdout).toContain("[DRY-RUN]");
|
||||
expect(res.stdout).toContain("ID01Xenwiu9w0D");
|
||||
expect(res.stdout).toContain("陈龙");
|
||||
expect(res.stdout).toContain("chenlong3016");
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,110 @@
|
||||
import { applyAssistTicket } from "../../../domains/assist-platform/services.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
||||
import { numberOption, stringOption } from "../../parser.js";
|
||||
import { printJson, printKeyValue } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { resolveAssistClient } from "./common.js";
|
||||
|
||||
export async function handleApply(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const client = resolveAssistClient(parsed, runtime);
|
||||
const corpId =
|
||||
parsed.args[0] ||
|
||||
stringOption(parsed.options, ["corp", "corpid", "id"]) ||
|
||||
runtime.selectedCorp?.id;
|
||||
|
||||
if (!corpId) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use assist-platform apply <企业ID> [--message <事由>] [--hours <小时数(1-24)>] [--dry-run/--yes]\n示例: hose-use assist-platform apply ID01KrLMQJWdMH --message \"测试环境接口联调\" --hours 24 --yes\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const days = numberOption(parsed.options, ["days", "day"]);
|
||||
let hours = numberOption(parsed.options, ["hours", "hour", "duration"]);
|
||||
if (days !== undefined) {
|
||||
hours = days * 24;
|
||||
}
|
||||
if (hours === undefined) {
|
||||
hours = 24;
|
||||
}
|
||||
|
||||
if (hours < 1 || hours > 24) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr:
|
||||
`[ERROR] 申请协助时长不能超过 24 小时 (1 天),当前传入: ${days !== undefined ? `${days} 天 (${hours} 小时)` : `${hours} 小时`}。\n` +
|
||||
`提示: 合思协助平台服务端(POST /api/assistPlatform/create)实施了硬性安全限制:单次协助工单最长有效期限为 24 小时 (1天),超过 24 小时服务端将直接拒绝受理。\n` +
|
||||
`如需持续协助支持,可在工单到期后再次快速发起或在端内续签。\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const message =
|
||||
stringOption(parsed.options, ["message", "msg", "reason", "matter"]) ||
|
||||
"测试环境接口联调与问题排查";
|
||||
|
||||
const targetCorp =
|
||||
runtime.corpContext?.getAllCorps?.()?.find((c) => c.id === corpId || c.corpId === corpId) ||
|
||||
(runtime.selectedCorp?.id === corpId || runtime.selectedCorp?.corpId === corpId
|
||||
? runtime.selectedCorp
|
||||
: undefined);
|
||||
const corpName = targetCorp?.name || corpId;
|
||||
|
||||
const nextConfirmCmd = `hose-use assist-platform apply ${corpId} --message "${message}" --hours ${hours} --yes`;
|
||||
|
||||
// 写操作两阶段确认守卫
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(
|
||||
parsed,
|
||||
runtime,
|
||||
"发起合思协助工单申请",
|
||||
`${corpName} (${corpId})`,
|
||||
{
|
||||
申请事项: message,
|
||||
申请时长: `${hours} 小时 (${hours * 3600 * 1000} ms)`,
|
||||
初始状态: "待提供 (需企业管理员在端内开启授权)",
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
`向企业 [${corpName}] 发起协助授权申请 (时长: ${hours}h, 事由: ${message})`,
|
||||
nextConfirmCmd
|
||||
);
|
||||
|
||||
const res = await applyAssistTicket(client, {
|
||||
corporationId: corpId,
|
||||
applyMessage: message,
|
||||
assistTime: hours * 3600 * 1000,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(res, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const pairs: Record<string, string> = {
|
||||
企业名称: corpName,
|
||||
企业ID: res.corporationId,
|
||||
新建工单ID: res.id,
|
||||
工单状态: "🟡 待提供 (等待客户管理员在企业端授权)",
|
||||
申请时长: `${hours} 小时`,
|
||||
申请事项: res.applyMessage,
|
||||
申请人: res.userName || "运营实施人员",
|
||||
};
|
||||
|
||||
return {
|
||||
stdout: `====== 合思协助工单申请提交成功 ======\n${printKeyValue(pairs)}\n\n后续步骤:\n 1. 提示企业管理员登录合思 Web/桌面端,在【远程协助/授权中心】确认开启授权;\n 2. 授权通过后工单变为【🟢 生效中】,即可运行: hose-use assist-platform enter ${corpId} --staff <员工姓名> --save --yes\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
import { createSessionClient } from "../../../core/http/session-client.js";
|
||||
import {
|
||||
approveAssistTicket,
|
||||
listAssistTickets,
|
||||
} from "../../../domains/assist-platform/services.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson, printKeyValue } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { resolveAssistClient } from "./common.js";
|
||||
|
||||
export async function handleApprove(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const corpOption = stringOption(parsed.options, ["corp", "corpid", "id"]);
|
||||
const explicitCorpId = corpOption || parsed.args[0] || runtime.selectedCorp?.id;
|
||||
|
||||
if (!explicitCorpId) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr:
|
||||
"用法: hose-use assist-platform approve [工单ID] [--corp <企业ID>] [--dry-run/--yes]\n" +
|
||||
"示例: hose-use assist-platform approve ID01Xeno3GpoNV --corp ID01ofWoOC1wiX --yes\n" +
|
||||
" hose-use assist-platform approve --corp ID01ofWoOC1wiX --yes (自动审批最新待授权工单)\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
// 1. 识别 corpId 与 ticketId
|
||||
const allCorps = runtime.corpContext?.getAllCorps?.() || [];
|
||||
const findCorp = (id: string) =>
|
||||
allCorps.find((c) => c.id === id || c.corpId === id) ||
|
||||
(runtime.selectedCorp?.id === id || runtime.selectedCorp?.corpId === id
|
||||
? runtime.selectedCorp
|
||||
: undefined);
|
||||
let targetCorp = findCorp(explicitCorpId);
|
||||
const ticketOption = stringOption(parsed.options, ["ticket", "ticket-id"]);
|
||||
let positionalTicketId: string | undefined;
|
||||
|
||||
// 如果第 0 个参数不是企业,可能是工单编号
|
||||
if (corpOption) {
|
||||
// 显式企业选项下,唯一位置参数始终是工单,不能被本地企业命中结果覆盖。
|
||||
positionalTicketId = parsed.args[0];
|
||||
} else if (!targetCorp && parsed.args[0]) {
|
||||
positionalTicketId = parsed.args[0];
|
||||
targetCorp = runtime.selectedCorp ?? undefined;
|
||||
} else if (targetCorp && parsed.args[1]) {
|
||||
positionalTicketId = parsed.args[1];
|
||||
}
|
||||
|
||||
const maxArgs = !corpOption && parsed.args[0] && findCorp(parsed.args[0]) ? 2 : 1;
|
||||
if (parsed.args.length > maxArgs ||
|
||||
(ticketOption && positionalTicketId && ticketOption !== positionalTicketId)) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "[ERROR] 企业或工单参数存在歧义或冲突。请使用 approve <工单ID> --corp <企业ID>,且 --ticket 必须与位置工单一致。\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
let ticketId = ticketOption || positionalTicketId;
|
||||
|
||||
if (!targetCorp) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[ERROR] 未在本地企业配置中找到企业 [${explicitCorpId}]。审批工单需要企业管理员权限凭证,请先确保目标企业已配置在本地并具备管理员会话。\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const corpName = targetCorp.name || targetCorp.id;
|
||||
const actualCorpId = targetCorp.corpId || targetCorp.id;
|
||||
|
||||
// 2. 若未显式传入工单编号,自动查询该企业当前处于【待提供】(status: 0) 的工单
|
||||
if (!ticketId) {
|
||||
try {
|
||||
const assistClient = resolveAssistClient(parsed, runtime);
|
||||
const tickets = await listAssistTickets(assistClient, actualCorpId);
|
||||
const pendingTicket = tickets.find(
|
||||
(t) => t.state === "0" || t.state.includes("待提供")
|
||||
);
|
||||
if (pendingTicket?.ticketId) {
|
||||
ticketId = pendingTicket.ticketId;
|
||||
}
|
||||
} catch {
|
||||
// 容错降级
|
||||
}
|
||||
}
|
||||
|
||||
if (!ticketId) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[WARN] 企业 [${corpName}] (${actualCorpId}) 协助中心未查询到待授权的工单。可指定 --ticket <工单ID>,或使用 hose-use assist-platform tickets ${actualCorpId} 查看工单列表。\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const nextConfirmCmd = `hose-use assist-platform approve ${ticketId} --corp ${actualCorpId} --yes`;
|
||||
|
||||
// 3. 写操作两阶段确认守卫
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(
|
||||
parsed,
|
||||
runtime,
|
||||
"审批通过合思协助授权申请",
|
||||
`${corpName} (${actualCorpId})`,
|
||||
{
|
||||
工单编号: ticketId,
|
||||
审批动作: "同意授权 (通过并生效)",
|
||||
授权范围: "允许运维与技术实施人员在有效期限内免密进入系统协助",
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
`审批通过企业 [${corpName}] 的协助授权工单 [${ticketId}]`,
|
||||
nextConfirmCmd
|
||||
);
|
||||
|
||||
// 4. 调用企业会话客户端执行审批
|
||||
const sessionClient = await createSessionClient(targetCorp);
|
||||
const res = await approveAssistTicket(sessionClient, {
|
||||
ticketId,
|
||||
corporationId: actualCorpId,
|
||||
status: 1,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(res, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const startStr = res.startTime ? new Date(res.startTime).toLocaleString("zh-CN", { hour12: false }) : "-";
|
||||
const endStr = res.endTime ? new Date(res.endTime).toLocaleString("zh-CN", { hour12: false }) : "-";
|
||||
|
||||
const pairs: Record<string, string> = {
|
||||
企业名称: corpName,
|
||||
企业ID: res.corporationId,
|
||||
授权工单: res.id,
|
||||
工单状态: "🟢 生效中 (授权已开启)",
|
||||
有效期限: `${startStr} 至 ${endStr}`,
|
||||
申请事项: res.applyMessage || "-",
|
||||
申请人: res.userName || "运营实施人员",
|
||||
};
|
||||
|
||||
return {
|
||||
stdout:
|
||||
`====== 合思协助工单授权通过成功 ======\n${printKeyValue(pairs)}\n\n后续步骤:\n` +
|
||||
` 1. 工单已处于生效状态,可直接换取免密链接调试: hose-use assist-platform enter ${actualCorpId} --save --yes\n` +
|
||||
` 2. 查看实时工单列表: hose-use assist-platform tickets ${actualCorpId}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { loadAssistPlatformSession } from "../../../core/auth/assist-platform-store.js";
|
||||
import { createAssistPlatformClient } from "../../../core/http/assist-platform-client.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import type { CliParsedArgs, CliRuntime } from "../../types.js";
|
||||
import { AuthenticationError } from "../../../core/errors.js";
|
||||
import type { KyInstance } from "ky";
|
||||
|
||||
export function resolveAssistClient(
|
||||
parsed: CliParsedArgs,
|
||||
_runtime: CliRuntime
|
||||
): KyInstance {
|
||||
const explicitToken = stringOption(parsed.options, ["token", "t"]);
|
||||
const session = loadAssistPlatformSession();
|
||||
const token = explicitToken || session?.token;
|
||||
|
||||
if (!token || !token.trim()) {
|
||||
throw new AuthenticationError(
|
||||
"未检测到协助平台登录凭证。请先运行: hose-use assist-platform login --token <TOKEN>"
|
||||
);
|
||||
}
|
||||
|
||||
return createAssistPlatformClient({
|
||||
token: token.trim(),
|
||||
hoseAccessToken: session?.hoseAccessToken,
|
||||
baseUrl: session?.baseUrl,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { getCorporationDetail } from "../../../domains/assist-platform/services.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson, printKeyValue, printTable } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { resolveAssistClient } from "./common.js";
|
||||
|
||||
export async function handleDetail(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const client = resolveAssistClient(parsed, runtime);
|
||||
const corpId =
|
||||
parsed.args[0] ||
|
||||
stringOption(parsed.options, ["corp", "corpid", "id"]) ||
|
||||
runtime.selectedCorp?.id;
|
||||
|
||||
if (!corpId) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use assist-platform detail <企业ID>\n示例: hose-use assist-platform detail Cxa3oOtQi2eS$g\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const detail = await getCorporationDetail(client, corpId);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(detail, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const corp = detail.corporation || {};
|
||||
const basic = detail.basic || {};
|
||||
|
||||
const summaryPairs: Record<string, string> = {
|
||||
企业名称: String(corp.name || "-"),
|
||||
企业ID: String(corp.id || corpId),
|
||||
基础状态: String(basic.status || corp.state || "-"),
|
||||
付费模式: String(corp.payType || "-"),
|
||||
部署集群: String(corp.platformName || "app"),
|
||||
灰度版本: String(corp.grayver || "-"),
|
||||
数据库版本: String(corp.dbVersion || "-"),
|
||||
授权人数: String(basic.peopleCount || "-"),
|
||||
生效时间: basic.startTime ? new Date(Number(basic.startTime)).toLocaleDateString() : "-",
|
||||
到期时间: basic.endTime ? new Date(Number(basic.endTime)).toLocaleDateString() : "-",
|
||||
};
|
||||
|
||||
const packageRows = detail.corporationPackageVos.map((p, i) => [
|
||||
String(i + 1),
|
||||
p.name,
|
||||
p.packageId,
|
||||
p.enable ? "🟢 已启用" : "⚪ 未开通",
|
||||
]);
|
||||
|
||||
const packageTable = printTable(["#", "套餐版本", "套餐 ID", "开通状态"], packageRows);
|
||||
|
||||
const goodsRows = detail.otherGoodsList.slice(0, 30).map((g, i) => [
|
||||
String(i + 1),
|
||||
String(g.name || "-"),
|
||||
String(g.catName || "-"),
|
||||
String(g.status || "-"),
|
||||
String(g.model || "-"),
|
||||
]);
|
||||
|
||||
const goodsTable = printTable(["#", "商品/功能名称", "业务类别", "状态", "类型"], goodsRows);
|
||||
const moreNotice = detail.otherGoodsList.length > 30
|
||||
? `\n(已显示前 30 项商品能力,全部 ${detail.otherGoodsList.length} 项可使用 --json 查看)\n`
|
||||
: "";
|
||||
|
||||
return {
|
||||
stdout: `====== 企业 [${corpId}] 协助中心全量业务配置 ======\n${printKeyValue(summaryPairs)}\n\n--- 原生套餐包规格 ---\n${packageTable}\n\n--- 已开通商品与扩展能力 ---\n${goodsTable}${moreNotice}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
import { BusinessError } from "../../../core/errors.js";
|
||||
import {
|
||||
generateAssistSession,
|
||||
importAssistSessionToLocal,
|
||||
} from "../../../domains/assist-platform/services.js";
|
||||
import type { AssistIdentityProfile } from "../../../domains/assist-platform/types.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
||||
import { booleanOption, stringOption } from "../../parser.js";
|
||||
import { printJson, printKeyValue } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { resolveAssistClient } from "./common.js";
|
||||
|
||||
function formatIdentityLines(ident?: AssistIdentityProfile): {
|
||||
profilePairs: Record<string, string>;
|
||||
warningText: string;
|
||||
} {
|
||||
const profilePairs: Record<string, string> = {};
|
||||
let warningText = "";
|
||||
|
||||
if (!ident) {
|
||||
return { profilePairs, warningText };
|
||||
}
|
||||
|
||||
profilePairs["获取员工身份"] = `${ident.staffName} (${ident.staffId || "-"})`;
|
||||
if (ident.departmentName) profilePairs["所属部门"] = ident.departmentName;
|
||||
if (ident.cellphone) profilePairs["绑定手机"] = ident.cellphone;
|
||||
if (ident.roleNames.length > 0) profilePairs["所配角色清单"] = ident.roleNames.join("、");
|
||||
if (ident.readablePermissions.length > 0) {
|
||||
const permSummary = ident.readablePermissions.slice(0, 5).join("、");
|
||||
profilePairs["核心系统权限"] = `${permSummary}${ident.readablePermissions.length > 5 ? ` 等共 ${ident.readablePermissions.length} 项` : ""}`;
|
||||
}
|
||||
|
||||
if (ident.profileComplete === false) {
|
||||
profilePairs["身份画像状态"] = "信息不完整,无法排除更高权限风险";
|
||||
}
|
||||
|
||||
if (ident.isSeniorExecutive && ident.riskWarning) {
|
||||
const titles = ident.seniorTitles.length > 0 ? ident.seniorTitles.join(" / ") : "高级管理人员";
|
||||
warningText =
|
||||
`\n⚠️ 【高阶管理人员权限风控警示 (Executive Role Risk Warning)】\n` +
|
||||
`当前协助会话获取的是企业【${titles}】身份(${ident.staffName})。\n` +
|
||||
`防范越权与误用守则:\n` +
|
||||
` 1. 该身份在企业内具备高级审批、财务支配与全系统管理权限;\n` +
|
||||
` 2. 经理与一线实施人员严禁代用高管身份进行业务审批通过或非授权表单提交;\n` +
|
||||
` 3. 请严格将此会话权限限定在必要的系统排障、配置诊断与接口联调中!\n`;
|
||||
}
|
||||
|
||||
return { profilePairs, warningText };
|
||||
}
|
||||
|
||||
export async function handleEnter(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const corpId =
|
||||
parsed.args[0] ||
|
||||
stringOption(parsed.options, ["corp", "corpid", "id"]) ||
|
||||
runtime.selectedCorp?.id;
|
||||
|
||||
if (!corpId) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use assist-platform enter <企业ID> [--admin] [--staff <姓名>] [--save] [--switch]\n示例: hose-use assist-platform enter Cxa3oOtQi2eS$g --staff 李志财 --save --yes\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const ticketId = stringOption(parsed.options, ["ticket", "ticket-id", "auth-code"]);
|
||||
const staffName = stringOption(parsed.options, ["staff", "user", "name"]);
|
||||
const forceAdmin = booleanOption(parsed.options, ["admin"]);
|
||||
// 如果显式指定了 staffName 且未显式指定 --admin,则为用户模式;否则默认为管理员模式
|
||||
const isAdmin = forceAdmin || !staffName;
|
||||
|
||||
const shouldSave = booleanOption(parsed.options, ["save", "import", "persist"]);
|
||||
const shouldSwitch = booleanOption(parsed.options, ["switch", "current"]);
|
||||
const overwrite = booleanOption(parsed.options, ["overwrite"]);
|
||||
const saveName = stringOption(parsed.options, ["alias", "corp-name"]);
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(
|
||||
parsed,
|
||||
runtime,
|
||||
shouldSave || shouldSwitch
|
||||
? "从协助平台换取免密凭证并落盘为本地企业配置"
|
||||
: "从协助平台换取免密凭证并生成直通链接",
|
||||
saveName || `企业 [${corpId}]`,
|
||||
{
|
||||
corpId,
|
||||
isAdmin,
|
||||
staffName: staffName || null,
|
||||
ticketId: ticketId || "自动选择最新有效工单",
|
||||
save: shouldSave || shouldSwitch,
|
||||
switchCurrent: shouldSwitch,
|
||||
overwrite,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
const client = resolveAssistClient(parsed, runtime);
|
||||
|
||||
// 1. 若不要求保存落盘,仅生成直通免密链接输出
|
||||
if (!shouldSave && !shouldSwitch) {
|
||||
const sessionRes = await generateAssistSession(client, {
|
||||
corpId,
|
||||
ticketId,
|
||||
isAdmin,
|
||||
staffName,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(sessionRes, runtime.outputOptions),
|
||||
preserveSensitiveStdout: true,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const pairs: Record<string, string> = {
|
||||
企业ID: sessionRes.corporationId,
|
||||
授权模式: sessionRes.isAdmin ? "👑 企业管理员 (Admin)" : `👤 普通员工 (${sessionRes.staffName || "-"})`,
|
||||
授权工单: sessionRes.ticketId,
|
||||
会话Token: sessionRes.token,
|
||||
免密直通链接: sessionRes.loginUrl,
|
||||
};
|
||||
|
||||
const { profilePairs, warningText } = formatIdentityLines(sessionRes.identity);
|
||||
Object.assign(pairs, profilePairs);
|
||||
|
||||
return {
|
||||
preserveSensitiveStdout: true,
|
||||
stdout:
|
||||
`====== 协助平台免密会话生成成功 ======\n${printKeyValue(pairs)}\n` +
|
||||
`${warningText}\n操作提示:\n` +
|
||||
` - 在浏览器中打开以上链接可直接进入协助调试工作台\n` +
|
||||
` - 若要一键落盘到本地企业配置: hose-use assist-platform enter ${corpId} ${sessionRes.isAdmin ? "--admin" : `--staff "${sessionRes.staffName}"`} --save --yes\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 2. 要求持久化落盘 / 切换为工作企业
|
||||
const nextConfirmCmd = `hose-use assist-platform enter ${corpId} ${isAdmin ? "--admin" : `--staff "${staffName}"`} --save ${shouldSwitch ? "--switch " : ""}--yes`;
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
`从协助平台换取凭证并导入企业 [${corpId}]`,
|
||||
nextConfirmCmd
|
||||
);
|
||||
|
||||
const { sessionResult, corpConfig } = await importAssistSessionToLocal(client, {
|
||||
corpId,
|
||||
ticketId,
|
||||
isAdmin,
|
||||
staffName,
|
||||
saveName,
|
||||
overwrite: overwrite ?? true,
|
||||
});
|
||||
|
||||
// 导入文件后同步注册到当前运行态,确保新企业可立即切换
|
||||
runtime.corpContext.upsertCorp(corpConfig);
|
||||
|
||||
// 若指定了 --switch,切换当前激活企业
|
||||
const switched = shouldSwitch && runtime.corpContext.switchCorp(corpConfig.id, true);
|
||||
if (shouldSwitch && !switched) {
|
||||
throw new BusinessError(`企业 [${corpConfig.id}] 配置已保存,但切换当前工作企业失败,请运行 hose-use corps switch ${corpConfig.id} 重试`);
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
preserveSensitiveStdout: true,
|
||||
stdout: printJson({
|
||||
success: true,
|
||||
sessionResult,
|
||||
enterprise: {
|
||||
id: corpConfig.id,
|
||||
name: corpConfig.name,
|
||||
staffId: corpConfig.credentials.staffId,
|
||||
hasOpenApi: Boolean(corpConfig.credentials.appKey),
|
||||
switched,
|
||||
},
|
||||
}, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const successPairs: Record<string, string> = {
|
||||
企业标识: corpConfig.id,
|
||||
企业名称: corpConfig.name,
|
||||
执行身份: sessionResult.isAdmin ? "👑 企业管理员" : `👤 ${sessionResult.staffName || "员工"} (${corpConfig.credentials.staffId})`,
|
||||
授权工单: sessionResult.ticketId,
|
||||
凭证状态: corpConfig.credentials.appKey ? `✅ 已提取 OpenAPI 持久化密钥 (${corpConfig.credentials.appKey})` : "⚪ 临时协助会话",
|
||||
配置文件: `enterprises/${corpConfig.id}.json`,
|
||||
激活状态: switched ? "🎯 已设为当前激活工作企业" : "可随时运行 hose-use corps switch 进行切换",
|
||||
};
|
||||
|
||||
const { profilePairs, warningText } = formatIdentityLines(sessionResult.identity);
|
||||
Object.assign(successPairs, profilePairs);
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] 协助企业凭证获取并落盘成功!\n${printKeyValue(successPairs)}\n${warningText}`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { handleLogin } from "./login.js";
|
||||
import { handleSearch } from "./search.js";
|
||||
import { handleDetail } from "./detail.js";
|
||||
import { handleTickets } from "./tickets.js";
|
||||
import { handleStaff } from "./staff.js";
|
||||
import { handleEnter } from "./enter.js";
|
||||
import { handleApply } from "./apply.js";
|
||||
import { handleApprove } from "./approve.js";
|
||||
import { handleTransfer } from "./transfer.js";
|
||||
|
||||
export async function handleAssistPlatformCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const action = (parsed.action || "help").toLowerCase();
|
||||
|
||||
switch (action) {
|
||||
case "login":
|
||||
case "auth":
|
||||
case "status":
|
||||
return handleLogin(parsed, runtime);
|
||||
|
||||
case "search":
|
||||
case "find":
|
||||
case "list":
|
||||
case "ls":
|
||||
return handleSearch(parsed, runtime);
|
||||
|
||||
case "detail":
|
||||
case "info":
|
||||
case "config":
|
||||
return handleDetail(parsed, runtime);
|
||||
|
||||
case "tickets":
|
||||
case "ticket":
|
||||
case "order":
|
||||
case "orders":
|
||||
return handleTickets(parsed, runtime);
|
||||
|
||||
case "staff":
|
||||
case "user":
|
||||
case "users":
|
||||
return handleStaff(parsed, runtime);
|
||||
|
||||
case "enter":
|
||||
case "import":
|
||||
case "token":
|
||||
case "get-token":
|
||||
return handleEnter(parsed, runtime);
|
||||
|
||||
case "apply":
|
||||
case "create":
|
||||
case "request":
|
||||
case "new":
|
||||
return handleApply(parsed, runtime);
|
||||
|
||||
case "approve":
|
||||
case "authorize":
|
||||
case "pass":
|
||||
return handleApprove(parsed, runtime);
|
||||
|
||||
case "transfer":
|
||||
case "transmit":
|
||||
case "forward":
|
||||
return handleTransfer(parsed, runtime);
|
||||
|
||||
case "help":
|
||||
case "--help":
|
||||
case "-h":
|
||||
default:
|
||||
return printHelp();
|
||||
}
|
||||
}
|
||||
|
||||
function printHelp(): CliResult {
|
||||
const helpText = `用法: hose-use assist-platform <子命令> [参数] [选项]
|
||||
|
||||
别名: assist-center, ap
|
||||
|
||||
合思协助平台(https://unity.ekuaibao.com/platform-charge/)自动化运维交互命令。
|
||||
提供跨企业 34万+ 检索、协助工单状态查询、员工定位与免密直通链接一键换票持久化能力。
|
||||
|
||||
子命令列表:
|
||||
login 查看当前协助平台会话,或传入 --token <TOKEN> 进行登录保存
|
||||
search <关键词> 在协助中心 34 万家企业库中分页检索企业
|
||||
detail <企业ID> 查看企业全量业务配置(套餐规格、基础参数、已开通商品扩展能力)
|
||||
tickets <企业ID> 查询指定企业的协助工单(申请人、授权码、剩余时长、工单状态)
|
||||
staff <企业ID> <姓名> 查询企业内部指定员工的工号、账号、邮箱及 admin 属性
|
||||
apply <企业ID> 向目标企业发起新的协助授权工单申请(待客户管理员审批)
|
||||
approve [工单ID] 审批通过协助授权工单申请(端内管理员通过授权)
|
||||
enter <企业ID> 一键换取协助免密直通链接并进入(可选 --save 落盘为本地工作企业)
|
||||
transfer <企业ID> 转交协助工单权限给其他同事(可指定 --to 与 --ticket,支持 --candidates 查询人员)
|
||||
|
||||
常用选项:
|
||||
--token, -t <TOKEN> 显式指定当前操作使用的协助平台 Token
|
||||
--admin 指定使用企业管理员模式换取免密链接(默认)
|
||||
--staff <员工姓名> 指定使用特定员工身份换取免密链接
|
||||
--save 一键将换取的免密会话持久化落盘至本地企业列表(自动提取 OpenAPI 密钥)
|
||||
--switch 配合 --save,导入后自动切换为当前激活工作企业
|
||||
--json 输出结构化 JSON 格式结果
|
||||
--dry-run 预览副作用操作,不真实落盘
|
||||
--yes, -y 跳过确认提示直接执行写操作
|
||||
|
||||
示例:
|
||||
hose-use assist-platform login --token c31e9bb7-b0ed-4238-91bd-12ec14e05a5b
|
||||
hose-use assist-platform search "CSM"
|
||||
hose-use assist-platform tickets Cxa3oOtQi2eS$g
|
||||
hose-use assist-platform staff Cxa3oOtQi2eS$g 李志财
|
||||
hose-use assist-platform enter Cxa3oOtQi2eS$g --staff 李志财 --save --switch --yes
|
||||
`;
|
||||
|
||||
return {
|
||||
stdout: helpText,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import {
|
||||
loadAssistPlatformSession,
|
||||
saveAssistPlatformSession,
|
||||
clearAssistPlatformSession,
|
||||
} from "../../../core/auth/assist-platform-store.js";
|
||||
import { createAssistPlatformClient } from "../../../core/http/assist-platform-client.js";
|
||||
import { searchCorporations } from "../../../domains/assist-platform/services.js";
|
||||
import { booleanOption, stringOption } from "../../parser.js";
|
||||
import { printJson, printKeyValue } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
|
||||
export async function handleLogin(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const logout = booleanOption(parsed.options, ["logout"]);
|
||||
if (logout) {
|
||||
clearAssistPlatformSession();
|
||||
return {
|
||||
stdout: "[SUCCESS] 已成功注销并清理协助平台本地会话。\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const explicitToken = stringOption(parsed.options, ["token", "t"]);
|
||||
const userName = stringOption(parsed.options, ["user", "name", "u"]);
|
||||
const hoseAccessToken = stringOption(parsed.options, ["hose-token", "jwt"]);
|
||||
|
||||
if (explicitToken) {
|
||||
// 验证 Token 连通性
|
||||
const testClient = createAssistPlatformClient({
|
||||
token: explicitToken,
|
||||
hoseAccessToken,
|
||||
});
|
||||
try {
|
||||
await searchCorporations(testClient, { limit: { start: 0, count: 1 } });
|
||||
} catch (err) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[ERROR] 协助平台 Token 校验失败: ${err instanceof Error ? err.message : String(err)}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
saveAssistPlatformSession({
|
||||
token: explicitToken,
|
||||
hoseAccessToken,
|
||||
userName: userName || "运营实施人员",
|
||||
baseUrl: "https://unity.ekuaibao.com/api",
|
||||
updatedAt: Date.now(),
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ success: true, token: explicitToken, userName }),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] 协助平台登录凭证保存成功!\n操作人员: ${userName || "运营人员"}\n会话 Token: ${explicitToken}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 查看当前协助平台会话状态
|
||||
const existing = loadAssistPlatformSession();
|
||||
if (!existing || !existing.token) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未检测到协助平台登录凭证。\n用法:\n hose-use assist-platform login --token <TOKEN> [--user <姓名>]\n hose-use assist-platform login --logout (清理凭证)\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(existing),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const pairs: Record<string, string> = {
|
||||
协助平台状态: "🟢 已登录",
|
||||
操作员工姓名: existing.userName || "运营实施人员",
|
||||
基础服务地址: existing.baseUrl || "https://unity.ekuaibao.com/api",
|
||||
当前会话凭证: existing.token.replace(/(.{4}).*(.{4})/, "$1****$2"),
|
||||
最后更新时间: new Date(existing.updatedAt).toLocaleString("zh-CN", { hour12: false }),
|
||||
};
|
||||
|
||||
return {
|
||||
stdout: `====== 合思协助平台当前会话 ======\n${printKeyValue(pairs)}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { searchCorporations } from "../../../domains/assist-platform/services.js";
|
||||
import { numberOption, stringOption } from "../../parser.js";
|
||||
import { printJson, printTable } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { resolveAssistClient } from "./common.js";
|
||||
|
||||
export async function handleSearch(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const client = resolveAssistClient(parsed, runtime);
|
||||
const keyword =
|
||||
parsed.args[0] ||
|
||||
stringOption(parsed.options, ["keyword", "query", "q", "name", "id"]) ||
|
||||
"";
|
||||
|
||||
const count = numberOption(parsed.options, ["count", "limit", "n"]) || 20;
|
||||
const start = numberOption(parsed.options, ["start", "offset"]) || 0;
|
||||
const state = stringOption(parsed.options, ["state", "status"]);
|
||||
|
||||
const res = await searchCorporations(client, {
|
||||
keyword: keyword.trim() || undefined,
|
||||
state: state?.trim() || undefined,
|
||||
limit: { start, count },
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(res, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (res.items.length === 0) {
|
||||
return {
|
||||
stdout: `协助平台企业库中未找到匹配 "${keyword}" 的企业记录。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = res.items.map((c, i) => [
|
||||
String(start + i + 1),
|
||||
c.id,
|
||||
c.name,
|
||||
c.platformName || "app",
|
||||
c.state || "-",
|
||||
c.payType === "TRYOUT" ? "试用" : c.payType === "PAY" ? "付费" : c.payType || "-",
|
||||
c.sumPeople !== null && c.sumPeople !== undefined ? String(c.sumPeople) : "-",
|
||||
c.tel || "-",
|
||||
]);
|
||||
|
||||
const table = printTable(
|
||||
["#", "企业 ID", "企业名称", "集群", "状态", "类型", "授权人数", "联系电话"],
|
||||
rows
|
||||
);
|
||||
|
||||
return {
|
||||
stdout: `====== 合思协助平台企业搜索结果 (共匹配 ${res.count} 家,当前显示 ${res.items.length} 条) ======\n${table}\n\n提示: 可使用 hose-use assist-platform tickets <企业ID> 查询协助工单\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { findStaff } from "../../../domains/assist-platform/services.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson, printTable } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { resolveAssistClient } from "./common.js";
|
||||
|
||||
export async function handleStaff(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const client = resolveAssistClient(parsed, runtime);
|
||||
const corpId =
|
||||
parsed.args[0] ||
|
||||
stringOption(parsed.options, ["corp", "corpid", "id"]) ||
|
||||
runtime.selectedCorp?.id;
|
||||
|
||||
const staffName =
|
||||
parsed.args[1] ||
|
||||
stringOption(parsed.options, ["name", "user", "staff"]);
|
||||
|
||||
if (!corpId || !staffName) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use assist-platform staff <企业ID> <员工姓名>\n示例: hose-use assist-platform staff Cxa3oOtQi2eS$g 李志财\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const staffList = await findStaff(client, corpId, staffName);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ corporationId: corpId, queryName: staffName, items: staffList }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (staffList.length === 0) {
|
||||
return {
|
||||
stdout: `企业 [${corpId}] 中未找到名为 "${staffName}" 的员工。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = staffList.map((s, i) => [
|
||||
String(i + 1),
|
||||
s.name,
|
||||
s.code || "-",
|
||||
s.admin ? "👑 是" : "否",
|
||||
s.cellphone || "-",
|
||||
s.email || "-",
|
||||
s.id,
|
||||
]);
|
||||
|
||||
const table = printTable(
|
||||
["#", "姓名", "工号", "管理员", "手机号码", "邮箱地址", "员工全局 ID (Staff ID)"],
|
||||
rows
|
||||
);
|
||||
|
||||
return {
|
||||
stdout: `====== 企业 [${corpId}] 员工查询结果 ("${staffName}") ======\n${table}\n\n操作提示: 可使用 hose-use assist-platform enter ${corpId} --staff ${staffName} --save --yes 一键换票导入\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { listAssistTickets } from "../../../domains/assist-platform/services.js";
|
||||
import { booleanOption, stringOption } from "../../parser.js";
|
||||
import { printJson, printTable } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { resolveAssistClient } from "./common.js";
|
||||
|
||||
export async function handleTickets(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const client = resolveAssistClient(parsed, runtime);
|
||||
const isAll = booleanOption(parsed.options, ["all", "a"], false);
|
||||
const corpId =
|
||||
parsed.args[0] ||
|
||||
stringOption(parsed.options, ["corp", "corpid", "id"]) ||
|
||||
runtime.selectedCorp?.id;
|
||||
|
||||
if (!corpId) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use assist-platform tickets <企业ID> [--all]\n示例: hose-use assist-platform tickets Cxa3oOtQi2eS$g\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const tickets = await listAssistTickets(client, corpId);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ corporationId: corpId, count: tickets.length, all: isAll, tickets }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (tickets.length === 0) {
|
||||
return {
|
||||
stdout: `企业 [${corpId}] 协助中心未查询到任何协助工单记录。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = tickets.map((t, i) => [
|
||||
String(i + 1),
|
||||
t.ticketId,
|
||||
t.applicant,
|
||||
t.principal || "-",
|
||||
t.state === "已提供" || t.state === "1"
|
||||
? "🟢 生效中"
|
||||
: t.state === "待提供" || t.state === "0"
|
||||
? "🟡 待提供"
|
||||
: t.state === "已过期" || t.state === "2"
|
||||
? "⚪ 已结束"
|
||||
: t.state,
|
||||
t.duration ? `${t.duration}h` : "-",
|
||||
t.usePeriodDesc || (t.startTime && t.endTime ? `${new Date(t.startTime).toLocaleDateString()} - ${new Date(t.endTime).toLocaleDateString()}` : "-"),
|
||||
]);
|
||||
|
||||
const table = printTable(
|
||||
["#", "授权码 (Ticket ID)", "申请人", "负责人", "工单状态", "时长", "有效期限"],
|
||||
rows
|
||||
);
|
||||
|
||||
return {
|
||||
stdout: `====== 企业 [${corpId}] 协助工单列表 (共 ${tickets.length} 条) ======\n${table}\n\n操作提示:\n - 一键管理员直通调试: hose-use assist-platform enter ${corpId} --save --yes\n - 一键指定员工身份进入: hose-use assist-platform enter ${corpId} --staff <员工姓名> --save --yes\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
import {
|
||||
listAssistTickets,
|
||||
listTransferCandidates,
|
||||
resolveTransferRecipient,
|
||||
transferAssistTicket,
|
||||
} from "../../../domains/assist-platform/services.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
||||
import { booleanOption, stringOption } from "../../parser.js";
|
||||
import { printJson, printKeyValue } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { resolveAssistClient } from "./common.js";
|
||||
|
||||
export async function handleTransfer(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const client = resolveAssistClient(parsed, runtime);
|
||||
const isListMode = booleanOption(parsed.options, ["candidates", "list-candidates"]);
|
||||
|
||||
// 1. 列出可转交候选人员清单
|
||||
if (isListMode) {
|
||||
const keyword = stringOption(parsed.options, ["keyword", "query", "q", "name"]) || parsed.args[0];
|
||||
const candidates = await listTransferCandidates(client, keyword);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ count: candidates.length, items: candidates }),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (candidates.length === 0) {
|
||||
return {
|
||||
stdout: `未找到匹配的可转交人员${keyword ? ` (关键词: ${keyword})` : ""}。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const lines = candidates.map(
|
||||
(c) => ` • ${c.name.padEnd(8, " ")} | 账号: ${c.id.padEnd(16, " ")} | 工号: ${c.code || "-"} | 角色: ${c.roles.join("、") || "-"}`
|
||||
);
|
||||
|
||||
return {
|
||||
stdout:
|
||||
`====== 协助平台可转交人员列表 (共 ${candidates.length} 人) ======\n` +
|
||||
lines.join("\n") +
|
||||
"\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 2. 转交指定工单
|
||||
const targetCorpId = parsed.args[0] || stringOption(parsed.options, ["corp", "corpid", "id"]);
|
||||
const targetRecipient = stringOption(parsed.options, ["to", "recipient", "target", "user", "name"]);
|
||||
const remarks = stringOption(parsed.options, ["remarks", "message", "msg", "comment"]);
|
||||
|
||||
if (!targetCorpId) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr:
|
||||
"[ERROR] 必须指定企业 ID 或工单编号。\n" +
|
||||
"用法:\n" +
|
||||
" hose-use assist-platform transfer <企业ID> [--ticket <工单号>] --to <姓名|工号|账号> [--remarks <备注>] --yes\n" +
|
||||
" hose-use assist-platform transfer --candidates [关键词] (查看可转交人员列表)\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (!targetRecipient) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr:
|
||||
"[ERROR] 必须通过 --to 指定接收人员姓名、工号或账号。\n" +
|
||||
"可运行 hose-use assist-platform transfer --candidates 查询人员名录。\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
// 解析工单编号:如果 args[1] 提供了则用 args[1],或 --ticket,否则自动在指定企业中查找当前生效中的工单
|
||||
let ticketId = parsed.args[1] || stringOption(parsed.options, ["ticket", "ticket-id"]);
|
||||
let resolvedRecipient;
|
||||
|
||||
try {
|
||||
resolvedRecipient = await resolveTransferRecipient(client, targetRecipient);
|
||||
} catch (err) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[ERROR] ${err instanceof Error ? err.message : String(err)}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (!ticketId) {
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
ticketId = "PREVIEW-ACTIVE-TICKET";
|
||||
} else {
|
||||
const tickets = await listAssistTickets(client, targetCorpId);
|
||||
const activeTicket = tickets.find((t) => t.state === "已提供" || t.state === "1");
|
||||
if (!activeTicket) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[ERROR] 企业 ${targetCorpId} 下未找到处于“已提供”生效状态的协助工单。\n可通过 hose-use assist-platform tickets ${targetCorpId} 查看历史工单。\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
ticketId = activeTicket.ticketId;
|
||||
}
|
||||
}
|
||||
|
||||
const operation = "协助工单转交";
|
||||
const target = `企业 ${targetCorpId} 的工单 [${ticketId}] 转交给 ${resolvedRecipient.name} (${resolvedRecipient.id})`;
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, operation, target, {
|
||||
ticketId,
|
||||
recipientId: resolvedRecipient.id,
|
||||
recipientName: resolvedRecipient.name,
|
||||
recipientCode: resolvedRecipient.code,
|
||||
remarks,
|
||||
});
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
operation,
|
||||
`hose-use assist-platform transfer ${targetCorpId} ${ticketId} --to "${resolvedRecipient.id}" --yes`
|
||||
);
|
||||
|
||||
const result = await transferAssistTicket(client, {
|
||||
ticketId,
|
||||
recipient: resolvedRecipient.id,
|
||||
remarks,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({
|
||||
success: true,
|
||||
ticketId,
|
||||
corpId: targetCorpId,
|
||||
recipient: resolvedRecipient,
|
||||
remarks,
|
||||
}),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const pairs: Record<string, string> = {
|
||||
转交状态: "🟢 转交成功",
|
||||
目标工单: ticketId,
|
||||
所属企业: targetCorpId,
|
||||
转交接收人: `${resolvedRecipient.name} (${resolvedRecipient.id}${resolvedRecipient.code ? `, 工号: ${resolvedRecipient.code}` : ""})`,
|
||||
};
|
||||
if (remarks) pairs["转交备注"] = remarks;
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] 协助工单转交成功!\n${printKeyValue(pairs)}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "bun:test";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import { parseArgs } from "../parser.js";
|
||||
import type { CliRuntime } from "../types.js";
|
||||
import { handleApprove } from "./assist-platform/approve.js";
|
||||
import { handleTransfer } from "./assist-platform/transfer.js";
|
||||
|
||||
const corp: CorpConfig = {
|
||||
id: "CORP", corpId: "CORP", name: "测试企业", source: "manual",
|
||||
baseUrl: "https://corp.invalid",
|
||||
credentials: { accessToken: "mock-token", corpId: "CORP", staffId: "ADMIN" },
|
||||
};
|
||||
const otherCorp: CorpConfig = { ...corp, id: "OTHER-CORP", corpId: "OTHER-CORP" };
|
||||
const sameNameUsers = [
|
||||
{ id: "ROLE1", userId: { id: "user3016", name: "张三", code: "3016" } },
|
||||
{ id: "ROLE2", userId: { id: "user3020", name: "张三", code: "3020" } },
|
||||
];
|
||||
|
||||
function runtime(selectedCorp: CorpConfig | null = corp): CliRuntime {
|
||||
return {
|
||||
jsonMode: true, selectedCorp,
|
||||
corpContext: { getAllCorps: () => [corp, otherCorp] } as CliRuntime["corpContext"],
|
||||
};
|
||||
}
|
||||
|
||||
let originalFetch: typeof globalThis.fetch;
|
||||
let originalStore: string | undefined;
|
||||
let stateDir: string;
|
||||
let requests: Request[];
|
||||
let responses: (request: Request) => Response | Promise<Response>;
|
||||
|
||||
beforeEach(() => {
|
||||
originalFetch = globalThis.fetch;
|
||||
originalStore = process.env.HOSE_ASSIST_PLATFORM_FILE;
|
||||
stateDir = mkdtempSync(join(tmpdir(), "hose-assist-targets-"));
|
||||
process.env.HOSE_ASSIST_PLATFORM_FILE = join(stateDir, "session.json");
|
||||
requests = [];
|
||||
responses = () => Response.json({ items: [{ ticketId: "OTHER-TICKET", state: "0" }] });
|
||||
globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {
|
||||
const request = input instanceof Request ? input : new Request(input.toString(), init);
|
||||
// Bun 的 Request.clone 声明采用 undici Headers;运行态仍是同一个 Request 类型。
|
||||
requests.push(request.clone() as unknown as Request);
|
||||
return responses(request);
|
||||
}) as typeof globalThis.fetch;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
globalThis.fetch = originalFetch;
|
||||
if (originalStore === undefined) delete process.env.HOSE_ASSIST_PLATFORM_FILE;
|
||||
else process.env.HOSE_ASSIST_PLATFORM_FILE = originalStore;
|
||||
rmSync(stateDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("assist-platform approve 的明确工单目标", () => {
|
||||
it.each([
|
||||
["REQUESTED", "--corp", "CORP"],
|
||||
["CORP", "REQUESTED"],
|
||||
["CORP", "--ticket", "REQUESTED"],
|
||||
["--corp", "CORP", "--ticket", "REQUESTED"],
|
||||
["REQUESTED"],
|
||||
["--ticket", "REQUESTED"],
|
||||
["REQUESTED", "--corp", "CORP", "--ticket", "REQUESTED"],
|
||||
].map((args) => ({ args })))("预览保留工单参数 %j,不自动查询其他工单", async ({ args }) => {
|
||||
const result = await handleApprove(parseArgs(["assist-platform", "approve", ...args, "--dry-run"]), runtime());
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(JSON.parse(result.stdout).changes["工单编号"]).toBe("REQUESTED");
|
||||
expect(requests).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("显式 --corp 下首参即使也是已知企业 ID,仍作为工单", async () => {
|
||||
const parsed = parseArgs(["assist-platform", "approve", "OTHER-CORP", "--corp", "CORP", "--dry-run"]);
|
||||
const result = await handleApprove(parsed, runtime());
|
||||
expect(JSON.parse(result.stdout).changes["工单编号"]).toBe("OTHER-CORP");
|
||||
expect(requests).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("--yes 真实提交路径只审批显式工单,不能自动替换为列表首项", async () => {
|
||||
responses = (request) => request.method === "PUT"
|
||||
? Response.json({ value: { id: "REQUESTED", corporationId: "CORP" } })
|
||||
: Response.json({ items: [{ ticketId: "OTHER-TICKET", state: "0" }] });
|
||||
const result = await handleApprove(
|
||||
parseArgs(["assist-platform", "approve", "REQUESTED", "--corp", "CORP", "--yes"]), runtime()
|
||||
);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(requests).toHaveLength(1);
|
||||
expect(requests[0].method).toBe("PUT");
|
||||
expect(requests[0].url).toContain("/$REQUESTED/updateStatus?corpId=CORP");
|
||||
expect(await requests[0].json()).toEqual({ id: "REQUESTED", status: 1 });
|
||||
});
|
||||
|
||||
it.each([
|
||||
["REQUESTED", "--corp", "CORP", "--ticket", "OTHER-TICKET"],
|
||||
["CORP", "REQUESTED", "--ticket", "OTHER-TICKET"],
|
||||
["UNKNOWN-CORP", "REQUESTED"],
|
||||
["CORP", "REQUESTED", "--corp", "OTHER-CORP"],
|
||||
["CORP", "REQUESTED", "EXTRA"],
|
||||
].map((args) => ({ args })))("拒绝歧义或冲突参数 %j,且不查询或提交", async ({ args }) => {
|
||||
const result = await handleApprove(parseArgs(["assist-platform", "approve", ...args, "--yes"]), runtime());
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain("歧义或冲突");
|
||||
expect(requests).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("显式企业未知时不能回退当前企业", async () => {
|
||||
const result = await handleApprove(
|
||||
parseArgs(["assist-platform", "approve", "REQUESTED", "--corp", "UNKNOWN", "--yes"]), runtime()
|
||||
);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain("UNKNOWN");
|
||||
expect(requests).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("只有未指定工单时才自动查询待授权工单", async () => {
|
||||
const result = await handleApprove(parseArgs([
|
||||
"assist-platform", "approve", "--corp", "CORP", "--token", "mock-token", "--dry-run",
|
||||
]), runtime());
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(JSON.parse(result.stdout).changes["工单编号"]).toBe("OTHER-TICKET");
|
||||
expect(requests).toHaveLength(1);
|
||||
expect(requests[0].url).toContain("assistPlatform/$CORP/search");
|
||||
});
|
||||
});
|
||||
|
||||
describe("assist-platform transfer 预览与执行的收件人解析", () => {
|
||||
it.each(["--dry-run", "--yes"])("%s 遇到同名用户都拒绝且不提交", async (mode) => {
|
||||
responses = () => Response.json({ items: sameNameUsers });
|
||||
const result = await handleTransfer(parseArgs([
|
||||
"assist-platform", "transfer", "CORP", "TICKET", "--to", "张三", "--token", "mock-token", mode,
|
||||
]), runtime());
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain("唯一工号或账号");
|
||||
expect(requests).toHaveLength(1);
|
||||
expect(requests[0].url).toContain("userRole/search");
|
||||
});
|
||||
|
||||
it("查询失败的 dry-run 也不能显示成功解析的预览", async () => {
|
||||
responses = () => new Response("unauthorized", { status: 401 });
|
||||
const result = await handleTransfer(parseArgs([
|
||||
"assist-platform", "transfer", "CORP", "TICKET", "--to", "user3016", "--token", "mock-token", "--dry-run",
|
||||
]), runtime());
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stdout).toBe("");
|
||||
});
|
||||
|
||||
it("唯一工号的 dry-run 显示实际账号,与 --yes 的请求一致", async () => {
|
||||
responses = (request) => request.url.includes("userRole/search")
|
||||
? Response.json({ items: sameNameUsers })
|
||||
: Response.json({ value: true });
|
||||
const args = ["assist-platform", "transfer", "CORP", "TICKET", "--to", "3016", "--token", "mock-token"];
|
||||
const preview = await handleTransfer(parseArgs([...args, "--dry-run"]), runtime());
|
||||
expect(JSON.parse(preview.stdout).changes.recipientId).toBe("user3016");
|
||||
const result = await handleTransfer(parseArgs([...args, "--yes"]), runtime());
|
||||
expect(result.exitCode).toBe(0);
|
||||
const writes = requests.filter((request) => request.url.includes("assistPlatform/transfer"));
|
||||
expect(writes).toHaveLength(1);
|
||||
expect(await writes[0].json()).toEqual({ assistId: "TICKET", recipient: "user3016" });
|
||||
});
|
||||
});
|
||||
@@ -207,7 +207,8 @@ export async function handleTrace(ctx: BillActionContext): Promise<CliResult> {
|
||||
}
|
||||
|
||||
const client = await ctx.getClient();
|
||||
const report = await traceBillFlowDetail(client, corpId, target);
|
||||
const skipInvoices = booleanOption(parsed.options, ["no-invoice", "noInvoice", "basic"]);
|
||||
const report = await traceBillFlowDetail(client, corpId, target, { skipInvoices });
|
||||
|
||||
if (!report.found) {
|
||||
if (runtime.jsonMode) {
|
||||
|
||||
@@ -3,6 +3,7 @@ import { parseHeadersOrCurl } from "../../core/auth/login.js";
|
||||
import { resolveCorpCluster } from "../../core/http/unity-client.js";
|
||||
import { handleCorpsCommand } from "./corps/index.js";
|
||||
import type { CliRuntime } from "../types.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
|
||||
describe("core/auth/login > parseHeadersOrCurl & URL link parsing", () => {
|
||||
it("successfully parses standard thirdparty.html assistance links", () => {
|
||||
@@ -418,4 +419,86 @@ describe("cli/commands/corps > handleCorpsCommand search & aliases", () => {
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("通过 OpenAPI 持久化密钥接入企业");
|
||||
});
|
||||
|
||||
it("supports corps hose-staffs with auto-resolved corp credentials", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
try {
|
||||
globalThis.fetch = (async (input: unknown) => {
|
||||
const urlStr = typeof input === "string" ? input : input instanceof URL ? input.toString() : (input as { url: string }).url;
|
||||
if (urlStr.includes("/api/openapi/v1/auth/getAccessToken")) {
|
||||
return new Response(JSON.stringify({
|
||||
value: {
|
||||
accessToken: "mock-open-token",
|
||||
corporationId: "corpKeyed",
|
||||
corporation: { id: "corpKeyed", name: "已配密钥企业" },
|
||||
},
|
||||
}), { status: 200 });
|
||||
}
|
||||
if (urlStr.includes("/api/openapi/v1/roleDefGroups")) {
|
||||
return new Response(JSON.stringify({
|
||||
items: [
|
||||
{
|
||||
id: "g1",
|
||||
name: "默认组",
|
||||
roleDefs: [
|
||||
{ id: "corpKeyed:admin", name: "主管理员" },
|
||||
],
|
||||
},
|
||||
],
|
||||
}), { status: 200 });
|
||||
}
|
||||
if (urlStr.includes("/api/openapi/v1/roledefs/")) {
|
||||
return new Response(JSON.stringify({
|
||||
value: {
|
||||
id: "corpKeyed:admin",
|
||||
name: "主管理员",
|
||||
count: 1,
|
||||
contents: [{ staffs: ["corpKeyed:staff1"] }],
|
||||
},
|
||||
}), { status: 200 });
|
||||
}
|
||||
if (urlStr.includes("/api/openapi/v1/staffs/getStaffIds")) {
|
||||
return new Response(JSON.stringify({
|
||||
items: [
|
||||
{ id: "corpKeyed:staff1", name: "测试管理员", code: "001", active: true },
|
||||
],
|
||||
}), { status: 200 });
|
||||
}
|
||||
return new Response(JSON.stringify({}), { status: 200 });
|
||||
}) as unknown as typeof fetch;
|
||||
|
||||
const corpWithKeys: CorpConfig = {
|
||||
id: "corpKeyed",
|
||||
name: "已配密钥企业",
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
source: "openapi",
|
||||
credentials: {
|
||||
accessToken: "token-x",
|
||||
corpId: "corpKeyed",
|
||||
staffId: "corpKeyed:STAFF",
|
||||
appKey: "my-key-123",
|
||||
appSecurity: "my-sec-456",
|
||||
},
|
||||
};
|
||||
|
||||
const res = await handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
action: "hose-staffs",
|
||||
args: [],
|
||||
options: { role: "admin", json: true },
|
||||
raw: ["corps", "hose-staffs", "--role=admin", "--json"],
|
||||
},
|
||||
{ ...searchRuntime, selectedCorp: corpWithKeys, jsonMode: true }
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
const data = JSON.parse(res.stdout);
|
||||
expect(data.roleName).toBe("主管理员");
|
||||
expect(data.staffs).toHaveLength(1);
|
||||
expect(data.staffs[0].name).toBe("测试管理员");
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -43,15 +43,21 @@ export async function handleProbeHose(parsed: CliParsedArgs, runtime: CliRuntime
|
||||
}
|
||||
|
||||
export 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"]);
|
||||
let appKey = stringOption(parsed.options, ["app-key", "appKey"]);
|
||||
let appSecurity = stringOption(parsed.options, ["app-security", "appSecurity", "secret"]);
|
||||
let domain = stringOption(parsed.options, ["domain", "base-url"]);
|
||||
const role = stringOption(parsed.options, ["role", "roleDefId"]);
|
||||
|
||||
if ((!appKey || !appSecurity) && runtime.selectedCorp?.credentials?.appKey && runtime.selectedCorp?.credentials?.appSecurity) {
|
||||
appKey = runtime.selectedCorp.credentials.appKey;
|
||||
appSecurity = runtime.selectedCorp.credentials.appSecurity;
|
||||
domain = domain || runtime.selectedCorp.baseUrl;
|
||||
}
|
||||
|
||||
if (!appKey || !appSecurity) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use corps hose-staffs --app-key=<key> --app-security=<secret> [--role=admin]\n",
|
||||
stderr: "用法: hose-use corps hose-staffs [--corp=<id>] [--app-key=<key> --app-security=<secret>] [--role=admin]\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -106,6 +106,7 @@ describe("CLI - feetype 费用类型管理命令", () => {
|
||||
total: 3,
|
||||
items: mockTree,
|
||||
rawTree: mockTree,
|
||||
ids: ["COST01", "COST02", "COST19"],
|
||||
});
|
||||
|
||||
const res = await handleFeeTypeCommand(
|
||||
@@ -134,6 +135,7 @@ describe("CLI - feetype 费用类型管理命令", () => {
|
||||
total: 2,
|
||||
items: mockTree,
|
||||
rawTree: mockTree,
|
||||
ids: ["COST01", "COST02"],
|
||||
});
|
||||
|
||||
const jsonRuntime = { ...dummyRuntimeWithCorp, jsonMode: true };
|
||||
|
||||
@@ -84,11 +84,15 @@ export async function handleFeeTypeCommand(
|
||||
booleanOption(parsed.options, ["flat", "flatten", "table"]) || false;
|
||||
const keyword =
|
||||
stringOption(parsed.options, ["keyword", "q", "query"]) || parsed.args[0];
|
||||
const subtree = stringOption(parsed.options, ["subtree", "subtree-id", "parent-id"]);
|
||||
const idsOnly = booleanOption(parsed.options, ["ids-only", "ids"]) || false;
|
||||
|
||||
const result = await listFeeTypes(await getClient(), corpId, {
|
||||
all: includeAll,
|
||||
flat: isFlat,
|
||||
flat: isFlat || Boolean(subtree) || idsOnly,
|
||||
keyword,
|
||||
subtreeParentId: subtree || undefined,
|
||||
idsOnly,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
@@ -100,7 +104,7 @@ export async function handleFeeTypeCommand(
|
||||
total: result.total,
|
||||
includeDisabled: includeAll,
|
||||
keyword: keyword || null,
|
||||
items: result.items,
|
||||
...(idsOnly ? { ids: result.ids } : { items: result.items }),
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
@@ -109,8 +113,16 @@ export async function handleFeeTypeCommand(
|
||||
};
|
||||
}
|
||||
|
||||
if (idsOnly) {
|
||||
return {
|
||||
stdout: JSON.stringify(result.ids) + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
let rows: (string | number)[][] = [];
|
||||
if (!isFlat && !keyword) {
|
||||
if (!isFlat && !keyword && !subtree) {
|
||||
rows = renderTreeRows(result.rawTree);
|
||||
} else {
|
||||
const flatItems = (result.items as FlatFeeTypeItem[]) || [];
|
||||
@@ -126,7 +138,7 @@ export async function handleFeeTypeCommand(
|
||||
|
||||
const title = `====== 费用类型列表 (企业: ${corp.name} | 共 ${result.total} 个${
|
||||
includeAll ? ",含停用" : ""
|
||||
}${keyword ? `,过滤: "${keyword}"` : ""}) ======`;
|
||||
}${keyword ? `,过滤: "${keyword}"` : ""}${subtree ? `,子树: "${subtree}"` : ""}) ======`;
|
||||
const tableStr = rows.length
|
||||
? printTable(["#", "名称 / 层级路径", "编码", "ID", "状态", "子节点"], rows)
|
||||
: "暂无匹配的费用类型";
|
||||
|
||||
@@ -525,5 +525,38 @@ describe("CLI - platform 命令与 record 动作", () => {
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
expect(write).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("platform gen-props 生成 MVEL 和 JS 格式的字段模板", 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({
|
||||
id: "E_contract",
|
||||
name: "合同",
|
||||
code: "CONTRACT",
|
||||
fields: [
|
||||
{ name: "E_contract_name", label: "合同名称", type: "text", optional: false },
|
||||
{ name: "E_contract_amount", label: "合同金额", type: "money", optional: true },
|
||||
],
|
||||
} as any));
|
||||
|
||||
// MVEL 模板 (默认)
|
||||
const mvelRes = await handlePlatformCommand(
|
||||
{ area: "platform", action: "gen-props", args: ["platform-1", "contract"], options: {}, raw: [] },
|
||||
dummyRuntime
|
||||
);
|
||||
expect(mvelRes.exitCode).toBe(0);
|
||||
expect(mvelRes.stdout).toContain('String TARGET_ENTITY_ID = "E_contract";');
|
||||
expect(mvelRes.stdout).toContain('String FIELD_合同名称 = FIELD_PREFIX + "name";');
|
||||
expect(mvelRes.stdout).toContain('row.put(FIELD_合同名称, "");');
|
||||
|
||||
// JS 模板
|
||||
const jsRes = await handlePlatformCommand(
|
||||
{ area: "platform", action: "gen-props", args: ["platform-1", "contract"], options: { lang: "js" }, raw: [] },
|
||||
dummyRuntime
|
||||
);
|
||||
expect(jsRes.exitCode).toBe(0);
|
||||
expect(jsRes.stdout).toContain('const ENTITY_ID = "E_contract";');
|
||||
expect(jsRes.stdout).toContain('"合同名称": FIELD_PREFIX + "name"');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -50,10 +50,55 @@ export async function handleSchema(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime);
|
||||
const entities = resolved.entity ? [resolved.entity] : await listPlatformEntities(resolved.clients.ekbClient, resolved.corpId, resolved.platform.id);
|
||||
const fieldKeyword = stringOption(parsed.options, ["keyword", "field", "name"])?.toLowerCase();
|
||||
const output = entities.map((entity) => ({ ...entity, fields: fieldKeyword ? entity.fields.filter((field) => [field.name, field.label, field.type].some((value) => value.toLowerCase().includes(fieldKeyword))) : entity.fields }));
|
||||
const output = entities.map((entity) => ({
|
||||
...entity,
|
||||
fields: fieldKeyword
|
||||
? entity.fields.filter((field) =>
|
||||
[field.name, field.label, field.type, field.fieldKey, field.displayName].some(
|
||||
(value) => typeof value === "string" && value.toLowerCase().includes(fieldKeyword)
|
||||
)
|
||||
)
|
||||
: entity.fields,
|
||||
}));
|
||||
if (runtime.jsonMode) return { stdout: printJson({ platform: resolved.platform, count: output.length, entities: output }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows = output.flatMap((entity) => entity.fields.map((field): Array<string | number | boolean | null | undefined> => [entity.name, field.name, field.label, field.type, field.optional === false ? "必填" : "可选", cell(field.entity)]));
|
||||
return { stdout: `====== 应用 [${resolved.platform.name}] 字段定义 ======\n${printTable(["业务对象", "字段名", "显示名", "类型", "必填性", "引用对象"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
const rows = output.flatMap((entity) =>
|
||||
entity.fields.map((field): Array<string | number | boolean | null | undefined> => {
|
||||
const roleTag =
|
||||
field.role === "title"
|
||||
? "⭐ 主标题 (_name)"
|
||||
: field.role === "code"
|
||||
? "🔢 业务编码 (_code)"
|
||||
: field.role === "system"
|
||||
? "⚙️ 系统字段"
|
||||
: "📝 业务字段";
|
||||
return [
|
||||
entity.name,
|
||||
field.name,
|
||||
field.label,
|
||||
field.type,
|
||||
roleTag,
|
||||
field.optional === false ? "必填" : "可选",
|
||||
cell(field.entity),
|
||||
];
|
||||
})
|
||||
);
|
||||
const table = printTable(
|
||||
["业务对象", "物理字段键 (fieldKey / 接口参数名)", "界面名称 (label)", "类型", "角色说明", "必填性", "引用对象"],
|
||||
rows
|
||||
);
|
||||
const tips = [
|
||||
"",
|
||||
"💡 字段命名与工作流配置避坑提示:",
|
||||
" 1. 物理字段键 (fieldKey / 接口参数名): 在工作流节点映射 (如 ekuaibao-datalink-create) 和 API 请求中,必须使用此键 (例如 E_..._费用金额),切勿使用中文显示名。",
|
||||
" 2. 结尾 _name: 代表实体的业务主名称/标题 (界面通常显示为单据/计划名称);",
|
||||
" 3. 结尾 _code: 代表业务编号/单号 (界面通常显示为单据/计划编码);若设置了 autoNumber 规则,创建时会自动生成流水号。",
|
||||
"",
|
||||
].join("\n");
|
||||
return {
|
||||
stdout: `====== 应用 [${resolved.platform.name}] 字段定义 (共 ${rows.length} 个字段) ======\n${table}\n${tips}`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handlePermissions(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
@@ -77,3 +122,90 @@ export async function handleImports(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `====== 导入任务: ${resolved.platform.name} / ${resolved.entity.name} ======\n${printTable(["#", "任务"], jobs.map((job, i) => [i + 1, cell(job)]))}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export async function handleGenProps(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime);
|
||||
if (!resolved.entity) {
|
||||
throw new Error("请提供业务对象 ID、编码或名称: hose-use platform gen-props <应用> <业务对象> [--lang=mvel|js]");
|
||||
}
|
||||
|
||||
const lang = (stringOption(parsed.options, ["lang", "language"]) || "mvel").toLowerCase();
|
||||
const entity = resolved.entity;
|
||||
const entityId = entity.id;
|
||||
const entityName = entity.name;
|
||||
const prefix = entityId ? `${entityId}_` : "";
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
platform: resolved.platform,
|
||||
entity: {
|
||||
id: entity.id,
|
||||
name: entity.name,
|
||||
code: entity.code,
|
||||
prefix,
|
||||
fields: entity.fields.map((f) => ({
|
||||
fieldKey: f.name,
|
||||
label: f.label,
|
||||
type: f.type,
|
||||
suffix: f.name.startsWith(prefix) ? f.name.slice(prefix.length) : f.name,
|
||||
})),
|
||||
},
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const lines: string[] = [];
|
||||
if (lang === "js" || lang === "javascript") {
|
||||
lines.push(`// ====== 自建应用实体代码模板 [${entityName}] (JS / QuickJS) ======`);
|
||||
lines.push(`const ENTITY_ID = "${entityId}";`);
|
||||
lines.push(`const FIELD_PREFIX = "${prefix}";`);
|
||||
lines.push("");
|
||||
lines.push("// ── 字段物理键定义 ──");
|
||||
lines.push("const FIELDS = {");
|
||||
for (const f of entity.fields) {
|
||||
const suffix = f.name.startsWith(prefix) ? f.name.slice(prefix.length) : f.name;
|
||||
const safeLabel = f.label.replace(/"/g, '\\"');
|
||||
lines.push(` "${safeLabel}": FIELD_PREFIX + "${suffix}", // ${f.type || "text"}${f.optional === false ? " [必填]" : ""}`);
|
||||
}
|
||||
lines.push("};");
|
||||
lines.push("");
|
||||
lines.push("// ── 写入数据对象示例 ──");
|
||||
lines.push("const recordData = {");
|
||||
for (const f of entity.fields) {
|
||||
const safeLabel = f.label.replace(/"/g, '\\"');
|
||||
lines.push(` [FIELDS["${safeLabel}"]]: "", // ${f.label}`);
|
||||
}
|
||||
lines.push("};");
|
||||
} else {
|
||||
// 默认 MVEL 模板
|
||||
lines.push(`// ====== 自建应用实体代码模板 [${entityName}] (MVEL) ======`);
|
||||
lines.push(`String TARGET_ENTITY_ID = "${entityId}";`);
|
||||
lines.push(`String FIELD_PREFIX = "${prefix}";`);
|
||||
lines.push("");
|
||||
lines.push("// ── 物理字段键常量 ──");
|
||||
for (const f of entity.fields) {
|
||||
const suffix = f.name.startsWith(prefix) ? f.name.slice(prefix.length) : f.name;
|
||||
const constName = `FIELD_${f.label.replace(/[^a-zA-Z0-9_\u4e00-\u9fa5]/g, "_")}`;
|
||||
lines.push(`String ${constName} = FIELD_PREFIX + "${suffix}"; // ${f.label} (${f.type || "text"})${f.optional === false ? " [必填]" : ""}`);
|
||||
}
|
||||
lines.push("");
|
||||
lines.push("// ── DataLink 行构建模板 (row.put) ──");
|
||||
lines.push("Map row = new HashMap();");
|
||||
for (const f of entity.fields) {
|
||||
const constName = `FIELD_${f.label.replace(/[^a-zA-Z0-9_\u4e00-\u9fa5]/g, "_")}`;
|
||||
lines.push(`row.put(${constName}, ""); // ${f.label}`);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `${lines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { booleanOption } from "../../parser.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { handleList, handleGet, handleEntities, handleSchema, handlePermissions, handleImports } from "./app-info.js";
|
||||
import { handleList, handleGet, handleEntities, handleSchema, handlePermissions, handleImports, handleGenProps } from "./app-info.js";
|
||||
import { handleRecords, handleAudit } from "./records.js";
|
||||
import { handleRecordAction } from "./record-actions.js";
|
||||
|
||||
@@ -47,9 +47,12 @@ export async function handlePlatformCommand(parsed: CliParsedArgs, runtime: CliR
|
||||
case "permissions":
|
||||
case "permission":
|
||||
case "auth": return handlePermissions(parsed, runtime);
|
||||
case "gen-props":
|
||||
case "gen-mvel-props":
|
||||
case "props": return handleGenProps(parsed, runtime);
|
||||
case "imports":
|
||||
case "import-jobs": return handleImports(parsed, runtime);
|
||||
default:
|
||||
return { stdout: "", stderr: `未知 platform 子命令: ${action}。支持: list, get, entities, schema, records, audit, record, permissions, imports\n`, exitCode: 1 };
|
||||
return { stdout: "", stderr: `未知 platform 子命令: ${action}。支持: list, get, entities, schema, records, audit, record, gen-props, permissions, imports\n`, exitCode: 1 };
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
auditEntityRecords,
|
||||
auditLedgerContinuityAndBaseline,
|
||||
buildKeywordFilter,
|
||||
buildServerFieldFilter,
|
||||
calculateEntityRecordStats,
|
||||
fetchAllEntityRecords,
|
||||
compileRecordPredicate,
|
||||
@@ -12,6 +13,7 @@ import {
|
||||
searchEntityRecords,
|
||||
selectRecordFields,
|
||||
} from "../../../domains/datalink/services.js";
|
||||
import type { DatalinkRecord } from "../../../domains/datalink/types.js";
|
||||
import type { LedgerContinuityReport } from "../../../domains/datalink/types.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../../parser.js";
|
||||
import { printJson, printTable, printKeyValue, redactSensitiveText } from "../../printer.js";
|
||||
@@ -32,7 +34,17 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
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 searchFields = splitFields(
|
||||
stringOption(parsed.options, ["search-fields", "searchFields", "search-field", "searchField"])
|
||||
);
|
||||
const rawFilter = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]);
|
||||
let filterBy: string | undefined;
|
||||
if (rawFilter) {
|
||||
filterBy = buildServerFieldFilter(rawFilter, resolved.entity);
|
||||
} else if (keyword) {
|
||||
filterBy = buildKeywordFilter(keyword, { entity: resolved.entity, searchFields });
|
||||
}
|
||||
|
||||
const whereClause = stringOption(parsed.options, ["where"]);
|
||||
const predicate = whereClause ? compileRecordPredicate(whereClause, resolved.entity) : undefined;
|
||||
const sumOption = stringOption(parsed.options, ["sum", "aggregate"]);
|
||||
@@ -41,7 +53,7 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
const isFlat = booleanOption(parsed.options, ["flat", "normalize", "normalized"], false);
|
||||
const isAll = booleanOption(parsed.options, ["all", "a"], false);
|
||||
const groupBy = stringOption(parsed.options, ["group-by", "groupBy"]);
|
||||
const fetchAll = isAll || Boolean(whereClause || sumOption || isProfileStats);
|
||||
const fetchAll = isAll || Boolean(sumOption || isProfileStats);
|
||||
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);
|
||||
@@ -125,12 +137,36 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
return { stdout: lines.join("\n") + "\n", stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const page = fetchAll
|
||||
? await fetchAllEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { filterBy, pageSize })
|
||||
: await searchEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { start, count, filterBy });
|
||||
let data: DatalinkRecord[] = [];
|
||||
let total = 0;
|
||||
|
||||
let data = page.data;
|
||||
if (predicate) data = data.filter(predicate);
|
||||
if (fetchAll) {
|
||||
const page = await fetchAllEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { filterBy, pageSize });
|
||||
total = page.total;
|
||||
data = page.data;
|
||||
if (predicate) data = data.filter(predicate);
|
||||
} else if (predicate) {
|
||||
// 客户端谓词早退机制:一旦匹配到 count 条记录,立即停止拉取后续页面,杜绝无限制全量扫描
|
||||
let matched = 0;
|
||||
const targetLimit = count ?? 20;
|
||||
for await (const record of iterateAllEntityRecords(
|
||||
resolved.clients.ekbClient,
|
||||
resolved.corpId,
|
||||
resolved.entity.id,
|
||||
{ filterBy, pageSize }
|
||||
)) {
|
||||
total++;
|
||||
if (predicate(record)) {
|
||||
data.push(record);
|
||||
matched++;
|
||||
if (matched >= targetLimit) break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const page = await searchEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { start, count, filterBy });
|
||||
total = page.total;
|
||||
data = page.data;
|
||||
}
|
||||
|
||||
// 3. 数学聚合核算模式 (--sum="租赁费用,日折旧费")
|
||||
if (sumOption) {
|
||||
@@ -191,7 +227,7 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
platform: resolved.platform,
|
||||
entity: resolved.entity,
|
||||
query: { start: fetchAll ? 0 : start, count: fetchAll ? data.length : count, all: fetchAll, filterBy, where: whereClause, fields, flat: isFlat },
|
||||
total: page.total,
|
||||
total: total || data.length,
|
||||
returned: data.length,
|
||||
data,
|
||||
};
|
||||
@@ -209,7 +245,7 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
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}${fetchAll ? ", 全量导出" : ""}) ======\n${printTable(["#", "记录 ID", "名称", "编码", "状态", "更新时间"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
return { stdout: `====== [${resolved.platform.name}] ${resolved.entity.name} 记录 (总数: ${total || data.length}, 当前: ${data.length}${fetchAll ? ", 全量导出" : ""}) ======\n${printTable(["#", "记录 ID", "名称", "编码", "状态", "更新时间"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ export async function handleProbeCommand(
|
||||
env: currentCorp.env,
|
||||
isTest: currentCorp.isTest,
|
||||
staffId: currentCorp.credentials.staffId,
|
||||
staffName: currentCorp.staffName || currentCorp.session?.staffName,
|
||||
baseUrl: currentCorp.baseUrl,
|
||||
source: currentCorp.source,
|
||||
accountId: currentCorp.accountId,
|
||||
@@ -52,6 +53,35 @@ export async function handleProbeCommand(
|
||||
loginStaffId: sessionRes.value?.loginStaffId,
|
||||
expTime: sessionRes.value?.expTime ? new Date(sessionRes.value.expTime).toLocaleString() : undefined,
|
||||
};
|
||||
|
||||
// 自愈补全员工姓名 (Self-Healing Profile Hydration)
|
||||
if (!currentCorp.staffName && !currentCorp.session?.staffName) {
|
||||
if (hasOpenApi && currentCorp.credentials.appKey && currentCorp.credentials.appSecurity && currentCorp.credentials.staffId) {
|
||||
try {
|
||||
const { fetchHoseOpenApiAccessToken, fetchHoseStaffDetails } = await import("../../core/auth/openapi-v1.js");
|
||||
const openapiToken = await fetchHoseOpenApiAccessToken({
|
||||
baseUrl: currentCorp.baseUrl,
|
||||
appKey: currentCorp.credentials.appKey,
|
||||
appSecurity: currentCorp.credentials.appSecurity,
|
||||
});
|
||||
const details = await fetchHoseStaffDetails(currentCorp.baseUrl || "https://app.ekuaibao.com", openapiToken, [currentCorp.credentials.staffId]);
|
||||
if (details[0]?.name) {
|
||||
currentCorp.staffName = details[0].name;
|
||||
if (!currentCorp.session) {
|
||||
currentCorp.session = { staffName: details[0].name } as any;
|
||||
} else {
|
||||
currentCorp.session.staffName = details[0].name;
|
||||
}
|
||||
if (details[0].cellphone && currentCorp.session) {
|
||||
currentCorp.session.cellphone = details[0].cellphone;
|
||||
}
|
||||
(results.enterprise as any).staffName = details[0].name;
|
||||
const { saveCorpConfig } = await import("../../core/config/loader.js");
|
||||
saveCorpConfig(currentCorp);
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
results.ekbSession = {
|
||||
status: "error",
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { expect, spyOn, test } from "bun:test";
|
||||
import * as service from "../service.js";
|
||||
import { parseArgs } from "../parser.js";
|
||||
import { handleServiceCommand } from "./service.js";
|
||||
test("service lifecycle previews never dispatch process or state mutations", async () => {
|
||||
const dispatch = spyOn(service, "runServiceCommand").mockResolvedValue({ running: false } as any);
|
||||
try {
|
||||
for (const action of ["start", "stop", "restart", "run"]) {
|
||||
const result = await handleServiceCommand(parseArgs(["service", action, "--dry-run", "--yes"]), { jsonMode: true } as any);
|
||||
expect(JSON.parse(result.stdout).dryRun).toBe(true);
|
||||
expect(JSON.parse(result.stdout).changes.action).toBe(action);
|
||||
}
|
||||
expect(dispatch).not.toHaveBeenCalled();
|
||||
await handleServiceCommand(parseArgs(["service", "status"]), { jsonMode: true } as any);
|
||||
expect(dispatch).toHaveBeenCalledTimes(1);
|
||||
} finally { dispatch.mockRestore(); }
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isDryRun, mutationPreview } from "../mutation.js";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { VERSION } from "../../version.js";
|
||||
@@ -42,6 +43,9 @@ export async function handleServiceCommand(
|
||||
host,
|
||||
};
|
||||
|
||||
if (["start", "stop", "restart", "run"].includes(action) && isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "管理 hose-use 服务", action, { action, port, host, stateDir: config.stateDir });
|
||||
}
|
||||
const result = await runServiceCommand(action, config);
|
||||
|
||||
if (result === undefined) {
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { expect, spyOn, test } from "bun:test";
|
||||
import * as cp from "node:child_process";
|
||||
import * as packaging from "../../../packaging/runtime.js";
|
||||
import * as skill from "../../../packaging/embedded-skill.js";
|
||||
import { parseArgs } from "../../parser.js";
|
||||
import { handleUpdateCommand } from "./index.js";
|
||||
|
||||
test("source and binary update previews do not fetch, spawn or install skills", async () => {
|
||||
const spawn = spyOn(cp, "spawnSync").mockImplementation(() => { throw new Error("unexpected spawn"); });
|
||||
const sync = spyOn(skill, "syncGlobalSkillIfPresent").mockImplementation(() => { throw new Error("unexpected install"); });
|
||||
const compiled = spyOn(packaging, "isCompiledBinary");
|
||||
const oldFetch = globalThis.fetch; let requests = 0;
|
||||
globalThis.fetch = (async () => { requests++; throw new Error("unexpected fetch"); }) as any;
|
||||
try {
|
||||
for (const binary of [false, true]) {
|
||||
compiled.mockReturnValue(binary);
|
||||
const result = await handleUpdateCommand(parseArgs(["update", "--dry-run"]), { jsonMode: true } as any, { appRoot: "/tmp/update-preview" });
|
||||
const preview = JSON.parse(result.stdout);
|
||||
expect(preview.dryRun).toBe(true);
|
||||
expect(preview.changes.mode).toBe(binary ? "binary" : "source");
|
||||
expect(result.exitCode).toBe(0);
|
||||
}
|
||||
expect(requests).toBe(0); expect(spawn).not.toHaveBeenCalled(); expect(sync).not.toHaveBeenCalled();
|
||||
} finally { globalThis.fetch = oldFetch; spawn.mockRestore(); sync.mockRestore(); compiled.mockRestore(); }
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isDryRun, mutationPreview } from "../../mutation.js";
|
||||
import { chmodSync, existsSync, mkdirSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
@@ -180,6 +181,13 @@ export async function handleUpdateCommand(
|
||||
}
|
||||
}
|
||||
|
||||
if (!options.checkOnly && !options.changelogOnly && isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "更新 hose-use", appRoot, {
|
||||
mode: isCompiledBinary() ? "binary" : "source",
|
||||
version: targetVersion || "latest", repo, sourcePreference, force: options.force,
|
||||
});
|
||||
}
|
||||
|
||||
// 1. Changelog / Release History query
|
||||
if (options.changelogOnly) {
|
||||
const releases = await fetchGitHubReleases(repo, options.limit ?? 10, options.sourcePreference);
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { expect, spyOn, test } from "bun:test";
|
||||
import { parseArgs } from "../parser.js";
|
||||
import { handleWorkflowCommand } from "./workflow/index.js";
|
||||
import * as services from "../../domains/platform/services.js";
|
||||
|
||||
test("node grant previews without a gateway call and requires explicit confirmation", async () => {
|
||||
const runtime = { selectedCorp: { id: "corp", credentials: { corpId: "corp" } }, jsonMode: true } as any;
|
||||
const grant = spyOn(services, "grantWorkflowNodes").mockResolvedValue({ success: true, saved: ["code-js2"], skipped: [], rawMessage: "ok" });
|
||||
try {
|
||||
await expect(handleWorkflowCommand(parseArgs(["workflow", "nodes", "grant", "code-js2"]), runtime)).rejects.toThrow("--yes");
|
||||
const result = await handleWorkflowCommand(parseArgs(["workflow", "nodes", "grant", "JS节点(新)", "--dry-run", "--yes"]), runtime);
|
||||
expect(JSON.parse(result.stdout).dryRun).toBe(true);
|
||||
expect(JSON.parse(result.stdout).changes.nodes).toEqual(["code-js2"]);
|
||||
expect(grant).not.toHaveBeenCalled();
|
||||
await handleWorkflowCommand(parseArgs(["workflow", "nodes", "grant", "code-js2", "--confirm"]), runtime);
|
||||
expect(grant).toHaveBeenCalledTimes(1);
|
||||
} finally { grant.mockRestore(); }
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import { expect, spyOn, test } from "bun:test";
|
||||
import { handleWorkflowCommand } from "./workflow/index.js";
|
||||
import { parseArgs } from "../parser.js";
|
||||
import * as services from "../../domains/platform/services.js";
|
||||
test("failed grants retain gateway details and never report success", async () => {
|
||||
const grant = spyOn(services, "grantWorkflowNodes").mockResolvedValue({ success: false, saved: [], skipped: [], rawMessage: "permission denied" });
|
||||
try {
|
||||
for (const jsonMode of [false, true]) {
|
||||
const result = await handleWorkflowCommand(parseArgs(["workflow", "nodes", "grant", "code-js2", "--yes"]), { selectedCorp: { id: "corp", name: "test" }, jsonMode } as any);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stdout).not.toContain("节点权限已生效");
|
||||
if (jsonMode) expect(JSON.parse(result.stdout)).toMatchObject({ success: false, rawMessage: "permission denied" });
|
||||
else expect(result.stderr).toContain("permission denied");
|
||||
}
|
||||
} finally { grant.mockRestore(); }
|
||||
});
|
||||
@@ -0,0 +1,289 @@
|
||||
import { describe, expect, it, spyOn, afterEach } from "bun:test";
|
||||
import { handleWorkflowCommand } from "./workflow/index.js";
|
||||
import * as services from "../../domains/platform/services.js";
|
||||
import * as api from "../../domains/platform/api.js";
|
||||
import * as helpers from "../helpers.js";
|
||||
import type { CliRuntime } from "../types.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
|
||||
const mockCorp: CorpConfig = {
|
||||
id: "ID01rJEL708iTI",
|
||||
name: "浙江麦瑞克科技有限公司",
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
source: "openapi",
|
||||
credentials: {
|
||||
accessToken: "mock-access-token",
|
||||
corpId: "ID01rJEL708iTI",
|
||||
staffId: "ID01rJEL708iTI:RkQ8G8L_eMhI00",
|
||||
appKey: "test-key",
|
||||
appSecurity: "test-security",
|
||||
},
|
||||
};
|
||||
|
||||
const mockRuntime: CliRuntime = {
|
||||
corpContext: {
|
||||
listCorps: () => [mockCorp],
|
||||
getCurrent: () => mockCorp,
|
||||
switchCorp: () => true,
|
||||
resolve: () => mockCorp,
|
||||
} as any,
|
||||
selectedCorp: mockCorp,
|
||||
jsonMode: false,
|
||||
outputOptions: {},
|
||||
};
|
||||
|
||||
describe("CLI - workflow nodes 字典探针与灰度开通测试", () => {
|
||||
let spies: ReturnType<typeof spyOn>[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const spy of spies) {
|
||||
spy.mockRestore();
|
||||
}
|
||||
spies = [];
|
||||
delete process.env.HOSE_ADMIN_PASSWORD;
|
||||
});
|
||||
|
||||
it("workflow nodes: 成功探查当前企业已开通节点字典", async () => {
|
||||
spies.push(
|
||||
spyOn(helpers, "createPiperClientForCorp").mockResolvedValue({} as any),
|
||||
spyOn(services, "getWorkflowAvailableNodes").mockResolvedValue({
|
||||
allTypes: new Set(["http", "code", "condition", "clock"]),
|
||||
actionNodes: [
|
||||
{ name: "http节点", type: "http" },
|
||||
{ name: "代码节点", type: "code" },
|
||||
],
|
||||
controlNodes: [{ name: "条件节点", type: "condition" }],
|
||||
triggerNodes: [{ name: "定时触发", type: "clock" }],
|
||||
})
|
||||
);
|
||||
|
||||
const res = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "nodes",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["workflow", "nodes"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("当前企业已开通工作流节点字典 [浙江麦瑞克科技有限公司]");
|
||||
expect(res.stdout).toContain("代码节点 (code)");
|
||||
expect(res.stdout).toContain("已开通节点数");
|
||||
});
|
||||
|
||||
it("workflow nodes --all: 成功输出与 108 个灰度节点对照表", async () => {
|
||||
spies.push(
|
||||
spyOn(helpers, "createPiperClientForCorp").mockResolvedValue({} as any),
|
||||
spyOn(services, "getWorkflowAvailableNodes").mockResolvedValue({
|
||||
allTypes: new Set(["code", "http"]),
|
||||
actionNodes: [{ name: "代码节点", type: "code" }],
|
||||
controlNodes: [],
|
||||
triggerNodes: [],
|
||||
})
|
||||
);
|
||||
|
||||
const res = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "nodes",
|
||||
args: [],
|
||||
options: { all: true },
|
||||
raw: ["workflow", "nodes", "--all"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("工作流节点字典与灰度开通对照 [浙江麦瑞克科技有限公司]");
|
||||
expect(res.stdout).toContain("code-js2");
|
||||
expect(res.stdout).toContain("🔒 未开通");
|
||||
expect(res.stdout).toContain("✅ 已开通");
|
||||
});
|
||||
|
||||
it("workflow nodes --json: 输出机器可读的结构化 JSON", async () => {
|
||||
spies.push(
|
||||
spyOn(helpers, "createPiperClientForCorp").mockResolvedValue({} as any),
|
||||
spyOn(services, "getWorkflowAvailableNodes").mockResolvedValue({
|
||||
allTypes: new Set(["code"]),
|
||||
actionNodes: [{ name: "代码节点", type: "code" }],
|
||||
controlNodes: [],
|
||||
triggerNodes: [],
|
||||
})
|
||||
);
|
||||
|
||||
const jsonRuntime: CliRuntime = { ...mockRuntime, jsonMode: true };
|
||||
const res = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "nodes",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["workflow", "nodes", "--json"],
|
||||
},
|
||||
jsonRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
const parsedJson = JSON.parse(res.stdout);
|
||||
expect(parsedJson.corpId).toBe("ID01rJEL708iTI");
|
||||
expect(parsedJson.totalGranted).toBe(1);
|
||||
expect(parsedJson.grantedTypes).toContain("code");
|
||||
});
|
||||
|
||||
it("workflow nodes grant: 免密模式下成功发起灰度节点开通", async () => {
|
||||
const grantSpy = spyOn(api, "grantWorkflowNodesApi").mockResolvedValue({
|
||||
success: true,
|
||||
saved: ["code-js2"],
|
||||
skipped: [],
|
||||
rawMessage: "新开通的节点:code-js2",
|
||||
});
|
||||
spies.push(grantSpy);
|
||||
|
||||
const res = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "nodes",
|
||||
args: ["grant", "code-js2"],
|
||||
options: { yes: true },
|
||||
raw: ["workflow", "nodes", "grant", "code-js2"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("灰度节点开通结果 [浙江麦瑞克科技有限公司]");
|
||||
expect(res.stdout).toContain("新开通成功");
|
||||
expect(res.stdout).toContain("code-js2");
|
||||
expect(grantSpy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
nodes: ["code-js2"],
|
||||
token: "mock-access-token",
|
||||
corpId: "ID01rJEL708iTI",
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("workflow nodes grant: 节点名称自动中文归一化 (如 'JS节点(新)' 映射为 'code-js2')", async () => {
|
||||
const grantSpy = spyOn(api, "grantWorkflowNodesApi").mockResolvedValue({
|
||||
success: true,
|
||||
saved: ["code-js2"],
|
||||
skipped: [],
|
||||
rawMessage: "新开通的节点:code-js2",
|
||||
});
|
||||
spies.push(grantSpy);
|
||||
|
||||
const res = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "nodes",
|
||||
args: ["grant", "JS节点(新)"],
|
||||
options: { yes: true },
|
||||
raw: ["workflow", "nodes", "grant", "JS节点(新)"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(grantSpy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
nodes: ["code-js2"],
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("workflow nodes grant: 管理员密码保护预留生效 (未提供密码或密码错误被拒绝)", async () => {
|
||||
process.env.HOSE_ADMIN_PASSWORD = "secret_admin_pass";
|
||||
|
||||
// 1. 无密码调用被拒绝
|
||||
expect(
|
||||
services.grantWorkflowNodes(mockCorp, {
|
||||
nodes: ["code-js2"],
|
||||
})
|
||||
).rejects.toThrow("管理员保护");
|
||||
|
||||
// 2. 错误密码调用被拒绝
|
||||
expect(
|
||||
services.grantWorkflowNodes(mockCorp, {
|
||||
nodes: ["code-js2"],
|
||||
password: "wrong_password",
|
||||
})
|
||||
).rejects.toThrow("管理员保护");
|
||||
|
||||
// 3. 正确密码调用放行
|
||||
const grantSpy = spyOn(api, "grantWorkflowNodesApi").mockResolvedValue({
|
||||
success: true,
|
||||
saved: ["code-js2"],
|
||||
skipped: [],
|
||||
rawMessage: "开通成功",
|
||||
});
|
||||
spies.push(grantSpy);
|
||||
|
||||
const result = await services.grantWorkflowNodes(mockCorp, {
|
||||
nodes: ["code-js2"],
|
||||
password: "secret_admin_pass",
|
||||
});
|
||||
expect(result.success).toBe(true);
|
||||
expect(grantSpy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("workflow analyze: 显式输出硬门禁与软建议边界,且支持 --fail 退出码门禁", async () => {
|
||||
spies.push(
|
||||
spyOn(helpers, "createClientsForCorp").mockResolvedValue({
|
||||
ekbClient: {},
|
||||
easoClient: {},
|
||||
} as any),
|
||||
spyOn(helpers, "createPiperClientForCorp").mockResolvedValue({} as any),
|
||||
spyOn(services, "getWorkflowDetail").mockResolvedValue({
|
||||
id: "wf-gate-test",
|
||||
label: "门禁测试流程",
|
||||
state: 0,
|
||||
version: "1",
|
||||
tasks: [
|
||||
{
|
||||
name: "bad_node",
|
||||
type: "code-js2",
|
||||
label: "未开通JS2节点",
|
||||
code: "return 1;",
|
||||
},
|
||||
],
|
||||
} as any),
|
||||
spyOn(services, "getWorkflowAvailableNodes").mockResolvedValue({
|
||||
allTypes: new Set(["http", "code"]),
|
||||
catalog: { action: [], control: [], trigger: [] },
|
||||
} as any)
|
||||
);
|
||||
|
||||
// 1. 常规运行(无 --fail):展示门禁裁决,exitCode 为 0
|
||||
const normalRes = await handleWorkflowCommand(
|
||||
{
|
||||
action: "analyze",
|
||||
args: ["wf-gate-test"],
|
||||
options: {},
|
||||
raw: ["workflow", "analyze", "wf-gate-test"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
expect(normalRes.exitCode).toBe(0);
|
||||
expect(normalRes.stdout).toContain("门禁裁决");
|
||||
expect(normalRes.stdout).toContain("硬门禁数");
|
||||
expect(normalRes.stdout).toContain("软建议数");
|
||||
expect(normalRes.stdout).toContain("⛔ 硬门禁");
|
||||
expect(normalRes.stdout).toContain("💡 软建议");
|
||||
expect(normalRes.stdout).toContain("PERMISSION_MISSING_NODE");
|
||||
|
||||
// 2. 带 --fail 运行:检测到硬门禁,exitCode 为 2
|
||||
const failRes = await handleWorkflowCommand(
|
||||
{
|
||||
action: "analyze",
|
||||
args: ["wf-gate-test"],
|
||||
options: { fail: true },
|
||||
raw: ["workflow", "analyze", "wf-gate-test", "--fail"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
expect(failRes.exitCode).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it, spyOn, afterEach } from "bun:test";
|
||||
import { handleWorkflowCommand } from "./workflow/index.js";
|
||||
import * as helpers from "../helpers.js";
|
||||
import * as platformServices from "../../domains/platform/services.js";
|
||||
import type { CliRuntime } from "../types.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
|
||||
@@ -1655,6 +1656,42 @@ describe("CLI - workflow job 执行详情与异常精准透视", () => {
|
||||
expect(editRes.exitCode).toBe(0);
|
||||
expect(editRes.stdout).toContain("修改已保存至工作流");
|
||||
|
||||
// 5.1 node map
|
||||
const mapRes = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "node",
|
||||
args: ["map", "pipe_node_test", "action_js_1"],
|
||||
options: { yes: true },
|
||||
raw: ["workflow", "node", "map", "pipe_node_test", "action_js_1", "--yes"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
expect(mapRes.exitCode).toBe(1);
|
||||
expect(mapRes.stderr).toContain("请通过 --mapping-file=<路径> 指定");
|
||||
|
||||
const tmpMappingFile = (await import("os")).tmpdir() + "/test-fields-" + Date.now() + ".json";
|
||||
await (await import("fs/promises")).writeFile(
|
||||
tmpMappingFile,
|
||||
JSON.stringify([{ name: "test_field", label: "测试字段", value: "test_val" }]),
|
||||
"utf-8"
|
||||
);
|
||||
|
||||
const mapSuccessRes = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "node",
|
||||
args: ["map", "pipe_node_test", "action_js_1"],
|
||||
options: { "mapping-file": tmpMappingFile, yes: true },
|
||||
raw: ["workflow", "node", "map", "pipe_node_test", "action_js_1", `--mapping-file=${tmpMappingFile}`, "--yes"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
expect(mapSuccessRes.exitCode).toBe(0);
|
||||
expect(mapSuccessRes.stdout).toContain("已批量应用映射");
|
||||
|
||||
await (await import("fs/promises")).unlink(tmpMappingFile).catch(() => {});
|
||||
|
||||
// 6. node rm
|
||||
const rmRes = await handleWorkflowCommand(
|
||||
{
|
||||
@@ -1989,5 +2026,307 @@ describe("CLI - workflow job 执行详情与异常精准透视", () => {
|
||||
expect(wfEvalRes.stdout).toContain("执行成功 ✅");
|
||||
expect(wfEvalRes.stdout).toContain('"total": 100');
|
||||
});
|
||||
|
||||
it("workflow logs correctly detects and formats running/delayed jobs and in-progress count", async () => {
|
||||
const mockDetail = {
|
||||
id: "pipe_delay_test",
|
||||
pipelineName: "审批延时测试流程",
|
||||
state: 1,
|
||||
tasks: [
|
||||
{ name: "trigger_1", type: "clock", label: "定时触发" },
|
||||
{ name: "action_delay_1", type: "task-dynamic-delay", label: "延时等待节点", sleepTime: 60 },
|
||||
{ name: "action_js_1", type: "code-js2", label: "通知节点" },
|
||||
],
|
||||
};
|
||||
|
||||
const mockLogs = {
|
||||
executeCount: 3,
|
||||
successCount: 2,
|
||||
errorCount: 0,
|
||||
number: 1,
|
||||
size: 10,
|
||||
totalPages: 1,
|
||||
totalItems: 3,
|
||||
jobList: [
|
||||
{
|
||||
state: 0,
|
||||
jobName: "审批延时测试流程",
|
||||
jobId: "job_running_001",
|
||||
executeTime: "2026-10-21 17:15:00",
|
||||
status: "STARTED",
|
||||
runType: "DEBUG",
|
||||
successTaskCount: 1,
|
||||
errorTaskCount: 0,
|
||||
hasError: "不存在",
|
||||
},
|
||||
{
|
||||
state: 0,
|
||||
jobName: "审批延时测试流程",
|
||||
jobId: "job_completed_002",
|
||||
executeTime: "2026-10-21 17:10:00",
|
||||
status: "COMPLETED",
|
||||
runType: "DEBUG",
|
||||
successTaskCount: 3,
|
||||
errorTaskCount: 0,
|
||||
hasError: "不存在",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const mockClient = {
|
||||
get: (url: string) => ({
|
||||
json: async () => {
|
||||
if (url.includes("/log")) return { code: 200, data: mockLogs };
|
||||
return { code: 200, data: mockDetail };
|
||||
},
|
||||
}),
|
||||
};
|
||||
|
||||
spies.push(
|
||||
spyOn(helpers, "createClientsForCorp").mockResolvedValue({
|
||||
ekbClient: mockClient as any,
|
||||
easoClient: mockClient as any,
|
||||
corp: mockCorp,
|
||||
} as any)
|
||||
);
|
||||
spies.push(spyOn(helpers, "createPiperClientForCorp").mockResolvedValue(mockClient as any));
|
||||
|
||||
// 1. All logs view
|
||||
const allLogsRes = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "logs",
|
||||
args: ["pipe_delay_test"],
|
||||
options: {},
|
||||
raw: ["workflow", "logs", "pipe_delay_test"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
expect(allLogsRes.exitCode).toBe(0);
|
||||
expect(allLogsRes.stdout).toContain("运行中/延时");
|
||||
expect(allLogsRes.stdout).toContain("1 (正在执行或延时等待中)");
|
||||
expect(allLogsRes.stdout).toContain("⏳ 运行中");
|
||||
expect(allLogsRes.stdout).toContain("✅ 已完成");
|
||||
expect(allLogsRes.stdout).toContain("⏳ 执行中");
|
||||
|
||||
// 2. Client-side filtering by --state=RUNNING
|
||||
const runningOnlyRes = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "logs",
|
||||
args: ["pipe_delay_test"],
|
||||
options: { state: "RUNNING" },
|
||||
raw: ["workflow", "logs", "pipe_delay_test", "--state=RUNNING"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
expect(runningOnlyRes.exitCode).toBe(0);
|
||||
expect(runningOnlyRes.stdout).toContain("job_running_001");
|
||||
expect(runningOnlyRes.stdout).not.toContain("job_completed_002");
|
||||
});
|
||||
|
||||
it("workflow job correctly displays mid-flight delayed job progress and non-interruptive hints", async () => {
|
||||
const mockDetail = {
|
||||
id: "pipe_delay_test",
|
||||
pipelineName: "审批延时测试流程",
|
||||
state: 1,
|
||||
tasks: [
|
||||
{ name: "trigger_1", type: "clock", label: "定时触发" },
|
||||
{ name: "action_delay_1", type: "task-dynamic-delay", label: "延时等待节点", sleepTime: 60 },
|
||||
{ name: "action_js_1", type: "code-js2", label: "通知节点" },
|
||||
],
|
||||
};
|
||||
|
||||
const mockRunningJob = {
|
||||
id: "job_running_001",
|
||||
pipelineId: "pipe_delay_test",
|
||||
status: "STARTED",
|
||||
state: 0,
|
||||
startTime: 1792574000000,
|
||||
};
|
||||
|
||||
const mockExecutionTree = [
|
||||
{ id: "exec_1", name: "trigger_1", label: "定时触发", type: "clock", status: "COMPLETED", durationTime: 10 },
|
||||
{ id: "exec_2", name: "action_delay_1", label: "延时等待节点", type: "task-dynamic-delay", status: "STARTED" },
|
||||
];
|
||||
|
||||
const mockClient = {
|
||||
get: (url: string) => ({
|
||||
json: async () => {
|
||||
if (url.includes("/execution")) return { code: 200, data: mockExecutionTree };
|
||||
if (url.includes("/failed")) return { code: 200, data: { items: [] } };
|
||||
if (url.includes("/jobs/job_running_001")) return { code: 200, data: mockRunningJob };
|
||||
return { code: 200, data: mockDetail };
|
||||
},
|
||||
}),
|
||||
};
|
||||
|
||||
spies.push(
|
||||
spyOn(helpers, "createClientsForCorp").mockResolvedValue({
|
||||
ekbClient: mockClient as any,
|
||||
easoClient: mockClient as any,
|
||||
corp: mockCorp,
|
||||
} as any)
|
||||
);
|
||||
spies.push(spyOn(helpers, "createPiperClientForCorp").mockResolvedValue(mockClient as any));
|
||||
|
||||
// 1. Overview view
|
||||
const jobRes = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "job",
|
||||
args: ["job_running_001"],
|
||||
options: {},
|
||||
raw: ["workflow", "job", "job_running_001"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
expect(jobRes.exitCode).toBe(0);
|
||||
expect(jobRes.stdout).toContain("⏳ 运行中 (STARTED)");
|
||||
expect(jobRes.stdout).toContain("当前正在执行第 2 步(延时等待中或任务处理中)");
|
||||
expect(jobRes.stdout).not.toContain("本次调度在第 2 步中断");
|
||||
expect(jobRes.stdout).toContain("⏳ 延时等待中");
|
||||
|
||||
// 2. Timeline view
|
||||
const timelineRes = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "job",
|
||||
args: ["job_running_001"],
|
||||
options: { timeline: true },
|
||||
raw: ["workflow", "job", "job_running_001", "--timeline"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
expect(timelineRes.exitCode).toBe(0);
|
||||
expect(timelineRes.stdout).toContain("✅ 已完成");
|
||||
expect(timelineRes.stdout).toContain("⏳ 延时等待中");
|
||||
expect(timelineRes.stdout).toContain("⏳ 等待前序步骤执行完成");
|
||||
expect(timelineRes.stdout).not.toContain("因前序步骤中断");
|
||||
});
|
||||
});
|
||||
|
||||
describe("CLI - workflow list 轻量化与名称搜索", () => {
|
||||
let spies: ReturnType<typeof spyOn>[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const spy of spies) {
|
||||
spy.mockRestore();
|
||||
}
|
||||
spies = [];
|
||||
});
|
||||
|
||||
const mockWorkflows = [
|
||||
{
|
||||
id: "wf_001",
|
||||
pipelineName: "待摊台账拆分计划",
|
||||
state: 1,
|
||||
runningCount: 0,
|
||||
errorCount: 0,
|
||||
updateTime: "2026-08-26 23:31:04",
|
||||
updateUser: "张三",
|
||||
platformId: "p_1",
|
||||
platformName: "合同台账",
|
||||
tasks: [
|
||||
{ name: "t1", type: "trigger", code: "long script 1..." },
|
||||
{ name: "t2", type: "code", code: "long script 2..." },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "wf_002",
|
||||
pipelineName: "费用报销审批同步",
|
||||
state: 0,
|
||||
runningCount: 0,
|
||||
errorCount: 0,
|
||||
updateTime: "2026-09-01 10:00:00",
|
||||
updateUser: "李四",
|
||||
platformId: "p_2",
|
||||
platformName: "费用应用",
|
||||
tasks: [{ name: "t1", type: "trigger", code: "long script 3..." }],
|
||||
},
|
||||
];
|
||||
|
||||
it("默认以轻量化模式输出 JSON,剥离庞大的 tasks 数组并提供 nodeCount", async () => {
|
||||
spies.push(
|
||||
spyOn(helpers, "createClientsForCorp").mockResolvedValue({} as any),
|
||||
spyOn(platformServices, "listAllWorkflows").mockResolvedValue({
|
||||
workflows: mockWorkflows as any,
|
||||
errors: [],
|
||||
})
|
||||
);
|
||||
|
||||
const res = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "list",
|
||||
args: [],
|
||||
options: { json: true },
|
||||
raw: ["workflow", "list", "--json"],
|
||||
},
|
||||
{ ...mockRuntime, jsonMode: true }
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
const data = JSON.parse(res.stdout);
|
||||
expect(data.workflows).toHaveLength(2);
|
||||
expect(data.workflows[0].tasks).toBeUndefined();
|
||||
expect(data.workflows[0].nodeCount).toBe(2);
|
||||
expect(data.workflows[1].nodeCount).toBe(1);
|
||||
expect(data.totalWorkflows).toBe(2);
|
||||
});
|
||||
|
||||
it("传入 --full 或 --with-tasks 时保留完整的 tasks 节点结构", async () => {
|
||||
spies.push(
|
||||
spyOn(helpers, "createClientsForCorp").mockResolvedValue({} as any),
|
||||
spyOn(platformServices, "listAllWorkflows").mockResolvedValue({
|
||||
workflows: mockWorkflows as any,
|
||||
errors: [],
|
||||
})
|
||||
);
|
||||
|
||||
const res = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "list",
|
||||
args: [],
|
||||
options: { json: true, full: true },
|
||||
raw: ["workflow", "list", "--json", "--full"],
|
||||
},
|
||||
{ ...mockRuntime, jsonMode: true }
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
const data = JSON.parse(res.stdout);
|
||||
expect(data.workflows[0].tasks).toHaveLength(2);
|
||||
expect(data.workflows[0].tasks[0].code).toBe("long script 1...");
|
||||
});
|
||||
|
||||
it("支持通过 --keyword 或 -q 过滤工作流名称", async () => {
|
||||
spies.push(
|
||||
spyOn(helpers, "createClientsForCorp").mockResolvedValue({} as any),
|
||||
spyOn(platformServices, "listAllWorkflows").mockResolvedValue({
|
||||
workflows: mockWorkflows as any,
|
||||
errors: [],
|
||||
})
|
||||
);
|
||||
|
||||
const res = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "list",
|
||||
args: [],
|
||||
options: { keyword: "待摊", json: true },
|
||||
raw: ["workflow", "list", "--keyword=待摊", "--json"],
|
||||
},
|
||||
{ ...mockRuntime, jsonMode: true }
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
const data = JSON.parse(res.stdout);
|
||||
expect(data.workflows).toHaveLength(1);
|
||||
expect(data.workflows[0].id).toBe("wf_001");
|
||||
expect(data.workflows[0].pipelineName).toBe("待摊台账拆分计划");
|
||||
expect(data.totalWorkflows).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { isClientGoodOpened } from "./analyze.js";
|
||||
|
||||
describe("workflow analyze enterprise application status", () => {
|
||||
it("uses the enterprise opening status and ignores marketplace online status", () => {
|
||||
expect(isClientGoodOpened({ status: "OPENED", onLineStatus: "OFFLINE" })).toBe(true);
|
||||
expect(isClientGoodOpened({ status: "EXPIRE", onLineStatus: "ONLINE" })).toBe(false);
|
||||
expect(isClientGoodOpened({ status: "CLOSED", onLineStatus: "ONLINE" })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,15 +1,19 @@
|
||||
import { getWorkflowDetail } from "../../../domains/platform/services.js";
|
||||
import { getWorkflowDetail, getWorkflowAvailableNodes } from "../../../domains/platform/services.js";
|
||||
import {
|
||||
analyzeWorkflow,
|
||||
extractWorkflowSpecificationIds,
|
||||
type WorkflowFormSpecLike,
|
||||
} from "../../../domains/platform/workflow/analysis/index.js";
|
||||
import { getFormSpecification } from "../../../domains/bill/tools.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { stringOption, booleanOption } from "../../parser.js";
|
||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { createWorkflowDetailClient } from "./shared.js";
|
||||
|
||||
export function isClientGoodOpened(item: { status?: string | null; onLineStatus?: string | null }): boolean {
|
||||
return item.status?.toUpperCase() === "OPENED";
|
||||
}
|
||||
|
||||
export 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 };
|
||||
@@ -30,20 +34,75 @@ export async function handleAnalyze(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
})
|
||||
);
|
||||
}
|
||||
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]);
|
||||
let availableNodeTypes: Set<string> | undefined;
|
||||
try {
|
||||
const available = await getWorkflowAvailableNodes(client);
|
||||
availableNodeTypes = available.allTypes;
|
||||
} catch {
|
||||
// 离线或受限网络环境下忽略探针失败
|
||||
}
|
||||
|
||||
let openedPowerCodes: Set<string> | undefined;
|
||||
try {
|
||||
const { fetchClientGoods } = await import("../../../domains/store/tools.js");
|
||||
const goods = await fetchClientGoods(runtime.selectedCorp!, { isAll: true });
|
||||
const codes = new Set<string>();
|
||||
for (const item of goods) {
|
||||
const isOpened = isClientGoodOpened(item);
|
||||
if (isOpened && Array.isArray(item.powers)) {
|
||||
for (const power of item.powers) {
|
||||
if (typeof power === "string") {
|
||||
codes.add(power.toLowerCase());
|
||||
} else if (power && typeof power === "object" && power.powerCode) {
|
||||
codes.add(power.powerCode.toLowerCase());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
openedPowerCodes = codes;
|
||||
} catch {
|
||||
// 离线或无商店应用查询权限时忽略
|
||||
}
|
||||
|
||||
const result = analyzeWorkflow(detail, { specifications, availableNodeTypes, openedPowerCodes });
|
||||
const failOnAlert = booleanOption(parsed.options, ["fail", "fail-on-alert", "failOnAlert"]);
|
||||
const exitCode = failOnAlert && !result.summary.passed ? 2 : 0;
|
||||
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode };
|
||||
|
||||
const gateDecision =
|
||||
result.summary.hardBlocks > 0
|
||||
? `❌ 发现 ${result.summary.hardBlocks} 项硬门禁阻断 (禁止发布上线)`
|
||||
: result.summary.softAdvices > 0
|
||||
? `⚠️ 硬门禁全通过,存在 ${result.summary.softAdvices} 项优化建议`
|
||||
: "✅ 全部门禁通过,可安全发布上线";
|
||||
|
||||
const diagnosticRows = result.diagnostics.map((item) => [
|
||||
item.category === "hard_block" ? "⛔ 硬门禁" : "💡 软建议",
|
||||
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,
|
||||
"状态": 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 };
|
||||
|
||||
return {
|
||||
stdout: [
|
||||
`====== 工作流静态分析 (${detail.label || detail.id}) ======`,
|
||||
printKeyValue({
|
||||
"工作流 ID": detail.id,
|
||||
"状态": detail.state === 1 ? "🟢 启用 (state=1)" : "⚪ 停用/草稿 (state=0)",
|
||||
"门禁裁决": gateDecision,
|
||||
"硬门禁数": `${result.summary.hardBlocks} 项 (致命配置/无权限/崩溃)`,
|
||||
"软建议数": `${result.summary.softAdvices} 项 (规范与最佳实践)`,
|
||||
"根节点数": result.ast.length,
|
||||
"依赖节点数": result.dependencies.length,
|
||||
}),
|
||||
`\n依赖引用:\n${dependencyRows.length ? printTable(["节点路径", "类型", "引用"], dependencyRows) : "暂无代码引用"}`,
|
||||
`\n诊断列表 (硬门禁 ⛔ / 软建议 💡):\n${diagnosticRows.length ? printTable(["分类", "级别", "代码", "节点路径", "说明"], diagnosticRows) : "未发现明显配置问题"}`,
|
||||
"",
|
||||
].join("\n"),
|
||||
stderr: "",
|
||||
exitCode,
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { listWorkflowLogs, listWorkflowSnapshots } from "../../../domains/platform/services.js";
|
||||
import { getWorkflowDetail, listWorkflowLogs, listWorkflowSnapshots } from "../../../domains/platform/services.js";
|
||||
import { stringOption, numberOption, booleanOption } from "../../parser.js";
|
||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
@@ -33,50 +33,121 @@ export async function handleLogs(parsed: CliParsedArgs, runtime: CliRuntime): Pr
|
||||
const rawResult = await listWorkflowLogs(client, pipelineId, {
|
||||
state: stringOption(parsed.options, ["state"]),
|
||||
page: numberOption(parsed.options, ["page"]),
|
||||
pageSize: numberOption(parsed.options, ["page-size", "pageSize", "size"]),
|
||||
pageSize: numberOption(parsed.options, ["page-size", "pageSize", "size", "limit", "count", "n"]),
|
||||
startTime: stringOption(parsed.options, ["start-time", "startTime"]),
|
||||
endTime: stringOption(parsed.options, ["end-time", "endTime"]),
|
||||
});
|
||||
const stateOption = stringOption(parsed.options, ["state"]);
|
||||
const hasErrorFilter = booleanOption(parsed.options, ["has-error", "hasError", "errors"]);
|
||||
const isJobError = (job: any): boolean => {
|
||||
const s = (job.status || "").toUpperCase();
|
||||
if (s === "STARTED" || s === "RUNNING") return false;
|
||||
if (job.hasError === true || job.hasError === "存在" || job.hasError === "true") return true;
|
||||
if (typeof job.errorTaskCount === "number" && job.errorTaskCount > 0) return true;
|
||||
if (job.state === "FAILED" || job.status === "FAILED") return true;
|
||||
return false;
|
||||
};
|
||||
const filteredJobList = hasErrorFilter
|
||||
? rawResult.jobList.filter(isJobError)
|
||||
: rawResult.jobList;
|
||||
const result = hasErrorFilter
|
||||
? { ...rawResult, jobList: filteredJobList }
|
||||
: rawResult;
|
||||
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
let filteredJobList = rawResult.jobList;
|
||||
if (hasErrorFilter) {
|
||||
filteredJobList = filteredJobList.filter(isJobError);
|
||||
} else if (stateOption) {
|
||||
const norm = stateOption.trim().toUpperCase();
|
||||
if (norm === "FAILED" || norm === "FAIL" || norm === "ERROR") {
|
||||
filteredJobList = filteredJobList.filter(isJobError);
|
||||
} else if (norm === "COMPLETED" || norm === "SUCCESS") {
|
||||
filteredJobList = filteredJobList.filter((j: any) => (j.status || "").toUpperCase() === "COMPLETED" && !isJobError(j));
|
||||
} else if (norm === "RUNNING" || norm === "STARTED" || norm === "IN_PROGRESS") {
|
||||
filteredJobList = filteredJobList.filter((j: any) => {
|
||||
const s = (j.status || "").toUpperCase();
|
||||
return s === "STARTED" || s === "RUNNING";
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const inProgressCount = Math.max(
|
||||
0,
|
||||
(rawResult.executeCount ?? 0) - (rawResult.successCount ?? 0) - (rawResult.errorCount ?? 0)
|
||||
);
|
||||
|
||||
const result = {
|
||||
...rawResult,
|
||||
jobList: filteredJobList,
|
||||
inProgressCount,
|
||||
};
|
||||
|
||||
let workflowName = rawResult.jobList[0]?.jobName;
|
||||
let workflowState: string | undefined;
|
||||
try {
|
||||
const detail = await getWorkflowDetail(client, pipelineId);
|
||||
if (detail) {
|
||||
workflowName = detail.pipelineName || detail.label || workflowName;
|
||||
workflowState = detail.state === 1 ? "🟢 启用中" : "⚪ 已停用";
|
||||
}
|
||||
} catch {}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ ...result, workflowName, workflowState }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const formatRunType = (runType?: string): string => {
|
||||
if (!runType) return "-";
|
||||
const upper = runType.toUpperCase();
|
||||
if (upper === "DEBUG") return "🧪 调试";
|
||||
if (upper === "RUN") return "🏃 运行";
|
||||
return runType;
|
||||
};
|
||||
|
||||
const formatJobStatus = (status?: string, state?: unknown): string => {
|
||||
const s = (status || "").toUpperCase();
|
||||
if (s === "STARTED" || s === "RUNNING") return "⏳ 运行中";
|
||||
if (s === "COMPLETED" || s === "SUCCESS") return "✅ 已完成";
|
||||
if (s === "FAILED" || s === "ERROR") return "❌ 失败";
|
||||
if (s === "STOP" || s === "STOPPED") return "🛑 终止";
|
||||
if (s === "CANCELLED" || s === "CANCELED") return "🚫 取消";
|
||||
if (!s && (state === 0 || state === "0")) return "COMPLETED";
|
||||
return s || String(state ?? "-");
|
||||
};
|
||||
|
||||
const formatErrorColumn = (job: any): string => {
|
||||
const s = (job.status || "").toUpperCase();
|
||||
if (s === "STARTED" || s === "RUNNING") return "⏳ 执行中";
|
||||
if (isJobError(job)) return "⚠️ 包含错误";
|
||||
return "正常";
|
||||
};
|
||||
|
||||
const rows = result.jobList.map((job: any, idx) => [
|
||||
idx + 1,
|
||||
job.jobId || job.id || "-",
|
||||
job.status || (job.state === 0 ? "COMPLETED" : String(job.state ?? "-")),
|
||||
formatRunType(job.runType),
|
||||
formatJobStatus(job.status, job.state),
|
||||
job.successTaskCount ?? 0,
|
||||
job.errorTaskCount ?? 0,
|
||||
isJobError(job) ? "⚠️ 包含错误" : "正常",
|
||||
formatErrorColumn(job),
|
||||
job.durationTime ?? "-",
|
||||
job.executeTime || job.startTime || "-",
|
||||
]);
|
||||
const tableStr = rows.length
|
||||
? printTable(
|
||||
["#", "Job ID", "状态 (state)", "成功节点 (successTaskCount)", "失败节点 (errorTaskCount)", "有错误 (hasError)", "耗时(ms)", "开始时间"],
|
||||
["#", "Job ID", "类型 (runType)", "状态 (state)", "成功节点", "失败节点", "有错误", "耗时(ms)", "开始时间"],
|
||||
rows
|
||||
)
|
||||
: "暂无匹配的运行记录";
|
||||
|
||||
return {
|
||||
stdout: [
|
||||
`====== 工作流运行日志 [${pipelineId}] ======`,
|
||||
`====== 工作流运行日志 [${pipelineId}]${workflowName ? ` · ${workflowName}` : ""}${workflowState ? ` (${workflowState})` : ""} ======`,
|
||||
printKeyValue({
|
||||
...(workflowName ? { "工作流名称": workflowName } : {}),
|
||||
...(workflowState ? { "当前状态": workflowState } : {}),
|
||||
"执行次数": result.executeCount,
|
||||
"成功次数": result.successCount,
|
||||
"错误次数": result.errorCount,
|
||||
...(result.inProgressCount > 0 ? { "运行中/延时": `${result.inProgressCount} (正在执行或延时等待中)` } : {}),
|
||||
"日志条数": result.totalItems,
|
||||
"当前返回记录": result.jobList.length,
|
||||
}),
|
||||
|
||||
@@ -15,6 +15,7 @@ import { handleNodeCommand } from "./node.js";
|
||||
import { handleWorkflowTailCommand } from "./tail.js";
|
||||
import { handleWorkflowLintScript, handleWorkflowEvalScript } from "./script.js";
|
||||
import { handleWorkflowEnum } from "./enum.js";
|
||||
import { handleWebhookCommand } from "./webhook.js";
|
||||
|
||||
export async function handleWorkflowCommand(
|
||||
parsed: CliParsedArgs,
|
||||
@@ -114,10 +115,14 @@ export async function handleWorkflowCommand(
|
||||
case "dictionary":
|
||||
case "dict":
|
||||
return handleWorkflowEnum(parsed, runtime);
|
||||
case "webhook":
|
||||
case "webhook-send":
|
||||
case "webhooks":
|
||||
return handleWebhookCommand(parsed, runtime);
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, history, logs, job, diff, diff-job, check, test, copy, create, delete, node, tail, lint-script, eval-script, enum\n`,
|
||||
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, history, logs, job, diff, diff-job, check, test, copy, create, delete, node, tail, lint-script, eval-script, enum, webhook\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
getJobExecutionLevel,
|
||||
getJobExecutionTree,
|
||||
getJobFailedExecutions,
|
||||
getWorkflowDetail,
|
||||
isTaskExecutionFailed,
|
||||
listPlatforms,
|
||||
explainConditionBranches,
|
||||
@@ -16,7 +17,7 @@ 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 { PLATFORM_ID_OPTION_KEYS } from "./shared.js";
|
||||
import { PLATFORM_ID_OPTION_KEYS, extractCodeNodeSummaries, formatCodeNodeSummariesCard } from "./shared.js";
|
||||
|
||||
async function createJobPiperClient(
|
||||
parsed: CliParsedArgs,
|
||||
@@ -119,6 +120,7 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
|
||||
const nodeQuery = stringOption(parsed.options, ["node", "task", "node-id", "nodeId"]);
|
||||
const onlyFailed = booleanOption(parsed.options, ["failed", "fail", "errors"]);
|
||||
const verbose = booleanOption(parsed.options, ["verbose", "v"]);
|
||||
const isTimeline = booleanOption(parsed.options, ["timeline", "progress", "steps"]);
|
||||
|
||||
// 1. --logs=<executionId>
|
||||
if (logsExecutionId) {
|
||||
@@ -389,7 +391,7 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
|
||||
};
|
||||
}
|
||||
|
||||
// 4. Default mode: Job overview + top-level tree + failed executions
|
||||
// 4. Default mode: Job overview + top-level tree + failed executions + timeline
|
||||
const [job, tree, failedPage] = await Promise.all([
|
||||
getJob(client, jobId),
|
||||
getJobExecutionTree(client, jobId),
|
||||
@@ -401,19 +403,120 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
|
||||
items: [] as WorkflowTaskExecution[],
|
||||
})),
|
||||
]);
|
||||
const workflowDetail = await getWorkflowDetail(client, job.pipelineId).catch(() => undefined);
|
||||
const failedExecutions = await enrichFailedExecutions(client, jobId, failedPage.items);
|
||||
|
||||
const conditionDiagnoses = explainConditionBranches(tree);
|
||||
|
||||
const timeline = workflowDetail?.tasks?.map((t: any, idx: number) => {
|
||||
const executed = tree.find((node) => node.name === t.name);
|
||||
let statusText = "⏳ 未执行";
|
||||
let errorDetail = "-";
|
||||
if (executed) {
|
||||
if (executed.status === "COMPLETED") statusText = "✅ 已完成";
|
||||
else if (executed.status === "FAILED") {
|
||||
statusText = "❌ 失败中断";
|
||||
const msg = (executed.error?.message || "执行失败").replace(/\s+/g, " ");
|
||||
errorDetail = msg.length > 100 ? `${msg.slice(0, 97)}...` : msg;
|
||||
} else if (executed.status === "STARTED" || executed.status === "RUNNING") {
|
||||
statusText = t.type === "task-dynamic-delay" ? "⏳ 延时等待中" : "⏳ 正在执行中";
|
||||
} else {
|
||||
statusText = executed.status;
|
||||
}
|
||||
} else {
|
||||
const runningPrior = tree.find((node) => node.status === "STARTED" || node.status === "RUNNING");
|
||||
const failedPrior = tree.find((node) => node.status === "FAILED");
|
||||
if (runningPrior) {
|
||||
statusText = "⏳ 等待前序步骤执行完成";
|
||||
} else if (failedPrior) {
|
||||
statusText = "⏳ 未执行 (因前序步骤中断)";
|
||||
}
|
||||
}
|
||||
return {
|
||||
index: idx + 1,
|
||||
name: t.name,
|
||||
displayName: t.displayName || t.label || t.name,
|
||||
type: t.type,
|
||||
status: statusText,
|
||||
duration: executed ? String((executed as any).durationTime ?? executed.executionTime ?? "-") : "-",
|
||||
detail: errorDetail,
|
||||
};
|
||||
});
|
||||
|
||||
if (isTimeline && timeline && timeline.length > 0) {
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
jobId,
|
||||
pipelineId: job.pipelineId,
|
||||
workflowName: workflowDetail?.pipelineName || workflowDetail?.label,
|
||||
workflowState: workflowDetail?.state === 1 ? "🟢 启用中" : "⚪ 已停用",
|
||||
jobStatus: job.state ?? job.status,
|
||||
totalTasks: timeline.length,
|
||||
executedTasks: tree.length,
|
||||
unexecutedTasks: timeline.length - tree.length,
|
||||
timeline,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
const timelineRows = timeline.map((it: any) => [
|
||||
it.index,
|
||||
it.name,
|
||||
it.displayName,
|
||||
it.type,
|
||||
it.status,
|
||||
it.duration,
|
||||
it.detail,
|
||||
]);
|
||||
return {
|
||||
stdout: [
|
||||
`====== 工作流全链路步骤进度 [${job.id}] ======`,
|
||||
printKeyValue({
|
||||
"Job ID": job.id,
|
||||
"工作流 ID": job.pipelineId,
|
||||
...(workflowDetail ? { "工作流名称": workflowDetail.pipelineName || workflowDetail.label } : {}),
|
||||
"工作流状态": workflowDetail?.state === 1 ? "🟢 启用中" : "⚪ 已停用",
|
||||
"Job 状态": job.state ?? job.status,
|
||||
"定义总步骤数": timeline.length,
|
||||
"已调度步骤数": tree.length,
|
||||
"未执行步骤数": timeline.length - tree.length,
|
||||
}),
|
||||
"",
|
||||
printTable(
|
||||
["#", "节点标识", "步骤名称", "类型", "执行状态", "耗时(ms)", "详细说明"],
|
||||
timelineRows
|
||||
),
|
||||
"",
|
||||
].join("\n"),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
jobId,
|
||||
job,
|
||||
workflow: workflowDetail
|
||||
? {
|
||||
id: workflowDetail.id,
|
||||
name: workflowDetail.pipelineName || workflowDetail.label,
|
||||
state: workflowDetail.state,
|
||||
stateLabel: workflowDetail.state === 1 ? "🟢 启用中" : "⚪ 已停用",
|
||||
totalTasks: workflowDetail.tasks?.length ?? tree.length,
|
||||
}
|
||||
: undefined,
|
||||
executionTree: tree,
|
||||
failedExecutions,
|
||||
conditionDiagnoses,
|
||||
timeline,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
@@ -422,16 +525,32 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
|
||||
};
|
||||
}
|
||||
|
||||
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 formatJobStatusLabel = (status?: string, state?: unknown): string => {
|
||||
const s = (status || "").toUpperCase();
|
||||
if (s === "STARTED" || s === "RUNNING") return "⏳ 运行中 (STARTED)";
|
||||
if (s === "COMPLETED" || s === "SUCCESS") return "✅ 已完成 (COMPLETED)";
|
||||
if (s === "FAILED" || s === "ERROR") return "❌ 失败 (FAILED)";
|
||||
if (s === "STOP" || s === "STOPPED") return "🛑 终止 (STOPPED)";
|
||||
if (s === "CANCELLED" || s === "CANCELED") return "🚫 已取消";
|
||||
return s || String(state ?? "-");
|
||||
};
|
||||
|
||||
const treeRows = tree.map((node, idx) => {
|
||||
const isRunning = node.status === "STARTED" || node.status === "RUNNING";
|
||||
const statusLabel = isRunning
|
||||
? (node.type === "task-dynamic-delay" ? "⏳ 延时等待中" : "⏳ 运行中")
|
||||
: node.status || "-";
|
||||
return [
|
||||
idx + 1,
|
||||
node.id,
|
||||
node.name || "-",
|
||||
node.label || node.displayName || "-",
|
||||
node.type || "-",
|
||||
statusLabel,
|
||||
String((node as Record<string, unknown>).durationTime ?? node.executionTime ?? "-"),
|
||||
node.error?.message || "-",
|
||||
];
|
||||
});
|
||||
|
||||
const failedRows = failedExecutions.map((item, idx) => [
|
||||
idx + 1,
|
||||
@@ -444,18 +563,32 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
|
||||
item.error?.message || "-",
|
||||
]);
|
||||
|
||||
const hasUnexecuted = workflowDetail && workflowDetail.tasks && workflowDetail.tasks.length > tree.length;
|
||||
const isJobRunning = (job.status || "").toUpperCase() === "STARTED" || (job.status || "").toUpperCase() === "RUNNING";
|
||||
const outLines = [
|
||||
`====== 工作流 Job 执行详情 [${job.id}] ======`,
|
||||
printKeyValue({
|
||||
"Job ID": job.id,
|
||||
"工作流 ID (pipelineId)": job.pipelineId,
|
||||
"Job 状态 (state)": job.state ?? job.status,
|
||||
...(workflowDetail ? { "工作流名称": workflowDetail.pipelineName || workflowDetail.label } : {}),
|
||||
"工作流状态": workflowDetail?.state === 1 ? "🟢 启用中" : "⚪ 已停用",
|
||||
"Job 状态 (state)": formatJobStatusLabel(job.status, job.state),
|
||||
"开始时间": job.startTime || "-",
|
||||
"结束时间": job.endTime || "-",
|
||||
"耗时(ms)": String(job.durationTime ?? "-"),
|
||||
"顶层节点数": tree.length,
|
||||
"定义总步骤数": workflowDetail?.tasks?.length ?? tree.length,
|
||||
"已调度节点数": tree.length,
|
||||
...(hasUnexecuted ? { "未执行步骤数": workflowDetail.tasks.length - tree.length } : {}),
|
||||
"异常/跳过节点数": failedExecutions.length,
|
||||
}),
|
||||
...(hasUnexecuted
|
||||
? [
|
||||
"",
|
||||
isJobRunning
|
||||
? `💡 提示: 该流程定义共 ${workflowDetail.tasks.length} 步,当前正在执行第 ${tree.length} 步(延时等待中或任务处理中),后续 ${workflowDetail.tasks.length - tree.length} 个步骤尚未调度。运行 'hose-use workflow job ${job.id} --timeline' 可查看实时节点进度。`
|
||||
: `💡 提示: 该流程定义共 ${workflowDetail.tasks.length} 步,本次调度在第 ${tree.length} 步中断,后续 ${workflowDetail.tasks.length - tree.length} 个步骤未执行。运行 'hose-use workflow job ${job.id} --timeline' 查看全链路步骤时间线。`,
|
||||
]
|
||||
: []),
|
||||
"",
|
||||
"── 顶层节点执行树 ──",
|
||||
treeRows.length
|
||||
@@ -496,6 +629,11 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
|
||||
}
|
||||
}
|
||||
|
||||
const codeSummaries = extractCodeNodeSummaries(tree, flattenExecutionTree);
|
||||
if (codeSummaries.length > 0) {
|
||||
outLines.push(...formatCodeNodeSummariesCard(codeSummaries, job.id));
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `${outLines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
|
||||
@@ -14,36 +14,62 @@ export async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Pr
|
||||
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 keyword = stringOption(parsed.options, ["keyword", "q", "query"]);
|
||||
const isFull = booleanOption(parsed.options, ["full", "with-tasks", "withTasks"], false);
|
||||
|
||||
const rawResult = await listAllWorkflows(clients, { page, pageSize });
|
||||
const workflows = filterPlatformId
|
||||
let workflows = filterPlatformId
|
||||
? rawResult.workflows.filter(
|
||||
(wf) => wf.platformId === filterPlatformId || wf.platformName === filterPlatformId
|
||||
)
|
||||
: rawResult.workflows;
|
||||
const result = filterPlatformId
|
||||
? { ...rawResult, workflows, totalWorkflows: workflows.length }
|
||||
: rawResult;
|
||||
|
||||
if (keyword) {
|
||||
const kw = keyword.toLowerCase();
|
||||
workflows = workflows.filter(
|
||||
(wf) =>
|
||||
wf.pipelineName.toLowerCase().includes(kw) ||
|
||||
wf.id.toLowerCase().includes(kw) ||
|
||||
Boolean(wf.platformName && wf.platformName.toLowerCase().includes(kw))
|
||||
);
|
||||
}
|
||||
|
||||
// 默认轻量化模式:列表态剥离庞大的 tasks 节点树与代码脚本,只输出核心元数据和节点数统计
|
||||
const outputWorkflows = isFull
|
||||
? workflows
|
||||
: workflows.map(({ tasks, ...rest }) => ({
|
||||
...rest,
|
||||
nodeCount: tasks?.length ?? 0,
|
||||
}));
|
||||
|
||||
const result = {
|
||||
...rawResult,
|
||||
workflows: outputWorkflows,
|
||||
totalWorkflows: workflows.length,
|
||||
};
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
if (result.workflows.length === 0) {
|
||||
if (workflows.length === 0) {
|
||||
const emptyMsg = keyword
|
||||
? `企业 [${runtime.selectedCorp!.name}] 下未找到包含关键词 "${keyword}" 的工作流\n`
|
||||
: `企业 [${runtime.selectedCorp!.name}] 下暂无工作流\n`;
|
||||
return {
|
||||
stdout: `企业 [${runtime.selectedCorp!.name}] 下暂无工作流\n`,
|
||||
stdout: emptyMsg,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = result.workflows.map((wf, i) => [
|
||||
const rows = workflows.map((wf, i) => [
|
||||
i + 1,
|
||||
wf.id,
|
||||
wf.pipelineName,
|
||||
wf.platformName || wf.platformId || "-",
|
||||
wf.state === 1 ? "🟢 启用" : "⚪ 停用",
|
||||
wf.tasks?.length ?? "-",
|
||||
wf.tasks?.length ?? (wf as any).nodeCount ?? "-",
|
||||
]);
|
||||
|
||||
const table = printTable(
|
||||
@@ -51,8 +77,15 @@ export async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Pr
|
||||
rows
|
||||
);
|
||||
|
||||
const filterDesc = [
|
||||
filterPlatformId ? `应用: ${filterPlatformId}` : "",
|
||||
keyword ? `关键词: "${keyword}"` : "",
|
||||
].filter(Boolean).join(", ");
|
||||
|
||||
const titleSuffix = filterDesc ? ` (过滤: ${filterDesc}, 共 ${workflows.length} 条)` : ` (共 ${workflows.length} 条)`;
|
||||
|
||||
return {
|
||||
stdout: `====== [${runtime.selectedCorp!.name}] 工作流列表 (共 ${result.workflows.length} 条) ======\n${table}\n`,
|
||||
stdout: `====== [${runtime.selectedCorp!.name}] 工作流列表${titleSuffix} ======\n${table}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
@@ -71,14 +104,21 @@ export async function handleGet(parsed: CliParsedArgs, runtime: CliRuntime): Pro
|
||||
return { stdout: printJson(detail, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const isDraft = detail.state === 0;
|
||||
const tasksVersion = (detail as Record<string, unknown>).tasksVersion;
|
||||
const summary = printKeyValue({
|
||||
"工作流 ID": detail.id,
|
||||
"工作流名称": detail.label,
|
||||
"状态": detail.state === 1 ? "🟢 启用" : "⚪ 停用",
|
||||
"版本号": detail.version || "-",
|
||||
"当前状态": detail.state === 1 ? "🟢 线上启用 (state=1)" : "⚪ 停用/未发布草稿 (state=0)",
|
||||
"发布版本 (version)": detail.version || "-",
|
||||
...(tasksVersion !== undefined ? { "草稿版本 (tasksVersion)": String(tasksVersion) } : {}),
|
||||
"节点总数": detail.tasks?.length ?? 0,
|
||||
});
|
||||
|
||||
const draftNotice = isDraft
|
||||
? `\n💡 提示: 该工作流当前处于未发布草稿态 (state=0)。草稿与生产流程共享同一实例 ID 和历史记录;直接修改草稿将在发布后覆盖线上逻辑。如需安全隔离测试,请先执行: hose-use workflow copy ${detail.id}\n`
|
||||
: "";
|
||||
|
||||
let taskList = "";
|
||||
if (detail.tasks && detail.tasks.length > 0) {
|
||||
const taskRows = detail.tasks.map((t, i) => [
|
||||
@@ -92,7 +132,7 @@ export async function handleGet(parsed: CliParsedArgs, runtime: CliRuntime): Pro
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `====== 工作流详情 ======\n${summary}\n${taskList}\n`,
|
||||
stdout: `====== 工作流详情 ======\n${summary}\n${draftNotice}${taskList}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
|
||||
@@ -6,20 +6,51 @@ import {
|
||||
addWorkflowTask,
|
||||
editWorkflowTask,
|
||||
removeWorkflowTask,
|
||||
applyNodeMapping,
|
||||
getWorkflowAvailableNodes,
|
||||
grantWorkflowNodes,
|
||||
} from "../../../domains/platform/services.js";
|
||||
import {
|
||||
GRAY_NODES_CATALOG,
|
||||
findGrayNode,
|
||||
} from "../../../domains/platform/workflow/nodes/gray-nodes-catalog.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { createPiperClientForCorp } from "../../helpers.js";
|
||||
import { createWorkflowDetailClient } from "./shared.js";
|
||||
|
||||
const SUB_ACTIONS = new Set(["list", "ls", "get", "show", "info", "add", "append", "insert", "edit", "update", "set", "rm", "remove", "delete", "del"]);
|
||||
const SUB_ACTIONS = new Set(["list", "ls", "get", "show", "info", "add", "append", "insert", "edit", "update", "set", "map", "rm", "remove", "delete", "del"]);
|
||||
const CORP_LEVEL_ACTIONS = new Set(["available", "list-available", "catalog", "probe", "grant", "open"]);
|
||||
|
||||
export async function handleNodeCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const isPluralNodes = parsed.action === "nodes";
|
||||
const firstArg = parsed.args[0]?.toLowerCase();
|
||||
|
||||
// 1. 企业级节点字典与灰度开通快捷分支
|
||||
if (firstArg === "grant" || firstArg === "open") {
|
||||
return handleGrantNodes(parsed, runtime);
|
||||
}
|
||||
if (
|
||||
firstArg === "available" ||
|
||||
firstArg === "list-available" ||
|
||||
firstArg === "catalog" ||
|
||||
firstArg === "probe"
|
||||
) {
|
||||
return handleListAvailableNodes(parsed, runtime);
|
||||
}
|
||||
|
||||
// 2. 如果是 `hose-use workflow nodes`(复数)且没有指定具体的 pipelineId
|
||||
const secondArg = parsed.args[1];
|
||||
const isSecondArgPipelineId = secondArg && /^\d{10,}$/.test(secondArg.trim());
|
||||
if (isPluralNodes && (!firstArg || ((firstArg === "list" || firstArg === "ls") && !isSecondArgPipelineId && !parsed.options.id && !parsed.options.pipelineId))) {
|
||||
return handleListAvailableNodes(parsed, runtime);
|
||||
}
|
||||
|
||||
let subAction = "list";
|
||||
let pipelineId = "";
|
||||
let nodeTarget = "";
|
||||
@@ -43,19 +74,23 @@ export async function handleNodeCommand(
|
||||
stderr: [
|
||||
"用法: hose-use workflow node <子命令> <pipelineId> [选项]",
|
||||
"",
|
||||
"子命令:",
|
||||
"子命令 (工作流级别):",
|
||||
" list <pipelineId> 列出工作流所有任务节点 (别名: ls, 默认)",
|
||||
" get <pipelineId> <节点标识> 查看指定节点的完整配置 (别名: show, info)",
|
||||
" add <pipelineId> [选项] 声明式追加或插入新任务节点 (别名: append, insert)",
|
||||
" edit <pipelineId> <节点标识> 定向修改指定节点配置 (别名: update, set)",
|
||||
" map <pipelineId> <节点标识> 从映射文件批量更新深层字段 (别名: node map --mapping-file)",
|
||||
" rm <pipelineId> <节点标识> 安全移除指定任务节点 (别名: remove, delete)",
|
||||
"",
|
||||
"子命令 (企业灰度节点级别):",
|
||||
" nodes [list] [--all] 列出当前企业已开通的节点字典 (别名: probe, catalog)",
|
||||
" nodes grant <type...> 为当前企业开通灰度节点",
|
||||
"",
|
||||
"示例:",
|
||||
" hose-use workflow nodes",
|
||||
" hose-use workflow nodes --all",
|
||||
" hose-use workflow nodes grant code-js2",
|
||||
" hose-use workflow node list 896398895352487950",
|
||||
" hose-use workflow node get 896398895352487950 action_dx9cci",
|
||||
" hose-use workflow node add 896398895352487950 --type=code-js2 --label='数据清洗' --code='return items;' --yes",
|
||||
" hose-use workflow node edit 896398895352487950 action_dx9cci --label='新清洗逻辑' --yes",
|
||||
" hose-use workflow node rm 896398895352487950 action_dx9cci --yes",
|
||||
].join("\n") + "\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
@@ -77,6 +112,8 @@ export async function handleNodeCommand(
|
||||
case "update":
|
||||
case "set":
|
||||
return handleEditNode(pipelineId, nodeTarget, parsed, runtime);
|
||||
case "map":
|
||||
return handleMapNode(pipelineId, nodeTarget, parsed, runtime);
|
||||
case "rm":
|
||||
case "remove":
|
||||
case "delete":
|
||||
@@ -215,7 +252,17 @@ async function handleAddNode(
|
||||
stderr: [
|
||||
"请指定新增节点类型: --type=<类型>",
|
||||
"常见类型: code-js2 (JS脚本), code (MVEL代码), http (HTTP请求), stop (终止流程), every (循环遍历), condition (分支条件)",
|
||||
"示例: hose-use workflow node add 896398895352487950 --type=code-js2 --label='数据清洗' --yes",
|
||||
"",
|
||||
"常用选项:",
|
||||
" --type=<type> 节点类型 (如 code-js2 / code)",
|
||||
" --label=<标题> 节点显示名称",
|
||||
" --code-file=<脚本路径> (推荐) 从本地文件导入代码,避免终端转义与 Token 浪费",
|
||||
" --code=<代码片段> 传入代码字符串(仅限简短代码)",
|
||||
" --parent=<容器节点name> 插入指定容器节点内部 (如 every 循环)",
|
||||
" --after=<前置节点name> 插入指定节点之后",
|
||||
" --yes 确认追加",
|
||||
"",
|
||||
"示例: hose-use workflow node add 896398895352487950 --type=code-js2 --label='数据清洗' --code-file=./clean.js --yes",
|
||||
].join("\n") + "\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
@@ -296,7 +343,21 @@ async function handleEditNode(
|
||||
if (!nodeTarget) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "请提供节点标识 (name 或层级序号): hose-use workflow node edit <pipelineId> <nodeNameOrIndex> [选项]\n",
|
||||
stderr: [
|
||||
"请提供节点标识 (name 或层级序号): hose-use workflow node edit <pipelineId> <nodeNameOrIndex> [选项]",
|
||||
"",
|
||||
"常用选项:",
|
||||
" --label=<新名称> 更新节点显示标题",
|
||||
" --code-file=<脚本路径> (推荐) 从本地文件导入最新脚本,避免终端转义与 Token 浪费",
|
||||
" --code=<行内代码> 直接传入代码片段(短脚本)",
|
||||
" --desc=<描述> 更新节点描述",
|
||||
" --set='key=value' 定向修改节点自定义属性",
|
||||
" --dry-run 只预览变更",
|
||||
" --yes 确认保存修改",
|
||||
"",
|
||||
"示例:",
|
||||
" hose-use workflow node edit 900682164608835609 action_cdd6fv --code-file=./clean.mvel --yes",
|
||||
].join("\n") + "\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
@@ -326,6 +387,14 @@ async function handleEditNode(
|
||||
}
|
||||
}
|
||||
|
||||
const mappingFile = stringOption(parsed.options, ["mapping-file", "mapping", "file", "json-file"]);
|
||||
if (mappingFile) {
|
||||
const fs = await import("fs/promises");
|
||||
const rawContent = await fs.readFile(mappingFile, "utf-8");
|
||||
const mappingData = JSON.parse(rawContent);
|
||||
return handleMapNode(pipelineId, nodeTarget, parsed, runtime, mappingData);
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
@@ -351,7 +420,7 @@ async function handleEditNode(
|
||||
updatedFields: {
|
||||
...(label ? { label } : {}),
|
||||
...(desc ? { desc } : {}),
|
||||
...(code !== undefined ? { code: `${code.length} 字符` } : {}),
|
||||
...(code !== undefined ? { code: `${code.length} 字符${!codeFile && code.length > 300 ? " [TIP: 建议使用 --code-file=<path> 从本地文件载入以规避转义错误并节省 Token]" : ""}` } : {}),
|
||||
...customSet,
|
||||
},
|
||||
});
|
||||
@@ -367,8 +436,103 @@ async function handleEditNode(
|
||||
};
|
||||
}
|
||||
|
||||
let codeTip = "";
|
||||
if (!codeFile && code && code.length > 300) {
|
||||
codeTip = `\n💡 提示: 检测到通过命令行行内传入大段代码 (${code.length} 字符)。建议将脚本落地为本地文件并通过 --code-file=<路径> 传入,避免 Token 浪费与 Shell 转义风险。\n`;
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `✅ 节点 [${editedTask.name}] (${editedTask.label}) 修改已保存至工作流 [${pipelineId}]。\n`,
|
||||
stdout: `✅ 节点 [${editedTask.name}] (${editedTask.label}) 修改已保存至工作流 [${pipelineId}]。\n${codeTip}`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleMapNode(
|
||||
pipelineId: string,
|
||||
nodeTarget: string,
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime,
|
||||
injectedMappingData?: any
|
||||
): Promise<CliResult> {
|
||||
if (!nodeTarget) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: [
|
||||
"请提供目标节点标识 (name 或层级序号): hose-use workflow node map <pipelineId> <nodeNameOrIndex> --mapping-file=<path> [选项]",
|
||||
"",
|
||||
"常用选项:",
|
||||
" --mapping-file=<路径> 包含字段映射的本地 JSON 文件 (可为字段数组或属性对象)",
|
||||
" --dry-run 只预览变更",
|
||||
" --yes 确认保存修改",
|
||||
"",
|
||||
"示例:",
|
||||
" hose-use workflow node map 900682164608835609 action_datalink_create --mapping-file=./fields.json --yes",
|
||||
].join("\n") + "\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
let mappingData = injectedMappingData;
|
||||
if (!mappingData) {
|
||||
const mappingFile = stringOption(parsed.options, ["mapping-file", "mapping", "file", "json-file"]);
|
||||
if (!mappingFile) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "错误: 请通过 --mapping-file=<路径> 指定本地字段映射 JSON 文件\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
const fs = await import("fs/promises");
|
||||
try {
|
||||
const content = await fs.readFile(mappingFile, "utf-8");
|
||||
mappingData = JSON.parse(content);
|
||||
} catch (e: any) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `错误: 读取或解析映射文件失败: ${e.message}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"批量映射工作流节点配置",
|
||||
`hose-use workflow node map ${pipelineId} ${nodeTarget} --yes`
|
||||
);
|
||||
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const detail = await getWorkflowDetail(client, pipelineId);
|
||||
|
||||
const { workflow: updatedWorkflow, editedTask, changedKeys } = applyNodeMapping(detail, nodeTarget, mappingData);
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "批量映射工作流节点配置", `${pipelineId}:${editedTask.name}`, {
|
||||
pipelineId,
|
||||
nodeName: editedTask.name,
|
||||
label: editedTask.label,
|
||||
nodeType: editedTask.type,
|
||||
changedKeys,
|
||||
mappingSummary: Array.isArray(mappingData)
|
||||
? `数组格式更新 (${mappingData.length} 项)`
|
||||
: `对象属性更新 (${Object.keys(mappingData).join(", ")})`,
|
||||
});
|
||||
}
|
||||
|
||||
const saveResult = await updateWorkflow(client, updatedWorkflow);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ success: true, pipelineId, editedTask, changedKeys, workflow: saveResult }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `✅ 节点 [${editedTask.name}] (${editedTask.label}) 已批量应用映射: ${changedKeys.join(", ")},并已保存至工作流 [${pipelineId}]。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
@@ -426,3 +590,175 @@ async function handleRemoveNode(
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// ── 企业可用节点字典与灰度开通 ──────────────────────────────────────────────
|
||||
|
||||
async function handleListAvailableNodes(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const corp = runtime.selectedCorp!;
|
||||
const platformId = stringOption(parsed.options, ["platform-id", "platformId", "app-id", "appId"]) || corp.id;
|
||||
const piperClient = await createPiperClientForCorp(corp, platformId);
|
||||
const available = await getWorkflowAvailableNodes(piperClient);
|
||||
|
||||
const showAll = Boolean(parsed.options.all || parsed.options.compare || parsed.options.diff);
|
||||
const filterKw = (
|
||||
parsed.args[1] ||
|
||||
stringOption(parsed.options, ["keyword", "query", "filter"]) ||
|
||||
""
|
||||
).toLowerCase();
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
const output = {
|
||||
corpId: corp.corpId || corp.id,
|
||||
corpName: corp.name,
|
||||
totalGranted: available.allTypes.size,
|
||||
actionNodesCount: available.actionNodes.length,
|
||||
controlNodesCount: available.controlNodes.length,
|
||||
triggerNodesCount: available.triggerNodes.length,
|
||||
grantedTypes: Array.from(available.allTypes).sort(),
|
||||
catalog: {
|
||||
action: available.actionNodes.map((n) => ({ name: n.name, type: n.type })),
|
||||
control: available.controlNodes.map((n) => ({ name: n.name, type: n.type })),
|
||||
trigger: available.triggerNodes.map((n) => ({ name: n.name, type: n.type })),
|
||||
},
|
||||
};
|
||||
return {
|
||||
stdout: printJson(output, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 渲染人类友好视图
|
||||
if (showAll) {
|
||||
// 对照全量 108 个灰度节点
|
||||
const rows = GRAY_NODES_CATALOG.filter((item) => {
|
||||
if (!filterKw) return true;
|
||||
return (
|
||||
item.displayName.toLowerCase().includes(filterKw) ||
|
||||
item.type.toLowerCase().includes(filterKw)
|
||||
);
|
||||
}).map((item) => {
|
||||
const isGranted = available.allTypes.has(item.type.toLowerCase());
|
||||
const statusText = isGranted ? "✅ 已开通" : "🔒 未开通";
|
||||
return [item.displayName, item.type, item.category || "action", statusText];
|
||||
});
|
||||
|
||||
const output = [
|
||||
`====== 工作流节点字典与灰度开通对照 [${corp.name}] ======`,
|
||||
printKeyValue({
|
||||
"当前企业": `${corp.name} (${corp.corpId || corp.id})`,
|
||||
"已开通节点总数": `${available.allTypes.size} 个`,
|
||||
"灰度对照清单": `${GRAY_NODES_CATALOG.length} 个`,
|
||||
}),
|
||||
"",
|
||||
printTable(["显示名称", "节点类型 (type)", "分组", "开通状态"], rows),
|
||||
"",
|
||||
"提示:",
|
||||
" - 使用 hose-use workflow nodes grant <type> 开通灰度节点 (如: hose-use workflow nodes grant code-js2)",
|
||||
].join("\n");
|
||||
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
// 简要分组视图
|
||||
const actionList = available.actionNodes.map((n) => `${n.name} (${n.type})`).join("、");
|
||||
const controlList = available.controlNodes.map((n) => `${n.name} (${n.type})`).join("、");
|
||||
const triggerList = available.triggerNodes.map((n) => `${n.name} (${n.type})`).join("、");
|
||||
|
||||
const output = [
|
||||
`====== 当前企业已开通工作流节点字典 [${corp.name}] ======`,
|
||||
printKeyValue({
|
||||
"当前企业": `${corp.name} (${corp.corpId || corp.id})`,
|
||||
"已开通节点数": `${available.allTypes.size} 个 (动作 ${available.actionNodes.length}, 控制 ${available.controlNodes.length}, 触发 ${available.triggerNodes.length})`,
|
||||
}),
|
||||
"",
|
||||
`⚡ 触发器节点 (${available.triggerNodes.length}):`,
|
||||
triggerList || "无",
|
||||
"",
|
||||
`⚙️ 动作节点 (${available.actionNodes.length}):`,
|
||||
actionList || "无",
|
||||
"",
|
||||
`🔀 控制流程节点 (${available.controlNodes.length}):`,
|
||||
controlList || "无",
|
||||
"",
|
||||
"提示:",
|
||||
" - 添加 --all 参数可查看与官方 108 个灰度节点清单的完整开通对照表",
|
||||
" - 使用 hose-use workflow nodes grant <type...> 开通新灰度节点 (如: hose-use workflow nodes grant code-js2)",
|
||||
].join("\n");
|
||||
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleGrantNodes(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const corp = runtime.selectedCorp!;
|
||||
const rawNodes = parsed.args.slice(1);
|
||||
const optionNodes = stringOption(parsed.options, ["nodes", "node", "type", "types"]);
|
||||
const targetNodes: string[] = [];
|
||||
|
||||
if (optionNodes) {
|
||||
targetNodes.push(...optionNodes.split(/[,,\s]+/).map((s) => s.trim()).filter(Boolean));
|
||||
}
|
||||
for (const arg of rawNodes) {
|
||||
if (arg && !arg.startsWith("-")) {
|
||||
targetNodes.push(...arg.split(/[,,\s]+/).map((s) => s.trim()).filter(Boolean));
|
||||
}
|
||||
}
|
||||
|
||||
if (targetNodes.length === 0) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "错误: 请指定要开通的节点类型 (如: hose-use workflow nodes grant code-js2 或 dify)\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
requireMutationConfirmation(parsed, runtime, "开通企业工作流灰度节点", "hose-use workflow nodes grant <type...> --yes");
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "开通企业工作流灰度节点", corp.corpId || corp.credentials.corpId || corp.id, {
|
||||
nodes: targetNodes.map(node => findGrayNode(node)?.type || node.trim()),
|
||||
adminPasswordRequired: Boolean(process.env.HOSE_ADMIN_PASSWORD),
|
||||
});
|
||||
}
|
||||
|
||||
const password = stringOption(parsed.options, ["password", "pwd", "admin-key"]);
|
||||
|
||||
const result = await grantWorkflowNodes(corp, {
|
||||
nodes: targetNodes,
|
||||
password,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(result, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: result.success ? 0 : 1,
|
||||
};
|
||||
}
|
||||
if (!result.success) {
|
||||
return { stdout: "", stderr: `灰度节点开通失败: ${result.rawMessage || "网关拒绝了开通请求"}\n`, exitCode: 1 };
|
||||
}
|
||||
|
||||
const lines = [
|
||||
`====== 灰度节点开通结果 [${corp.name}] ======`,
|
||||
printKeyValue({
|
||||
"申请开通节点": targetNodes.join(", "),
|
||||
"新开通成功": result.saved.length ? result.saved.join(", ") : "无 (已处于开通状态)",
|
||||
"跳过(已开通)": result.skipped.length ? result.skipped.join(", ") : "无",
|
||||
"网关反馈": result.rawMessage || "处理成功",
|
||||
}),
|
||||
"",
|
||||
"✅ 节点权限已生效!工作流设计器与 hose-use workflow analyze 将立即支持该节点。",
|
||||
];
|
||||
|
||||
return {
|
||||
stdout: lines.join("\n"),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { expect, spyOn, test } from "bun:test";
|
||||
import { mkdtempSync, readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
import { parseArgs } from "../../parser.js";
|
||||
import { handleWorkflowLintScript, handleWorkflowEvalScript } from "./script.js";
|
||||
import * as shared from "./shared.js";
|
||||
import * as services from "../../../domains/platform/services.js";
|
||||
|
||||
test("all local and remote script JSON branches return reports and honor output files", async () => {
|
||||
const client = spyOn(shared, "createWorkflowDetailClient").mockResolvedValue({ client: {} } as any);
|
||||
const detail = spyOn(services, "getWorkflowDetail").mockResolvedValue({ id: "wf", tasks: [{ name: "code", type: "code-js2", code: "return 7;" }] } as any);
|
||||
const root = mkdtempSync(join(tmpdir(), "hose-script-json-"));
|
||||
try {
|
||||
for (const action of ["lint-script", "eval-script"]) {
|
||||
for (const remote of [false, true]) {
|
||||
const handler = action === "lint-script" ? handleWorkflowLintScript : handleWorkflowEvalScript;
|
||||
const args = remote ? ["wf", "code", "--input", '{"x":1}'] : ["--code", "return 7;"];
|
||||
const parsed = parseArgs(["workflow", action, ...args, "--json"]);
|
||||
const report = await handler(parsed, { jsonMode: true } as any);
|
||||
expect(report.exitCode).toBe(0);
|
||||
const data = JSON.parse(report.stdout);
|
||||
if (action === "eval-script") expect(data.returnValue).toBe(7);
|
||||
else expect(data.valid ?? data.allValid).toBe(true);
|
||||
const outputFile = join(root, `${action}-${remote}.json`);
|
||||
const output = await handler(parsed, { jsonMode: true, outputOptions: { outputFile } } as any);
|
||||
expect(JSON.parse(output.stdout).outputFile).toBe(outputFile);
|
||||
expect(JSON.parse(readFileSync(outputFile, "utf8"))).toEqual(expect.objectContaining(action === "eval-script" ? { returnValue: 7 } : {}));
|
||||
}
|
||||
}
|
||||
} finally { client.mockRestore(); detail.mockRestore(); }
|
||||
});
|
||||
test("script failures retain JSON output and failure exit code", async () => {
|
||||
const result = await handleWorkflowEvalScript(parseArgs(["workflow", "eval-script", "--code", "throw new Error('failure');", "-j"]), { jsonMode: true } as any);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(JSON.parse(result.stdout).error.message).toBe("failure");
|
||||
});
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
lintJavaScriptCode,
|
||||
lintMvelCode,
|
||||
executeJavaScriptSandbox,
|
||||
executeMvelSandbox,
|
||||
} from "../../../domains/platform/services.js";
|
||||
import { stringOption, booleanOption } from "../../parser.js";
|
||||
import { printJson, printKeyValue } from "../../printer.js";
|
||||
@@ -20,7 +21,7 @@ export async function handleWorkflowLintScript(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const isJson = booleanOption(parsed.options, ["json"]);
|
||||
const isJson = runtime.jsonMode || booleanOption(parsed.options, ["json", "j"]);
|
||||
const filePath = stringOption(parsed.options, ["file", "path"]);
|
||||
const codeInline = stringOption(parsed.options, ["code"]);
|
||||
const explicitType = (stringOption(parsed.options, ["type"]) || "code-js2").toLowerCase();
|
||||
@@ -68,8 +69,7 @@ export async function handleWorkflowLintScript(
|
||||
};
|
||||
|
||||
if (isJson) {
|
||||
printJson(report);
|
||||
return { stdout: "", stderr: "", exitCode: hasErrors ? 1 : 0 };
|
||||
return { stdout: printJson(report, runtime.outputOptions), stderr: "", exitCode: hasErrors ? 1 : 0 };
|
||||
}
|
||||
|
||||
const lines: string[] = [];
|
||||
@@ -132,8 +132,7 @@ export async function handleWorkflowLintScript(
|
||||
const report = lintWorkflowScripts(workflow, targetNode);
|
||||
|
||||
if (isJson) {
|
||||
printJson(report);
|
||||
return { stdout: "", stderr: "", exitCode: report.allValid ? 0 : 1 };
|
||||
return { stdout: printJson(report, runtime.outputOptions), stderr: "", exitCode: report.allValid ? 0 : 1 };
|
||||
}
|
||||
|
||||
const lines: string[] = [];
|
||||
@@ -193,11 +192,13 @@ export async function handleWorkflowEvalScript(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const isJson = booleanOption(parsed.options, ["json"]);
|
||||
const isJson = runtime.jsonMode || booleanOption(parsed.options, ["json", "j"]);
|
||||
const filePath = stringOption(parsed.options, ["file", "path"]);
|
||||
const codeInline = stringOption(parsed.options, ["code"]);
|
||||
const timeoutStr = stringOption(parsed.options, ["timeout"]);
|
||||
const timeoutMs = timeoutStr ? parseInt(timeoutStr, 10) : 3000;
|
||||
const explicitType = (stringOption(parsed.options, ["type"]) || "").toLowerCase();
|
||||
const isMvel = explicitType === "code" || explicitType === "mvel" || (filePath ? filePath.endsWith(".mvel") : false);
|
||||
|
||||
// 1. 获取输入参数 inputs
|
||||
let inputs: Record<string, unknown> = {};
|
||||
@@ -247,11 +248,12 @@ export async function handleWorkflowEvalScript(
|
||||
code = fs.readFileSync(filePath, "utf-8");
|
||||
}
|
||||
|
||||
const evalResult = await executeJavaScriptSandbox(code, inputs, { timeoutMs });
|
||||
const evalResult = isMvel
|
||||
? await executeMvelSandbox(code, inputs, { timeoutMs })
|
||||
: await executeJavaScriptSandbox(code, inputs, { timeoutMs });
|
||||
|
||||
if (isJson) {
|
||||
printJson(evalResult);
|
||||
return { stdout: "", stderr: "", exitCode: evalResult.success ? 0 : 1 };
|
||||
return { stdout: printJson(evalResult, runtime.outputOptions), stderr: "", exitCode: evalResult.success ? 0 : 1 };
|
||||
}
|
||||
|
||||
return formatEvalCliResult(evalResult, filePath ? `file: ${filePath}` : "inline-code");
|
||||
@@ -299,18 +301,7 @@ export async function handleWorkflowEvalScript(
|
||||
}
|
||||
|
||||
const task = located.task;
|
||||
if (task.type !== "code-js2") {
|
||||
if (task.type === "code") {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: [
|
||||
`节点 [${task.name}] 是 MVEL (code) 节点。`,
|
||||
"当前本地离线沙箱仅支持 JavaScript (code-js2) 运行时仿真。",
|
||||
"提示: 您可以使用 hose-use workflow lint-script 检查其括号与上游引用,或使用 hose-use workflow test 进行全链路调试。",
|
||||
].join("\n") + "\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
if (task.type !== "code-js2" && task.type !== "code") {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `节点 [${task.name}] 不是代码节点,类型为: ${task.type}\n`,
|
||||
@@ -319,6 +310,7 @@ export async function handleWorkflowEvalScript(
|
||||
}
|
||||
|
||||
const code: string = (task as any).code || "";
|
||||
const isNodeMvel = task.type === "code";
|
||||
|
||||
// 如果没有显式传 input,尝试提取工作流样本数据
|
||||
if (Object.keys(inputs).length === 0) {
|
||||
@@ -355,11 +347,12 @@ export async function handleWorkflowEvalScript(
|
||||
}
|
||||
}
|
||||
|
||||
const evalResult = await executeJavaScriptSandbox(code, inputs, { timeoutMs });
|
||||
const evalResult = isNodeMvel
|
||||
? await executeMvelSandbox(code, inputs, { timeoutMs })
|
||||
: await executeJavaScriptSandbox(code, inputs, { timeoutMs });
|
||||
|
||||
if (isJson) {
|
||||
printJson(evalResult);
|
||||
return { stdout: "", stderr: "", exitCode: evalResult.success ? 0 : 1 };
|
||||
return { stdout: printJson(evalResult, runtime.outputOptions), stderr: "", exitCode: evalResult.success ? 0 : 1 };
|
||||
}
|
||||
|
||||
const targetDesc = `节点 [${task.name}] ${task.label || task.displayName || ""} (${pipelineId})`;
|
||||
|
||||
@@ -3,7 +3,7 @@ import { stringOption } from "../../parser.js";
|
||||
import { createClientsForCorp, createPiperClientForCorp } from "../../helpers.js";
|
||||
import type { CliParsedArgs, CliRuntime } from "../../types.js";
|
||||
|
||||
export const PLATFORM_ID_OPTION_KEYS = ["platform-id", "platformId", "app-id", "appId"];
|
||||
export const PLATFORM_ID_OPTION_KEYS = ["platform", "platform-id", "platformId", "app", "app-id", "appId"];
|
||||
|
||||
export async function createWorkflowDetailClient(
|
||||
parsed: CliParsedArgs,
|
||||
@@ -56,3 +56,105 @@ export async function createJobPiperClient(
|
||||
}
|
||||
return clients.easoClient;
|
||||
}
|
||||
|
||||
export interface CodeNodeSummary {
|
||||
id: string;
|
||||
name: string;
|
||||
label: string;
|
||||
type: string;
|
||||
status: string;
|
||||
rawOutput: unknown;
|
||||
summaryLines: string[];
|
||||
}
|
||||
|
||||
export function extractCodeNodeSummaries(
|
||||
nodes: Array<any>,
|
||||
flattenExecutionTreeFn?: (nodes: any[]) => any[]
|
||||
): CodeNodeSummary[] {
|
||||
const flattened = flattenExecutionTreeFn ? flattenExecutionTreeFn(nodes) : nodes;
|
||||
const summaries: CodeNodeSummary[] = [];
|
||||
|
||||
for (const node of flattened) {
|
||||
if (!node) continue;
|
||||
const type = String(node.type || "");
|
||||
if (type !== "code" && type !== "code-js2") continue;
|
||||
|
||||
const rawOutput = node.output ?? node.outputs ?? node.details;
|
||||
const summaryLines: string[] = [];
|
||||
|
||||
if (rawOutput === undefined || rawOutput === null) {
|
||||
summaryLines.push(" 出参: (无返回值或 null)");
|
||||
} else if (Array.isArray(rawOutput)) {
|
||||
summaryLines.push(` 出参类型: Array (${rawOutput.length} 项)`);
|
||||
if (rawOutput.length > 0) {
|
||||
const first = rawOutput[0];
|
||||
if (first && typeof first === "object") {
|
||||
const keys = ["planCode", "code", "id", "name", "title", "totalAmount", "amount"];
|
||||
const matchedKey = keys.find((k) => (first as Record<string, unknown>)[k] !== undefined);
|
||||
if (matchedKey) {
|
||||
summaryLines.push(` 首项 ${matchedKey}: ${String((first as Record<string, unknown>)[matchedKey])}`);
|
||||
}
|
||||
if ((first as any).amount !== undefined && matchedKey !== "amount") {
|
||||
summaryLines.push(` 首项金额: ${String((first as any).amount)}`);
|
||||
}
|
||||
} else {
|
||||
summaryLines.push(` 首项值: ${String(first)}`);
|
||||
}
|
||||
}
|
||||
} else if (typeof rawOutput === "object") {
|
||||
const obj = rawOutput as Record<string, unknown>;
|
||||
summaryLines.push(" 出参类型: Object");
|
||||
if (Array.isArray(obj.items)) {
|
||||
summaryLines.push(` items.length: ${obj.items.length}`);
|
||||
}
|
||||
for (const k of ["planCode", "totalAmount", "count", "code", "total", "amount", "success"]) {
|
||||
if (obj[k] !== undefined) {
|
||||
summaryLines.push(` ${k}: ${String(obj[k])}`);
|
||||
}
|
||||
}
|
||||
const allKeys = Object.keys(obj);
|
||||
if (summaryLines.length === 1 && allKeys.length > 0) {
|
||||
summaryLines.push(` 字段列表 (${allKeys.length} 个): ${allKeys.slice(0, 5).join(", ")}${allKeys.length > 5 ? "..." : ""}`);
|
||||
}
|
||||
} else {
|
||||
summaryLines.push(` 出参值: ${String(rawOutput)}`);
|
||||
}
|
||||
|
||||
summaries.push({
|
||||
id: node.id || "-",
|
||||
name: node.name || "-",
|
||||
label: node.label || node.displayName || (type === "code" ? "MVEL代码节点" : "JS代码节点"),
|
||||
type,
|
||||
status: node.status || "UNKNOWN",
|
||||
rawOutput,
|
||||
summaryLines,
|
||||
});
|
||||
}
|
||||
|
||||
return summaries;
|
||||
}
|
||||
|
||||
export function formatCodeNodeSummariesCard(
|
||||
summaries: CodeNodeSummary[],
|
||||
jobId?: string
|
||||
): string[] {
|
||||
if (summaries.length === 0) return [];
|
||||
|
||||
const lines: string[] = [
|
||||
"",
|
||||
"── 🧮 核心代码节点出参即时摘要 (Code Return Values) ──",
|
||||
];
|
||||
|
||||
for (const s of summaries) {
|
||||
const statusIcon = s.status === "COMPLETED" || s.status === "SUCCESS" ? "✅" : s.status === "FAILED" ? "❌" : "⏳";
|
||||
lines.push(` ${statusIcon} [${s.name}] ${s.label} (${s.type}, 状态: ${s.status})`);
|
||||
for (const l of s.summaryLines) {
|
||||
lines.push(` ${l}`);
|
||||
}
|
||||
if (jobId) {
|
||||
lines.push(` ↳ 完整出参查看: hose-use workflow job ${jobId} --node=${s.name} --full`);
|
||||
}
|
||||
}
|
||||
|
||||
return lines;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { expect, spyOn, test } from "bun:test";
|
||||
import { parseArgs } from "../../parser.js";
|
||||
import * as shared from "./shared.js";
|
||||
import { handleWorkflowTailCommand } from "./tail.js";
|
||||
test("CLI tail exits nonzero and emits timeout for a job still running at the deadline", async () => {
|
||||
const client = { get: async (path: string) => Response.json({ data: path.includes("/execution") ? [] : { id: "job", pipelineId: "wf", status: "RUNNING" } }) };
|
||||
const spy = spyOn(shared, "createWorkflowDetailClient").mockResolvedValue({ client } as any);
|
||||
try {
|
||||
const result = await handleWorkflowTailCommand(parseArgs(["workflow", "tail", "wf", "--job", "job", "--timeout", "0.005"]), { jsonMode: true } as any);
|
||||
expect(result.exitCode).toBe(1);
|
||||
const events = result.stdout.trim().split("\n").map(line => JSON.parse(line));
|
||||
expect(events.some(e => e.type === "timeout")).toBe(true);
|
||||
expect(events.some(e => e.type === "job_completed")).toBe(false);
|
||||
} finally { spy.mockRestore(); }
|
||||
});
|
||||
@@ -94,19 +94,19 @@ export async function handleWorkflowTailCommand(
|
||||
return {
|
||||
stdout: printJson(report, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: report.hasFailures ? 1 : 0,
|
||||
exitCode: report.hasFailures || report.timedOut || report.cancelled ? 1 : 0,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: runtime.writeStdout ? "" : outputChunks.join(""),
|
||||
stderr: "",
|
||||
exitCode: report.hasFailures ? 1 : 0,
|
||||
exitCode: report.hasFailures || report.timedOut || report.cancelled ? 1 : 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: runtime.writeStdout ? "" : outputChunks.join(""),
|
||||
stderr: "",
|
||||
exitCode: report.hasFailures ? 1 : 0,
|
||||
exitCode: report.hasFailures || report.timedOut || report.cancelled ? 1 : 0,
|
||||
};
|
||||
}
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
import { stringOption, booleanOption, numberOption } from "../../parser.js";
|
||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { createWorkflowDetailClient } from "./shared.js";
|
||||
import { createWorkflowDetailClient, extractCodeNodeSummaries, formatCodeNodeSummariesCard } from "./shared.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
||||
|
||||
export async function handleWorkflowTest(
|
||||
@@ -58,9 +58,28 @@ export async function handleWorkflowTest(
|
||||
if (isProductionCorp) {
|
||||
warnings.push(`⚠️ 当前企业 [${runtime.selectedCorp?.name || runtime.selectedCorp?.id}] 为正式生产环境 (env: prod)!正式执行时需显式追加 --force 参数。`);
|
||||
}
|
||||
const confirmExecution = () => requireMutationConfirmation(parsed, runtime, "执行工作流调试", `hose-use workflow test ${pipelineId} --yes`);
|
||||
const nextActionCmd = isProductionCorp
|
||||
? `hose-use workflow test ${pipelineId} --yes --force`
|
||||
: `hose-use workflow test ${pipelineId} --yes`;
|
||||
const confirmExecution = () => requireMutationConfirmation(parsed, runtime, "执行工作流调试", nextActionCmd);
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "执行工作流调试", pipelineId, { flowCodeOrId, rawBody, filePath, empty: isEmpty, autoPublish, timeoutMs, warnings });
|
||||
const previewResult = mutationPreview(parsed, runtime, "执行工作流调试", pipelineId, { flowCodeOrId, rawBody, filePath, empty: isEmpty, autoPublish, timeoutMs, warnings });
|
||||
if (isProductionCorp) {
|
||||
if (runtime.jsonMode) {
|
||||
try {
|
||||
const parsedJson = JSON.parse(previewResult.stdout);
|
||||
if (parsedJson.nextAction && !parsedJson.nextAction.includes("--force")) {
|
||||
parsedJson.nextAction = `${parsedJson.nextAction} --force`;
|
||||
previewResult.stdout = `${JSON.stringify(parsedJson, null, 2)}\n`;
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
} else {
|
||||
previewResult.stdout = previewResult.stdout.replace(/--yes/g, "--yes --force");
|
||||
}
|
||||
}
|
||||
return previewResult;
|
||||
}
|
||||
if (flowCodeOrId || rawBody || filePath || isEmpty) confirmExecution();
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
@@ -88,9 +107,39 @@ export async function handleWorkflowTest(
|
||||
}
|
||||
|
||||
case "WEBHOOK": {
|
||||
// 分支 B: Webhook / 外部事件触发器 ── 支持 sample / body / file / empty
|
||||
// 分支 B: Webhook / 外部事件触发器 ── 支持 flow/bill / sample / body / file / empty
|
||||
targetId = "";
|
||||
if (rawBody) {
|
||||
if (flowCodeOrId && !rawBody && !filePath) {
|
||||
try {
|
||||
const { getBillByCodeOrId } = await import("../../../domains/bill/tools.js");
|
||||
const { createSessionClient } = await import("../../../core/http/index.js");
|
||||
const sessionClient = await createSessionClient(runtime.selectedCorp!);
|
||||
const corpId = runtime.selectedCorp?.corpId || runtime.selectedCorp?.id || "";
|
||||
const bills = await getBillByCodeOrId(sessionClient, corpId, flowCodeOrId);
|
||||
const bill = bills[0];
|
||||
if (bill) {
|
||||
customPayload = {
|
||||
code: bill.billCode,
|
||||
flowId: bill.billId,
|
||||
title: bill.title,
|
||||
data: bill,
|
||||
corporationId: corpId,
|
||||
};
|
||||
} else {
|
||||
customPayload = {
|
||||
code: flowCodeOrId,
|
||||
flowId: flowCodeOrId,
|
||||
corporationId: corpId,
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
customPayload = {
|
||||
code: flowCodeOrId,
|
||||
flowId: flowCodeOrId,
|
||||
corporationId: runtime.selectedCorp?.corpId || runtime.selectedCorp?.id,
|
||||
};
|
||||
}
|
||||
} else if (rawBody) {
|
||||
try {
|
||||
customPayload = JSON.parse(rawBody);
|
||||
} catch (e: any) {
|
||||
@@ -435,6 +484,11 @@ export async function handleWorkflowTest(
|
||||
}
|
||||
}
|
||||
|
||||
const codeSummaries = extractCodeNodeSummaries(report.executionTree);
|
||||
if (codeSummaries.length > 0) {
|
||||
outLines.push(...formatCodeNodeSummariesCard(codeSummaries, report.jobId));
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `${outLines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
import { describe, expect, it, spyOn, afterEach } from "bun:test";
|
||||
import { handleWebhookCommand } from "./webhook.js";
|
||||
import * as shared from "./shared.js";
|
||||
import * as services from "../../../domains/platform/services.js";
|
||||
import type { CliParsedArgs, CliRuntime } from "../../types.js";
|
||||
|
||||
function createMockRuntime(overrides: Partial<CliRuntime> = {}): CliRuntime {
|
||||
const corp: any = {
|
||||
id: "corp-1",
|
||||
name: "测试企业",
|
||||
corpId: "corp-1",
|
||||
env: "test",
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
source: "manual",
|
||||
credentials: {
|
||||
corpId: "corp-1",
|
||||
accessToken: "token-1",
|
||||
staffId: "user-1",
|
||||
},
|
||||
};
|
||||
return {
|
||||
corpContext: {
|
||||
listCorps: () => [corp],
|
||||
getCurrent: () => corp,
|
||||
switchCorp: () => true,
|
||||
resolve: () => corp,
|
||||
} as any,
|
||||
selectedCorp: corp,
|
||||
jsonMode: false,
|
||||
outputOptions: {},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("workflow webhook command", () => {
|
||||
let spies: ReturnType<typeof spyOn>[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const spy of spies) {
|
||||
spy.mockRestore();
|
||||
}
|
||||
spies = [];
|
||||
});
|
||||
|
||||
it("prints usage when pipelineId is not provided", async () => {
|
||||
const parsed: CliParsedArgs = {
|
||||
area: "workflow",
|
||||
action: "webhook",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["webhook"],
|
||||
};
|
||||
const runtime = createMockRuntime();
|
||||
const result = await handleWebhookCommand(parsed, runtime);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain("用法: hose-use workflow webhook");
|
||||
});
|
||||
|
||||
it("previews webhook payload in dry-run mode", async () => {
|
||||
const parsed: CliParsedArgs = {
|
||||
area: "workflow",
|
||||
action: "webhook",
|
||||
args: ["send", "881196955148578838"],
|
||||
options: { "dry-run": true, body: '{"foo":"bar"}' },
|
||||
raw: ["send", "881196955148578838", "--dry-run"],
|
||||
};
|
||||
const runtime = createMockRuntime();
|
||||
|
||||
const mockDetail = {
|
||||
id: "881196955148578838",
|
||||
label: "测试 Webhook 工作流",
|
||||
tasks: [
|
||||
{
|
||||
name: "trigger_webhook",
|
||||
type: "webhook",
|
||||
label: "Webhook 触发器",
|
||||
urlPath: "test-token-12345",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
spies.push(
|
||||
spyOn(shared, "createWorkflowDetailClient").mockResolvedValue({
|
||||
client: {} as any,
|
||||
clients: { ekbClient: {} as any } as any,
|
||||
}),
|
||||
spyOn(services, "getWorkflowDetail").mockResolvedValue(mockDetail as any)
|
||||
);
|
||||
|
||||
const result = await handleWebhookCommand(parsed, runtime);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain("[DRY-RUN]");
|
||||
expect(result.stdout).toContain("881196955148578838");
|
||||
expect(result.stdout).toContain("https://piper.ekuaibao.com/api/webhook/test-token-12345");
|
||||
});
|
||||
|
||||
it("rejects non-webhook workflows with clear error", async () => {
|
||||
const parsed: CliParsedArgs = {
|
||||
area: "workflow",
|
||||
action: "webhook",
|
||||
args: ["881196955148578838"],
|
||||
options: { yes: true },
|
||||
raw: ["881196955148578838", "--yes"],
|
||||
};
|
||||
const runtime = createMockRuntime();
|
||||
|
||||
const mockDetail = {
|
||||
id: "881196955148578838",
|
||||
label: "定时触发流程",
|
||||
tasks: [
|
||||
{
|
||||
name: "trigger_clock",
|
||||
type: "clock",
|
||||
label: "定时触发器",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
spies.push(
|
||||
spyOn(shared, "createWorkflowDetailClient").mockResolvedValue({
|
||||
client: {} as any,
|
||||
clients: { ekbClient: {} as any } as any,
|
||||
}),
|
||||
spyOn(services, "getWorkflowDetail").mockResolvedValue(mockDetail as any)
|
||||
);
|
||||
|
||||
const result = await handleWebhookCommand(parsed, runtime);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain("首节点不是 Webhook 触发器");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,227 @@
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import ky from "ky";
|
||||
import { getWorkflowDetail } from "../../../domains/platform/services.js";
|
||||
import { getBillByCodeOrId } from "../../../domains/bill/tools.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson, printKeyValue } from "../../printer.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { createWorkflowDetailClient } from "./shared.js";
|
||||
|
||||
export async function handleWebhookCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const firstArg = parsed.args[0]?.toLowerCase();
|
||||
const isActionVerb = firstArg === "send" || firstArg === "trigger" || firstArg === "post";
|
||||
const pipelineId =
|
||||
(isActionVerb ? parsed.args[1] : parsed.args[0]) ||
|
||||
stringOption(parsed.options, ["id", "pipelineId", "source"]);
|
||||
|
||||
if (!pipelineId) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: [
|
||||
"用法: hose-use workflow webhook [send] <pipelineId> [选项]",
|
||||
"",
|
||||
"说明:",
|
||||
" 向工作流的 Webhook 触发器地址发送测试数据,生成新的数据样本。",
|
||||
" 可彻底解决 Web 控制台复制或新建工作流后【获取更多数据样本】收不到事件的问题。",
|
||||
"",
|
||||
"选项:",
|
||||
" --body='{...}' 指定自定义 JSON 请求体",
|
||||
" --file=<path.json> 从 JSON 文件读取请求体",
|
||||
" --bill=<单号|单据ID> 抓取真实单据数据作为测试载荷发送",
|
||||
" --dry-run 仅预览目标 Webhook 地址与载荷,不实际发送",
|
||||
" --yes 确认发送网络请求",
|
||||
"",
|
||||
"示例:",
|
||||
" hose-use workflow webhook send 881196955148578838 --bill=spWC2AmbRbovsQ --yes",
|
||||
" hose-use workflow webhook 881196955148578838 --body='{\"event\":\"test\"}' --yes",
|
||||
].join("\n") + "\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const { client, clients } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const detail = await getWorkflowDetail(client, pipelineId);
|
||||
|
||||
const triggerNode =
|
||||
detail.tasks?.find(
|
||||
(t) => t.type === "webhook" || t.type === "datalink-button-trigger"
|
||||
) || detail.tasks?.[0];
|
||||
|
||||
const triggerType = triggerNode?.type || "unknown";
|
||||
if (triggerType !== "webhook" && triggerType !== "datalink-button-trigger") {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `❌ 工作流 [${detail.label || pipelineId}] 的首节点不是 Webhook 触发器 (当前类型: ${triggerType})。\n该命令仅适用于以 Webhook 或外部事件为触发源的工作流。\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const rawNode = triggerNode as Record<string, unknown>;
|
||||
const rawPath =
|
||||
(typeof rawNode.urlPath === "string" && rawNode.urlPath) ||
|
||||
(typeof rawNode.url === "string" && rawNode.url) ||
|
||||
(typeof rawNode.path === "string" && rawNode.path);
|
||||
|
||||
if (!rawPath) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `❌ 未能在 Webhook 触发器节点 [${triggerNode?.name || "-"}] 中找到有效的调用路径 (urlPath)。\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const webhookUrl = rawPath.startsWith("http")
|
||||
? rawPath
|
||||
: `https://piper.ekuaibao.com/api/webhook/${rawPath.replace(/^\/+/, "")}`;
|
||||
|
||||
let payload: Record<string, unknown> = {};
|
||||
const rawBody = stringOption(parsed.options, ["body", "data", "payload"]);
|
||||
const filePath = stringOption(parsed.options, ["file", "path"]);
|
||||
const billId = stringOption(parsed.options, ["bill", "flow", "code"]);
|
||||
|
||||
if (billId) {
|
||||
const corpId = runtime.selectedCorp!.corpId || runtime.selectedCorp!.id;
|
||||
try {
|
||||
const bills = await getBillByCodeOrId(clients.ekbClient, corpId, billId);
|
||||
if (!bills.length) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `❌ 未找到单号/ID 为 [${billId}] 的单据\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
const bill = bills[0];
|
||||
payload = {
|
||||
event: "flow.submit",
|
||||
action: "flow.submit",
|
||||
flowId: bill.billId,
|
||||
code: bill.billCode,
|
||||
title: bill.title,
|
||||
data: bill,
|
||||
mockTimestamp: Date.now(),
|
||||
};
|
||||
} catch (err: unknown) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `❌ 抓取单据 [${billId}] 失败: ${err instanceof Error ? err.message : String(err)}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
} else if (rawBody) {
|
||||
try {
|
||||
payload = JSON.parse(rawBody);
|
||||
} catch (e: unknown) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `❌ --body 参数不是合法的 JSON 格式: ${e instanceof Error ? e.message : String(e)}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
} else if (filePath) {
|
||||
if (!existsSync(filePath)) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `❌ 指定的 Payload 文件不存在: ${filePath}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
try {
|
||||
payload = JSON.parse(readFileSync(filePath, "utf-8"));
|
||||
} catch (e: unknown) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `❌ 读取并解析文件 [${filePath}] 失败: ${e instanceof Error ? e.message : String(e)}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
} else {
|
||||
payload = {
|
||||
event: "manual_sample_test",
|
||||
pipelineId,
|
||||
triggerType,
|
||||
timestamp: Date.now(),
|
||||
message: "Sample event injected via hose-use workflow webhook send",
|
||||
};
|
||||
}
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "发送 Webhook 测试事件", pipelineId, {
|
||||
pipelineId,
|
||||
pipelineName: detail.label,
|
||||
targetUrl: webhookUrl,
|
||||
payload,
|
||||
});
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"发送 Webhook 测试事件",
|
||||
`hose-use workflow webhook send ${pipelineId}${billId ? ` --bill=${billId}` : ""} --yes`
|
||||
);
|
||||
|
||||
let responseText = "";
|
||||
let responseStatus = 200;
|
||||
try {
|
||||
const res = await ky.post(webhookUrl, {
|
||||
json: payload,
|
||||
timeout: 15000,
|
||||
throwHttpErrors: false,
|
||||
});
|
||||
responseStatus = res.status;
|
||||
responseText = await res.text();
|
||||
} catch (err: unknown) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `❌ 发送 Webhook 请求失败: ${err instanceof Error ? err.message : String(err)}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const isSuccess = responseStatus >= 200 && responseStatus < 300;
|
||||
const resultData = {
|
||||
pipelineId,
|
||||
pipelineName: detail.label,
|
||||
webhookUrl,
|
||||
statusCode: responseStatus,
|
||||
payloadSize: JSON.stringify(payload).length,
|
||||
response: responseText,
|
||||
success: isSuccess,
|
||||
};
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(resultData, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: isSuccess ? 0 : 2,
|
||||
};
|
||||
}
|
||||
|
||||
const out = [
|
||||
isSuccess ? "✅ Webhook 测试样本已成功发送!" : "⚠️ Webhook 请求已发送但服务端返回非 2xx 状态码:",
|
||||
printKeyValue({
|
||||
"工作流 ID": pipelineId,
|
||||
"工作流名称": detail.label,
|
||||
"Webhook 目标地址": webhookUrl,
|
||||
"HTTP 状态码": String(responseStatus),
|
||||
"载荷字节大小": `${resultData.payloadSize} bytes`,
|
||||
}),
|
||||
"",
|
||||
"服务端响应体:",
|
||||
responseText || "(空响应体)",
|
||||
"",
|
||||
"下一步操作建议:",
|
||||
" 1. Web 控制台: 在工作流首节点触发器中点击【获取更多数据样本】,直接选取刚刚注入的样本;",
|
||||
` 2. 命令行调试: 执行 hose-use workflow test ${pipelineId} --sample=1 进行沙箱运行。`,
|
||||
].join("\n");
|
||||
|
||||
return {
|
||||
stdout: `${out}\n`,
|
||||
stderr: "",
|
||||
exitCode: isSuccess ? 0 : 2,
|
||||
};
|
||||
}
|
||||
+2
-2
@@ -25,12 +25,12 @@ export class MutationConfirmationRequired extends CliError {
|
||||
}
|
||||
|
||||
export function isDryRun(parsed: CliParsedArgs, runtime: CliRuntime): boolean {
|
||||
return runtime.dryRun === true || booleanOption(parsed.options, ["dry-run", "dryRun", "dryrun"]);
|
||||
return (Object.hasOwn(runtime, "dryRun") && runtime.dryRun === true) || booleanOption(parsed.options, ["dry-run", "dryRun", "dryrun"]);
|
||||
}
|
||||
|
||||
export function isConfirmed(parsed: CliParsedArgs, runtime: CliRuntime): boolean {
|
||||
return (
|
||||
runtime.confirmed === true ||
|
||||
(Object.hasOwn(runtime, "confirmed") && runtime.confirmed === true) ||
|
||||
booleanOption(parsed.options, ["yes", "y", "confirm", "force-write"])
|
||||
);
|
||||
}
|
||||
|
||||
+4
-1
@@ -58,7 +58,7 @@ export function isJsonRequested(raw: string[]): boolean {
|
||||
}
|
||||
|
||||
export function parseArgs(rawArgs: string[], areaOverride?: string): CliParsedArgs {
|
||||
const options: Record<string, string | boolean | number> = {};
|
||||
const options: Record<string, string | boolean | number> = Object.create(null);
|
||||
const positional: string[] = [];
|
||||
const context = findContext(rawArgs, areaOverride);
|
||||
const flags = commandFlags(context.area, context.action);
|
||||
@@ -115,6 +115,7 @@ export function stringOption(
|
||||
fallback?: string
|
||||
): string | undefined {
|
||||
for (const k of keys) {
|
||||
if (!Object.hasOwn(options, k)) continue;
|
||||
const val = options[k];
|
||||
if (typeof val === "string" && val.length > 0) return val;
|
||||
}
|
||||
@@ -127,6 +128,7 @@ export function booleanOption(
|
||||
fallback: boolean = false
|
||||
): boolean {
|
||||
for (const k of keys) {
|
||||
if (!Object.hasOwn(options, k)) continue;
|
||||
const val = options[k];
|
||||
if (typeof val === "boolean") return val;
|
||||
if (typeof val === "string") {
|
||||
@@ -144,6 +146,7 @@ export function numberOption(
|
||||
fallback?: number
|
||||
): number | undefined {
|
||||
for (const k of keys) {
|
||||
if (!Object.hasOwn(options, k)) continue;
|
||||
const val = options[k];
|
||||
if (typeof val === "number" && !Number.isNaN(val)) return val;
|
||||
if (typeof val === "string") {
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import { parseArgs, booleanOption, stringOption, numberOption } from "./parser.js";
|
||||
import { isConfirmed, isDryRun } from "./mutation.js";
|
||||
import { applyWorkflowPathPatch } from "../domains/platform/workflow/state/index.js";
|
||||
|
||||
test("rejects prototype paths before mutation and keeps normal patches working", () => {
|
||||
for (const path of ["__proto__.yes", "constructor.prototype.yes", "tasks.__proto__.yes"]) {
|
||||
expect(() => applyWorkflowPathPatch({ tasks: [] } as any, path, true)).toThrow("对象原型");
|
||||
}
|
||||
expect(({} as any).yes).toBeUndefined();
|
||||
expect(applyWorkflowPathPatch({ tasks: [{ code: "old" }] } as any, "tasks.0.code", "new").tasks[0].code).toBe("new");
|
||||
});
|
||||
test("inherited options and runtime fields cannot authorize or change a command", () => {
|
||||
const inherited = Object.create({ yes: true, confirmed: true, dryRun: true, path: "secret", count: 99 });
|
||||
const parsed = { options: inherited } as any;
|
||||
expect(isConfirmed(parsed, inherited)).toBe(false);
|
||||
expect(isDryRun(parsed, inherited)).toBe(false);
|
||||
expect(booleanOption(inherited, ["yes"])).toBe(false);
|
||||
expect(stringOption(inherited, ["path"])).toBeUndefined();
|
||||
expect(numberOption(inherited, ["count"])).toBeUndefined();
|
||||
expect(Object.getPrototypeOf(parseArgs(["version"]).options)).toBeNull();
|
||||
expect(isConfirmed(parseArgs(["message", "read", "m", "--yes"]), {} as any)).toBe(true);
|
||||
});
|
||||
@@ -26,6 +26,7 @@ import { handleContextCommand } from "./commands/context.js";
|
||||
import { handleKeysCommand } from "./commands/keys.js";
|
||||
import { handleStoreCommand } from "./commands/store.js";
|
||||
import { handleFeeTypeCommand } from "./commands/feetype.js";
|
||||
import { handleAssistPlatformCommand } from "./commands/assist-platform/index.js";
|
||||
import { COMMAND_METADATA, type CliCommandMetadata } from "./command-metadata.js";
|
||||
import type { CliParsedArgs, CliResult, CliRunOptions, CliRuntime } from "./types.js";
|
||||
|
||||
@@ -195,6 +196,11 @@ export const CLI_COMMAND_REGISTRY: readonly CliCommandDefinition[] = [
|
||||
standing: true,
|
||||
handler: (parsed, _runtime, options) => handleMcpCommand(parsed, options),
|
||||
},
|
||||
{
|
||||
area: "assist-platform",
|
||||
...COMMAND_METADATA["assist-platform"],
|
||||
handler: (parsed, runtime) => handleAssistPlatformCommand(parsed, runtime),
|
||||
},
|
||||
];
|
||||
|
||||
const COMMAND_LOOKUP = new Map<string, CliCommandDefinition>();
|
||||
|
||||
@@ -58,3 +58,5 @@ src/core/
|
||||
- `getCorpProvisionalAuthLink` 显式指定 `staffId` 时需要已配置的 OpenAPI 密钥;旧员工的 Session Token 不会伪装成目标员工。
|
||||
- 临时换签只返回独立链接,不修改默认身份、Token 或缓存。只有 `persistStaff=true` 才把目标身份、Token、有效期和员工名称一起持久化;同一身份的普通续期保持原行为。
|
||||
- 校验签发身份与目标一致,并在保存成功后更新内存配置;失败时不留下半更新的内存身份。
|
||||
|
||||
子域客户端在 401 后使缓存失效、重新换票,并从新缓存读取请求头重放原请求一次;同一客户端无需重建。持续鉴权失败停止重试,POST 请求体在重放时保持一致。
|
||||
@@ -0,0 +1,73 @@
|
||||
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { join, dirname } from "node:path";
|
||||
import { homedir } from "node:os";
|
||||
import { z } from "zod";
|
||||
|
||||
export const ASSIST_PLATFORM_STORE_PATH = join(
|
||||
homedir(),
|
||||
".config",
|
||||
"hose-use",
|
||||
"assist-platform.json"
|
||||
);
|
||||
|
||||
export function resolveAssistPlatformStorePath(): string {
|
||||
const envFile = process.env.HOSE_ASSIST_PLATFORM_FILE?.trim();
|
||||
if (envFile) return envFile;
|
||||
const stateDir = process.env.HOSE_STATE_DIR?.trim();
|
||||
if (stateDir) return join(stateDir, "assist-platform.json");
|
||||
return ASSIST_PLATFORM_STORE_PATH;
|
||||
}
|
||||
|
||||
export const AssistPlatformSessionSchema = z.object({
|
||||
token: z.string().describe("协助平台 API 会话 Token"),
|
||||
hoseAccessToken: z.string().optional().describe("统一认证 Access Token (JWT)"),
|
||||
userName: z.string().optional().describe("登录运维/客服员工姓名"),
|
||||
userId: z.string().optional().describe("登录用户 ID"),
|
||||
baseUrl: z.string().default("https://unity.ekuaibao.com").describe("协助平台基础服务地址"),
|
||||
updatedAt: z.number().default(() => Date.now()),
|
||||
});
|
||||
|
||||
export type AssistPlatformSession = z.infer<typeof AssistPlatformSessionSchema>;
|
||||
|
||||
function ensureDir(path: string): void {
|
||||
const dir = dirname(path);
|
||||
if (!existsSync(dir)) {
|
||||
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
||||
}
|
||||
try {
|
||||
chmodSync(dir, 0o700);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
export function loadAssistPlatformSession(): AssistPlatformSession | null {
|
||||
const filePath = resolveAssistPlatformStorePath();
|
||||
try {
|
||||
if (!existsSync(filePath)) return null;
|
||||
const content = readFileSync(filePath, "utf-8");
|
||||
const parsed = JSON.parse(content);
|
||||
return AssistPlatformSessionSchema.parse(parsed);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function saveAssistPlatformSession(session: AssistPlatformSession): void {
|
||||
const filePath = resolveAssistPlatformStorePath();
|
||||
ensureDir(filePath);
|
||||
writeFileSync(filePath, JSON.stringify(session, null, 2), {
|
||||
encoding: "utf-8",
|
||||
mode: 0o600,
|
||||
});
|
||||
try {
|
||||
chmodSync(filePath, 0o600);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
export function clearAssistPlatformSession(): void {
|
||||
const filePath = resolveAssistPlatformStorePath();
|
||||
try {
|
||||
if (existsSync(filePath)) {
|
||||
writeFileSync(filePath, "{}", { encoding: "utf-8", mode: 0o600 });
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
@@ -155,10 +155,11 @@ export async function fetchHoseOpenApiAccessToken(params: {
|
||||
);
|
||||
}
|
||||
|
||||
const token = res.value?.accessToken ?? res.accessToken ?? res.token;
|
||||
if (!token) {
|
||||
const rawToken = res.value?.accessToken ?? res.accessToken ?? res.token;
|
||||
if (!rawToken) {
|
||||
throw new AuthenticationError("合思 OpenAPI getAccessToken 未返回有效 accessToken");
|
||||
}
|
||||
const token = decodeURIComponent(rawToken);
|
||||
|
||||
openapiV1TokenCache.set(cacheKey, {
|
||||
token,
|
||||
|
||||
@@ -46,6 +46,14 @@ export const CorpSessionInfoSchema = z.object({
|
||||
loginTime: z.number().nullable().optional().describe("登录时间戳 (ms)"),
|
||||
expTime: z.number().nullable().optional().describe("过期时间戳 (ms)"),
|
||||
sourceChannel: z.string().nullable().optional().describe("来源渠道 (如 APP, WEB)"),
|
||||
departmentName: z.string().nullable().optional().describe("所属部门名称"),
|
||||
roles: z.array(z.string()).nullable().optional().describe("员工角色清单"),
|
||||
roleTitles: z.string().nullable().optional().describe("高管/高级角色头衔"),
|
||||
isSeniorExecutive: z.boolean().nullable().optional().describe("是否包含高管/高级审批角色"),
|
||||
identityComplete: z.boolean().optional().describe("身份画像查询是否完整"),
|
||||
identityUnavailableFields: z.array(z.string()).optional().describe("身份画像未能确认的信息"),
|
||||
riskLevel: z.string().nullable().optional().describe("身份风控等级 (HIGH/MEDIUM/NORMAL/UNKNOWN)"),
|
||||
permissions: z.array(z.string()).nullable().optional().describe("员工功能权限清单"),
|
||||
});
|
||||
export type CorpSessionInfo = z.infer<typeof CorpSessionInfoSchema>;
|
||||
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import ky, { type KyInstance } from "ky";
|
||||
import { AuthenticationError } from "../errors.js";
|
||||
|
||||
export const DEFAULT_ASSIST_PLATFORM_API_URL = "https://unity.ekuaibao.com/api";
|
||||
|
||||
export interface AssistPlatformClientOptions {
|
||||
token: string;
|
||||
baseUrl?: string;
|
||||
hoseAccessToken?: string;
|
||||
timeout?: number;
|
||||
}
|
||||
|
||||
export function createAssistPlatformClient(options: AssistPlatformClientOptions): KyInstance {
|
||||
if (!options.token || !options.token.trim()) {
|
||||
throw new AuthenticationError("缺少协助平台凭证 Token,请先登录协助平台");
|
||||
}
|
||||
|
||||
const baseUrl = options.baseUrl || DEFAULT_ASSIST_PLATFORM_API_URL;
|
||||
const cookieParts: string[] = [];
|
||||
if (options.hoseAccessToken) {
|
||||
cookieParts.push(`hose-access-token=${options.hoseAccessToken}`);
|
||||
}
|
||||
|
||||
return ky.create({
|
||||
prefix: baseUrl,
|
||||
timeout: options.timeout ?? 30000,
|
||||
headers: {
|
||||
accept: "application/json",
|
||||
"content-type": "application/json;charset=UTF-8",
|
||||
token: options.token.trim(),
|
||||
referer: "https://unity.ekuaibao.com/platform-charge/index.html",
|
||||
...(cookieParts.length > 0 ? { cookie: cookieParts.join("; ") } : {}),
|
||||
},
|
||||
hooks: {
|
||||
afterResponse: [
|
||||
async ({ response }) => {
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
throw new AuthenticationError("协助平台凭证已过期或无效,请重新登录协助平台");
|
||||
}
|
||||
return response;
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
+13
-22
@@ -1,4 +1,4 @@
|
||||
import ky, { KyInstance } from "ky";
|
||||
import ky, { KyInstance, type BeforeRequestState } from "ky";
|
||||
|
||||
export interface CreateClientOptions {
|
||||
prefixUrl: string;
|
||||
@@ -24,14 +24,12 @@ export function createClient(options: CreateClientOptions): KyInstance {
|
||||
}
|
||||
|
||||
export function createAuthClient(options: CreateAuthClientOptions): KyInstance {
|
||||
const replays = new WeakMap<object, ReturnType<BeforeRequestState["request"]["clone"]>>();
|
||||
return ky.create({
|
||||
prefix: options.prefixUrl,
|
||||
timeout: options.timeout ?? 30000,
|
||||
retry: {
|
||||
limit: options.retryUnauthorized === false ? 0 : 1,
|
||||
methods: ["get", "post", "put", "delete", "patch"],
|
||||
statusCodes: [401],
|
||||
},
|
||||
// Authentication replay is handled once below; nested retries must not renew repeatedly.
|
||||
retry: 0,
|
||||
hooks: {
|
||||
beforeRequest: [
|
||||
async ({ request }) => {
|
||||
@@ -41,6 +39,7 @@ export function createAuthClient(options: CreateAuthClientOptions): KyInstance {
|
||||
request.headers.set(key, value);
|
||||
}
|
||||
}
|
||||
if (options.onUnauthorized && options.retryUnauthorized !== false) replays.set(request, request.clone());
|
||||
},
|
||||
],
|
||||
afterResponse: [
|
||||
@@ -52,7 +51,10 @@ export function createAuthClient(options: CreateAuthClientOptions): KyInstance {
|
||||
errorType === "UnauthenticatedException" ||
|
||||
errorType === "UnauthorizedException";
|
||||
|
||||
if (isAuthError && options.onUnauthorized) {
|
||||
if (isAuthError && options.onUnauthorized && options.retryUnauthorized !== false) {
|
||||
const replay = replays.get(request);
|
||||
replays.delete(request);
|
||||
if (!replay) throw new Error("Authentication replay request is unavailable");
|
||||
// 触发自动续杯刷新 Token
|
||||
await options.onUnauthorized();
|
||||
|
||||
@@ -60,30 +62,19 @@ export function createAuthClient(options: CreateAuthClientOptions): KyInstance {
|
||||
const freshHeaders = await options.getHeaders();
|
||||
for (const [key, value] of Object.entries(freshHeaders)) {
|
||||
if (value !== undefined) {
|
||||
request.headers.set(key, value);
|
||||
replay.headers.set(key, value);
|
||||
}
|
||||
}
|
||||
return ky(request);
|
||||
// Ky's Request.clone type omits Bun's extra Headers methods; the runtime object is unchanged.
|
||||
return ky(replay as unknown as Request, { retry: 0, timeout: options.timeout ?? 30000 });
|
||||
}
|
||||
if (isAuthError && options.onAuthFailure) {
|
||||
throw options.onAuthFailure(response);
|
||||
}
|
||||
replays.delete(request);
|
||||
return response;
|
||||
},
|
||||
],
|
||||
beforeRetry: [
|
||||
async ({ request }) => {
|
||||
if (options.onUnauthorized) {
|
||||
await options.onUnauthorized();
|
||||
}
|
||||
const headers = await options.getHeaders();
|
||||
for (const [key, value] of Object.entries(headers)) {
|
||||
if (value !== undefined) {
|
||||
request.headers.set(key, value);
|
||||
}
|
||||
}
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -118,13 +118,21 @@ export async function getScriptEngineClient(
|
||||
const cachedHoseToken = mem.hoseToken;
|
||||
return createAuthClient({
|
||||
prefixUrl: SCRIPT_ENGINE_BASE_URL,
|
||||
getHeaders: () => ({
|
||||
Authorization: `Bearer ${cachedJwt}`,
|
||||
platformid: platformId,
|
||||
hoseaccesstoken: cachedHoseToken,
|
||||
}),
|
||||
onUnauthorized: () => {
|
||||
getHeaders: () => {
|
||||
const headers: Record<string, string> = {
|
||||
Authorization: `Bearer ${scriptEngineMemoryCache.get(cacheKey)?.jwt ?? cachedJwt}`,
|
||||
platformid: platformId,
|
||||
};
|
||||
const currentHoseToken = scriptEngineMemoryCache.get(cacheKey)?.hoseToken ?? cachedHoseToken;
|
||||
if (currentHoseToken) {
|
||||
headers.hoseaccesstoken = currentHoseToken;
|
||||
}
|
||||
return headers;
|
||||
},
|
||||
onUnauthorized: async () => {
|
||||
invalidateScriptEngineCache(corp.id, cacheKey);
|
||||
if (canRefreshCorpAccessToken(corp)) await refreshSingleCorpAccessToken(corp);
|
||||
await getScriptEngineClient(corp, platformId);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -142,11 +150,17 @@ export async function getScriptEngineClient(
|
||||
const baseUrl = corp.baseUrl || EKB_BASE_URL;
|
||||
|
||||
// 重新换取
|
||||
const hoseToken = await fetchHoseToken(
|
||||
corp.credentials.accessToken,
|
||||
corpId,
|
||||
environment
|
||||
);
|
||||
let hoseToken = "";
|
||||
try {
|
||||
hoseToken = await fetchHoseToken(
|
||||
corp.credentials.accessToken,
|
||||
corpId,
|
||||
environment
|
||||
);
|
||||
} catch {
|
||||
// 独立私有化域名或部分仅持 OpenAPI 凭证的租户在 business-center 换取 hose-access-token 可能受限,
|
||||
// 此处优雅降级避免阻塞 Piper / ScriptEngine 客户端构建
|
||||
}
|
||||
const easoJwt = await fetchEasoJwt(
|
||||
corp.credentials.accessToken,
|
||||
corpId,
|
||||
@@ -177,13 +191,21 @@ export async function getScriptEngineClient(
|
||||
|
||||
return createAuthClient({
|
||||
prefixUrl: SCRIPT_ENGINE_BASE_URL,
|
||||
getHeaders: () => ({
|
||||
Authorization: `Bearer ${easoJwt}`,
|
||||
platformid: platformId,
|
||||
hoseaccesstoken: hoseToken,
|
||||
}),
|
||||
onUnauthorized: () => {
|
||||
getHeaders: () => {
|
||||
const headers: Record<string, string> = {
|
||||
Authorization: `Bearer ${scriptEngineMemoryCache.get(cacheKey)?.jwt ?? easoJwt}`,
|
||||
platformid: platformId,
|
||||
};
|
||||
const currentHoseToken = scriptEngineMemoryCache.get(cacheKey)?.hoseToken ?? hoseToken;
|
||||
if (currentHoseToken) {
|
||||
headers.hoseaccesstoken = currentHoseToken;
|
||||
}
|
||||
return headers;
|
||||
},
|
||||
onUnauthorized: async () => {
|
||||
invalidateScriptEngineCache(corp.id, cacheKey);
|
||||
if (canRefreshCorpAccessToken(corp)) await refreshSingleCorpAccessToken(corp);
|
||||
await getScriptEngineClient(corp, platformId);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import ky, { type KyInstance } from "ky";
|
||||
import { AuthenticationError } from "../errors.js";
|
||||
|
||||
export const DEFAULT_SSO_BASE_URL = "https://sso.hosecloud.com";
|
||||
|
||||
export interface SsoClientOptions {
|
||||
baseUrl?: string;
|
||||
timeout?: number;
|
||||
}
|
||||
|
||||
export function createSsoClient(options: SsoClientOptions = {}): KyInstance {
|
||||
const baseUrl = options.baseUrl || DEFAULT_SSO_BASE_URL;
|
||||
return ky.create({
|
||||
prefix: baseUrl,
|
||||
timeout: options.timeout ?? 15000,
|
||||
headers: {
|
||||
accept: "application/json, text/plain, */*",
|
||||
"user-agent": "hose-use/assist-platform-client",
|
||||
referer: `${baseUrl}/`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export interface QrCodeStatusResponse {
|
||||
code: number;
|
||||
message: string;
|
||||
data?: {
|
||||
token?: string;
|
||||
ticket?: string;
|
||||
redirectUrl?: string;
|
||||
[key: string]: unknown;
|
||||
} | string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 轮询 HoseCloudSSO 钉钉扫码登录确认状态
|
||||
*/
|
||||
export async function pollSsoQrCodeStatus(
|
||||
client: KyInstance,
|
||||
options: {
|
||||
sessionId?: string;
|
||||
cookie?: string;
|
||||
signal?: AbortSignal;
|
||||
} = {}
|
||||
): Promise<QrCodeStatusResponse> {
|
||||
const headers: Record<string, string> = {};
|
||||
if (options.cookie) {
|
||||
headers.cookie = options.cookie;
|
||||
} else if (options.sessionId) {
|
||||
headers.cookie = `SSO_SESSION_ID=${options.sessionId}`;
|
||||
}
|
||||
|
||||
try {
|
||||
return await client
|
||||
.get("api/v1/user/login/qrcode/status", {
|
||||
searchParams: { _t: Date.now() },
|
||||
headers,
|
||||
signal: options.signal,
|
||||
})
|
||||
.json<QrCodeStatusResponse>();
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.name === "AbortError") {
|
||||
throw error;
|
||||
}
|
||||
throw new AuthenticationError(
|
||||
`SSO 状态轮询异常: ${error instanceof Error ? error.message : String(error)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { afterEach, expect, test } from "bun:test";
|
||||
import { mkdtempSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { getEasoClient, getUnityClient, clearUnityClientCache } from "./unity-client.js";
|
||||
import { getScriptEngineClient, clearScriptEngineClientCache } from "./script-engine-client.js";
|
||||
import { resetTokenStoreMemory, setCorpTokens } from "../auth/token-store.js";
|
||||
const oldFetch = globalThis.fetch, oldFile = process.env.HOSE_TOKENS_FILE;
|
||||
afterEach(() => { clearScriptEngineClientCache(); clearUnityClientCache(); resetTokenStoreMemory(); globalThis.fetch = oldFetch; if (oldFile === undefined) delete process.env.HOSE_TOKENS_FILE; else process.env.HOSE_TOKENS_FILE = oldFile; });
|
||||
for (const kind of ["piper", "easo", "unity"] as const) {
|
||||
for (const denied of [false, true]) {
|
||||
test(`${kind} replaces cached credentials and replays a POST at most once (denied=${denied})`, async () => {
|
||||
process.env.HOSE_TOKENS_FILE = join(mkdtempSync(join(tmpdir(), "hose-renew-")), "tokens.json"); resetTokenStoreMemory();
|
||||
const corp = { id: `renew-${kind}-${denied}`, source: "manual", credentials: { accessToken: "source", corpId: "corp", staffId: "staff" } } as any;
|
||||
const shared = { sourceAccessToken: "source", expiresAt: Date.now() + 3600000 };
|
||||
setCorpTokens(corp.id, { piper: { ...shared, easJwt: "stale", hoseToken: "old-hose" }, unity: { ...shared, unityJwt: "stale" }, eas: { ...shared, easToken: "stale", unityJwt: "stale", hoseToken: "old-hose" } });
|
||||
const sent: Array<{ auth: string | null; body: string }> = [];
|
||||
globalThis.fetch = (async (input: any, init: any) => {
|
||||
const req = input instanceof Request ? input : new Request(input, init);
|
||||
if (req.url.includes("/grant/")) return Response.json({ data: "new-hose" });
|
||||
if (req.url.includes("/actions/jwt")) return Response.json({ id: "fresh" });
|
||||
if (req.url.includes("/realms/")) return Response.json({ value: { accessToken: "fresh" } });
|
||||
sent.push({ auth: req.headers.get("authorization"), body: await req.text() });
|
||||
return denied || req.headers.get("authorization") === "Bearer stale" ? new Response("expired", { status: 401 }) : Response.json({ ok: true });
|
||||
}) as any;
|
||||
const client = kind === "piper" ? await getScriptEngineClient(corp, "app") : kind === "easo" ? (await getEasoClient(corp)).client : (await getUnityClient(corp)).client;
|
||||
const request = client.post("api/review", { json: { amount: 42 } }).json();
|
||||
if (denied) await expect(request).rejects.toThrow(); else expect(await request).toEqual({ ok: true });
|
||||
expect(sent).toEqual([{ auth: "Bearer stale", body: '{"amount":42}' }, { auth: "Bearer fresh", body: '{"amount":42}' }]);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -107,15 +107,18 @@ export async function fetchUnityJwt(
|
||||
export async function fetchEasoRealmToken(
|
||||
corpId: string,
|
||||
unityJwt: string,
|
||||
hoseToken: string
|
||||
hoseToken?: string
|
||||
): Promise<string> {
|
||||
const headers: Record<string, string> = {
|
||||
Authorization: `Bearer ${unityJwt}`,
|
||||
};
|
||||
if (hoseToken) {
|
||||
headers.hoseaccesstoken = hoseToken;
|
||||
}
|
||||
const response = await ky
|
||||
.get(`${EASO_BASE_URL}/api/realms/EASO`, {
|
||||
searchParams: { corpId },
|
||||
headers: {
|
||||
Authorization: `Bearer ${unityJwt}`,
|
||||
hoseaccesstoken: hoseToken,
|
||||
},
|
||||
headers,
|
||||
})
|
||||
.json<{ value?: { accessToken?: string } }>();
|
||||
const token = response.value?.accessToken;
|
||||
@@ -138,9 +141,11 @@ function invalidateEasoCache(corpId: string): void {
|
||||
function invalidateUnityCache(corpId: string): void {
|
||||
unityMemoryCache.delete(`${corpId}:unity`);
|
||||
const persisted = getCorpTokens(corpId);
|
||||
if (persisted?.unity) {
|
||||
if (persisted?.unity || persisted?.eas) {
|
||||
const next = { ...persisted };
|
||||
delete next.unity;
|
||||
// EASO also persists the Unity JWT; do not resurrect the rejected token through that fallback.
|
||||
delete next.eas;
|
||||
setCorpTokens(corpId, next);
|
||||
}
|
||||
}
|
||||
@@ -183,14 +188,22 @@ export async function getEasoClient(corp: CorpConfig): Promise<{
|
||||
return {
|
||||
client: createAuthClient({
|
||||
prefixUrl: EASO_BASE_URL,
|
||||
getHeaders: () => ({
|
||||
Authorization: `Bearer ${cachedToken}`,
|
||||
accesstoken: corp.credentials.accessToken,
|
||||
corporationid: corpId,
|
||||
hoseaccesstoken: cachedHoseToken,
|
||||
}),
|
||||
onUnauthorized: () => {
|
||||
getHeaders: () => {
|
||||
const headers: Record<string, string> = {
|
||||
Authorization: `Bearer ${easoMemoryCache.get(cacheKey)?.token ?? cachedToken}`,
|
||||
accesstoken: corp.credentials.accessToken,
|
||||
corporationid: corpId,
|
||||
};
|
||||
const currentHoseToken = easoMemoryCache.get(cacheKey)?.hoseToken ?? cachedHoseToken;
|
||||
if (currentHoseToken) {
|
||||
headers.hoseaccesstoken = currentHoseToken;
|
||||
}
|
||||
return headers;
|
||||
},
|
||||
onUnauthorized: async () => {
|
||||
invalidateEasoCache(corp.id);
|
||||
if (canRefreshCorpAccessToken(corp)) await refreshSingleCorpAccessToken(corp);
|
||||
await getEasoClient(corp);
|
||||
},
|
||||
}),
|
||||
};
|
||||
@@ -208,11 +221,17 @@ export async function getEasoClient(corp: CorpConfig): Promise<{
|
||||
const baseUrl = corp.baseUrl || EKB_BASE_URL;
|
||||
|
||||
// 重新换取
|
||||
const hoseToken = await fetchHoseToken(
|
||||
corp.credentials.accessToken,
|
||||
corpId,
|
||||
environment
|
||||
);
|
||||
let hoseToken = "";
|
||||
try {
|
||||
hoseToken = await fetchHoseToken(
|
||||
corp.credentials.accessToken,
|
||||
corpId,
|
||||
environment
|
||||
);
|
||||
} catch {
|
||||
// 独立私有化域名或部分仅持 OpenAPI 凭证的租户在 business-center 换取 hose-access-token 可能受限,
|
||||
// 但 EASO Realm 换票仅依赖 Unity JWT 即可完成鉴权,此处降级兼容以避免阻断
|
||||
}
|
||||
const unityJwt = await fetchUnityJwt(
|
||||
corp.credentials.accessToken,
|
||||
corpId,
|
||||
@@ -222,7 +241,7 @@ export async function getEasoClient(corp: CorpConfig): Promise<{
|
||||
const easoToken = await fetchEasoRealmToken(
|
||||
corpId,
|
||||
unityJwt,
|
||||
hoseToken
|
||||
hoseToken || undefined
|
||||
);
|
||||
|
||||
const expiresAt = Date.now() + 2 * 60 * 60 * 1000; // 2小时
|
||||
@@ -261,14 +280,22 @@ export async function getEasoClient(corp: CorpConfig): Promise<{
|
||||
return {
|
||||
client: createAuthClient({
|
||||
prefixUrl: EASO_BASE_URL,
|
||||
getHeaders: () => ({
|
||||
Authorization: `Bearer ${easoToken}`,
|
||||
accesstoken: corp.credentials.accessToken,
|
||||
corporationid: corpId,
|
||||
hoseaccesstoken: hoseToken,
|
||||
}),
|
||||
onUnauthorized: () => {
|
||||
getHeaders: () => {
|
||||
const headers: Record<string, string> = {
|
||||
Authorization: `Bearer ${easoMemoryCache.get(cacheKey)?.token ?? easoToken}`,
|
||||
accesstoken: corp.credentials.accessToken,
|
||||
corporationid: corpId,
|
||||
};
|
||||
const currentHoseToken = easoMemoryCache.get(cacheKey)?.hoseToken ?? hoseToken;
|
||||
if (currentHoseToken) {
|
||||
headers.hoseaccesstoken = currentHoseToken;
|
||||
}
|
||||
return headers;
|
||||
},
|
||||
onUnauthorized: async () => {
|
||||
invalidateEasoCache(corp.id);
|
||||
if (canRefreshCorpAccessToken(corp)) await refreshSingleCorpAccessToken(corp);
|
||||
await getEasoClient(corp);
|
||||
},
|
||||
}),
|
||||
};
|
||||
@@ -314,10 +341,12 @@ export async function getUnityClient(corp: CorpConfig): Promise<{
|
||||
client: createAuthClient({
|
||||
prefixUrl: EASO_BASE_URL,
|
||||
getHeaders: () => ({
|
||||
Authorization: `Bearer ${cachedJwt}`,
|
||||
Authorization: `Bearer ${unityMemoryCache.get(cacheKey)?.token ?? cachedJwt}`,
|
||||
}),
|
||||
onUnauthorized: () => {
|
||||
onUnauthorized: async () => {
|
||||
invalidateUnityCache(corp.id);
|
||||
if (canRefreshCorpAccessToken(corp)) await refreshSingleCorpAccessToken(corp);
|
||||
await getUnityClient(corp);
|
||||
},
|
||||
}),
|
||||
};
|
||||
@@ -364,10 +393,12 @@ export async function getUnityClient(corp: CorpConfig): Promise<{
|
||||
client: createAuthClient({
|
||||
prefixUrl: EASO_BASE_URL,
|
||||
getHeaders: () => ({
|
||||
Authorization: `Bearer ${unityJwt}`,
|
||||
Authorization: `Bearer ${unityMemoryCache.get(cacheKey)?.token ?? unityJwt}`,
|
||||
}),
|
||||
onUnauthorized: () => {
|
||||
onUnauthorized: async () => {
|
||||
invalidateUnityCache(corp.id);
|
||||
if (canRefreshCorpAccessToken(corp)) await refreshSingleCorpAccessToken(corp);
|
||||
await getUnityClient(corp);
|
||||
},
|
||||
}),
|
||||
};
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
本目录按业务域组织代码,每个域独立负责自己的传输层(`api.ts`)、业务编排层(`tools.ts` / `services.ts`)和模型层(`types.ts`)。
|
||||
|
||||
## 当前域(共 14 个)
|
||||
## 当前域(共 15 个)
|
||||
|
||||
| 域 | 内部形态 | 说明 | 详细文档 |
|
||||
|---|---|---|---|
|
||||
@@ -10,6 +10,7 @@
|
||||
| `datalink/` | `api / tools / services / types` | 自建应用下的业务对象、字段、记录检索、安全合并编辑(Read-Modify-Write)、台账体检与导入状态 | [README.datalink.md](./datalink/README.datalink.md) |
|
||||
| `bill/` | `api / tools / translator / types` | 费控单据、报销单、发票、审批流时间线、风控扫描与 Markdown 智能转译器 | [README.bill.md](./bill/README.bill.md) |
|
||||
| `approval/` | `index / gateway / parser / repository / service / db / types` | AI PRO 智能审批引擎(DSL 规则解析、确定性安全网关、要点核验与 `core/db` 会话持久化) | [README.approval.md](./approval/README.approval.md) |
|
||||
| `assist-platform/` | `api / services / types` | 合思协助平台(Unity 运营中心)多租户检索、工单匹配、指定代客员工免密直通与落盘提权 | [README.assist-platform.md](./assist-platform/README.assist-platform.md) |
|
||||
| `store/` | `api / tools / types` | 企业应用中心/应用商店与 OpenAPI 密钥凭证探查 | [README.store.md](./store/README.store.md) |
|
||||
| `feetype/` | `api / tools / types` | 企业费用类型全生命周期管理与字段规格配置 | [README.feetype.md](./feetype/README.feetype.md) |
|
||||
| `contact/` | `api / tools / types` | 企业组织架构(部门树)与员工通讯录检索 | [README.contact.md](./contact/README.contact.md) |
|
||||
@@ -32,6 +33,7 @@
|
||||
- `bill/`:独立拆分 `translator.ts` 负责复杂单据/审批流到结构化 Markdown 的纯函数转译
|
||||
- `approval/`:采用 `parser.ts`(DSL 解析)+ `gateway.ts`(确定性仲裁门禁)+ `repository.ts`(基于 `core/db` 的数据访问)+ `service.ts`(业务编排)
|
||||
- `events/`:组合 `task/` 与 `message/` 域的 `tools.ts` 实现轮询(`poller.ts`),并通过 `store.ts` 落盘至 `core/db`
|
||||
- `assist-platform/`:使用 `services.ts` 封装合思运营平台多租户检索、工单匹配、指定代客员工定位、免密直通换票及与租户存储的联动落盘提权
|
||||
3. **边界与异常约束**(由 `src/cli/architecture-boundaries.test.ts` 强制校验):
|
||||
- 任何入口层(`src/cli/**`, `src/http/**`, `src/server.ts`, `src/cli.ts`, `src/aipro-cli.ts`)严禁直接导入 `domains/*/api.ts`
|
||||
- `domains/*` 严禁反向导入 `cli/`、`http/` 或顶层入口文件
|
||||
|
||||
@@ -15,3 +15,11 @@
|
||||
|
||||
- 决策必须经 gateway 仲裁:`ApprovalDecision` 为封闭枚举(`APPROVE` / `REJECT` / `PASS_WITH_NOTE` / `REVIEW` / `PENDING` / `ERROR`),写动作由 `validateGatewayAction` 卡点。
|
||||
- 规则严格度分四级:`硬性` / `弹性` / `建议` / `特殊`。
|
||||
|
||||
AI PRO 执行真实审批前必须校验会话企业与当前企业、客户端企业一致;企业信息缺失或不一致时拒绝下发,不更新该会话的决策。
|
||||
|
||||
核验状态在批量核验、存储及网关入口均限定为 `PENDING/PASS/FAIL/SKIP`;未知状态拒绝写入,历史异常状态阻断决策。批量状态预检失败不会部分更新要点。
|
||||
|
||||
`approval` 和 AI PRO 的注入、核验与决策支持统一 `--dry-run` 预览;该选项优先于 `--apply --yes`,预览不创建客户端、会话数据库,也不更新核验结果、决策或下发审批。
|
||||
|
||||
审批操作按短 ID、UUID 或单号访问会话时统一检查 6 小时有效期;重新注入会话会刷新有效期。历史日志显式使用只读过期访问,不删除历史记录,也不放宽审批入口。
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
ApprovalFindingRecord,
|
||||
ApprovalGatewayBlockedError,
|
||||
StrictnessTier,
|
||||
isValidFindingCheckStatus,
|
||||
} from "./types.js";
|
||||
|
||||
/**
|
||||
@@ -104,6 +105,7 @@ export function analyzeFindings(findings: ApprovalFindingRecord[]): FindingsAnal
|
||||
const specialFailed: ApprovalFindingRecord[] = [];
|
||||
|
||||
for (const f of findings) {
|
||||
if (!isValidFindingCheckStatus(f.checkStatus)) throw new ApprovalGatewayBlockedError("审核要点包含非法核验状态,禁止审批决策");
|
||||
if (f.checkStatus === "PENDING") {
|
||||
pendingFindings.push(f);
|
||||
} else if (f.checkStatus === "PASS") {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import { getDatabase } from "../../core/db/index.js";
|
||||
import { BusinessError, NotFoundError } from "../../core/errors.js";
|
||||
import { BusinessError, NotFoundError, ValidationError } from "../../core/errors.js";
|
||||
import { parseRuleBody, validatePreferenceText } from "./parser.js";
|
||||
import {
|
||||
AiProLogRecord,
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
ApprovalFindingRecord,
|
||||
ApprovalRunRecord,
|
||||
FindingCheckStatus,
|
||||
isValidFindingCheckStatus,
|
||||
PreferenceRecord,
|
||||
RuleRecord,
|
||||
ScopeDetail,
|
||||
@@ -339,10 +340,11 @@ export class ApprovalRepository {
|
||||
this.db.run(
|
||||
`
|
||||
UPDATE approval_runs
|
||||
SET flow_id = ?, corp_id = ?, scope = ?, decision = ?, decision_summary = ?, matched_rules_count = ?, failed_rules_count = ?, document_snapshot = ?, updated_at = ?
|
||||
SET expires_at = ?, flow_id = ?, corp_id = ?, scope = ?, decision = ?, decision_summary = ?, matched_rules_count = ?, failed_rules_count = ?, document_snapshot = ?, updated_at = ?
|
||||
WHERE id = ?
|
||||
`,
|
||||
[
|
||||
input.expiresAt ?? (now + 6 * 3600 * 1000),
|
||||
(input.flowId !== undefined ? input.flowId : existing.flowId) ?? null,
|
||||
(input.corpId !== undefined ? input.corpId : existing.corpId) ?? null,
|
||||
(input.scope !== undefined ? input.scope : existing.scope) ?? null,
|
||||
@@ -361,25 +363,42 @@ export class ApprovalRepository {
|
||||
return this.createApprovalRun(input);
|
||||
}
|
||||
|
||||
public getRunByHandle(handle: string, corpId?: string): ApprovalRunRecord | null {
|
||||
public getRunByHandle(handle: string, corpId?: string, options: { allowExpired?: boolean } = {}): ApprovalRunRecord | null {
|
||||
const trimmed = handle.trim();
|
||||
const now = Date.now();
|
||||
const requireActive = (run: ApprovalRunRecord | null) => {
|
||||
if (run && corpId !== undefined && run.corpId !== corpId) return null;
|
||||
if (run && run.expiresAt != null && run.expiresAt <= now && !options.allowExpired) {
|
||||
throw new BusinessError(`审批会话 [${trimmed}] 已过期(有效时长 6 小时),请运行 hose-aipro init 重新发起审批会话`);
|
||||
}
|
||||
return run;
|
||||
};
|
||||
// 1. 如果符合 6 位大写短 ID 特征
|
||||
if (/^[A-Za-z0-9]{6}$/.test(trimmed)) {
|
||||
if (options.allowExpired) {
|
||||
const historical = this.db.query("SELECT * FROM approval_runs WHERE UPPER(short_id) = UPPER(?)").get(trimmed) as any;
|
||||
if (historical) {
|
||||
const scoped = requireActive(this.mapRunRow(historical));
|
||||
if (scoped) return scoped;
|
||||
}
|
||||
}
|
||||
const row = this.db
|
||||
.query("SELECT * FROM approval_runs WHERE UPPER(short_id) = UPPER(?) AND (expires_at IS NULL OR expires_at > ?)")
|
||||
.get(trimmed, now) as any;
|
||||
if (row) return this.mapRunRow(row);
|
||||
if (row) {
|
||||
const scoped = requireActive(this.mapRunRow(row));
|
||||
if (scoped) return scoped;
|
||||
}
|
||||
const expiredRow = this.db.query("SELECT * FROM approval_runs WHERE UPPER(short_id) = UPPER(?)").get(trimmed) as any;
|
||||
if (expiredRow) {
|
||||
if (expiredRow && (corpId === undefined || expiredRow.corp_id === corpId)) {
|
||||
throw new BusinessError(`审批会话 [${trimmed}] 已过期(有效时长 6 小时),请运行 hose-aipro init 重新发起审批会话`);
|
||||
}
|
||||
}
|
||||
// 2. 尝试按长 UUID 查找
|
||||
const byId = this.getRunById(trimmed);
|
||||
if (byId) return byId;
|
||||
if (byId) return requireActive(byId);
|
||||
// 3. 尝试按单号查找最新未过期的运行记录
|
||||
return this.getLatestRunBySn(trimmed, corpId);
|
||||
return requireActive(this.getLatestRunBySn(trimmed, corpId));
|
||||
}
|
||||
|
||||
public getLatestRunBySn(documentSn: string, corpId?: string): ApprovalRunRecord | null {
|
||||
@@ -472,6 +491,10 @@ export class ApprovalRepository {
|
||||
throw new NotFoundError(`审批运行记录不存在: ${runId}`);
|
||||
}
|
||||
|
||||
for (const finding of findings) {
|
||||
if (!isValidFindingCheckStatus(finding.checkStatus ?? "PENDING")) throw new ValidationError("核验状态必须为 PENDING、PASS、FAIL 或 SKIP");
|
||||
}
|
||||
|
||||
// 重新挂载时清空旧要点
|
||||
this.db.run("DELETE FROM approval_findings WHERE run_id = ?", [runId]);
|
||||
|
||||
@@ -526,6 +549,7 @@ export class ApprovalRepository {
|
||||
}
|
||||
|
||||
const checkStatus = updates.checkStatus ?? row.check_status;
|
||||
if (!isValidFindingCheckStatus(checkStatus)) throw new ValidationError("核验状态必须为 PENDING、PASS、FAIL 或 SKIP");
|
||||
const evidence = updates.evidence !== undefined ? updates.evidence : row.evidence;
|
||||
const reasoning = updates.reasoning !== undefined ? updates.reasoning : row.reasoning;
|
||||
|
||||
@@ -546,7 +570,7 @@ export class ApprovalRepository {
|
||||
run: ApprovalRunRecord | null;
|
||||
findings: ApprovalFindingRecord[];
|
||||
} {
|
||||
const run = this.getLatestRunBySn(documentSn, corpId);
|
||||
const run = this.getRunByHandle(documentSn, corpId);
|
||||
if (!run) {
|
||||
return { run: null, findings: [] };
|
||||
}
|
||||
@@ -586,7 +610,7 @@ export class ApprovalRepository {
|
||||
return {
|
||||
id: row.id,
|
||||
shortId: row.short_id ?? null,
|
||||
expiresAt: row.expires_at ? Number(row.expires_at) : null,
|
||||
expiresAt: row.expires_at != null ? Number(row.expires_at) : null,
|
||||
flowId: row.flow_id,
|
||||
documentSn: row.document_sn,
|
||||
corpId: row.corp_id,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { KyInstance } from "ky";
|
||||
import { BusinessError, NotFoundError } from "../../core/errors.js";
|
||||
import { BusinessError, NotFoundError, ValidationError } from "../../core/errors.js";
|
||||
import { ApprovalRepository } from "./repository.js";
|
||||
import { parseRuleBody } from "./parser.js";
|
||||
import {
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
ApprovalGatewayBlockedError,
|
||||
ApprovalRunRecord,
|
||||
FindingCheckStatus,
|
||||
isValidFindingCheckStatus,
|
||||
} from "./types.js";
|
||||
import {
|
||||
ApprovalGatewayPolicy,
|
||||
@@ -184,6 +185,9 @@ export class ApprovalService {
|
||||
);
|
||||
}
|
||||
|
||||
if (evaluations.some(item => !isValidFindingCheckStatus(item.status))) {
|
||||
throw new ValidationError("核验状态必须为 PENDING、PASS、FAIL 或 SKIP");
|
||||
}
|
||||
for (const item of evaluations) {
|
||||
let target: ApprovalFindingRecord | undefined;
|
||||
if (item.id) {
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { afterEach, expect, test } from "bun:test";
|
||||
import { getDatabase, closeDatabase } from "../../core/db/index.js";
|
||||
import { ApprovalRepository } from "./repository.js";
|
||||
|
||||
afterEach(closeDatabase);
|
||||
test("all operation handles reject expired sessions while history remains readable", async () => {
|
||||
const repo = new ApprovalRepository(getDatabase(":memory:"));
|
||||
const run = repo.createApprovalRun({ documentSn: "EXPIRED-SN", corpId: "corp", expiresAt: Date.now() - 1000 });
|
||||
for (const handle of [run.shortId!, run.id, run.documentSn]) {
|
||||
expect(() => repo.getRunByHandle(handle)).toThrow("已过期");
|
||||
expect(repo.getRunByHandle(handle, undefined, { allowExpired: true })?.id).toBe(run.id);
|
||||
}
|
||||
repo.logAiProAction({ action: "init", runId: run.shortId, documentSn: run.documentSn });
|
||||
expect(repo.getRunById(run.id)?.id).toBe(run.id);
|
||||
const reset = repo.createOrResetApprovalRun({ documentSn: run.documentSn, corpId: "corp" });
|
||||
expect(reset.expiresAt!).toBeGreaterThan(Date.now());
|
||||
expect(repo.getRunByHandle(run.shortId!)?.id).toBe(run.id);
|
||||
});
|
||||
|
||||
test("epoch-zero expiry is expired rather than an unlimited session", () => {
|
||||
const repo = new ApprovalRepository(getDatabase(":memory:"));
|
||||
const run = repo.createApprovalRun({ documentSn: "ZERO-SN", expiresAt: 0 });
|
||||
for (const handle of [run.shortId!, run.id, run.documentSn]) expect(() => repo.getRunByHandle(handle)).toThrow("已过期");
|
||||
});
|
||||
|
||||
test("checklist operations enforce expiry and scoped handles cannot select another corporation", () => {
|
||||
const repo = new ApprovalRepository(getDatabase(":memory:"));
|
||||
const expired = repo.createApprovalRun({ documentSn: "OLD-SN", corpId: "A", expiresAt: Date.now() - 1 });
|
||||
expect(() => repo.getAuditChecklist(expired.documentSn, "A")).toThrow("已过期");
|
||||
const live = repo.createApprovalRun({ documentSn: "LIVE-SN", corpId: "A" });
|
||||
expect(repo.getRunByHandle(live.shortId!, "B")).toBeNull();
|
||||
expect(repo.getRunByHandle(live.id, "B")).toBeNull();
|
||||
expect(repo.getAuditChecklist(live.documentSn, "B").run).toBeNull();
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import { afterEach, expect, test } from "bun:test";
|
||||
import { getDatabase, closeDatabase } from "../../core/db/index.js";
|
||||
import { ApprovalRepository } from "./repository.js";
|
||||
import { ApprovalService } from "./service.js";
|
||||
import { evaluateGatewayPolicy } from "./gateway.js";
|
||||
|
||||
afterEach(closeDatabase);
|
||||
test("rejects unknown status before updates and blocks corrupt persisted findings", () => {
|
||||
const db = getDatabase(":memory:");
|
||||
const repo = new ApprovalRepository(db);
|
||||
const run = repo.createApprovalRun({ documentSn: "SN", corpId: "corp" });
|
||||
const findings = repo.injectFindings(run.id, [{ clauseText: "invoice", strictness: "硬性", checkStatus: "PENDING" }, { clauseText: "amount", strictness: "硬性", checkStatus: "PENDING" }]);
|
||||
expect(() => repo.updateFinding(findings[0].id, { checkStatus: "TYPO" as any })).toThrow("核验状态");
|
||||
expect(() => new ApprovalService(repo).evaluateAuditPoints("SN", [{ index: 1, status: "PASS" }, { index: 2, status: "TYPO" as any }], "corp")).toThrow("核验状态");
|
||||
expect(repo.getFindingsByRunId(run.id).map(f => f.checkStatus)).toEqual(["PENDING", "PENDING"]);
|
||||
expect(() => repo.injectFindings(run.id, [{ clauseText: "bad", strictness: "硬性", checkStatus: "TYPO" as any }])).toThrow("核验状态");
|
||||
expect(repo.getFindingsByRunId(run.id)).toHaveLength(2);
|
||||
db.run("UPDATE approval_findings SET check_status = 'TYPO' WHERE run_id = ?", [run.id]);
|
||||
expect(() => evaluateGatewayPolicy({ documentSn: "SN", findings: repo.getFindingsByRunId(run.id) })).toThrow("非法核验状态");
|
||||
});
|
||||
@@ -94,6 +94,10 @@ export interface ApprovalRunRecord {
|
||||
|
||||
export type FindingCheckStatus = "PENDING" | "PASS" | "FAIL" | "SKIP";
|
||||
|
||||
export function isValidFindingCheckStatus(value: unknown): value is FindingCheckStatus {
|
||||
return typeof value === "string" && ["PENDING", "PASS", "FAIL", "SKIP"].includes(value);
|
||||
}
|
||||
|
||||
export interface ApprovalFindingRecord {
|
||||
id: string;
|
||||
runId: string;
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
# Assist Platform (合思协助平台 / 运营平台) 域说明
|
||||
|
||||
本域负责对接合思官方内部运营平台(Unity Assist Platform,`https://unity.ekuaibao.com/platform-charge/`)及其 SSO 统一身份认证服务(`https://sso.hosecloud.com`)。
|
||||
|
||||
## 架构与分工
|
||||
|
||||
- **SSO 身份客户端 (`src/core/http/sso-client.ts`)**:
|
||||
负责与 `sso.hosecloud.com` 的登录二维码生成、扫码状态轮询以及凭证提取。
|
||||
- **协助平台网关客户端 (`src/core/http/assist-platform-client.ts`)**:
|
||||
负责与 `unity.ekuaibao.com/api` 网关通信,自动挂载 `token: <sessionToken>` 请求头与 Cookie。
|
||||
- **协助平台本地凭证安全存储 (`src/core/auth/assist-platform-store.ts`)**:
|
||||
将协助平台会话安全持久化在 `~/.config/hose-use/assist-platform.json`(权限 0600)。
|
||||
- **传输层 (`api.ts`)**:
|
||||
封装协助中心全部核心 REST API 并通过 Zod 进行响应强校验。
|
||||
- **业务编排层 (`services.ts`)**:
|
||||
纯函数式高阶编排,包括企业检索、协助工单提取、员工匹配定位、免密直通 Token 换取,以及无缝对接 `corps.importFromLink` 的一键落盘与 OpenAPI 自动提权。
|
||||
- **模型层 (`types.ts`)**:
|
||||
企业信息、工单列表、员工信息、直通链接及入参强类型定义。
|
||||
|
||||
## 关键 API
|
||||
|
||||
- `searchCorporations`: 全量企业库检索(按关键词/企业 ID)
|
||||
- `getCorporationDetail`: 查询企业详细画像与开通版本
|
||||
- `listAssistTickets`: 查询企业生效中的协助工单(包含 ticketId、原因、有效期、申请人)
|
||||
- `searchStaffList`: 查询企业内部员工名单(用于指定代客身份时的 staffId 定位)
|
||||
- `getAssistToken`: 换取免密代客登录链接与临时 JWT凭证
|
||||
|
||||
## 会话生成、导入与身份完整度
|
||||
|
||||
- `assist-platform enter <corpId> --dry-run` 在换票、身份查询和落盘前返回预览;无论是否带 `--save` / `--switch`,均不需要协助平台登录,也不会发出网络请求。
|
||||
- `--save --yes` 导入后同步注册当前企业上下文;`--switch` 仅在实际切换成功后输出 `switched: true`。失败时说明配置已保存并提示重试切换。
|
||||
- 生成成功的文本与 JSON 明确交付会话 Token 和可用免密链接,使用 CLI 受控凭证输出机制;捕获的诊断日志和错误继续统一脱敏。
|
||||
- 导入默认沿用底层最佳努力 OpenAPI 密钥提取:无密钥、无读取权限或存在多个密钥均不阻止有效临时会话保存。SDK 显式 `elevate: true` 仍要求成功提取密钥,`elevate: false` 跳过提取。
|
||||
- 身份画像输出可选的 `profileComplete` / `unavailableFields`,配置 `session` 对应保存可选的 `identityComplete` / `identityUnavailableFields`;旧配置仍可读取。员工、管理员标记、角色、权限或部门查询缺失时,完整度为 false;未知的 `isAdmin` / `isSeniorExecutive` 为 null,缺乏已知高风险证据时 `riskLevel` 为 `UNKNOWN`,不会假装 `NORMAL`。
|
||||
- 已知管理员、角色或高权限证据仍显示 HIGH/MEDIUM;导入时补用 JWT 已确认的身份。同一员工的历史权限及高风险状态不会因本次探测不完整而被降级,其他员工的画像不会被沿用。
|
||||
|
||||
SDK 消费者应处理画像布尔值的 null 和新增的 UNKNOWN 风险枚举;会话结果顶层 `isAdmin` 仍表示请求的授权模式,其 boolean 类型不变。
|
||||
|
||||
## 审批与转交目标解析
|
||||
|
||||
- `approve <工单ID> --corp <企业ID>`:显式 `--corp` 下,唯一位置参数始终为工单 ID;也支持 `approve <企业ID> <工单ID>`、`approve <企业ID> --ticket <工单ID>`,以及使用当前企业的 `approve <工单ID>` / `approve --ticket <工单ID>`。位置工单与 `--ticket` 不一致或位置参数多余时拒绝执行;只有完全未指定工单时才自动查询待授权工单。
|
||||
- 转交收件人依次按账号 ID、工号、姓名精确匹配,再尝试模糊匹配。同一账号的多条角色记录按用户 ID 去重;同一匹配级别命中多个用户时拒绝选择,须改用唯一工号或账号。
|
||||
- 转交的 dry-run 与执行使用相同的收件人解析规则。歧义、未找到人员或查询失败都会终止,不会将未解析的输入直接提交给转交接口。
|
||||
@@ -0,0 +1,589 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { EkbApiError, BusinessError, NotFoundError } from "../../core/errors.js";
|
||||
import type {
|
||||
AssistPlatformCorporation,
|
||||
AssistPlatformStaff,
|
||||
AssistPlatformTicket,
|
||||
CorporationDetail,
|
||||
StaffRoleItem,
|
||||
AssistIdentityUnavailableField,
|
||||
TransferCandidate,
|
||||
TransferTicketParams,
|
||||
} from "./types.js";
|
||||
|
||||
export interface SearchCorporationsApiParams {
|
||||
keyword?: string;
|
||||
state?: string;
|
||||
limit?: {
|
||||
start: number;
|
||||
count: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface SearchCorporationsApiResponse {
|
||||
count: number;
|
||||
items: AssistPlatformCorporation[];
|
||||
}
|
||||
|
||||
export async function searchCorporationsApi(
|
||||
client: KyInstance,
|
||||
params: SearchCorporationsApiParams = {}
|
||||
): Promise<SearchCorporationsApiResponse> {
|
||||
const requestBody: Record<string, unknown> = {
|
||||
limit: {
|
||||
start: params.limit?.start ?? 0,
|
||||
count: params.limit?.count ?? 20,
|
||||
},
|
||||
};
|
||||
|
||||
const conditions: string[] = [];
|
||||
if (params.keyword?.trim()) {
|
||||
const kw = params.keyword.trim().replace(/"/g, '\\"');
|
||||
conditions.push(`(id == "${kw}" || name == "${kw}")`);
|
||||
}
|
||||
if (params.state?.trim()) {
|
||||
const st = params.state.trim().replace(/"/g, '\\"');
|
||||
conditions.push(`state == "${st}"`);
|
||||
}
|
||||
if (conditions.length > 0) {
|
||||
requestBody.filterBy = conditions.join(" && ");
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await client
|
||||
.post("corporation/search", {
|
||||
json: requestBody,
|
||||
})
|
||||
.json<{ count?: number; items?: AssistPlatformCorporation[] }>();
|
||||
|
||||
return {
|
||||
count: res.count ?? (res.items?.length || 0),
|
||||
items: res.items || [],
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.name === "AuthenticationError") throw error;
|
||||
throw new EkbApiError(
|
||||
`查询协助企业列表失败: ${error instanceof Error ? error.message : String(error)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getCorporationDetailApi(
|
||||
client: KyInstance,
|
||||
corpId: string
|
||||
): Promise<CorporationDetail> {
|
||||
if (!corpId || !corpId.trim()) {
|
||||
throw new BusinessError("必须指定企业 ID");
|
||||
}
|
||||
|
||||
const cleanId = corpId.trim();
|
||||
const normalizedId = cleanId.startsWith("$") ? cleanId : `$${cleanId}`;
|
||||
|
||||
try {
|
||||
const res = await client
|
||||
.get(`corporation/${normalizedId}/getCorporationDetail`)
|
||||
.json<{ items?: CorporationDetail[] }>();
|
||||
|
||||
const detail = res.items?.[0];
|
||||
if (!detail) {
|
||||
throw new NotFoundError(`未找到企业 [${corpId}] 的详细业务配置`);
|
||||
}
|
||||
return detail;
|
||||
} catch (error) {
|
||||
if (error instanceof Error && (error.name === "AuthenticationError" || error.name === "NotFoundError")) {
|
||||
throw error;
|
||||
}
|
||||
throw new EkbApiError(
|
||||
`获取企业 [${corpId}] 详情失败: ${error instanceof Error ? error.message : String(error)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function searchAssistTicketsApi(
|
||||
client: KyInstance,
|
||||
corpId: string
|
||||
): Promise<AssistPlatformTicket[]> {
|
||||
if (!corpId || !corpId.trim()) {
|
||||
throw new BusinessError("必须指定企业 ID");
|
||||
}
|
||||
|
||||
const cleanId = corpId.trim();
|
||||
const normalizedId = cleanId.startsWith("$") ? cleanId : `$${cleanId}`;
|
||||
|
||||
try {
|
||||
const res = await client
|
||||
.post(`assistPlatform/${normalizedId}/search`, {
|
||||
json: { query: {} },
|
||||
})
|
||||
.json<{ items?: Array<Record<string, unknown>> }>();
|
||||
|
||||
const rawItems = res.items || [];
|
||||
return rawItems.map((item) => {
|
||||
const startTime = typeof item.startTime === "number" ? item.startTime : undefined;
|
||||
const endTime = typeof item.endTime === "number" ? item.endTime : undefined;
|
||||
const usePeriodDesc = (startTime && endTime)
|
||||
? `${new Date(startTime).toLocaleString("zh-CN", { hour12: false })} 至 ${new Date(endTime).toLocaleString("zh-CN", { hour12: false })}`
|
||||
: undefined;
|
||||
|
||||
const rawStatus = item.state ?? item.status;
|
||||
const stateStr = rawStatus !== undefined && rawStatus !== null ? String(rawStatus) : "未知状态";
|
||||
|
||||
return {
|
||||
id: String(item.id || item.ticketId || ""),
|
||||
ticketId: String(item.ticketId || item.id || item.authCode || ""),
|
||||
applicant: String(item.applicant || item.applyUserName || item.userName || "未知申请人"),
|
||||
applicantId: item.applicantId ? String(item.applicantId) : undefined,
|
||||
principal: item.principal ? String(item.principal) : (item.operationUserName ? String(item.operationUserName) : undefined),
|
||||
principalId: item.principalId ? String(item.principalId) : undefined,
|
||||
state: stateStr,
|
||||
duration: typeof item.duration === "number" ? item.duration : (typeof item.hours === "number" ? item.hours : undefined),
|
||||
startTime,
|
||||
endTime,
|
||||
usePeriodDesc,
|
||||
matter: item.matter ? String(item.matter) : undefined,
|
||||
createTime: typeof item.createTime === "number" ? item.createTime : undefined,
|
||||
};
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.name === "AuthenticationError") throw error;
|
||||
throw new EkbApiError(
|
||||
`查询企业 [${corpId}] 协助工单失败: ${error instanceof Error ? error.message : String(error)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getStaffApi(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
name: string
|
||||
): Promise<AssistPlatformStaff[]> {
|
||||
if (!corpId || !corpId.trim()) throw new BusinessError("必须指定企业 ID");
|
||||
if (!name || !name.trim()) throw new BusinessError("必须指定要查询的用户姓名");
|
||||
|
||||
try {
|
||||
const res = await client
|
||||
.post("assistPlatform/getStaff", {
|
||||
json: {
|
||||
corporationId: corpId.trim(),
|
||||
name: name.trim(),
|
||||
},
|
||||
})
|
||||
.json<{ total?: number; items?: Array<Record<string, unknown>> }>();
|
||||
|
||||
const items = res.items || [];
|
||||
return items.map((raw) => ({
|
||||
id: String(raw.id || ""),
|
||||
code: raw.code ? String(raw.code) : undefined,
|
||||
name: String(raw.name || name),
|
||||
email: raw.email ? String(raw.email) : undefined,
|
||||
cellphone: raw.cellphone ? String(raw.cellphone) : undefined,
|
||||
admin: Boolean(raw.admin),
|
||||
userId: raw.userId ? String(raw.userId) : undefined,
|
||||
corporationId: String(raw.corporationId || corpId),
|
||||
departments: Array.isArray(raw.departments) ? raw.departments.map(String) : [],
|
||||
active: raw.active !== false,
|
||||
}));
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.name === "AuthenticationError") throw error;
|
||||
throw new EkbApiError(
|
||||
`查询企业员工 [${name}] 失败: ${error instanceof Error ? error.message : String(error)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export interface GetAssistTokenApiParams {
|
||||
ticketId: string;
|
||||
corporationId: string;
|
||||
isAdmin: boolean;
|
||||
staffId?: string;
|
||||
}
|
||||
|
||||
export interface GetAssistTokenApiResponse {
|
||||
token: string;
|
||||
loginUrl: string;
|
||||
baseUrl: string;
|
||||
}
|
||||
|
||||
export async function getAssistTokenApi(
|
||||
client: KyInstance,
|
||||
params: GetAssistTokenApiParams
|
||||
): Promise<GetAssistTokenApiResponse> {
|
||||
const { ticketId, corporationId, isAdmin, staffId } = params;
|
||||
if (!ticketId) throw new BusinessError("缺少协助授权码 ticketId");
|
||||
if (!corporationId) throw new BusinessError("缺少企业 ID corporationId");
|
||||
|
||||
const body: Record<string, unknown> = {
|
||||
ticketId,
|
||||
corporationId,
|
||||
isAdmin,
|
||||
};
|
||||
if (!isAdmin && staffId) {
|
||||
body.staffId = staffId;
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await client
|
||||
.post("assistPlatform/getToken", {
|
||||
json: body,
|
||||
})
|
||||
.json<{
|
||||
value?: {
|
||||
token?: string;
|
||||
loginUrl?: string;
|
||||
baseUrl?: string;
|
||||
};
|
||||
}>();
|
||||
|
||||
if (!res.value?.token || !res.value?.loginUrl) {
|
||||
throw new BusinessError("协助平台服务端未返回有效免密直通链接");
|
||||
}
|
||||
|
||||
return {
|
||||
token: res.value.token,
|
||||
loginUrl: res.value.loginUrl,
|
||||
baseUrl: res.value.baseUrl || "https://app.ekuaibao.com",
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof Error && (error.name === "AuthenticationError" || error.name === "BusinessError")) {
|
||||
throw error;
|
||||
}
|
||||
throw new EkbApiError(
|
||||
`换取协助免密链接失败: ${error instanceof Error ? error.message : String(error)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export interface CreateAssistTicketApiParams {
|
||||
corporationId: string;
|
||||
applyMessage?: string;
|
||||
assistTime?: number; // 毫秒,默认 24 小时
|
||||
}
|
||||
|
||||
export interface CreateAssistTicketApiResponse {
|
||||
id: string;
|
||||
corporationId: string;
|
||||
applyMessage: string;
|
||||
assistTime: number;
|
||||
userName?: string;
|
||||
responsibleUserName?: string;
|
||||
status: number;
|
||||
}
|
||||
|
||||
export async function createAssistTicketApi(
|
||||
client: KyInstance,
|
||||
params: CreateAssistTicketApiParams
|
||||
): Promise<CreateAssistTicketApiResponse> {
|
||||
const { corporationId, applyMessage, assistTime } = params;
|
||||
if (!corporationId || !corporationId.trim()) {
|
||||
throw new BusinessError("必须指定目标企业 ID");
|
||||
}
|
||||
|
||||
const durationMs = assistTime ?? 24 * 3600 * 1000;
|
||||
const message = applyMessage?.trim() || "自动化联调与测试";
|
||||
|
||||
try {
|
||||
const res = await client
|
||||
.post("assistPlatform/create", {
|
||||
json: {
|
||||
corporationId: corporationId.trim(),
|
||||
applyMessage: message,
|
||||
assistTime: durationMs,
|
||||
},
|
||||
})
|
||||
.json<{
|
||||
value?: Record<string, unknown>;
|
||||
}>();
|
||||
|
||||
const val = res.value || {};
|
||||
return {
|
||||
id: String(val.id || ""),
|
||||
corporationId: String(val.corporationId || corporationId),
|
||||
applyMessage: String(val.applyMessage || message),
|
||||
assistTime: typeof val.assistTime === "number" ? val.assistTime : durationMs,
|
||||
userName: val.userName ? String(val.userName) : undefined,
|
||||
responsibleUserName: val.responsibleUserName ? String(val.responsibleUserName) : undefined,
|
||||
status: typeof val.status === "number" ? val.status : 0,
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof Error && (error.name === "AuthenticationError" || error.name === "BusinessError")) {
|
||||
throw error;
|
||||
}
|
||||
throw new EkbApiError(
|
||||
`发起协助工单申请失败: ${error instanceof Error ? error.message : String(error)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export interface ApproveAssistTicketApiParams {
|
||||
ticketId: string;
|
||||
corporationId: string;
|
||||
status?: number; // 默认 1 (通过授权 / 已提供)
|
||||
}
|
||||
|
||||
export interface ApproveAssistTicketApiResponse {
|
||||
id: string;
|
||||
corporationId: string;
|
||||
status: number;
|
||||
active: boolean;
|
||||
startTime: number;
|
||||
endTime: number;
|
||||
applyMessage: string;
|
||||
userName?: string;
|
||||
responsibleUserName?: string;
|
||||
}
|
||||
|
||||
export async function approveAssistTicketApi(
|
||||
client: KyInstance,
|
||||
params: ApproveAssistTicketApiParams
|
||||
): Promise<ApproveAssistTicketApiResponse> {
|
||||
const { ticketId, corporationId, status = 1 } = params;
|
||||
if (!ticketId || !ticketId.trim()) {
|
||||
throw new BusinessError("必须指定协助工单编号 (ticketId)");
|
||||
}
|
||||
if (!corporationId || !corporationId.trim()) {
|
||||
throw new BusinessError("必须指定目标企业 ID (corporationId)");
|
||||
}
|
||||
|
||||
const cleanTicketId = ticketId.trim();
|
||||
const cleanCorpId = corporationId.trim();
|
||||
|
||||
try {
|
||||
const res = await client
|
||||
.put(`api/assistPlatform/$${cleanTicketId}/updateStatus`, {
|
||||
searchParams: {
|
||||
corpId: cleanCorpId,
|
||||
},
|
||||
json: {
|
||||
id: cleanTicketId,
|
||||
status,
|
||||
},
|
||||
})
|
||||
.json<{
|
||||
value?: Record<string, unknown>;
|
||||
}>();
|
||||
|
||||
const val = res.value || {};
|
||||
return {
|
||||
id: String(val.id || cleanTicketId),
|
||||
corporationId: String(val.corporationId || cleanCorpId),
|
||||
status: typeof val.status === "number" ? val.status : status,
|
||||
active: Boolean(val.active),
|
||||
startTime: Number(val.startTime || 0),
|
||||
endTime: Number(val.endTime || 0),
|
||||
applyMessage: String(val.applyMessage || ""),
|
||||
userName: val.userName ? String(val.userName) : undefined,
|
||||
responsibleUserName: val.responsibleUserName ? String(val.responsibleUserName) : undefined,
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof Error && (error.name === "AuthenticationError" || error.name === "BusinessError")) {
|
||||
throw error;
|
||||
}
|
||||
throw new EkbApiError(
|
||||
`审批协助工单失败: ${error instanceof Error ? error.message : String(error)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getStaffMeAndRolesApi(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
staffId?: string
|
||||
): Promise<{
|
||||
staff: Record<string, unknown>;
|
||||
permissions: string[];
|
||||
roles: StaffRoleItem[];
|
||||
departmentName?: string;
|
||||
unavailableFields: AssistIdentityUnavailableField[];
|
||||
}> {
|
||||
let staff: Record<string, unknown> = {};
|
||||
let permissions: string[] = [];
|
||||
const unavailableFields = new Set<AssistIdentityUnavailableField>(["staff", "admin", "permissions", "roles"]);
|
||||
|
||||
try {
|
||||
const meRes = await client
|
||||
.get("api/v1/organization/staffs/me", {
|
||||
searchParams: { corpId },
|
||||
})
|
||||
.json<{
|
||||
value?: {
|
||||
staff?: Record<string, unknown>;
|
||||
permissions?: string[];
|
||||
};
|
||||
}>();
|
||||
if (meRes.value?.staff) {
|
||||
staff = meRes.value.staff;
|
||||
if (staff.id) unavailableFields.delete("staff");
|
||||
if (typeof staff.admin === "boolean") unavailableFields.delete("admin");
|
||||
}
|
||||
if (Array.isArray(meRes.value?.permissions) && meRes.value.permissions.every((permission) => typeof permission === "string")) {
|
||||
permissions = meRes.value.permissions.map(String);
|
||||
unavailableFields.delete("permissions");
|
||||
}
|
||||
} catch {
|
||||
// 允许容错降级
|
||||
}
|
||||
|
||||
const effectiveStaffId = String(staff.id || staffId || "");
|
||||
|
||||
const roles: StaffRoleItem[] = [];
|
||||
if (effectiveStaffId) {
|
||||
try {
|
||||
const cleanStaffId = effectiveStaffId.startsWith("$") ? effectiveStaffId : `$${effectiveStaffId}`;
|
||||
const rolesRes = await client
|
||||
.get(`api/v1/organization/staffs/${cleanStaffId}/roles`, {
|
||||
searchParams: { corpId },
|
||||
})
|
||||
.json<{
|
||||
items?: Array<{
|
||||
roleDefId?: string;
|
||||
roleDefName?: string;
|
||||
roleDefCode?: string;
|
||||
}>;
|
||||
}>();
|
||||
|
||||
if (Array.isArray(rolesRes.items)) {
|
||||
if (rolesRes.items.every((item) => item && typeof item.roleDefName === "string")) {
|
||||
unavailableFields.delete("roles");
|
||||
}
|
||||
for (const item of rolesRes.items) {
|
||||
if (item?.roleDefName) {
|
||||
roles.push({
|
||||
id: String(item.roleDefId || ""),
|
||||
name: String(item.roleDefName),
|
||||
code: item.roleDefCode ? String(item.roleDefCode) : undefined,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 允许容错降级
|
||||
}
|
||||
}
|
||||
|
||||
let departmentName: string | undefined;
|
||||
const deptId = String(
|
||||
staff.defaultDepartment || (Array.isArray(staff.departments) ? staff.departments[0] : "") || ""
|
||||
);
|
||||
if (deptId) {
|
||||
unavailableFields.add("department");
|
||||
try {
|
||||
const cleanDeptId = deptId.startsWith("$") ? deptId : `$${deptId}`;
|
||||
const deptRes = await client
|
||||
.get(`api/v1/organization/departments/${cleanDeptId}`, {
|
||||
searchParams: { corpId },
|
||||
})
|
||||
.json<{ value?: { name?: string } }>();
|
||||
if (deptRes.value?.name) {
|
||||
departmentName = deptRes.value.name;
|
||||
unavailableFields.delete("department");
|
||||
}
|
||||
} catch {
|
||||
// 允许容错降级
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
staff,
|
||||
permissions,
|
||||
roles,
|
||||
departmentName,
|
||||
unavailableFields: [...unavailableFields],
|
||||
};
|
||||
}
|
||||
|
||||
export async function searchTransferCandidatesApi(
|
||||
client: KyInstance,
|
||||
keyword?: string
|
||||
): Promise<TransferCandidate[]> {
|
||||
try {
|
||||
const res = await client
|
||||
.post("userRole/search", {
|
||||
json: {
|
||||
filterBy: "(active==true)",
|
||||
orderBy: [{ value: "createTime", order: "DESC" }],
|
||||
limit: { start: 0, count: 1000 },
|
||||
select: "userId(id, name,code),roleIds(id, name),`...`",
|
||||
permissions: ["charge-assistance", "charge-assistance-non-admin"],
|
||||
},
|
||||
})
|
||||
.json<{
|
||||
items?: Array<{
|
||||
id: string;
|
||||
userId?: { id?: string; name?: string; code?: string };
|
||||
roleIds?: Array<{ id?: string; name?: string }>;
|
||||
}>;
|
||||
}>();
|
||||
|
||||
const candidates: TransferCandidate[] = [];
|
||||
if (Array.isArray(res.items)) {
|
||||
for (const item of res.items) {
|
||||
if (!item.userId?.id || !item.userId?.name) continue;
|
||||
const name = String(item.userId.name);
|
||||
const code = item.userId.code ? String(item.userId.code) : undefined;
|
||||
const id = String(item.userId.id);
|
||||
if (
|
||||
keyword &&
|
||||
!name.includes(keyword) &&
|
||||
!id.includes(keyword) &&
|
||||
(!code || !code.includes(keyword))
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
candidates.push({
|
||||
id,
|
||||
name,
|
||||
code,
|
||||
userRoleId: String(item.id || ""),
|
||||
roles: Array.isArray(item.roleIds)
|
||||
? item.roleIds.map((r) => String(r.name || "")).filter(Boolean)
|
||||
: [],
|
||||
});
|
||||
}
|
||||
}
|
||||
return candidates;
|
||||
} catch (err) {
|
||||
if (err instanceof BusinessError || err instanceof NotFoundError) {
|
||||
throw err;
|
||||
}
|
||||
throw new EkbApiError(
|
||||
`查询可转交人员列表失败: ${err instanceof Error ? err.message : String(err)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function transferAssistTicketApi(
|
||||
client: KyInstance,
|
||||
params: TransferTicketParams
|
||||
): Promise<{ success: boolean; value?: unknown }> {
|
||||
try {
|
||||
const res = await client
|
||||
.post("assistPlatform/transfer", {
|
||||
json: {
|
||||
assistId: params.ticketId,
|
||||
recipient: params.recipient,
|
||||
remarks: params.remarks,
|
||||
},
|
||||
})
|
||||
.json<{
|
||||
errorCode?: number;
|
||||
errorMessage?: string;
|
||||
value?: unknown;
|
||||
}>();
|
||||
|
||||
if (res.errorCode) {
|
||||
throw new BusinessError(res.errorMessage || "工单转交失败");
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
value: res.value,
|
||||
};
|
||||
} catch (err) {
|
||||
if (err instanceof BusinessError || err instanceof NotFoundError) {
|
||||
throw err;
|
||||
}
|
||||
throw new EkbApiError(
|
||||
`工单转交失败: ${err instanceof Error ? err.message : String(err)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "bun:test";
|
||||
import ky from "ky";
|
||||
import {
|
||||
analyzeStaffRoleRisk,
|
||||
applyAssistTicket,
|
||||
approveAssistTicket,
|
||||
findStaff,
|
||||
generateAssistSession,
|
||||
getCorporationDetail,
|
||||
inspectAssistIdentity,
|
||||
listAssistTickets,
|
||||
listTransferCandidates,
|
||||
resolveTransferRecipient,
|
||||
searchCorporations,
|
||||
transferAssistTicket,
|
||||
} from "./services.js";
|
||||
|
||||
function createMockClient(handler: (req: Request) => Response | Promise<Response>) {
|
||||
return ky.create({
|
||||
prefix: "https://unity.ekuaibao.com/api",
|
||||
fetch: async (input: string | Request | URL, init?: RequestInit) => {
|
||||
const req = input instanceof Request ? input : new Request(input.toString(), init);
|
||||
return handler(req);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
describe("domains/assist-platform - 协助平台业务编排", () => {
|
||||
let originalFetch: typeof fetch;
|
||||
beforeEach(() => {
|
||||
originalFetch = globalThis.fetch;
|
||||
// 身份穿透创建独立客户端;禁止这些 mock 编排测试访问真实企业接口。
|
||||
globalThis.fetch = (async () => new Response("Mock identity unavailable", { status: 403 })) as unknown as typeof fetch;
|
||||
});
|
||||
afterEach(() => { globalThis.fetch = originalFetch; });
|
||||
it("searchCorporations 能够正确分页并返回企业列表", async () => {
|
||||
const client = createMockClient(async (req) => {
|
||||
expect(req.url).toContain("corporation/search");
|
||||
const body = (await req.json()) as any;
|
||||
expect(body.limit.count).toBe(10);
|
||||
expect(body.filterBy).toContain('name == "CSM"');
|
||||
return Response.json({
|
||||
count: 1,
|
||||
items: [
|
||||
{
|
||||
id: "Cxa3oOtQi2eS$g",
|
||||
name: "CSM",
|
||||
platformName: "app",
|
||||
state: "可用",
|
||||
payType: "TRYOUT",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
const res = await searchCorporations(client, {
|
||||
keyword: "CSM",
|
||||
limit: { start: 0, count: 10 },
|
||||
});
|
||||
|
||||
expect(res.count).toBe(1);
|
||||
expect(res.items[0].id).toBe("Cxa3oOtQi2eS$g");
|
||||
expect(res.items[0].name).toBe("CSM");
|
||||
});
|
||||
|
||||
it("getCorporationDetail 返回企业详细配置", async () => {
|
||||
const client = createMockClient(async (req) => {
|
||||
expect(req.url).toContain("corporation/$Cxa3oOtQi2eS$g/getCorporationDetail");
|
||||
return Response.json({
|
||||
items: [
|
||||
{
|
||||
corporation: { id: "Cxa3oOtQi2eS$g", name: "CSM" },
|
||||
basic: { name: "基础功能", status: "可用" },
|
||||
corporationPackageVos: [{ packageId: "20210415003", name: "原生企业版", enable: true }],
|
||||
otherGoodsList: [{ goodsId: "g1", name: "收款单据" }],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
const detail = await getCorporationDetail(client, "Cxa3oOtQi2eS$g");
|
||||
expect(detail.corporation?.name).toBe("CSM");
|
||||
expect(detail.corporationPackageVos.length).toBe(1);
|
||||
});
|
||||
|
||||
it("listAssistTickets 正确映射工单时间、申请人与授权码", async () => {
|
||||
const client = createMockClient(async (req) => {
|
||||
expect(req.url).toContain("assistPlatform/$Cxa3oOtQi2eS$g/search");
|
||||
return Response.json({
|
||||
items: [
|
||||
{
|
||||
ticketId: "ID01Xeh99QmgQn",
|
||||
applicant: "李志财",
|
||||
principal: "谢子豪",
|
||||
state: "已提供",
|
||||
duration: 24,
|
||||
startTime: 1792547700000,
|
||||
endTime: 1792634100000,
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
const tickets = await listAssistTickets(client, "Cxa3oOtQi2eS$g");
|
||||
expect(tickets.length).toBe(1);
|
||||
expect(tickets[0].ticketId).toBe("ID01Xeh99QmgQn");
|
||||
expect(tickets[0].applicant).toBe("李志财");
|
||||
expect(tickets[0].usePeriodDesc).toContain("至");
|
||||
});
|
||||
|
||||
it("findStaff 正确检索企业员工工号与角色", async () => {
|
||||
const client = createMockClient(async (req) => {
|
||||
expect(req.url).toContain("assistPlatform/getStaff");
|
||||
const body = (await req.json()) as any;
|
||||
expect(body.name).toBe("李志财");
|
||||
return Response.json({
|
||||
total: 1,
|
||||
items: [
|
||||
{
|
||||
id: "Cxa3oOtQi2eS$g:2HQbkGx2DgnM00",
|
||||
code: "777",
|
||||
name: "李志财",
|
||||
admin: true,
|
||||
email: "lizhicai@hosecloud.com",
|
||||
cellphone: "15727689231",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
const staffList = await findStaff(client, "Cxa3oOtQi2eS$g", "李志财");
|
||||
expect(staffList.length).toBe(1);
|
||||
expect(staffList[0].name).toBe("李志财");
|
||||
expect(staffList[0].admin).toBe(true);
|
||||
});
|
||||
|
||||
it("generateAssistSession 管理员模式一键换取免密登录直通链接", async () => {
|
||||
const client = createMockClient(async (req) => {
|
||||
const url = req.url;
|
||||
if (url.includes("assistPlatform/$Cxa3oOtQi2eS$g/search") || url.includes("assistPlatform/Cxa3oOtQi2eS$g/search")) {
|
||||
return Response.json({
|
||||
items: [{ ticketId: "ID01Xeh99QmgQn", applicant: "李志财", state: "已提供" }],
|
||||
});
|
||||
}
|
||||
if (url.includes("assistPlatform/getToken")) {
|
||||
const body = (await req.json()) as any;
|
||||
expect(body.isAdmin).toBe(true);
|
||||
expect(body.ticketId).toBe("ID01Xeh99QmgQn");
|
||||
return Response.json({
|
||||
value: {
|
||||
token: "ID01XehbTTcihF",
|
||||
loginUrl: "https://app.ekuaibao.com/api/engine/assistPlatform/login?corpId=Cxa3oOtQi2eS%24g&code=test1234",
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
},
|
||||
});
|
||||
}
|
||||
return new Response("Not found", { status: 404 });
|
||||
});
|
||||
|
||||
const result = await generateAssistSession(client, {
|
||||
corpId: "Cxa3oOtQi2eS$g",
|
||||
isAdmin: true,
|
||||
});
|
||||
|
||||
expect(result.token).toBe("ID01XehbTTcihF");
|
||||
expect(result.loginUrl).toContain("assistPlatform/login");
|
||||
expect(result.isAdmin).toBe(true);
|
||||
});
|
||||
|
||||
it("generateAssistSession 用户模式自动定位 staffId 换取免密链接", async () => {
|
||||
const client = createMockClient(async (req) => {
|
||||
const url = req.url;
|
||||
if (url.includes("assistPlatform/$Cxa3oOtQi2eS$g/search") || url.includes("assistPlatform/Cxa3oOtQi2eS$g/search")) {
|
||||
return Response.json({
|
||||
items: [{ ticketId: "ID01Xeh99QmgQn", applicant: "李志财", state: "已提供" }],
|
||||
});
|
||||
}
|
||||
if (url.includes("assistPlatform/getStaff")) {
|
||||
return Response.json({
|
||||
items: [{ id: "Cxa3oOtQi2eS$g:2HQbkGx2DgnM00", name: "李志财", admin: true }],
|
||||
});
|
||||
}
|
||||
if (url.includes("assistPlatform/getToken")) {
|
||||
const body = (await req.json()) as any;
|
||||
expect(body.isAdmin).toBe(false);
|
||||
expect(body.staffId).toBe("Cxa3oOtQi2eS$g:2HQbkGx2DgnM00");
|
||||
return Response.json({
|
||||
value: {
|
||||
token: "ID01Xeh9JK2Wlh",
|
||||
loginUrl: "https://app.ekuaibao.com/api/engine/assistPlatform/login?corpId=Cxa3oOtQi2eS%24g&code=user5678",
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
},
|
||||
});
|
||||
}
|
||||
return new Response("Not found", { status: 404 });
|
||||
});
|
||||
|
||||
const result = await generateAssistSession(client, {
|
||||
corpId: "Cxa3oOtQi2eS$g",
|
||||
isAdmin: false,
|
||||
staffName: "李志财",
|
||||
});
|
||||
|
||||
expect(result.token).toBe("ID01Xeh9JK2Wlh");
|
||||
expect(result.isAdmin).toBe(false);
|
||||
expect(result.staffId).toBe("Cxa3oOtQi2eS$g:2HQbkGx2DgnM00");
|
||||
});
|
||||
|
||||
it("applyAssistTicket 发起新的协助工单申请", async () => {
|
||||
const client = createMockClient(async (req) => {
|
||||
expect(req.url).toContain("assistPlatform/create");
|
||||
const body = (await req.json()) as any;
|
||||
expect(body.corporationId).toBe("ID01KrLMQJWdMH");
|
||||
expect(body.assistTime).toBe(86400000);
|
||||
return Response.json({
|
||||
value: {
|
||||
id: "ID01XelIEeCbw3",
|
||||
corporationId: "ID01KrLMQJWdMH",
|
||||
applyMessage: "测试环境接口联调",
|
||||
assistTime: 86400000,
|
||||
status: 0,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
const res = await applyAssistTicket(client, {
|
||||
corporationId: "ID01KrLMQJWdMH",
|
||||
applyMessage: "测试环境接口联调",
|
||||
assistTime: 86400000,
|
||||
});
|
||||
expect(res.id).toBe("ID01XelIEeCbw3");
|
||||
expect(res.status).toBe(0);
|
||||
});
|
||||
|
||||
it("approveAssistTicket 审批通过协助工单", async () => {
|
||||
const client = createMockClient(async (req) => {
|
||||
expect(req.url).toContain("assistPlatform/$ID01Xeno3GpoNV/updateStatus");
|
||||
expect(req.url).toContain("corpId=ID01ofWoOC1wiX");
|
||||
expect(req.method).toBe("PUT");
|
||||
const body = (await req.json()) as any;
|
||||
expect(body.id).toBe("ID01Xeno3GpoNV");
|
||||
expect(body.status).toBe(1);
|
||||
return Response.json({
|
||||
value: {
|
||||
id: "ID01Xeno3GpoNV",
|
||||
corporationId: "ID01ofWoOC1wiX",
|
||||
status: 1,
|
||||
active: true,
|
||||
startTime: 1792552656850,
|
||||
endTime: 1792595856850,
|
||||
applyMessage: "测试二次授权接口",
|
||||
userName: "谢子豪",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
const res = await approveAssistTicket(client, {
|
||||
ticketId: "ID01Xeno3GpoNV",
|
||||
corporationId: "ID01ofWoOC1wiX",
|
||||
});
|
||||
expect(res.id).toBe("ID01Xeno3GpoNV");
|
||||
expect(res.status).toBe(1);
|
||||
expect(res.active).toBe(true);
|
||||
expect(res.userName).toBe("谢子豪");
|
||||
});
|
||||
|
||||
describe("analyzeStaffRoleRisk - 高管权限风控识别", () => {
|
||||
it("普通员工不触发高管警示", () => {
|
||||
const risk = analyzeStaffRoleRisk({
|
||||
staffName: "普通员工",
|
||||
isAdmin: false,
|
||||
roleNames: ["普通员工", "销售代表"],
|
||||
permissions: ["INVOICE_READ", "TRAVEL_SUBMIT"],
|
||||
});
|
||||
|
||||
expect(risk.isSeniorExecutive).toBe(false);
|
||||
expect(risk.riskLevel).toBe("NORMAL");
|
||||
expect(risk.seniorTitles).toEqual([]);
|
||||
expect(risk.riskWarning).toBeUndefined();
|
||||
});
|
||||
|
||||
it("命中主管理员角色触发 HIGH 级别风控", () => {
|
||||
const risk = analyzeStaffRoleRisk({
|
||||
staffName: "沈玥妍",
|
||||
isAdmin: true,
|
||||
roleNames: ["主管理员", "财务主管"],
|
||||
permissions: ["SYS_ADMIN", "CORP_PAYMENT_MANAGE"],
|
||||
});
|
||||
|
||||
expect(risk.isSeniorExecutive).toBe(true);
|
||||
expect(risk.riskLevel).toBe("HIGH");
|
||||
expect(risk.seniorTitles).toContain("主管理员");
|
||||
expect(risk.seniorTitles).toContain("财务主管");
|
||||
expect(risk.riskWarning).toContain("沈玥妍");
|
||||
expect(risk.riskWarning).toContain("经理与实施人员严禁借用该身份发起或通过非授权审批");
|
||||
});
|
||||
|
||||
it("具备全系统管理权限或对公付款权限即使无角色名也触发风控", () => {
|
||||
const risk = analyzeStaffRoleRisk({
|
||||
staffName: "特权人员",
|
||||
isAdmin: false,
|
||||
roleNames: [],
|
||||
permissions: ["SYS_ADMIN"],
|
||||
});
|
||||
|
||||
expect(risk.isSeniorExecutive).toBe(true);
|
||||
expect(risk.riskLevel).toBe("MEDIUM");
|
||||
expect(risk.riskWarning).toContain("特权人员");
|
||||
});
|
||||
});
|
||||
|
||||
describe("transferAssistTicket - 协助工单转交服务", () => {
|
||||
it("listTransferCandidates 正确解析候选人清单", async () => {
|
||||
const client = createMockClient(async (req) => {
|
||||
expect(req.url).toContain("userRole/search");
|
||||
return Response.json({
|
||||
count: 1,
|
||||
items: [
|
||||
{
|
||||
id: "ID01TZKdvh3nAz",
|
||||
userId: { id: "chenlong3016", name: "陈龙", code: "3016" },
|
||||
roleIds: [{ id: "r1", name: "COE-协助链接" }],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
const candidates = await listTransferCandidates(client, "陈龙");
|
||||
expect(candidates.length).toBe(1);
|
||||
expect(candidates[0].name).toBe("陈龙");
|
||||
expect(candidates[0].id).toBe("chenlong3016");
|
||||
expect(candidates[0].code).toBe("3016");
|
||||
});
|
||||
|
||||
it("resolveTransferRecipient 能够按姓名或工号精确定位人员", async () => {
|
||||
const client = createMockClient(async () => {
|
||||
return Response.json({
|
||||
items: [
|
||||
{
|
||||
id: "ID01TZKdvh3nAz",
|
||||
userId: { id: "chenlong3016", name: "陈龙", code: "3016" },
|
||||
roleIds: [{ id: "r1", name: "COE-协助链接" }],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
const recipient = await resolveTransferRecipient(client, "陈龙");
|
||||
expect(recipient.id).toBe("chenlong3016");
|
||||
expect(recipient.name).toBe("陈龙");
|
||||
});
|
||||
|
||||
it("transferAssistTicket 能够向服务端发起转交请求并成功返回", async () => {
|
||||
const client = createMockClient(async (req) => {
|
||||
if (req.url.includes("userRole/search")) {
|
||||
return Response.json({
|
||||
items: [
|
||||
{
|
||||
id: "ID01TZKdvh3nAz",
|
||||
userId: { id: "chenlong3016", name: "陈龙", code: "3016" },
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
if (req.url.includes("assistPlatform/transfer")) {
|
||||
const body = (await req.json()) as any;
|
||||
expect(body.assistId).toBe("ID01Xenwiu9w0D");
|
||||
expect(body.recipient).toBe("chenlong3016");
|
||||
expect(body.remarks).toBe("转交给陈龙测试");
|
||||
return Response.json({ value: true });
|
||||
}
|
||||
return new Response("Not found", { status: 404 });
|
||||
});
|
||||
|
||||
const res = await transferAssistTicket(client, {
|
||||
ticketId: "ID01Xenwiu9w0D",
|
||||
recipient: "陈龙",
|
||||
remarks: "转交给陈龙测试",
|
||||
});
|
||||
|
||||
expect(res.success).toBe(true);
|
||||
expect(res.recipient).toBe("chenlong3016");
|
||||
expect(res.recipientName).toBe("陈龙");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from "./types.js";
|
||||
export * from "./services.js";
|
||||
@@ -0,0 +1,497 @@
|
||||
import ky, { type KyInstance } from "ky";
|
||||
import { BusinessError, NotFoundError } from "../../core/errors.js";
|
||||
import { importFromLink, type ImportFromLinkOptions } from "../../core/auth/link-import.js";
|
||||
import { loadCorpConfigs, saveCorpConfig } from "../../core/config/loader.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import {
|
||||
approveAssistTicketApi,
|
||||
createAssistTicketApi,
|
||||
getAssistTokenApi,
|
||||
getCorporationDetailApi,
|
||||
getStaffApi,
|
||||
getStaffMeAndRolesApi,
|
||||
searchAssistTicketsApi,
|
||||
searchCorporationsApi,
|
||||
searchTransferCandidatesApi,
|
||||
transferAssistTicketApi,
|
||||
type ApproveAssistTicketApiParams,
|
||||
type ApproveAssistTicketApiResponse,
|
||||
type CreateAssistTicketApiParams,
|
||||
type CreateAssistTicketApiResponse,
|
||||
type SearchCorporationsApiParams,
|
||||
type SearchCorporationsApiResponse,
|
||||
} from "./api.js";
|
||||
import type {
|
||||
AssistIdentityProfile,
|
||||
AssistPlatformCorporation,
|
||||
AssistPlatformSessionResult,
|
||||
AssistPlatformStaff,
|
||||
AssistPlatformTicket,
|
||||
CorporationDetail,
|
||||
StaffRoleItem,
|
||||
TransferCandidate,
|
||||
TransferTicketParams,
|
||||
TransferTicketResult,
|
||||
} from "./types.js";
|
||||
|
||||
export const PERMISSION_LABEL_MAP: Record<string, string> = {
|
||||
SYS_ADMIN: "系统管理",
|
||||
ROLE_ADMIN: "角色权限管理",
|
||||
CONTACTS_MANAGE: "通讯录管理",
|
||||
CORP_PAYMENT_MANAGE: "对公付款管理",
|
||||
CORPORATE_BANKING: "账户管理-付款账户",
|
||||
CORPORATE_RECEIPT: "账户管理-收款账户",
|
||||
BUDGET_MANAGE: "预算管理",
|
||||
COST_CONTROL_ADMIN: "费控管理",
|
||||
FLOW_ADMIN: "审批流管理",
|
||||
FORM_SPEC_ADMIN: "单据模板管理",
|
||||
AI_APPROVAL_NODE: "AI智能审核管理",
|
||||
INVOICE_MANAGE: "发票管理",
|
||||
INVOICE_REVIEW_QUICK_EXPENSE: "发票复核管理",
|
||||
INVOICE_RISK_CHECK: "发票风险巡检",
|
||||
MALL_MANAGE: "合思商城管理",
|
||||
LOAN_MANAGE: "借款管理",
|
||||
CREDIT_MANAGE: "信用管理",
|
||||
EXTEND_DIMENSION: "扩展档案管理",
|
||||
FEE_TYPE_ADMIN: "费用类型管理",
|
||||
HOME_PAGE_ADMIN: "移动端首页配置",
|
||||
CONSUMER_MATTERS: "申请事项管理",
|
||||
CHECKING_BILL_MANAGE: "对账单管理",
|
||||
OUTPUT_TAX_MANAGE: "销项税管理",
|
||||
SUPPLEMENT_INVOICE: "补充发票管理",
|
||||
VIRTUAL_CARD_MANAGE: "易商卡管理",
|
||||
WAIT_INVOICE_AUTHORIZE: "待开发票管理",
|
||||
RECORD_LINK_ADMIN: "档案关系管理",
|
||||
CORP_AGENCY_EXPENSE: "代垫费用管理",
|
||||
};
|
||||
|
||||
export const SENIOR_ROLE_KEYWORDS = [
|
||||
"总监", "副总", "总经理", "总裁", "CEO", "CFO", "COO", "CTO", "VP",
|
||||
"主管理员", "系统管理员", "财务主管", "财务负责人", "审计主管", "风控主管",
|
||||
"合伙人", "董事长", "董事", "行长", "部长", "处长", "站长", "分管领导", "经理", "主管"
|
||||
];
|
||||
|
||||
export function analyzeStaffRoleRisk(profile: {
|
||||
staffName: string;
|
||||
isAdmin: boolean | null;
|
||||
profileComplete?: boolean;
|
||||
roleNames: string[];
|
||||
permissions: string[];
|
||||
}): {
|
||||
isSeniorExecutive: boolean | null;
|
||||
seniorTitles: string[];
|
||||
riskLevel: "HIGH" | "MEDIUM" | "NORMAL" | "UNKNOWN";
|
||||
riskWarning?: string;
|
||||
} {
|
||||
const seniorTitles: string[] = [];
|
||||
|
||||
if (profile.isAdmin && !seniorTitles.includes("企业主管理员")) {
|
||||
seniorTitles.push("企业主管理员");
|
||||
}
|
||||
|
||||
for (const roleName of profile.roleNames) {
|
||||
for (const kw of SENIOR_ROLE_KEYWORDS) {
|
||||
if (roleName.includes(kw) && !seniorTitles.includes(roleName)) {
|
||||
seniorTitles.push(roleName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const hasHighRiskPerms = profile.permissions.some((p) =>
|
||||
["SYS_ADMIN", "ROLE_ADMIN", "CORP_PAYMENT_MANAGE", "FLOW_ADMIN"].includes(p)
|
||||
);
|
||||
|
||||
const hasKnownRisk = seniorTitles.length > 0 || hasHighRiskPerms;
|
||||
const incomplete = profile.profileComplete === false;
|
||||
const isSeniorExecutive = hasKnownRisk ? true : incomplete ? null : false;
|
||||
const riskLevel = seniorTitles.length > 0 ? "HIGH" : hasHighRiskPerms ? "MEDIUM" : incomplete ? "UNKNOWN" : "NORMAL";
|
||||
|
||||
let riskWarning: string | undefined;
|
||||
if (hasKnownRisk) {
|
||||
const titleSummary = seniorTitles.length > 0 ? seniorTitles.join(" / ") : "高级系统管理员";
|
||||
riskWarning =
|
||||
`当前协助会话获取的是高阶管理人员身份 [${titleSummary}](${profile.staffName})。` +
|
||||
`该身份拥有高级审批、财务权限或全系统管理权限。经理与实施人员严禁借用该身份发起或通过非授权审批,防范越权误操作!`;
|
||||
}
|
||||
|
||||
if (incomplete) {
|
||||
riskWarning = `${riskWarning || ""}身份或角色权限信息不完整,无法排除更高权限风险,请先核验当前身份。`;
|
||||
}
|
||||
|
||||
return {
|
||||
isSeniorExecutive,
|
||||
seniorTitles,
|
||||
riskLevel,
|
||||
riskWarning,
|
||||
};
|
||||
}
|
||||
|
||||
export async function inspectAssistIdentity(
|
||||
token: string,
|
||||
corpId: string,
|
||||
baseUrl: string = "https://app.ekuaibao.com",
|
||||
fallbackStaffId?: string,
|
||||
fallbackStaffName?: string
|
||||
): Promise<AssistIdentityProfile> {
|
||||
const normalizedBase = baseUrl.replace(/\/+$/, "");
|
||||
const client = ky.create({
|
||||
prefix: normalizedBase,
|
||||
headers: {
|
||||
accesstoken: token,
|
||||
corpid: corpId,
|
||||
accept: "application/json",
|
||||
"content-type": "application/json",
|
||||
},
|
||||
timeout: 10000,
|
||||
});
|
||||
|
||||
const res = await getStaffMeAndRolesApi(client, corpId, fallbackStaffId);
|
||||
const staff = res.staff;
|
||||
const staffId = String(staff.id || fallbackStaffId || "");
|
||||
const staffName = String(staff.name || fallbackStaffName || "企业操作人员");
|
||||
const cellphone = staff.cellphone ? String(staff.cellphone) : undefined;
|
||||
const email = staff.email ? String(staff.email) : undefined;
|
||||
const code = staff.code ? String(staff.code) : undefined;
|
||||
const isAdmin = typeof staff.admin === "boolean" ? staff.admin : null;
|
||||
const profileComplete = res.unavailableFields.length === 0;
|
||||
|
||||
const roleNames = res.roles.map((r) => r.name);
|
||||
const readablePermissions = res.permissions.map(
|
||||
(p) => `${PERMISSION_LABEL_MAP[p] || p} (${p})`
|
||||
);
|
||||
|
||||
const riskAnalysis = analyzeStaffRoleRisk({
|
||||
profileComplete,
|
||||
staffName,
|
||||
isAdmin,
|
||||
roleNames,
|
||||
permissions: res.permissions,
|
||||
});
|
||||
|
||||
return {
|
||||
profileComplete,
|
||||
unavailableFields: res.unavailableFields,
|
||||
staffId,
|
||||
staffName,
|
||||
cellphone,
|
||||
email,
|
||||
code,
|
||||
isAdmin,
|
||||
departmentId: String(staff.defaultDepartment || ""),
|
||||
departmentName: res.departmentName,
|
||||
roles: res.roles,
|
||||
roleNames,
|
||||
permissions: res.permissions,
|
||||
readablePermissions,
|
||||
...riskAnalysis,
|
||||
};
|
||||
}
|
||||
|
||||
export async function searchCorporations(
|
||||
client: KyInstance,
|
||||
params: SearchCorporationsApiParams = {}
|
||||
): Promise<SearchCorporationsApiResponse> {
|
||||
return await searchCorporationsApi(client, params);
|
||||
}
|
||||
|
||||
export async function getCorporationDetail(
|
||||
client: KyInstance,
|
||||
corpId: string
|
||||
): Promise<CorporationDetail> {
|
||||
return await getCorporationDetailApi(client, corpId);
|
||||
}
|
||||
|
||||
export async function listAssistTickets(
|
||||
client: KyInstance,
|
||||
corpId: string
|
||||
): Promise<AssistPlatformTicket[]> {
|
||||
return await searchAssistTicketsApi(client, corpId);
|
||||
}
|
||||
|
||||
export async function findStaff(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
name: string
|
||||
): Promise<AssistPlatformStaff[]> {
|
||||
return await getStaffApi(client, corpId, name);
|
||||
}
|
||||
|
||||
export async function applyAssistTicket(
|
||||
client: KyInstance,
|
||||
params: CreateAssistTicketApiParams
|
||||
): Promise<CreateAssistTicketApiResponse> {
|
||||
return await createAssistTicketApi(client, params);
|
||||
}
|
||||
|
||||
export async function approveAssistTicket(
|
||||
client: KyInstance,
|
||||
params: ApproveAssistTicketApiParams
|
||||
): Promise<ApproveAssistTicketApiResponse> {
|
||||
return await approveAssistTicketApi(client, params);
|
||||
}
|
||||
|
||||
export interface GenerateAssistSessionParams {
|
||||
corpId: string;
|
||||
ticketId?: string;
|
||||
isAdmin?: boolean;
|
||||
staffName?: string;
|
||||
staffId?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 智能解析并换取协助平台的免密登录直通链接
|
||||
*/
|
||||
export async function generateAssistSession(
|
||||
client: KyInstance,
|
||||
params: GenerateAssistSessionParams
|
||||
): Promise<AssistPlatformSessionResult> {
|
||||
const corpId = params.corpId.trim();
|
||||
let ticketId = params.ticketId?.trim();
|
||||
|
||||
// 若未手动指定授权码 ticketId,自动检索该企业名下首个有效状态工单
|
||||
if (!ticketId) {
|
||||
const tickets = await searchAssistTicketsApi(client, corpId);
|
||||
if (tickets.length === 0) {
|
||||
throw new NotFoundError(`企业 [${corpId}] 协助中心未查询到任何协助工单`);
|
||||
}
|
||||
|
||||
const activeTicket =
|
||||
tickets.find(
|
||||
(t) =>
|
||||
t.state === "已提供" ||
|
||||
t.state === "待提供" ||
|
||||
t.state === "1" ||
|
||||
t.state === "生效中"
|
||||
) ?? tickets[0];
|
||||
|
||||
if (!activeTicket || !activeTicket.ticketId) {
|
||||
throw new NotFoundError(`企业 [${corpId}] 暂无可用状态的协助授权工单`);
|
||||
}
|
||||
ticketId = activeTicket.ticketId;
|
||||
}
|
||||
|
||||
const isAdmin =
|
||||
params.isAdmin !== undefined
|
||||
? params.isAdmin
|
||||
: !(params.staffId || params.staffName);
|
||||
let resolvedStaffId = params.staffId?.trim();
|
||||
let resolvedStaffName = params.staffName?.trim();
|
||||
|
||||
// 若要求用户模式且指定了姓名,自动检索员工工号
|
||||
if (!isAdmin && resolvedStaffName && !resolvedStaffId) {
|
||||
const staffList = await getStaffApi(client, corpId, resolvedStaffName);
|
||||
if (staffList.length === 0) {
|
||||
throw new NotFoundError(
|
||||
`在企业 [${corpId}] 中未找到名为 "${resolvedStaffName}" 的员工`
|
||||
);
|
||||
}
|
||||
const targetStaff = staffList[0];
|
||||
resolvedStaffId = targetStaff.id;
|
||||
resolvedStaffName = targetStaff.name;
|
||||
}
|
||||
|
||||
const tokenRes = await getAssistTokenApi(client, {
|
||||
ticketId,
|
||||
corporationId: corpId,
|
||||
isAdmin,
|
||||
staffId: resolvedStaffId,
|
||||
});
|
||||
|
||||
// 深度解析当前会话人员身份、所属部门与角色权限画像(包含高管权限风控检测)
|
||||
let identity: AssistIdentityProfile | undefined;
|
||||
try {
|
||||
identity = await inspectAssistIdentity(
|
||||
tokenRes.token,
|
||||
corpId,
|
||||
tokenRes.baseUrl,
|
||||
resolvedStaffId,
|
||||
resolvedStaffName
|
||||
);
|
||||
} catch {
|
||||
// 允许容错降级
|
||||
}
|
||||
|
||||
return {
|
||||
token: tokenRes.token,
|
||||
loginUrl: tokenRes.loginUrl,
|
||||
baseUrl: tokenRes.baseUrl,
|
||||
ticketId,
|
||||
corporationId: corpId,
|
||||
isAdmin,
|
||||
staffId: identity?.staffId || resolvedStaffId,
|
||||
staffName: identity?.staffName || resolvedStaffName,
|
||||
identity,
|
||||
};
|
||||
}
|
||||
|
||||
export interface ImportAssistSessionParams extends GenerateAssistSessionParams {
|
||||
saveName?: string;
|
||||
overwrite?: boolean;
|
||||
enterprisesDir?: string;
|
||||
ttl?: string | number;
|
||||
elevate?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 自动化闭环:换取协助免密链接,并通过 importFromLink 一键落盘持久化至本地企业配置
|
||||
*/
|
||||
export async function importAssistSessionToLocal(
|
||||
client: KyInstance,
|
||||
params: ImportAssistSessionParams
|
||||
): Promise<{
|
||||
sessionResult: AssistPlatformSessionResult;
|
||||
corpConfig: CorpConfig;
|
||||
}> {
|
||||
const sessionResult = await generateAssistSession(client, params);
|
||||
|
||||
const importOptions: ImportFromLinkOptions = {
|
||||
name: params.saveName,
|
||||
overwrite: params.overwrite ?? true,
|
||||
enterprisesDir: params.enterprisesDir,
|
||||
ttl: params.ttl,
|
||||
elevate: params.elevate,
|
||||
};
|
||||
|
||||
const linkToImport = sessionResult.loginUrl.includes("accessToken=")
|
||||
? sessionResult.loginUrl
|
||||
: `https://app.ekuaibao.com/web/thirdparty.html?accessToken=${encodeURIComponent(sessionResult.token)}&ekbCorpId=${encodeURIComponent(sessionResult.corporationId)}${sessionResult.staffId ? `&staffId=${encodeURIComponent(sessionResult.staffId)}` : ""}`;
|
||||
|
||||
const previousCorp = loadCorpConfigs(params.enterprisesDir ? [params.enterprisesDir] : undefined)
|
||||
.find((corp) => corp.id === sessionResult.corporationId);
|
||||
const corpConfig = await importFromLink(linkToImport, importOptions);
|
||||
|
||||
// 注入完整身份画像与角色权限风控元数据并保存落盘
|
||||
if (sessionResult.identity) {
|
||||
const ident = sessionResult.identity;
|
||||
// 画像接口失败时保留 JWT 已确认的身份,不能将未知值降为非管理员或低风险
|
||||
const previousSession = previousCorp?.credentials.staffId === corpConfig.credentials.staffId
|
||||
? previousCorp.session
|
||||
: undefined;
|
||||
ident.isAdmin ??= corpConfig.session?.isAdmin ?? previousSession?.isAdmin ?? null;
|
||||
const unavailable = ident.unavailableFields || [];
|
||||
if (unavailable.includes("roles") && previousSession?.roles) {
|
||||
ident.roleNames = [...new Set([...ident.roleNames, ...previousSession.roles])];
|
||||
}
|
||||
if (unavailable.includes("permissions") && previousSession?.permissions) {
|
||||
ident.permissions = [...new Set([...ident.permissions, ...previousSession.permissions])];
|
||||
ident.readablePermissions = ident.permissions.map((p) => `${PERMISSION_LABEL_MAP[p] || p} (${p})`);
|
||||
}
|
||||
if (unavailable.includes("staff")) {
|
||||
ident.staffId = corpConfig.credentials.staffId || ident.staffId;
|
||||
ident.staffName = corpConfig.session?.staffName || ident.staffName;
|
||||
}
|
||||
Object.assign(ident, analyzeStaffRoleRisk(ident));
|
||||
// 同一员工的历史高风险证据不能因本次探测不完整而被降级。
|
||||
if (ident.profileComplete === false && previousSession?.riskLevel) {
|
||||
const riskRank: Record<string, number> = { UNKNOWN: 0, NORMAL: 0, MEDIUM: 1, HIGH: 2 };
|
||||
if ((riskRank[previousSession.riskLevel] || 0) > riskRank[ident.riskLevel]!) {
|
||||
ident.riskLevel = previousSession.riskLevel as "HIGH" | "MEDIUM";
|
||||
ident.isSeniorExecutive = true;
|
||||
}
|
||||
}
|
||||
sessionResult.staffId = ident.staffId || sessionResult.staffId;
|
||||
sessionResult.staffName = ident.staffName || sessionResult.staffName;
|
||||
corpConfig.session = {
|
||||
...corpConfig.session,
|
||||
identityComplete: ident.profileComplete,
|
||||
identityUnavailableFields: ident.unavailableFields,
|
||||
staffName: ident.staffName || corpConfig.session?.staffName,
|
||||
cellphone: ident.cellphone || corpConfig.session?.cellphone,
|
||||
isAdmin: ident.isAdmin ?? corpConfig.session?.isAdmin,
|
||||
departmentName: ident.departmentName,
|
||||
roles: ident.roleNames,
|
||||
roleTitles: ident.seniorTitles.length > 0 ? ident.seniorTitles.join(" / ") : undefined,
|
||||
isSeniorExecutive: ident.isSeniorExecutive,
|
||||
riskLevel: ident.riskLevel,
|
||||
permissions: ident.permissions,
|
||||
};
|
||||
saveCorpConfig(corpConfig, importOptions.enterprisesDir);
|
||||
}
|
||||
|
||||
return {
|
||||
sessionResult,
|
||||
corpConfig,
|
||||
};
|
||||
}
|
||||
|
||||
export async function listTransferCandidates(
|
||||
client: KyInstance,
|
||||
keyword?: string
|
||||
): Promise<TransferCandidate[]> {
|
||||
return searchTransferCandidatesApi(client, keyword);
|
||||
}
|
||||
|
||||
export async function resolveTransferRecipient(
|
||||
client: KyInstance,
|
||||
target: string
|
||||
): Promise<TransferCandidate> {
|
||||
const cleanTarget = target.trim();
|
||||
if (!cleanTarget) {
|
||||
throw new BusinessError("必须指定转交接收人(姓名、工号或账号)");
|
||||
}
|
||||
|
||||
const candidates = await listTransferCandidates(client);
|
||||
// 一个用户可能有多条角色记录;先匹配,再按稳定账号 ID 去重。
|
||||
const uniqueUsers = (matches: TransferCandidate[]) =>
|
||||
[...new Map(matches.map((candidate) => [candidate.id, candidate])).values()];
|
||||
const rejectAmbiguous = (matches: TransferCandidate[]): never => {
|
||||
const names = matches
|
||||
.slice(0, 5)
|
||||
.map((m) => `${m.name}(${m.id}${m.code ? `, 工号: ${m.code}` : ""})`)
|
||||
.join("、");
|
||||
throw new BusinessError(`匹配到多个可转交人员 [${names}],请指定唯一工号或账号`);
|
||||
};
|
||||
|
||||
// 账号 ID 优先于工号、姓名,避免一个人的姓名覆盖另一个人的明确账号。
|
||||
for (const matches of [
|
||||
candidates.filter((c) => c.id === cleanTarget),
|
||||
candidates.filter((c) => c.code === cleanTarget),
|
||||
candidates.filter((c) => c.name === cleanTarget),
|
||||
]) {
|
||||
const users = uniqueUsers(matches);
|
||||
if (users.length === 1) return users[0];
|
||||
if (users.length > 1) rejectAmbiguous(users);
|
||||
}
|
||||
|
||||
const fuzzyMatches = uniqueUsers(candidates.filter(
|
||||
(c) =>
|
||||
c.name.includes(cleanTarget) ||
|
||||
(c.code && c.code.includes(cleanTarget)) ||
|
||||
c.id.includes(cleanTarget)
|
||||
));
|
||||
if (fuzzyMatches.length === 1) {
|
||||
return fuzzyMatches[0];
|
||||
}
|
||||
if (fuzzyMatches.length > 1) {
|
||||
rejectAmbiguous(fuzzyMatches);
|
||||
}
|
||||
|
||||
throw new NotFoundError(`未在具备协助权限的人员库中找到匹配的人员: "${cleanTarget}"`);
|
||||
}
|
||||
|
||||
export async function transferAssistTicket(
|
||||
client: KyInstance,
|
||||
params: {
|
||||
ticketId: string;
|
||||
recipient: string;
|
||||
remarks?: string;
|
||||
}
|
||||
): Promise<TransferTicketResult> {
|
||||
const candidate = await resolveTransferRecipient(client, params.recipient);
|
||||
const resolvedRecipientId = candidate.id;
|
||||
const recipientName = candidate.name;
|
||||
|
||||
await transferAssistTicketApi(client, {
|
||||
ticketId: params.ticketId,
|
||||
recipient: resolvedRecipientId,
|
||||
remarks: params.remarks,
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
ticketId: params.ticketId,
|
||||
recipient: resolvedRecipientId,
|
||||
recipientName,
|
||||
remarks: params.remarks,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import ky from "ky";
|
||||
import { BusinessError, EkbApiError, NotFoundError } from "../../core/errors.js";
|
||||
import { resolveTransferRecipient, transferAssistTicket } from "./services.js";
|
||||
|
||||
type User = { id: string; name: string; code?: string };
|
||||
const first: User = { id: "zhang3016", name: "张三", code: "3016" };
|
||||
const second: User = { id: "zhang3020", name: "张三", code: "3020" };
|
||||
|
||||
function mockClient(users: User[], failSearch = false) {
|
||||
const writes: unknown[] = [];
|
||||
const client = ky.create({
|
||||
prefix: "https://assist.invalid/api",
|
||||
retry: 0,
|
||||
fetch: async (input, init) => {
|
||||
const request = input instanceof Request ? input : new Request(input.toString(), init);
|
||||
if (request.url.endsWith("userRole/search")) {
|
||||
if (failSearch) return new Response("unavailable", { status: 503 });
|
||||
return Response.json({ items: users.map((userId, i) => ({
|
||||
id: `role-row-${i}`,
|
||||
userId,
|
||||
roleIds: [{ id: `role-${i}`, name: `角色${i}` }],
|
||||
})) });
|
||||
}
|
||||
if (request.url.endsWith("assistPlatform/transfer")) {
|
||||
writes.push(await request.json());
|
||||
return Response.json({ value: true });
|
||||
}
|
||||
throw new Error(`Unexpected request: ${request.url}`);
|
||||
},
|
||||
});
|
||||
return { client, writes };
|
||||
}
|
||||
|
||||
describe("assist-platform 转交目标解析", () => {
|
||||
it("同名不同账号拒绝精确匹配,错误提示唯一工号或账号", async () => {
|
||||
const { client } = mockClient([first, second]);
|
||||
await expect(resolveTransferRecipient(client, "张三")).rejects.toBeInstanceOf(BusinessError);
|
||||
await expect(resolveTransferRecipient(client, "张三")).rejects.toThrow("唯一工号或账号");
|
||||
});
|
||||
|
||||
it("相同工号的不同用户也拒绝选择第一人", async () => {
|
||||
const { client } = mockClient([first, { ...second, code: first.code }]);
|
||||
await expect(resolveTransferRecipient(client, "3016")).rejects.toThrow("多个可转交人员");
|
||||
});
|
||||
|
||||
it("账号精确匹配优先于其他人的工号和姓名", async () => {
|
||||
const { client } = mockClient([
|
||||
{ ...second, code: first.id },
|
||||
{ id: "other", name: first.id },
|
||||
first,
|
||||
]);
|
||||
expect((await resolveTransferRecipient(client, first.id)).id).toBe(first.id);
|
||||
});
|
||||
|
||||
it("工号精确匹配优先于其他人的姓名", async () => {
|
||||
const { client } = mockClient([{ ...second, name: "3016" }, first]);
|
||||
expect((await resolveTransferRecipient(client, "3016")).id).toBe(first.id);
|
||||
});
|
||||
|
||||
it.each(["张三", "3016", "zhang3016", "zhang", " 3016 "])(
|
||||
"同一稳定账号的多条角色记录不会令 %s 产生歧义",
|
||||
async (target) => {
|
||||
const { client } = mockClient([first, first]);
|
||||
expect((await resolveTransferRecipient(client, target)).id).toBe(first.id);
|
||||
}
|
||||
);
|
||||
|
||||
it("模糊匹配存在多个用户时拒绝", async () => {
|
||||
const { client } = mockClient([first, second]);
|
||||
await expect(resolveTransferRecipient(client, "zhang")).rejects.toThrow("多个可转交人员");
|
||||
});
|
||||
|
||||
it.each(["张三", "不存在的账号"])("执行转交时 %s 解析失败不提交原始值", async (recipient) => {
|
||||
const { client, writes } = mockClient([first, second]);
|
||||
const ErrorClass = recipient === "张三" ? BusinessError : NotFoundError;
|
||||
await expect(transferAssistTicket(client, { ticketId: "TICKET", recipient }))
|
||||
.rejects.toBeInstanceOf(ErrorClass);
|
||||
expect(writes).toEqual([]);
|
||||
});
|
||||
|
||||
it("查询候选人失败时不以原始账号继续写入", async () => {
|
||||
const { client, writes } = mockClient([], true);
|
||||
await expect(transferAssistTicket(client, { ticketId: "TICKET", recipient: first.id }))
|
||||
.rejects.toBeInstanceOf(EkbApiError);
|
||||
expect(writes).toEqual([]);
|
||||
});
|
||||
|
||||
it("使用唯一工号时写入稳定账号 ID", async () => {
|
||||
const { client, writes } = mockClient([first, first, second]);
|
||||
const result = await transferAssistTicket(client, {
|
||||
ticketId: "TICKET", recipient: "3016", remarks: "交接",
|
||||
});
|
||||
expect(result.recipient).toBe(first.id);
|
||||
expect(result.recipientName).toBe(first.name);
|
||||
expect(writes).toEqual([{ assistId: "TICKET", recipient: first.id, remarks: "交接" }]);
|
||||
});
|
||||
});
|
||||
Loaded 100 of 147 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user